@odatano/core 2.0.0-rc.5 → 2.0.0-rc.51

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 (239) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +358 -0
  4. package/@cds-models/CardanoBackendService/index.js +41 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
  6. package/@cds-models/CardanoIndexerService/index.js +74 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +417 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +45 -19
  10. package/@cds-models/CardanoSignService/index.js +4 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
  12. package/@cds-models/CardanoTransactionService/index.js +5 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
  14. package/@cds-models/CardanoWorkerService/index.js +2 -0
  15. package/@cds-models/index.d.ts +114 -4
  16. package/@cds-models/index.js +20 -4
  17. package/@cds-models/odatano/cardano/index.d.ts +451 -32
  18. package/@cds-models/odatano/cardano/index.js +48 -0
  19. package/README.md +103 -167
  20. package/db/schema.cds +2455 -1705
  21. package/db/types.cds +456 -295
  22. package/package.json +41 -53
  23. package/scripts/deploy-schema.mjs +113 -0
  24. package/scripts/migrate-schema.mjs +528 -0
  25. package/scripts/migrate-slot-leader.mjs +96 -0
  26. package/src/index.d.ts +20 -21
  27. package/src/index.js +45 -31
  28. package/src/plugin.js +17 -35
  29. package/srv/blockchain/asset-decimals.d.ts +7 -0
  30. package/srv/blockchain/asset-decimals.js +91 -0
  31. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
  32. package/srv/blockchain/backends/blockfrost-backend.js +125 -215
  33. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  34. package/srv/blockchain/backends/call-signal.js +22 -0
  35. package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
  36. package/srv/blockchain/backends/cardano-backend.js +29 -5
  37. package/srv/blockchain/backends/koios-backend.d.ts +108 -170
  38. package/srv/blockchain/backends/koios-backend.js +488 -482
  39. package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
  40. package/srv/blockchain/backends/odatano-backend.js +211 -0
  41. package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
  42. package/srv/blockchain/backends/ogmios-backend.js +683 -327
  43. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  44. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  45. package/srv/blockchain/cardano-client.d.ts +71 -241
  46. package/srv/blockchain/cardano-client.js +354 -322
  47. package/srv/blockchain/cardano-indexer.d.ts +295 -283
  48. package/srv/blockchain/cardano-indexer.js +1690 -502
  49. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  50. package/srv/blockchain/cardano-tx-builder.js +164 -140
  51. package/srv/blockchain/circuit-breaker.d.ts +2 -13
  52. package/srv/blockchain/circuit-breaker.js +11 -15
  53. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  54. package/srv/blockchain/crawler/account-snapshots.js +173 -0
  55. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
  56. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  57. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
  58. package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
  59. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  60. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  61. package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
  62. package/srv/blockchain/crawler/certificate-backfill.js +174 -0
  63. package/srv/blockchain/crawler/crawler.d.ts +125 -81
  64. package/srv/blockchain/crawler/crawler.js +738 -167
  65. package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
  66. package/srv/blockchain/crawler/credential-backfill.js +101 -0
  67. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  68. package/srv/blockchain/crawler/index.d.ts +1 -8
  69. package/srv/blockchain/crawler/index.js +31 -17
  70. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  71. package/srv/blockchain/crawler/input-asset-copies.js +161 -0
  72. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  73. package/srv/blockchain/crawler/key-pages.js +48 -0
  74. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
  75. package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
  76. package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
  77. package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
  78. package/srv/blockchain/crawler/sync-state.d.ts +31 -47
  79. package/srv/blockchain/crawler/sync-state.js +135 -128
  80. package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
  81. package/srv/blockchain/crawler/transaction-backfill.js +271 -0
  82. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  83. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  84. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  85. package/srv/blockchain/crawler/window-plan.js +59 -0
  86. package/srv/blockchain/ledger-state.d.ts +62 -0
  87. package/srv/blockchain/ledger-state.js +521 -0
  88. package/srv/blockchain/pending-spends.d.ts +16 -0
  89. package/srv/blockchain/pending-spends.js +81 -0
  90. package/srv/blockchain/pool-metadata.d.ts +15 -0
  91. package/srv/blockchain/pool-metadata.js +132 -0
  92. package/srv/blockchain/request-coalescer.d.ts +2 -16
  93. package/srv/blockchain/request-coalescer.js +2 -16
  94. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  95. package/srv/blockchain/signing/cose-verifier.js +146 -70
  96. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  97. package/srv/blockchain/signing/external-signer.js +22 -131
  98. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  99. package/srv/blockchain/signing/failed-recheck.js +135 -0
  100. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  101. package/srv/blockchain/signing/hsm-signer.js +28 -79
  102. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  103. package/srv/blockchain/signing/landing-proof.js +224 -0
  104. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  105. package/srv/blockchain/signing/signature-verifier.js +71 -87
  106. package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
  107. package/srv/blockchain/signing/submission-finalizer.js +280 -86
  108. package/srv/blockchain/stored-chain.d.ts +19 -0
  109. package/srv/blockchain/stored-chain.js +258 -0
  110. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  111. package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
  112. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  113. package/srv/blockchain/transaction-presence.d.ts +12 -0
  114. package/srv/blockchain/transaction-presence.js +29 -0
  115. package/srv/blockchain/transaction-rows.d.ts +12 -0
  116. package/srv/blockchain/transaction-rows.js +44 -0
  117. package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
  118. package/srv/blockchain/wallet-worker/build-request.js +40 -353
  119. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
  120. package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
  121. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  122. package/srv/blockchain/wallet-worker/index.js +3 -11
  123. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  124. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  125. package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
  126. package/srv/blockchain/wallet-worker/job-store.js +200 -273
  127. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  128. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  129. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  130. package/srv/blockchain/wallet-worker/signers.js +4 -12
  131. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
  132. package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
  133. package/srv/cardano-agent-service.cds +122 -84
  134. package/srv/cardano-agent-service.js +12 -9
  135. package/srv/cardano-backend-service.cds +81 -0
  136. package/srv/cardano-backend-service.d.ts +2 -0
  137. package/srv/cardano-backend-service.js +259 -0
  138. package/srv/cardano-indexer-service.cds +393 -18
  139. package/srv/cardano-indexer-service.d.ts +5 -1
  140. package/srv/cardano-indexer-service.js +477 -16
  141. package/srv/cardano-service.cds +426 -269
  142. package/srv/cardano-service.js +640 -217
  143. package/srv/cardano-sign-service.cds +211 -180
  144. package/srv/cardano-sign-service.js +210 -287
  145. package/srv/cardano-tx-service.cds +462 -370
  146. package/srv/cardano-tx-service.js +283 -800
  147. package/srv/cardano-ui.cds +16 -16
  148. package/srv/cardano-worker-service.cds +141 -125
  149. package/srv/cardano-worker-service.js +104 -61
  150. package/srv/cbor/cip68.d.ts +13 -0
  151. package/srv/cbor/cip68.js +56 -0
  152. package/srv/cbor/index.d.ts +3 -1
  153. package/srv/cbor/index.js +9 -1
  154. package/srv/cbor/parse.d.ts +30 -18
  155. package/srv/cbor/parse.js +44 -9
  156. package/srv/cbor/plutus-data-json.d.ts +20 -0
  157. package/srv/cbor/plutus-data-json.js +32 -0
  158. package/srv/config.d.ts +117 -0
  159. package/srv/config.js +419 -0
  160. package/srv/server.d.ts +15 -110
  161. package/srv/server.js +83 -405
  162. package/srv/utils/agent-access.d.ts +11 -0
  163. package/srv/utils/agent-access.js +86 -0
  164. package/srv/utils/agent-grants-config.d.ts +0 -46
  165. package/srv/utils/agent-grants-config.js +17 -85
  166. package/srv/utils/agent-grants.d.ts +106 -122
  167. package/srv/utils/agent-grants.js +538 -237
  168. package/srv/utils/agent-token-auth.d.ts +4 -99
  169. package/srv/utils/agent-token-auth.js +62 -186
  170. package/srv/utils/backend-request-handler.d.ts +3 -17
  171. package/srv/utils/backend-request-handler.js +3 -18
  172. package/srv/utils/build-request.d.ts +52 -0
  173. package/srv/utils/build-request.js +487 -0
  174. package/srv/utils/collections.d.ts +4 -10
  175. package/srv/utils/collections.js +14 -10
  176. package/srv/utils/const.d.ts +32 -75
  177. package/srv/utils/const.js +40 -80
  178. package/srv/utils/crypto.d.ts +3 -12
  179. package/srv/utils/crypto.js +11 -25
  180. package/srv/utils/db-indexes.d.ts +31 -0
  181. package/srv/utils/db-indexes.js +185 -0
  182. package/srv/utils/db-kind.d.ts +23 -0
  183. package/srv/utils/db-kind.js +42 -0
  184. package/srv/utils/db-sanitize.d.ts +20 -0
  185. package/srv/utils/db-sanitize.js +80 -0
  186. package/srv/utils/deep-json.d.ts +6 -0
  187. package/srv/utils/deep-json.js +240 -0
  188. package/srv/utils/detached-run.d.ts +41 -0
  189. package/srv/utils/detached-run.js +101 -0
  190. package/srv/utils/epoch-slots.d.ts +14 -0
  191. package/srv/utils/epoch-slots.js +45 -0
  192. package/srv/utils/error-codes.d.ts +26 -75
  193. package/srv/utils/error-codes.js +27 -72
  194. package/srv/utils/errors.d.ts +55 -187
  195. package/srv/utils/errors.js +161 -235
  196. package/srv/utils/lease.d.ts +20 -0
  197. package/srv/utils/lease.js +62 -0
  198. package/srv/utils/liveness.d.ts +12 -0
  199. package/srv/utils/liveness.js +35 -0
  200. package/srv/utils/mappers.d.ts +111 -223
  201. package/srv/utils/mappers.js +432 -371
  202. package/srv/utils/navigation.d.ts +17 -0
  203. package/srv/utils/navigation.js +52 -0
  204. package/srv/utils/network-context.d.ts +0 -1
  205. package/srv/utils/network-context.js +9 -15
  206. package/srv/utils/paging.d.ts +31 -0
  207. package/srv/utils/paging.js +43 -0
  208. package/srv/utils/pg-inline-json.d.ts +8 -0
  209. package/srv/utils/pg-inline-json.js +58 -0
  210. package/srv/utils/pg-order-nulls.d.ts +14 -0
  211. package/srv/utils/pg-order-nulls.js +54 -0
  212. package/srv/utils/plutus-placeholders.d.ts +16 -22
  213. package/srv/utils/plutus-placeholders.js +62 -33
  214. package/srv/utils/rate-limiter.d.ts +2 -21
  215. package/srv/utils/rate-limiter.js +5 -17
  216. package/srv/utils/readiness.d.ts +12 -0
  217. package/srv/utils/readiness.js +29 -0
  218. package/srv/utils/reference-script.d.ts +19 -0
  219. package/srv/utils/reference-script.js +84 -0
  220. package/srv/utils/resolution.d.ts +13 -0
  221. package/srv/utils/resolution.js +47 -0
  222. package/srv/utils/result-numbers.d.ts +15 -0
  223. package/srv/utils/result-numbers.js +61 -0
  224. package/srv/utils/row-values.d.ts +7 -0
  225. package/srv/utils/row-values.js +27 -0
  226. package/srv/utils/service-events.d.ts +0 -24
  227. package/srv/utils/service-events.js +3 -25
  228. package/srv/utils/signing-helper.d.ts +3 -20
  229. package/srv/utils/signing-helper.js +35 -64
  230. package/srv/utils/tx-build-helper.d.ts +25 -105
  231. package/srv/utils/tx-build-helper.js +108 -156
  232. package/srv/utils/tx-request-parsers.d.ts +82 -33
  233. package/srv/utils/tx-request-parsers.js +401 -49
  234. package/srv/utils/tx-utils.d.ts +3 -27
  235. package/srv/utils/tx-utils.js +32 -50
  236. package/srv/utils/types.d.ts +294 -232
  237. package/srv/utils/types.js +2 -22
  238. package/srv/utils/validators.d.ts +22 -92
  239. package/srv/utils/validators.js +60 -170
@@ -4,39 +4,38 @@ 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.ogmiosPlutusScriptCbor = ogmiosPlutusScriptCbor;
9
+ exports.issuerKeyToPoolId = issuerKeyToPoolId;
10
+ exports.mapOgmiosEpochState = mapOgmiosEpochState;
11
+ exports.decodeDrepId = decodeDrepId;
7
12
  exports.resolveOgmiosTip = resolveOgmiosTip;
8
13
  exports.resolveOgmiosHeight = resolveOgmiosHeight;
9
14
  const cds_1 = __importDefault(require("@sap/cds"));
10
15
  const node_http_1 = __importDefault(require("node:http"));
11
16
  const client_1 = require("@cardano-ogmios/client");
17
+ const bech32_1 = require("bech32");
18
+ const crypto_1 = require("@harmoniclabs/crypto");
19
+ const reference_script_1 = require("../../utils/reference-script");
12
20
  const backend_request_handler_1 = require("../../utils/backend-request-handler");
13
21
  const errors_1 = require("../../utils/errors");
22
+ const tx_build_helper_1 = require("../../utils/tx-build-helper");
23
+ const ogmios_frame_guard_1 = require("./ogmios-frame-guard");
24
+ const call_signal_1 = require("./call-signal");
25
+ const epoch_slots_1 = require("../../utils/epoch-slots");
14
26
  const mappers_1 = require("../../utils/mappers");
15
27
  const const_1 = require("../../utils/const");
16
28
  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);
29
+ /** Text of a mempool refusal whose inputs are spent. The mempool error carries no structured reason. */
30
+ const MEMPOOL_SPENT_INPUTS = /inputs are spent|badinputs|already been included/i;
31
+ /** True for a refusal over spent inputs, which a resubmit of a transaction the node already holds also gets. */
32
+ function refusedForSpentInputs(code, data) {
33
+ if (code === const_1.OGMIOS_UNKNOWN_OUTPUT_REFERENCES)
34
+ return true;
35
+ const error = data?.error;
36
+ return code === const_1.OGMIOS_UNEXPECTED_MEMPOOL_ERROR && MEMPOOL_SPENT_INPUTS.test(String(error ?? ''));
34
37
  }
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
- */
38
+ /** Parse an Ogmios `Ratio` ("num/den", e.g. "3/1000") into a number; `Number("3/1000")` is NaN. */
40
39
  function parseOgmiosRatio(ratio) {
41
40
  if (ratio === null || ratio === undefined)
42
41
  return 0;
@@ -50,11 +49,40 @@ function parseOgmiosRatio(ratio) {
50
49
  const n = Number(ratio);
51
50
  return Number.isFinite(n) ? n : 0;
52
51
  }
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
- */
52
+ /** Hash of an Ogmios `Script`: blake2b-224 over the language tag byte followed by the script CBOR. */
53
+ function ogmiosScriptHash(script) {
54
+ return (0, reference_script_1.ogmiosReferenceScript)(script)?.hash ?? null;
55
+ }
56
+ /** Full CBOR of a Plutus reference script as Ogmios delivers it; null for native or absent scripts. */
57
+ function ogmiosPlutusScriptCbor(script) {
58
+ return (0, reference_script_1.ogmiosReferenceScript)(script)?.cbor ?? null;
59
+ }
60
+ /** Reference-script columns of an output or UTxO from an Ogmios `script`. */
61
+ function ogmiosReferenceScriptFields(script) {
62
+ const ref = (0, reference_script_1.ogmiosReferenceScript)(script);
63
+ return { referenceScriptHash: ref?.hash ?? null, referenceScriptSize: ref?.size ?? null, referenceScriptType: ref?.type ?? null };
64
+ }
65
+ /** Bech32 pool id of a block issuer: blake2b-224 of its cold verification key. */
66
+ function issuerKeyToPoolId(verificationKeyHex) {
67
+ const keyHash = (0, crypto_1.blake2b_224)(Uint8Array.from(Buffer.from(verificationKeyHex, 'hex')));
68
+ return bech32_1.bech32.encode('pool', bech32_1.bech32.toWords(keyHash));
69
+ }
70
+ /** CIP-129 DRep id for a registered DRep, the predefined id for abstain / no confidence. */
71
+ function ogmiosDrepToId(d) {
72
+ if (!d)
73
+ return null;
74
+ if (d.type === 'abstain')
75
+ return 'drep_always_abstain';
76
+ if (d.type === 'noConfidence')
77
+ return 'drep_always_no_confidence';
78
+ return d.id ? (0, mappers_1.credentialToDrepId)(d.id, d.from === 'script') : null;
79
+ }
80
+ // Reward balance of a summary. Ogmios 7.0 answers 0 for an account without a pool delegation,
81
+ // whatever it holds, so that balance is unknown.
82
+ function ogmiosRewardBalance(summary) {
83
+ return summary.stakePool?.id ? ogmiosValueToLovelaceString(summary.rewards) : null;
84
+ }
85
+ /** Lovelace amount from Ogmios' value shapes; v6 returns `{ ada: { lovelace } }` objects. */
58
86
  function ogmiosValueToLovelaceString(value) {
59
87
  if (value === null || value === undefined)
60
88
  return '0';
@@ -63,6 +91,91 @@ function ogmiosValueToLovelaceString(value) {
63
91
  const lovelace = value.ada?.lovelace;
64
92
  return lovelace === undefined ? '0' : String(lovelace);
65
93
  }
94
+ /** Fraction a/b of two lovelace amounts; 0 when b is 0. */
95
+ function ratio(a, b) {
96
+ return b === 0n ? 0 : Number((a * 1000000n) / b) / 1_000_000;
97
+ }
98
+ // Saturation is live stake over ((max supply - reserves) / nOpt), as in the ledger.
99
+ // Figures the ledger does not carry stay 0 or null, such as active stake and block counts.
100
+ function mapOgmiosEpochState(raw) {
101
+ const lovelace = (v) => BigInt(ogmiosValueToLovelaceString(v));
102
+ const reserves = raw.pots?.reserves ? lovelace(raw.pots.reserves) : null;
103
+ const nOpt = raw.performances?.desiredNumberOfStakePools ?? 0;
104
+ const saturationPoint = reserves != null && nOpt > 0
105
+ ? (BigInt(const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY) - reserves) / BigInt(nOpt)
106
+ : 0n;
107
+ const entries = Object.entries(raw.stakePools);
108
+ const liveTotal = entries.reduce((sum, [, p]) => sum + lovelace(p.stake), 0n);
109
+ const pools = entries.map(([poolId, p]) => {
110
+ const live = lovelace(p.stake);
111
+ return {
112
+ poolId,
113
+ vrfKeyHash: p.vrfVerificationKeyHash || '',
114
+ blocksMinted: null,
115
+ blocksEpoch: null,
116
+ liveStake: live.toString(),
117
+ liveSize: ratio(live, liveTotal),
118
+ liveSaturation: ratio(live, saturationPoint),
119
+ liveDelegators: null,
120
+ activeStake: null,
121
+ activeSize: null,
122
+ pledge: ogmiosValueToLovelaceString(p.pledge),
123
+ margin: parseOgmiosRatio(p.margin),
124
+ fixedCost: ogmiosValueToLovelaceString(p.cost),
125
+ rewardAccount: p.rewardAccount || '',
126
+ };
127
+ });
128
+ let abstain = null;
129
+ let noConfidence = null;
130
+ const dreps = [];
131
+ for (const d of raw.dreps) {
132
+ if (d.type === 'abstain') {
133
+ abstain = (abstain ?? 0n) + lovelace(d.stake);
134
+ continue;
135
+ }
136
+ if (d.type === 'noConfidence') {
137
+ noConfidence = (noConfidence ?? 0n) + lovelace(d.stake);
138
+ continue;
139
+ }
140
+ if (d.type !== 'registered' || !d.id)
141
+ continue;
142
+ const mandate = d.mandate?.epoch;
143
+ dreps.push({
144
+ drepId: (0, mappers_1.credentialToDrepId)(d.id, d.from === 'script'),
145
+ hex: d.id,
146
+ amount: ogmiosValueToLovelaceString(d.stake),
147
+ hasScript: d.from === 'script',
148
+ lastActiveEpoch: 0,
149
+ expired: typeof mandate === 'number' && mandate < raw.epoch,
150
+ retired: false,
151
+ deposit: d.deposit ? ogmiosValueToLovelaceString(d.deposit) : null,
152
+ expiresEpoch: typeof mandate === 'number' ? mandate : null,
153
+ delegatorCount: Array.isArray(d.delegators) ? d.delegators.length : null,
154
+ });
155
+ }
156
+ return {
157
+ epoch: raw.epoch,
158
+ pools,
159
+ dreps,
160
+ treasury: raw.pots?.treasury ? ogmiosValueToLovelaceString(raw.pots.treasury) : null,
161
+ reserves: reserves == null ? null : reserves.toString(),
162
+ drepAbstainStake: abstain == null ? null : abstain.toString(),
163
+ drepNoConfidenceStake: noConfidence == null ? null : noConfidence.toString(),
164
+ };
165
+ }
166
+ // Decode a CIP-129 DRep ID into credential hash and type. In the header byte the high
167
+ // nibble 0x2 means DRep. The low nibble is 0x2 for a key hash and 0x3 for a script hash.
168
+ function decodeDrepId(drepId) {
169
+ const decoded = bech32_1.bech32.decode(drepId, const_1.BECH32_MAX_LENGTH);
170
+ const bytes = Buffer.from(bech32_1.bech32.fromWords(decoded.words));
171
+ if (decoded.prefix !== 'drep' || bytes.length !== 29) {
172
+ throw new errors_1.NotFoundError('Drep', 'ogmios');
173
+ }
174
+ return {
175
+ hashHex: bytes.subarray(1).toString('hex'),
176
+ isScript: (bytes[0] & 0x0f) === 0x03,
177
+ };
178
+ }
66
179
  /** Resolve Ogmios ledger tip which may be 'origin' (genesis block) or a point */
67
180
  function resolveOgmiosTip(tip) {
68
181
  return tip === 'origin' ? { slot: 0, hash: '' } : { slot: tip.slot, hash: tip.id };
@@ -71,39 +184,52 @@ function resolveOgmiosTip(tip) {
71
184
  function resolveOgmiosHeight(height) {
72
185
  return height === 'origin' ? 0 : height;
73
186
  }
187
+ // Redeemers of a chain-sync tx. A spend index points into the inputs sorted by txHash and index.
188
+ // A mint index points into the sorted policy ids. Both are resolved here.
189
+ function mapOgmiosRedeemers(tx) {
190
+ const sortedInputs = [...(tx.inputs ?? [])].sort((a, b) => (0, mappers_1.compareOutRef)({ txHash: a.transaction.id, outputIndex: a.index }, { txHash: b.transaction.id, outputIndex: b.index }));
191
+ const sortedPolicies = Object.keys(tx.mint ?? {}).sort();
192
+ return (tx.redeemers ?? []).map((r) => {
193
+ const { purpose, index } = r.validator;
194
+ const spent = purpose === 'spend' ? sortedInputs[index] : undefined;
195
+ return {
196
+ purpose,
197
+ index,
198
+ data: r.redeemer,
199
+ mem: r.executionUnits.memory.toString(),
200
+ steps: r.executionUnits.cpu.toString(),
201
+ txHash: spent?.transaction.id ?? null,
202
+ outputIndex: spent?.index ?? null,
203
+ policyId: purpose === 'mint' ? (sortedPolicies[index] ?? null) : null,
204
+ };
205
+ });
206
+ }
74
207
  class OgmiosBackend {
75
208
  name = 'ogmios';
76
- /**
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.
83
- */
209
+ /** Ogmios cannot answer historic queries. The orchestrator skips it for these. */
84
210
  unsupportedMethods = new Set([
85
- // getEpoch is NOT listed: Ogmios can serve the CURRENT epoch and only
86
- // rejects historic ones — routing prefers historical backends anyway.
211
+ // getEpoch is not listed, because Ogmios serves the current epoch.
212
+ // Routing prefers historical backends for it anyway.
87
213
  'getBlock',
88
214
  'getTransaction',
89
215
  'getTransactionMetadata',
90
216
  'getAddressTransactions',
91
- 'getDrep',
217
+ // getDrep is NOT listed: served from the live ledger state via
218
+ // queryLedgerState/delegateRepresentatives (Ogmios ≥ 6.4).
92
219
  'getAssetInfo',
93
- 'getAddress',
94
- 'getNetworkInformation',
95
220
  ]);
96
221
  stateQueryClient = null;
97
222
  txSubmissionClient = null;
98
223
  context = null;
224
+ /** Second connection for address queries (see scanQueryClient). */
225
+ scanClient = null;
226
+ scanContext = null;
227
+ scanConnecting = null;
99
228
  isShutdown = false;
100
229
  reconnectPromise = null;
101
230
  network;
102
231
  timeoutMs;
103
232
  ogmiosUrl;
104
- /**
105
- * Constructor
106
- */
107
233
  constructor(network, timeoutMs, ogmiosUrl) {
108
234
  if (!ogmiosUrl) {
109
235
  throw new errors_1.BackendInitError('ogmios', new Error('ogmiosUrl is not set'));
@@ -112,23 +238,8 @@ class OgmiosBackend {
112
238
  this.timeoutMs = timeoutMs;
113
239
  this.ogmiosUrl = ogmiosUrl;
114
240
  }
115
- /**
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.
131
- */
241
+ // The `/health` probe uses node-fetch v2 on `http.globalAgent`. Its kept-alive sockets fail with
242
+ // "Premature close" once Ogmios half-closes them. There is no agent hook, so keep-alive is off for http.
132
243
  static keepAliveDisabled = false;
133
244
  static disableHttpKeepAlive() {
134
245
  if (OgmiosBackend.keepAliveDisabled)
@@ -141,7 +252,7 @@ class OgmiosBackend {
141
252
  const url = new URL(rawUrl);
142
253
  // Only allow WebSocket schemes (block file://, http://, etc.)
143
254
  if (url.protocol !== 'ws:' && url.protocol !== 'wss:') {
144
- throw new errors_1.BackendInitError('ogmios', new Error(`Invalid Ogmios URL scheme "${url.protocol}" — only ws:// and wss:// are allowed`));
255
+ throw new errors_1.BackendInitError('ogmios', new Error(`Invalid Ogmios URL scheme "${url.protocol}": only ws:// and wss:// are allowed`));
145
256
  }
146
257
  // In production, block link-local / metadata IPs (SSRF prevention).
147
258
  // Private/loopback IPs are allowed since Ogmios typically runs on the local node.
@@ -154,18 +265,10 @@ class OgmiosBackend {
154
265
  throw new errors_1.BackendInitError('ogmios', new Error('Ogmios URL must not point to a link-local or metadata address'));
155
266
  }
156
267
  }
157
- /**
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.
164
- */
268
+ // The WebSocket handshake has no timeout and can hang on a busy node. The rejection says
269
+ // "timeout" so the orchestrator retries it as a transient error.
165
270
  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.
271
+ // Short on purpose: the orchestrator retries init several times within a bounded bootstrap window.
169
272
  const ms = Math.max(1, Math.min(this.timeoutMs, 4000));
170
273
  let timer;
171
274
  const timeout = new Promise((_, reject) => {
@@ -174,12 +277,7 @@ class OgmiosBackend {
174
277
  });
175
278
  return Promise.race([p, timeout]).finally(() => clearTimeout(timer));
176
279
  }
177
- /**
178
- * Force-release an Ogmios interaction socket after a failed/expired open or
179
- * close step. The runtime uses `ws` (and therefore supports `terminate`), but
180
- * the close fallback keeps the helper compatible with the public structural
181
- * InteractionContext type and lightweight test doubles.
182
- */
280
+ /** Force-release a socket after a failed open or close. Test doubles without `terminate` get `close`. */
183
281
  forceCloseContext(context) {
184
282
  const socket = context.socket;
185
283
  try {
@@ -194,9 +292,7 @@ class OgmiosBackend {
194
292
  // Best effort only: the socket may already have completed its close event.
195
293
  }
196
294
  }
197
- /**
198
- * Initialize the Ogmios backend connection
199
- */
295
+ /** Open the interaction context and the query/submission clients. */
200
296
  async init() {
201
297
  OgmiosBackend.disableHttpKeepAlive();
202
298
  OgmiosBackend.validateOgmiosUrl(this.ogmiosUrl);
@@ -209,12 +305,10 @@ class OgmiosBackend {
209
305
  const context = await this.withInitTimeout((0, client_1.createInteractionContext)(
210
306
  /* c8 ignore next */
211
307
  (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.
308
+ // Socket closed: clear the clients so the next request reconnects via ensureConnected.
215
309
  if (this.isShutdown)
216
310
  return;
217
- logger.warn('[OgmiosBackend] WebSocket closed — will reconnect on next request');
311
+ logger.warn('[OgmiosBackend] WebSocket closed, will reconnect on next request');
218
312
  this.stateQueryClient = null;
219
313
  this.txSubmissionClient = null;
220
314
  }, { connection }), 'createInteractionContext');
@@ -234,12 +328,36 @@ class OgmiosBackend {
234
328
  this.context = context;
235
329
  return true;
236
330
  }
237
- /**
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.
242
- */
331
+ // Address queries scan the whole UTxO set and take seconds. Ogmios answers one connection in order,
332
+ // so they get their own connection and do not hold up tip and epoch queries.
333
+ async scanQueryClient() {
334
+ this.ensureNotShutdown();
335
+ // never initialized (test-injected clients): the shared client
336
+ if (!this.context)
337
+ return this.stateQueryClient;
338
+ const socket = this.scanContext?.socket;
339
+ if (this.scanClient && socket && socket.readyState === (socket.OPEN ?? 1))
340
+ return this.scanClient;
341
+ if (!this.scanConnecting) {
342
+ this.scanConnecting = (async () => {
343
+ const url = new URL(this.ogmiosUrl);
344
+ const connection = { host: url.hostname, port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80), tls: url.protocol === 'wss:' };
345
+ const context = await this.withInitTimeout((0, client_1.createInteractionContext)((err) => logger.error(`[OgmiosBackend] address-query context error: ${err.message}`), () => { this.scanClient = null; }, { connection }), 'scan/createInteractionContext');
346
+ try {
347
+ const client = await this.withInitTimeout((0, client_1.createLedgerStateQueryClient)(context), 'scan/ledgerStateQueryClient');
348
+ this.scanContext = context;
349
+ this.scanClient = client;
350
+ return client;
351
+ }
352
+ catch (err) {
353
+ this.forceCloseContext(context);
354
+ throw err;
355
+ }
356
+ })().finally(() => { this.scanConnecting = null; });
357
+ }
358
+ return this.scanConnecting;
359
+ }
360
+ /** Reconnect a dead WebSocket. Concurrent callers share one attempt. No-op before the first init. */
243
361
  async ensureConnected() {
244
362
  this.ensureNotShutdown();
245
363
  if (!this.context)
@@ -249,238 +367,429 @@ class OgmiosBackend {
249
367
  if (this.stateQueryClient && socketOpen)
250
368
  return;
251
369
  if (!this.reconnectPromise) {
252
- logger.warn('[OgmiosBackend] WebSocket not connected — reconnecting');
370
+ logger.warn('[OgmiosBackend] WebSocket not connected, reconnecting');
253
371
  this.reconnectPromise = this.init()
254
372
  .then(() => undefined)
255
373
  .finally(() => { this.reconnectPromise = null; });
256
374
  }
257
375
  await this.reconnectPromise;
258
376
  }
259
- /**
260
- * Get specific Block Data (not supported)
261
- * @param _hash block hash (hex)
262
- * @returns {Promise<BlockData>} block data
263
- */
264
377
  async getBlock(_hash) {
265
378
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
266
379
  throw new errors_1.NotFoundError('Historic Block queries not supported', this.name);
267
380
  }, this.name);
268
381
  }
269
- /**
270
- * Get specific Epoch Data (not supported)
271
- * @param _epochNumber epoch number
272
- * @returns {Promise<EpochData>} epoch data
273
- */
382
+ /** Only the current epoch. */
274
383
  async getEpoch(epochNumber) {
275
384
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
276
385
  await this.ensureConnected();
277
- // Get current epoch directly via epoch() query
278
386
  const currentEpoch = await this.stateQueryClient.epoch();
279
387
  // Ogmios only supports current epoch queries
280
388
  if (epochNumber !== currentEpoch) {
281
389
  throw new errors_1.NotFoundError(`Historic Epoch ${epochNumber} not supported (current: ${currentEpoch})`, this.name);
282
390
  }
283
- // Return current epoch data
284
391
  return this.getLatestEpoch();
285
392
  }, this.name);
286
393
  }
287
- /**
288
- * Get specific Transaction Data (not supported)
289
- * @param _hash transaction hash (hex)
290
- * @returns {Promise<Transaction>} transaction data
291
- */
292
394
  async getTransaction(_hash) {
293
395
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
294
396
  throw new errors_1.NotFoundError('Historic Transaction queries not supported', this.name);
295
397
  }, this.name);
296
398
  }
297
- /**
298
- * Get specific Transaction Metadata (not supported)
299
- * @param _tx_hash transaction hash (hex)
300
- * @returns {Promise<MetadataLabelTx[]>} transaction metadata list
301
- */
302
399
  async getTransactionMetadata(_tx_hash) {
303
400
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
304
401
  throw new errors_1.NotFoundError('Historic Transaction metadata not supported', this.name);
305
402
  }, this.name);
306
403
  }
307
- /**
308
- * Get specific Drep Data (not supported for Ogmios)
309
- * @param _drepId drep id
310
- * @returns {Promise<DrepData>} drep data
311
- */
312
- async getDrep(_drepId) {
404
+ // DRep from `queryLedgerState/delegateRepresentatives` via raw `Method()`, as the client has no wrapper.
405
+ // Ogmios lists only registered DReps, so others are NotFoundError.
406
+ async getDrep(drepId) {
313
407
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
314
- throw new errors_1.ProviderUnavailableError('DRep queries not supported by Ogmios backend', this.name);
408
+ await this.ensureConnected();
409
+ if (!this.context) {
410
+ throw new errors_1.ProviderUnavailableError('Ogmios interaction context not available', this.name);
411
+ }
412
+ const { hashHex, isScript } = decodeDrepId(drepId);
413
+ const [summaries, currentEpoch] = await Promise.all([
414
+ (0, client_1.Method)({
415
+ method: 'queryLedgerState/delegateRepresentatives',
416
+ params: isScript ? { scripts: [hashHex] } : { keys: [hashHex] },
417
+ }, {
418
+ handler: (response, resolve, reject) => {
419
+ if (response.error) {
420
+ reject(new Error(response.error.message ?? `Ogmios error ${response.error.code ?? ''}`.trim()));
421
+ }
422
+ else {
423
+ resolve(Array.isArray(response.result) ? response.result : []);
424
+ }
425
+ },
426
+ }, this.context),
427
+ this.stateQueryClient.epoch(),
428
+ ]);
429
+ // Filter by id: the query is already credential-scoped, but never trust a
430
+ // broader answer (abstain/noConfidence rows carry no id and are dropped here).
431
+ const drep = summaries.find((s) => s.type === 'registered' && s.id?.toLowerCase() === hashHex);
432
+ if (!drep)
433
+ throw new errors_1.NotFoundError('Drep', this.name);
434
+ const mandateEpoch = drep.mandate?.epoch;
435
+ return {
436
+ drepId,
437
+ hex: hashHex,
438
+ amount: ogmiosValueToLovelaceString(drep.stake),
439
+ hasScript: isScript || drep.from === 'script',
440
+ // Ogmios reports the mandate expiry epoch, not the last activity.
441
+ lastActiveEpoch: 0,
442
+ expired: typeof mandateEpoch === 'number' && mandateEpoch < Number(currentEpoch),
443
+ retired: false,
444
+ };
315
445
  }, this.name);
316
446
  }
317
- /**
318
- * Get Asset Info (not supported for Ogmios — no aggregate-supply query in the protocol)
319
- * @param _unit asset unit (policyId + assetNameHex)
320
- * @returns {Promise<AssetInfo>} asset info
321
- */
447
+ /** Not supported. The protocol has no aggregate-supply query. */
322
448
  async getAssetInfo(_unit) {
323
449
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
324
450
  throw new errors_1.ProviderUnavailableError('Asset info queries not supported by Ogmios backend', this.name);
325
451
  }, this.name);
326
452
  }
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
- */
453
+ /** Total supply is max supply minus reserves. Circulating, locked and stake totals stay '0'. */
333
454
  async getNetworkInformation() {
334
455
  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);
456
+ await this.ensureConnected();
457
+ if (!this.context) {
458
+ throw new errors_1.ProviderUnavailableError('Ogmios interaction context not available', this.name);
459
+ }
460
+ const pots = await (0, client_1.Method)({ method: 'queryLedgerState/treasuryAndReserves' }, {
461
+ handler: (response, resolve, reject) => {
462
+ if (response.error) {
463
+ reject(new Error(response.error.message ?? `Ogmios error ${response.error.code ?? ''}`.trim()));
464
+ }
465
+ else {
466
+ resolve(response.result ?? {});
467
+ }
468
+ },
469
+ }, this.context);
470
+ const max = const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY;
471
+ const reserves = ogmiosValueToLovelaceString(pots.reserves);
472
+ return {
473
+ // the ledger pots give treasury and reserves; circulation and stake are not in them
474
+ supply: {
475
+ max,
476
+ total: (BigInt(max) - BigInt(reserves)).toString(),
477
+ circulating: null,
478
+ locked: null,
479
+ treasury: ogmiosValueToLovelaceString(pots.treasury),
480
+ reserves,
481
+ },
482
+ stake: { live: null, active: null },
483
+ };
336
484
  }, this.name);
337
485
  }
338
- /**
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.)
343
- */
344
- async getAddress(_address) {
486
+ /** Address at the tip, decoded locally, with UTxOs and balance from the ledger. No tx history. */
487
+ async getAddress(address) {
345
488
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
346
- throw new errors_1.ProviderUnavailableError('Address detail queries not supported by Ogmios backend — use Blockfrost/Koios', this.name);
489
+ await this.ensureConnected();
490
+ const decoded = (0, mappers_1.decodeShelleyAddress)(address);
491
+ const raw = await (await this.scanQueryClient()).utxo({ addresses: [address] });
492
+ const utxos = raw.map((u) => this.mapOgmiosUtxo(u, address));
493
+ return {
494
+ address,
495
+ stakeAddress: decoded.stakeAddress,
496
+ type: decoded.type,
497
+ isScript: decoded.isScript,
498
+ amount: (0, mappers_1.sumUtxoAmounts)(utxos),
499
+ utxos,
500
+ };
347
501
  }, this.name);
348
502
  }
349
- /** get current specific Address UTxOs
350
- * @param address bech32 address
351
- * @returns {Promise<UTxO[]>} address UTxOs
352
- */
353
503
  async getAddressUtxos(address) {
354
504
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
355
505
  await this.ensureConnected();
356
- 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
- });
506
+ const utxos = await (await this.scanQueryClient()).utxo({ addresses: [address] });
507
+ return utxos.map((u) => this.mapOgmiosUtxo(u, address));
373
508
  }, this.name);
374
509
  }
375
- /**
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
380
- */
510
+ /** Ogmios `Utxo` entry → normalized UTxO line (shared by the address query and the set import). */
511
+ mapOgmiosUtxo(u, fallbackAddress = '') {
512
+ const ref = (0, reference_script_1.ogmiosReferenceScript)(u.script);
513
+ return {
514
+ txHash: u.transaction?.id || '',
515
+ outputIndex: u.index || 0,
516
+ address: u.address || fallbackAddress,
517
+ amount: this.convertOgmiosValue(u.value),
518
+ blockHash: '',
519
+ datumHash: u.datumHash,
520
+ // Ogmios delivers the inline datum as CBOR hex in `datum`
521
+ inlineDatum: typeof u.datum === 'string' ? u.datum : null,
522
+ scriptRef: ref?.hash,
523
+ scriptRefCbor: ref?.cbor ?? null,
524
+ scriptRefSize: ref?.size ?? null,
525
+ scriptRefType: ref?.type ?? null,
526
+ };
527
+ }
528
+ // Runs `fn` on the ledger state at `point` over a separate WebSocket. A connection holds one acquired
529
+ // point, so the shared socket would pin live queries to the past. `point` must be within k blocks.
530
+ async withLedgerStateAt(point, label, fn) {
531
+ const session = await this.openLedgerStateAt(point, label);
532
+ try {
533
+ return await fn(session.client);
534
+ }
535
+ finally {
536
+ await session.close();
537
+ }
538
+ }
539
+ // A connection of its own with the ledger state at `point` acquired. The caller closes it. The
540
+ // call signal closes it too: a closed socket rejects every pending query, so a stuck caller ends.
541
+ async openLedgerStateAt(point, label) {
542
+ const signal = (0, call_signal_1.callSignal)();
543
+ signal?.throwIfAborted();
544
+ const url = new URL(this.ogmiosUrl);
545
+ const connection = { host: url.hostname, port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80), tls: url.protocol === 'wss:' };
546
+ const context = await (0, client_1.createInteractionContext)((err) => logger.error(`[OgmiosBackend] ${label} context error: ${err.message}`), () => { }, { connection });
547
+ const onAbort = () => this.forceCloseContext(context);
548
+ try {
549
+ if (signal?.aborted)
550
+ throw signal.reason;
551
+ signal?.addEventListener('abort', onAbort, { once: true });
552
+ const client = await (0, client_1.createLedgerStateQueryClient)(context, { point: { slot: point.slot, id: point.hash } });
553
+ // shutdown() closes THIS connection only; the backend's own socket is untouched
554
+ return {
555
+ client,
556
+ close: async () => {
557
+ signal?.removeEventListener('abort', onAbort);
558
+ try {
559
+ await client.shutdown();
560
+ }
561
+ catch { /* best effort */ }
562
+ },
563
+ };
564
+ }
565
+ catch (err) {
566
+ signal?.removeEventListener('abort', onAbort);
567
+ this.forceCloseContext(context);
568
+ throw err;
569
+ }
570
+ }
571
+ // Reward accounts at `point`. The node lists an account while it is delegated to a pool or a DRep.
572
+ // Errors of `read` itself pass through unchanged.
573
+ async rewardAccountsAt(point, read) {
574
+ const session = await (0, backend_request_handler_1.handleBackendRequest)(() => this.openLedgerStateAt(point, 'account snapshot'), this.name);
575
+ try {
576
+ return await read((stakeAddresses) => (0, backend_request_handler_1.handleBackendRequest)(async () => {
577
+ if (!stakeAddresses.length)
578
+ return [];
579
+ // the node keeps key and script credentials apart and finds a script only under `scripts`
580
+ const scripts = stakeAddresses.filter(a => (0, mappers_1.decodeShelleyAddress)(a).isScript);
581
+ const keys = scripts.length ? stakeAddresses.filter(a => !scripts.includes(a)) : stakeAddresses;
582
+ const raw = await session.client.rewardAccountSummaries({ ...(keys.length ? { keys } : {}), ...(scripts.length ? { scripts } : {}) });
583
+ const summaries = (Array.isArray(raw) ? raw : Object.values(raw));
584
+ return summaries.flatMap((s) => (s.credential ? [{
585
+ stakeAddress: (0, mappers_1.credentialToStakeAddress)(s.credential, s.from === 'script', this.network),
586
+ withdrawableAmount: ogmiosRewardBalance(s),
587
+ deposit: s.deposit == null ? null : ogmiosValueToLovelaceString(s.deposit),
588
+ poolId: s.stakePool?.id || null,
589
+ drepId: ogmiosDrepToId(s.delegateRepresentative),
590
+ }] : []));
591
+ }, this.name));
592
+ }
593
+ finally {
594
+ await session.close();
595
+ }
596
+ }
597
+ /** Whole UTxO set as of `point` (crawler snapshot import). */
598
+ async queryUtxoSetAt(point) {
599
+ return (0, backend_request_handler_1.handleBackendRequest)(() => this.withLedgerStateAt(point, 'snapshot', async (client) => {
600
+ const utxos = await client.utxo();
601
+ return utxos.map((u) => this.mapOgmiosUtxo(u));
602
+ }), this.name);
603
+ }
604
+ /** Pools, DReps and pots at `point` from one ledger state. Without nOpt saturation stays 0. */
605
+ async epochStateAt(point) {
606
+ return (0, backend_request_handler_1.handleBackendRequest)(() => this.withLedgerStateAt(point, 'epoch snapshot', async (client) => {
607
+ const ctx = client.context;
608
+ const [epoch, stakePools, performances, dreps, pots] = await Promise.all([
609
+ client.epoch(),
610
+ client.stakePools(undefined, true),
611
+ client.stakePoolsPerformances().catch((err) => {
612
+ logger.warn(`stakePoolsPerformances unavailable, saturation stays 0: ${err?.message ?? err}`);
613
+ return null;
614
+ }),
615
+ (0, client_1.Method)({ method: 'queryLedgerState/delegateRepresentatives' }, {}, ctx),
616
+ (0, client_1.Method)({ method: 'queryLedgerState/treasuryAndReserves' }, {}, ctx),
617
+ ]);
618
+ return mapOgmiosEpochState({
619
+ epoch: Number(epoch),
620
+ stakePools: (stakePools ?? {}),
621
+ performances: performances,
622
+ dreps: Array.isArray(dreps) ? dreps : [],
623
+ pots: pots ?? null,
624
+ });
625
+ }), this.name);
626
+ }
627
+ /** Not supported. Ogmios only queries live state. */
381
628
  async getAddressTransactions(_address) {
382
629
  throw new errors_1.NotFoundError('Address transactions not available via Ogmios - use historical backend (Blockfrost/Koios)', this.name);
383
630
  }
384
- /**
385
- * Get current specific Pool Data
386
- * @param poolId pool id
387
- * @returns {Promise<PoolData>} pool data
388
- */
389
631
  async getPool(poolId) {
390
632
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
391
633
  await this.ensureConnected();
392
634
  // Query from tip (no acquire needed) with stake included
393
635
  const pools = await this.stateQueryClient.stakePools([{ id: poolId }], true);
394
- // Extract pool from response - stakePools returns object keyed by poolId
636
+ // stakePools returns an object keyed by poolId
395
637
  const pool = pools[poolId];
396
638
  if (!pool)
397
639
  throw new errors_1.NotFoundError('Pool', this.name);
398
640
  return {
399
641
  poolId,
400
- vrfKeyHash: pool.vrf || pool.vrfKeyHash || '',
401
- blocksMinted: 0,
402
- blocksEpoch: 0,
642
+ vrfKeyHash: pool.vrfVerificationKeyHash || '',
643
+ // block counts are not in the ledger state
644
+ blocksMinted: null,
645
+ blocksEpoch: null,
403
646
  liveStake: pool.stake?.ada?.lovelace ? String(pool.stake.ada.lovelace) : '0',
404
- liveSize: 0,
405
- liveDelegators: 0,
406
- liveSaturation: 0,
407
- // activeStake is not available from Ogmios pool params — report 0 instead
408
- // of fabricating it from the pledge
409
- activeStake: '0',
410
- 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")
647
+ // no total live stake to divide by; null = unavailable
648
+ liveSize: null,
649
+ // not in the ledger state; null = unavailable
650
+ liveDelegators: null,
651
+ // no saturation point and no active stake in the live pool view
652
+ liveSaturation: null,
653
+ activeStake: null,
654
+ activeSize: null,
655
+ // pledge/cost are ValueAdaOnly objects in Ogmios v6; margin is a Ratio string ("1/10")
413
656
  pledge: ogmiosValueToLovelaceString(pool.pledge),
414
657
  margin: parseOgmiosRatio(pool.margin),
415
658
  fixedCost: ogmiosValueToLovelaceString(pool.cost),
416
- rewardAccount: pool.rewardAccount || ''
659
+ rewardAccount: pool.rewardAccount || '',
660
+ // the node knows where the file is, not what it says
661
+ metadataUrl: pool.metadata?.url ?? null,
662
+ metadataHash: pool.metadata?.hash ?? null,
417
663
  };
418
664
  }, this.name);
419
665
  }
420
- /**
421
- * Get Account Data for specified stake address
422
- * @param stakeAddress stake address
423
- * @returns {Promise<AccountData>} account data
424
- */
425
666
  async getAccount(stakeAddress) {
426
667
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
427
668
  await this.ensureConnected();
428
- const rawResult = await this.stateQueryClient.rewardAccountSummaries({ keys: [stakeAddress] });
669
+ // Ogmios keeps key-hash and script-hash credentials in separate lists. A script stake address
670
+ // asked under `keys` is never found.
671
+ const rawResult = await this.stateQueryClient.rewardAccountSummaries((0, mappers_1.decodeShelleyAddress)(stakeAddress).isScript ? { scripts: [stakeAddress] } : { keys: [stakeAddress] });
429
672
  // Ogmios returns a record keyed by stake address; normalize to array
430
673
  const summaries = Array.isArray(rawResult)
431
674
  ? rawResult
432
675
  : Object.values(rawResult);
433
- // Ogmios API returns array of account summaries
434
676
  const account = summaries && summaries.length > 0 ? summaries[0] : null;
677
+ // The summary lists only credentials delegated to a pool or a DRep. A registered credential without
678
+ // delegation is absent here, so "not found" does not mean "not registered".
435
679
  if (!account) {
436
680
  throw new errors_1.NotFoundError('Account', this.name);
437
681
  }
438
682
  return {
439
683
  stakeaddress: stakeAddress,
440
- // Ogmios only returns reward-account summaries for REGISTERED stake keys —
441
- // reaching this point (summary found) therefore implies the account is active.
684
+ // a summary exists only for a registered credential
442
685
  active: true,
443
- activeEpoch: 0,
444
- controlledAmount: ogmiosValueToLovelaceString(account.controlledAmount),
445
- rewardsSum: ogmiosValueToLovelaceString(account.rewards),
446
- withdrawalsSum: ogmiosValueToLovelaceString(account.withdrawals),
447
- reservesSum: '0',
448
- treasurySum: '0',
449
- withdrawableAmount: ogmiosValueToLovelaceString(account.rewards),
450
- poolId: account.delegate?.id || account.delegation?.poolId || null,
451
- drepId: account.vote?.id || account.drep?.id || null,
686
+ // a reward-account summary carries the current balance only: no registration epoch, no
687
+ // controlled amount, no totals of rewards, withdrawals or pot payments
688
+ activeEpoch: null,
689
+ controlledAmount: null,
690
+ rewardsSum: null,
691
+ withdrawalsSum: null,
692
+ reservesSum: null,
693
+ treasurySum: null,
694
+ withdrawableAmount: ogmiosRewardBalance(account),
695
+ poolId: account.stakePool?.id || null,
696
+ drepId: ogmiosDrepToId(account.delegateRepresentative),
452
697
  addresses: []
453
698
  };
454
699
  }, this.name);
455
700
  }
456
- /**
457
- * Submit Transaction to the network
458
- * @param signedTxCbor signed transaction in CBOR hex format
459
- * @returns {Promise<string>} transaction hash
460
- */
461
701
  async submitTransaction(signedTxCbor) {
462
702
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
463
703
  await this.ensureConnected();
464
- const txHash = await this.txSubmissionClient.submitTransaction(signedTxCbor);
465
- return txHash;
704
+ try {
705
+ return await this.txSubmissionClient.submitTransaction(signedTxCbor);
706
+ }
707
+ catch (err) {
708
+ // JSON-RPC 3000-3999: the node rejected the transaction, and the code decides, never its text.
709
+ // Only a node that holds the transaction makes it a 409. The code stays on the error as
710
+ // originalError.code for the callers to classify.
711
+ const e = err;
712
+ const rpcCode = typeof e?.code === 'number' && e.code >= 3000 && e.code < 4000 ? e.code : null;
713
+ if (rpcCode !== null) {
714
+ if (refusedForSpentInputs(rpcCode, e.data)) {
715
+ const txHash = this.txHashOrNull(signedTxCbor);
716
+ const held = txHash ? await this.isKnownTransaction(txHash) : false;
717
+ if (held === true)
718
+ throw new errors_1.TransactionAlreadySubmittedError(txHash, err);
719
+ // without the lookup the refusal may be about this very transaction: no verdict
720
+ if (held === null) {
721
+ throw new errors_1.ProviderUnavailableError(`node refused ${txHash} with spent inputs, and whether it holds the transaction could not be read`, this.name, undefined, err);
722
+ }
723
+ }
724
+ const detail = e.data === undefined ? '' : ` ${JSON.stringify(e.data).slice(0, 800)}`;
725
+ throw new errors_1.TransactionValidationError(`node rejected the transaction (${rpcCode}): ${String(e.message ?? '')}${detail}`, err);
726
+ }
727
+ // no node verdict, whatever the text says: a socket or session failure
728
+ throw new errors_1.ProviderUnavailableError(`submit to the node failed without a verdict: ${(0, errors_1.errorText)(err)}`, this.name, undefined, err);
729
+ }
466
730
  }, this.name);
467
731
  }
468
- /**
469
- * Evaluate transaction script execution units
470
- * @param unsignedTxCbor unsigned transaction in CBOR hex format
471
- * @returns {Promise<ScriptEvaluationResult[]>} evaluation results
472
- */
732
+ /** Hash of a signed transaction, or null when the CBOR does not parse. */
733
+ txHashOrNull(signedTxCbor) {
734
+ try {
735
+ return (0, tx_build_helper_1.getTxHashFromCbor)(signedTxCbor);
736
+ }
737
+ catch {
738
+ return null;
739
+ }
740
+ }
741
+ /** Whether the node holds the transaction: in its mempool, or on chain with its first output unspent. Null when the lookup failed. */
742
+ async isKnownTransaction(txHash) {
743
+ try {
744
+ if (await this.mempoolHas(txHash))
745
+ return true;
746
+ const query = await this.scanQueryClient();
747
+ const onChain = await this.withInitTimeout(query.utxo({ outputReferences: [{ transaction: { id: txHash }, index: 0 }] }), 'utxo/known-transaction');
748
+ return onChain.length > 0;
749
+ }
750
+ catch (err) {
751
+ logger.warn(`[OgmiosBackend] could not check whether ${txHash} is known: ${(0, errors_1.errorText)(err)}`);
752
+ return null;
753
+ }
754
+ }
755
+ /** Mempool lookup on its own short connection, since an acquired mempool snapshot blocks the session. */
756
+ async mempoolHas(txHash) {
757
+ const url = new URL(this.ogmiosUrl);
758
+ const connection = { host: url.hostname, port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80), tls: url.protocol === 'wss:' };
759
+ const context = await this.withInitTimeout((0, client_1.createInteractionContext)((err) => logger.debug(`[OgmiosBackend] mempool context error: ${err.message}`), () => undefined, { connection }), 'mempool/createInteractionContext');
760
+ try {
761
+ const mempool = await this.withInitTimeout((0, client_1.createMempoolMonitoringClient)(context), 'mempool/client');
762
+ await this.withInitTimeout(mempool.acquireMempool(), 'mempool/acquire');
763
+ const has = await this.withInitTimeout(mempool.hasTransaction(txHash), 'mempool/hasTransaction');
764
+ await mempool.shutdown().catch(() => undefined);
765
+ return has;
766
+ }
767
+ finally {
768
+ this.forceCloseContext(context);
769
+ }
770
+ }
473
771
  async evaluateTransaction(unsignedTxCbor) {
474
772
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
475
773
  await this.ensureConnected();
476
- const results = await this.txSubmissionClient.evaluateTransaction(unsignedTxCbor);
477
- return results;
774
+ try {
775
+ const results = await this.txSubmissionClient.evaluateTransaction(unsignedTxCbor);
776
+ return results;
777
+ }
778
+ catch (err) {
779
+ // JSON-RPC 3000-3099 except 3003: the transaction cannot be evaluated as given, a 400 with its reason.
780
+ // 3003 means the node is still syncing, so it stays retryable.
781
+ const known = (0, errors_1.normalizeBackendError)(err, this.name);
782
+ if (known.statusCode >= 400 && known.statusCode < 500)
783
+ throw known;
784
+ const e = err;
785
+ if (typeof e?.code === 'number' && e.code >= 3000 && e.code < 3100 && e.code !== 3003) {
786
+ const detail = e.data === undefined ? '' : ` ${JSON.stringify(e.data).slice(0, 800)}`;
787
+ throw new errors_1.TransactionValidationError(`transaction cannot be evaluated (${e.code}): ${String(e.message ?? '')}${detail}`, err);
788
+ }
789
+ throw err;
790
+ }
478
791
  }, this.name);
479
792
  }
480
- /**
481
- * Get current Protocol Parameters
482
- * @returns {Promise<LedgerProtocolParameters>} protocol parameters
483
- */
484
793
  async getProtocolParameters() {
485
794
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
486
795
  await this.ensureConnected();
@@ -508,6 +817,7 @@ class OgmiosBackend {
508
817
  collateralPercent: params.collateralPercentage || 0,
509
818
  maxCollateralInputs: params.maxCollateralInputs || 0,
510
819
  coinsPerUtxoSize: params.minUtxoDepositCoefficient?.toString() || '0',
820
+ minFeeRefScriptCostPerByte: params.minFeeReferenceScripts?.base ?? null,
511
821
  maxBlockHeaderSize: params.maxBlockHeaderSize?.bytes || 0,
512
822
  maxTxSize: params.maxTransactionSize?.bytes || 0,
513
823
  keyDeposit: params.stakeCredentialDeposit?.ada?.lovelace?.toString() || '0',
@@ -516,7 +826,7 @@ class OgmiosBackend {
516
826
  eMax: params.stakePoolRetirementEpochBound || 0,
517
827
  nOpt: params.desiredNumberOfStakePools || 0,
518
828
  a0: parseOgmiosRatio(params.stakePoolPledgeInfluence),
519
- // ρ = monetaryExpansion, τ = treasuryExpansion (was swapped; Koios maps it correctly)
829
+ // ρ = monetaryExpansion, τ = treasuryExpansion
520
830
  rho: parseOgmiosRatio(params.monetaryExpansion),
521
831
  tau: parseOgmiosRatio(params.treasuryExpansion),
522
832
  decentralisationParam: 0,
@@ -528,10 +838,6 @@ class OgmiosBackend {
528
838
  };
529
839
  }, this.name);
530
840
  }
531
- /**
532
- * Get Latest Epoch Data
533
- * @returns {Promise<EpochData>} latest epoch data
534
- */
535
841
  async getLatestEpoch() {
536
842
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
537
843
  await this.ensureConnected();
@@ -541,26 +847,23 @@ class OgmiosBackend {
541
847
  ]);
542
848
  const { slot } = resolveOgmiosTip(tip);
543
849
  // Network-aware epoch geometry + Shelley-anchored slot→time conversion
544
- const startSlot = epochStartSlot(this.network, currentEpoch);
850
+ const startSlot = (0, epoch_slots_1.epochStartSlot)(this.network, currentEpoch);
545
851
  const endSlot = startSlot + const_1.EPOCH_CONFIG_BY_NETWORK[this.network].slotsPerEpoch;
546
852
  return {
547
853
  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),
552
- block_count: 0, // Not available from Ogmios state queries
553
- tx_count: 0, // Not available from Ogmios state queries
554
- output: '0',
555
- fees: '0',
854
+ start_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, startSlot),
855
+ end_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, endSlot),
856
+ // block statistics are not in the ledger state
857
+ first_block_time: null,
858
+ last_block_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, slot),
859
+ block_count: null,
860
+ tx_count: null,
861
+ output: null,
862
+ fees: null,
556
863
  active_stake: null,
557
864
  };
558
865
  }, this.name);
559
866
  }
560
- /**
561
- * Get current Latest Block Data
562
- * @returns {Promise<BlockData>} latest block data
563
- */
564
867
  async getLatestBlock() {
565
868
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
566
869
  await this.ensureConnected();
@@ -572,10 +875,10 @@ class OgmiosBackend {
572
875
  ]);
573
876
  const { slot, hash } = resolveOgmiosTip(tip);
574
877
  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));
878
+ // network-aware slot-in-epoch
879
+ const epochSlot = Math.max(0, slot - (0, epoch_slots_1.epochStartSlot)(this.network, epoch));
577
880
  return {
578
- time: slotToPosixSeconds(this.network, slot), // seconds (mapBlock expects seconds)
881
+ time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, slot), // seconds (mapBlock expects seconds)
579
882
  height,
580
883
  hash,
581
884
  slot,
@@ -585,13 +888,10 @@ class OgmiosBackend {
585
888
  size: 0, // Not available via ledgerTip - would need full block data
586
889
  txCount: 0, // Not available via ledgerTip - would need full block data
587
890
  fees: '0', // Not available via ledgerTip - would need full block data
891
+ headerOnly: true,
588
892
  };
589
893
  }, this.name);
590
894
  }
591
- /**
592
- * Get the latest chain tip slot.
593
- * @returns {Promise<number>} current chain slot
594
- */
595
895
  async getCurrentSlot() {
596
896
  const block = await this.getLatestBlock();
597
897
  if (block.slot == null) {
@@ -599,13 +899,7 @@ class OgmiosBackend {
599
899
  }
600
900
  return block.slot;
601
901
  }
602
- /**
603
- * Check whether a UTxO is still unspent via Ogmios `queryLedgerState/utxo`
604
- * with an outputReferences filter. Empty result means spent or nonexistent.
605
- * @param txHash 64-char lowercase hex
606
- * @param outputIndex non-negative integer
607
- * @returns {Promise<boolean>} true iff the UTxO exists and is unspent
608
- */
902
+ /** Unspent check via `queryLedgerState/utxo`. An empty answer means spent or unknown. */
609
903
  async isUtxoUnspent(txHash, outputIndex) {
610
904
  if (!Number.isInteger(outputIndex) || outputIndex < 0)
611
905
  return false;
@@ -617,10 +911,19 @@ class OgmiosBackend {
617
911
  return Array.isArray(result) && result.length > 0;
618
912
  }, this.name);
619
913
  }
620
- /**
621
- * Shutdown the Ogmios Backend
622
- * Closes all connections and marks as shutdown
623
- */
914
+ /** Outputs among `refs` that are unspent in the live ledger; spent or unknown references are absent. */
915
+ async getUnspentOutputs(refs) {
916
+ if (refs.length === 0)
917
+ return [];
918
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
919
+ await this.ensureConnected();
920
+ const result = await this.stateQueryClient.utxo({
921
+ outputReferences: refs.map(r => ({ transaction: { id: r.txHash }, index: r.outputIndex })),
922
+ });
923
+ return result.map((u) => this.mapOgmiosUtxo(u));
924
+ }, this.name);
925
+ }
926
+ /** Close the WebSocket and mark the backend as shut down. */
624
927
  async shutdown() {
625
928
  if (this.isShutdown)
626
929
  return;
@@ -639,13 +942,14 @@ class OgmiosBackend {
639
942
  });
640
943
  }
641
944
  }
945
+ if (this.scanContext)
946
+ this.forceCloseContext(this.scanContext);
642
947
  this.stateQueryClient = null;
643
948
  this.txSubmissionClient = null;
644
949
  this.context = null;
950
+ this.scanClient = null;
951
+ this.scanContext = null;
645
952
  }
646
- /**
647
- * Check if backend is connected
648
- */
649
953
  isConnected() {
650
954
  if (this.isShutdown || !this.context?.socket) {
651
955
  return false;
@@ -656,29 +960,20 @@ class OgmiosBackend {
656
960
  // ---------------------------------------------------------------------------
657
961
  // Helpers
658
962
  // ---------------------------------------------------------------------------
659
- /**
660
- * Ensure the client is not shutdown before operations
661
- */
662
963
  ensureNotShutdown() {
663
964
  if (this.isShutdown) {
664
965
  throw new errors_1.ProviderUnavailableError('Ogmios client has been shutdown', this.name);
665
966
  }
666
967
  }
667
- /**
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' }]
671
- */
968
+ /** Ogmios value `{ ada: { lovelace }, policyId: { assetName: qty } }` to a list of units and quantities. */
672
969
  convertOgmiosValue(value) {
673
970
  const amounts = [];
674
- // Handle ADA (lovelace)
675
971
  if (value.ada?.lovelace) {
676
972
  amounts.push({
677
973
  unit: 'lovelace',
678
974
  quantity: value.ada.lovelace.toString()
679
975
  });
680
976
  }
681
- // handle native assets (policy.assetName)
682
977
  for (const [policyId, assets] of Object.entries(value)) {
683
978
  if (policyId === 'ada')
684
979
  continue;
@@ -692,21 +987,10 @@ class OgmiosBackend {
692
987
  return amounts;
693
988
  }
694
989
  // ---------------------------------------------------------------------------
695
- // ChainSyncBackend — streamed forward sync for the chain crawler (v2.0)
990
+ // ChainSyncBackend: streamed forward sync for the chain crawler
696
991
  // ---------------------------------------------------------------------------
697
- /**
698
- * Open a dedicated chain-synchronization stream. Uses its own InteractionContext
699
- * (a separate WebSocket) from the query/submission clients, because it is a
700
- * long-lived stream. `sequential: true` + `inFlight: 1` deliver blocks one at a
701
- * time in order, which the crawler needs for reorg detection and serial persist.
702
- *
703
- * KNOWN LIMITATIONS (documented, to harden against a live node — see CRAWLER_DESIGN.md):
704
- * - Input address/amount are left empty: Ogmios chain-sync inputs are bare
705
- * references ({txId,index}); the indexer resolves them from already-indexed
706
- * outputs (indexBlockFull, C3).
707
- * - Per-tx `size` and `deposit` are not surfaced by chain-sync (set 0).
708
- * - Output `referenceScriptHash` is not derived from the inline script yet.
709
- */
992
+ // Opens a chain-sync stream on its own WebSocket. One block in flight keeps blocks strictly
993
+ // in order, which reorg detection needs. Inputs arrive as bare references the indexer resolves.
710
994
  async openChainSync(from, callbacks) {
711
995
  OgmiosBackend.validateOgmiosUrl(this.ogmiosUrl);
712
996
  const url = new URL(this.ogmiosUrl);
@@ -731,6 +1015,12 @@ class OgmiosBackend {
731
1015
  logger.error('[OgmiosBackend] chain-sync onError callback failed:', callbackError);
732
1016
  }
733
1017
  };
1018
+ // A frame the client's parser cannot handle throws inside the library's un-awaited socket
1019
+ // handler and would end the process; the guard routes it here as a stream error instead.
1020
+ // Registered per open and removed on close, so concurrent streams each get the report.
1021
+ const unregisterFrameGuard = (0, ogmios_frame_guard_1.installOgmiosFrameGuard)(({ height, id, reason }) => {
1022
+ void reportStreamError(new errors_1.ChainSyncFrameError(height, id, reason));
1023
+ });
734
1024
  const contextPromise = (0, client_1.createInteractionContext)((err) => {
735
1025
  logger.error(`[OgmiosBackend] chain-sync context error: ${err.message}`);
736
1026
  void reportStreamError(err);
@@ -738,7 +1028,7 @@ class OgmiosBackend {
738
1028
  if (intentionalClose || this.isShutdown)
739
1029
  return;
740
1030
  const detail = reason?.toString() || 'no reason supplied';
741
- const err = new errors_1.ProviderUnavailableError(`Ogmios chain-sync socket closed unexpectedly (code ${code}: ${detail})`, this.name);
1031
+ const err = new errors_1.ChainSyncClosedError(`Ogmios chain-sync socket closed unexpectedly (code ${code}: ${detail})`, this.name);
742
1032
  logger.warn(`[OgmiosBackend] ${err.message}`);
743
1033
  void reportStreamError(err);
744
1034
  }, { connection });
@@ -750,19 +1040,18 @@ class OgmiosBackend {
750
1040
  // A timeout rejects our race but cannot cancel the library's health probe /
751
1041
  // handshake. If it resolves later, close that late socket as well.
752
1042
  intentionalClose = true;
1043
+ unregisterFrameGuard();
753
1044
  void contextPromise.then(lateContext => this.forceCloseContext(lateContext)).catch(() => undefined);
754
1045
  throw err;
755
1046
  }
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.
1047
+ // Both handlers are fully try/caught: the client awaits them without a catch, and with
1048
+ // sequential+inFlight:1 a throw before nextBlock() stalls the stream. On error nextBlock()
1049
+ // is deliberately NOT called (stop, don't skip a block); the error goes to callbacks.onError.
761
1050
  const handlers = {
762
1051
  rollForward: async ({ block, tip }, nextBlock) => {
763
1052
  try {
764
1053
  const b = block;
765
- // Byron epoch-boundary (ebb) / bft blocks carry no indexable Praos txs — skip.
1054
+ // Byron boundary and bft blocks carry no indexable txs
766
1055
  if (b.type !== 'praos') {
767
1056
  nextBlock();
768
1057
  return;
@@ -776,18 +1065,22 @@ class OgmiosBackend {
776
1065
  nextBlock();
777
1066
  }
778
1067
  catch (err) {
779
- logger.error('[OgmiosBackend] chain-sync rollForward failed — stream halted:', err);
1068
+ logger.error('[OgmiosBackend] chain-sync rollForward failed, stream halted:', err);
780
1069
  await reportStreamError(err);
781
1070
  }
782
1071
  },
783
- rollBackward: async ({ point }, nextBlock) => {
1072
+ rollBackward: async ({ point, tip }, nextBlock) => {
784
1073
  try {
785
1074
  const p = point;
786
- await callbacks.rollBackward(p === 'origin' ? 'origin' : { slot: p.slot, hash: p.id });
1075
+ const t = tip;
1076
+ const tipPoint = t && t !== 'origin' && t.slot != null && t.id
1077
+ ? { slot: t.slot, hash: t.id, height: t.height }
1078
+ : undefined;
1079
+ await callbacks.rollBackward(p === 'origin' ? 'origin' : { slot: p.slot, hash: p.id }, tipPoint);
787
1080
  nextBlock();
788
1081
  }
789
1082
  catch (err) {
790
- logger.error('[OgmiosBackend] chain-sync rollBackward failed — stream halted:', err);
1083
+ logger.error('[OgmiosBackend] chain-sync rollBackward failed, stream halted:', err);
791
1084
  await reportStreamError(err);
792
1085
  }
793
1086
  },
@@ -802,6 +1095,7 @@ class OgmiosBackend {
802
1095
  }
803
1096
  catch (err) {
804
1097
  intentionalClose = true;
1098
+ unregisterFrameGuard();
805
1099
  if (client) {
806
1100
  try {
807
1101
  await this.withInitTimeout(client.shutdown(), 'chainSync/failedOpenShutdown');
@@ -819,6 +1113,7 @@ class OgmiosBackend {
819
1113
  // Idempotency matters when an operator stop races an onError-triggered halt.
820
1114
  if (!closePromise) {
821
1115
  intentionalClose = true;
1116
+ unregisterFrameGuard();
822
1117
  closePromise = (async () => {
823
1118
  try {
824
1119
  await this.withInitTimeout(client.shutdown(), 'chainSync/shutdown');
@@ -833,40 +1128,31 @@ class OgmiosBackend {
833
1128
  }
834
1129
  };
835
1130
  }
836
- /**
837
- * Map an Ogmios Praos block into our BlockData + its transactions. Block-level
838
- * fees are the sum of per-tx fees; epoch/epochSlot are derived from the slot via
839
- * the network's Shelley anchor (same config the tx-builder uses).
840
- */
1131
+ // Block fees are the sum of tx fees. A phase-2 failure without `total_collateral` keeps
1132
+ // its declared fee here, and applyCollateralFees() corrects it later.
841
1133
  mapOgmiosBlock(block) {
842
1134
  const txs = (block.transactions ?? []).map((t, i) => this.mapOgmiosTx(t, block, i));
843
1135
  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);
1136
+ const epoch = (0, epoch_slots_1.epochOfSlot)(this.network, block.slot);
1137
+ // Shelley-anchored helpers (handle preview/preprod geometry and the Byron offset)
1138
+ const epochSlot = block.slot - (0, epoch_slots_1.epochStartSlot)(this.network, epoch);
849
1139
  const blockData = {
850
- time: slotToPosixSeconds(this.network, block.slot),
1140
+ time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, block.slot),
851
1141
  height: block.height,
852
1142
  hash: block.id,
853
1143
  slot: block.slot,
854
- slotLeader: block.issuer?.verificationKey ?? '',
1144
+ slotLeader: block.issuer?.verificationKey ? issuerKeyToPoolId(block.issuer.verificationKey) : '',
855
1145
  epoch,
856
1146
  epochSlot,
857
1147
  size: block.size?.bytes ?? 0,
858
1148
  txCount: txs.length,
859
1149
  fees: totalFees.toString(),
1150
+ previousHash: block.ancestor === 'genesis' ? null : block.ancestor,
860
1151
  };
861
1152
  return { block: blockData, txs };
862
1153
  }
863
- /**
864
- * Map a single Ogmios chain-sync transaction into our Transaction. Outputs, fee
865
- * and metadata are mapped fully; inputs are kept as bare references (address/amount
866
- * resolved downstream by the indexer). `spends` selects the ledger-applied
867
- * partition: a phase-2-invalid transaction consumes collaterals and creates only
868
- * its collateral-return output, never its declared regular inputs/outputs.
869
- */
1154
+ // A phase-2 invalid tx consumes its collaterals and creates only the collateral-return output.
1155
+ // `spends` selects which side the ledger applied, and the fee follows it.
870
1156
  mapOgmiosTx(tx, block, index) {
871
1157
  const mapInput = (input, flags = {}) => ({
872
1158
  address: '',
@@ -889,7 +1175,7 @@ class OgmiosBackend {
889
1175
  dataHash: output.datumHash ?? null,
890
1176
  inlineDatum: output.datum ?? null,
891
1177
  isCollateral,
892
- referenceScriptHash: null,
1178
+ ...ogmiosReferenceScriptFields(output.script),
893
1179
  });
894
1180
  const outputs = spendsCollaterals
895
1181
  ? (tx.collateralReturn
@@ -905,24 +1191,94 @@ class OgmiosBackend {
905
1191
  json: v.json,
906
1192
  }))
907
1193
  : [];
908
- return {
1194
+ // A phase-2 failure pays `total_collateral`, not the declared fee; the body often omits it,
1195
+ // so the indexer derives the rest from the resolved collateral inputs later.
1196
+ const declaredFee = (tx.fee?.ada?.lovelace ?? 0).toString();
1197
+ const totalCollateral = tx.totalCollateral ? tx.totalCollateral.ada.lovelace.toString() : null;
1198
+ // the same ledger view the pagination sources produce (ordering; the partition is already applied)
1199
+ return (0, mappers_1.ledgerView)({
909
1200
  hash: tx.id,
910
1201
  blockHash: block.id,
911
1202
  blockHeight: block.height,
912
1203
  slot: block.slot,
913
1204
  index,
914
- fee: (tx.fee?.ada?.lovelace ?? 0).toString(),
915
- deposit: '0',
916
- // null = unknown (chain-sync doesn't surface the serialized size) — matches the
917
- // lazy path's `size ?? null` convention; 0 would masquerade as a real size
918
- size: null,
919
- blockTime: slotToPosixSeconds(this.network, block.slot),
1205
+ fee: spendsCollaterals ? (totalCollateral ?? declaredFee) : declaredFee,
1206
+ spendsCollaterals,
1207
+ totalCollateral,
1208
+ // Only certificates and proposals move deposits, and none applies when the script phase failed.
1209
+ // Null leaves the amount to the indexer, which has the spent inputs.
1210
+ deposit: spendsCollaterals || !(tx.certificates?.length || tx.proposals?.length) ? '0' : null,
1211
+ treasuryDonation: tx.treasury?.donation?.ada?.lovelace?.toString() ?? null,
1212
+ // The ledger applies no mint when the script phase failed: the body's mint field is
1213
+ // declared but never enacted, so a phase-2 failure must report none at all.
1214
+ mint: spendsCollaterals ? undefined : this.convertOgmiosValue(tx.mint ?? {}),
1215
+ // null without the bytes: 0 would look like a real size
1216
+ size: tx.cbor ? tx.cbor.length / 2 : null,
1217
+ blockTime: (0, epoch_slots_1.slotToPosixSeconds)(this.network, block.slot),
920
1218
  inputs,
921
1219
  outputs,
922
- // undefined (not []) when absent — matches the Blockfrost path so
923
- // mapTransaction's hasMetadata flag stays false for metadata-less txs
1220
+ // undefined, not [], so hasMetadata stays false as on the Blockfrost path
924
1221
  metadata: metadataEntries.length ? metadataEntries : undefined,
925
- };
1222
+ certificates: this.mapOgmiosCertificates(tx.certificates ?? []),
1223
+ withdrawals: Object.entries(tx.withdrawals ?? {}).map(([stakeAddress, value]) => ({
1224
+ stakeAddress,
1225
+ amount: (value?.ada?.lovelace ?? 0).toString(),
1226
+ })),
1227
+ redeemers: mapOgmiosRedeemers(tx),
1228
+ datums: Object.entries(tx.datums ?? {}).map(([hash, cbor]) => ({ hash, cbor })),
1229
+ });
1230
+ }
1231
+ // Maps Ogmios certificates to `CertificateKind`. A delegation to both pool and DRep becomes two
1232
+ // entries with one index, as db-sync reports it. Credential hashes are re-encoded as bech32.
1233
+ mapOgmiosCertificates(certs) {
1234
+ const out = [];
1235
+ const lovelace = (v) => v?.ada?.lovelace != null ? v.ada.lovelace.toString() : null;
1236
+ const stakeAddr = (c) => c.credential ? (0, mappers_1.credentialToStakeAddress)(c.credential, c.from === 'script', this.network) : null;
1237
+ certs.forEach((c, certIndex) => {
1238
+ switch (c.type) {
1239
+ case 'stakeCredentialRegistration':
1240
+ out.push({ certIndex, kind: 'stake_registration', stakeAddress: stakeAddr(c), deposit: lovelace(c.deposit) });
1241
+ break;
1242
+ case 'stakeCredentialDeregistration':
1243
+ out.push({ certIndex, kind: 'stake_deregistration', stakeAddress: stakeAddr(c), deposit: lovelace(c.deposit) });
1244
+ break;
1245
+ case 'stakeDelegation': {
1246
+ const stakeAddress = stakeAddr(c);
1247
+ if (c.stakePool?.id)
1248
+ out.push({ certIndex, kind: 'pool_delegation', stakeAddress, poolId: c.stakePool.id });
1249
+ if (c.delegateRepresentative)
1250
+ out.push({ certIndex, kind: 'vote_delegation', stakeAddress, drepId: ogmiosDrepToId(c.delegateRepresentative) });
1251
+ break;
1252
+ }
1253
+ case 'stakePoolRegistration':
1254
+ out.push({ certIndex, kind: 'pool_registration', poolId: c.stakePool?.id ?? null });
1255
+ break;
1256
+ case 'stakePoolRetirement':
1257
+ out.push({ certIndex, kind: 'pool_retirement', poolId: c.stakePool?.id ?? null, epoch: c.stakePool?.retirementEpoch ?? null });
1258
+ break;
1259
+ case 'delegateRepresentativeRegistration':
1260
+ out.push({ certIndex, kind: 'drep_registration', drepId: ogmiosDrepToId(c.delegateRepresentative), deposit: lovelace(c.deposit) });
1261
+ break;
1262
+ case 'delegateRepresentativeUpdate':
1263
+ out.push({ certIndex, kind: 'drep_update', drepId: ogmiosDrepToId(c.delegateRepresentative) });
1264
+ break;
1265
+ case 'delegateRepresentativeRetirement':
1266
+ out.push({ certIndex, kind: 'drep_retirement', drepId: ogmiosDrepToId(c.delegateRepresentative), deposit: lovelace(c.deposit) });
1267
+ break;
1268
+ case 'constitutionalCommitteeDelegation':
1269
+ out.push({ certIndex, kind: 'committee_hot_auth' });
1270
+ break;
1271
+ case 'constitutionalCommitteeRetirement':
1272
+ out.push({ certIndex, kind: 'committee_resign' });
1273
+ break;
1274
+ case 'genesisDelegation':
1275
+ out.push({ certIndex, kind: 'genesis_delegation' });
1276
+ break;
1277
+ default:
1278
+ out.push({ certIndex, kind: c.type });
1279
+ }
1280
+ });
1281
+ return out;
926
1282
  }
927
1283
  }
928
1284
  exports.OgmiosBackend = OgmiosBackend;