All files / src/AssetInfoProvider BlockfrostAssetProvider.ts

74.6% Statements 47/63
82.22% Branches 37/45
81.25% Functions 13/16
80.39% Lines 41/51

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 14811x   11x   11x 11x     11x   6x       5x     5x 5x 5x 5x             1x 1x 1x 1x 1x 1x                                                     18x       15x 8x 5x   10x     15x       3x 1x 1x 1x 1x 2x               5x           6x     6x     6x   1x       2x                                 6x 6x 6x 6x 6x 6x                                        
import { Asset, AssetProvider, Cardano, GetAssetArgs, GetAssetsArgs } from '@cardano-sdk/core';
import { BlockfrostClient } from '../blockfrost/BlockfrostClient';
import { BlockfrostProvider } from '../blockfrost/BlockfrostProvider';
import { Logger } from 'ts-log';
import { isNotNil } from '@cardano-sdk/util';
import omit from 'lodash/omit.js';
import type { Responses } from '@blockfrost/blockfrost-js';
 
export class BlockfrostAssetProvider extends BlockfrostProvider implements AssetProvider {
  constructor(client: BlockfrostClient, logger: Logger) {
    super(client, logger);
  }
 
  private mapNftMetadata(asset: Responses['asset']): Asset.NftMetadata | null {
    const image = this.metadatumToString(
      (asset.onchain_metadata?.image as string | string[] | undefined) || asset.metadata?.logo
    );
    const name = (asset.onchain_metadata?.name as string | undefined) || asset.metadata?.name;
    Iif (!image || !name) return null;
    try {
      return {
        description: this.metadatumToString(
          (asset.onchain_metadata?.description as string | string[] | undefined) || asset.metadata?.description
        ),
        files: Array.isArray(asset.onchain_metadata?.files)
          ? asset
              .onchain_metadata!.files.map((file): Asset.NftMetadataFile | null => {
                const mediaType = file.mediaType as string | undefined;
                const fileName = file.name as string | undefined;
                const src = this.metadatumToString(file.src as string | string[] | undefined);
                Iif (!src || !mediaType) return null;
                try {
                  return {
                    mediaType: Asset.MediaType(mediaType),
                    name: fileName,
                    otherProperties: this.mapNftMetadataOtherProperties(file),
                    src: Asset.Uri(src)
                  };
                } catch (error) {
                  this.logger.warn('Failed to parse onchain_metadata file', file, error);
                  return null;
                }
              })
              .filter(isNotNil)
          : undefined,
        image: Asset.Uri(image),
        mediaType: asset.onchain_metadata?.mediaType
          ? Asset.ImageMediaType(asset.onchain_metadata.mediaType as string)
          : undefined,
        name,
        otherProperties: this.mapNftMetadataOtherProperties(asset.onchain_metadata),
        version: this.mapNftMetadataVersion(asset.onchain_metadata)
      };
    } catch (error) {
      this.logger.warn('Failed to parse nft metadata', asset, error);
      return null;
    }
  }
 
  private asString = (metadatum: unknown) => (typeof metadatum === 'string' ? metadatum : undefined);
 
  private metadatumToString(metadatum: Cardano.Metadatum | undefined | null): string | undefined {
    let stringMetadatum: string | undefined;
    if (Array.isArray(metadatum)) {
      const result = metadatum.map((metadata) => this.asString(metadata)).filter(isNotNil);
      stringMetadatum = result.join('');
    } else {
      stringMetadatum = this.asString(metadatum);
    }
 
    return stringMetadatum;
  }
 
  private objToMetadatum(obj: unknown): Cardano.Metadatum {
    if (typeof obj === 'string') return obj;
    Iif (typeof obj === 'number') return BigInt(obj);
    if (typeof obj === 'object') {
      Iif (obj === null) return '';
      if (Array.isArray(obj)) {
        return obj.map((item) => this.objToMetadatum(item));
      }
      return new Map(Object.entries(obj).map(([key, value]) => [key, this.objToMetadatum(value)]));
    }
    return '';
  }
 
  private mapNftMetadataVersion(metadata: Responses['asset']['onchain_metadata']) {
    return typeof metadata?.version === 'string' ? metadata.version : '1.0';
  }
 
  private mapNftMetadataOtherProperties(
    metadata: Responses['asset']['onchain_metadata']
  ): Map<string, Cardano.Metadatum> | undefined {
    Iif (!metadata) {
      return;
    }
    const otherProperties = Object.entries(
      omit(metadata, ['name', 'image', 'description', 'mediaType', 'files', 'version'])
    );
    if (otherProperties.length === 0) return;
    // eslint-disable-next-line consistent-return
    return new Map(otherProperties.map(([key, value]) => [key, this.objToMetadatum(value)]));
  }
 
  private mapTokenMetadata(assetId: Cardano.AssetId, asset: Responses['asset']): Asset.TokenMetadata {
    return {
      assetId,
      decimals: asset.metadata?.decimals || undefined,
      desc: this.metadatumToString(
        asset.metadata?.description || (asset.onchain_metadata?.description as string | string[] | undefined)
      ),
      icon: this.metadatumToString(
        asset.metadata?.logo || (asset.onchain_metadata?.image as string | string[] | undefined)
      ),
      name: asset.metadata?.name || (asset.onchain_metadata?.name as string | undefined),
      ticker: asset.metadata?.ticker || undefined,
      url: asset.metadata?.url || undefined,
      version: '1.0'
    };
  }
 
  async getAsset({ assetId, extraData }: GetAssetArgs): Promise<Asset.AssetInfo> {
    try {
      const response = await this.request<Responses['asset']>(`assets/${assetId.toString()}`);
      const name = Cardano.AssetId.getAssetName(assetId);
      const policyId = Cardano.PolicyId(response.policy_id);
      const quantity = BigInt(response.quantity);
      return {
        assetId,
        fingerprint: Cardano.AssetFingerprint(response.fingerprint),
        name,
        nftMetadata: extraData?.nftMetadata ? this.mapNftMetadata(response) : null,
        policyId,
        quantity,
        supply: quantity,
        tokenMetadata: extraData?.tokenMetadata ? this.mapTokenMetadata(assetId, response) : null
      };
    } catch (error) {
      this.logger.error('getAsset failed', assetId, extraData);
      throw this.toProviderError(error);
    }
  }
 
  getAssets({ assetIds, extraData }: GetAssetsArgs): Promise<Asset.AssetInfo[]> {
    return Promise.all(assetIds.map((assetId) => this.getAsset({ assetId, extraData })));
  }
}