All files / src/services/DelegationTracker DelegationTracker.ts

93.84% Statements 61/65
90% Branches 18/20
88.23% Functions 15/17
93.44% Lines 57/61

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  42x       42x                           42x           42x 42x   42x   42x 42x     42x                 125x                                                         42x 10x   7x                 42x 8x   11x     11x 10x 10x   10x   8x 2x 2x     6x 6x 6x       11x       42x   11x   42x             130x 9x 130x   131x 127x     127x   4x 4x 7x         4x 1x             3x     3x 2x   1x     1x       1x                         42x                                                         125x                   125x                   125x                   125x     125x           120x 120x 120x 120x        
/* eslint-disable unicorn/consistent-function-scoping */
import { Cardano, RewardAccountInfoProvider } from '@cardano-sdk/core';
import { DelegationTracker, TransactionsTracker, UtxoTracker } from '../types';
import { GroupedAddress } from '@cardano-sdk/key-management';
import { Logger } from 'ts-log';
import {
  Observable,
  combineLatest,
  concat,
  defaultIfEmpty,
  distinctUntilChanged,
  filter,
  map,
  mergeMap,
  of,
  switchMap,
  take,
  tap
} from 'rxjs';
import {
  ObservableRewardAccountInfoProvider,
  createRewardAccountInfoProvider,
  createRewardAccountsTracker
} from './RewardAccounts';
import { RetryBackoffConfig } from 'backoff-rxjs';
import { RewardsHistoryProvider, createRewardsHistoryProvider, createRewardsHistoryTracker } from './RewardsHistory';
import { Shutdown, contextLogger, deepEquals } from '@cardano-sdk/util';
import { TrackedRewardAccountInfoProvider, TrackedRewardsProvider } from '../ProviderTracker';
import { TrackerSubject } from '@cardano-sdk/util-rxjs';
import { WalletStores } from '../../persistence';
import { createDelegationDistributionTracker } from './DelegationDistributionTracker';
import { pollProvider } from '../util';
 
const createDelegationPortfolioProvider =
  ({
    rewardAccountInfoProvider,
    retryBackoffConfig,
    logger
  }: {
    rewardAccountInfoProvider: RewardAccountInfoProvider;
    retryBackoffConfig: RetryBackoffConfig;
    logger: Logger;
  }) =>
  (rewardAccount: Cardano.RewardAccount): Observable<Cardano.Cip17DelegationPortfolio | null> =>
    pollProvider({
      logger,
      retryBackoffConfig,
      sample: () => rewardAccountInfoProvider.delegationPortfolio(rewardAccount)
    });
 
type DelegationPortfolioProvider = ReturnType<typeof createDelegationPortfolioProvider>;
 
export interface DelegationTrackerProps {
  rewardsTracker: TrackedRewardsProvider;
  rewardAccountAddresses$: Observable<Cardano.RewardAccount[]>;
  rewardAccountInfoProvider: TrackedRewardAccountInfoProvider;
  epoch$: Observable<Cardano.EpochNo>;
  transactionsTracker: Pick<TransactionsTracker, 'outgoing' | 'new$' | 'history$'>;
  protocolParameters$: Observable<Pick<Cardano.ProtocolParameters, 'stakeKeyDeposit'>>;
  retryBackoffConfig: RetryBackoffConfig;
  utxoTracker: UtxoTracker;
  refetchRewardAccountInfo$: Observable<void>;
  knownAddresses$: Observable<GroupedAddress[]>;
  stores: WalletStores;
  internals?: {
    rewardsHistoryProvider?: RewardsHistoryProvider;
    observableRewardAccountInfoProvider?: ObservableRewardAccountInfoProvider;
    delegationPortfolioProvider?: DelegationPortfolioProvider;
  };
  logger: Logger;
}
 
const hasDelegationCert = (certificates: Array<Cardano.Certificate> | undefined): boolean =>
  !!certificates &&
  certificates.some((cert) =>
    Cardano.isCertType(cert, [...Cardano.RegAndDeregCertificateTypes, ...Cardano.StakeDelegationCertificateTypes])
  );
 
/**
 * @returns Observable that emits:
 * - delegation portfolio if multi-delegation metadata is found in transactions
 * - `null` if not multi-delegating
 * - `undefined` if no relevant transactions were found
 */
const findDelegationPortfolioMetadata = () => (recentTransactions: Observable<Cardano.Tx[]>) =>
  recentTransactions.pipe(
    map((hydratedTxs) => {
      const sortedTransactions = [...hydratedTxs].reverse();
 
      let result;
      for (const sorted of sortedTransactions) {
        const portfolio = sorted.auxiliaryData?.blob?.get(Cardano.DelegationMetadataLabel);
        const altersDelegationState = hasDelegationCert(sorted.body.certificates);
 
        if (!portfolio && !altersDelegationState) continue;
 
        if (altersDelegationState && !portfolio) {
          result = null;
          break;
        }
 
        if (portfolio) {
          result = Cardano.cip17FromMetadatum(portfolio);
          break;
        }
      }
 
      return result;
    })
  );
 
const delegationTransactionFound = (
  portfolio: Cardano.Cip17DelegationPortfolio | null | undefined
): portfolio is Cardano.Cip17DelegationPortfolio | null => typeof portfolio !== 'undefined';
 
export const createDelegationPortfolioTracker = (
  rewardAccounts$: Observable<Cardano.RewardAccount[]>,
  recentTransactionHistory$: Observable<Cardano.HydratedTx[]>,
  newTransaction$: Observable<Cardano.OnChainTx>,
  delegationPortfolioProvider: DelegationPortfolioProvider,
  store: WalletStores['delegationPortfolio']
) => {
  const storageSet = (portfolio: Cardano.Cip17DelegationPortfolio | null) =>
    portfolio ? store.set(portfolio).subscribe() : store.delete().subscribe();
  return combineLatest([store.get().pipe(defaultIfEmpty(null)), rewardAccounts$]).pipe(
    switchMap(([storedPortfolio, rewardAccounts]) => {
      if (rewardAccounts.length <= 1) {
        Iif (storedPortfolio) {
          storageSet(null);
        }
        return of(null);
      }
      const checkRecentHistory$ = recentTransactionHistory$.pipe(findDelegationPortfolioMetadata(), take(1));
      const observeNewTransactions$ = newTransaction$.pipe(
        map((newTx) => [newTx]),
        findDelegationPortfolioMetadata(),
        filter(delegationTransactionFound),
        tap(storageSet)
      );
      if (storedPortfolio) {
        return concat(
          of(storedPortfolio),
          // history is checked to recover from stale stored porfolio
          checkRecentHistory$.pipe(filter(delegationTransactionFound)),
          observeNewTransactions$
        );
      }
      return concat(
        checkRecentHistory$.pipe(
          mergeMap((historyPorfolio) => {
            if (delegationTransactionFound(historyPorfolio)) {
              return of(historyPorfolio);
            }
            return recentTransactionHistory$.pipe(
              take(1),
              mergeMap((recentHistory) => {
                Iif (recentHistory.length === 0) {
                  // no transactions => new wallet => not multi-delegating
                  return of(null);
                }
                return delegationPortfolioProvider(rewardAccounts[0]).pipe(take(1));
              })
            );
          }),
          tap(storageSet)
        ),
        observeNewTransactions$
      );
    }),
    distinctUntilChanged(deepEquals)
  );
};
 
export const createDelegationTracker = ({
  rewardAccountAddresses$,
  epoch$,
  rewardsTracker,
  retryBackoffConfig,
  transactionsTracker,
  rewardAccountInfoProvider,
  knownAddresses$,
  refetchRewardAccountInfo$,
  protocolParameters$,
  utxoTracker,
  stores,
  logger,
  internals: {
    rewardsHistoryProvider = createRewardsHistoryProvider(rewardsTracker, retryBackoffConfig),
    observableRewardAccountInfoProvider = createRewardAccountInfoProvider({
      epoch$,
      externalTrigger$: refetchRewardAccountInfo$,
      logger,
      retryBackoffConfig,
      rewardAccountInfoProvider
    }),
    delegationPortfolioProvider = createDelegationPortfolioProvider({
      logger,
      retryBackoffConfig,
      rewardAccountInfoProvider
    })
  } = {}
}: DelegationTrackerProps): DelegationTracker & Shutdown => {
  const rewardsHistory$ = new TrackerSubject(
    createRewardsHistoryTracker(
      rewardAccountAddresses$,
      epoch$,
      rewardsHistoryProvider,
      stores.rewardsHistory,
      contextLogger(logger, 'rewardsHistory$')
    )
  );
 
  const portfolio$ = new TrackerSubject(
    createDelegationPortfolioTracker(
      rewardAccountAddresses$,
      transactionsTracker.history$,
      transactionsTracker.new$,
      delegationPortfolioProvider,
      stores.delegationPortfolio
    )
  );
 
  const rewardAccounts$ = new TrackerSubject(
    createRewardAccountsTracker({
      newTransaction$: transactionsTracker.new$,
      protocolParameters$,
      rewardAccountAddresses$,
      rewardAccountInfoProvider: observableRewardAccountInfoProvider,
      store: stores.rewardAccountInfo,
      transactionsInFlight$: transactionsTracker.outgoing.inFlight$
    })
  );
  const distribution$ = new TrackerSubject(
    createDelegationDistributionTracker({ knownAddresses$, rewardAccounts$, utxoTracker })
  );
  return {
    distribution$,
    portfolio$,
    rewardAccounts$,
    rewardsHistory$,
    shutdown: () => {
      rewardAccounts$.complete();
      rewardsHistory$.complete();
      portfolio$.complete();
      logger.debug('Shutdown');
    }
  };
};