@odatano/core 2.0.0-rc.2 → 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 (132) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +139 -2
  4. package/@cds-models/CardanoIndexerService/index.js +18 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +224 -0
  6. package/@cds-models/CardanoODataService/index.js +27 -0
  7. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  8. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  9. package/@cds-models/odatano/cardano/index.d.ts +316 -0
  10. package/@cds-models/odatano/cardano/index.js +33 -0
  11. package/README.md +195 -136
  12. package/db/schema.cds +2121 -1633
  13. package/package.json +179 -173
  14. package/src/index.d.ts +10 -10
  15. package/src/index.js +24 -14
  16. package/src/plugin.js +39 -52
  17. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  18. package/srv/blockchain/backends/blockfrost-backend.js +45 -158
  19. package/srv/blockchain/backends/cardano-backend.d.ts +78 -158
  20. package/srv/blockchain/backends/cardano-backend.js +14 -5
  21. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  22. package/srv/blockchain/backends/koios-backend.js +292 -202
  23. package/srv/blockchain/backends/ogmios-backend.d.ts +59 -96
  24. package/srv/blockchain/backends/ogmios-backend.js +241 -153
  25. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  26. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  27. package/srv/blockchain/cardano-client.d.ts +50 -205
  28. package/srv/blockchain/cardano-client.js +80 -224
  29. package/srv/blockchain/cardano-indexer.d.ts +146 -244
  30. package/srv/blockchain/cardano-indexer.js +442 -285
  31. package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
  32. package/srv/blockchain/cardano-tx-builder.js +21 -107
  33. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  34. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  35. package/srv/blockchain/crawler/crawler.d.ts +121 -53
  36. package/srv/blockchain/crawler/crawler.js +402 -82
  37. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  38. package/srv/blockchain/crawler/index.d.ts +5 -0
  39. package/srv/blockchain/crawler/index.js +35 -7
  40. package/srv/blockchain/crawler/sync-state.d.ts +44 -28
  41. package/srv/blockchain/crawler/sync-state.js +115 -43
  42. package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
  43. package/srv/blockchain/crawler/utxo-set-import.js +269 -0
  44. package/srv/blockchain/ledger-state.d.ts +80 -0
  45. package/srv/blockchain/ledger-state.js +383 -0
  46. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  47. package/srv/blockchain/signing/cose-verifier.js +6 -12
  48. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  49. package/srv/blockchain/signing/external-signer.js +19 -122
  50. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  51. package/srv/blockchain/signing/hsm-signer.js +23 -63
  52. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  53. package/srv/blockchain/signing/signature-verifier.js +13 -54
  54. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  55. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  56. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
  57. package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
  58. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  59. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  60. package/srv/blockchain/wallet-worker/build-request.js +39 -23
  61. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  62. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  63. package/srv/blockchain/wallet-worker/index.js +2 -8
  64. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  65. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  66. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  67. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  68. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  69. package/srv/blockchain/wallet-worker/signers.js +3 -8
  70. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  71. package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
  72. package/srv/cardano-agent-service.cds +146 -0
  73. package/srv/cardano-agent-service.d.ts +2 -0
  74. package/srv/cardano-agent-service.js +12 -0
  75. package/srv/cardano-indexer-service.cds +164 -73
  76. package/srv/cardano-indexer-service.js +156 -11
  77. package/srv/cardano-service.cds +45 -0
  78. package/srv/cardano-service.js +38 -96
  79. package/srv/cardano-sign-service.cds +200 -180
  80. package/srv/cardano-sign-service.js +55 -173
  81. package/srv/cardano-tx-service.cds +32 -26
  82. package/srv/cardano-tx-service.js +133 -195
  83. package/srv/cardano-worker-service.js +7 -15
  84. package/srv/server.d.ts +28 -86
  85. package/srv/server.js +95 -128
  86. package/srv/utils/agent-grants-config.d.ts +37 -0
  87. package/srv/utils/agent-grants-config.js +138 -0
  88. package/srv/utils/agent-grants.d.ts +262 -0
  89. package/srv/utils/agent-grants.js +914 -0
  90. package/srv/utils/agent-token-auth.d.ts +16 -0
  91. package/srv/utils/agent-token-auth.js +78 -0
  92. package/srv/utils/backend-request-handler.d.ts +2 -16
  93. package/srv/utils/backend-request-handler.js +3 -18
  94. package/srv/utils/collections.d.ts +4 -8
  95. package/srv/utils/collections.js +4 -8
  96. package/srv/utils/const.d.ts +19 -68
  97. package/srv/utils/const.js +20 -69
  98. package/srv/utils/crypto.d.ts +3 -12
  99. package/srv/utils/crypto.js +5 -18
  100. package/srv/utils/db-indexes.d.ts +25 -0
  101. package/srv/utils/db-indexes.js +89 -0
  102. package/srv/utils/db-sanitize.d.ts +27 -0
  103. package/srv/utils/db-sanitize.js +85 -0
  104. package/srv/utils/error-codes.d.ts +18 -73
  105. package/srv/utils/error-codes.js +17 -70
  106. package/srv/utils/errors.d.ts +34 -178
  107. package/srv/utils/errors.js +55 -217
  108. package/srv/utils/liveness.d.ts +16 -0
  109. package/srv/utils/liveness.js +41 -0
  110. package/srv/utils/mappers.d.ts +82 -210
  111. package/srv/utils/mappers.js +272 -293
  112. package/srv/utils/network-context.js +2 -11
  113. package/srv/utils/pg-order-nulls.d.ts +14 -0
  114. package/srv/utils/pg-order-nulls.js +57 -0
  115. package/srv/utils/plutus-placeholders.d.ts +6 -18
  116. package/srv/utils/plutus-placeholders.js +6 -20
  117. package/srv/utils/rate-limiter.d.ts +46 -0
  118. package/srv/utils/rate-limiter.js +116 -0
  119. package/srv/utils/service-events.d.ts +2 -22
  120. package/srv/utils/service-events.js +3 -23
  121. package/srv/utils/signing-helper.d.ts +3 -18
  122. package/srv/utils/signing-helper.js +10 -32
  123. package/srv/utils/tx-build-helper.d.ts +18 -92
  124. package/srv/utils/tx-build-helper.js +32 -123
  125. package/srv/utils/tx-request-parsers.d.ts +14 -20
  126. package/srv/utils/tx-request-parsers.js +33 -20
  127. package/srv/utils/tx-utils.d.ts +4 -23
  128. package/srv/utils/tx-utils.js +12 -41
  129. package/srv/utils/types.d.ts +112 -169
  130. package/srv/utils/types.js +2 -6
  131. package/srv/utils/validators.d.ts +19 -89
  132. package/srv/utils/validators.js +31 -138
@@ -4,39 +4,36 @@ 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");
16
+ const ogmios_frame_guard_1 = require("./ogmios-frame-guard");
14
17
  const mappers_1 = require("../../utils/mappers");
15
18
  const const_1 = require("../../utils/const");
16
19
  const logger = cds_1.default.log('OgmiosBackend');
17
20
  /**
18
- * First absolute slot of the given epoch, from the network's Shelley anchor.
19
- * Replaces the old `epoch * 432000` math, which was wrong on preview (86 400
20
- * 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).
21
23
  */
22
24
  function epochStartSlot(network, epoch) {
23
25
  const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[network];
24
26
  return cfg.shelleyStartSlot + (epoch - cfg.shelleyStartEpoch) * cfg.slotsPerEpoch;
25
27
  }
26
28
  /**
27
- * Absolute POSIX seconds for a slot, via the same Shelley-anchored genesis infos
28
- * the transaction builder uses for validity windows. The previous code treated
29
- * 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.
30
31
  */
31
32
  function slotToPosixSeconds(network, slot) {
32
33
  const genesis = const_1.GENESIS_INFOS_BY_NETWORK[network];
33
34
  return Math.floor((genesis.systemStartPosixMs + (slot - genesis.startSlotNo) * genesis.slotLengthMs) / 1000);
34
35
  }
35
- /**
36
- * Parse an Ogmios `Ratio` ("num/den" string, e.g. "3/1000") into a number.
37
- * `Number("3/1000")` is NaN — previously every ratio-typed protocol parameter
38
- * (priceMem, priceStep, a0, rho, tau) came out as NaN.
39
- */
36
+ /** Parse an Ogmios `Ratio` ("num/den", e.g. "3/1000") into a number; `Number("3/1000")` is NaN. */
40
37
  function parseOgmiosRatio(ratio) {
41
38
  if (ratio === null || ratio === undefined)
42
39
  return 0;
@@ -50,11 +47,7 @@ function parseOgmiosRatio(ratio) {
50
47
  const n = Number(ratio);
51
48
  return Number.isFinite(n) ? n : 0;
52
49
  }
53
- /**
54
- * Extract a lovelace amount from Ogmios' value shapes. Ogmios v6 returns
55
- * `{ ada: { lovelace } }` objects — calling `.toString()` on those yields
56
- * "[object Object]", which previously ended up in the AccountData fields.
57
- */
50
+ /** Lovelace amount from Ogmios' value shapes; v6 returns `{ ada: { lovelace } }` objects. */
58
51
  function ogmiosValueToLovelaceString(value) {
59
52
  if (value === null || value === undefined)
60
53
  return '0';
@@ -63,6 +56,21 @@ function ogmiosValueToLovelaceString(value) {
63
56
  const lovelace = value.ada?.lovelace;
64
57
  return lovelace === undefined ? '0' : String(lovelace);
65
58
  }
59
+ /**
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.
62
+ */
63
+ function decodeDrepId(drepId) {
64
+ const decoded = bech32_1.bech32.decode(drepId, const_1.BECH32_MAX_LENGTH);
65
+ const bytes = Buffer.from(bech32_1.bech32.fromWords(decoded.words));
66
+ if (decoded.prefix !== 'drep' || bytes.length !== 29) {
67
+ throw new errors_1.NotFoundError('Drep', 'ogmios');
68
+ }
69
+ return {
70
+ hashHex: bytes.subarray(1).toString('hex'),
71
+ isScript: (bytes[0] & 0x0f) === 0x03,
72
+ };
73
+ }
66
74
  /** Resolve Ogmios ledger tip which may be 'origin' (genesis block) or a point */
67
75
  function resolveOgmiosTip(tip) {
68
76
  return tip === 'origin' ? { slot: 0, hash: '' } : { slot: tip.slot, hash: tip.id };
@@ -71,15 +79,13 @@ function resolveOgmiosTip(tip) {
71
79
  function resolveOgmiosHeight(height) {
72
80
  return height === 'origin' ? 0 : height;
73
81
  }
82
+ /** CardanoBackend implementation over an Ogmios WebSocket (local node). */
74
83
  class OgmiosBackend {
75
84
  name = 'ogmios';
76
85
  /**
77
- * Capability declaration — the orchestrator skips Ogmios for these without
78
- * counting circuit failures. Historic queries are out of protocol scope;
79
- * getAddress/getNetworkInformation previously FABRICATED placeholder data
80
- * (type:'base'/isScript:false/stakeAddress:null resp. maxSupply as
81
- * total/circulating) which preferLive routing then preferred over correct
82
- * 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.
83
89
  */
84
90
  unsupportedMethods = new Set([
85
91
  // getEpoch is NOT listed: Ogmios can serve the CURRENT epoch and only
@@ -88,7 +94,8 @@ class OgmiosBackend {
88
94
  'getTransaction',
89
95
  'getTransactionMetadata',
90
96
  'getAddressTransactions',
91
- 'getDrep',
97
+ // getDrep is NOT listed: served from the live ledger state via
98
+ // queryLedgerState/delegateRepresentatives (Ogmios ≥ 6.4).
92
99
  'getAssetInfo',
93
100
  'getAddress',
94
101
  'getNetworkInformation',
@@ -101,9 +108,6 @@ class OgmiosBackend {
101
108
  network;
102
109
  timeoutMs;
103
110
  ogmiosUrl;
104
- /**
105
- * Constructor
106
- */
107
111
  constructor(network, timeoutMs, ogmiosUrl) {
108
112
  if (!ogmiosUrl) {
109
113
  throw new errors_1.BackendInitError('ogmios', new Error('ogmiosUrl is not set'));
@@ -113,21 +117,9 @@ class OgmiosBackend {
113
117
  this.ogmiosUrl = ogmiosUrl;
114
118
  }
115
119
  /**
116
- * Force fresh (non-keep-alive) HTTP connections for the Ogmios `/health` probe.
117
- *
118
- * createInteractionContext() opens the WebSocket, but FIRST probes
119
- * `GET http://<ogmios>/health` via the library's `cross-fetch` → node-fetch v2
120
- * → Node-core `http`. Since Node 19, `http.globalAgent` defaults to
121
- * keepAlive:true, so node-fetch reuses pooled sockets. Against Ogmios' Warp
122
- * server on Node 22/24 a reused socket the server has already half-closed
123
- * yields "Invalid response body … Premature close" the instant the body is
124
- * read — deterministically (Node 20's older http client tolerated it; `curl`
125
- * does too, so the /health response itself is well-formed and the node is
126
- * healthy). The lib pins cross-fetch even in 7.0 and exposes no way to inject
127
- * an agent into that internal fetch, so we neutralise keep-alive process-wide
128
- * for `http://`. Blast radius is tiny: the only `http://` consumer is the local
129
- * Ogmios probe — Blockfrost/Koios run over `https` with their own axios agents
130
- * 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.
131
123
  */
132
124
  static keepAliveDisabled = false;
133
125
  static disableHttpKeepAlive() {
@@ -155,17 +147,12 @@ class OgmiosBackend {
155
147
  }
156
148
  }
157
149
  /**
158
- * Bound an init step in time. A hung WebSocket connect/handshake (e.g. the
159
- * node is alive but too busy catching up to answer) would otherwise block
160
- * forever — there is no built-in connect timeout — hanging the whole
161
- * app-context bootstrap (seen as a 6h CI job timeout). On timeout we reject
162
- * with a message containing "timeout" so the orchestrator's transient-error
163
- * 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.
164
153
  */
165
154
  withInitTimeout(p, label) {
166
- // Keep this SHORT: the orchestrator retries init a few times within the
167
- // integration suite's 20s cds.test() hook, so each attempt must be brief.
168
- // Still bounds a genuinely hung connect in production.
155
+ // Short on purpose: the orchestrator retries init several times within a bounded bootstrap window.
169
156
  const ms = Math.max(1, Math.min(this.timeoutMs, 4000));
170
157
  let timer;
171
158
  const timeout = new Promise((_, reject) => {
@@ -175,10 +162,8 @@ class OgmiosBackend {
175
162
  return Promise.race([p, timeout]).finally(() => clearTimeout(timer));
176
163
  }
177
164
  /**
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.
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.
182
167
  */
183
168
  forceCloseContext(context) {
184
169
  const socket = context.socket;
@@ -194,9 +179,7 @@ class OgmiosBackend {
194
179
  // Best effort only: the socket may already have completed its close event.
195
180
  }
196
181
  }
197
- /**
198
- * Initialize the Ogmios backend connection
199
- */
182
+ /** Open the interaction context and the query/submission clients. */
200
183
  async init() {
201
184
  OgmiosBackend.disableHttpKeepAlive();
202
185
  OgmiosBackend.validateOgmiosUrl(this.ogmiosUrl);
@@ -209,9 +192,7 @@ class OgmiosBackend {
209
192
  const context = await this.withInitTimeout((0, client_1.createInteractionContext)(
210
193
  /* c8 ignore next */
211
194
  (err) => logger.error(`[OgmiosBackend] Interaction context error: ${err.message}`), () => {
212
- // Socket closed: clear the clients so the next request reconnects via
213
- // ensureConnected — previously this handler only logged and the backend
214
- // stayed dead until process restart.
195
+ // Socket closed: clear the clients so the next request reconnects via ensureConnected.
215
196
  if (this.isShutdown)
216
197
  return;
217
198
  logger.warn('[OgmiosBackend] WebSocket closed — will reconnect on next request');
@@ -235,10 +216,8 @@ class OgmiosBackend {
235
216
  return true;
236
217
  }
237
218
  /**
238
- * Reconnect when the WebSocket has died since the last successful init.
239
- * No-op when never initialized (test-injected clients) — startup-init
240
- * recovery is the orchestrator's job (lazy init retry in CardanoClient).
241
- * 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.
242
221
  */
243
222
  async ensureConnected() {
244
223
  this.ensureNotShutdown();
@@ -274,13 +253,11 @@ class OgmiosBackend {
274
253
  async getEpoch(epochNumber) {
275
254
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
276
255
  await this.ensureConnected();
277
- // Get current epoch directly via epoch() query
278
256
  const currentEpoch = await this.stateQueryClient.epoch();
279
257
  // Ogmios only supports current epoch queries
280
258
  if (epochNumber !== currentEpoch) {
281
259
  throw new errors_1.NotFoundError(`Historic Epoch ${epochNumber} not supported (current: ${currentEpoch})`, this.name);
282
260
  }
283
- // Return current epoch data
284
261
  return this.getLatestEpoch();
285
262
  }, this.name);
286
263
  }
@@ -305,13 +282,50 @@ class OgmiosBackend {
305
282
  }, this.name);
306
283
  }
307
284
  /**
308
- * Get specific Drep Data (not supported for Ogmios)
309
- * @param _drepId drep id
310
- * @returns {Promise<DrepData>} drep data
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.
288
+ * @param drepId CIP-129 bech32 DRep ID (`drep1…`)
311
289
  */
312
- async getDrep(_drepId) {
290
+ async getDrep(drepId) {
313
291
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
314
- throw new errors_1.ProviderUnavailableError('DRep queries not supported by Ogmios backend', this.name);
292
+ await this.ensureConnected();
293
+ if (!this.context) {
294
+ throw new errors_1.ProviderUnavailableError('Ogmios interaction context not available', this.name);
295
+ }
296
+ const { hashHex, isScript } = decodeDrepId(drepId);
297
+ const [summaries, currentEpoch] = await Promise.all([
298
+ (0, client_1.Method)({
299
+ method: 'queryLedgerState/delegateRepresentatives',
300
+ params: isScript ? { scripts: [hashHex] } : { keys: [hashHex] },
301
+ }, {
302
+ handler: (response, resolve, reject) => {
303
+ if (response.error) {
304
+ reject(new Error(response.error.message ?? `Ogmios error ${response.error.code ?? ''}`.trim()));
305
+ }
306
+ else {
307
+ resolve(Array.isArray(response.result) ? response.result : []);
308
+ }
309
+ },
310
+ }, this.context),
311
+ this.stateQueryClient.epoch(),
312
+ ]);
313
+ // Filter by id: the query is already credential-scoped, but never trust a
314
+ // broader answer (abstain/noConfidence rows carry no id and are dropped here).
315
+ const drep = summaries.find((s) => s.type === 'registered' && s.id?.toLowerCase() === hashHex);
316
+ if (!drep)
317
+ throw new errors_1.NotFoundError('Drep', this.name);
318
+ const mandateEpoch = drep.mandate?.epoch;
319
+ return {
320
+ drepId,
321
+ hex: hashHex,
322
+ amount: ogmiosValueToLovelaceString(drep.stake),
323
+ hasScript: isScript || drep.from === 'script',
324
+ // Ogmios reports the mandate (expiry) epoch, not the last activity — keep 0.
325
+ lastActiveEpoch: 0,
326
+ expired: typeof mandateEpoch === 'number' && mandateEpoch < Number(currentEpoch),
327
+ retired: false,
328
+ };
315
329
  }, this.name);
316
330
  }
317
331
  /**
@@ -324,22 +338,15 @@ class OgmiosBackend {
324
338
  throw new errors_1.ProviderUnavailableError('Asset info queries not supported by Ogmios backend', this.name);
325
339
  }, this.name);
326
340
  }
327
- /**
328
- * Get specific Network Information (not supported — Ogmios state queries
329
- * expose no supply/stake aggregates; the previous implementation fabricated
330
- * maxSupply as total/circulating, which preferLive routing then preferred
331
- * over correct Blockfrost/Koios data)
332
- */
341
+ /** Not supported — Ogmios state queries expose no supply/stake aggregates. */
333
342
  async getNetworkInformation() {
334
343
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
335
344
  throw new errors_1.ProviderUnavailableError('Network information not supported by Ogmios backend — use Blockfrost/Koios', this.name);
336
345
  }, this.name);
337
346
  }
338
347
  /**
339
- * Get current specific Address Data (not supported — address type, script
340
- * flag and stake address are not derivable from Ogmios state queries; the
341
- * previous implementation fabricated type:'base'/isScript:false/
342
- * 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.
343
350
  */
344
351
  async getAddress(_address) {
345
352
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
@@ -354,30 +361,53 @@ class OgmiosBackend {
354
361
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
355
362
  await this.ensureConnected();
356
363
  const utxos = await this.stateQueryClient.utxo({ addresses: [address] });
357
- return utxos.map((u) => {
358
- // convert Ogmios value format to standard amount array
359
- const amount = this.convertOgmiosValue(u.value);
360
- return {
361
- txHash: u.transaction?.id || '',
362
- outputIndex: u.index || 0,
363
- address: u.address || address,
364
- amount: amount,
365
- blockHash: '',
366
- datumHash: u.datumHash,
367
- // Ogmios delivers the inline datum as CBOR hex in `datum` — it was
368
- // dropped before, breaking inline-datum spends when Ogmios serves UTxOs
369
- inlineDatum: typeof u.datum === 'string' ? u.datum : null,
370
- scriptRef: u.script?.hash
371
- };
372
- });
364
+ return utxos.map((u) => this.mapOgmiosUtxo(u, address));
373
365
  }, this.name);
374
366
  }
367
+ /** Ogmios `Utxo` entry → normalized UTxO line (shared by the address query and the set import). */
368
+ mapOgmiosUtxo(u, fallbackAddress = '') {
369
+ return {
370
+ txHash: u.transaction?.id || '',
371
+ outputIndex: u.index || 0,
372
+ address: u.address || fallbackAddress,
373
+ amount: this.convertOgmiosValue(u.value),
374
+ blockHash: '',
375
+ datumHash: u.datumHash,
376
+ // Ogmios delivers the inline datum as CBOR hex in `datum`
377
+ inlineDatum: typeof u.datum === 'string' ? u.datum : null,
378
+ scriptRef: u.script?.hash,
379
+ };
380
+ }
375
381
  /**
376
- * Get Address Transactions (not supported by Ogmios - use historical backend)
377
- * Ogmios is a live state query backend and does not provide historical transaction data
378
- * @param _address bech32 address
379
- * @returns {Promise<Transaction[]>} always throws - use historical backend instead
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.
380
385
  */
386
+ async queryUtxoSetAt(point) {
387
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
388
+ const url = new URL(this.ogmiosUrl);
389
+ const connection = { host: url.hostname, port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80), tls: url.protocol === 'wss:' };
390
+ const context = await (0, client_1.createInteractionContext)((err) => logger.error(`[OgmiosBackend] snapshot context error: ${err.message}`), () => { }, { connection });
391
+ let client = null;
392
+ try {
393
+ client = await (0, client_1.createLedgerStateQueryClient)(context, { point: { slot: point.slot, id: point.hash } });
394
+ const utxos = await client.utxo();
395
+ return utxos.map((u) => this.mapOgmiosUtxo(u));
396
+ }
397
+ finally {
398
+ // shutdown() closes THIS connection only; the backend's own socket is untouched
399
+ if (client) {
400
+ try {
401
+ await client.shutdown();
402
+ }
403
+ catch { /* best effort */ }
404
+ }
405
+ else
406
+ this.forceCloseContext(context);
407
+ }
408
+ }, this.name);
409
+ }
410
+ /** Not supported — Ogmios is a live state-query backend; use Blockfrost/Koios. */
381
411
  async getAddressTransactions(_address) {
382
412
  throw new errors_1.NotFoundError('Address transactions not available via Ogmios - use historical backend (Blockfrost/Koios)', this.name);
383
413
  }
@@ -391,7 +421,7 @@ class OgmiosBackend {
391
421
  await this.ensureConnected();
392
422
  // Query from tip (no acquire needed) with stake included
393
423
  const pools = await this.stateQueryClient.stakePools([{ id: poolId }], true);
394
- // Extract pool from response - stakePools returns object keyed by poolId
424
+ // stakePools returns an object keyed by poolId
395
425
  const pool = pools[poolId];
396
426
  if (!pool)
397
427
  throw new errors_1.NotFoundError('Pool', this.name);
@@ -408,8 +438,7 @@ class OgmiosBackend {
408
438
  // of fabricating it from the pledge
409
439
  activeStake: '0',
410
440
  activeSize: 0,
411
- // pledge/cost are ValueAdaOnly objects in Ogmios v6 — String() on those
412
- // 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")
413
442
  pledge: ogmiosValueToLovelaceString(pool.pledge),
414
443
  margin: parseOgmiosRatio(pool.margin),
415
444
  fixedCost: ogmiosValueToLovelaceString(pool.cost),
@@ -430,7 +459,6 @@ class OgmiosBackend {
430
459
  const summaries = Array.isArray(rawResult)
431
460
  ? rawResult
432
461
  : Object.values(rawResult);
433
- // Ogmios API returns array of account summaries
434
462
  const account = summaries && summaries.length > 0 ? summaries[0] : null;
435
463
  if (!account) {
436
464
  throw new errors_1.NotFoundError('Account', this.name);
@@ -516,7 +544,7 @@ class OgmiosBackend {
516
544
  eMax: params.stakePoolRetirementEpochBound || 0,
517
545
  nOpt: params.desiredNumberOfStakePools || 0,
518
546
  a0: parseOgmiosRatio(params.stakePoolPledgeInfluence),
519
- // ρ = monetaryExpansion, τ = treasuryExpansion (was swapped; Koios maps it correctly)
547
+ // ρ = monetaryExpansion, τ = treasuryExpansion
520
548
  rho: parseOgmiosRatio(params.monetaryExpansion),
521
549
  tau: parseOgmiosRatio(params.treasuryExpansion),
522
550
  decentralisationParam: 0,
@@ -572,7 +600,7 @@ class OgmiosBackend {
572
600
  ]);
573
601
  const { slot, hash } = resolveOgmiosTip(tip);
574
602
  const height = resolveOgmiosHeight(blockHeight);
575
- // network-aware slot-in-epoch (the old `slot % 432000` was wrong on every network)
603
+ // network-aware slot-in-epoch
576
604
  const epochSlot = Math.max(0, slot - epochStartSlot(this.network, epoch));
577
605
  return {
578
606
  time: slotToPosixSeconds(this.network, slot), // seconds (mapBlock expects seconds)
@@ -600,11 +628,9 @@ class OgmiosBackend {
600
628
  return block.slot;
601
629
  }
602
630
  /**
603
- * Check whether a UTxO is still unspent via Ogmios `queryLedgerState/utxo`
604
- * with an outputReferences filter. Empty result means spent or nonexistent.
631
+ * Unspent check via `queryLedgerState/utxo` with an outputReferences filter; empty = spent or nonexistent.
605
632
  * @param txHash 64-char lowercase hex
606
633
  * @param outputIndex non-negative integer
607
- * @returns {Promise<boolean>} true iff the UTxO exists and is unspent
608
634
  */
609
635
  async isUtxoUnspent(txHash, outputIndex) {
610
636
  if (!Number.isInteger(outputIndex) || outputIndex < 0)
@@ -617,10 +643,7 @@ class OgmiosBackend {
617
643
  return Array.isArray(result) && result.length > 0;
618
644
  }, this.name);
619
645
  }
620
- /**
621
- * Shutdown the Ogmios Backend
622
- * Closes all connections and marks as shutdown
623
- */
646
+ /** Close the WebSocket and mark the backend as shut down. */
624
647
  async shutdown() {
625
648
  if (this.isShutdown)
626
649
  return;
@@ -643,9 +666,6 @@ class OgmiosBackend {
643
666
  this.txSubmissionClient = null;
644
667
  this.context = null;
645
668
  }
646
- /**
647
- * Check if backend is connected
648
- */
649
669
  isConnected() {
650
670
  if (this.isShutdown || !this.context?.socket) {
651
671
  return false;
@@ -656,29 +676,23 @@ class OgmiosBackend {
656
676
  // ---------------------------------------------------------------------------
657
677
  // Helpers
658
678
  // ---------------------------------------------------------------------------
659
- /**
660
- * Ensure the client is not shutdown before operations
661
- */
662
679
  ensureNotShutdown() {
663
680
  if (this.isShutdown) {
664
681
  throw new errors_1.ProviderUnavailableError('Ogmios client has been shutdown', this.name);
665
682
  }
666
683
  }
667
684
  /**
668
- * Convert Ogmios value format to odatano amount array
669
- * Ogmios: { ada: { lovelace: 1000000 }, policyId: { assetName: quantity } }
670
- * 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 }]`.
671
687
  */
672
688
  convertOgmiosValue(value) {
673
689
  const amounts = [];
674
- // Handle ADA (lovelace)
675
690
  if (value.ada?.lovelace) {
676
691
  amounts.push({
677
692
  unit: 'lovelace',
678
693
  quantity: value.ada.lovelace.toString()
679
694
  });
680
695
  }
681
- // handle native assets (policy.assetName)
682
696
  for (const [policyId, assets] of Object.entries(value)) {
683
697
  if (policyId === 'ada')
684
698
  continue;
@@ -692,20 +706,12 @@ class OgmiosBackend {
692
706
  return amounts;
693
707
  }
694
708
  // ---------------------------------------------------------------------------
695
- // ChainSyncBackend — streamed forward sync for the chain crawler (v2.0)
709
+ // ChainSyncBackend — streamed forward sync for the chain crawler
696
710
  // ---------------------------------------------------------------------------
697
711
  /**
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.
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.
709
715
  */
710
716
  async openChainSync(from, callbacks) {
711
717
  OgmiosBackend.validateOgmiosUrl(this.ogmiosUrl);
@@ -731,6 +737,12 @@ class OgmiosBackend {
731
737
  logger.error('[OgmiosBackend] chain-sync onError callback failed:', callbackError);
732
738
  }
733
739
  };
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 }) => {
744
+ void reportStreamError(new errors_1.ChainSyncFrameError(height, id, reason));
745
+ });
734
746
  const contextPromise = (0, client_1.createInteractionContext)((err) => {
735
747
  logger.error(`[OgmiosBackend] chain-sync context error: ${err.message}`);
736
748
  void reportStreamError(err);
@@ -750,14 +762,13 @@ class OgmiosBackend {
750
762
  // A timeout rejects our race but cannot cancel the library's health probe /
751
763
  // handshake. If it resolves later, close that late socket as well.
752
764
  intentionalClose = true;
765
+ unregisterFrameGuard();
753
766
  void contextPromise.then(lateContext => this.forceCloseContext(lateContext)).catch(() => undefined);
754
767
  throw err;
755
768
  }
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.
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.
761
772
  const handlers = {
762
773
  rollForward: async ({ block, tip }, nextBlock) => {
763
774
  try {
@@ -802,6 +813,7 @@ class OgmiosBackend {
802
813
  }
803
814
  catch (err) {
804
815
  intentionalClose = true;
816
+ unregisterFrameGuard();
805
817
  if (client) {
806
818
  try {
807
819
  await this.withInitTimeout(client.shutdown(), 'chainSync/failedOpenShutdown');
@@ -819,6 +831,7 @@ class OgmiosBackend {
819
831
  // Idempotency matters when an operator stop races an onError-triggered halt.
820
832
  if (!closePromise) {
821
833
  intentionalClose = true;
834
+ unregisterFrameGuard();
822
835
  closePromise = (async () => {
823
836
  try {
824
837
  await this.withInitTimeout(client.shutdown(), 'chainSync/shutdown');
@@ -834,17 +847,16 @@ class OgmiosBackend {
834
847
  };
835
848
  }
836
849
  /**
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).
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.
840
853
  */
841
854
  mapOgmiosBlock(block) {
842
855
  const txs = (block.transactions ?? []).map((t, i) => this.mapOgmiosTx(t, block, i));
843
856
  const totalFees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n);
844
857
  const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[this.network];
845
858
  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
859
+ // Shelley-anchored helper (handles preview/preprod geometry and the Byron offset)
848
860
  const epochSlot = block.slot - epochStartSlot(this.network, epoch);
849
861
  const blockData = {
850
862
  time: slotToPosixSeconds(this.network, block.slot),
@@ -861,11 +873,9 @@ class OgmiosBackend {
861
873
  return { block: blockData, txs };
862
874
  }
863
875
  /**
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.
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.
869
879
  */
870
880
  mapOgmiosTx(tx, block, index) {
871
881
  const mapInput = (input, flags = {}) => ({
@@ -905,14 +915,23 @@ class OgmiosBackend {
905
915
  json: v.json,
906
916
  }))
907
917
  : [];
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.
920
+ const declaredFee = (tx.fee?.ada?.lovelace ?? 0).toString();
921
+ const totalCollateral = tx.totalCollateral ? tx.totalCollateral.ada.lovelace.toString() : null;
908
922
  return {
909
923
  hash: tx.id,
910
924
  blockHash: block.id,
911
925
  blockHeight: block.height,
912
926
  slot: block.slot,
913
927
  index,
914
- fee: (tx.fee?.ada?.lovelace ?? 0).toString(),
928
+ fee: spendsCollaterals ? (totalCollateral ?? declaredFee) : declaredFee,
929
+ spendsCollaterals,
930
+ totalCollateral,
915
931
  deposit: '0',
932
+ // The ledger applies no mint when the script phase failed: the body's mint field is
933
+ // declared but never enacted, so a phase-2 failure must report none at all.
934
+ mint: spendsCollaterals ? undefined : this.convertOgmiosValue(tx.mint ?? {}),
916
935
  // null = unknown (chain-sync doesn't surface the serialized size) — matches the
917
936
  // lazy path's `size ?? null` convention; 0 would masquerade as a real size
918
937
  size: null,
@@ -922,8 +941,77 @@ class OgmiosBackend {
922
941
  // undefined (not []) when absent — matches the Blockfrost path so
923
942
  // mapTransaction's hasMetadata flag stays false for metadata-less txs
924
943
  metadata: metadataEntries.length ? metadataEntries : undefined,
944
+ certificates: this.mapOgmiosCertificates(tx.certificates ?? []),
945
+ withdrawals: Object.entries(tx.withdrawals ?? {}).map(([stakeAddress, value]) => ({
946
+ stakeAddress,
947
+ amount: (value?.ada?.lovelace ?? 0).toString(),
948
+ })),
925
949
  };
926
950
  }
951
+ /**
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.
955
+ */
956
+ mapOgmiosCertificates(certs) {
957
+ const out = [];
958
+ const lovelace = (v) => v?.ada?.lovelace != null ? v.ada.lovelace.toString() : null;
959
+ const stakeAddr = (c) => c.credential ? (0, mappers_1.credentialToStakeAddress)(c.credential, c.from === 'script', this.network) : null;
960
+ const drepId = (d) => {
961
+ if (!d)
962
+ return null;
963
+ if (d.type === 'abstain')
964
+ return 'drep_always_abstain';
965
+ if (d.type === 'noConfidence')
966
+ return 'drep_always_no_confidence';
967
+ return d.id ? (0, mappers_1.credentialToDrepId)(d.id, d.from === 'script') : null;
968
+ };
969
+ certs.forEach((c, certIndex) => {
970
+ switch (c.type) {
971
+ case 'stakeCredentialRegistration':
972
+ out.push({ certIndex, kind: 'stake_registration', stakeAddress: stakeAddr(c), deposit: lovelace(c.deposit) });
973
+ break;
974
+ case 'stakeCredentialDeregistration':
975
+ out.push({ certIndex, kind: 'stake_deregistration', stakeAddress: stakeAddr(c), deposit: lovelace(c.deposit) });
976
+ break;
977
+ case 'stakeDelegation': {
978
+ const stakeAddress = stakeAddr(c);
979
+ if (c.stakePool?.id)
980
+ out.push({ certIndex, kind: 'pool_delegation', stakeAddress, poolId: c.stakePool.id });
981
+ if (c.delegateRepresentative)
982
+ out.push({ certIndex, kind: 'vote_delegation', stakeAddress, drepId: drepId(c.delegateRepresentative) });
983
+ break;
984
+ }
985
+ case 'stakePoolRegistration':
986
+ out.push({ certIndex, kind: 'pool_registration', poolId: c.stakePool?.id ?? null });
987
+ break;
988
+ case 'stakePoolRetirement':
989
+ out.push({ certIndex, kind: 'pool_retirement', poolId: c.stakePool?.id ?? null, epoch: c.stakePool?.retirementEpoch ?? null });
990
+ break;
991
+ case 'delegateRepresentativeRegistration':
992
+ out.push({ certIndex, kind: 'drep_registration', drepId: drepId(c.delegateRepresentative), deposit: lovelace(c.deposit) });
993
+ break;
994
+ case 'delegateRepresentativeUpdate':
995
+ out.push({ certIndex, kind: 'drep_update', drepId: drepId(c.delegateRepresentative) });
996
+ break;
997
+ case 'delegateRepresentativeRetirement':
998
+ out.push({ certIndex, kind: 'drep_retirement', drepId: drepId(c.delegateRepresentative), deposit: lovelace(c.deposit) });
999
+ break;
1000
+ case 'constitutionalCommitteeDelegation':
1001
+ out.push({ certIndex, kind: 'committee_hot_auth' });
1002
+ break;
1003
+ case 'constitutionalCommitteeRetirement':
1004
+ out.push({ certIndex, kind: 'committee_resign' });
1005
+ break;
1006
+ case 'genesisDelegation':
1007
+ out.push({ certIndex, kind: 'genesis_delegation' });
1008
+ break;
1009
+ default:
1010
+ out.push({ certIndex, kind: c.type });
1011
+ }
1012
+ });
1013
+ return out;
1014
+ }
927
1015
  }
928
1016
  exports.OgmiosBackend = OgmiosBackend;
929
1017
  //# sourceMappingURL=ogmios-backend.js.map