All files / src/services UtxoTracker.ts

100% Statements 55/55
100% Branches 20/20
100% Functions 26/26
100% Lines 47/47

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    42x 42x       42x 42x 42x 42x     42x                                   42x             124x   123x       128x   128x   128x 128x     128x               42x                         124x       125x         129x 1447x   10906x 843x   10906x   10906x     88x     203x       94x       76x         76x 76x         60423x 1447x 1x   1447x     129x     1082x 8668x 8668x 8668x         129x     1x 1x     121x 121x 121x         76x   4x        
import { Cardano, UtxoProvider } from '@cardano-sdk/core';
import { Logger } from 'ts-log';
import { NEVER, Observable, combineLatest, concat, distinctUntilChanged, map, of, switchMap } from 'rxjs';
import { PersistentCollectionTrackerSubject, txInEquals, utxoEquals } from './util';
import { RetryBackoffConfig } from 'backoff-rxjs';
import { TxInFlight, UtxoTracker } from './types';
import { WalletStores } from '../persistence';
import { coldObservableProvider } from '@cardano-sdk/util-rxjs';
import { sortUtxoByTxIn } from '@cardano-sdk/input-selection';
import chunk from 'lodash/chunk.js';
import uniqWith from 'lodash/uniqWith.js';
 
// Temporarily hardcoded. Will be replaced with ChainHistoryProvider 'maxPageSize' value once ADP-2249 is implemented
const PAGE_SIZE = 25;
 
export interface UtxoTrackerProps {
  utxoProvider: UtxoProvider;
  addresses$: Observable<Cardano.PaymentAddress[]>;
  stores: Pick<WalletStores, 'utxo' | 'unspendableUtxo'>;
  transactionsInFlight$: Observable<TxInFlight[]>;
  history$: Observable<Cardano.HydratedTx[]>;
  retryBackoffConfig: RetryBackoffConfig;
  logger: Logger;
  onFatalError?: (value: unknown) => void;
}
 
export interface UtxoTrackerInternals {
  utxoSource$?: PersistentCollectionTrackerSubject<Cardano.Utxo>;
  unspendableUtxoSource$?: PersistentCollectionTrackerSubject<Cardano.Utxo>;
}
 
export const createUtxoProvider = (
  utxoProvider: UtxoProvider,
  addresses$: Observable<Cardano.PaymentAddress[]>,
  history$: Observable<Cardano.HydratedTx[]>,
  retryBackoffConfig: RetryBackoffConfig,
  onFatalError?: (value: unknown) => void
) =>
  addresses$.pipe(
    switchMap((paymentAddresses) =>
      coldObservableProvider({
        equals: utxoEquals,
        onFatalError,
        provider: async () => {
          let utxos = new Array<Cardano.Utxo>();
 
          const addressesSubGroups = chunk(paymentAddresses, PAGE_SIZE);
 
          for (const addresses of addressesSubGroups) {
            utxos = [...utxos, ...(await utxoProvider.utxoByAddresses({ addresses }))];
          }
 
          return utxos.sort(sortUtxoByTxIn);
        },
        retryBackoffConfig,
        trigger$: history$
      })
    )
  );
 
export const createUtxoTracker = (
  {
    utxoProvider,
    addresses$,
    stores,
    transactionsInFlight$,
    retryBackoffConfig,
    history$,
    logger,
    onFatalError
  }: UtxoTrackerProps,
  {
    utxoSource$ = new PersistentCollectionTrackerSubject<Cardano.Utxo>(
      () => createUtxoProvider(utxoProvider, addresses$, history$, retryBackoffConfig, onFatalError),
      stores.utxo
    ),
    unspendableUtxoSource$ = new PersistentCollectionTrackerSubject(
      (stored) => (stored.length > 0 ? NEVER : concat(of([]), NEVER)),
      stores.unspendableUtxo
    )
  }: UtxoTrackerInternals = {}
): UtxoTracker => {
  const total$ = combineLatest([utxoSource$, transactionsInFlight$, addresses$]).pipe(
    map(([onChainUtxo, transactionsInFlight, ownAddresses]) => [
      ...onChainUtxo.filter(([utxoTxIn]) => {
        const utxoIsUsedInFlight = transactionsInFlight.some(({ body: { inputs } }) =>
          inputs.some((input) => input.txId === utxoTxIn.txId && input.index === utxoTxIn.index)
        );
        utxoIsUsedInFlight &&
          logger.debug('OnChain UTXO is already used in in-flight transaction. Excluding from total$.', utxoTxIn);
        return !utxoIsUsedInFlight;
      }),
      ...transactionsInFlight.flatMap(({ body: { outputs }, id }, txInFlightIndex) =>
        outputs
          .filter(
            ({ address }, outputIndex) =>
              ownAddresses.includes(address) &&
              // not already consumed by another tx in flight
              !transactionsInFlight.some(
                ({ body: { inputs } }, i) =>
                  txInFlightIndex !== i && inputs.some((txIn) => txIn.txId === id && txIn.index === outputIndex)
              )
          )
          .map((txOut): Cardano.Utxo => {
            const txIn: Cardano.HydratedTxIn = {
              address: txOut.address, // not necessarily correct in multi-address wallet
              index: outputs.indexOf(txOut),
              txId: id
            };
            logger.debug('New UTXO available from in-flight transactions. Including in total$.', txIn);
            return [txIn, txOut];
          })
      )
    ]),
    map((utxo) => {
      const uniqueUtxo = uniqWith(utxo, ([a], [b]) => a.txId === b.txId && a.index === b.index);
      if (uniqueUtxo.length !== utxo.length) {
        logger.debug('Found duplicate UTxO in', utxo);
      }
      return uniqueUtxo;
    })
  );
  const available$ = combineLatest([total$, unspendableUtxoSource$]).pipe(
    // filter to utxo that are not included in in-flight transactions or unspendable
    map(([utxo, unspendableUtxo]) =>
      utxo.filter(([utxoTxIn]) => {
        const txInIsUnspendable = unspendableUtxo.some(([unspendable]) => txInEquals(utxoTxIn, unspendable));
        txInIsUnspendable && logger.debug('Exclude unspendable UTXO from availble$', utxoTxIn);
        return !txInIsUnspendable;
      })
    )
  );
 
  return {
    available$,
    setUnspendable: async (utxo) => {
      logger.debug('setUnspendable', utxo);
      unspendableUtxoSource$.next(utxo);
    },
    shutdown: () => {
      utxoSource$.complete();
      unspendableUtxoSource$.complete();
      logger.debug('Shutdown');
    },
    total$,
    unspendable$: combineLatest([unspendableUtxoSource$, total$]).pipe(
      map(([unspendableUtxo, utxo]) =>
        unspendableUtxo.filter(([unspendable]) => utxo.some(([utxoTxIn]) => txInEquals(utxoTxIn, unspendable)))
      ),
      distinctUntilChanged((previous, current) => utxoEquals(previous, current))
    )
  };
};