All files / src/Asset/DbSyncAssetProvider DbSyncAssetProvider.ts

92.18% Statements 59/64
68.42% Branches 13/19
100% Functions 12/12
91.52% Lines 54/59

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 15136x                     36x   36x 36x                                       36x 36x           36x 9x 9x 9x 9x           9x 9x   9x 9x 9x 9x       9x   7x 7x 4x 4x   2x 2x 2x             7x       5x 1x             4x 1x   1x 1x                   1x     4x   4x 4x   3x 3x 1x   3x     4x     36x 5x   3x         13x 10x 10x 10x   10x 3x           7x 7x   7x   7x        
import {
  Asset,
  AssetProvider,
  Cardano,
  CardanoNodeUtil,
  GetAssetArgs,
  GetAssetsArgs,
  ProviderError,
  ProviderFailure,
  Seconds
} from '@cardano-sdk/core';
import { AssetBuilder } from './AssetBuilder';
import { AssetPolicyIdAndName, NftMetadataService, TokenMetadataService } from '../types';
import { DB_CACHE_TTL_DEFAULT, InMemoryCache, NoCache } from '../../InMemoryCache';
import { DbSyncProvider, DbSyncProviderDependencies } from '../../util';
 
/** Properties that are need to create DbSyncAssetProvider */
export interface DbSyncAssetProviderProps {
  /** Pagination page size limit used for provider methods constraint. */
  paginationPageSizeLimit: number;
  /** Cache TTL in seconds, defaults to 2 hours */
  cacheTTL?: Seconds;
  /** Does not use in-memory cache if `true` */
  disableDbCache?: boolean;
}
 
/** Dependencies that are need to create DbSyncAssetProvider */
export interface DbSyncAssetProviderDependencies extends DbSyncProviderDependencies {
  /** The NftMetadataService to retrieve Asset.NftMetadata. */
  ntfMetadataService: NftMetadataService;
  /** The TokenMetadataService to retrieve Asset.TokenMetadata. */
  tokenMetadataService: TokenMetadataService;
}
 
const nftMetadataCacheKey = (assetId: Cardano.AssetId) => `nm_${assetId.toString()}`;
const assetInfoCacheKey = (assetId: Cardano.AssetId) => `ai_${assetId.toString()}`;
 
/**
 * AssetProvider implementation using {@link NftMetadataService}, {@link TokenMetadataService}
 * and `cardano-db-sync` database as sources
 */
export class DbSyncAssetProvider extends DbSyncProvider() implements AssetProvider {
  #builder: AssetBuilder;
  #dependencies: DbSyncAssetProviderDependencies;
  #paginationPageSizeLimit: number;
  #cache: InMemoryCache;
 
  constructor(
    { paginationPageSizeLimit, disableDbCache, cacheTTL = DB_CACHE_TTL_DEFAULT }: DbSyncAssetProviderProps,
    dependencies: DbSyncAssetProviderDependencies
  ) {
    const { cache, dbPools, cardanoNode, logger } = dependencies;
    super({ cache, cardanoNode, dbPools, logger });
 
    this.#builder = new AssetBuilder(dbPools.main, logger);
    this.#dependencies = dependencies;
    this.#paginationPageSizeLimit = paginationPageSizeLimit;
    this.#cache = disableDbCache ? new NoCache() : new InMemoryCache(cacheTTL);
  }
 
  async getAsset({ assetId, extraData }: GetAssetArgs) {
    const assetInfo = await this.#getAssetInfo(assetId);
 
    if (extraData?.nftMetadata) assetInfo.nftMetadata = await this.#getNftMetadata(assetInfo);
    if (extraData?.tokenMetadata) {
      try {
        assetInfo.tokenMetadata = (await this.#dependencies.tokenMetadataService.getTokenMetadata([assetId]))[0];
      } catch (error) {
        if (CardanoNodeUtil.isProviderError(error) && error.reason === ProviderFailure.Unhealthy) {
          this.logger.error(`Failed to fetch token metadata for asset with ${assetId} due to: ${error.message}`);
          assetInfo.tokenMetadata = undefined;
        } else E{
          throw error;
        }
      }
    }
 
    return assetInfo;
  }
 
  async getAssets({ assetIds, extraData }: GetAssetsArgs) {
    if (assetIds.length > this.#paginationPageSizeLimit) {
      throw new ProviderError(
        ProviderFailure.BadRequest,
        undefined,
        `AssetIds count of ${assetIds.length} can not be greater than ${this.#paginationPageSizeLimit}`
      );
    }
 
    const fetchTokenMetadataList = async () => {
      let tokenMetadataList: (Asset.TokenMetadata | null | undefined)[] = [];
 
      try {
        tokenMetadataList = await this.#dependencies.tokenMetadataService.getTokenMetadata(assetIds);
      } catch (error) {
        if (CardanoNodeUtil.isProviderError(error) && error.reason === ProviderFailure.Unhealthy) {
          this.logger.error(`Failed to fetch token metadata for assets ${assetIds} due to: ${error.message}`);
          tokenMetadataList = Array.from({ length: assetIds.length });
        } else {
          throw error;
        }
      }
 
      return tokenMetadataList;
    };
 
    const tokenMetadataListPromise = extraData?.tokenMetadata ? fetchTokenMetadataList() : undefined;
 
    const getAssetInfo = async (assetId: Cardano.AssetId) => {
      const assetInfo = await this.#getAssetInfo(assetId);
 
      if (extraData?.nftMetadata) assetInfo.nftMetadata = await this.#getNftMetadata(assetInfo);
      if (tokenMetadataListPromise)
        assetInfo.tokenMetadata = (await tokenMetadataListPromise)[assetIds.indexOf(assetId)];
 
      return assetInfo;
    };
 
    return Promise.all(assetIds.map((_) => getAssetInfo(_)));
  }
 
  async #getNftMetadata(asset: AssetPolicyIdAndName): Promise<Asset.NftMetadata | null> {
    return this.#cache.get(
      nftMetadataCacheKey(Cardano.AssetId.fromParts(asset.policyId, asset.name)),
      async () => await this.#dependencies.ntfMetadataService.getNftMetadata(asset)
    );
  }
 
  async #getAssetInfo(assetId: Cardano.AssetId): Promise<Asset.AssetInfo> {
    return this.#cache.get(assetInfoCacheKey(assetId), async () => {
      const name = Cardano.AssetId.getAssetName(assetId);
      const policyId = Cardano.AssetId.getPolicyId(assetId);
      const multiAsset = await this.#builder.queryMultiAsset(policyId, name);
 
      if (!multiAsset)
        throw new ProviderError(
          ProviderFailure.NotFound,
          undefined,
          `No entries found in multi_asset table for asset '${assetId}'`
        );
 
      const fingerprint = multiAsset.fingerprint as unknown as Cardano.AssetFingerprint;
      const supply = BigInt(multiAsset.sum);
      // Backwards compatibility
      const quantity = supply;
 
      return { assetId, fingerprint, name, policyId, quantity, supply };
    });
  }
}