All files / src/NetworkInfo/DbSyncNetworkInfoProvider DbSyncNetworkInfoProvider.ts

95.38% Statements 62/65
50% Branches 2/4
100% Functions 19/19
96.82% Lines 61/63

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 16435x 35x                     35x   35x   35x 35x 35x 35x                               35x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x     4x   4x 4x 4x 4x 4x 4x 4x       2x   2x         2x 1x   1x 1x     1x               2x       2x 2x       5x       6x   6x     5x         5x         6x       8x   8x   7x   7x     8x             3x   3x           3x       3x 3x       3x 3x     35x 1x 1x   1x       3x 3x      
import * as NetworkInfoCacheKey from './keys';
import {
  Cardano,
  CardanoNodeUtil,
  EraSummary,
  NetworkInfoProvider,
  Seconds,
  SlotEpochCalc,
  StakeSummary,
  SupplySummary,
  createSlotEpochCalc
} from '@cardano-sdk/core';
import { DbSyncProvider, DbSyncProviderDependencies, Disposer, EpochMonitor } from '../../util';
import { GenesisData } from '../../types';
import { InMemoryCache, UNLIMITED_CACHE_TTL } from '../../InMemoryCache';
import { Logger } from 'ts-log';
import { NetworkInfoBuilder } from './NetworkInfoBuilder';
import { RunnableModule } from '@cardano-sdk/util';
import { toGenesisParams, toLedgerTip, toProtocolParams, toSupply } from './mappers';
import memoize from 'lodash/memoize.js';
 
/** Dependencies that are need to create DbSyncNetworkInfoProvider */
export interface NetworkInfoProviderDependencies extends DbSyncProviderDependencies {
  /** The in memory cache engine. */
  cache: DbSyncProviderDependencies['cache'] & {
    db: InMemoryCache;
  };
 
  /** Monitor the epoch rollover through db polling. */
  epochMonitor: EpochMonitor;
 
  /** The genesis data loaded from the genesis file. */
  genesisData: GenesisData;
}
 
export class DbSyncNetworkInfoProvider extends DbSyncProvider(RunnableModule) implements NetworkInfoProvider {
  #logger: Logger;
  #cache: InMemoryCache;
  #currentEpoch: Cardano.EpochNo;
  #currentHash: Cardano.BlockId | undefined;
  #builder: NetworkInfoBuilder;
  #genesisData: GenesisData;
  #epochMonitor: EpochMonitor;
  #epochRolloverDisposer: Disposer;
  #slotEpochCalc: SlotEpochCalc;
  #ledgerTipTtl: Seconds;
 
  constructor({ cache, cardanoNode, dbPools, epochMonitor, genesisData, logger }: NetworkInfoProviderDependencies) {
    super({ cache, cardanoNode, dbPools, logger }, 'DbSyncNetworkInfoProvider', logger);
 
    this.#logger = logger;
    this.#cache = cache.db;
    this.#currentEpoch = Cardano.EpochNo(0);
    this.#ledgerTipTtl = Seconds(0);
    this.#epochMonitor = epochMonitor;
    this.#builder = new NetworkInfoBuilder(dbPools.main, logger);
    this.#genesisData = genesisData;
  }
 
  public async ledgerTip(): Promise<Cardano.Tip> {
    const result = await this.#cache.get(
      NetworkInfoCacheKey.LEDGER_TIP,
      async () => toLedgerTip(await this.#builder.queryLedgerTip()),
      this.#ledgerTipTtl
    );
 
    // Perform computation only on changed tip
    if (this.#currentHash !== result.hash) {
      this.#currentHash = result.hash;
 
      const slotEpochCalc = await this.#getSlotEpochCalc();
      const currentEpoch = slotEpochCalc(result.slot);
 
      // On epoch rollover, invalidate the cache before returning
      Iif (this.#currentEpoch !== currentEpoch) {
        // The first time, no need to invalidate the cache
        Iif (this.#currentEpoch !== 0) this.#epochMonitor.onEpoch(currentEpoch);
 
        this.#currentEpoch = currentEpoch;
      }
    }
 
    return result;
  }
 
  public async protocolParameters(): Promise<Cardano.ProtocolParameters> {
    const currentProtocolParams = await this.#builder.queryProtocolParams();
    return toProtocolParams(currentProtocolParams);
  }
 
  public async genesisParameters(): Promise<Cardano.CompactGenesis> {
    return toGenesisParams(this.#genesisData);
  }
 
  public async lovelaceSupply(): Promise<SupplySummary> {
    const { maxLovelaceSupply } = this.#genesisData;
 
    const [circulatingSupply, totalSupply] = await Promise.all([
      this.#cache.get(
        NetworkInfoCacheKey.CIRCULATING_SUPPLY,
        () => this.#builder.queryCirculatingSupply(),
        UNLIMITED_CACHE_TTL
      ),
      this.#cache.get(
        NetworkInfoCacheKey.TOTAL_SUPPLY,
        () => this.#builder.queryTotalSupply(maxLovelaceSupply),
        UNLIMITED_CACHE_TTL
      )
    ]);
 
    return toSupply({ circulatingSupply, totalSupply });
  }
 
  public async stake(): Promise<StakeSummary> {
    this.#logger.debug('About to query stake data');
 
    const [live, activeStake] = await Promise.all([
      this.#cache.get(NetworkInfoCacheKey.LIVE_STAKE, () =>
        this.cardanoNode.stakeDistribution().then(CardanoNodeUtil.toLiveStake)
      ),
      this.#cache.get(NetworkInfoCacheKey.ACTIVE_STAKE, () => this.#builder.queryActiveStake(), UNLIMITED_CACHE_TTL)
    ]);
 
    return {
      active: BigInt(activeStake),
      live
    };
  }
 
  public async eraSummaries(): Promise<EraSummary[]> {
    return await this.#cache.get(
      NetworkInfoCacheKey.ERA_SUMMARIES,
      () => this.cardanoNode.eraSummaries(),
      UNLIMITED_CACHE_TTL
    );
  }
 
  async initializeImpl() {
    return Promise.resolve();
  }
 
  async startImpl() {
    this.#epochRolloverDisposer = this.#epochMonitor.onEpochRollover(() => this.#cache.clear());
    this.#ledgerTipTtl = await this.#getLedgerTipTtl();
  }
 
  async shutdownImpl() {
    this.#cache.shutdown();
    this.#epochRolloverDisposer();
  }
 
  async #getSlotEpochCalc() {
    if (!this.#slotEpochCalc) {
      this.#slotEpochCalc = memoize(createSlotEpochCalc(await this.eraSummaries()));
    }
    return this.#slotEpochCalc;
  }
 
  async #getLedgerTipTtl(): Promise<Seconds> {
    const genesisParams = await this.genesisParameters();
    return Seconds(genesisParams.slotLength / genesisParams.activeSlotsCoefficient / 20);
  }
}