All files / src/Asset CardanoTokenRegistry.ts

100% Statements 60/60
93.75% Branches 15/16
100% Functions 7/7
100% Lines 57/57

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 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 18036x                 36x     36x 36x 36x   36x 36x 36x                                       36x 36x 5x 26x           36x 2x   1x   1x                                                           36x   17x     17x     17x     17x         17x 17x 17x 17x       17x 17x       11x       16x   16x     16x   15x   15x 15x         11x 5x 5x   4x 3x 3x   3x 3x   1x           2x       6x 4x           2x     9x       16x 16x   16x 20x   20x 4x 4x 16x     16x      
import {
  Asset,
  Cardano,
  CardanoNodeUtil,
  Milliseconds,
  ProviderError,
  ProviderFailure,
  Seconds
} from '@cardano-sdk/core';
import { InMemoryCache } from '../InMemoryCache';
import { Logger } from 'ts-log';
import { TokenMetadataService } from './types';
import { contextLogger } from '@cardano-sdk/util';
import axios, { AxiosInstance } from 'axios';
import pick from 'lodash/pick.js';
 
export const DEFAULT_TOKEN_METADATA_CACHE_TTL = Seconds(10 * 60);
export const DEFAULT_TOKEN_METADATA_REQUEST_TIMEOUT = Milliseconds(3 * 1000);
export const DEFAULT_TOKEN_METADATA_SERVER_URL = 'https://tokens.cardano.org';
 
interface NumberValue {
  value?: number;
}
 
interface StringValue {
  value?: string;
}
 
interface TokenMetadataServiceRecord {
  decimals?: NumberValue;
  description?: StringValue;
  logo?: StringValue;
  name?: StringValue;
  subject: string;
  ticker?: StringValue;
  url?: StringValue;
}
 
const propertiesToChange: Record<string, string> = { description: 'desc', logo: 'icon', subject: 'assetId' };
export const toCoreTokenMetadata = (record: TokenMetadataServiceRecord): Asset.TokenMetadata =>
  Object.fromEntries(
    Object.entries(record).map(([key, value]) => [
      propertiesToChange[key] || key,
      typeof value === 'string' ? value : value.value
    ])
  ) as Asset.TokenMetadata;
 
const toProviderError = (error: unknown, details: string) => {
  if (CardanoNodeUtil.isProviderError(error)) return error;
 
  const message = error instanceof Error ? `${error.message} ` : '';
 
  return new ProviderError(ProviderFailure.Unknown, error, `${message}${details}`);
};
 
/** Configuration options for CardanoTokenRegistry */
export interface CardanoTokenRegistryConfiguration {
  /** The cache TTL in seconds. Default: 10 minutes. */
  tokenMetadataCacheTTL?: Seconds;
 
  /** The Cardano Token Registry API base URL. Default: https://tokens.cardano.org */
  tokenMetadataServerUrl?: string;
 
  /** The HTTP request timeout value */
  tokenMetadataRequestTimeout?: Milliseconds;
}
 
interface CardanoTokenRegistryConfigurationWithRequired extends CardanoTokenRegistryConfiguration {
  tokenMetadataCacheTTL: Seconds;
  tokenMetadataServerUrl: string;
}
 
/** Dependencies that are need to create CardanoTokenRegistry */
export interface CardanoTokenRegistryDependencies {
  /** The cache engine. Default: InMemoryCache with CardanoTokenRegistryConfiguration.cacheTTL as default TTL */
  cache?: InMemoryCache;
 
  /** The logger object */
  logger: Logger;
}
 
/** TokenMetadataService implementation using Cardano Token Registry API */
export class CardanoTokenRegistry implements TokenMetadataService {
  /** The axios client used to retrieve metadata from API */
  #axiosClient: AxiosInstance;
 
  /** The in memory cache engine */
  #cache: InMemoryCache;
 
  /** The logger object */
  #logger: Logger;
 
  constructor({ cache, logger }: CardanoTokenRegistryDependencies, config: CardanoTokenRegistryConfiguration = {}) {
    const defaultConfig: CardanoTokenRegistryConfigurationWithRequired = {
      tokenMetadataCacheTTL: DEFAULT_TOKEN_METADATA_CACHE_TTL,
      tokenMetadataRequestTimeout: DEFAULT_TOKEN_METADATA_REQUEST_TIMEOUT,
      tokenMetadataServerUrl: DEFAULT_TOKEN_METADATA_SERVER_URL
    };
    const configKeys = Object.keys(defaultConfig);
    const mergedConfig = { ...defaultConfig, ...config };
    this.#cache = cache || new InMemoryCache(mergedConfig.tokenMetadataCacheTTL);
    this.#axiosClient = axios.create({
      baseURL: mergedConfig.tokenMetadataServerUrl,
      timeout: mergedConfig.tokenMetadataRequestTimeout
    });
    this.#logger = contextLogger(logger, 'CardanoTokenRegistry');
    this.#logger.info('Config:', pick(mergedConfig, configKeys));
  }
 
  shutdown() {
    this.#cache.shutdown();
  }
 
  async getTokenMetadata(assetIds: Cardano.AssetId[]): Promise<(Asset.TokenMetadata | null)[]> {
    this.#logger.debug(`getTokenMetadata: "${assetIds}"`);
 
    const [assetIdsToRequest, tokenMetadata] = this.getTokenMetadataFromCache(assetIds);
 
    // All metadata was taken from cache
    if (assetIdsToRequest.length === 0) return tokenMetadata;
 
    this.#logger.debug(`Fetching batch of ${assetIdsToRequest.length} assetIds`);
 
    try {
      const response = await this.#axiosClient.post<{ subjects: TokenMetadataServiceRecord[] }>('metadata/query', {
        properties: ['decimals', 'description', 'logo', 'name', 'ticker', 'url'],
        subjects: assetIdsToRequest
      });
 
      for (const record of response.data.subjects) {
        try {
          const { subject } = record;
 
          if (subject) {
            const assetId = Cardano.AssetId(subject);
            const metadata = toCoreTokenMetadata(record);
 
            tokenMetadata[assetIds.indexOf(assetId)] = metadata;
            this.#cache.set(assetId, metadata);
          } else
            throw new ProviderError(
              ProviderFailure.InvalidResponse,
              undefined,
              `Missing 'subject' property in metadata record ${JSON.stringify(record)}`
            );
        } catch (error) {
          throw toProviderError(error, `while evaluating metadata record ${JSON.stringify(record)}`);
        }
      }
    } catch (error) {
      if (axios.isAxiosError(error)) {
        throw new ProviderError(
          ProviderFailure.Unhealthy,
          error,
          `CardanoTokenRegistry failed to fetch asset metadata from the token registry server due to: ${error.message}`
        );
      }
      throw error;
    }
 
    return tokenMetadata;
  }
 
  getTokenMetadataFromCache(assetIds: Cardano.AssetId[]) {
    const assetIdsToRequest: Cardano.AssetId[] = [];
    const cachedTokenMetadata = Array.from({ length: assetIds.length }).fill(null) as (Asset.TokenMetadata | null)[];
 
    for (const [i, assetId] of assetIds.entries()) {
      const cachedMetadata = this.#cache.getVal<Asset.TokenMetadata>(assetId);
 
      if (cachedMetadata) {
        this.#logger.debug(`Using cached asset metadata value for "${assetId}"`);
        cachedTokenMetadata[i] = cachedMetadata;
      } else assetIdsToRequest.push(assetId);
    }
 
    return [assetIdsToRequest, cachedTokenMetadata] as const;
  }
}