All files / src/chainSync index.ts

36.2% Statements 21/58
18.18% Branches 2/11
9.09% Functions 1/11
37.5% Lines 21/56

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 1662x                     2x           2x 2x 2x 2x                                     2x   2x                                                                                                                         2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x                                                                                                  
import {
  Cardano,
  ChainSyncError,
  ChainSyncErrorCode,
  GeneralCardanoNodeError,
  GeneralCardanoNodeErrorCode,
  Intersection,
  Point,
  PointOrOrigin
} from '@cardano-sdk/core';
 
import {
  ChainSyncEvent,
  ChainSyncEventType,
  ChainSyncRollBackward,
  ChainSyncRollForward
} from '@cardano-sdk/projection';
import { Observable, of, throwError } from 'rxjs';
import { fromSerializableObject } from '@cardano-sdk/util';
import { genesisToEraSummary } from './genesisToEraSummary';
import memoize from 'lodash/memoize.js';
import type { ObservableCardanoNode } from '@cardano-sdk/projection';
 
export type SerializedChainSyncEvent =
  | Omit<ChainSyncRollForward, 'requestNext'>
  | Omit<ChainSyncRollBackward, 'requestNext'>;
 
export type ChainSyncMetadata = {
  cardano: {
    compactGenesis: Cardano.CompactGenesis;
    intersection: Intersection;
  };
};
 
export type ChainSyncData = {
  body: SerializedChainSyncEvent[];
  metadata: ChainSyncMetadata;
};
 
export * from './genesisToEraSummary';
 
const intersect = (events: ChainSyncData['body'], points: PointOrOrigin[]) => {
  const blockPoints = points.filter((point): point is Point => point !== 'origin');
  Iif (blockPoints.length === 0) {
    Iif (points.length === 0) {
      throw new ChainSyncError(
        ChainSyncErrorCode.IntersectionNotFound,
        { points, tip: events[0].tip },
        'Intersection not found'
      );
    }
    return {
      events,
      intersection: {
        point: 'origin' as const,
        tip: events[0].tip
      }
    };
  }
  const remainingEvents = [...events];
  let eventsSinceIntersection: SerializedChainSyncEvent[] = [];
  let evt: ChainSyncData['body'][0] | undefined;
  while ((evt = remainingEvents.pop())) {
    Iif (evt.eventType !== ChainSyncEventType.RollForward) {
      eventsSinceIntersection = [evt, ...eventsSinceIntersection];
      continue;
    }
    const {
      block: { header }
    } = evt;
    const point = blockPoints.find(({ hash }) => header.hash === hash);
    Iif (point) {
      return {
        events: eventsSinceIntersection,
        intersection: {
          point,
          tip:
            eventsSinceIntersection.length > 0
              ? eventsSinceIntersection[eventsSinceIntersection.length - 1].tip
              : header
        }
      };
    }
    eventsSinceIntersection = [evt, ...eventsSinceIntersection];
  }
  Iif (points.includes('origin')) {
    return {
      events,
      intersection: {
        point: 'origin' as const,
        tip: events[0].tip
      }
    };
  }
 
  throw new ChainSyncError(
    ChainSyncErrorCode.IntersectionNotFound,
    { points, tip: events[0].tip },
    'Intersection not found'
  );
};
 
export enum ChainSyncDataSet {
  PreviewStakePoolProblem = 'preview-stake-pool-problem.json',
  AssetNameUtf8Problem = 'asset-name-utf8-problem.json',
  MissingExtraDatumMetadataProblem = 'missing-extra-datum-metadata-problem.json',
  ExtraDataNullCharactersProblem = 'extra-data-null-characters-problem.json',
  Cip68WitnessDatumProblem = 'cip68-witness-datum-problem.json',
  WithPoolRetirement = 'with-pool-retirement.json',
  WithStakeKeyDeregistration = 'with-stake-key-deregistration.json',
  WithMint = 'with-mint.json',
  WithHandle = 'with-handle.json',
  WithInlineDatum = 'with-inline-datum.json',
  Cip68HandleProblem = 'cip68-handle-problem.json'
}
 
export const chainSyncData = memoize((dataSet: ChainSyncDataSet) => {
  const {
    body: allEvents,
    metadata: {
      cardano: { compactGenesis }
    }
  } = fromSerializableObject(require(`./data/${dataSet}`)) as ChainSyncData;
  const eraSummaries = [genesisToEraSummary(compactGenesis)];
  const cardanoNode: ObservableCardanoNode = {
    eraSummaries$: of(eraSummaries),
    findIntersect: (points) => {
      const { intersection, events } = intersect(allEvents, points);
      return of({
        chainSync$: new Observable<ChainSyncEvent>((subscriber) => {
          const remainingEvents = [...events];
          const requestNext = () => {
            const nextEvent = remainingEvents.shift();
            if (nextEvent) {
              subscriber.next({
                ...nextEvent,
                requestNext: () => setTimeout(requestNext, 1)
              });
            } else {
              subscriber.complete();
            }
          };
          requestNext();
        }),
        intersection
      });
    },
    genesisParameters$: of(compactGenesis),
    healthCheck$: new Observable(),
    submitTx: () =>
      throwError(
        () => new GeneralCardanoNodeError(GeneralCardanoNodeErrorCode.Unknown, null, 'submitTx is not implemented')
      )
  };
  return {
    allEvents,
    cardanoNode,
    networkInfo: {
      eraSummaries,
      genesisParameters: compactGenesis
    }
  };
});
 
export type StubChainSyncData = ReturnType<typeof chainSyncData>;