@odatano/core 1.11.0 → 2.0.0-rc.10

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 (133) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +255 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +177 -0
  4. package/@cds-models/CardanoIndexerService/index.js +27 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +693 -2172
  6. package/@cds-models/CardanoODataService/index.js +88 -390
  7. package/@cds-models/CardanoSignService/index.d.ts +448 -1576
  8. package/@cds-models/CardanoSignService/index.js +62 -293
  9. package/@cds-models/CardanoTransactionService/index.d.ts +437 -1494
  10. package/@cds-models/CardanoTransactionService/index.js +60 -271
  11. package/@cds-models/CardanoWorkerService/index.d.ts +224 -0
  12. package/@cds-models/CardanoWorkerService/index.js +32 -0
  13. package/@cds-models/_/index.d.ts +70 -40
  14. package/@cds-models/_/index.js +17 -32
  15. package/@cds-models/cds/outbox/index.d.ts +28 -0
  16. package/@cds-models/index.d.ts +225 -522
  17. package/@cds-models/index.js +35 -218
  18. package/@cds-models/odatano/cardano/index.d.ts +919 -2884
  19. package/@cds-models/odatano/cardano/index.js +115 -536
  20. package/@cds-models/sap/common/index.d.ts +196 -600
  21. package/@cds-models/sap/common/index.js +28 -269
  22. package/README.md +194 -102
  23. package/db/schema.cds +388 -1
  24. package/db/types.cds +48 -0
  25. package/package.json +48 -33
  26. package/src/index.d.ts +7 -1
  27. package/src/index.js +30 -2
  28. package/src/plugin.js +33 -20
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +21 -2
  30. package/srv/blockchain/backends/blockfrost-backend.js +69 -25
  31. package/srv/blockchain/backends/cardano-backend.d.ts +69 -0
  32. package/srv/blockchain/backends/cardano-backend.js +13 -0
  33. package/srv/blockchain/backends/koios-backend.d.ts +26 -2
  34. package/srv/blockchain/backends/koios-backend.js +148 -25
  35. package/srv/blockchain/backends/ogmios-backend.d.ts +60 -9
  36. package/srv/blockchain/backends/ogmios-backend.js +326 -10
  37. package/srv/blockchain/cardano-client.d.ts +19 -0
  38. package/srv/blockchain/cardano-client.js +36 -0
  39. package/srv/blockchain/cardano-indexer.d.ts +50 -1
  40. package/srv/blockchain/cardano-indexer.js +193 -0
  41. package/srv/blockchain/crawler/crawler.d.ts +176 -0
  42. package/srv/blockchain/crawler/crawler.js +744 -0
  43. package/srv/blockchain/crawler/hooks.d.ts +43 -0
  44. package/srv/blockchain/crawler/hooks.js +62 -0
  45. package/srv/blockchain/crawler/index.d.ts +35 -0
  46. package/srv/blockchain/crawler/index.js +168 -0
  47. package/srv/blockchain/crawler/sync-state.d.ts +106 -0
  48. package/srv/blockchain/crawler/sync-state.js +287 -0
  49. package/srv/blockchain/signing/hsm-signer.d.ts +45 -0
  50. package/srv/blockchain/signing/hsm-signer.js +8 -1
  51. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +20 -0
  52. package/srv/blockchain/transaction-building/buildooor-tx.js +104 -20
  53. package/srv/blockchain/wallet-worker/build-request.d.ts +26 -0
  54. package/srv/blockchain/wallet-worker/build-request.js +370 -0
  55. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +117 -0
  56. package/srv/blockchain/wallet-worker/confirmation-tracker.js +290 -0
  57. package/srv/blockchain/wallet-worker/index.d.ts +14 -0
  58. package/srv/blockchain/wallet-worker/index.js +80 -0
  59. package/srv/blockchain/wallet-worker/job-store.d.ts +272 -0
  60. package/srv/blockchain/wallet-worker/job-store.js +597 -0
  61. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +43 -0
  62. package/srv/blockchain/wallet-worker/lease-heartbeat.js +99 -0
  63. package/srv/blockchain/wallet-worker/signers.d.ts +57 -0
  64. package/srv/blockchain/wallet-worker/signers.js +131 -0
  65. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +145 -0
  66. package/srv/blockchain/wallet-worker/wallet-worker.js +542 -0
  67. package/srv/cardano-agent-service.cds +150 -0
  68. package/srv/cardano-agent-service.d.ts +2 -0
  69. package/srv/cardano-agent-service.js +16 -0
  70. package/srv/cardano-indexer-service.cds +106 -0
  71. package/srv/cardano-indexer-service.d.ts +2 -0
  72. package/srv/cardano-indexer-service.js +79 -0
  73. package/srv/cardano-service.js +79 -4
  74. package/srv/cardano-sign-service.cds +200 -180
  75. package/srv/cardano-tx-service.cds +32 -26
  76. package/srv/cardano-tx-service.d.ts +1 -11
  77. package/srv/cardano-tx-service.js +107 -200
  78. package/srv/cardano-worker-service.cds +125 -0
  79. package/srv/cardano-worker-service.d.ts +2 -0
  80. package/srv/cardano-worker-service.js +199 -0
  81. package/srv/server.d.ts +34 -2
  82. package/srv/server.js +246 -36
  83. package/srv/utils/agent-grants-config.d.ts +65 -0
  84. package/srv/utils/agent-grants-config.js +148 -0
  85. package/srv/utils/agent-grants.d.ts +314 -0
  86. package/srv/utils/agent-grants.js +821 -0
  87. package/srv/utils/agent-token-auth.d.ts +19 -0
  88. package/srv/utils/agent-token-auth.js +81 -0
  89. package/srv/utils/collections.d.ts +13 -0
  90. package/srv/utils/collections.js +24 -0
  91. package/srv/utils/crypto.d.ts +16 -0
  92. package/srv/utils/crypto.js +75 -0
  93. package/srv/utils/db-sanitize.d.ts +40 -0
  94. package/srv/utils/db-sanitize.js +98 -0
  95. package/srv/utils/error-codes.d.ts +6 -0
  96. package/srv/utils/error-codes.js +6 -0
  97. package/srv/utils/errors.d.ts +12 -0
  98. package/srv/utils/errors.js +45 -0
  99. package/srv/utils/liveness.d.ts +23 -0
  100. package/srv/utils/liveness.js +49 -0
  101. package/srv/utils/mappers.d.ts +27 -0
  102. package/srv/utils/mappers.js +80 -10
  103. package/srv/utils/rate-limiter.d.ts +57 -0
  104. package/srv/utils/rate-limiter.js +126 -0
  105. package/srv/utils/service-events.d.ts +26 -0
  106. package/srv/utils/service-events.js +46 -0
  107. package/srv/utils/tx-request-parsers.d.ts +71 -0
  108. package/srv/utils/tx-request-parsers.js +202 -0
  109. package/srv/utils/tx-utils.d.ts +2 -1
  110. package/srv/utils/tx-utils.js +3 -2
  111. package/srv/utils/types.d.ts +17 -1
  112. package/@cds-models/CardanoODataService/index.d.ts.map +0 -1
  113. package/@cds-models/CardanoODataService/index.js.map +0 -1
  114. package/@cds-models/CardanoODataService/index.ts +0 -776
  115. package/@cds-models/CardanoSignService/index.d.ts.map +0 -1
  116. package/@cds-models/CardanoSignService/index.js.map +0 -1
  117. package/@cds-models/CardanoSignService/index.ts +0 -569
  118. package/@cds-models/CardanoTransactionService/index.d.ts.map +0 -1
  119. package/@cds-models/CardanoTransactionService/index.js.map +0 -1
  120. package/@cds-models/CardanoTransactionService/index.ts +0 -526
  121. package/@cds-models/_/index.d.ts.map +0 -1
  122. package/@cds-models/_/index.js.map +0 -1
  123. package/@cds-models/_/index.ts +0 -96
  124. package/@cds-models/cds/outbox/index.ts +0 -27
  125. package/@cds-models/index.d.ts.map +0 -1
  126. package/@cds-models/index.js.map +0 -1
  127. package/@cds-models/index.ts +0 -245
  128. package/@cds-models/odatano/cardano/index.d.ts.map +0 -1
  129. package/@cds-models/odatano/cardano/index.js.map +0 -1
  130. package/@cds-models/odatano/cardano/index.ts +0 -789
  131. package/@cds-models/sap/common/index.d.ts.map +0 -1
  132. package/@cds-models/sap/common/index.js.map +0 -1
  133. package/@cds-models/sap/common/index.ts +0 -249
@@ -1,6 +1,16 @@
1
1
  import { Transaction, BlockData, Address, UTxO, NetworkInformation, EpochData, MetadataLabelTx, PoolData, AccountData, DrepData, AssetInfo, LedgerProtocolParameters, ScriptEvaluationResult } from '../../utils/types';
2
- import { EvaluatingBackend } from './cardano-backend';
2
+ import { EvaluatingBackend, ChainSyncBackend, ChainSyncCallbacks, ChainSyncHandle, ChainPoint } from './cardano-backend';
3
3
  import { Network } from '../cardano-client';
4
+ /**
5
+ * Decode a CIP-129 DRep ID (`drep1…`, 29 bytes) into its credential hash and
6
+ * type. Header byte: high nibble 0x2 = DRep, low nibble 0x2 = key hash /
7
+ * 0x3 = script hash. The validators already enforce HRP + length before the
8
+ * request reaches a backend, so this only has to split the payload.
9
+ */
10
+ export declare function decodeDrepId(drepId: string): {
11
+ hashHex: string;
12
+ isScript: boolean;
13
+ };
4
14
  /** Resolve Ogmios ledger tip which may be 'origin' (genesis block) or a point */
5
15
  export declare function resolveOgmiosTip(tip: 'origin' | {
6
16
  slot: number;
@@ -11,11 +21,7 @@ export declare function resolveOgmiosTip(tip: 'origin' | {
11
21
  };
12
22
  /** Resolve Ogmios block height which may be 'origin' (genesis block) or a number */
13
23
  export declare function resolveOgmiosHeight(height: 'origin' | number): number;
14
- /**
15
- * Ogmios Backend Implementation for Cardano Backend Interface
16
- * Implements the CardanoBackend interface using Ogmios WebSocket client for local node interaction
17
- */
18
- export declare class OgmiosBackend implements EvaluatingBackend {
24
+ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBackend {
19
25
  readonly name = "ogmios";
20
26
  /**
21
27
  * Capability declaration — the orchestrator skips Ogmios for these without
@@ -68,6 +74,13 @@ export declare class OgmiosBackend implements EvaluatingBackend {
68
74
  * retry picks it up instead of dying.
69
75
  */
70
76
  private withInitTimeout;
77
+ /**
78
+ * Force-release an Ogmios interaction socket after a failed/expired open or
79
+ * close step. The runtime uses `ws` (and therefore supports `terminate`), but
80
+ * the close fallback keeps the helper compatible with the public structural
81
+ * InteractionContext type and lightweight test doubles.
82
+ */
83
+ private forceCloseContext;
71
84
  /**
72
85
  * Initialize the Ogmios backend connection
73
86
  */
@@ -104,11 +117,21 @@ export declare class OgmiosBackend implements EvaluatingBackend {
104
117
  */
105
118
  getTransactionMetadata(_tx_hash: string): Promise<MetadataLabelTx[]>;
106
119
  /**
107
- * Get specific Drep Data (not supported for Ogmios)
108
- * @param _drepId drep id
120
+ * Get DRep data from the live ledger state (`queryLedgerState/delegateRepresentatives`).
121
+ *
122
+ * The client package (6.14) ships the schema types but no wrapper for this query,
123
+ * so it goes through the exported `Method()` primitive on our interaction context —
124
+ * the same building block the client uses for `stakePools` & co.
125
+ *
126
+ * Semantics vs. Blockfrost/Koios: Ogmios only lists REGISTERED DReps, so a retired
127
+ * or unknown DRep is a NotFoundError here (never `retired: true`), and there is no
128
+ * last-activity epoch — `expired` is derived from the mandate epoch instead.
129
+ * Routing keeps `getDrep` historical-preferred; this is the Ogmios-only fallback.
130
+ *
131
+ * @param drepId CIP-129 bech32 DRep ID (`drep1…`)
109
132
  * @returns {Promise<DrepData>} drep data
110
133
  */
111
- getDrep(_drepId: string): Promise<DrepData>;
134
+ getDrep(drepId: string): Promise<DrepData>;
112
135
  /**
113
136
  * Get Asset Info (not supported for Ogmios — no aggregate-supply query in the protocol)
114
137
  * @param _unit asset unit (policyId + assetNameHex)
@@ -212,5 +235,33 @@ export declare class OgmiosBackend implements EvaluatingBackend {
212
235
  * Standard: [{ unit: 'lovelace', quantity: '1000000' }, { unit: 'policyId.assetName', quantity: 'N' }]
213
236
  */
214
237
  private convertOgmiosValue;
238
+ /**
239
+ * Open a dedicated chain-synchronization stream. Uses its own InteractionContext
240
+ * (a separate WebSocket) from the query/submission clients, because it is a
241
+ * long-lived stream. `sequential: true` + `inFlight: 1` deliver blocks one at a
242
+ * time in order, which the crawler needs for reorg detection and serial persist.
243
+ *
244
+ * KNOWN LIMITATIONS (documented, to harden against a live node — see CRAWLER_DESIGN.md):
245
+ * - Input address/amount are left empty: Ogmios chain-sync inputs are bare
246
+ * references ({txId,index}); the indexer resolves them from already-indexed
247
+ * outputs (indexBlockFull, C3).
248
+ * - Per-tx `size` and `deposit` are not surfaced by chain-sync (set 0).
249
+ * - Output `referenceScriptHash` is not derived from the inline script yet.
250
+ */
251
+ openChainSync(from: ChainPoint[] | 'origin', callbacks: ChainSyncCallbacks): Promise<ChainSyncHandle>;
252
+ /**
253
+ * Map an Ogmios Praos block into our BlockData + its transactions. Block-level
254
+ * fees are the sum of per-tx fees; epoch/epochSlot are derived from the slot via
255
+ * the network's Shelley anchor (same config the tx-builder uses).
256
+ */
257
+ private mapOgmiosBlock;
258
+ /**
259
+ * Map a single Ogmios chain-sync transaction into our Transaction. Outputs, fee
260
+ * and metadata are mapped fully; inputs are kept as bare references (address/amount
261
+ * resolved downstream by the indexer). `spends` selects the ledger-applied
262
+ * partition: a phase-2-invalid transaction consumes collaterals and creates only
263
+ * its collateral-return output, never its declared regular inputs/outputs.
264
+ */
265
+ private mapOgmiosTx;
215
266
  }
216
267
  //# sourceMappingURL=ogmios-backend.d.ts.map
@@ -4,11 +4,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.OgmiosBackend = void 0;
7
+ exports.decodeDrepId = decodeDrepId;
7
8
  exports.resolveOgmiosTip = resolveOgmiosTip;
8
9
  exports.resolveOgmiosHeight = resolveOgmiosHeight;
9
10
  const cds_1 = __importDefault(require("@sap/cds"));
10
11
  const node_http_1 = __importDefault(require("node:http"));
11
12
  const client_1 = require("@cardano-ogmios/client");
13
+ const bech32_1 = require("bech32");
12
14
  const backend_request_handler_1 = require("../../utils/backend-request-handler");
13
15
  const errors_1 = require("../../utils/errors");
14
16
  const mappers_1 = require("../../utils/mappers");
@@ -63,6 +65,23 @@ function ogmiosValueToLovelaceString(value) {
63
65
  const lovelace = value.ada?.lovelace;
64
66
  return lovelace === undefined ? '0' : String(lovelace);
65
67
  }
68
+ /**
69
+ * Decode a CIP-129 DRep ID (`drep1…`, 29 bytes) into its credential hash and
70
+ * type. Header byte: high nibble 0x2 = DRep, low nibble 0x2 = key hash /
71
+ * 0x3 = script hash. The validators already enforce HRP + length before the
72
+ * request reaches a backend, so this only has to split the payload.
73
+ */
74
+ function decodeDrepId(drepId) {
75
+ const decoded = bech32_1.bech32.decode(drepId, const_1.BECH32_MAX_LENGTH);
76
+ const bytes = Buffer.from(bech32_1.bech32.fromWords(decoded.words));
77
+ if (decoded.prefix !== 'drep' || bytes.length !== 29) {
78
+ throw new errors_1.NotFoundError('Drep', 'ogmios');
79
+ }
80
+ return {
81
+ hashHex: bytes.subarray(1).toString('hex'),
82
+ isScript: (bytes[0] & 0x0f) === 0x03,
83
+ };
84
+ }
66
85
  /** Resolve Ogmios ledger tip which may be 'origin' (genesis block) or a point */
67
86
  function resolveOgmiosTip(tip) {
68
87
  return tip === 'origin' ? { slot: 0, hash: '' } : { slot: tip.slot, hash: tip.id };
@@ -71,10 +90,6 @@ function resolveOgmiosTip(tip) {
71
90
  function resolveOgmiosHeight(height) {
72
91
  return height === 'origin' ? 0 : height;
73
92
  }
74
- /**
75
- * Ogmios Backend Implementation for Cardano Backend Interface
76
- * Implements the CardanoBackend interface using Ogmios WebSocket client for local node interaction
77
- */
78
93
  class OgmiosBackend {
79
94
  name = 'ogmios';
80
95
  /**
@@ -92,7 +107,8 @@ class OgmiosBackend {
92
107
  'getTransaction',
93
108
  'getTransactionMetadata',
94
109
  'getAddressTransactions',
95
- 'getDrep',
110
+ // getDrep is NOT listed: served from the live ledger state via
111
+ // queryLedgerState/delegateRepresentatives (Ogmios ≥ 6.4).
96
112
  'getAssetInfo',
97
113
  'getAddress',
98
114
  'getNetworkInformation',
@@ -170,7 +186,7 @@ class OgmiosBackend {
170
186
  // Keep this SHORT: the orchestrator retries init a few times within the
171
187
  // integration suite's 20s cds.test() hook, so each attempt must be brief.
172
188
  // Still bounds a genuinely hung connect in production.
173
- const ms = Math.min(this.timeoutMs, 4000);
189
+ const ms = Math.max(1, Math.min(this.timeoutMs, 4000));
174
190
  let timer;
175
191
  const timeout = new Promise((_, reject) => {
176
192
  timer = setTimeout(() => reject(new Error(`Ogmios init timeout after ${ms}ms (${label})`)), ms);
@@ -178,6 +194,26 @@ class OgmiosBackend {
178
194
  });
179
195
  return Promise.race([p, timeout]).finally(() => clearTimeout(timer));
180
196
  }
197
+ /**
198
+ * Force-release an Ogmios interaction socket after a failed/expired open or
199
+ * close step. The runtime uses `ws` (and therefore supports `terminate`), but
200
+ * the close fallback keeps the helper compatible with the public structural
201
+ * InteractionContext type and lightweight test doubles.
202
+ */
203
+ forceCloseContext(context) {
204
+ const socket = context.socket;
205
+ try {
206
+ if (typeof socket.terminate === 'function') {
207
+ socket.terminate();
208
+ }
209
+ else if (typeof socket.close === 'function' && socket.readyState !== (socket.CLOSED ?? 3)) {
210
+ socket.close();
211
+ }
212
+ }
213
+ catch {
214
+ // Best effort only: the socket may already have completed its close event.
215
+ }
216
+ }
181
217
  /**
182
218
  * Initialize the Ogmios backend connection
183
219
  */
@@ -289,13 +325,60 @@ class OgmiosBackend {
289
325
  }, this.name);
290
326
  }
291
327
  /**
292
- * Get specific Drep Data (not supported for Ogmios)
293
- * @param _drepId drep id
328
+ * Get DRep data from the live ledger state (`queryLedgerState/delegateRepresentatives`).
329
+ *
330
+ * The client package (6.14) ships the schema types but no wrapper for this query,
331
+ * so it goes through the exported `Method()` primitive on our interaction context —
332
+ * the same building block the client uses for `stakePools` & co.
333
+ *
334
+ * Semantics vs. Blockfrost/Koios: Ogmios only lists REGISTERED DReps, so a retired
335
+ * or unknown DRep is a NotFoundError here (never `retired: true`), and there is no
336
+ * last-activity epoch — `expired` is derived from the mandate epoch instead.
337
+ * Routing keeps `getDrep` historical-preferred; this is the Ogmios-only fallback.
338
+ *
339
+ * @param drepId CIP-129 bech32 DRep ID (`drep1…`)
294
340
  * @returns {Promise<DrepData>} drep data
295
341
  */
296
- async getDrep(_drepId) {
342
+ async getDrep(drepId) {
297
343
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
298
- throw new errors_1.ProviderUnavailableError('DRep queries not supported by Ogmios backend', this.name);
344
+ await this.ensureConnected();
345
+ if (!this.context) {
346
+ throw new errors_1.ProviderUnavailableError('Ogmios interaction context not available', this.name);
347
+ }
348
+ const { hashHex, isScript } = decodeDrepId(drepId);
349
+ const [summaries, currentEpoch] = await Promise.all([
350
+ (0, client_1.Method)({
351
+ method: 'queryLedgerState/delegateRepresentatives',
352
+ params: isScript ? { scripts: [hashHex] } : { keys: [hashHex] },
353
+ }, {
354
+ handler: (response, resolve, reject) => {
355
+ if (response.error) {
356
+ reject(new Error(response.error.message ?? `Ogmios error ${response.error.code ?? ''}`.trim()));
357
+ }
358
+ else {
359
+ resolve(Array.isArray(response.result) ? response.result : []);
360
+ }
361
+ },
362
+ }, this.context),
363
+ this.stateQueryClient.epoch(),
364
+ ]);
365
+ // Filter by id: the query is already credential-scoped, but never trust a
366
+ // broader answer (abstain/noConfidence rows carry no id and are dropped here).
367
+ const drep = summaries.find((s) => s.type === 'registered' && s.id?.toLowerCase() === hashHex);
368
+ if (!drep)
369
+ throw new errors_1.NotFoundError('Drep', this.name);
370
+ const mandateEpoch = drep.mandate?.epoch;
371
+ return {
372
+ drepId,
373
+ hex: hashHex,
374
+ amount: ogmiosValueToLovelaceString(drep.stake),
375
+ hasScript: isScript || drep.from === 'script',
376
+ // Ogmios reports the mandate (expiry) epoch, not the last activity — keep 0,
377
+ // matching what the Koios mapper does since its schema change.
378
+ lastActiveEpoch: 0,
379
+ expired: typeof mandateEpoch === 'number' && mandateEpoch < Number(currentEpoch),
380
+ retired: false,
381
+ };
299
382
  }, this.name);
300
383
  }
301
384
  /**
@@ -675,6 +758,239 @@ class OgmiosBackend {
675
758
  }
676
759
  return amounts;
677
760
  }
761
+ // ---------------------------------------------------------------------------
762
+ // ChainSyncBackend — streamed forward sync for the chain crawler (v2.0)
763
+ // ---------------------------------------------------------------------------
764
+ /**
765
+ * Open a dedicated chain-synchronization stream. Uses its own InteractionContext
766
+ * (a separate WebSocket) from the query/submission clients, because it is a
767
+ * long-lived stream. `sequential: true` + `inFlight: 1` deliver blocks one at a
768
+ * time in order, which the crawler needs for reorg detection and serial persist.
769
+ *
770
+ * KNOWN LIMITATIONS (documented, to harden against a live node — see CRAWLER_DESIGN.md):
771
+ * - Input address/amount are left empty: Ogmios chain-sync inputs are bare
772
+ * references ({txId,index}); the indexer resolves them from already-indexed
773
+ * outputs (indexBlockFull, C3).
774
+ * - Per-tx `size` and `deposit` are not surfaced by chain-sync (set 0).
775
+ * - Output `referenceScriptHash` is not derived from the inline script yet.
776
+ */
777
+ async openChainSync(from, callbacks) {
778
+ OgmiosBackend.validateOgmiosUrl(this.ogmiosUrl);
779
+ const url = new URL(this.ogmiosUrl);
780
+ const connection = {
781
+ host: url.hostname,
782
+ port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80),
783
+ tls: url.protocol === 'wss:'
784
+ };
785
+ let intentionalClose = false;
786
+ let terminalErrorReported = false;
787
+ // Context callbacks are synchronous, while the crawler callback is async.
788
+ // Start it without leaving an unhandled rejection and suppress the common
789
+ // error+close double notification for a single broken socket.
790
+ const reportStreamError = async (err) => {
791
+ if (intentionalClose || this.isShutdown || terminalErrorReported)
792
+ return;
793
+ terminalErrorReported = true;
794
+ try {
795
+ await callbacks.onError?.(err);
796
+ }
797
+ catch (callbackError) {
798
+ logger.error('[OgmiosBackend] chain-sync onError callback failed:', callbackError);
799
+ }
800
+ };
801
+ const contextPromise = (0, client_1.createInteractionContext)((err) => {
802
+ logger.error(`[OgmiosBackend] chain-sync context error: ${err.message}`);
803
+ void reportStreamError(err);
804
+ }, (code, reason) => {
805
+ if (intentionalClose || this.isShutdown)
806
+ return;
807
+ const detail = reason?.toString() || 'no reason supplied';
808
+ const err = new errors_1.ProviderUnavailableError(`Ogmios chain-sync socket closed unexpectedly (code ${code}: ${detail})`, this.name);
809
+ logger.warn(`[OgmiosBackend] ${err.message}`);
810
+ void reportStreamError(err);
811
+ }, { connection });
812
+ let context;
813
+ try {
814
+ context = await this.withInitTimeout(contextPromise, 'chainSync/createInteractionContext');
815
+ }
816
+ catch (err) {
817
+ // A timeout rejects our race but cannot cancel the library's health probe /
818
+ // handshake. If it resolves later, close that late socket as well.
819
+ intentionalClose = true;
820
+ void contextPromise.then(lateContext => this.forceCloseContext(lateContext)).catch(() => undefined);
821
+ throw err;
822
+ }
823
+ // Both handlers are fully try/caught: the ogmios client lib awaits them with NO
824
+ // catch of its own, and with sequential+inFlight:1 a throw before nextBlock()
825
+ // stalls the stream forever. On error we deliberately do NOT call nextBlock()
826
+ // (stopping deterministically instead of skipping a block) and surface the error
827
+ // via callbacks.onError so the consumer can record it and close/restart.
828
+ const handlers = {
829
+ rollForward: async ({ block, tip }, nextBlock) => {
830
+ try {
831
+ const b = block;
832
+ // Byron epoch-boundary (ebb) / bft blocks carry no indexable Praos txs — skip.
833
+ if (b.type !== 'praos') {
834
+ nextBlock();
835
+ return;
836
+ }
837
+ const mapped = this.mapOgmiosBlock(b);
838
+ const t = tip;
839
+ const tipPoint = t && t !== 'origin' && t.slot != null && t.id
840
+ ? { slot: t.slot, hash: t.id, height: t.height }
841
+ : undefined;
842
+ await callbacks.rollForward(mapped.block, mapped.txs, tipPoint);
843
+ nextBlock();
844
+ }
845
+ catch (err) {
846
+ logger.error('[OgmiosBackend] chain-sync rollForward failed — stream halted:', err);
847
+ await reportStreamError(err);
848
+ }
849
+ },
850
+ rollBackward: async ({ point }, nextBlock) => {
851
+ try {
852
+ const p = point;
853
+ await callbacks.rollBackward(p === 'origin' ? 'origin' : { slot: p.slot, hash: p.id });
854
+ nextBlock();
855
+ }
856
+ catch (err) {
857
+ logger.error('[OgmiosBackend] chain-sync rollBackward failed — stream halted:', err);
858
+ await reportStreamError(err);
859
+ }
860
+ },
861
+ };
862
+ let client;
863
+ try {
864
+ client = await this.withInitTimeout((0, client_1.createChainSynchronizationClient)(context, handlers, { sequential: true }), 'chainSync/createClient');
865
+ // Ogmios intersects at the FIRST of these still on its chain, so ancestors
866
+ // turn a fork we slept through into a rollBackward instead of a hard failure.
867
+ const points = from === 'origin' ? ['origin'] : from.map((p) => ({ slot: p.slot, id: p.hash }));
868
+ await this.withInitTimeout(client.resume(points, 1), 'chainSync/resume');
869
+ }
870
+ catch (err) {
871
+ intentionalClose = true;
872
+ if (client) {
873
+ try {
874
+ await this.withInitTimeout(client.shutdown(), 'chainSync/failedOpenShutdown');
875
+ }
876
+ catch {
877
+ // forceCloseContext below is the final cleanup path
878
+ }
879
+ }
880
+ this.forceCloseContext(context);
881
+ throw err;
882
+ }
883
+ let closePromise = null;
884
+ return {
885
+ close: () => {
886
+ // Idempotency matters when an operator stop races an onError-triggered halt.
887
+ if (!closePromise) {
888
+ intentionalClose = true;
889
+ closePromise = (async () => {
890
+ try {
891
+ await this.withInitTimeout(client.shutdown(), 'chainSync/shutdown');
892
+ }
893
+ finally {
894
+ // Also handles a shutdown timeout or an already-closed socket.
895
+ this.forceCloseContext(context);
896
+ }
897
+ })();
898
+ }
899
+ return closePromise;
900
+ }
901
+ };
902
+ }
903
+ /**
904
+ * Map an Ogmios Praos block into our BlockData + its transactions. Block-level
905
+ * fees are the sum of per-tx fees; epoch/epochSlot are derived from the slot via
906
+ * the network's Shelley anchor (same config the tx-builder uses).
907
+ */
908
+ mapOgmiosBlock(block) {
909
+ const txs = (block.transactions ?? []).map((t, i) => this.mapOgmiosTx(t, block, i));
910
+ const totalFees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n);
911
+ const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[this.network];
912
+ const epoch = cfg.shelleyStartEpoch + Math.floor((block.slot - cfg.shelleyStartSlot) / cfg.slotsPerEpoch);
913
+ // reuse the Shelley-anchored helper (carries the preview/preprod/Byron-offset fix)
914
+ // instead of a second inline modulo formula
915
+ const epochSlot = block.slot - epochStartSlot(this.network, epoch);
916
+ const blockData = {
917
+ time: slotToPosixSeconds(this.network, block.slot),
918
+ height: block.height,
919
+ hash: block.id,
920
+ slot: block.slot,
921
+ slotLeader: block.issuer?.verificationKey ?? '',
922
+ epoch,
923
+ epochSlot,
924
+ size: block.size?.bytes ?? 0,
925
+ txCount: txs.length,
926
+ fees: totalFees.toString(),
927
+ };
928
+ return { block: blockData, txs };
929
+ }
930
+ /**
931
+ * Map a single Ogmios chain-sync transaction into our Transaction. Outputs, fee
932
+ * and metadata are mapped fully; inputs are kept as bare references (address/amount
933
+ * resolved downstream by the indexer). `spends` selects the ledger-applied
934
+ * partition: a phase-2-invalid transaction consumes collaterals and creates only
935
+ * its collateral-return output, never its declared regular inputs/outputs.
936
+ */
937
+ mapOgmiosTx(tx, block, index) {
938
+ const mapInput = (input, flags = {}) => ({
939
+ address: '',
940
+ amount: [],
941
+ txHash: input.transaction.id,
942
+ outputIndex: input.index,
943
+ ...flags,
944
+ });
945
+ const spendsCollaterals = tx.spends === 'collaterals';
946
+ const inputs = [
947
+ ...(spendsCollaterals ? [] : (tx.inputs ?? []).map(input => mapInput(input))),
948
+ ...(tx.collaterals ?? []).map(input => mapInput(input, { isCollateral: true })),
949
+ ...(tx.references ?? []).map(input => mapInput(input, { isReference: true })),
950
+ ];
951
+ const mapOutput = (output, outputIndex, isCollateral) => ({
952
+ address: output.address,
953
+ amount: this.convertOgmiosValue(output.value),
954
+ txHash: tx.id,
955
+ outputIndex,
956
+ dataHash: output.datumHash ?? null,
957
+ inlineDatum: output.datum ?? null,
958
+ isCollateral,
959
+ referenceScriptHash: null,
960
+ });
961
+ const outputs = spendsCollaterals
962
+ ? (tx.collateralReturn
963
+ // The ledger assigns collateral return the index immediately after the
964
+ // declared regular outputs, even though those outputs are not produced.
965
+ ? [mapOutput(tx.collateralReturn, tx.outputs?.length ?? 0, true)]
966
+ : [])
967
+ : (tx.outputs ?? []).map((output, outputIndex) => mapOutput(output, outputIndex, false));
968
+ const metadataEntries = tx.metadata?.labels
969
+ ? Object.entries(tx.metadata.labels).map(([label, v]) => ({
970
+ txHash: tx.id,
971
+ label,
972
+ json: v.json,
973
+ }))
974
+ : [];
975
+ return {
976
+ hash: tx.id,
977
+ blockHash: block.id,
978
+ blockHeight: block.height,
979
+ slot: block.slot,
980
+ index,
981
+ fee: (tx.fee?.ada?.lovelace ?? 0).toString(),
982
+ deposit: '0',
983
+ // null = unknown (chain-sync doesn't surface the serialized size) — matches the
984
+ // lazy path's `size ?? null` convention; 0 would masquerade as a real size
985
+ size: null,
986
+ blockTime: slotToPosixSeconds(this.network, block.slot),
987
+ inputs,
988
+ outputs,
989
+ // undefined (not []) when absent — matches the Blockfrost path so
990
+ // mapTransaction's hasMetadata flag stays false for metadata-less txs
991
+ metadata: metadataEntries.length ? metadataEntries : undefined,
992
+ };
993
+ }
678
994
  }
679
995
  exports.OgmiosBackend = OgmiosBackend;
680
996
  //# 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