@odatano/core 2.0.0-rc.19 → 2.0.0-rc.20

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 (119) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +1 -5
  2. package/@cds-models/CardanoIndexerService/index.d.ts +51 -2
  3. package/@cds-models/CardanoIndexerService/index.js +7 -0
  4. package/package.json +1 -1
  5. package/src/index.d.ts +4 -10
  6. package/src/index.js +6 -16
  7. package/src/plugin.js +11 -27
  8. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  9. package/srv/blockchain/backends/blockfrost-backend.js +39 -150
  10. package/srv/blockchain/backends/cardano-backend.d.ts +53 -171
  11. package/srv/blockchain/backends/cardano-backend.js +1 -5
  12. package/srv/blockchain/backends/koios-backend.d.ts +26 -71
  13. package/srv/blockchain/backends/koios-backend.js +50 -132
  14. package/srv/blockchain/backends/ogmios-backend.d.ts +43 -124
  15. package/srv/blockchain/backends/ogmios-backend.js +71 -179
  16. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +12 -57
  17. package/srv/blockchain/backends/ogmios-frame-guard.js +27 -66
  18. package/srv/blockchain/cardano-client.d.ts +43 -216
  19. package/srv/blockchain/cardano-client.js +49 -234
  20. package/srv/blockchain/cardano-indexer.d.ts +79 -357
  21. package/srv/blockchain/cardano-indexer.js +98 -406
  22. package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
  23. package/srv/blockchain/cardano-tx-builder.js +21 -107
  24. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  25. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  26. package/srv/blockchain/crawler/crawler.d.ts +41 -145
  27. package/srv/blockchain/crawler/crawler.js +57 -172
  28. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  29. package/srv/blockchain/crawler/index.d.ts +2 -6
  30. package/srv/blockchain/crawler/index.js +4 -9
  31. package/srv/blockchain/crawler/sync-state.d.ts +17 -39
  32. package/srv/blockchain/crawler/sync-state.js +23 -55
  33. package/srv/blockchain/crawler/utxo-set-import.d.ts +5 -22
  34. package/srv/blockchain/crawler/utxo-set-import.js +8 -28
  35. package/srv/blockchain/ledger-state.d.ts +3 -12
  36. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  37. package/srv/blockchain/signing/cose-verifier.js +6 -12
  38. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  39. package/srv/blockchain/signing/external-signer.js +19 -122
  40. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  41. package/srv/blockchain/signing/hsm-signer.js +23 -63
  42. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  43. package/srv/blockchain/signing/signature-verifier.js +13 -54
  44. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  45. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  46. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +65 -174
  47. package/srv/blockchain/transaction-building/buildooor-tx.js +107 -266
  48. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  49. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  50. package/srv/blockchain/wallet-worker/build-request.js +9 -22
  51. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +12 -35
  52. package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -32
  53. package/srv/blockchain/wallet-worker/index.js +2 -8
  54. package/srv/blockchain/wallet-worker/job-store.d.ts +33 -111
  55. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  56. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  57. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  58. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  59. package/srv/blockchain/wallet-worker/signers.js +3 -8
  60. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  61. package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
  62. package/srv/cardano-agent-service.cds +1 -5
  63. package/srv/cardano-agent-service.js +3 -7
  64. package/srv/cardano-indexer-service.cds +32 -4
  65. package/srv/cardano-indexer-service.js +83 -15
  66. package/srv/cardano-service.js +36 -98
  67. package/srv/cardano-sign-service.cds +1 -1
  68. package/srv/cardano-sign-service.js +55 -173
  69. package/srv/cardano-tx-service.cds +1 -1
  70. package/srv/cardano-tx-service.js +54 -174
  71. package/srv/cardano-worker-service.js +7 -15
  72. package/srv/server.d.ts +27 -86
  73. package/srv/server.js +52 -148
  74. package/srv/utils/agent-grants-config.d.ts +11 -50
  75. package/srv/utils/agent-grants-config.js +12 -45
  76. package/srv/utils/agent-grants.d.ts +34 -123
  77. package/srv/utils/agent-grants.js +57 -156
  78. package/srv/utils/agent-token-auth.d.ts +2 -5
  79. package/srv/utils/agent-token-auth.js +2 -5
  80. package/srv/utils/backend-request-handler.d.ts +2 -16
  81. package/srv/utils/backend-request-handler.js +3 -18
  82. package/srv/utils/collections.d.ts +4 -8
  83. package/srv/utils/collections.js +4 -8
  84. package/srv/utils/const.d.ts +19 -68
  85. package/srv/utils/const.js +20 -69
  86. package/srv/utils/crypto.d.ts +3 -12
  87. package/srv/utils/crypto.js +5 -18
  88. package/srv/utils/db-indexes.d.ts +2 -7
  89. package/srv/utils/db-indexes.js +7 -34
  90. package/srv/utils/db-sanitize.d.ts +5 -18
  91. package/srv/utils/db-sanitize.js +6 -19
  92. package/srv/utils/error-codes.d.ts +18 -73
  93. package/srv/utils/error-codes.js +17 -70
  94. package/srv/utils/errors.d.ts +29 -191
  95. package/srv/utils/errors.js +44 -229
  96. package/srv/utils/liveness.d.ts +2 -9
  97. package/srv/utils/liveness.js +3 -11
  98. package/srv/utils/mappers.d.ts +50 -298
  99. package/srv/utils/mappers.js +80 -386
  100. package/srv/utils/network-context.js +2 -11
  101. package/srv/utils/pg-order-nulls.js +4 -23
  102. package/srv/utils/plutus-placeholders.d.ts +6 -18
  103. package/srv/utils/plutus-placeholders.js +6 -20
  104. package/srv/utils/rate-limiter.d.ts +6 -17
  105. package/srv/utils/rate-limiter.js +5 -15
  106. package/srv/utils/service-events.d.ts +2 -22
  107. package/srv/utils/service-events.js +3 -23
  108. package/srv/utils/signing-helper.d.ts +3 -18
  109. package/srv/utils/signing-helper.js +10 -32
  110. package/srv/utils/tx-build-helper.d.ts +18 -92
  111. package/srv/utils/tx-build-helper.js +32 -123
  112. package/srv/utils/tx-request-parsers.d.ts +7 -26
  113. package/srv/utils/tx-request-parsers.js +7 -26
  114. package/srv/utils/tx-utils.d.ts +4 -23
  115. package/srv/utils/tx-utils.js +12 -41
  116. package/srv/utils/types.d.ts +67 -206
  117. package/srv/utils/types.js +2 -6
  118. package/srv/utils/validators.d.ts +19 -89
  119. package/srv/utils/validators.js +31 -138
@@ -18,28 +18,22 @@ const mappers_1 = require("../../utils/mappers");
18
18
  const const_1 = require("../../utils/const");
19
19
  const logger = cds_1.default.log('OgmiosBackend');
20
20
  /**
21
- * First absolute slot of the given epoch, from the network's Shelley anchor.
22
- * Replaces the old `epoch * 432000` math, which was wrong on preview (86 400
23
- * slots per epoch) and on mainnet/preprod (Byron offset).
21
+ * First absolute slot of an epoch, from the network's Shelley anchor
22
+ * (86 400 slots per epoch on preview; Byron offset on mainnet/preprod).
24
23
  */
25
24
  function epochStartSlot(network, epoch) {
26
25
  const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[network];
27
26
  return cfg.shelleyStartSlot + (epoch - cfg.shelleyStartEpoch) * cfg.slotsPerEpoch;
28
27
  }
29
28
  /**
30
- * Absolute POSIX seconds for a slot, via the same Shelley-anchored genesis infos
31
- * the transaction builder uses for validity windows. The previous code treated
32
- * Ogmios' `eraStart.time` (RelativeTime since SYSTEM start) as a Unix timestamp.
29
+ * Absolute POSIX seconds for a slot via the Shelley-anchored genesis infos. Ogmios'
30
+ * `eraStart.time` is RelativeTime since system start, not a Unix timestamp.
33
31
  */
34
32
  function slotToPosixSeconds(network, slot) {
35
33
  const genesis = const_1.GENESIS_INFOS_BY_NETWORK[network];
36
34
  return Math.floor((genesis.systemStartPosixMs + (slot - genesis.startSlotNo) * genesis.slotLengthMs) / 1000);
37
35
  }
38
- /**
39
- * Parse an Ogmios `Ratio` ("num/den" string, e.g. "3/1000") into a number.
40
- * `Number("3/1000")` is NaN — previously every ratio-typed protocol parameter
41
- * (priceMem, priceStep, a0, rho, tau) came out as NaN.
42
- */
36
+ /** Parse an Ogmios `Ratio` ("num/den", e.g. "3/1000") into a number; `Number("3/1000")` is NaN. */
43
37
  function parseOgmiosRatio(ratio) {
44
38
  if (ratio === null || ratio === undefined)
45
39
  return 0;
@@ -53,11 +47,7 @@ function parseOgmiosRatio(ratio) {
53
47
  const n = Number(ratio);
54
48
  return Number.isFinite(n) ? n : 0;
55
49
  }
56
- /**
57
- * Extract a lovelace amount from Ogmios' value shapes. Ogmios v6 returns
58
- * `{ ada: { lovelace } }` objects — calling `.toString()` on those yields
59
- * "[object Object]", which previously ended up in the AccountData fields.
60
- */
50
+ /** Lovelace amount from Ogmios' value shapes; v6 returns `{ ada: { lovelace } }` objects. */
61
51
  function ogmiosValueToLovelaceString(value) {
62
52
  if (value === null || value === undefined)
63
53
  return '0';
@@ -67,10 +57,8 @@ function ogmiosValueToLovelaceString(value) {
67
57
  return lovelace === undefined ? '0' : String(lovelace);
68
58
  }
69
59
  /**
70
- * Decode a CIP-129 DRep ID (`drep1…`, 29 bytes) into its credential hash and
71
- * type. Header byte: high nibble 0x2 = DRep, low nibble 0x2 = key hash /
72
- * 0x3 = script hash. The validators already enforce HRP + length before the
73
- * request reaches a backend, so this only has to split the payload.
60
+ * Decode a CIP-129 DRep ID (`drep1…`, 29 bytes) into credential hash and type. Header byte:
61
+ * high nibble 0x2 = DRep, low nibble 0x2 = key hash / 0x3 = script hash.
74
62
  */
75
63
  function decodeDrepId(drepId) {
76
64
  const decoded = bech32_1.bech32.decode(drepId, const_1.BECH32_MAX_LENGTH);
@@ -91,15 +79,13 @@ function resolveOgmiosTip(tip) {
91
79
  function resolveOgmiosHeight(height) {
92
80
  return height === 'origin' ? 0 : height;
93
81
  }
82
+ /** CardanoBackend implementation over an Ogmios WebSocket (local node). */
94
83
  class OgmiosBackend {
95
84
  name = 'ogmios';
96
85
  /**
97
- * Capability declaration — the orchestrator skips Ogmios for these without
98
- * counting circuit failures. Historic queries are out of protocol scope;
99
- * getAddress/getNetworkInformation previously FABRICATED placeholder data
100
- * (type:'base'/isScript:false/stakeAddress:null resp. maxSupply as
101
- * total/circulating) which preferLive routing then preferred over correct
102
- * Blockfrost/Koios data.
86
+ * Capability declaration — the orchestrator skips Ogmios for these without counting
87
+ * circuit failures. Historic queries are out of protocol scope, and address/network
88
+ * aggregates cannot be derived from state queries.
103
89
  */
104
90
  unsupportedMethods = new Set([
105
91
  // getEpoch is NOT listed: Ogmios can serve the CURRENT epoch and only
@@ -122,9 +108,6 @@ class OgmiosBackend {
122
108
  network;
123
109
  timeoutMs;
124
110
  ogmiosUrl;
125
- /**
126
- * Constructor
127
- */
128
111
  constructor(network, timeoutMs, ogmiosUrl) {
129
112
  if (!ogmiosUrl) {
130
113
  throw new errors_1.BackendInitError('ogmios', new Error('ogmiosUrl is not set'));
@@ -134,21 +117,9 @@ class OgmiosBackend {
134
117
  this.ogmiosUrl = ogmiosUrl;
135
118
  }
136
119
  /**
137
- * Force fresh (non-keep-alive) HTTP connections for the Ogmios `/health` probe.
138
- *
139
- * createInteractionContext() opens the WebSocket, but FIRST probes
140
- * `GET http://<ogmios>/health` via the library's `cross-fetch` → node-fetch v2
141
- * → Node-core `http`. Since Node 19, `http.globalAgent` defaults to
142
- * keepAlive:true, so node-fetch reuses pooled sockets. Against Ogmios' Warp
143
- * server on Node 22/24 a reused socket the server has already half-closed
144
- * yields "Invalid response body … Premature close" the instant the body is
145
- * read — deterministically (Node 20's older http client tolerated it; `curl`
146
- * does too, so the /health response itself is well-formed and the node is
147
- * healthy). The lib pins cross-fetch even in 7.0 and exposes no way to inject
148
- * an agent into that internal fetch, so we neutralise keep-alive process-wide
149
- * for `http://`. Blast radius is tiny: the only `http://` consumer is the local
150
- * Ogmios probe — Blockfrost/Koios run over `https` with their own axios agents
151
- * and are unaffected. Runs once, lazily, only when Ogmios is actually used.
120
+ * Force non-keep-alive HTTP for the Ogmios `/health` probe: node-fetch v2 uses `http.globalAgent`,
121
+ * whose pooled sockets (kept alive since Node 19) fail with "Premature close" once Ogmios' Warp server
122
+ * half-closes them. No agent hook exists, so keep-alive is disabled process-wide for `http://` only.
152
123
  */
153
124
  static keepAliveDisabled = false;
154
125
  static disableHttpKeepAlive() {
@@ -176,17 +147,12 @@ class OgmiosBackend {
176
147
  }
177
148
  }
178
149
  /**
179
- * Bound an init step in time. A hung WebSocket connect/handshake (e.g. the
180
- * node is alive but too busy catching up to answer) would otherwise block
181
- * forever — there is no built-in connect timeout — hanging the whole
182
- * app-context bootstrap (seen as a 6h CI job timeout). On timeout we reject
183
- * with a message containing "timeout" so the orchestrator's transient-error
184
- * retry picks it up instead of dying.
150
+ * Bound an init step in time: the WebSocket connect/handshake has no built-in timeout and
151
+ * can hang when the node is busy. The rejection message contains "timeout" so the
152
+ * orchestrator's transient-error retry picks it up.
185
153
  */
186
154
  withInitTimeout(p, label) {
187
- // Keep this SHORT: the orchestrator retries init a few times within the
188
- // integration suite's 20s cds.test() hook, so each attempt must be brief.
189
- // Still bounds a genuinely hung connect in production.
155
+ // Short on purpose: the orchestrator retries init several times within a bounded bootstrap window.
190
156
  const ms = Math.max(1, Math.min(this.timeoutMs, 4000));
191
157
  let timer;
192
158
  const timeout = new Promise((_, reject) => {
@@ -196,10 +162,8 @@ class OgmiosBackend {
196
162
  return Promise.race([p, timeout]).finally(() => clearTimeout(timer));
197
163
  }
198
164
  /**
199
- * Force-release an Ogmios interaction socket after a failed/expired open or
200
- * close step. The runtime uses `ws` (and therefore supports `terminate`), but
201
- * the close fallback keeps the helper compatible with the public structural
202
- * InteractionContext type and lightweight test doubles.
165
+ * Force-release an interaction socket after a failed/expired open or close. The runtime
166
+ * socket is `ws` (has `terminate`); the `close` fallback keeps test doubles working.
203
167
  */
204
168
  forceCloseContext(context) {
205
169
  const socket = context.socket;
@@ -215,9 +179,7 @@ class OgmiosBackend {
215
179
  // Best effort only: the socket may already have completed its close event.
216
180
  }
217
181
  }
218
- /**
219
- * Initialize the Ogmios backend connection
220
- */
182
+ /** Open the interaction context and the query/submission clients. */
221
183
  async init() {
222
184
  OgmiosBackend.disableHttpKeepAlive();
223
185
  OgmiosBackend.validateOgmiosUrl(this.ogmiosUrl);
@@ -230,9 +192,7 @@ class OgmiosBackend {
230
192
  const context = await this.withInitTimeout((0, client_1.createInteractionContext)(
231
193
  /* c8 ignore next */
232
194
  (err) => logger.error(`[OgmiosBackend] Interaction context error: ${err.message}`), () => {
233
- // Socket closed: clear the clients so the next request reconnects via
234
- // ensureConnected — previously this handler only logged and the backend
235
- // stayed dead until process restart.
195
+ // Socket closed: clear the clients so the next request reconnects via ensureConnected.
236
196
  if (this.isShutdown)
237
197
  return;
238
198
  logger.warn('[OgmiosBackend] WebSocket closed — will reconnect on next request');
@@ -256,10 +216,8 @@ class OgmiosBackend {
256
216
  return true;
257
217
  }
258
218
  /**
259
- * Reconnect when the WebSocket has died since the last successful init.
260
- * No-op when never initialized (test-injected clients) — startup-init
261
- * recovery is the orchestrator's job (lazy init retry in CardanoClient).
262
- * Concurrent callers share one reconnect attempt.
219
+ * Reconnect when the WebSocket died since the last init. No-op when never initialized
220
+ * (test-injected clients); concurrent callers share one reconnect attempt.
263
221
  */
264
222
  async ensureConnected() {
265
223
  this.ensureNotShutdown();
@@ -295,13 +253,11 @@ class OgmiosBackend {
295
253
  async getEpoch(epochNumber) {
296
254
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
297
255
  await this.ensureConnected();
298
- // Get current epoch directly via epoch() query
299
256
  const currentEpoch = await this.stateQueryClient.epoch();
300
257
  // Ogmios only supports current epoch queries
301
258
  if (epochNumber !== currentEpoch) {
302
259
  throw new errors_1.NotFoundError(`Historic Epoch ${epochNumber} not supported (current: ${currentEpoch})`, this.name);
303
260
  }
304
- // Return current epoch data
305
261
  return this.getLatestEpoch();
306
262
  }, this.name);
307
263
  }
@@ -326,19 +282,10 @@ class OgmiosBackend {
326
282
  }, this.name);
327
283
  }
328
284
  /**
329
- * Get DRep data from the live ledger state (`queryLedgerState/delegateRepresentatives`).
330
- *
331
- * The client package (6.14) ships the schema types but no wrapper for this query,
332
- * so it goes through the exported `Method()` primitive on our interaction context —
333
- * the same building block the client uses for `stakePools` & co.
334
- *
335
- * Semantics vs. Blockfrost/Koios: Ogmios only lists REGISTERED DReps, so a retired
336
- * or unknown DRep is a NotFoundError here (never `retired: true`), and there is no
337
- * last-activity epoch — `expired` is derived from the mandate epoch instead.
338
- * Routing keeps `getDrep` historical-preferred; this is the Ogmios-only fallback.
339
- *
285
+ * DRep data from the live ledger state (`queryLedgerState/delegateRepresentatives`) via the
286
+ * raw `Method()` primitive, since the client ships no wrapper. Ogmios lists only REGISTERED
287
+ * DReps: retired/unknown → NotFoundError; `expired` is derived from the mandate epoch.
340
288
  * @param drepId CIP-129 bech32 DRep ID (`drep1…`)
341
- * @returns {Promise<DrepData>} drep data
342
289
  */
343
290
  async getDrep(drepId) {
344
291
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
@@ -374,8 +321,7 @@ class OgmiosBackend {
374
321
  hex: hashHex,
375
322
  amount: ogmiosValueToLovelaceString(drep.stake),
376
323
  hasScript: isScript || drep.from === 'script',
377
- // Ogmios reports the mandate (expiry) epoch, not the last activity — keep 0,
378
- // matching what the Koios mapper does since its schema change.
324
+ // Ogmios reports the mandate (expiry) epoch, not the last activity — keep 0.
379
325
  lastActiveEpoch: 0,
380
326
  expired: typeof mandateEpoch === 'number' && mandateEpoch < Number(currentEpoch),
381
327
  retired: false,
@@ -392,22 +338,15 @@ class OgmiosBackend {
392
338
  throw new errors_1.ProviderUnavailableError('Asset info queries not supported by Ogmios backend', this.name);
393
339
  }, this.name);
394
340
  }
395
- /**
396
- * Get specific Network Information (not supported — Ogmios state queries
397
- * expose no supply/stake aggregates; the previous implementation fabricated
398
- * maxSupply as total/circulating, which preferLive routing then preferred
399
- * over correct Blockfrost/Koios data)
400
- */
341
+ /** Not supported — Ogmios state queries expose no supply/stake aggregates. */
401
342
  async getNetworkInformation() {
402
343
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
403
344
  throw new errors_1.ProviderUnavailableError('Network information not supported by Ogmios backend — use Blockfrost/Koios', this.name);
404
345
  }, this.name);
405
346
  }
406
347
  /**
407
- * Get current specific Address Data (not supported — address type, script
408
- * flag and stake address are not derivable from Ogmios state queries; the
409
- * previous implementation fabricated type:'base'/isScript:false/
410
- * stakeAddress:null. UTxOs remain available via getAddressUtxos.)
348
+ * Not supported — address type, script flag and stake address are not derivable from
349
+ * state queries. UTxOs remain available via getAddressUtxos.
411
350
  */
412
351
  async getAddress(_address) {
413
352
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
@@ -431,23 +370,18 @@ class OgmiosBackend {
431
370
  txHash: u.transaction?.id || '',
432
371
  outputIndex: u.index || 0,
433
372
  address: u.address || fallbackAddress,
434
- // convert Ogmios value format to standard amount array
435
373
  amount: this.convertOgmiosValue(u.value),
436
374
  blockHash: '',
437
375
  datumHash: u.datumHash,
438
- // Ogmios delivers the inline datum as CBOR hex in `datum` — it was
439
- // dropped before, breaking inline-datum spends when Ogmios serves UTxOs
376
+ // Ogmios delivers the inline datum as CBOR hex in `datum`
440
377
  inlineDatum: typeof u.datum === 'string' ? u.datum : null,
441
378
  scriptRef: u.script?.hash,
442
379
  };
443
380
  }
444
381
  /**
445
- * The whole UTxO set as of `point` (LedgerStateBackend — crawler.utxoSet snapshot import).
446
- * Opens a SEPARATE WebSocket connection for it: the local-state-query protocol keeps one
447
- * acquired point per connection, so a client on the shared socket would move every live
448
- * query to the historical anchor for the duration. The point must be inside the node's
449
- * volatile window (the last 2160 blocks) or the node refuses the acquisition. Whole-set
450
- * queries are fine on preview/preprod; on mainnet prefer a cardano-cli file.
382
+ * Whole UTxO set as of `point` (crawler snapshot import) on a SEPARATE WebSocket: local-state-query
383
+ * holds one acquired point per connection, so the shared socket would pin live queries to the past.
384
+ * The point must be inside the node's volatile window (last 2160 blocks) or acquisition is refused.
451
385
  */
452
386
  async queryUtxoSetAt(point) {
453
387
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
@@ -473,12 +407,7 @@ class OgmiosBackend {
473
407
  }
474
408
  }, this.name);
475
409
  }
476
- /**
477
- * Get Address Transactions (not supported by Ogmios - use historical backend)
478
- * Ogmios is a live state query backend and does not provide historical transaction data
479
- * @param _address bech32 address
480
- * @returns {Promise<Transaction[]>} always throws - use historical backend instead
481
- */
410
+ /** Not supported — Ogmios is a live state-query backend; use Blockfrost/Koios. */
482
411
  async getAddressTransactions(_address) {
483
412
  throw new errors_1.NotFoundError('Address transactions not available via Ogmios - use historical backend (Blockfrost/Koios)', this.name);
484
413
  }
@@ -492,7 +421,7 @@ class OgmiosBackend {
492
421
  await this.ensureConnected();
493
422
  // Query from tip (no acquire needed) with stake included
494
423
  const pools = await this.stateQueryClient.stakePools([{ id: poolId }], true);
495
- // Extract pool from response - stakePools returns object keyed by poolId
424
+ // stakePools returns an object keyed by poolId
496
425
  const pool = pools[poolId];
497
426
  if (!pool)
498
427
  throw new errors_1.NotFoundError('Pool', this.name);
@@ -509,8 +438,7 @@ class OgmiosBackend {
509
438
  // of fabricating it from the pledge
510
439
  activeStake: '0',
511
440
  activeSize: 0,
512
- // pledge/cost are ValueAdaOnly objects in Ogmios v6 — String() on those
513
- // yielded "[object Object]"; margin is a Ratio string ("1/10")
441
+ // pledge/cost are ValueAdaOnly objects in Ogmios v6; margin is a Ratio string ("1/10")
514
442
  pledge: ogmiosValueToLovelaceString(pool.pledge),
515
443
  margin: parseOgmiosRatio(pool.margin),
516
444
  fixedCost: ogmiosValueToLovelaceString(pool.cost),
@@ -531,7 +459,6 @@ class OgmiosBackend {
531
459
  const summaries = Array.isArray(rawResult)
532
460
  ? rawResult
533
461
  : Object.values(rawResult);
534
- // Ogmios API returns array of account summaries
535
462
  const account = summaries && summaries.length > 0 ? summaries[0] : null;
536
463
  if (!account) {
537
464
  throw new errors_1.NotFoundError('Account', this.name);
@@ -617,7 +544,7 @@ class OgmiosBackend {
617
544
  eMax: params.stakePoolRetirementEpochBound || 0,
618
545
  nOpt: params.desiredNumberOfStakePools || 0,
619
546
  a0: parseOgmiosRatio(params.stakePoolPledgeInfluence),
620
- // ρ = monetaryExpansion, τ = treasuryExpansion (was swapped; Koios maps it correctly)
547
+ // ρ = monetaryExpansion, τ = treasuryExpansion
621
548
  rho: parseOgmiosRatio(params.monetaryExpansion),
622
549
  tau: parseOgmiosRatio(params.treasuryExpansion),
623
550
  decentralisationParam: 0,
@@ -673,7 +600,7 @@ class OgmiosBackend {
673
600
  ]);
674
601
  const { slot, hash } = resolveOgmiosTip(tip);
675
602
  const height = resolveOgmiosHeight(blockHeight);
676
- // network-aware slot-in-epoch (the old `slot % 432000` was wrong on every network)
603
+ // network-aware slot-in-epoch
677
604
  const epochSlot = Math.max(0, slot - epochStartSlot(this.network, epoch));
678
605
  return {
679
606
  time: slotToPosixSeconds(this.network, slot), // seconds (mapBlock expects seconds)
@@ -701,11 +628,9 @@ class OgmiosBackend {
701
628
  return block.slot;
702
629
  }
703
630
  /**
704
- * Check whether a UTxO is still unspent via Ogmios `queryLedgerState/utxo`
705
- * with an outputReferences filter. Empty result means spent or nonexistent.
631
+ * Unspent check via `queryLedgerState/utxo` with an outputReferences filter; empty = spent or nonexistent.
706
632
  * @param txHash 64-char lowercase hex
707
633
  * @param outputIndex non-negative integer
708
- * @returns {Promise<boolean>} true iff the UTxO exists and is unspent
709
634
  */
710
635
  async isUtxoUnspent(txHash, outputIndex) {
711
636
  if (!Number.isInteger(outputIndex) || outputIndex < 0)
@@ -718,10 +643,7 @@ class OgmiosBackend {
718
643
  return Array.isArray(result) && result.length > 0;
719
644
  }, this.name);
720
645
  }
721
- /**
722
- * Shutdown the Ogmios Backend
723
- * Closes all connections and marks as shutdown
724
- */
646
+ /** Close the WebSocket and mark the backend as shut down. */
725
647
  async shutdown() {
726
648
  if (this.isShutdown)
727
649
  return;
@@ -744,9 +666,6 @@ class OgmiosBackend {
744
666
  this.txSubmissionClient = null;
745
667
  this.context = null;
746
668
  }
747
- /**
748
- * Check if backend is connected
749
- */
750
669
  isConnected() {
751
670
  if (this.isShutdown || !this.context?.socket) {
752
671
  return false;
@@ -757,29 +676,23 @@ class OgmiosBackend {
757
676
  // ---------------------------------------------------------------------------
758
677
  // Helpers
759
678
  // ---------------------------------------------------------------------------
760
- /**
761
- * Ensure the client is not shutdown before operations
762
- */
763
679
  ensureNotShutdown() {
764
680
  if (this.isShutdown) {
765
681
  throw new errors_1.ProviderUnavailableError('Ogmios client has been shutdown', this.name);
766
682
  }
767
683
  }
768
684
  /**
769
- * Convert Ogmios value format to odatano amount array
770
- * Ogmios: { ada: { lovelace: 1000000 }, policyId: { assetName: quantity } }
771
- * Standard: [{ unit: 'lovelace', quantity: '1000000' }, { unit: 'policyId.assetName', quantity: 'N' }]
685
+ * Ogmios value `{ ada: { lovelace }, policyId: { assetName: qty } }` →
686
+ * `[{ unit: 'lovelace', quantity }, { unit: policyId+assetName, quantity }]`.
772
687
  */
773
688
  convertOgmiosValue(value) {
774
689
  const amounts = [];
775
- // Handle ADA (lovelace)
776
690
  if (value.ada?.lovelace) {
777
691
  amounts.push({
778
692
  unit: 'lovelace',
779
693
  quantity: value.ada.lovelace.toString()
780
694
  });
781
695
  }
782
- // handle native assets (policy.assetName)
783
696
  for (const [policyId, assets] of Object.entries(value)) {
784
697
  if (policyId === 'ada')
785
698
  continue;
@@ -793,20 +706,12 @@ class OgmiosBackend {
793
706
  return amounts;
794
707
  }
795
708
  // ---------------------------------------------------------------------------
796
- // ChainSyncBackend — streamed forward sync for the chain crawler (v2.0)
709
+ // ChainSyncBackend — streamed forward sync for the chain crawler
797
710
  // ---------------------------------------------------------------------------
798
711
  /**
799
- * Open a dedicated chain-synchronization stream. Uses its own InteractionContext
800
- * (a separate WebSocket) from the query/submission clients, because it is a
801
- * long-lived stream. `sequential: true` + `inFlight: 1` deliver blocks one at a
802
- * time in order, which the crawler needs for reorg detection and serial persist.
803
- *
804
- * KNOWN LIMITATIONS (documented, to harden against a live node — see CRAWLER_DESIGN.md):
805
- * - Input address/amount are left empty: Ogmios chain-sync inputs are bare
806
- * references ({txId,index}); the indexer resolves them from already-indexed
807
- * outputs (indexBlockFull, C3).
808
- * - Per-tx `size` and `deposit` are not surfaced by chain-sync (set 0).
809
- * - Output `referenceScriptHash` is not derived from the inline script yet.
712
+ * Open a long-lived chain-sync stream on its own WebSocket. `sequential: true` + `inFlight: 1`
713
+ * deliver blocks strictly in order (required by reorg detection and serial persist). Inputs arrive
714
+ * as bare references (resolved by the indexer from indexed outputs); per-tx size/deposit are not surfaced.
810
715
  */
811
716
  async openChainSync(from, callbacks) {
812
717
  OgmiosBackend.validateOgmiosUrl(this.ogmiosUrl);
@@ -832,12 +737,10 @@ class OgmiosBackend {
832
737
  logger.error('[OgmiosBackend] chain-sync onError callback failed:', callbackError);
833
738
  }
834
739
  };
835
- // A frame the client's own parser cannot handle never reaches this class: it throws
836
- // inside the library's socket handler, where nothing awaits it, and ends the process.
837
- // The guard intercepts that and routes the unusable frame here instead, as an ordinary
838
- // stream error naming the block. Installed per open (one stream at a time) and
839
- // idempotent, so reopening only swaps the callback.
840
- (0, ogmios_frame_guard_1.installOgmiosFrameGuard)(({ height, id, reason }) => {
740
+ // A frame the client's parser cannot handle throws inside the library's un-awaited socket
741
+ // handler and would end the process; the guard routes it here as a stream error instead.
742
+ // Registered per open and removed on close, so concurrent streams each get the report.
743
+ const unregisterFrameGuard = (0, ogmios_frame_guard_1.installOgmiosFrameGuard)(({ height, id, reason }) => {
841
744
  void reportStreamError(new errors_1.ChainSyncFrameError(height, id, reason));
842
745
  });
843
746
  const contextPromise = (0, client_1.createInteractionContext)((err) => {
@@ -859,14 +762,13 @@ class OgmiosBackend {
859
762
  // A timeout rejects our race but cannot cancel the library's health probe /
860
763
  // handshake. If it resolves later, close that late socket as well.
861
764
  intentionalClose = true;
765
+ unregisterFrameGuard();
862
766
  void contextPromise.then(lateContext => this.forceCloseContext(lateContext)).catch(() => undefined);
863
767
  throw err;
864
768
  }
865
- // Both handlers are fully try/caught: the ogmios client lib awaits them with NO
866
- // catch of its own, and with sequential+inFlight:1 a throw before nextBlock()
867
- // stalls the stream forever. On error we deliberately do NOT call nextBlock()
868
- // (stopping deterministically instead of skipping a block) and surface the error
869
- // via callbacks.onError so the consumer can record it and close/restart.
769
+ // Both handlers are fully try/caught: the client awaits them without a catch, and with
770
+ // sequential+inFlight:1 a throw before nextBlock() stalls the stream. On error nextBlock()
771
+ // is deliberately NOT called (stop, don't skip a block); the error goes to callbacks.onError.
870
772
  const handlers = {
871
773
  rollForward: async ({ block, tip }, nextBlock) => {
872
774
  try {
@@ -911,6 +813,7 @@ class OgmiosBackend {
911
813
  }
912
814
  catch (err) {
913
815
  intentionalClose = true;
816
+ unregisterFrameGuard();
914
817
  if (client) {
915
818
  try {
916
819
  await this.withInitTimeout(client.shutdown(), 'chainSync/failedOpenShutdown');
@@ -928,6 +831,7 @@ class OgmiosBackend {
928
831
  // Idempotency matters when an operator stop races an onError-triggered halt.
929
832
  if (!closePromise) {
930
833
  intentionalClose = true;
834
+ unregisterFrameGuard();
931
835
  closePromise = (async () => {
932
836
  try {
933
837
  await this.withInitTimeout(client.shutdown(), 'chainSync/shutdown');
@@ -943,21 +847,16 @@ class OgmiosBackend {
943
847
  };
944
848
  }
945
849
  /**
946
- * Map an Ogmios Praos block into our BlockData + its transactions. Block-level
947
- * fees are the sum of per-tx fees; epoch/epochSlot are derived from the slot via
948
- * the network's Shelley anchor (same config the tx-builder uses).
949
- *
950
- * A phase-2 failure whose body declares no `total_collateral` still carries its
951
- * declared fee here, because the collateral inputs are not resolved yet. The indexer
952
- * corrects both the transaction and this sum in applyCollateralFees().
850
+ * Map an Ogmios Praos block to BlockData + transactions. Block fees are the sum of per-tx
851
+ * fees; epoch/epochSlot derive from the slot via the Shelley anchor. A phase-2 failure without
852
+ * `total_collateral` still carries its declared fee here; applyCollateralFees() corrects it.
953
853
  */
954
854
  mapOgmiosBlock(block) {
955
855
  const txs = (block.transactions ?? []).map((t, i) => this.mapOgmiosTx(t, block, i));
956
856
  const totalFees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n);
957
857
  const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[this.network];
958
858
  const epoch = cfg.shelleyStartEpoch + Math.floor((block.slot - cfg.shelleyStartSlot) / cfg.slotsPerEpoch);
959
- // reuse the Shelley-anchored helper (carries the preview/preprod/Byron-offset fix)
960
- // instead of a second inline modulo formula
859
+ // Shelley-anchored helper (handles preview/preprod geometry and the Byron offset)
961
860
  const epochSlot = block.slot - epochStartSlot(this.network, epoch);
962
861
  const blockData = {
963
862
  time: slotToPosixSeconds(this.network, block.slot),
@@ -974,12 +873,9 @@ class OgmiosBackend {
974
873
  return { block: blockData, txs };
975
874
  }
976
875
  /**
977
- * Map a single Ogmios chain-sync transaction into our Transaction. Outputs, fee
978
- * and metadata are mapped fully; inputs are kept as bare references (address/amount
979
- * resolved downstream by the indexer). `spends` selects the ledger-applied
980
- * partition: a phase-2-invalid transaction consumes collaterals and creates only
981
- * its collateral-return output, never its declared regular inputs/outputs. The fee
982
- * follows that partition too — see the `spendsCollaterals` branch below.
876
+ * Map one chain-sync transaction. Inputs stay bare references (resolved by the indexer).
877
+ * `spends` selects the ledger-applied partition: a phase-2-invalid tx consumes collaterals
878
+ * and creates only its collateral-return output; the fee follows that partition too.
983
879
  */
984
880
  mapOgmiosTx(tx, block, index) {
985
881
  const mapInput = (input, flags = {}) => ({
@@ -1019,10 +915,8 @@ class OgmiosBackend {
1019
915
  json: v.json,
1020
916
  }))
1021
917
  : [];
1022
- // A phase-2 failure does not pay the fee declared in the body — the ledger consumes
1023
- // the collateral instead. `total_collateral` is that amount and the ledger enforces
1024
- // the equality, so prefer it; the body omits it often enough that the indexer derives
1025
- // the rest from the resolved collateral inputs once it has them.
918
+ // A phase-2 failure pays `total_collateral`, not the declared fee; the body often omits it,
919
+ // so the indexer derives the rest from the resolved collateral inputs later.
1026
920
  const declaredFee = (tx.fee?.ada?.lovelace ?? 0).toString();
1027
921
  const totalCollateral = tx.totalCollateral ? tx.totalCollateral.ada.lovelace.toString() : null;
1028
922
  return {
@@ -1055,11 +949,9 @@ class OgmiosBackend {
1055
949
  };
1056
950
  }
1057
951
  /**
1058
- * Normalize Ogmios certificates onto the shared `CertificateKind` vocabulary.
1059
- * A `stakeDelegation` carrying both a pool and a DRep target is split into two entries
1060
- * with the same index, matching what Koios (db-sync) reports for the Conway combined
1061
- * certificate. Ogmios credentials are bare hashes; they are re-encoded as bech32 here so
1062
- * the rows carry the same identifiers as every other table.
952
+ * Normalize Ogmios certificates onto the shared `CertificateKind` vocabulary. A `stakeDelegation`
953
+ * with both pool and DRep target is split into two entries with the same index (as db-sync
954
+ * reports it); bare credential hashes are re-encoded as bech32 to match the other tables.
1063
955
  */
1064
956
  mapOgmiosCertificates(certs) {
1065
957
  const out = [];
@@ -1,47 +1,7 @@
1
1
  /**
2
- * Guard against Ogmios chain-sync frames that the client's JSON parser cannot handle.
3
- *
4
- * `@cardano-ogmios/client` parses every WebSocket frame with `safeJSON.parse`, which is
5
- * `sanitize(JSONBig.parse(raw))`. Both halves recurse once per nesting level: the
6
- * `@cardanosolutions/json-bigint` parser is Crockford's recursive descent, and `sanitize`
7
- * walks the parsed tree recursively. A native script nests one JSON object per clause, and
8
- * nested clauses cost only a few bytes each in CBOR — so an ordinary-looking block can
9
- * expand into JSON that is ten thousand levels deep and exhaust the V8 stack.
10
- *
11
- * That is not a theoretical shape. Preprod block 5183974 carries a native script nested
12
- * 10 774 levels deep (`{"clause":"all","from":[ … ]}` down to a single signature clause).
13
- * The block is 43 kB on chain and 205 kB as a chain-sync frame.
14
- *
15
- * The crash is fatal rather than merely annoying, because of where the parse happens
16
- * (`ChainSynchronization/Client.js`):
17
- *
18
- * socket.on('message', async (message) => {
19
- * await responseHandler(util_1.safeJSON.parse(message));
20
- * });
21
- *
22
- * `safeJSON.parse` throws synchronously inside an `async` handler that nobody awaits, so
23
- * the `RangeError` surfaces as an unhandled rejection and Node takes the process down. The
24
- * crawler's poison-block latch cannot help: it guards the persist path, and the server is
25
- * gone long before a block reaches it. Docker restarts, the crawler resumes at the same
26
- * block, and the loop repeats — 53 restarts in seven minutes on the hosted box.
27
- *
28
- * This guard wraps `safeJSON.parse` (a public export of the client package) so that the
29
- * fast path is untouched and only an overflowing frame takes the recovery route:
30
- *
31
- * 1. the original parser, so every ordinary frame keeps its exact BigInt handling;
32
- * 2. on `RangeError`, `widenBigIntegers()` rewrites integer literals that a double cannot
33
- * hold into JSON strings, then plain `JSON.parse` — V8's parser is iterative, so depth
34
- * is no longer a limit. `sanitize` is skipped, because it would overflow on the very
35
- * same structure;
36
- * 3. if even that fails, the frame is reported to the caller and a sentinel is returned.
37
- * The guard never throws, because throwing here is what kills the process.
38
- *
39
- * Measured against the real frame (node 22, 205 728 bytes, depth 10 774): json-bigint and
40
- * `JSON.parse` with a reviver both overflow — a reviver walk is recursive too — while plain
41
- * `JSON.parse` completes in 17 ms.
42
- *
43
- * Upstream: a recursive parser on untrusted chain data is a denial-of-service against every
44
- * consumer of the client, mainnet included. This guard is a local mitigation, not the cure.
2
+ * Guard for Ogmios chain-sync frames the client's `safeJSON.parse` cannot handle: it recurses per
3
+ * nesting level, so a deeply nested native script overflows the stack inside an un-awaited socket
4
+ * handler and ends the process. On RangeError fall back to iterative `JSON.parse` (big ints as strings).
45
5
  */
46
6
  import { safeJSON } from '@cardano-ogmios/client';
47
7
  /** A frame the guard could not turn into an object at all. */
@@ -54,24 +14,19 @@ export interface UnparseableFrame {
54
14
  bytes: number;
55
15
  }
56
16
  /**
57
- * Integers outside the safe double range, written into JSON strings so that plain
58
- * `JSON.parse` cannot round them. Runs as one linear pass with an explicit in-string state,
59
- * never recursing, so it is immune to the nesting that sent us here in the first place.
60
- *
61
- * Only numbers in value position are touched: digits inside strings (hashes, CBOR, asset
62
- * names) are skipped, and so are floats and exponents, which are doubles by nature and have
63
- * no exact integer to preserve.
17
+ * Wrap integers outside the safe double range in JSON strings so plain `JSON.parse` cannot
18
+ * round them. One linear pass, no recursion; digits inside strings, floats and exponents
19
+ * are left alone.
64
20
  */
65
21
  export declare function widenBigIntegers(text: string): string;
66
22
  /**
67
- * Wrap `safeJSON.parse` once per process. Idempotent: a second call only replaces the
68
- * report callback, so reopening the chain-sync stream never stacks wrappers.
69
- *
70
- * @param onUnparseableFrame called when a frame survives neither parser. The guard returns
71
- * a sentinel instead of throwing, so the caller owns what happens next — the stream
72
- * itself stalls, because the client drops anything that is not a nextBlock response.
23
+ * Wrap `safeJSON.parse` once per process and register a report callback; returns its
24
+ * unregister function. The parser is shared by every open chain-sync socket and cannot tell
25
+ * which one a frame came from, so an unusable frame goes to every registered callback.
26
+ * After a reported frame the stream stalls (the client drops non-nextBlock responses),
27
+ * so the caller decides what happens next.
73
28
  */
74
- export declare function installOgmiosFrameGuard(onUnparseableFrame: (frame: UnparseableFrame) => void): void;
29
+ export declare function installOgmiosFrameGuard(onUnparseableFrame: (frame: UnparseableFrame) => void): () => void;
75
30
  /** Tests only — drop the wrapper so each case starts from the untouched client. */
76
31
  export declare function resetOgmiosFrameGuardForTests(originalParse?: typeof safeJSON.parse): void;
77
32
  //# sourceMappingURL=ogmios-frame-guard.d.ts.map