All files / src/services DRepRegistrationTracker.ts

100% Statements 23/23
100% Branches 8/8
100% Functions 4/4
100% Lines 18/18

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  43x 43x 43x 43x                       43x 256x       43x       124x     124x   135x 132x   132x     258x 135x 256x 5x 4x         127x              
/* eslint-disable sonarjs/cognitive-complexity */
import * as Crypto from '@cardano-sdk/crypto';
import { Cardano } from '@cardano-sdk/core';
import { Observable, distinctUntilChanged, map, switchMap } from 'rxjs';
import { TrackerSubject } from '@cardano-sdk/util-rxjs';
 
interface CreateDRepRegistrationTrackerProps {
  historyTransactions$: Observable<Cardano.HydratedTx[]>;
  pubDRepKeyHash$: Observable<Crypto.Ed25519KeyHashHex | undefined>;
}
 
interface IsOwnDRepCredentialProps {
  certificate: Cardano.Certificate;
  dRepKeyHash: Crypto.Ed25519KeyHashHex;
}
 
const hasOwnDRepCredential = ({ certificate, dRepKeyHash }: IsOwnDRepCredentialProps) =>
  'dRepCredential' in certificate &&
  certificate.dRepCredential.type === Cardano.CredentialType.KeyHash &&
  certificate.dRepCredential.hash === Crypto.Hash28ByteBase16.fromEd25519KeyHashHex(dRepKeyHash);
 
export const createDRepRegistrationTracker = ({
  historyTransactions$,
  pubDRepKeyHash$
}: CreateDRepRegistrationTrackerProps): TrackerSubject<boolean> =>
  new TrackerSubject(
    pubDRepKeyHash$.pipe(
      switchMap((dRepKeyHash) =>
        historyTransactions$.pipe(
          map((txs) => {
            if (!dRepKeyHash) return false;
            const reverseTxs = [...txs].reverse();
 
            for (const {
              body: { certificates }
            } of reverseTxs) {
              if (certificates) {
                for (const certificate of certificates) {
                  if (!hasOwnDRepCredential({ certificate, dRepKeyHash })) continue;
                  if (certificate.__typename === Cardano.CertificateType.UnregisterDelegateRepresentative) return false;
                  if (certificate.__typename === Cardano.CertificateType.RegisterDelegateRepresentative) return true;
                }
              }
            }
 
            return false;
          })
        )
      ),
      distinctUntilChanged()
    )
  );