All files / src/services AssetsTracker.ts

100% Statements 92/92
96.42% Branches 27/28
100% Functions 34/34
100% Lines 85/85

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 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 26042x       42x                                   42x 42x 42x 42x 42x 42x   42x 646x 137x       42x 132x 132x   42x 42x 42x   42x 16x                         42x         249x 249x 249x   249x 385x   385x 244x 244x     141x   141x   141x   141x 126x   15x       249x     42x             249x   249x   249x     1x 1x     1x     248x         248x 248x 370x 370x           248x     42x 42x                 130x 237x   237x         249x       137x                                   42x 502x 129x   42x                                             132x 132x 132x 132x 132x   128x   128x           128x             129x       129x 234x 234x     129x   18x 18x 18x 1x             129x   129x         250x 362x         250x 150x   150x 305x 150x        
import { Asset, Cardano } from '@cardano-sdk/core';
import { Assets } from '../types';
import { BalanceTracker, Milliseconds, TransactionsTracker } from './types';
import { Logger } from 'ts-log';
import {
  Observable,
  buffer,
  concat,
  connect,
  debounceTime,
  distinctUntilChanged,
  filter,
  firstValueFrom,
  map,
  of,
  share,
  switchMap,
  take,
  tap
} from 'rxjs';
import { RetryBackoffConfig } from 'backoff-rxjs';
import { TrackedAssetProvider } from './ProviderTracker';
import { concatAndCombineLatest } from '@cardano-sdk/util-rxjs';
import { deepEquals, isNotNil } from '@cardano-sdk/util';
import { newTransactions$ } from './TransactionsTracker';
import { pollProvider } from './util';
import chunk from 'lodash/chunk.js';
import uniq from 'lodash/uniq.js';
 
const isAssetInfoComplete = (assetInfo: Asset.AssetInfo): boolean =>
  assetInfo.nftMetadata !== undefined && assetInfo.tokenMetadata !== undefined;
const isEveryAssetInfoComplete = (assetInfos: Asset.AssetInfo[]): boolean => assetInfos.every(isAssetInfoComplete);
 
/** Buffers the source Observable values emitted at the same time (within 1 ms) */
const bufferTick =
  <T>() =>
  (source$: Observable<T>) =>
    source$.pipe(connect((shared$) => shared$.pipe(buffer(shared$.pipe(debounceTime(1))))));
 
const ASSET_INFO_FETCH_CHUNK_SIZE = 100;
const ONE_DAY = 24 * 60 * 60 * 1000;
const ONE_WEEK = 7 * ONE_DAY;
 
const isInBalance = (assetId: Cardano.AssetId, balance: Cardano.Value): boolean =>
  balance.assets?.has(assetId) ?? false;
 
/**
 * Splits a list of asset IDs into cached and uncached groups based on their presence in the cache,
 * their freshness, and their balance status:
 *
 * 1. Assets not in Balance:
 *    - Always use the cached version if present in the cache, ignoring freshness.
 * 2. Assets in Balance:
 *    - Use the cached version only if it exists and its `staleAt` timestamp did not expire.
 * 3. Uncached Assets:
 *    - If an asset is not in the cache or does not meet the above criteria, mark it as uncached.
 */
const splitCachedAndUncachedAssets = (
  cache: Assets,
  balance: Cardano.Value,
  assetIds: Cardano.AssetId[]
): { cachedAssets: Assets; uncachedAssetIds: Cardano.AssetId[] } => {
  const cachedAssets: Assets = new Map();
  const uncachedAssetIds: Cardano.AssetId[] = [];
  const now = new Date();
 
  for (const id of assetIds) {
    const cachedAssetInfo = cache.get(id);
 
    if (!cachedAssetInfo) {
      uncachedAssetIds.push(id);
      continue;
    }
 
    const { staleAt } = cachedAssetInfo;
 
    const expired = !staleAt || new Date(staleAt) < now;
 
    const mustFetch = !isAssetInfoComplete(cachedAssetInfo) || (isInBalance(id, balance) && expired);
 
    if (mustFetch) {
      uncachedAssetIds.push(id);
    } else {
      cachedAssets.set(id, cachedAssetInfo);
    }
  }
 
  return { cachedAssets, uncachedAssetIds };
};
 
const getAssetsWithCache = async (
  assetIdsChunk: Cardano.AssetId[],
  assetCache$: Observable<Assets>,
  totalBalance$: Observable<Cardano.Value>,
  assetProvider: TrackedAssetProvider,
  maxAssetInfoCacheAge: Milliseconds
): Promise<Asset.AssetInfo[]> => {
  const [cache, totalValue] = await Promise.all([firstValueFrom(assetCache$), firstValueFrom(totalBalance$)]);
 
  const { cachedAssets, uncachedAssetIds } = splitCachedAndUncachedAssets(cache, totalValue, assetIdsChunk);
 
  if (uncachedAssetIds.length === 0) {
    // If all assets are cached we wont perform any fetches from assetProvider, but still need to
    // mark it as initialized.
    if (!assetProvider.stats.getAsset$.value.initialized) {
      assetProvider.setStatInitialized(assetProvider.stats.getAsset$);
    }
 
    return [...cachedAssets.values()];
  }
 
  const fetchedAssets = await assetProvider.getAssets({
    assetIds: uncachedAssetIds,
    extraData: { nftMetadata: true, tokenMetadata: true }
  });
 
  const now = Date.now();
  const updatedFetchedAssets = fetchedAssets.map((asset) => {
    const randomDelta = Math.floor(Math.random() * 2 * ONE_DAY); // Random time between 0 and 2 days
    return {
      ...asset,
      staleAt: new Date(now + maxAssetInfoCacheAge + randomDelta)
    };
  });
 
  return [...cachedAssets.values(), ...updatedFetchedAssets];
};
 
export const createAssetService =
  (
    assetProvider: TrackedAssetProvider,
    assetCache$: Observable<Assets>,
    totalBalance$: Observable<Cardano.Value>,
    retryBackoffConfig: RetryBackoffConfig,
    logger: Logger,
    maxAssetInfoCacheAge: Milliseconds = ONE_WEEK
    // eslint-disable-next-line max-params
  ) =>
  (assetIds: Cardano.AssetId[]) =>
    concatAndCombineLatest(
      chunk(assetIds, ASSET_INFO_FETCH_CHUNK_SIZE).map((assetIdsChunk) =>
        pollProvider({
          logger,
          pollUntil: isEveryAssetInfoComplete,
          retryBackoffConfig,
          sample: () =>
            getAssetsWithCache(assetIdsChunk, assetCache$, totalBalance$, assetProvider, maxAssetInfoCacheAge),
          trigger$: of(true) // fetch only once
        })
      )
    ).pipe(map((arr) => arr.flat())); // Concatenate the chunk results
 
export type AssetService = ReturnType<typeof createAssetService>;
 
export interface AssetsTrackerProps {
  transactionsTracker: TransactionsTracker;
  assetProvider: TrackedAssetProvider;
  retryBackoffConfig: RetryBackoffConfig;
  logger: Logger;
  assetsCache$: Observable<Assets>;
  balanceTracker: BalanceTracker;
  maxAssetInfoCacheAge?: Milliseconds;
}
 
interface AssetsTrackerInternals {
  assetService?: AssetService;
}
 
const uniqueAssetIds = ({ body: { outputs } }: Cardano.OnChainTx) =>
  outputs.flatMap(({ value: { assets } }) => (assets ? [...assets.keys()] : []));
const flatUniqueAssetIds = (txes: Cardano.OnChainTx[]) => uniq(txes.flatMap(uniqueAssetIds));
 
export const createAssetsTracker = (
  {
    assetProvider,
    assetsCache$,
    transactionsTracker: { history$ },
    balanceTracker: {
      utxo: { total$ }
    },
    retryBackoffConfig,
    logger,
    maxAssetInfoCacheAge
  }: AssetsTrackerProps,
  {
    assetService = createAssetService(
      assetProvider,
      assetsCache$,
      total$,
      retryBackoffConfig,
      logger,
      maxAssetInfoCacheAge
    )
  }: AssetsTrackerInternals = {}
) =>
  new Observable<Map<Cardano.AssetId, Asset.AssetInfo>>((subscriber) => {
    let fetchedAssetInfoMap = new Map<Cardano.AssetId, Asset.AssetInfo>();
    const allAssetIds = new Set<Cardano.AssetId>();
    const sharedHistory$ = history$.pipe(share());
    return concat(
      sharedHistory$.pipe(
        map((historyTxs) => uniq(historyTxs.flatMap(uniqueAssetIds))),
        tap((assetIds) =>
          logger.debug(
            assetIds.length > 0
              ? `Historical total assets: ${assetIds.length}`
              : 'Setting assetProvider stats as initialized'
          )
        ),
        tap((assetIds) => assetIds.length === 0 && assetProvider.setStatInitialized(assetProvider.stats.getAsset$)),
        take(1)
      ),
      newTransactions$(sharedHistory$).pipe(
        bufferTick(),
        map(flatUniqueAssetIds),
        map((assetIds) => {
          const newAssetIds = assetIds.filter((assetId) => !allAssetIds.has(assetId));
          // re-fetch all asset infos that either
          // - weren't fetched yet
          // - were fetched with incomplete metadata
          const assetIdsToRefetch = [...allAssetIds.values()].filter((assetId) => {
            const assetInfo = fetchedAssetInfoMap.get(assetId);
            return !assetInfo || !isAssetInfoComplete(assetInfo);
          });
          // When we see a CIP-68 reference NFT, it means metadata for a user NFT that we own might have changed
          const assetsWithCip68MetadataUpdates = assetIds
            .map((assetId) => {
              const assetName = Cardano.AssetId.getAssetName(assetId);
              const decoded = Asset.AssetNameLabel.decode(assetName);
              if (decoded?.label === Asset.AssetNameLabelNum.ReferenceNFT) {
                return Cardano.AssetId.fromParts(
                  Cardano.AssetId.getPolicyId(assetId),
                  Asset.AssetNameLabel.encode(decoded.content, Asset.AssetNameLabelNum.UserNFT)
                );
              }
            })
            .filter(isNotNil);
          return uniq([...newAssetIds, ...assetIdsToRefetch, ...assetsWithCip68MetadataUpdates]);
        }),
        filter((assetIds) => assetIds.length > 0)
      )
    )
      .pipe(
        tap((assetIds) => {
          for (const assetId of assetIds) {
            allAssetIds.add(assetId);
          }
        }),
        // Restart inner observable if there are new assets to be fetched,
        // otherwise the whole pipe will hang waiting for all assetInfos to resolve
        switchMap((assetIdsToFetch) => (assetIdsToFetch.length > 0 ? assetService(assetIdsToFetch) : of([]))),
        map((fetchedAssetInfos) => [...[...fetchedAssetInfoMap.values()].filter(isNotNil), ...fetchedAssetInfos]),
        distinctUntilChanged(deepEquals), // It optimizes to not process duplicate emissions of the assets
        tap((assetInfos) => logger.debug(`Got metadata for ${assetInfos.length} assets`)),
        map((assetInfos) => new Map(assetInfos.map((assetInfo) => [assetInfo.assetId, assetInfo]))),
        tap((v) => (fetchedAssetInfoMap = v))
      )
      .subscribe(subscriber);
  });