@odatano/core 2.0.0-rc.2 → 2.0.0-rc.21

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 (138) 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 +231 -6
  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 +323 -6
  10. package/@cds-models/odatano/cardano/index.js +33 -0
  11. package/README.md +195 -136
  12. package/db/schema.cds +2133 -1633
  13. package/package.json +181 -173
  14. package/scripts/migrate-slot-leader.mjs +104 -0
  15. package/scripts/migrate-txseq.mjs +147 -0
  16. package/src/index.d.ts +10 -10
  17. package/src/index.js +24 -14
  18. package/src/plugin.js +39 -52
  19. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  20. package/srv/blockchain/backends/blockfrost-backend.js +45 -158
  21. package/srv/blockchain/backends/cardano-backend.d.ts +83 -158
  22. package/srv/blockchain/backends/cardano-backend.js +14 -5
  23. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  24. package/srv/blockchain/backends/koios-backend.js +293 -203
  25. package/srv/blockchain/backends/ogmios-backend.d.ts +69 -94
  26. package/srv/blockchain/backends/ogmios-backend.js +319 -185
  27. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  28. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  29. package/srv/blockchain/cardano-client.d.ts +57 -204
  30. package/srv/blockchain/cardano-client.js +94 -226
  31. package/srv/blockchain/cardano-indexer.d.ts +176 -240
  32. package/srv/blockchain/cardano-indexer.js +615 -338
  33. package/srv/blockchain/cardano-tx-builder.d.ts +29 -82
  34. package/srv/blockchain/cardano-tx-builder.js +88 -128
  35. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  36. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  37. package/srv/blockchain/crawler/crawler.d.ts +121 -53
  38. package/srv/blockchain/crawler/crawler.js +403 -89
  39. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  40. package/srv/blockchain/crawler/index.d.ts +5 -0
  41. package/srv/blockchain/crawler/index.js +35 -7
  42. package/srv/blockchain/crawler/sync-state.d.ts +44 -28
  43. package/srv/blockchain/crawler/sync-state.js +115 -43
  44. package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
  45. package/srv/blockchain/crawler/utxo-set-import.js +269 -0
  46. package/srv/blockchain/ledger-state.d.ts +80 -0
  47. package/srv/blockchain/ledger-state.js +383 -0
  48. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  49. package/srv/blockchain/signing/cose-verifier.js +6 -12
  50. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  51. package/srv/blockchain/signing/external-signer.js +19 -122
  52. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  53. package/srv/blockchain/signing/hsm-signer.js +23 -63
  54. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  55. package/srv/blockchain/signing/signature-verifier.js +13 -54
  56. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  57. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  58. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
  59. package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
  60. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  61. package/srv/blockchain/transaction-rows.d.ts +12 -0
  62. package/srv/blockchain/transaction-rows.js +42 -0
  63. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  64. package/srv/blockchain/wallet-worker/build-request.js +39 -23
  65. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  66. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  67. package/srv/blockchain/wallet-worker/index.js +2 -8
  68. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  69. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  70. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  71. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  72. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  73. package/srv/blockchain/wallet-worker/signers.js +3 -8
  74. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  75. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  76. package/srv/cardano-agent-service.cds +146 -0
  77. package/srv/cardano-agent-service.d.ts +2 -0
  78. package/srv/cardano-agent-service.js +12 -0
  79. package/srv/cardano-indexer-service.cds +164 -73
  80. package/srv/cardano-indexer-service.js +156 -11
  81. package/srv/cardano-service.cds +45 -0
  82. package/srv/cardano-service.js +38 -96
  83. package/srv/cardano-sign-service.cds +200 -180
  84. package/srv/cardano-sign-service.js +55 -173
  85. package/srv/cardano-tx-service.cds +32 -26
  86. package/srv/cardano-tx-service.js +136 -196
  87. package/srv/cardano-worker-service.js +7 -15
  88. package/srv/server.d.ts +28 -86
  89. package/srv/server.js +95 -128
  90. package/srv/utils/agent-grants-config.d.ts +37 -0
  91. package/srv/utils/agent-grants-config.js +138 -0
  92. package/srv/utils/agent-grants.d.ts +262 -0
  93. package/srv/utils/agent-grants.js +914 -0
  94. package/srv/utils/agent-token-auth.d.ts +16 -0
  95. package/srv/utils/agent-token-auth.js +78 -0
  96. package/srv/utils/backend-request-handler.d.ts +2 -16
  97. package/srv/utils/backend-request-handler.js +3 -18
  98. package/srv/utils/collections.d.ts +4 -8
  99. package/srv/utils/collections.js +4 -8
  100. package/srv/utils/const.d.ts +19 -68
  101. package/srv/utils/const.js +20 -69
  102. package/srv/utils/crypto.d.ts +3 -12
  103. package/srv/utils/crypto.js +5 -18
  104. package/srv/utils/db-indexes.d.ts +25 -0
  105. package/srv/utils/db-indexes.js +93 -0
  106. package/srv/utils/db-sanitize.d.ts +27 -0
  107. package/srv/utils/db-sanitize.js +85 -0
  108. package/srv/utils/epoch-slots.d.ts +13 -0
  109. package/srv/utils/epoch-slots.js +25 -0
  110. package/srv/utils/error-codes.d.ts +18 -73
  111. package/srv/utils/error-codes.js +17 -70
  112. package/srv/utils/errors.d.ts +36 -179
  113. package/srv/utils/errors.js +62 -220
  114. package/srv/utils/liveness.d.ts +16 -0
  115. package/srv/utils/liveness.js +41 -0
  116. package/srv/utils/mappers.d.ts +89 -214
  117. package/srv/utils/mappers.js +289 -301
  118. package/srv/utils/network-context.js +2 -11
  119. package/srv/utils/pg-order-nulls.d.ts +14 -0
  120. package/srv/utils/pg-order-nulls.js +57 -0
  121. package/srv/utils/plutus-placeholders.d.ts +6 -18
  122. package/srv/utils/plutus-placeholders.js +6 -20
  123. package/srv/utils/rate-limiter.d.ts +46 -0
  124. package/srv/utils/rate-limiter.js +116 -0
  125. package/srv/utils/service-events.d.ts +2 -22
  126. package/srv/utils/service-events.js +3 -23
  127. package/srv/utils/signing-helper.d.ts +3 -18
  128. package/srv/utils/signing-helper.js +10 -32
  129. package/srv/utils/tx-build-helper.d.ts +18 -92
  130. package/srv/utils/tx-build-helper.js +32 -123
  131. package/srv/utils/tx-request-parsers.d.ts +14 -20
  132. package/srv/utils/tx-request-parsers.js +33 -20
  133. package/srv/utils/tx-utils.d.ts +4 -23
  134. package/srv/utils/tx-utils.js +12 -41
  135. package/srv/utils/types.d.ts +114 -169
  136. package/srv/utils/types.js +2 -6
  137. package/srv/utils/validators.d.ts +19 -89
  138. package/srv/utils/validators.js +31 -138
@@ -4,39 +4,24 @@ 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.ogmiosScriptHash = ogmiosScriptHash;
8
+ exports.issuerKeyToPoolId = issuerKeyToPoolId;
9
+ exports.decodeDrepId = decodeDrepId;
7
10
  exports.resolveOgmiosTip = resolveOgmiosTip;
8
11
  exports.resolveOgmiosHeight = resolveOgmiosHeight;
9
12
  const cds_1 = __importDefault(require("@sap/cds"));
10
13
  const node_http_1 = __importDefault(require("node:http"));
11
14
  const client_1 = require("@cardano-ogmios/client");
15
+ const bech32_1 = require("bech32");
16
+ const crypto_1 = require("@harmoniclabs/crypto");
12
17
  const backend_request_handler_1 = require("../../utils/backend-request-handler");
13
18
  const errors_1 = require("../../utils/errors");
19
+ const ogmios_frame_guard_1 = require("./ogmios-frame-guard");
20
+ const epoch_slots_1 = require("../../utils/epoch-slots");
14
21
  const mappers_1 = require("../../utils/mappers");
15
22
  const const_1 = require("../../utils/const");
16
23
  const logger = cds_1.default.log('OgmiosBackend');
17
- /**
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
- */
22
- function epochStartSlot(network, epoch) {
23
- const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[network];
24
- return cfg.shelleyStartSlot + (epoch - cfg.shelleyStartEpoch) * cfg.slotsPerEpoch;
25
- }
26
- /**
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.
30
- */
31
- function slotToPosixSeconds(network, slot) {
32
- const genesis = const_1.GENESIS_INFOS_BY_NETWORK[network];
33
- return Math.floor((genesis.systemStartPosixMs + (slot - genesis.startSlotNo) * genesis.slotLengthMs) / 1000);
34
- }
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
- */
24
+ /** Parse an Ogmios `Ratio` ("num/den", e.g. "3/1000") into a number; `Number("3/1000")` is NaN. */
40
25
  function parseOgmiosRatio(ratio) {
41
26
  if (ratio === null || ratio === undefined)
42
27
  return 0;
@@ -50,11 +35,32 @@ function parseOgmiosRatio(ratio) {
50
35
  const n = Number(ratio);
51
36
  return Number.isFinite(n) ? n : 0;
52
37
  }
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
- */
38
+ const SCRIPT_LANGUAGE_TAG = { native: 0, 'plutus:v1': 1, 'plutus:v2': 2, 'plutus:v3': 3 };
39
+ /** Hash of an Ogmios `Script`: blake2b-224 over the language tag byte followed by the script CBOR. */
40
+ function ogmiosScriptHash(script) {
41
+ const s = script;
42
+ const tag = s?.language === undefined ? undefined : SCRIPT_LANGUAGE_TAG[s.language];
43
+ if (tag === undefined || typeof s?.cbor !== 'string' || s.cbor.length === 0)
44
+ return null;
45
+ const bytes = Uint8Array.from(Buffer.concat([Buffer.from([tag]), Buffer.from(s.cbor, 'hex')]));
46
+ return Buffer.from((0, crypto_1.blake2b_224)(bytes)).toString('hex');
47
+ }
48
+ /** Bech32 pool id of a block issuer: blake2b-224 of its cold verification key. */
49
+ function issuerKeyToPoolId(verificationKeyHex) {
50
+ const keyHash = (0, crypto_1.blake2b_224)(Uint8Array.from(Buffer.from(verificationKeyHex, 'hex')));
51
+ return bech32_1.bech32.encode('pool', bech32_1.bech32.toWords(keyHash));
52
+ }
53
+ /** CIP-129 DRep id for a registered DRep, the predefined id for abstain / no confidence. */
54
+ function ogmiosDrepToId(d) {
55
+ if (!d)
56
+ return null;
57
+ if (d.type === 'abstain')
58
+ return 'drep_always_abstain';
59
+ if (d.type === 'noConfidence')
60
+ return 'drep_always_no_confidence';
61
+ return d.id ? (0, mappers_1.credentialToDrepId)(d.id, d.from === 'script') : null;
62
+ }
63
+ /** Lovelace amount from Ogmios' value shapes; v6 returns `{ ada: { lovelace } }` objects. */
58
64
  function ogmiosValueToLovelaceString(value) {
59
65
  if (value === null || value === undefined)
60
66
  return '0';
@@ -63,6 +69,21 @@ function ogmiosValueToLovelaceString(value) {
63
69
  const lovelace = value.ada?.lovelace;
64
70
  return lovelace === undefined ? '0' : String(lovelace);
65
71
  }
72
+ /**
73
+ * Decode a CIP-129 DRep ID (`drep1…`, 29 bytes) into credential hash and type. Header byte:
74
+ * high nibble 0x2 = DRep, low nibble 0x2 = key hash / 0x3 = script hash.
75
+ */
76
+ function decodeDrepId(drepId) {
77
+ const decoded = bech32_1.bech32.decode(drepId, const_1.BECH32_MAX_LENGTH);
78
+ const bytes = Buffer.from(bech32_1.bech32.fromWords(decoded.words));
79
+ if (decoded.prefix !== 'drep' || bytes.length !== 29) {
80
+ throw new errors_1.NotFoundError('Drep', 'ogmios');
81
+ }
82
+ return {
83
+ hashHex: bytes.subarray(1).toString('hex'),
84
+ isScript: (bytes[0] & 0x0f) === 0x03,
85
+ };
86
+ }
66
87
  /** Resolve Ogmios ledger tip which may be 'origin' (genesis block) or a point */
67
88
  function resolveOgmiosTip(tip) {
68
89
  return tip === 'origin' ? { slot: 0, hash: '' } : { slot: tip.slot, hash: tip.id };
@@ -71,15 +92,13 @@ function resolveOgmiosTip(tip) {
71
92
  function resolveOgmiosHeight(height) {
72
93
  return height === 'origin' ? 0 : height;
73
94
  }
95
+ /** CardanoBackend implementation over an Ogmios WebSocket (local node). */
74
96
  class OgmiosBackend {
75
97
  name = 'ogmios';
76
98
  /**
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.
99
+ * Capability declaration — the orchestrator skips Ogmios for these without counting
100
+ * circuit failures. Historic queries are out of protocol scope, and address aggregates
101
+ * cannot be derived from state queries.
83
102
  */
84
103
  unsupportedMethods = new Set([
85
104
  // getEpoch is NOT listed: Ogmios can serve the CURRENT epoch and only
@@ -88,10 +107,10 @@ class OgmiosBackend {
88
107
  'getTransaction',
89
108
  'getTransactionMetadata',
90
109
  'getAddressTransactions',
91
- 'getDrep',
110
+ // getDrep is NOT listed: served from the live ledger state via
111
+ // queryLedgerState/delegateRepresentatives (Ogmios ≥ 6.4).
92
112
  'getAssetInfo',
93
113
  'getAddress',
94
- 'getNetworkInformation',
95
114
  ]);
96
115
  stateQueryClient = null;
97
116
  txSubmissionClient = null;
@@ -101,9 +120,6 @@ class OgmiosBackend {
101
120
  network;
102
121
  timeoutMs;
103
122
  ogmiosUrl;
104
- /**
105
- * Constructor
106
- */
107
123
  constructor(network, timeoutMs, ogmiosUrl) {
108
124
  if (!ogmiosUrl) {
109
125
  throw new errors_1.BackendInitError('ogmios', new Error('ogmiosUrl is not set'));
@@ -113,21 +129,9 @@ class OgmiosBackend {
113
129
  this.ogmiosUrl = ogmiosUrl;
114
130
  }
115
131
  /**
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.
132
+ * Force non-keep-alive HTTP for the Ogmios `/health` probe: node-fetch v2 uses `http.globalAgent`,
133
+ * whose pooled sockets (kept alive since Node 19) fail with "Premature close" once Ogmios' Warp server
134
+ * half-closes them. No agent hook exists, so keep-alive is disabled process-wide for `http://` only.
131
135
  */
132
136
  static keepAliveDisabled = false;
133
137
  static disableHttpKeepAlive() {
@@ -155,17 +159,12 @@ class OgmiosBackend {
155
159
  }
156
160
  }
157
161
  /**
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.
162
+ * Bound an init step in time: the WebSocket connect/handshake has no built-in timeout and
163
+ * can hang when the node is busy. The rejection message contains "timeout" so the
164
+ * orchestrator's transient-error retry picks it up.
164
165
  */
165
166
  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.
167
+ // Short on purpose: the orchestrator retries init several times within a bounded bootstrap window.
169
168
  const ms = Math.max(1, Math.min(this.timeoutMs, 4000));
170
169
  let timer;
171
170
  const timeout = new Promise((_, reject) => {
@@ -175,10 +174,8 @@ class OgmiosBackend {
175
174
  return Promise.race([p, timeout]).finally(() => clearTimeout(timer));
176
175
  }
177
176
  /**
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.
177
+ * Force-release an interaction socket after a failed/expired open or close. The runtime
178
+ * socket is `ws` (has `terminate`); the `close` fallback keeps test doubles working.
182
179
  */
183
180
  forceCloseContext(context) {
184
181
  const socket = context.socket;
@@ -194,9 +191,7 @@ class OgmiosBackend {
194
191
  // Best effort only: the socket may already have completed its close event.
195
192
  }
196
193
  }
197
- /**
198
- * Initialize the Ogmios backend connection
199
- */
194
+ /** Open the interaction context and the query/submission clients. */
200
195
  async init() {
201
196
  OgmiosBackend.disableHttpKeepAlive();
202
197
  OgmiosBackend.validateOgmiosUrl(this.ogmiosUrl);
@@ -209,9 +204,7 @@ class OgmiosBackend {
209
204
  const context = await this.withInitTimeout((0, client_1.createInteractionContext)(
210
205
  /* c8 ignore next */
211
206
  (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.
207
+ // Socket closed: clear the clients so the next request reconnects via ensureConnected.
215
208
  if (this.isShutdown)
216
209
  return;
217
210
  logger.warn('[OgmiosBackend] WebSocket closed — will reconnect on next request');
@@ -235,10 +228,8 @@ class OgmiosBackend {
235
228
  return true;
236
229
  }
237
230
  /**
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.
231
+ * Reconnect when the WebSocket died since the last init. No-op when never initialized
232
+ * (test-injected clients); concurrent callers share one reconnect attempt.
242
233
  */
243
234
  async ensureConnected() {
244
235
  this.ensureNotShutdown();
@@ -274,13 +265,11 @@ class OgmiosBackend {
274
265
  async getEpoch(epochNumber) {
275
266
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
276
267
  await this.ensureConnected();
277
- // Get current epoch directly via epoch() query
278
268
  const currentEpoch = await this.stateQueryClient.epoch();
279
269
  // Ogmios only supports current epoch queries
280
270
  if (epochNumber !== currentEpoch) {
281
271
  throw new errors_1.NotFoundError(`Historic Epoch ${epochNumber} not supported (current: ${currentEpoch})`, this.name);
282
272
  }
283
- // Return current epoch data
284
273
  return this.getLatestEpoch();
285
274
  }, this.name);
286
275
  }
@@ -305,13 +294,50 @@ class OgmiosBackend {
305
294
  }, this.name);
306
295
  }
307
296
  /**
308
- * Get specific Drep Data (not supported for Ogmios)
309
- * @param _drepId drep id
310
- * @returns {Promise<DrepData>} drep data
297
+ * DRep data from the live ledger state (`queryLedgerState/delegateRepresentatives`) via the
298
+ * raw `Method()` primitive, since the client ships no wrapper. Ogmios lists only REGISTERED
299
+ * DReps: retired/unknown → NotFoundError; `expired` is derived from the mandate epoch.
300
+ * @param drepId CIP-129 bech32 DRep ID (`drep1…`)
311
301
  */
312
- async getDrep(_drepId) {
302
+ async getDrep(drepId) {
313
303
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
314
- throw new errors_1.ProviderUnavailableError('DRep queries not supported by Ogmios backend', this.name);
304
+ await this.ensureConnected();
305
+ if (!this.context) {
306
+ throw new errors_1.ProviderUnavailableError('Ogmios interaction context not available', this.name);
307
+ }
308
+ const { hashHex, isScript } = decodeDrepId(drepId);
309
+ const [summaries, currentEpoch] = await Promise.all([
310
+ (0, client_1.Method)({
311
+ method: 'queryLedgerState/delegateRepresentatives',
312
+ params: isScript ? { scripts: [hashHex] } : { keys: [hashHex] },
313
+ }, {
314
+ handler: (response, resolve, reject) => {
315
+ if (response.error) {
316
+ reject(new Error(response.error.message ?? `Ogmios error ${response.error.code ?? ''}`.trim()));
317
+ }
318
+ else {
319
+ resolve(Array.isArray(response.result) ? response.result : []);
320
+ }
321
+ },
322
+ }, this.context),
323
+ this.stateQueryClient.epoch(),
324
+ ]);
325
+ // Filter by id: the query is already credential-scoped, but never trust a
326
+ // broader answer (abstain/noConfidence rows carry no id and are dropped here).
327
+ const drep = summaries.find((s) => s.type === 'registered' && s.id?.toLowerCase() === hashHex);
328
+ if (!drep)
329
+ throw new errors_1.NotFoundError('Drep', this.name);
330
+ const mandateEpoch = drep.mandate?.epoch;
331
+ return {
332
+ drepId,
333
+ hex: hashHex,
334
+ amount: ogmiosValueToLovelaceString(drep.stake),
335
+ hasScript: isScript || drep.from === 'script',
336
+ // Ogmios reports the mandate (expiry) epoch, not the last activity — keep 0.
337
+ lastActiveEpoch: 0,
338
+ expired: typeof mandateEpoch === 'number' && mandateEpoch < Number(currentEpoch),
339
+ retired: false,
340
+ };
315
341
  }, this.name);
316
342
  }
317
343
  /**
@@ -325,21 +351,43 @@ class OgmiosBackend {
325
351
  }, this.name);
326
352
  }
327
353
  /**
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)
354
+ * Supply figures from `queryLedgerState/treasuryAndReserves`: total = max − reserves.
355
+ * Circulating, locked and stake totals are not in the ledger state and stay '0'.
332
356
  */
333
357
  async getNetworkInformation() {
334
358
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
335
- throw new errors_1.ProviderUnavailableError('Network information not supported by Ogmios backend — use Blockfrost/Koios', this.name);
359
+ await this.ensureConnected();
360
+ if (!this.context) {
361
+ throw new errors_1.ProviderUnavailableError('Ogmios interaction context not available', this.name);
362
+ }
363
+ const pots = await (0, client_1.Method)({ method: 'queryLedgerState/treasuryAndReserves' }, {
364
+ handler: (response, resolve, reject) => {
365
+ if (response.error) {
366
+ reject(new Error(response.error.message ?? `Ogmios error ${response.error.code ?? ''}`.trim()));
367
+ }
368
+ else {
369
+ resolve(response.result ?? {});
370
+ }
371
+ },
372
+ }, this.context);
373
+ const max = const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY;
374
+ const reserves = ogmiosValueToLovelaceString(pots.reserves);
375
+ return {
376
+ supply: {
377
+ max,
378
+ total: (BigInt(max) - BigInt(reserves)).toString(),
379
+ circulating: '0',
380
+ locked: '0',
381
+ treasury: ogmiosValueToLovelaceString(pots.treasury),
382
+ reserves,
383
+ },
384
+ stake: { live: '0', active: '0' },
385
+ };
336
386
  }, this.name);
337
387
  }
338
388
  /**
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.)
389
+ * Not supported — address type, script flag and stake address are not derivable from
390
+ * state queries. UTxOs remain available via getAddressUtxos.
343
391
  */
344
392
  async getAddress(_address) {
345
393
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
@@ -354,30 +402,53 @@ class OgmiosBackend {
354
402
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
355
403
  await this.ensureConnected();
356
404
  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
- });
405
+ return utxos.map((u) => this.mapOgmiosUtxo(u, address));
373
406
  }, this.name);
374
407
  }
408
+ /** Ogmios `Utxo` entry → normalized UTxO line (shared by the address query and the set import). */
409
+ mapOgmiosUtxo(u, fallbackAddress = '') {
410
+ return {
411
+ txHash: u.transaction?.id || '',
412
+ outputIndex: u.index || 0,
413
+ address: u.address || fallbackAddress,
414
+ amount: this.convertOgmiosValue(u.value),
415
+ blockHash: '',
416
+ datumHash: u.datumHash,
417
+ // Ogmios delivers the inline datum as CBOR hex in `datum`
418
+ inlineDatum: typeof u.datum === 'string' ? u.datum : null,
419
+ scriptRef: ogmiosScriptHash(u.script) ?? undefined,
420
+ };
421
+ }
375
422
  /**
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
423
+ * Whole UTxO set as of `point` (crawler snapshot import) on a SEPARATE WebSocket: local-state-query
424
+ * holds one acquired point per connection, so the shared socket would pin live queries to the past.
425
+ * The point must be inside the node's volatile window (last 2160 blocks) or acquisition is refused.
380
426
  */
427
+ async queryUtxoSetAt(point) {
428
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
429
+ const url = new URL(this.ogmiosUrl);
430
+ const connection = { host: url.hostname, port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80), tls: url.protocol === 'wss:' };
431
+ const context = await (0, client_1.createInteractionContext)((err) => logger.error(`[OgmiosBackend] snapshot context error: ${err.message}`), () => { }, { connection });
432
+ let client = null;
433
+ try {
434
+ client = await (0, client_1.createLedgerStateQueryClient)(context, { point: { slot: point.slot, id: point.hash } });
435
+ const utxos = await client.utxo();
436
+ return utxos.map((u) => this.mapOgmiosUtxo(u));
437
+ }
438
+ finally {
439
+ // shutdown() closes THIS connection only; the backend's own socket is untouched
440
+ if (client) {
441
+ try {
442
+ await client.shutdown();
443
+ }
444
+ catch { /* best effort */ }
445
+ }
446
+ else
447
+ this.forceCloseContext(context);
448
+ }
449
+ }, this.name);
450
+ }
451
+ /** Not supported — Ogmios is a live state-query backend; use Blockfrost/Koios. */
381
452
  async getAddressTransactions(_address) {
382
453
  throw new errors_1.NotFoundError('Address transactions not available via Ogmios - use historical backend (Blockfrost/Koios)', this.name);
383
454
  }
@@ -391,15 +462,16 @@ class OgmiosBackend {
391
462
  await this.ensureConnected();
392
463
  // Query from tip (no acquire needed) with stake included
393
464
  const pools = await this.stateQueryClient.stakePools([{ id: poolId }], true);
394
- // Extract pool from response - stakePools returns object keyed by poolId
465
+ // stakePools returns an object keyed by poolId
395
466
  const pool = pools[poolId];
396
467
  if (!pool)
397
468
  throw new errors_1.NotFoundError('Pool', this.name);
398
469
  return {
399
470
  poolId,
400
- vrfKeyHash: pool.vrf || pool.vrfKeyHash || '',
471
+ vrfKeyHash: pool.vrfVerificationKeyHash || '',
401
472
  blocksMinted: 0,
402
- blocksEpoch: 0,
473
+ // not in the ledger state; null = unavailable, as on Koios
474
+ blocksEpoch: null,
403
475
  liveStake: pool.stake?.ada?.lovelace ? String(pool.stake.ada.lovelace) : '0',
404
476
  liveSize: 0,
405
477
  liveDelegators: 0,
@@ -408,8 +480,7 @@ class OgmiosBackend {
408
480
  // of fabricating it from the pledge
409
481
  activeStake: '0',
410
482
  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")
483
+ // pledge/cost are ValueAdaOnly objects in Ogmios v6; margin is a Ratio string ("1/10")
413
484
  pledge: ogmiosValueToLovelaceString(pool.pledge),
414
485
  margin: parseOgmiosRatio(pool.margin),
415
486
  fixedCost: ogmiosValueToLovelaceString(pool.cost),
@@ -430,7 +501,6 @@ class OgmiosBackend {
430
501
  const summaries = Array.isArray(rawResult)
431
502
  ? rawResult
432
503
  : Object.values(rawResult);
433
- // Ogmios API returns array of account summaries
434
504
  const account = summaries && summaries.length > 0 ? summaries[0] : null;
435
505
  if (!account) {
436
506
  throw new errors_1.NotFoundError('Account', this.name);
@@ -441,14 +511,15 @@ class OgmiosBackend {
441
511
  // reaching this point (summary found) therefore implies the account is active.
442
512
  active: true,
443
513
  activeEpoch: 0,
444
- controlledAmount: ogmiosValueToLovelaceString(account.controlledAmount),
514
+ // reward-account summaries carry no controlled amount and no withdrawal totals
515
+ controlledAmount: '0',
445
516
  rewardsSum: ogmiosValueToLovelaceString(account.rewards),
446
- withdrawalsSum: ogmiosValueToLovelaceString(account.withdrawals),
517
+ withdrawalsSum: '0',
447
518
  reservesSum: '0',
448
519
  treasurySum: '0',
449
520
  withdrawableAmount: ogmiosValueToLovelaceString(account.rewards),
450
- poolId: account.delegate?.id || account.delegation?.poolId || null,
451
- drepId: account.vote?.id || account.drep?.id || null,
521
+ poolId: account.stakePool?.id || null,
522
+ drepId: ogmiosDrepToId(account.delegateRepresentative),
452
523
  addresses: []
453
524
  };
454
525
  }, this.name);
@@ -516,7 +587,7 @@ class OgmiosBackend {
516
587
  eMax: params.stakePoolRetirementEpochBound || 0,
517
588
  nOpt: params.desiredNumberOfStakePools || 0,
518
589
  a0: parseOgmiosRatio(params.stakePoolPledgeInfluence),
519
- // ρ = monetaryExpansion, τ = treasuryExpansion (was swapped; Koios maps it correctly)
590
+ // ρ = monetaryExpansion, τ = treasuryExpansion
520
591
  rho: parseOgmiosRatio(params.monetaryExpansion),
521
592
  tau: parseOgmiosRatio(params.treasuryExpansion),
522
593
  decentralisationParam: 0,
@@ -541,14 +612,14 @@ class OgmiosBackend {
541
612
  ]);
542
613
  const { slot } = resolveOgmiosTip(tip);
543
614
  // Network-aware epoch geometry + Shelley-anchored slot→time conversion
544
- const startSlot = epochStartSlot(this.network, currentEpoch);
615
+ const startSlot = (0, epoch_slots_1.epochStartSlot)(this.network, currentEpoch);
545
616
  const endSlot = startSlot + const_1.EPOCH_CONFIG_BY_NETWORK[this.network].slotsPerEpoch;
546
617
  return {
547
618
  epoch: currentEpoch,
548
- start_time: slotToPosixSeconds(this.network, startSlot),
549
- end_time: slotToPosixSeconds(this.network, endSlot),
550
- first_block_time: slotToPosixSeconds(this.network, startSlot),
551
- last_block_time: slotToPosixSeconds(this.network, slot),
619
+ start_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, startSlot),
620
+ end_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, endSlot),
621
+ first_block_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, startSlot),
622
+ last_block_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, slot),
552
623
  block_count: 0, // Not available from Ogmios state queries
553
624
  tx_count: 0, // Not available from Ogmios state queries
554
625
  output: '0',
@@ -572,10 +643,10 @@ class OgmiosBackend {
572
643
  ]);
573
644
  const { slot, hash } = resolveOgmiosTip(tip);
574
645
  const height = resolveOgmiosHeight(blockHeight);
575
- // network-aware slot-in-epoch (the old `slot % 432000` was wrong on every network)
576
- const epochSlot = Math.max(0, slot - epochStartSlot(this.network, epoch));
646
+ // network-aware slot-in-epoch
647
+ const epochSlot = Math.max(0, slot - (0, epoch_slots_1.epochStartSlot)(this.network, epoch));
577
648
  return {
578
- time: slotToPosixSeconds(this.network, slot), // seconds (mapBlock expects seconds)
649
+ time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, slot), // seconds (mapBlock expects seconds)
579
650
  height,
580
651
  hash,
581
652
  slot,
@@ -585,6 +656,7 @@ class OgmiosBackend {
585
656
  size: 0, // Not available via ledgerTip - would need full block data
586
657
  txCount: 0, // Not available via ledgerTip - would need full block data
587
658
  fees: '0', // Not available via ledgerTip - would need full block data
659
+ headerOnly: true,
588
660
  };
589
661
  }, this.name);
590
662
  }
@@ -600,11 +672,9 @@ class OgmiosBackend {
600
672
  return block.slot;
601
673
  }
602
674
  /**
603
- * Check whether a UTxO is still unspent via Ogmios `queryLedgerState/utxo`
604
- * with an outputReferences filter. Empty result means spent or nonexistent.
675
+ * Unspent check via `queryLedgerState/utxo` with an outputReferences filter; empty = spent or nonexistent.
605
676
  * @param txHash 64-char lowercase hex
606
677
  * @param outputIndex non-negative integer
607
- * @returns {Promise<boolean>} true iff the UTxO exists and is unspent
608
678
  */
609
679
  async isUtxoUnspent(txHash, outputIndex) {
610
680
  if (!Number.isInteger(outputIndex) || outputIndex < 0)
@@ -617,10 +687,19 @@ class OgmiosBackend {
617
687
  return Array.isArray(result) && result.length > 0;
618
688
  }, this.name);
619
689
  }
620
- /**
621
- * Shutdown the Ogmios Backend
622
- * Closes all connections and marks as shutdown
623
- */
690
+ /** Outputs among `refs` that are unspent in the live ledger; spent or unknown references are absent. */
691
+ async getUnspentOutputs(refs) {
692
+ if (refs.length === 0)
693
+ return [];
694
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
695
+ await this.ensureConnected();
696
+ const result = await this.stateQueryClient.utxo({
697
+ outputReferences: refs.map(r => ({ transaction: { id: r.txHash }, index: r.outputIndex })),
698
+ });
699
+ return result.map((u) => this.mapOgmiosUtxo(u));
700
+ }, this.name);
701
+ }
702
+ /** Close the WebSocket and mark the backend as shut down. */
624
703
  async shutdown() {
625
704
  if (this.isShutdown)
626
705
  return;
@@ -643,9 +722,6 @@ class OgmiosBackend {
643
722
  this.txSubmissionClient = null;
644
723
  this.context = null;
645
724
  }
646
- /**
647
- * Check if backend is connected
648
- */
649
725
  isConnected() {
650
726
  if (this.isShutdown || !this.context?.socket) {
651
727
  return false;
@@ -656,29 +732,23 @@ class OgmiosBackend {
656
732
  // ---------------------------------------------------------------------------
657
733
  // Helpers
658
734
  // ---------------------------------------------------------------------------
659
- /**
660
- * Ensure the client is not shutdown before operations
661
- */
662
735
  ensureNotShutdown() {
663
736
  if (this.isShutdown) {
664
737
  throw new errors_1.ProviderUnavailableError('Ogmios client has been shutdown', this.name);
665
738
  }
666
739
  }
667
740
  /**
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' }]
741
+ * Ogmios value `{ ada: { lovelace }, policyId: { assetName: qty } }` →
742
+ * `[{ unit: 'lovelace', quantity }, { unit: policyId+assetName, quantity }]`.
671
743
  */
672
744
  convertOgmiosValue(value) {
673
745
  const amounts = [];
674
- // Handle ADA (lovelace)
675
746
  if (value.ada?.lovelace) {
676
747
  amounts.push({
677
748
  unit: 'lovelace',
678
749
  quantity: value.ada.lovelace.toString()
679
750
  });
680
751
  }
681
- // handle native assets (policy.assetName)
682
752
  for (const [policyId, assets] of Object.entries(value)) {
683
753
  if (policyId === 'ada')
684
754
  continue;
@@ -692,20 +762,12 @@ class OgmiosBackend {
692
762
  return amounts;
693
763
  }
694
764
  // ---------------------------------------------------------------------------
695
- // ChainSyncBackend — streamed forward sync for the chain crawler (v2.0)
765
+ // ChainSyncBackend — streamed forward sync for the chain crawler
696
766
  // ---------------------------------------------------------------------------
697
767
  /**
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.
768
+ * Open a long-lived chain-sync stream on its own WebSocket. `sequential: true` + `inFlight: 1`
769
+ * deliver blocks strictly in order (required by reorg detection and serial persist). Inputs arrive
770
+ * as bare references (resolved by the indexer from indexed outputs); per-tx size/deposit are not surfaced.
709
771
  */
710
772
  async openChainSync(from, callbacks) {
711
773
  OgmiosBackend.validateOgmiosUrl(this.ogmiosUrl);
@@ -731,6 +793,12 @@ class OgmiosBackend {
731
793
  logger.error('[OgmiosBackend] chain-sync onError callback failed:', callbackError);
732
794
  }
733
795
  };
796
+ // A frame the client's parser cannot handle throws inside the library's un-awaited socket
797
+ // handler and would end the process; the guard routes it here as a stream error instead.
798
+ // Registered per open and removed on close, so concurrent streams each get the report.
799
+ const unregisterFrameGuard = (0, ogmios_frame_guard_1.installOgmiosFrameGuard)(({ height, id, reason }) => {
800
+ void reportStreamError(new errors_1.ChainSyncFrameError(height, id, reason));
801
+ });
734
802
  const contextPromise = (0, client_1.createInteractionContext)((err) => {
735
803
  logger.error(`[OgmiosBackend] chain-sync context error: ${err.message}`);
736
804
  void reportStreamError(err);
@@ -750,14 +818,13 @@ class OgmiosBackend {
750
818
  // A timeout rejects our race but cannot cancel the library's health probe /
751
819
  // handshake. If it resolves later, close that late socket as well.
752
820
  intentionalClose = true;
821
+ unregisterFrameGuard();
753
822
  void contextPromise.then(lateContext => this.forceCloseContext(lateContext)).catch(() => undefined);
754
823
  throw err;
755
824
  }
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.
825
+ // Both handlers are fully try/caught: the client awaits them without a catch, and with
826
+ // sequential+inFlight:1 a throw before nextBlock() stalls the stream. On error nextBlock()
827
+ // is deliberately NOT called (stop, don't skip a block); the error goes to callbacks.onError.
761
828
  const handlers = {
762
829
  rollForward: async ({ block, tip }, nextBlock) => {
763
830
  try {
@@ -802,6 +869,7 @@ class OgmiosBackend {
802
869
  }
803
870
  catch (err) {
804
871
  intentionalClose = true;
872
+ unregisterFrameGuard();
805
873
  if (client) {
806
874
  try {
807
875
  await this.withInitTimeout(client.shutdown(), 'chainSync/failedOpenShutdown');
@@ -819,6 +887,7 @@ class OgmiosBackend {
819
887
  // Idempotency matters when an operator stop races an onError-triggered halt.
820
888
  if (!closePromise) {
821
889
  intentionalClose = true;
890
+ unregisterFrameGuard();
822
891
  closePromise = (async () => {
823
892
  try {
824
893
  await this.withInitTimeout(client.shutdown(), 'chainSync/shutdown');
@@ -834,24 +903,22 @@ class OgmiosBackend {
834
903
  };
835
904
  }
836
905
  /**
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).
906
+ * Map an Ogmios Praos block to BlockData + transactions. Block fees are the sum of per-tx
907
+ * fees; epoch/epochSlot derive from the slot via the Shelley anchor. A phase-2 failure without
908
+ * `total_collateral` still carries its declared fee here; applyCollateralFees() corrects it.
840
909
  */
841
910
  mapOgmiosBlock(block) {
842
911
  const txs = (block.transactions ?? []).map((t, i) => this.mapOgmiosTx(t, block, i));
843
912
  const totalFees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n);
844
- const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[this.network];
845
- const epoch = cfg.shelleyStartEpoch + Math.floor((block.slot - cfg.shelleyStartSlot) / cfg.slotsPerEpoch);
846
- // reuse the Shelley-anchored helper (carries the preview/preprod/Byron-offset fix)
847
- // instead of a second inline modulo formula
848
- const epochSlot = block.slot - epochStartSlot(this.network, epoch);
913
+ const epoch = (0, epoch_slots_1.epochOfSlot)(this.network, block.slot);
914
+ // Shelley-anchored helpers (handle preview/preprod geometry and the Byron offset)
915
+ const epochSlot = block.slot - (0, epoch_slots_1.epochStartSlot)(this.network, epoch);
849
916
  const blockData = {
850
- time: slotToPosixSeconds(this.network, block.slot),
917
+ time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, block.slot),
851
918
  height: block.height,
852
919
  hash: block.id,
853
920
  slot: block.slot,
854
- slotLeader: block.issuer?.verificationKey ?? '',
921
+ slotLeader: block.issuer?.verificationKey ? issuerKeyToPoolId(block.issuer.verificationKey) : '',
855
922
  epoch,
856
923
  epochSlot,
857
924
  size: block.size?.bytes ?? 0,
@@ -861,11 +928,9 @@ class OgmiosBackend {
861
928
  return { block: blockData, txs };
862
929
  }
863
930
  /**
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.
931
+ * Map one chain-sync transaction. Inputs stay bare references (resolved by the indexer).
932
+ * `spends` selects the ledger-applied partition: a phase-2-invalid tx consumes collaterals
933
+ * and creates only its collateral-return output; the fee follows that partition too.
869
934
  */
870
935
  mapOgmiosTx(tx, block, index) {
871
936
  const mapInput = (input, flags = {}) => ({
@@ -889,7 +954,7 @@ class OgmiosBackend {
889
954
  dataHash: output.datumHash ?? null,
890
955
  inlineDatum: output.datum ?? null,
891
956
  isCollateral,
892
- referenceScriptHash: null,
957
+ referenceScriptHash: ogmiosScriptHash(output.script),
893
958
  });
894
959
  const outputs = spendsCollaterals
895
960
  ? (tx.collateralReturn
@@ -905,25 +970,94 @@ class OgmiosBackend {
905
970
  json: v.json,
906
971
  }))
907
972
  : [];
973
+ // A phase-2 failure pays `total_collateral`, not the declared fee; the body often omits it,
974
+ // so the indexer derives the rest from the resolved collateral inputs later.
975
+ const declaredFee = (tx.fee?.ada?.lovelace ?? 0).toString();
976
+ const totalCollateral = tx.totalCollateral ? tx.totalCollateral.ada.lovelace.toString() : null;
908
977
  return {
909
978
  hash: tx.id,
910
979
  blockHash: block.id,
911
980
  blockHeight: block.height,
912
981
  slot: block.slot,
913
982
  index,
914
- fee: (tx.fee?.ada?.lovelace ?? 0).toString(),
983
+ fee: spendsCollaterals ? (totalCollateral ?? declaredFee) : declaredFee,
984
+ spendsCollaterals,
985
+ totalCollateral,
915
986
  deposit: '0',
987
+ // The ledger applies no mint when the script phase failed: the body's mint field is
988
+ // declared but never enacted, so a phase-2 failure must report none at all.
989
+ mint: spendsCollaterals ? undefined : this.convertOgmiosValue(tx.mint ?? {}),
916
990
  // null = unknown (chain-sync doesn't surface the serialized size) — matches the
917
991
  // lazy path's `size ?? null` convention; 0 would masquerade as a real size
918
992
  size: null,
919
- blockTime: slotToPosixSeconds(this.network, block.slot),
993
+ blockTime: (0, epoch_slots_1.slotToPosixSeconds)(this.network, block.slot),
920
994
  inputs,
921
995
  outputs,
922
996
  // undefined (not []) when absent — matches the Blockfrost path so
923
997
  // mapTransaction's hasMetadata flag stays false for metadata-less txs
924
998
  metadata: metadataEntries.length ? metadataEntries : undefined,
999
+ certificates: this.mapOgmiosCertificates(tx.certificates ?? []),
1000
+ withdrawals: Object.entries(tx.withdrawals ?? {}).map(([stakeAddress, value]) => ({
1001
+ stakeAddress,
1002
+ amount: (value?.ada?.lovelace ?? 0).toString(),
1003
+ })),
925
1004
  };
926
1005
  }
1006
+ /**
1007
+ * Normalize Ogmios certificates onto the shared `CertificateKind` vocabulary. A `stakeDelegation`
1008
+ * with both pool and DRep target is split into two entries with the same index (as db-sync
1009
+ * reports it); bare credential hashes are re-encoded as bech32 to match the other tables.
1010
+ */
1011
+ mapOgmiosCertificates(certs) {
1012
+ const out = [];
1013
+ const lovelace = (v) => v?.ada?.lovelace != null ? v.ada.lovelace.toString() : null;
1014
+ const stakeAddr = (c) => c.credential ? (0, mappers_1.credentialToStakeAddress)(c.credential, c.from === 'script', this.network) : null;
1015
+ certs.forEach((c, certIndex) => {
1016
+ switch (c.type) {
1017
+ case 'stakeCredentialRegistration':
1018
+ out.push({ certIndex, kind: 'stake_registration', stakeAddress: stakeAddr(c), deposit: lovelace(c.deposit) });
1019
+ break;
1020
+ case 'stakeCredentialDeregistration':
1021
+ out.push({ certIndex, kind: 'stake_deregistration', stakeAddress: stakeAddr(c), deposit: lovelace(c.deposit) });
1022
+ break;
1023
+ case 'stakeDelegation': {
1024
+ const stakeAddress = stakeAddr(c);
1025
+ if (c.stakePool?.id)
1026
+ out.push({ certIndex, kind: 'pool_delegation', stakeAddress, poolId: c.stakePool.id });
1027
+ if (c.delegateRepresentative)
1028
+ out.push({ certIndex, kind: 'vote_delegation', stakeAddress, drepId: ogmiosDrepToId(c.delegateRepresentative) });
1029
+ break;
1030
+ }
1031
+ case 'stakePoolRegistration':
1032
+ out.push({ certIndex, kind: 'pool_registration', poolId: c.stakePool?.id ?? null });
1033
+ break;
1034
+ case 'stakePoolRetirement':
1035
+ out.push({ certIndex, kind: 'pool_retirement', poolId: c.stakePool?.id ?? null, epoch: c.stakePool?.retirementEpoch ?? null });
1036
+ break;
1037
+ case 'delegateRepresentativeRegistration':
1038
+ out.push({ certIndex, kind: 'drep_registration', drepId: ogmiosDrepToId(c.delegateRepresentative), deposit: lovelace(c.deposit) });
1039
+ break;
1040
+ case 'delegateRepresentativeUpdate':
1041
+ out.push({ certIndex, kind: 'drep_update', drepId: ogmiosDrepToId(c.delegateRepresentative) });
1042
+ break;
1043
+ case 'delegateRepresentativeRetirement':
1044
+ out.push({ certIndex, kind: 'drep_retirement', drepId: ogmiosDrepToId(c.delegateRepresentative), deposit: lovelace(c.deposit) });
1045
+ break;
1046
+ case 'constitutionalCommitteeDelegation':
1047
+ out.push({ certIndex, kind: 'committee_hot_auth' });
1048
+ break;
1049
+ case 'constitutionalCommitteeRetirement':
1050
+ out.push({ certIndex, kind: 'committee_resign' });
1051
+ break;
1052
+ case 'genesisDelegation':
1053
+ out.push({ certIndex, kind: 'genesis_delegation' });
1054
+ break;
1055
+ default:
1056
+ out.push({ certIndex, kind: c.type });
1057
+ }
1058
+ });
1059
+ return out;
1060
+ }
927
1061
  }
928
1062
  exports.OgmiosBackend = OgmiosBackend;
929
1063
  //# sourceMappingURL=ogmios-backend.js.map