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

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