@odatano/core 1.11.0 → 2.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/@cds-models/CardanoIndexerService/index.d.ts +142 -0
  2. package/@cds-models/CardanoIndexerService/index.js +23 -0
  3. package/@cds-models/CardanoODataService/index.d.ts +693 -2172
  4. package/@cds-models/CardanoODataService/index.js +88 -390
  5. package/@cds-models/CardanoSignService/index.d.ts +443 -1574
  6. package/@cds-models/CardanoSignService/index.js +62 -293
  7. package/@cds-models/CardanoTransactionService/index.d.ts +431 -1488
  8. package/@cds-models/CardanoTransactionService/index.js +60 -271
  9. package/@cds-models/CardanoWorkerService/index.d.ts +224 -0
  10. package/@cds-models/CardanoWorkerService/index.js +32 -0
  11. package/@cds-models/_/index.d.ts +70 -40
  12. package/@cds-models/_/index.js +17 -32
  13. package/@cds-models/cds/outbox/index.d.ts +28 -0
  14. package/@cds-models/index.d.ts +225 -522
  15. package/@cds-models/index.js +35 -218
  16. package/@cds-models/odatano/cardano/index.d.ts +896 -2947
  17. package/@cds-models/odatano/cardano/index.js +109 -536
  18. package/@cds-models/sap/common/index.d.ts +196 -600
  19. package/@cds-models/sap/common/index.js +28 -269
  20. package/README.md +36 -2
  21. package/db/schema.cds +283 -1
  22. package/db/types.cds +48 -0
  23. package/package.json +173 -164
  24. package/src/index.d.ts +1 -1
  25. package/src/index.js +10 -2
  26. package/src/plugin.js +12 -2
  27. package/srv/blockchain/backends/blockfrost-backend.d.ts +21 -2
  28. package/srv/blockchain/backends/blockfrost-backend.js +68 -15
  29. package/srv/blockchain/backends/cardano-backend.d.ts +69 -0
  30. package/srv/blockchain/backends/cardano-backend.js +13 -0
  31. package/srv/blockchain/backends/koios-backend.d.ts +26 -2
  32. package/srv/blockchain/backends/koios-backend.js +147 -15
  33. package/srv/blockchain/backends/ogmios-backend.d.ts +37 -6
  34. package/srv/blockchain/backends/ogmios-backend.js +254 -5
  35. package/srv/blockchain/cardano-client.d.ts +19 -0
  36. package/srv/blockchain/cardano-client.js +36 -0
  37. package/srv/blockchain/cardano-indexer.d.ts +50 -1
  38. package/srv/blockchain/cardano-indexer.js +191 -0
  39. package/srv/blockchain/crawler/crawler.d.ts +151 -0
  40. package/srv/blockchain/crawler/crawler.js +677 -0
  41. package/srv/blockchain/crawler/hooks.d.ts +43 -0
  42. package/srv/blockchain/crawler/hooks.js +62 -0
  43. package/srv/blockchain/crawler/index.d.ts +26 -0
  44. package/srv/blockchain/crawler/index.js +135 -0
  45. package/srv/blockchain/crawler/sync-state.d.ts +94 -0
  46. package/srv/blockchain/crawler/sync-state.js +265 -0
  47. package/srv/blockchain/signing/hsm-signer.d.ts +45 -0
  48. package/srv/blockchain/signing/hsm-signer.js +8 -1
  49. package/srv/blockchain/wallet-worker/build-request.d.ts +26 -0
  50. package/srv/blockchain/wallet-worker/build-request.js +341 -0
  51. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +86 -0
  52. package/srv/blockchain/wallet-worker/confirmation-tracker.js +228 -0
  53. package/srv/blockchain/wallet-worker/index.d.ts +14 -0
  54. package/srv/blockchain/wallet-worker/index.js +80 -0
  55. package/srv/blockchain/wallet-worker/job-store.d.ts +261 -0
  56. package/srv/blockchain/wallet-worker/job-store.js +564 -0
  57. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +43 -0
  58. package/srv/blockchain/wallet-worker/lease-heartbeat.js +99 -0
  59. package/srv/blockchain/wallet-worker/signers.d.ts +57 -0
  60. package/srv/blockchain/wallet-worker/signers.js +131 -0
  61. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +145 -0
  62. package/srv/blockchain/wallet-worker/wallet-worker.js +542 -0
  63. package/srv/cardano-indexer-service.cds +73 -0
  64. package/srv/cardano-indexer-service.d.ts +2 -0
  65. package/srv/cardano-indexer-service.js +76 -0
  66. package/srv/cardano-service.js +76 -5
  67. package/srv/cardano-tx-service.d.ts +1 -11
  68. package/srv/cardano-tx-service.js +11 -162
  69. package/srv/cardano-worker-service.cds +125 -0
  70. package/srv/cardano-worker-service.d.ts +2 -0
  71. package/srv/cardano-worker-service.js +199 -0
  72. package/srv/server.d.ts +32 -1
  73. package/srv/server.js +229 -36
  74. package/srv/utils/collections.d.ts +13 -0
  75. package/srv/utils/collections.js +24 -0
  76. package/srv/utils/crypto.d.ts +16 -0
  77. package/srv/utils/crypto.js +75 -0
  78. package/srv/utils/error-codes.d.ts +6 -0
  79. package/srv/utils/error-codes.js +6 -0
  80. package/srv/utils/errors.d.ts +12 -0
  81. package/srv/utils/errors.js +45 -0
  82. package/srv/utils/mappers.js +13 -3
  83. package/srv/utils/service-events.d.ts +26 -0
  84. package/srv/utils/service-events.js +46 -0
  85. package/srv/utils/tx-request-parsers.d.ts +58 -0
  86. package/srv/utils/tx-request-parsers.js +170 -0
  87. package/srv/utils/tx-utils.d.ts +2 -1
  88. package/srv/utils/tx-utils.js +3 -2
  89. package/srv/utils/types.d.ts +2 -1
  90. package/@cds-models/CardanoODataService/index.d.ts.map +0 -1
  91. package/@cds-models/CardanoODataService/index.js.map +0 -1
  92. package/@cds-models/CardanoODataService/index.ts +0 -776
  93. package/@cds-models/CardanoSignService/index.d.ts.map +0 -1
  94. package/@cds-models/CardanoSignService/index.js.map +0 -1
  95. package/@cds-models/CardanoSignService/index.ts +0 -569
  96. package/@cds-models/CardanoTransactionService/index.d.ts.map +0 -1
  97. package/@cds-models/CardanoTransactionService/index.js.map +0 -1
  98. package/@cds-models/CardanoTransactionService/index.ts +0 -526
  99. package/@cds-models/_/index.d.ts.map +0 -1
  100. package/@cds-models/_/index.js.map +0 -1
  101. package/@cds-models/_/index.ts +0 -96
  102. package/@cds-models/cds/outbox/index.ts +0 -27
  103. package/@cds-models/index.d.ts.map +0 -1
  104. package/@cds-models/index.js.map +0 -1
  105. package/@cds-models/index.ts +0 -245
  106. package/@cds-models/odatano/cardano/index.d.ts.map +0 -1
  107. package/@cds-models/odatano/cardano/index.js.map +0 -1
  108. package/@cds-models/odatano/cardano/index.ts +0 -789
  109. package/@cds-models/sap/common/index.d.ts.map +0 -1
  110. package/@cds-models/sap/common/index.js.map +0 -1
  111. package/@cds-models/sap/common/index.ts +0 -249
@@ -71,10 +71,6 @@ function resolveOgmiosTip(tip) {
71
71
  function resolveOgmiosHeight(height) {
72
72
  return height === 'origin' ? 0 : height;
73
73
  }
74
- /**
75
- * Ogmios Backend Implementation for Cardano Backend Interface
76
- * Implements the CardanoBackend interface using Ogmios WebSocket client for local node interaction
77
- */
78
74
  class OgmiosBackend {
79
75
  name = 'ogmios';
80
76
  /**
@@ -170,7 +166,7 @@ class OgmiosBackend {
170
166
  // Keep this SHORT: the orchestrator retries init a few times within the
171
167
  // integration suite's 20s cds.test() hook, so each attempt must be brief.
172
168
  // Still bounds a genuinely hung connect in production.
173
- const ms = Math.min(this.timeoutMs, 4000);
169
+ const ms = Math.max(1, Math.min(this.timeoutMs, 4000));
174
170
  let timer;
175
171
  const timeout = new Promise((_, reject) => {
176
172
  timer = setTimeout(() => reject(new Error(`Ogmios init timeout after ${ms}ms (${label})`)), ms);
@@ -178,6 +174,26 @@ class OgmiosBackend {
178
174
  });
179
175
  return Promise.race([p, timeout]).finally(() => clearTimeout(timer));
180
176
  }
177
+ /**
178
+ * Force-release an Ogmios interaction socket after a failed/expired open or
179
+ * close step. The runtime uses `ws` (and therefore supports `terminate`), but
180
+ * the close fallback keeps the helper compatible with the public structural
181
+ * InteractionContext type and lightweight test doubles.
182
+ */
183
+ forceCloseContext(context) {
184
+ const socket = context.socket;
185
+ try {
186
+ if (typeof socket.terminate === 'function') {
187
+ socket.terminate();
188
+ }
189
+ else if (typeof socket.close === 'function' && socket.readyState !== (socket.CLOSED ?? 3)) {
190
+ socket.close();
191
+ }
192
+ }
193
+ catch {
194
+ // Best effort only: the socket may already have completed its close event.
195
+ }
196
+ }
181
197
  /**
182
198
  * Initialize the Ogmios backend connection
183
199
  */
@@ -675,6 +691,239 @@ class OgmiosBackend {
675
691
  }
676
692
  return amounts;
677
693
  }
694
+ // ---------------------------------------------------------------------------
695
+ // ChainSyncBackend — streamed forward sync for the chain crawler (v2.0)
696
+ // ---------------------------------------------------------------------------
697
+ /**
698
+ * Open a dedicated chain-synchronization stream. Uses its own InteractionContext
699
+ * (a separate WebSocket) from the query/submission clients, because it is a
700
+ * long-lived stream. `sequential: true` + `inFlight: 1` deliver blocks one at a
701
+ * time in order, which the crawler needs for reorg detection and serial persist.
702
+ *
703
+ * KNOWN LIMITATIONS (documented, to harden against a live node — see CRAWLER_DESIGN.md):
704
+ * - Input address/amount are left empty: Ogmios chain-sync inputs are bare
705
+ * references ({txId,index}); the indexer resolves them from already-indexed
706
+ * outputs (indexBlockFull, C3).
707
+ * - Per-tx `size` and `deposit` are not surfaced by chain-sync (set 0).
708
+ * - Output `referenceScriptHash` is not derived from the inline script yet.
709
+ */
710
+ async openChainSync(from, callbacks) {
711
+ OgmiosBackend.validateOgmiosUrl(this.ogmiosUrl);
712
+ const url = new URL(this.ogmiosUrl);
713
+ const connection = {
714
+ host: url.hostname,
715
+ port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80),
716
+ tls: url.protocol === 'wss:'
717
+ };
718
+ let intentionalClose = false;
719
+ let terminalErrorReported = false;
720
+ // Context callbacks are synchronous, while the crawler callback is async.
721
+ // Start it without leaving an unhandled rejection and suppress the common
722
+ // error+close double notification for a single broken socket.
723
+ const reportStreamError = async (err) => {
724
+ if (intentionalClose || this.isShutdown || terminalErrorReported)
725
+ return;
726
+ terminalErrorReported = true;
727
+ try {
728
+ await callbacks.onError?.(err);
729
+ }
730
+ catch (callbackError) {
731
+ logger.error('[OgmiosBackend] chain-sync onError callback failed:', callbackError);
732
+ }
733
+ };
734
+ const contextPromise = (0, client_1.createInteractionContext)((err) => {
735
+ logger.error(`[OgmiosBackend] chain-sync context error: ${err.message}`);
736
+ void reportStreamError(err);
737
+ }, (code, reason) => {
738
+ if (intentionalClose || this.isShutdown)
739
+ return;
740
+ const detail = reason?.toString() || 'no reason supplied';
741
+ const err = new errors_1.ProviderUnavailableError(`Ogmios chain-sync socket closed unexpectedly (code ${code}: ${detail})`, this.name);
742
+ logger.warn(`[OgmiosBackend] ${err.message}`);
743
+ void reportStreamError(err);
744
+ }, { connection });
745
+ let context;
746
+ try {
747
+ context = await this.withInitTimeout(contextPromise, 'chainSync/createInteractionContext');
748
+ }
749
+ catch (err) {
750
+ // A timeout rejects our race but cannot cancel the library's health probe /
751
+ // handshake. If it resolves later, close that late socket as well.
752
+ intentionalClose = true;
753
+ void contextPromise.then(lateContext => this.forceCloseContext(lateContext)).catch(() => undefined);
754
+ throw err;
755
+ }
756
+ // Both handlers are fully try/caught: the ogmios client lib awaits them with NO
757
+ // catch of its own, and with sequential+inFlight:1 a throw before nextBlock()
758
+ // stalls the stream forever. On error we deliberately do NOT call nextBlock()
759
+ // (stopping deterministically instead of skipping a block) and surface the error
760
+ // via callbacks.onError so the consumer can record it and close/restart.
761
+ const handlers = {
762
+ rollForward: async ({ block, tip }, nextBlock) => {
763
+ try {
764
+ const b = block;
765
+ // Byron epoch-boundary (ebb) / bft blocks carry no indexable Praos txs — skip.
766
+ if (b.type !== 'praos') {
767
+ nextBlock();
768
+ return;
769
+ }
770
+ const mapped = this.mapOgmiosBlock(b);
771
+ const t = tip;
772
+ const tipPoint = t && t !== 'origin' && t.slot != null && t.id
773
+ ? { slot: t.slot, hash: t.id, height: t.height }
774
+ : undefined;
775
+ await callbacks.rollForward(mapped.block, mapped.txs, tipPoint);
776
+ nextBlock();
777
+ }
778
+ catch (err) {
779
+ logger.error('[OgmiosBackend] chain-sync rollForward failed — stream halted:', err);
780
+ await reportStreamError(err);
781
+ }
782
+ },
783
+ rollBackward: async ({ point }, nextBlock) => {
784
+ try {
785
+ const p = point;
786
+ await callbacks.rollBackward(p === 'origin' ? 'origin' : { slot: p.slot, hash: p.id });
787
+ nextBlock();
788
+ }
789
+ catch (err) {
790
+ logger.error('[OgmiosBackend] chain-sync rollBackward failed — stream halted:', err);
791
+ await reportStreamError(err);
792
+ }
793
+ },
794
+ };
795
+ let client;
796
+ try {
797
+ client = await this.withInitTimeout((0, client_1.createChainSynchronizationClient)(context, handlers, { sequential: true }), 'chainSync/createClient');
798
+ // Ogmios intersects at the FIRST of these still on its chain, so ancestors
799
+ // turn a fork we slept through into a rollBackward instead of a hard failure.
800
+ const points = from === 'origin' ? ['origin'] : from.map((p) => ({ slot: p.slot, id: p.hash }));
801
+ await this.withInitTimeout(client.resume(points, 1), 'chainSync/resume');
802
+ }
803
+ catch (err) {
804
+ intentionalClose = true;
805
+ if (client) {
806
+ try {
807
+ await this.withInitTimeout(client.shutdown(), 'chainSync/failedOpenShutdown');
808
+ }
809
+ catch {
810
+ // forceCloseContext below is the final cleanup path
811
+ }
812
+ }
813
+ this.forceCloseContext(context);
814
+ throw err;
815
+ }
816
+ let closePromise = null;
817
+ return {
818
+ close: () => {
819
+ // Idempotency matters when an operator stop races an onError-triggered halt.
820
+ if (!closePromise) {
821
+ intentionalClose = true;
822
+ closePromise = (async () => {
823
+ try {
824
+ await this.withInitTimeout(client.shutdown(), 'chainSync/shutdown');
825
+ }
826
+ finally {
827
+ // Also handles a shutdown timeout or an already-closed socket.
828
+ this.forceCloseContext(context);
829
+ }
830
+ })();
831
+ }
832
+ return closePromise;
833
+ }
834
+ };
835
+ }
836
+ /**
837
+ * Map an Ogmios Praos block into our BlockData + its transactions. Block-level
838
+ * fees are the sum of per-tx fees; epoch/epochSlot are derived from the slot via
839
+ * the network's Shelley anchor (same config the tx-builder uses).
840
+ */
841
+ mapOgmiosBlock(block) {
842
+ const txs = (block.transactions ?? []).map((t, i) => this.mapOgmiosTx(t, block, i));
843
+ const totalFees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n);
844
+ const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[this.network];
845
+ const epoch = cfg.shelleyStartEpoch + Math.floor((block.slot - cfg.shelleyStartSlot) / cfg.slotsPerEpoch);
846
+ // reuse the Shelley-anchored helper (carries the preview/preprod/Byron-offset fix)
847
+ // instead of a second inline modulo formula
848
+ const epochSlot = block.slot - epochStartSlot(this.network, epoch);
849
+ const blockData = {
850
+ time: slotToPosixSeconds(this.network, block.slot),
851
+ height: block.height,
852
+ hash: block.id,
853
+ slot: block.slot,
854
+ slotLeader: block.issuer?.verificationKey ?? '',
855
+ epoch,
856
+ epochSlot,
857
+ size: block.size?.bytes ?? 0,
858
+ txCount: txs.length,
859
+ fees: totalFees.toString(),
860
+ };
861
+ return { block: blockData, txs };
862
+ }
863
+ /**
864
+ * Map a single Ogmios chain-sync transaction into our Transaction. Outputs, fee
865
+ * and metadata are mapped fully; inputs are kept as bare references (address/amount
866
+ * resolved downstream by the indexer). `spends` selects the ledger-applied
867
+ * partition: a phase-2-invalid transaction consumes collaterals and creates only
868
+ * its collateral-return output, never its declared regular inputs/outputs.
869
+ */
870
+ mapOgmiosTx(tx, block, index) {
871
+ const mapInput = (input, flags = {}) => ({
872
+ address: '',
873
+ amount: [],
874
+ txHash: input.transaction.id,
875
+ outputIndex: input.index,
876
+ ...flags,
877
+ });
878
+ const spendsCollaterals = tx.spends === 'collaterals';
879
+ const inputs = [
880
+ ...(spendsCollaterals ? [] : (tx.inputs ?? []).map(input => mapInput(input))),
881
+ ...(tx.collaterals ?? []).map(input => mapInput(input, { isCollateral: true })),
882
+ ...(tx.references ?? []).map(input => mapInput(input, { isReference: true })),
883
+ ];
884
+ const mapOutput = (output, outputIndex, isCollateral) => ({
885
+ address: output.address,
886
+ amount: this.convertOgmiosValue(output.value),
887
+ txHash: tx.id,
888
+ outputIndex,
889
+ dataHash: output.datumHash ?? null,
890
+ inlineDatum: output.datum ?? null,
891
+ isCollateral,
892
+ referenceScriptHash: null,
893
+ });
894
+ const outputs = spendsCollaterals
895
+ ? (tx.collateralReturn
896
+ // The ledger assigns collateral return the index immediately after the
897
+ // declared regular outputs, even though those outputs are not produced.
898
+ ? [mapOutput(tx.collateralReturn, tx.outputs?.length ?? 0, true)]
899
+ : [])
900
+ : (tx.outputs ?? []).map((output, outputIndex) => mapOutput(output, outputIndex, false));
901
+ const metadataEntries = tx.metadata?.labels
902
+ ? Object.entries(tx.metadata.labels).map(([label, v]) => ({
903
+ txHash: tx.id,
904
+ label,
905
+ json: v.json,
906
+ }))
907
+ : [];
908
+ return {
909
+ hash: tx.id,
910
+ blockHash: block.id,
911
+ blockHeight: block.height,
912
+ slot: block.slot,
913
+ index,
914
+ fee: (tx.fee?.ada?.lovelace ?? 0).toString(),
915
+ deposit: '0',
916
+ // null = unknown (chain-sync doesn't surface the serialized size) — matches the
917
+ // lazy path's `size ?? null` convention; 0 would masquerade as a real size
918
+ size: null,
919
+ blockTime: slotToPosixSeconds(this.network, block.slot),
920
+ inputs,
921
+ outputs,
922
+ // undefined (not []) when absent — matches the Blockfrost path so
923
+ // mapTransaction's hasMetadata flag stays false for metadata-less txs
924
+ metadata: metadataEntries.length ? metadataEntries : undefined,
925
+ };
926
+ }
678
927
  }
679
928
  exports.OgmiosBackend = OgmiosBackend;
680
929
  //# sourceMappingURL=ogmios-backend.js.map
@@ -1,3 +1,4 @@
1
+ import { ChainSyncBackend, PaginatingBackend } from './backends/cardano-backend';
1
2
  import { type CircuitBreakerConfig } from './circuit-breaker';
2
3
  import { Transaction, Address, UTxO, NetworkInformation, BlockData, EpochData, MetadataLabelTx, PoolData, DrepData, AccountData, AssetInfo, AssetHistoryEntry, LedgerProtocolParameters, ScriptEvaluationResult } from '../utils/types';
3
4
  export type Network = 'mainnet' | 'preview' | 'preprod';
@@ -236,6 +237,24 @@ export declare class CardanoClient {
236
237
  * dead branch.
237
238
  */
238
239
  private getOrderedBackends;
240
+ /**
241
+ * Get a backend that supports streamed chain-synchronization (Ogmios), or null.
242
+ * The crawler's primary, reorg-aware source. Checks the live backend first.
243
+ * Backends whose init() failed are skipped — the crawler uses these instances
244
+ * DIRECTLY (outside executeWithPriority's lazy-retry/breaker), so handing out an
245
+ * uninitialized backend would wedge it.
246
+ */
247
+ getChainSyncBackend(): ChainSyncBackend | null;
248
+ /**
249
+ * Get a backend that can be walked forward by pagination (Blockfrost/Koios), or null.
250
+ * The crawler's fallback source when no Ogmios chain-sync is available.
251
+ * Skips backends whose init() failed (see getChainSyncBackend).
252
+ *
253
+ * Koios is preferred over Blockfrost for bulk block-crawling: Koios batches 100 txs
254
+ * per POST /tx_info, while Blockfrost has no batch endpoint (~3 HTTP calls per tx) —
255
+ * roughly a 40x difference in request volume per crawled block.
256
+ */
257
+ getPaginatingBackend(): PaginatingBackend | null;
239
258
  /**
240
259
  * Get protocol parameters with caching (5 minute TTL)
241
260
  * Protocol parameters rarely change (once per epoch at most), so caching improves performance
@@ -534,6 +534,42 @@ class CardanoClient {
534
534
  backends.push(this.liveBackend);
535
535
  return backends;
536
536
  }
537
+ /**
538
+ * Get a backend that supports streamed chain-synchronization (Ogmios), or null.
539
+ * The crawler's primary, reorg-aware source. Checks the live backend first.
540
+ * Backends whose init() failed are skipped — the crawler uses these instances
541
+ * DIRECTLY (outside executeWithPriority's lazy-retry/breaker), so handing out an
542
+ * uninitialized backend would wedge it.
543
+ */
544
+ getChainSyncBackend() {
545
+ const candidates = [this.liveBackend, ...this.historicalBackends];
546
+ for (const b of candidates) {
547
+ if (b && !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isChainSyncBackend)(b))
548
+ return b;
549
+ }
550
+ return null;
551
+ }
552
+ /**
553
+ * Get a backend that can be walked forward by pagination (Blockfrost/Koios), or null.
554
+ * The crawler's fallback source when no Ogmios chain-sync is available.
555
+ * Skips backends whose init() failed (see getChainSyncBackend).
556
+ *
557
+ * Koios is preferred over Blockfrost for bulk block-crawling: Koios batches 100 txs
558
+ * per POST /tx_info, while Blockfrost has no batch endpoint (~3 HTTP calls per tx) —
559
+ * roughly a 40x difference in request volume per crawled block.
560
+ */
561
+ getPaginatingBackend() {
562
+ const usable = this.historicalBackends.filter((b) => !this.uninitializedBackends.has(b) && (0, cardano_backend_1.isPaginatingBackend)(b));
563
+ const koios = usable.find((b) => b.name === 'koios');
564
+ if (koios)
565
+ return koios;
566
+ if (usable.length)
567
+ return usable[0];
568
+ if (this.liveBackend && !this.uninitializedBackends.has(this.liveBackend) && (0, cardano_backend_1.isPaginatingBackend)(this.liveBackend)) {
569
+ return this.liveBackend;
570
+ }
571
+ return null;
572
+ }
537
573
  /**
538
574
  * Get protocol parameters with caching (5 minute TTL)
539
575
  * Protocol parameters rarely change (once per epoch at most), so caching improves performance
@@ -3,7 +3,7 @@ import type { CardanoClient } from './cardano-client';
3
3
  import type { CardanoTransactionBuilder } from './cardano-tx-builder';
4
4
  import { Transaction as CardanoTransaction, AddressUTxOs, TransactionMetadata, NetworkInformation, Block, Epoch, AssetHistory, Account, Drep, Pool, Asset, Address, LedgerProtocolParameter, AddressTransactions } from '#cds-models/CardanoODataService';
5
5
  import { TransactionBuild, TransactionSubmission } from '#cds-models/CardanoTransactionService';
6
- import { TxBuildRequest, Transaction as ProviderTransaction } from '../utils/types';
6
+ import { TxBuildRequest, Transaction as ProviderTransaction, BlockData } from '../utils/types';
7
7
  import type { TxCacheTargets } from '../utils/tx-build-helper';
8
8
  /**
9
9
  * CardanoIndexer - Indexer for Cardano blockchain data into OData entities
@@ -22,6 +22,28 @@ export declare class CardanoIndexer {
22
22
  private client;
23
23
  private txBuilder;
24
24
  private lastParamsFetchTime;
25
+ private static readonly CRAWL_EPOCH_REFRESH_MS;
26
+ private static readonly CRAWL_EPOCH_RETRY_MS;
27
+ /**
28
+ * Crawler epoch memo. Network reads are refreshed periodically while an epoch is
29
+ * live and once more when the next epoch starts, so counters such as block_count,
30
+ * fees and lastBlockTime do not remain frozen at their first observed value.
31
+ *
32
+ * At most the current and immediately previous epoch are retained. The rows are
33
+ * intentionally UPSERTed in every block transaction: the caller owns that
34
+ * transaction, so an in-memory "persisted" bit cannot know whether its commit later
35
+ * succeeded. Repeating one local UPSERT is cheap and remains correct after rollback.
36
+ */
37
+ private crawlEpochCache;
38
+ private crawlEpochCurrent;
39
+ private crawlEpochPrevious;
40
+ /**
41
+ * Network-only epoch prefetch for the crawler. Call BEFORE opening the per-block
42
+ * write transaction — the backend round-trip must never run while the DB write
43
+ * lock is held (indexBlockFull then serves the epoch from this memo). Never throws.
44
+ */
45
+ prefetchCrawlEpoch(epochNumber: number): Promise<void>;
46
+ private refreshCrawlEpoch;
25
47
  /**
26
48
  * Create a new CardanoIndexer instance
27
49
  * @param client - The CardanoClient instance for blockchain queries
@@ -138,6 +160,33 @@ export declare class CardanoIndexer {
138
160
  * @returns {Promise<Block>} block entity data
139
161
  */
140
162
  indexBlock(tx: CapTransaction, blockHash: string): Promise<Block>;
163
+ /**
164
+ * Bulk-index a whole block and all of its transactions in ONE pass (chain crawler,
165
+ * v2.0). Unlike indexTransaction()/indexBlock() this does NOT re-fetch per hash — the
166
+ * crawler already carries the block + full tx list from the stream/page. Rows are
167
+ * accumulated across the block's txs and UPSERTed once per table (few statements).
168
+ *
169
+ * All writes run inside the caller's CAP transaction (`tx`), so a block is persisted
170
+ * atomically — a failure mid-block rolls the whole block back, keeping the cursor and
171
+ * the data consistent.
172
+ *
173
+ * Inputs from the Ogmios chain-sync path arrive as bare references (no address/amount);
174
+ * resolveInputs() backfills them from this block's own outputs and previously-indexed
175
+ * outputs before mapping. Blockfrost/Koios inputs already carry address/amount and are
176
+ * left untouched.
177
+ *
178
+ * @param tx CAP transaction (one per block, committed by the crawler)
179
+ * @param blockData block header/summary from the crawler source
180
+ * @param txs the block's full transaction list (in block order)
181
+ */
182
+ indexBlockFull(tx: CapTransaction, blockData: BlockData, txs: ProviderTransaction[]): Promise<void>;
183
+ /**
184
+ * Backfill input address/amount for chain-sync transactions whose inputs are bare
185
+ * references. Resolves first from this block's own outputs (a tx may spend an earlier
186
+ * tx's output in the same block), then batch-reads previously-indexed outputs from the
187
+ * DB. Inputs that already carry an address (Blockfrost/Koios) are skipped.
188
+ */
189
+ private resolveInputs;
141
190
  /**
142
191
  * Index & return the epoch information data
143
192
  * @param tx CAP transaction object
@@ -9,6 +9,7 @@ const CardanoODataService_1 = require("#cds-models/CardanoODataService");
9
9
  const CardanoTransactionService_1 = require("#cds-models/CardanoTransactionService");
10
10
  const CardanoSignService_1 = require("#cds-models/CardanoSignService");
11
11
  const mappers_1 = require("../utils/mappers");
12
+ const collections_1 = require("../utils/collections");
12
13
  const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
13
14
  const logger = cds_1.default.log('CardanoIndexer');
14
15
  /**
@@ -28,6 +29,76 @@ class CardanoIndexer {
28
29
  client;
29
30
  txBuilder;
30
31
  lastParamsFetchTime = 0;
32
+ static CRAWL_EPOCH_REFRESH_MS = 5 * 60 * 1000;
33
+ static CRAWL_EPOCH_RETRY_MS = 30 * 1000;
34
+ /**
35
+ * Crawler epoch memo. Network reads are refreshed periodically while an epoch is
36
+ * live and once more when the next epoch starts, so counters such as block_count,
37
+ * fees and lastBlockTime do not remain frozen at their first observed value.
38
+ *
39
+ * At most the current and immediately previous epoch are retained. The rows are
40
+ * intentionally UPSERTed in every block transaction: the caller owns that
41
+ * transaction, so an in-memory "persisted" bit cannot know whether its commit later
42
+ * succeeded. Repeating one local UPSERT is cheap and remains correct after rollback.
43
+ */
44
+ crawlEpochCache = new Map();
45
+ crawlEpochCurrent = null;
46
+ crawlEpochPrevious = null;
47
+ /**
48
+ * Network-only epoch prefetch for the crawler. Call BEFORE opening the per-block
49
+ * write transaction — the backend round-trip must never run while the DB write
50
+ * lock is held (indexBlockFull then serves the epoch from this memo). Never throws.
51
+ */
52
+ async prefetchCrawlEpoch(epochNumber) {
53
+ const previousEpoch = this.crawlEpochCurrent;
54
+ const enteringNewEpoch = previousEpoch !== null && previousEpoch !== epochNumber;
55
+ // At an epoch boundary, refresh the completed epoch one last time. A failed
56
+ // final refresh is retried with a short backoff on subsequent blocks.
57
+ if (enteringNewEpoch && previousEpoch !== null) {
58
+ await this.refreshCrawlEpoch(previousEpoch, true, true);
59
+ this.crawlEpochPrevious = previousEpoch;
60
+ }
61
+ else {
62
+ for (const [cachedEpoch, entry] of this.crawlEpochCache) {
63
+ if (cachedEpoch !== epochNumber && !entry.finalized) {
64
+ await this.refreshCrawlEpoch(cachedEpoch, false, true);
65
+ }
66
+ }
67
+ }
68
+ await this.refreshCrawlEpoch(epochNumber, false, false);
69
+ this.crawlEpochCurrent = epochNumber;
70
+ // Keep only the live epoch and its predecessor/final snapshot.
71
+ for (const cachedEpoch of this.crawlEpochCache.keys()) {
72
+ if (cachedEpoch !== epochNumber && cachedEpoch !== this.crawlEpochPrevious) {
73
+ this.crawlEpochCache.delete(cachedEpoch);
74
+ }
75
+ }
76
+ }
77
+ async refreshCrawlEpoch(epochNumber, force, finalized) {
78
+ const now = Date.now();
79
+ const existing = this.crawlEpochCache.get(epochNumber);
80
+ if (existing?.finalized && finalized)
81
+ return;
82
+ if (!force && existing && now < existing.nextRefreshAt)
83
+ return;
84
+ try {
85
+ const row = (0, mappers_1.mapEpoch)(await this.client.getEpoch(epochNumber));
86
+ this.crawlEpochCache.set(epochNumber, {
87
+ row,
88
+ nextRefreshAt: now + CardanoIndexer.CRAWL_EPOCH_REFRESH_MS,
89
+ finalized,
90
+ });
91
+ }
92
+ catch {
93
+ // Keep the last good snapshot, but retry transient/negative results soon rather
94
+ // than suppressing enrichment for the rest of the five-day epoch.
95
+ this.crawlEpochCache.set(epochNumber, {
96
+ row: existing?.row,
97
+ nextRefreshAt: now + CardanoIndexer.CRAWL_EPOCH_RETRY_MS,
98
+ finalized: false,
99
+ });
100
+ }
101
+ }
31
102
  /**
32
103
  * Create a new CardanoIndexer instance
33
104
  * @param client - The CardanoClient instance for blockchain queries
@@ -389,6 +460,126 @@ class CardanoIndexer {
389
460
  await tx.run(UPSERT.into(CardanoODataService_1.Block).entries(blockEntity));
390
461
  return blockEntity;
391
462
  }
463
+ /**
464
+ * Bulk-index a whole block and all of its transactions in ONE pass (chain crawler,
465
+ * v2.0). Unlike indexTransaction()/indexBlock() this does NOT re-fetch per hash — the
466
+ * crawler already carries the block + full tx list from the stream/page. Rows are
467
+ * accumulated across the block's txs and UPSERTed once per table (few statements).
468
+ *
469
+ * All writes run inside the caller's CAP transaction (`tx`), so a block is persisted
470
+ * atomically — a failure mid-block rolls the whole block back, keeping the cursor and
471
+ * the data consistent.
472
+ *
473
+ * Inputs from the Ogmios chain-sync path arrive as bare references (no address/amount);
474
+ * resolveInputs() backfills them from this block's own outputs and previously-indexed
475
+ * outputs before mapping. Blockfrost/Koios inputs already carry address/amount and are
476
+ * left untouched.
477
+ *
478
+ * @param tx CAP transaction (one per block, committed by the crawler)
479
+ * @param blockData block header/summary from the crawler source
480
+ * @param txs the block's full transaction list (in block order)
481
+ */
482
+ async indexBlockFull(tx, blockData, txs) {
483
+ // Block row — best-effort epoch enrichment from the prefetched memo. The network
484
+ // fetch happens in prefetchCrawlEpoch() BEFORE the caller opened this write tx;
485
+ // if the caller skipped it, resolve now (memoized) and accept the in-tx fetch.
486
+ let epoch;
487
+ if (blockData.epoch != null) {
488
+ await this.prefetchCrawlEpoch(blockData.epoch);
489
+ epoch = this.crawlEpochCache.get(blockData.epoch)?.row;
490
+ const epochRows = [...this.crawlEpochCache.values()]
491
+ .map((entry) => entry.row)
492
+ .filter((row) => row !== undefined);
493
+ if (epochRows.length)
494
+ await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries(epochRows));
495
+ }
496
+ await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
497
+ // Backfill chain-sync inputs (empty address/amount) from local outputs
498
+ await this.resolveInputs(tx, txs);
499
+ // Accumulate rows across the whole block, then one bulk UPSERT per table
500
+ const txRows = txs.map(t => (0, mappers_1.mapTransaction)(t));
501
+ const inputRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputs)(t.hash, t.inputs ?? []));
502
+ const inputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputAssets)(t.hash, t.inputs ?? []));
503
+ const outputRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputs)(t.hash, t.outputs ?? []));
504
+ const outputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputAssets)(t.hash, t.outputs ?? []));
505
+ const metadataRows = txs.flatMap(t => (0, mappers_1.mapTransactionMetadata)(t.metadata ?? []));
506
+ if (txRows.length)
507
+ await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRows));
508
+ if (inputRows.length)
509
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputs).entries(inputRows));
510
+ if (inputAssetRows.length)
511
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputAssets).entries(inputAssetRows));
512
+ if (outputRows.length)
513
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputs).entries(outputRows));
514
+ if (outputAssetRows.length)
515
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
516
+ if (metadataRows.length)
517
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
518
+ logger.debug(`indexBlockFull: block ${blockData.hash} — ${txs.length} txs, ${outputRows.length} outputs`);
519
+ }
520
+ /**
521
+ * Backfill input address/amount for chain-sync transactions whose inputs are bare
522
+ * references. Resolves first from this block's own outputs (a tx may spend an earlier
523
+ * tx's output in the same block), then batch-reads previously-indexed outputs from the
524
+ * DB. Inputs that already carry an address (Blockfrost/Koios) are skipped.
525
+ */
526
+ async resolveInputs(tx, txs) {
527
+ // 1. In-memory index of this block's outputs (txHash#outputIndex -> {address, amount})
528
+ const blockOutputs = new Map();
529
+ for (const t of txs) {
530
+ for (const o of t.outputs ?? []) {
531
+ blockOutputs.set(`${t.hash}#${o.outputIndex}`, { address: o.address, amount: o.amount ?? [] });
532
+ }
533
+ }
534
+ // 2. Collect inputs still needing resolution after the same-block pass
535
+ const unresolved = [];
536
+ for (const t of txs) {
537
+ for (const input of t.inputs ?? []) {
538
+ if (input.address)
539
+ continue; // already resolved by the backend (Blockfrost/Koios)
540
+ const key = `${input.txHash}#${input.outputIndex}`;
541
+ const local = blockOutputs.get(key);
542
+ if (local) {
543
+ input.address = local.address;
544
+ input.amount = local.amount;
545
+ }
546
+ else {
547
+ unresolved.push({ input, key });
548
+ }
549
+ }
550
+ }
551
+ if (!unresolved.length)
552
+ return;
553
+ // 3. Batch-read prior-block outputs from the DB — chunked so a dense block's
554
+ // input set can never exceed a driver's bind-variable cap (same IN_CHUNK
555
+ // discipline as the crawler's reorg deletes)
556
+ const sourceHashes = [...new Set(unresolved.map(u => u.input.txHash))];
557
+ const addrByKey = new Map();
558
+ const amtByKey = new Map();
559
+ for (const hashChunk of (0, collections_1.chunk)(sourceHashes, collections_1.IN_CHUNK)) {
560
+ const [outRows, assetRows] = await Promise.all([
561
+ tx.run(SELECT.from(CardanoODataService_1.TransactionOutputs).where({ tx_hash: { in: hashChunk } })),
562
+ tx.run(SELECT.from(CardanoODataService_1.TransactionOutputAssets).where({ output_tx_hash: { in: hashChunk } })),
563
+ ]);
564
+ for (const r of outRows) {
565
+ addrByKey.set(`${r.tx_hash}#${r.outputIndex}`, r.address_address);
566
+ }
567
+ for (const r of assetRows) {
568
+ const k = `${r.output_tx_hash}#${r.output_outputIndex}`;
569
+ const list = amtByKey.get(k) ?? [];
570
+ list.push({ unit: r.unit, quantity: String(r.asset_quantity) });
571
+ amtByKey.set(k, list);
572
+ }
573
+ }
574
+ for (const { input, key } of unresolved) {
575
+ const addr = addrByKey.get(key);
576
+ if (addr != null)
577
+ input.address = addr;
578
+ const amt = amtByKey.get(key);
579
+ if (amt)
580
+ input.amount = amt;
581
+ }
582
+ }
392
583
  /**
393
584
  * Index & return the epoch information data
394
585
  * @param tx CAP transaction object