All files / src/services HandlesTracker.ts

100% Statements 60/60
95.83% Branches 23/24
100% Functions 21/21
100% Lines 58/58

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 16442x   42x                                 42x 42x 42x 42x   42x 42x                                 42x 1x         42x 6x   42x 42x 44x 2x 2x 2x 1x               1x 1x       42x 42x 51x 51x 51x   10x   6x   15x           1x       6x 5x                   42x       47x   9x 47x     37x 37x 28x     9x 9x 9x   8x       8x       9x   8x 8x 2x 2x   6x                 9x   2x     7x   6x 1x 1x   5x       1x        
import { Asset, Cardano, Handle, HandleProvider } from '@cardano-sdk/core';
import { Assets, HandleInfo } from '../types';
import {
  EMPTY,
  Observable,
  catchError,
  combineLatest,
  concatMap,
  defer,
  distinctUntilChanged,
  from,
  mergeMap,
  of,
  shareReplay,
  startWith,
  tap,
  toArray
} from 'rxjs';
import { Logger } from 'ts-log';
import { deepEquals, isNotNil, sameArrayItems } from '@cardano-sdk/util';
import { passthrough } from '@cardano-sdk/util-rxjs';
import { retryBackoff } from 'backoff-rxjs';
import uniqBy from 'lodash/uniqBy.js';
 
export const HYDRATE_HANDLE_INITIAL_INTERVAL = 50;
export const HYDRATE_HANDLE_MAX_RETRIES = 5;
 
export interface HandlesTrackerProps {
  utxo$: Observable<Cardano.Utxo[]>;
  assetInfo$: Observable<Assets>;
  handlePolicyIds$: Observable<Cardano.PolicyId[]>;
  logger: Logger;
  handleProvider: HandleProvider;
}
 
interface HandlesTrackerInternals {
  hydrateHandle?: (
    handleProvider: HandleProvider,
    logger: Logger
  ) => (handles: HandleInfo) => Promise<HandleInfo> | Observable<HandleInfo>;
}
 
const handleInfoEquals = (a: HandleInfo, b: HandleInfo) =>
  a.assetId === b.assetId &&
  a.resolvedAt?.hash === b.resolvedAt?.hash &&
  deepEquals(a.tokenMetadata, b.tokenMetadata) &&
  deepEquals(a.nftMetadata, b.nftMetadata);
 
const isHydrated = (handleInfo: HandleInfo) =>
  'image' in handleInfo && 'backgroundImage' in handleInfo && 'profilePic' in handleInfo;
 
export const hydrateHandleAsync =
  (handleProvider: HandleProvider, logger: Logger) =>
  async (handle: HandleInfo): Promise<HandleInfo> => {
    logger.debug('hydrating handle', handle.handle);
    try {
      const [resolution] = await handleProvider.resolveHandles({ handles: [handle.handle] });
      return {
        ...handle,
        backgroundImage: resolution?.backgroundImage,
        image: resolution?.image,
        profilePic: resolution?.profilePic,
        resolvedAt: resolution?.resolvedAt
      };
    } catch (error) {
      logger.error("Couldn't hydrate handle", error);
      throw error;
    }
  };
 
export const hydrateHandles =
  (hydrateHandle: (handle: HandleInfo) => Promise<HandleInfo> | Observable<HandleInfo>) =>
  (evt$: Observable<HandleInfo[]>): Observable<HandleInfo[]> => {
    const hydratedHandles: Partial<Record<Handle, HandleInfo>> = {};
    return evt$.pipe(
      mergeMap((handles) =>
        from(handles).pipe(
          concatMap((handleInfo) =>
            handleInfo.handle in hydratedHandles
              ? of(hydratedHandles[handleInfo.handle]!)
              : defer(() => from(hydrateHandle(handleInfo))).pipe(
                  retryBackoff({
                    initialInterval: HYDRATE_HANDLE_INITIAL_INTERVAL,
                    maxRetries: HYDRATE_HANDLE_MAX_RETRIES,
                    resetOnSuccess: true
                  }),
                  catchError(() => of(handleInfo))
                )
          ),
          tap((handleInfo) => {
            if (isHydrated(handleInfo)) {
              hydratedHandles[handleInfo.handle] = handleInfo;
            }
          }),
          toArray(),
          handles.length > 0 ? startWith(handles) : passthrough()
        )
      )
    );
  };
 
export const createHandlesTracker = (
  { assetInfo$, handlePolicyIds$, handleProvider, logger, utxo$ }: HandlesTrackerProps,
  { hydrateHandle = hydrateHandleAsync }: HandlesTrackerInternals = {}
) =>
  combineLatest([handlePolicyIds$, utxo$, assetInfo$]).pipe(
    mergeMap(([handlePolicyIds, utxo, assets]) => {
      const filteredUtxo = utxo.flatMap(([_, txOut]) =>
        uniqBy(
          [...(txOut.value.assets?.keys() || [])]
            .filter((assetId) => {
              const matchPolicyId = handlePolicyIds.some((policyId) => assetId.startsWith(policyId));
              if (!matchPolicyId) {
                return false;
              }
 
              const assetName = Cardano.AssetId.getAssetName(assetId);
              const decoded = Asset.AssetNameLabel.decode(assetName);
              return !decoded || decoded.label === Asset.AssetNameLabelNum.UserNFT;
            })
            .map((assetId) => ({
              handleAssetId: assetId,
              txOut
            })),
          ({ handleAssetId }) => handleAssetId
        )
      );
 
      const handlesWithAssetInfo = filteredUtxo
        .map(({ handleAssetId, txOut }): HandleInfo | null => {
          const assetInfo = assets.get(handleAssetId);
          if (!assetInfo) {
            logger.debug(`Asset info not (yet?) found for ${handleAssetId}`);
            return null;
          }
          return {
            ...assetInfo,
            cardanoAddress: txOut.address,
            handle: Asset.util.getAssetNameAsText(handleAssetId),
            hasDatum: !!txOut.datum
          };
        })
        .filter(isNotNil);
 
      if (filteredUtxo.length > 0 && handlesWithAssetInfo.length === 0) {
        // AssetInfo is still resolving
        return EMPTY;
      }
 
      return of(
        handlesWithAssetInfo.filter(({ handle, supply }) => {
          if (supply > 1n) {
            logger.warn(`Omitting handle with supply >1: ${handle}`);
            return false;
          }
          return true;
        })
      );
    }),
    distinctUntilChanged((a, b) => sameArrayItems(a, b, handleInfoEquals)),
    hydrateHandles(hydrateHandle(handleProvider, logger)),
    shareReplay({ bufferSize: 1, refCount: true })
  );