@odatano/core 2.0.0-rc.3 → 2.0.0-rc.31

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 (162) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +294 -7
  8. package/@cds-models/CardanoODataService/index.js +33 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +52 -19
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +18 -0
  14. package/@cds-models/index.js +3 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +677 -13
  19. package/db/types.cds +27 -0
  20. package/package.json +182 -173
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +11 -10
  24. package/src/index.js +28 -14
  25. package/src/plugin.js +39 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +49 -160
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +356 -217
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +548 -197
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +78 -205
  39. package/srv/blockchain/cardano-client.js +186 -242
  40. package/srv/blockchain/cardano-indexer.d.ts +302 -242
  41. package/srv/blockchain/cardano-indexer.js +1193 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +43 -81
  43. package/srv/blockchain/cardano-tx-builder.js +177 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  68. package/srv/blockchain/signing/signature-verifier.js +13 -54
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +115 -160
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +651 -287
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +48 -24
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +56 -1
  102. package/srv/cardano-service.js +52 -113
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +55 -173
  105. package/srv/cardano-tx-service.cds +439 -364
  106. package/srv/cardano-tx-service.js +305 -209
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/parse.js +13 -1
  110. package/srv/server.d.ts +28 -86
  111. package/srv/server.js +130 -135
  112. package/srv/utils/agent-grants-config.d.ts +37 -0
  113. package/srv/utils/agent-grants-config.js +138 -0
  114. package/srv/utils/agent-grants.d.ts +262 -0
  115. package/srv/utils/agent-grants.js +922 -0
  116. package/srv/utils/agent-token-auth.d.ts +16 -0
  117. package/srv/utils/agent-token-auth.js +78 -0
  118. package/srv/utils/backend-request-handler.d.ts +2 -16
  119. package/srv/utils/backend-request-handler.js +3 -18
  120. package/srv/utils/collections.d.ts +4 -8
  121. package/srv/utils/collections.js +4 -8
  122. package/srv/utils/const.d.ts +30 -67
  123. package/srv/utils/const.js +32 -72
  124. package/srv/utils/crypto.d.ts +3 -12
  125. package/srv/utils/crypto.js +5 -18
  126. package/srv/utils/db-indexes.d.ts +25 -0
  127. package/srv/utils/db-indexes.js +94 -0
  128. package/srv/utils/db-sanitize.d.ts +27 -0
  129. package/srv/utils/db-sanitize.js +85 -0
  130. package/srv/utils/epoch-slots.d.ts +13 -0
  131. package/srv/utils/epoch-slots.js +25 -0
  132. package/srv/utils/error-codes.d.ts +20 -73
  133. package/srv/utils/error-codes.js +19 -70
  134. package/srv/utils/errors.d.ts +50 -177
  135. package/srv/utils/errors.js +94 -218
  136. package/srv/utils/liveness.d.ts +16 -0
  137. package/srv/utils/liveness.js +40 -0
  138. package/srv/utils/mappers.d.ts +128 -214
  139. package/srv/utils/mappers.js +354 -299
  140. package/srv/utils/network-context.js +2 -11
  141. package/srv/utils/pg-inline-json.d.ts +8 -0
  142. package/srv/utils/pg-inline-json.js +62 -0
  143. package/srv/utils/pg-order-nulls.d.ts +14 -0
  144. package/srv/utils/pg-order-nulls.js +56 -0
  145. package/srv/utils/plutus-placeholders.d.ts +23 -16
  146. package/srv/utils/plutus-placeholders.js +63 -27
  147. package/srv/utils/rate-limiter.d.ts +46 -0
  148. package/srv/utils/rate-limiter.js +116 -0
  149. package/srv/utils/service-events.d.ts +2 -22
  150. package/srv/utils/service-events.js +3 -23
  151. package/srv/utils/signing-helper.d.ts +3 -18
  152. package/srv/utils/signing-helper.js +10 -32
  153. package/srv/utils/tx-build-helper.d.ts +26 -92
  154. package/srv/utils/tx-build-helper.js +68 -123
  155. package/srv/utils/tx-request-parsers.d.ts +107 -21
  156. package/srv/utils/tx-request-parsers.js +433 -34
  157. package/srv/utils/tx-utils.d.ts +4 -23
  158. package/srv/utils/tx-utils.js +12 -41
  159. package/srv/utils/types.d.ts +238 -169
  160. package/srv/utils/types.js +2 -6
  161. package/srv/utils/validators.d.ts +24 -90
  162. package/srv/utils/validators.js +50 -147
@@ -4,39 +4,26 @@ 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");
12
19
  const backend_request_handler_1 = require("../../utils/backend-request-handler");
13
20
  const errors_1 = require("../../utils/errors");
21
+ const ogmios_frame_guard_1 = require("./ogmios-frame-guard");
22
+ const epoch_slots_1 = require("../../utils/epoch-slots");
14
23
  const mappers_1 = require("../../utils/mappers");
15
24
  const const_1 = require("../../utils/const");
16
25
  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
- */
26
+ /** Parse an Ogmios `Ratio` ("num/den", e.g. "3/1000") into a number; `Number("3/1000")` is NaN. */
40
27
  function parseOgmiosRatio(ratio) {
41
28
  if (ratio === null || ratio === undefined)
42
29
  return 0;
@@ -50,11 +37,37 @@ function parseOgmiosRatio(ratio) {
50
37
  const n = Number(ratio);
51
38
  return Number.isFinite(n) ? n : 0;
52
39
  }
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
- */
40
+ const SCRIPT_LANGUAGE_TAG = { native: 0, 'plutus:v1': 1, 'plutus:v2': 2, 'plutus:v3': 3 };
41
+ /** Hash of an Ogmios `Script`: blake2b-224 over the language tag byte followed by the script CBOR. */
42
+ function ogmiosScriptHash(script) {
43
+ const s = script;
44
+ const tag = s?.language === undefined ? undefined : SCRIPT_LANGUAGE_TAG[s.language];
45
+ if (tag === undefined || typeof s?.cbor !== 'string' || s.cbor.length === 0)
46
+ return null;
47
+ const bytes = Uint8Array.from(Buffer.concat([Buffer.from([tag]), Buffer.from(s.cbor, 'hex')]));
48
+ return Buffer.from((0, crypto_1.blake2b_224)(bytes)).toString('hex');
49
+ }
50
+ /** Full CBOR of a Plutus reference script as Ogmios delivers it; null for native or absent scripts. */
51
+ function ogmiosPlutusScriptCbor(script) {
52
+ const s = script;
53
+ return s?.language?.startsWith('plutus:') && typeof s.cbor === 'string' && s.cbor.length > 0 ? s.cbor : null;
54
+ }
55
+ /** Bech32 pool id of a block issuer: blake2b-224 of its cold verification key. */
56
+ function issuerKeyToPoolId(verificationKeyHex) {
57
+ const keyHash = (0, crypto_1.blake2b_224)(Uint8Array.from(Buffer.from(verificationKeyHex, 'hex')));
58
+ return bech32_1.bech32.encode('pool', bech32_1.bech32.toWords(keyHash));
59
+ }
60
+ /** CIP-129 DRep id for a registered DRep, the predefined id for abstain / no confidence. */
61
+ function ogmiosDrepToId(d) {
62
+ if (!d)
63
+ return null;
64
+ if (d.type === 'abstain')
65
+ return 'drep_always_abstain';
66
+ if (d.type === 'noConfidence')
67
+ return 'drep_always_no_confidence';
68
+ return d.id ? (0, mappers_1.credentialToDrepId)(d.id, d.from === 'script') : null;
69
+ }
70
+ /** Lovelace amount from Ogmios' value shapes; v6 returns `{ ada: { lovelace } }` objects. */
58
71
  function ogmiosValueToLovelaceString(value) {
59
72
  if (value === null || value === undefined)
60
73
  return '0';
@@ -63,6 +76,97 @@ function ogmiosValueToLovelaceString(value) {
63
76
  const lovelace = value.ada?.lovelace;
64
77
  return lovelace === undefined ? '0' : String(lovelace);
65
78
  }
79
+ /** Fraction a/b of two lovelace amounts; 0 when b is 0. */
80
+ function ratio(a, b) {
81
+ return b === 0n ? 0 : Number((a * 1000000n) / b) / 1_000_000;
82
+ }
83
+ /**
84
+ * Ogmios ledger answers -> EpochLedgerState. Saturation follows the ledger: live stake over
85
+ * (max supply - reserves) / nOpt. Figures the ledger view does not carry stay 0 / null: active
86
+ * stake (the indexer derives it from the previous snapshot), block counts, delegator counts,
87
+ * DRep last activity.
88
+ */
89
+ function mapOgmiosEpochState(raw) {
90
+ const lovelace = (v) => BigInt(ogmiosValueToLovelaceString(v));
91
+ const reserves = raw.pots?.reserves ? lovelace(raw.pots.reserves) : null;
92
+ const nOpt = raw.performances?.desiredNumberOfStakePools ?? 0;
93
+ const saturationPoint = reserves != null && nOpt > 0
94
+ ? (BigInt(const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY) - reserves) / BigInt(nOpt)
95
+ : 0n;
96
+ const entries = Object.entries(raw.stakePools);
97
+ const liveTotal = entries.reduce((sum, [, p]) => sum + lovelace(p.stake), 0n);
98
+ const pools = entries.map(([poolId, p]) => {
99
+ const live = lovelace(p.stake);
100
+ return {
101
+ poolId,
102
+ vrfKeyHash: p.vrfVerificationKeyHash || '',
103
+ blocksMinted: 0,
104
+ blocksEpoch: null,
105
+ liveStake: live.toString(),
106
+ liveSize: ratio(live, liveTotal),
107
+ liveSaturation: ratio(live, saturationPoint),
108
+ liveDelegators: null,
109
+ activeStake: '0',
110
+ activeSize: 0,
111
+ pledge: ogmiosValueToLovelaceString(p.pledge),
112
+ margin: parseOgmiosRatio(p.margin),
113
+ fixedCost: ogmiosValueToLovelaceString(p.cost),
114
+ rewardAccount: p.rewardAccount || '',
115
+ };
116
+ });
117
+ let abstain = null;
118
+ let noConfidence = null;
119
+ const dreps = [];
120
+ for (const d of raw.dreps) {
121
+ if (d.type === 'abstain') {
122
+ abstain = (abstain ?? 0n) + lovelace(d.stake);
123
+ continue;
124
+ }
125
+ if (d.type === 'noConfidence') {
126
+ noConfidence = (noConfidence ?? 0n) + lovelace(d.stake);
127
+ continue;
128
+ }
129
+ if (d.type !== 'registered' || !d.id)
130
+ continue;
131
+ const mandate = d.mandate?.epoch;
132
+ dreps.push({
133
+ drepId: (0, mappers_1.credentialToDrepId)(d.id, d.from === 'script'),
134
+ hex: d.id,
135
+ amount: ogmiosValueToLovelaceString(d.stake),
136
+ hasScript: d.from === 'script',
137
+ lastActiveEpoch: 0,
138
+ expired: typeof mandate === 'number' && mandate < raw.epoch,
139
+ retired: false,
140
+ deposit: d.deposit ? ogmiosValueToLovelaceString(d.deposit) : null,
141
+ expiresEpoch: typeof mandate === 'number' ? mandate : null,
142
+ delegatorCount: Array.isArray(d.delegators) ? d.delegators.length : null,
143
+ });
144
+ }
145
+ return {
146
+ epoch: raw.epoch,
147
+ pools,
148
+ dreps,
149
+ treasury: raw.pots?.treasury ? ogmiosValueToLovelaceString(raw.pots.treasury) : null,
150
+ reserves: reserves == null ? null : reserves.toString(),
151
+ drepAbstainStake: abstain == null ? null : abstain.toString(),
152
+ drepNoConfidenceStake: noConfidence == null ? null : noConfidence.toString(),
153
+ };
154
+ }
155
+ /**
156
+ * Decode a CIP-129 DRep ID (`drep1…`, 29 bytes) into credential hash and type. Header byte:
157
+ * high nibble 0x2 = DRep, low nibble 0x2 = key hash / 0x3 = script hash.
158
+ */
159
+ function decodeDrepId(drepId) {
160
+ const decoded = bech32_1.bech32.decode(drepId, const_1.BECH32_MAX_LENGTH);
161
+ const bytes = Buffer.from(bech32_1.bech32.fromWords(decoded.words));
162
+ if (decoded.prefix !== 'drep' || bytes.length !== 29) {
163
+ throw new errors_1.NotFoundError('Drep', 'ogmios');
164
+ }
165
+ return {
166
+ hashHex: bytes.subarray(1).toString('hex'),
167
+ isScript: (bytes[0] & 0x0f) === 0x03,
168
+ };
169
+ }
66
170
  /** Resolve Ogmios ledger tip which may be 'origin' (genesis block) or a point */
67
171
  function resolveOgmiosTip(tip) {
68
172
  return tip === 'origin' ? { slot: 0, hash: '' } : { slot: tip.slot, hash: tip.id };
@@ -71,15 +175,34 @@ function resolveOgmiosTip(tip) {
71
175
  function resolveOgmiosHeight(height) {
72
176
  return height === 'origin' ? 0 : height;
73
177
  }
178
+ /**
179
+ * Redeemers of a chain-sync tx. A spend index points into the body inputs sorted by
180
+ * (txHash, index), a mint index into the sorted policy ids; both are resolved here.
181
+ */
182
+ function mapOgmiosRedeemers(tx) {
183
+ 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 }));
184
+ const sortedPolicies = Object.keys(tx.mint ?? {}).sort();
185
+ return (tx.redeemers ?? []).map((r) => {
186
+ const { purpose, index } = r.validator;
187
+ const spent = purpose === 'spend' ? sortedInputs[index] : undefined;
188
+ return {
189
+ purpose,
190
+ index,
191
+ data: r.redeemer,
192
+ mem: r.executionUnits.memory.toString(),
193
+ steps: r.executionUnits.cpu.toString(),
194
+ txHash: spent?.transaction.id ?? null,
195
+ outputIndex: spent?.index ?? null,
196
+ policyId: purpose === 'mint' ? (sortedPolicies[index] ?? null) : null,
197
+ };
198
+ });
199
+ }
200
+ /** CardanoBackend implementation over an Ogmios WebSocket (local node). */
74
201
  class OgmiosBackend {
75
202
  name = 'ogmios';
76
203
  /**
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.
204
+ * Capability declaration — the orchestrator skips Ogmios for these without counting
205
+ * circuit failures. Historic queries are out of protocol scope.
83
206
  */
84
207
  unsupportedMethods = new Set([
85
208
  // getEpoch is NOT listed: Ogmios can serve the CURRENT epoch and only
@@ -88,22 +211,22 @@ class OgmiosBackend {
88
211
  'getTransaction',
89
212
  'getTransactionMetadata',
90
213
  'getAddressTransactions',
91
- 'getDrep',
214
+ // getDrep is NOT listed: served from the live ledger state via
215
+ // queryLedgerState/delegateRepresentatives (Ogmios ≥ 6.4).
92
216
  'getAssetInfo',
93
- 'getAddress',
94
- 'getNetworkInformation',
95
217
  ]);
96
218
  stateQueryClient = null;
97
219
  txSubmissionClient = null;
98
220
  context = null;
221
+ /** Second connection for address queries (see scanQueryClient). */
222
+ scanClient = null;
223
+ scanContext = null;
224
+ scanConnecting = null;
99
225
  isShutdown = false;
100
226
  reconnectPromise = null;
101
227
  network;
102
228
  timeoutMs;
103
229
  ogmiosUrl;
104
- /**
105
- * Constructor
106
- */
107
230
  constructor(network, timeoutMs, ogmiosUrl) {
108
231
  if (!ogmiosUrl) {
109
232
  throw new errors_1.BackendInitError('ogmios', new Error('ogmiosUrl is not set'));
@@ -113,21 +236,9 @@ class OgmiosBackend {
113
236
  this.ogmiosUrl = ogmiosUrl;
114
237
  }
115
238
  /**
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.
239
+ * Force non-keep-alive HTTP for the Ogmios `/health` probe: node-fetch v2 uses `http.globalAgent`,
240
+ * whose pooled sockets (kept alive since Node 19) fail with "Premature close" once Ogmios' Warp server
241
+ * half-closes them. No agent hook exists, so keep-alive is disabled process-wide for `http://` only.
131
242
  */
132
243
  static keepAliveDisabled = false;
133
244
  static disableHttpKeepAlive() {
@@ -155,17 +266,12 @@ class OgmiosBackend {
155
266
  }
156
267
  }
157
268
  /**
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.
269
+ * Bound an init step in time: the WebSocket connect/handshake has no built-in timeout and
270
+ * can hang when the node is busy. The rejection message contains "timeout" so the
271
+ * orchestrator's transient-error retry picks it up.
164
272
  */
165
273
  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.
274
+ // Short on purpose: the orchestrator retries init several times within a bounded bootstrap window.
169
275
  const ms = Math.max(1, Math.min(this.timeoutMs, 4000));
170
276
  let timer;
171
277
  const timeout = new Promise((_, reject) => {
@@ -175,10 +281,8 @@ class OgmiosBackend {
175
281
  return Promise.race([p, timeout]).finally(() => clearTimeout(timer));
176
282
  }
177
283
  /**
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.
284
+ * Force-release an interaction socket after a failed/expired open or close. The runtime
285
+ * socket is `ws` (has `terminate`); the `close` fallback keeps test doubles working.
182
286
  */
183
287
  forceCloseContext(context) {
184
288
  const socket = context.socket;
@@ -194,9 +298,7 @@ class OgmiosBackend {
194
298
  // Best effort only: the socket may already have completed its close event.
195
299
  }
196
300
  }
197
- /**
198
- * Initialize the Ogmios backend connection
199
- */
301
+ /** Open the interaction context and the query/submission clients. */
200
302
  async init() {
201
303
  OgmiosBackend.disableHttpKeepAlive();
202
304
  OgmiosBackend.validateOgmiosUrl(this.ogmiosUrl);
@@ -209,9 +311,7 @@ class OgmiosBackend {
209
311
  const context = await this.withInitTimeout((0, client_1.createInteractionContext)(
210
312
  /* c8 ignore next */
211
313
  (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.
314
+ // Socket closed: clear the clients so the next request reconnects via ensureConnected.
215
315
  if (this.isShutdown)
216
316
  return;
217
317
  logger.warn('[OgmiosBackend] WebSocket closed — will reconnect on next request');
@@ -235,10 +335,40 @@ class OgmiosBackend {
235
335
  return true;
236
336
  }
237
337
  /**
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.
338
+ * Query client for address queries. The node answers them by scanning its whole UTxO set (seconds
339
+ * each), and Ogmios serves the queries of one connection in order; on their own connection they no
340
+ * longer hold up tip, epoch and protocol parameters. Opened on first use, reopened after a close.
341
+ */
342
+ async scanQueryClient() {
343
+ this.ensureNotShutdown();
344
+ // never initialized (test-injected clients): the shared client
345
+ if (!this.context)
346
+ return this.stateQueryClient;
347
+ const socket = this.scanContext?.socket;
348
+ if (this.scanClient && socket && socket.readyState === (socket.OPEN ?? 1))
349
+ return this.scanClient;
350
+ if (!this.scanConnecting) {
351
+ this.scanConnecting = (async () => {
352
+ const url = new URL(this.ogmiosUrl);
353
+ const connection = { host: url.hostname, port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80), tls: url.protocol === 'wss:' };
354
+ 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');
355
+ try {
356
+ const client = await this.withInitTimeout((0, client_1.createLedgerStateQueryClient)(context), 'scan/ledgerStateQueryClient');
357
+ this.scanContext = context;
358
+ this.scanClient = client;
359
+ return client;
360
+ }
361
+ catch (err) {
362
+ this.forceCloseContext(context);
363
+ throw err;
364
+ }
365
+ })().finally(() => { this.scanConnecting = null; });
366
+ }
367
+ return this.scanConnecting;
368
+ }
369
+ /**
370
+ * Reconnect when the WebSocket died since the last init. No-op when never initialized
371
+ * (test-injected clients); concurrent callers share one reconnect attempt.
242
372
  */
243
373
  async ensureConnected() {
244
374
  this.ensureNotShutdown();
@@ -274,13 +404,11 @@ class OgmiosBackend {
274
404
  async getEpoch(epochNumber) {
275
405
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
276
406
  await this.ensureConnected();
277
- // Get current epoch directly via epoch() query
278
407
  const currentEpoch = await this.stateQueryClient.epoch();
279
408
  // Ogmios only supports current epoch queries
280
409
  if (epochNumber !== currentEpoch) {
281
410
  throw new errors_1.NotFoundError(`Historic Epoch ${epochNumber} not supported (current: ${currentEpoch})`, this.name);
282
411
  }
283
- // Return current epoch data
284
412
  return this.getLatestEpoch();
285
413
  }, this.name);
286
414
  }
@@ -305,13 +433,50 @@ class OgmiosBackend {
305
433
  }, this.name);
306
434
  }
307
435
  /**
308
- * Get specific Drep Data (not supported for Ogmios)
309
- * @param _drepId drep id
310
- * @returns {Promise<DrepData>} drep data
436
+ * DRep data from the live ledger state (`queryLedgerState/delegateRepresentatives`) via the
437
+ * raw `Method()` primitive, since the client ships no wrapper. Ogmios lists only REGISTERED
438
+ * DReps: retired/unknown → NotFoundError; `expired` is derived from the mandate epoch.
439
+ * @param drepId CIP-129 bech32 DRep ID (`drep1…`)
311
440
  */
312
- async getDrep(_drepId) {
441
+ async getDrep(drepId) {
313
442
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
314
- throw new errors_1.ProviderUnavailableError('DRep queries not supported by Ogmios backend', this.name);
443
+ await this.ensureConnected();
444
+ if (!this.context) {
445
+ throw new errors_1.ProviderUnavailableError('Ogmios interaction context not available', this.name);
446
+ }
447
+ const { hashHex, isScript } = decodeDrepId(drepId);
448
+ const [summaries, currentEpoch] = await Promise.all([
449
+ (0, client_1.Method)({
450
+ method: 'queryLedgerState/delegateRepresentatives',
451
+ params: isScript ? { scripts: [hashHex] } : { keys: [hashHex] },
452
+ }, {
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(Array.isArray(response.result) ? response.result : []);
459
+ }
460
+ },
461
+ }, this.context),
462
+ this.stateQueryClient.epoch(),
463
+ ]);
464
+ // Filter by id: the query is already credential-scoped, but never trust a
465
+ // broader answer (abstain/noConfidence rows carry no id and are dropped here).
466
+ const drep = summaries.find((s) => s.type === 'registered' && s.id?.toLowerCase() === hashHex);
467
+ if (!drep)
468
+ throw new errors_1.NotFoundError('Drep', this.name);
469
+ const mandateEpoch = drep.mandate?.epoch;
470
+ return {
471
+ drepId,
472
+ hex: hashHex,
473
+ amount: ogmiosValueToLovelaceString(drep.stake),
474
+ hasScript: isScript || drep.from === 'script',
475
+ // Ogmios reports the mandate (expiry) epoch, not the last activity — keep 0.
476
+ lastActiveEpoch: 0,
477
+ expired: typeof mandateEpoch === 'number' && mandateEpoch < Number(currentEpoch),
478
+ retired: false,
479
+ };
315
480
  }, this.name);
316
481
  }
317
482
  /**
@@ -325,25 +490,58 @@ class OgmiosBackend {
325
490
  }, this.name);
326
491
  }
327
492
  /**
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)
493
+ * Supply figures from `queryLedgerState/treasuryAndReserves`: total = max − reserves.
494
+ * Circulating, locked and stake totals are not in the ledger state and stay '0'.
332
495
  */
333
496
  async getNetworkInformation() {
334
497
  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);
498
+ await this.ensureConnected();
499
+ if (!this.context) {
500
+ throw new errors_1.ProviderUnavailableError('Ogmios interaction context not available', this.name);
501
+ }
502
+ const pots = await (0, client_1.Method)({ method: 'queryLedgerState/treasuryAndReserves' }, {
503
+ handler: (response, resolve, reject) => {
504
+ if (response.error) {
505
+ reject(new Error(response.error.message ?? `Ogmios error ${response.error.code ?? ''}`.trim()));
506
+ }
507
+ else {
508
+ resolve(response.result ?? {});
509
+ }
510
+ },
511
+ }, this.context);
512
+ const max = const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY;
513
+ const reserves = ogmiosValueToLovelaceString(pots.reserves);
514
+ return {
515
+ supply: {
516
+ max,
517
+ total: (BigInt(max) - BigInt(reserves)).toString(),
518
+ circulating: '0',
519
+ locked: '0',
520
+ treasury: ogmiosValueToLovelaceString(pots.treasury),
521
+ reserves,
522
+ },
523
+ stake: { live: '0', active: '0' },
524
+ };
336
525
  }, this.name);
337
526
  }
338
527
  /**
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.)
528
+ * Address at the tip: type, script flag and stake address decoded from the address itself,
529
+ * UTxOs from the ledger, balance summed over them. No transaction history (getAddressTransactions).
343
530
  */
344
- async getAddress(_address) {
531
+ async getAddress(address) {
345
532
  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);
533
+ await this.ensureConnected();
534
+ const decoded = (0, mappers_1.decodeShelleyAddress)(address);
535
+ const raw = await (await this.scanQueryClient()).utxo({ addresses: [address] });
536
+ const utxos = raw.map((u) => this.mapOgmiosUtxo(u, address));
537
+ return {
538
+ address,
539
+ stakeAddress: decoded.stakeAddress,
540
+ type: decoded.type,
541
+ isScript: decoded.isScript,
542
+ amount: (0, mappers_1.sumUtxoAmounts)(utxos),
543
+ utxos,
544
+ };
347
545
  }, this.name);
348
546
  }
349
547
  /** get current specific Address UTxOs
@@ -353,31 +551,85 @@ class OgmiosBackend {
353
551
  async getAddressUtxos(address) {
354
552
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
355
553
  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
- });
554
+ const utxos = await (await this.scanQueryClient()).utxo({ addresses: [address] });
555
+ return utxos.map((u) => this.mapOgmiosUtxo(u, address));
373
556
  }, this.name);
374
557
  }
558
+ /** Ogmios `Utxo` entry → normalized UTxO line (shared by the address query and the set import). */
559
+ mapOgmiosUtxo(u, fallbackAddress = '') {
560
+ return {
561
+ txHash: u.transaction?.id || '',
562
+ outputIndex: u.index || 0,
563
+ address: u.address || fallbackAddress,
564
+ amount: this.convertOgmiosValue(u.value),
565
+ blockHash: '',
566
+ datumHash: u.datumHash,
567
+ // Ogmios delivers the inline datum as CBOR hex in `datum`
568
+ inlineDatum: typeof u.datum === 'string' ? u.datum : null,
569
+ scriptRef: ogmiosScriptHash(u.script) ?? undefined,
570
+ scriptRefCbor: ogmiosPlutusScriptCbor(u.script),
571
+ };
572
+ }
375
573
  /**
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
574
+ * Run `fn` against the ledger state acquired at `point` on a SEPARATE WebSocket: local-state-query
575
+ * holds one acquired point per connection, so the shared socket would pin live queries to the past.
576
+ * The point must be inside the node's volatile window (k blocks) or acquisition is refused.
380
577
  */
578
+ async withLedgerStateAt(point, label, fn) {
579
+ const url = new URL(this.ogmiosUrl);
580
+ const connection = { host: url.hostname, port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80), tls: url.protocol === 'wss:' };
581
+ const context = await (0, client_1.createInteractionContext)((err) => logger.error(`[OgmiosBackend] ${label} context error: ${err.message}`), () => { }, { connection });
582
+ let client = null;
583
+ try {
584
+ client = await (0, client_1.createLedgerStateQueryClient)(context, { point: { slot: point.slot, id: point.hash } });
585
+ return await fn(client);
586
+ }
587
+ finally {
588
+ // shutdown() closes THIS connection only; the backend's own socket is untouched
589
+ if (client) {
590
+ try {
591
+ await client.shutdown();
592
+ }
593
+ catch { /* best effort */ }
594
+ }
595
+ else
596
+ this.forceCloseContext(context);
597
+ }
598
+ }
599
+ /** Whole UTxO set as of `point` (crawler snapshot import). */
600
+ async queryUtxoSetAt(point) {
601
+ return (0, backend_request_handler_1.handleBackendRequest)(() => this.withLedgerStateAt(point, 'snapshot', async (client) => {
602
+ const utxos = await client.utxo();
603
+ return utxos.map((u) => this.mapOgmiosUtxo(u));
604
+ }), this.name);
605
+ }
606
+ /**
607
+ * Pools, DReps and pots as of `point` (crawler epoch snapshot), all read from one acquired
608
+ * ledger state. Performances are optional: without them (no nOpt) saturation stays 0.
609
+ */
610
+ async epochStateAt(point) {
611
+ return (0, backend_request_handler_1.handleBackendRequest)(() => this.withLedgerStateAt(point, 'epoch snapshot', async (client) => {
612
+ const ctx = client.context;
613
+ const [epoch, stakePools, performances, dreps, pots] = await Promise.all([
614
+ client.epoch(),
615
+ client.stakePools(undefined, true),
616
+ client.stakePoolsPerformances().catch((err) => {
617
+ logger.warn(`stakePoolsPerformances unavailable, saturation stays 0: ${err?.message ?? err}`);
618
+ return null;
619
+ }),
620
+ (0, client_1.Method)({ method: 'queryLedgerState/delegateRepresentatives' }, {}, ctx),
621
+ (0, client_1.Method)({ method: 'queryLedgerState/treasuryAndReserves' }, {}, ctx),
622
+ ]);
623
+ return mapOgmiosEpochState({
624
+ epoch: Number(epoch),
625
+ stakePools: (stakePools ?? {}),
626
+ performances: performances,
627
+ dreps: Array.isArray(dreps) ? dreps : [],
628
+ pots: pots ?? null,
629
+ });
630
+ }), this.name);
631
+ }
632
+ /** Not supported — Ogmios is a live state-query backend; use Blockfrost/Koios. */
381
633
  async getAddressTransactions(_address) {
382
634
  throw new errors_1.NotFoundError('Address transactions not available via Ogmios - use historical backend (Blockfrost/Koios)', this.name);
383
635
  }
@@ -391,25 +643,26 @@ class OgmiosBackend {
391
643
  await this.ensureConnected();
392
644
  // Query from tip (no acquire needed) with stake included
393
645
  const pools = await this.stateQueryClient.stakePools([{ id: poolId }], true);
394
- // Extract pool from response - stakePools returns object keyed by poolId
646
+ // stakePools returns an object keyed by poolId
395
647
  const pool = pools[poolId];
396
648
  if (!pool)
397
649
  throw new errors_1.NotFoundError('Pool', this.name);
398
650
  return {
399
651
  poolId,
400
- vrfKeyHash: pool.vrf || pool.vrfKeyHash || '',
652
+ vrfKeyHash: pool.vrfVerificationKeyHash || '',
401
653
  blocksMinted: 0,
402
- blocksEpoch: 0,
654
+ // not in the ledger state; null = unavailable, as on Koios
655
+ blocksEpoch: null,
403
656
  liveStake: pool.stake?.ada?.lovelace ? String(pool.stake.ada.lovelace) : '0',
404
657
  liveSize: 0,
405
- liveDelegators: 0,
658
+ // not in the ledger state; null = unavailable
659
+ liveDelegators: null,
406
660
  liveSaturation: 0,
407
661
  // activeStake is not available from Ogmios pool params — report 0 instead
408
662
  // of fabricating it from the pledge
409
663
  activeStake: '0',
410
664
  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")
665
+ // pledge/cost are ValueAdaOnly objects in Ogmios v6; margin is a Ratio string ("1/10")
413
666
  pledge: ogmiosValueToLovelaceString(pool.pledge),
414
667
  margin: parseOgmiosRatio(pool.margin),
415
668
  fixedCost: ogmiosValueToLovelaceString(pool.cost),
@@ -430,7 +683,6 @@ class OgmiosBackend {
430
683
  const summaries = Array.isArray(rawResult)
431
684
  ? rawResult
432
685
  : Object.values(rawResult);
433
- // Ogmios API returns array of account summaries
434
686
  const account = summaries && summaries.length > 0 ? summaries[0] : null;
435
687
  if (!account) {
436
688
  throw new errors_1.NotFoundError('Account', this.name);
@@ -441,14 +693,15 @@ class OgmiosBackend {
441
693
  // reaching this point (summary found) therefore implies the account is active.
442
694
  active: true,
443
695
  activeEpoch: 0,
444
- controlledAmount: ogmiosValueToLovelaceString(account.controlledAmount),
696
+ // reward-account summaries carry no controlled amount and no withdrawal totals
697
+ controlledAmount: '0',
445
698
  rewardsSum: ogmiosValueToLovelaceString(account.rewards),
446
- withdrawalsSum: ogmiosValueToLovelaceString(account.withdrawals),
699
+ withdrawalsSum: '0',
447
700
  reservesSum: '0',
448
701
  treasurySum: '0',
449
702
  withdrawableAmount: ogmiosValueToLovelaceString(account.rewards),
450
- poolId: account.delegate?.id || account.delegation?.poolId || null,
451
- drepId: account.vote?.id || account.drep?.id || null,
703
+ poolId: account.stakePool?.id || null,
704
+ drepId: ogmiosDrepToId(account.delegateRepresentative),
452
705
  addresses: []
453
706
  };
454
707
  }, this.name);
@@ -461,8 +714,22 @@ class OgmiosBackend {
461
714
  async submitTransaction(signedTxCbor) {
462
715
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
463
716
  await this.ensureConnected();
464
- const txHash = await this.txSubmissionClient.submitTransaction(signedTxCbor);
465
- return txHash;
717
+ try {
718
+ return await this.txSubmissionClient.submitTransaction(signedTxCbor);
719
+ }
720
+ catch (err) {
721
+ // JSON-RPC 3000-3999: the node rejected the transaction. Known kinds keep their class
722
+ // (already submitted = 409, script failure = 400); anything else becomes a 400 with its reason.
723
+ const known = (0, errors_1.normalizeBackendError)(err, this.name);
724
+ if (known.statusCode >= 400 && known.statusCode < 500)
725
+ throw known;
726
+ const e = err;
727
+ if (typeof e?.code === 'number' && e.code >= 3000 && e.code < 4000) {
728
+ const detail = e.data === undefined ? '' : ` ${JSON.stringify(e.data).slice(0, 800)}`;
729
+ throw new errors_1.TransactionValidationError(`node rejected the transaction (${e.code}): ${String(e.message ?? '')}${detail}`, err);
730
+ }
731
+ throw err;
732
+ }
466
733
  }, this.name);
467
734
  }
468
735
  /**
@@ -473,8 +740,23 @@ class OgmiosBackend {
473
740
  async evaluateTransaction(unsignedTxCbor) {
474
741
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
475
742
  await this.ensureConnected();
476
- const results = await this.txSubmissionClient.evaluateTransaction(unsignedTxCbor);
477
- return results;
743
+ try {
744
+ const results = await this.txSubmissionClient.evaluateTransaction(unsignedTxCbor);
745
+ return results;
746
+ }
747
+ catch (err) {
748
+ // JSON-RPC 3000-3099 except 3003: the transaction cannot be evaluated as given, a 400 with its reason.
749
+ // 3003 means the node is still syncing, so it stays retryable.
750
+ const known = (0, errors_1.normalizeBackendError)(err, this.name);
751
+ if (known.statusCode >= 400 && known.statusCode < 500)
752
+ throw known;
753
+ const e = err;
754
+ if (typeof e?.code === 'number' && e.code >= 3000 && e.code < 3100 && e.code !== 3003) {
755
+ const detail = e.data === undefined ? '' : ` ${JSON.stringify(e.data).slice(0, 800)}`;
756
+ throw new errors_1.TransactionValidationError(`transaction cannot be evaluated (${e.code}): ${String(e.message ?? '')}${detail}`, err);
757
+ }
758
+ throw err;
759
+ }
478
760
  }, this.name);
479
761
  }
480
762
  /**
@@ -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,
@@ -541,14 +823,14 @@ class OgmiosBackend {
541
823
  ]);
542
824
  const { slot } = resolveOgmiosTip(tip);
543
825
  // Network-aware epoch geometry + Shelley-anchored slot→time conversion
544
- const startSlot = epochStartSlot(this.network, currentEpoch);
826
+ const startSlot = (0, epoch_slots_1.epochStartSlot)(this.network, currentEpoch);
545
827
  const endSlot = startSlot + const_1.EPOCH_CONFIG_BY_NETWORK[this.network].slotsPerEpoch;
546
828
  return {
547
829
  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),
830
+ start_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, startSlot),
831
+ end_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, endSlot),
832
+ first_block_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, startSlot),
833
+ last_block_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, slot),
552
834
  block_count: 0, // Not available from Ogmios state queries
553
835
  tx_count: 0, // Not available from Ogmios state queries
554
836
  output: '0',
@@ -572,10 +854,10 @@ class OgmiosBackend {
572
854
  ]);
573
855
  const { slot, hash } = resolveOgmiosTip(tip);
574
856
  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));
857
+ // network-aware slot-in-epoch
858
+ const epochSlot = Math.max(0, slot - (0, epoch_slots_1.epochStartSlot)(this.network, epoch));
577
859
  return {
578
- time: slotToPosixSeconds(this.network, slot), // seconds (mapBlock expects seconds)
860
+ time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, slot), // seconds (mapBlock expects seconds)
579
861
  height,
580
862
  hash,
581
863
  slot,
@@ -585,6 +867,7 @@ class OgmiosBackend {
585
867
  size: 0, // Not available via ledgerTip - would need full block data
586
868
  txCount: 0, // Not available via ledgerTip - would need full block data
587
869
  fees: '0', // Not available via ledgerTip - would need full block data
870
+ headerOnly: true,
588
871
  };
589
872
  }, this.name);
590
873
  }
@@ -600,11 +883,9 @@ class OgmiosBackend {
600
883
  return block.slot;
601
884
  }
602
885
  /**
603
- * Check whether a UTxO is still unspent via Ogmios `queryLedgerState/utxo`
604
- * with an outputReferences filter. Empty result means spent or nonexistent.
886
+ * Unspent check via `queryLedgerState/utxo` with an outputReferences filter; empty = spent or nonexistent.
605
887
  * @param txHash 64-char lowercase hex
606
888
  * @param outputIndex non-negative integer
607
- * @returns {Promise<boolean>} true iff the UTxO exists and is unspent
608
889
  */
609
890
  async isUtxoUnspent(txHash, outputIndex) {
610
891
  if (!Number.isInteger(outputIndex) || outputIndex < 0)
@@ -617,10 +898,19 @@ class OgmiosBackend {
617
898
  return Array.isArray(result) && result.length > 0;
618
899
  }, this.name);
619
900
  }
620
- /**
621
- * Shutdown the Ogmios Backend
622
- * Closes all connections and marks as shutdown
623
- */
901
+ /** Outputs among `refs` that are unspent in the live ledger; spent or unknown references are absent. */
902
+ async getUnspentOutputs(refs) {
903
+ if (refs.length === 0)
904
+ return [];
905
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
906
+ await this.ensureConnected();
907
+ const result = await this.stateQueryClient.utxo({
908
+ outputReferences: refs.map(r => ({ transaction: { id: r.txHash }, index: r.outputIndex })),
909
+ });
910
+ return result.map((u) => this.mapOgmiosUtxo(u));
911
+ }, this.name);
912
+ }
913
+ /** Close the WebSocket and mark the backend as shut down. */
624
914
  async shutdown() {
625
915
  if (this.isShutdown)
626
916
  return;
@@ -639,13 +929,14 @@ class OgmiosBackend {
639
929
  });
640
930
  }
641
931
  }
932
+ if (this.scanContext)
933
+ this.forceCloseContext(this.scanContext);
642
934
  this.stateQueryClient = null;
643
935
  this.txSubmissionClient = null;
644
936
  this.context = null;
937
+ this.scanClient = null;
938
+ this.scanContext = null;
645
939
  }
646
- /**
647
- * Check if backend is connected
648
- */
649
940
  isConnected() {
650
941
  if (this.isShutdown || !this.context?.socket) {
651
942
  return false;
@@ -656,29 +947,23 @@ class OgmiosBackend {
656
947
  // ---------------------------------------------------------------------------
657
948
  // Helpers
658
949
  // ---------------------------------------------------------------------------
659
- /**
660
- * Ensure the client is not shutdown before operations
661
- */
662
950
  ensureNotShutdown() {
663
951
  if (this.isShutdown) {
664
952
  throw new errors_1.ProviderUnavailableError('Ogmios client has been shutdown', this.name);
665
953
  }
666
954
  }
667
955
  /**
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' }]
956
+ * Ogmios value `{ ada: { lovelace }, policyId: { assetName: qty } }` →
957
+ * `[{ unit: 'lovelace', quantity }, { unit: policyId+assetName, quantity }]`.
671
958
  */
672
959
  convertOgmiosValue(value) {
673
960
  const amounts = [];
674
- // Handle ADA (lovelace)
675
961
  if (value.ada?.lovelace) {
676
962
  amounts.push({
677
963
  unit: 'lovelace',
678
964
  quantity: value.ada.lovelace.toString()
679
965
  });
680
966
  }
681
- // handle native assets (policy.assetName)
682
967
  for (const [policyId, assets] of Object.entries(value)) {
683
968
  if (policyId === 'ada')
684
969
  continue;
@@ -692,20 +977,12 @@ class OgmiosBackend {
692
977
  return amounts;
693
978
  }
694
979
  // ---------------------------------------------------------------------------
695
- // ChainSyncBackend — streamed forward sync for the chain crawler (v2.0)
980
+ // ChainSyncBackend — streamed forward sync for the chain crawler
696
981
  // ---------------------------------------------------------------------------
697
982
  /**
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.
983
+ * Open a long-lived chain-sync stream on its own WebSocket. `sequential: true` + `inFlight: 1`
984
+ * deliver blocks strictly in order (required by reorg detection and serial persist). Inputs arrive
985
+ * as bare references (resolved by the indexer from indexed outputs); per-tx size/deposit are not surfaced.
709
986
  */
710
987
  async openChainSync(from, callbacks) {
711
988
  OgmiosBackend.validateOgmiosUrl(this.ogmiosUrl);
@@ -731,6 +1008,12 @@ class OgmiosBackend {
731
1008
  logger.error('[OgmiosBackend] chain-sync onError callback failed:', callbackError);
732
1009
  }
733
1010
  };
1011
+ // A frame the client's parser cannot handle throws inside the library's un-awaited socket
1012
+ // handler and would end the process; the guard routes it here as a stream error instead.
1013
+ // Registered per open and removed on close, so concurrent streams each get the report.
1014
+ const unregisterFrameGuard = (0, ogmios_frame_guard_1.installOgmiosFrameGuard)(({ height, id, reason }) => {
1015
+ void reportStreamError(new errors_1.ChainSyncFrameError(height, id, reason));
1016
+ });
734
1017
  const contextPromise = (0, client_1.createInteractionContext)((err) => {
735
1018
  logger.error(`[OgmiosBackend] chain-sync context error: ${err.message}`);
736
1019
  void reportStreamError(err);
@@ -738,7 +1021,7 @@ class OgmiosBackend {
738
1021
  if (intentionalClose || this.isShutdown)
739
1022
  return;
740
1023
  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);
1024
+ const err = new errors_1.ChainSyncClosedError(`Ogmios chain-sync socket closed unexpectedly (code ${code}: ${detail})`, this.name);
742
1025
  logger.warn(`[OgmiosBackend] ${err.message}`);
743
1026
  void reportStreamError(err);
744
1027
  }, { connection });
@@ -750,14 +1033,13 @@ class OgmiosBackend {
750
1033
  // A timeout rejects our race but cannot cancel the library's health probe /
751
1034
  // handshake. If it resolves later, close that late socket as well.
752
1035
  intentionalClose = true;
1036
+ unregisterFrameGuard();
753
1037
  void contextPromise.then(lateContext => this.forceCloseContext(lateContext)).catch(() => undefined);
754
1038
  throw err;
755
1039
  }
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.
1040
+ // Both handlers are fully try/caught: the client awaits them without a catch, and with
1041
+ // sequential+inFlight:1 a throw before nextBlock() stalls the stream. On error nextBlock()
1042
+ // is deliberately NOT called (stop, don't skip a block); the error goes to callbacks.onError.
761
1043
  const handlers = {
762
1044
  rollForward: async ({ block, tip }, nextBlock) => {
763
1045
  try {
@@ -802,6 +1084,7 @@ class OgmiosBackend {
802
1084
  }
803
1085
  catch (err) {
804
1086
  intentionalClose = true;
1087
+ unregisterFrameGuard();
805
1088
  if (client) {
806
1089
  try {
807
1090
  await this.withInitTimeout(client.shutdown(), 'chainSync/failedOpenShutdown');
@@ -819,6 +1102,7 @@ class OgmiosBackend {
819
1102
  // Idempotency matters when an operator stop races an onError-triggered halt.
820
1103
  if (!closePromise) {
821
1104
  intentionalClose = true;
1105
+ unregisterFrameGuard();
822
1106
  closePromise = (async () => {
823
1107
  try {
824
1108
  await this.withInitTimeout(client.shutdown(), 'chainSync/shutdown');
@@ -834,24 +1118,22 @@ class OgmiosBackend {
834
1118
  };
835
1119
  }
836
1120
  /**
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).
1121
+ * Map an Ogmios Praos block to BlockData + transactions. Block fees are the sum of per-tx
1122
+ * fees; epoch/epochSlot derive from the slot via the Shelley anchor. A phase-2 failure without
1123
+ * `total_collateral` still carries its declared fee here; applyCollateralFees() corrects it.
840
1124
  */
841
1125
  mapOgmiosBlock(block) {
842
1126
  const txs = (block.transactions ?? []).map((t, i) => this.mapOgmiosTx(t, block, i));
843
1127
  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);
1128
+ const epoch = (0, epoch_slots_1.epochOfSlot)(this.network, block.slot);
1129
+ // Shelley-anchored helpers (handle preview/preprod geometry and the Byron offset)
1130
+ const epochSlot = block.slot - (0, epoch_slots_1.epochStartSlot)(this.network, epoch);
849
1131
  const blockData = {
850
- time: slotToPosixSeconds(this.network, block.slot),
1132
+ time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, block.slot),
851
1133
  height: block.height,
852
1134
  hash: block.id,
853
1135
  slot: block.slot,
854
- slotLeader: block.issuer?.verificationKey ?? '',
1136
+ slotLeader: block.issuer?.verificationKey ? issuerKeyToPoolId(block.issuer.verificationKey) : '',
855
1137
  epoch,
856
1138
  epochSlot,
857
1139
  size: block.size?.bytes ?? 0,
@@ -861,11 +1143,9 @@ class OgmiosBackend {
861
1143
  return { block: blockData, txs };
862
1144
  }
863
1145
  /**
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.
1146
+ * Map one chain-sync transaction. Inputs stay bare references (resolved by the indexer).
1147
+ * `spends` selects the ledger-applied partition: a phase-2-invalid tx consumes collaterals
1148
+ * and creates only its collateral-return output; the fee follows that partition too.
869
1149
  */
870
1150
  mapOgmiosTx(tx, block, index) {
871
1151
  const mapInput = (input, flags = {}) => ({
@@ -889,7 +1169,7 @@ class OgmiosBackend {
889
1169
  dataHash: output.datumHash ?? null,
890
1170
  inlineDatum: output.datum ?? null,
891
1171
  isCollateral,
892
- referenceScriptHash: null,
1172
+ referenceScriptHash: ogmiosScriptHash(output.script),
893
1173
  });
894
1174
  const outputs = spendsCollaterals
895
1175
  ? (tx.collateralReturn
@@ -905,24 +1185,95 @@ class OgmiosBackend {
905
1185
  json: v.json,
906
1186
  }))
907
1187
  : [];
908
- return {
1188
+ // A phase-2 failure pays `total_collateral`, not the declared fee; the body often omits it,
1189
+ // so the indexer derives the rest from the resolved collateral inputs later.
1190
+ const declaredFee = (tx.fee?.ada?.lovelace ?? 0).toString();
1191
+ const totalCollateral = tx.totalCollateral ? tx.totalCollateral.ada.lovelace.toString() : null;
1192
+ // the same ledger view the pagination sources produce (ordering; the partition is already applied)
1193
+ return (0, mappers_1.ledgerView)({
909
1194
  hash: tx.id,
910
1195
  blockHash: block.id,
911
1196
  blockHeight: block.height,
912
1197
  slot: block.slot,
913
1198
  index,
914
- fee: (tx.fee?.ada?.lovelace ?? 0).toString(),
1199
+ fee: spendsCollaterals ? (totalCollateral ?? declaredFee) : declaredFee,
1200
+ spendsCollaterals,
1201
+ totalCollateral,
915
1202
  deposit: '0',
1203
+ // The ledger applies no mint when the script phase failed: the body's mint field is
1204
+ // declared but never enacted, so a phase-2 failure must report none at all.
1205
+ mint: spendsCollaterals ? undefined : this.convertOgmiosValue(tx.mint ?? {}),
916
1206
  // null = unknown (chain-sync doesn't surface the serialized size) — matches the
917
1207
  // lazy path's `size ?? null` convention; 0 would masquerade as a real size
918
1208
  size: null,
919
- blockTime: slotToPosixSeconds(this.network, block.slot),
1209
+ blockTime: (0, epoch_slots_1.slotToPosixSeconds)(this.network, block.slot),
920
1210
  inputs,
921
1211
  outputs,
922
1212
  // undefined (not []) when absent — matches the Blockfrost path so
923
1213
  // mapTransaction's hasMetadata flag stays false for metadata-less txs
924
1214
  metadata: metadataEntries.length ? metadataEntries : undefined,
925
- };
1215
+ certificates: this.mapOgmiosCertificates(tx.certificates ?? []),
1216
+ withdrawals: Object.entries(tx.withdrawals ?? {}).map(([stakeAddress, value]) => ({
1217
+ stakeAddress,
1218
+ amount: (value?.ada?.lovelace ?? 0).toString(),
1219
+ })),
1220
+ redeemers: mapOgmiosRedeemers(tx),
1221
+ });
1222
+ }
1223
+ /**
1224
+ * Normalize Ogmios certificates onto the shared `CertificateKind` vocabulary. A `stakeDelegation`
1225
+ * with both pool and DRep target is split into two entries with the same index (as db-sync
1226
+ * reports it); bare credential hashes are re-encoded as bech32 to match the other tables.
1227
+ */
1228
+ mapOgmiosCertificates(certs) {
1229
+ const out = [];
1230
+ const lovelace = (v) => v?.ada?.lovelace != null ? v.ada.lovelace.toString() : null;
1231
+ const stakeAddr = (c) => c.credential ? (0, mappers_1.credentialToStakeAddress)(c.credential, c.from === 'script', this.network) : null;
1232
+ certs.forEach((c, certIndex) => {
1233
+ switch (c.type) {
1234
+ case 'stakeCredentialRegistration':
1235
+ out.push({ certIndex, kind: 'stake_registration', stakeAddress: stakeAddr(c), deposit: lovelace(c.deposit) });
1236
+ break;
1237
+ case 'stakeCredentialDeregistration':
1238
+ out.push({ certIndex, kind: 'stake_deregistration', stakeAddress: stakeAddr(c), deposit: lovelace(c.deposit) });
1239
+ break;
1240
+ case 'stakeDelegation': {
1241
+ const stakeAddress = stakeAddr(c);
1242
+ if (c.stakePool?.id)
1243
+ out.push({ certIndex, kind: 'pool_delegation', stakeAddress, poolId: c.stakePool.id });
1244
+ if (c.delegateRepresentative)
1245
+ out.push({ certIndex, kind: 'vote_delegation', stakeAddress, drepId: ogmiosDrepToId(c.delegateRepresentative) });
1246
+ break;
1247
+ }
1248
+ case 'stakePoolRegistration':
1249
+ out.push({ certIndex, kind: 'pool_registration', poolId: c.stakePool?.id ?? null });
1250
+ break;
1251
+ case 'stakePoolRetirement':
1252
+ out.push({ certIndex, kind: 'pool_retirement', poolId: c.stakePool?.id ?? null, epoch: c.stakePool?.retirementEpoch ?? null });
1253
+ break;
1254
+ case 'delegateRepresentativeRegistration':
1255
+ out.push({ certIndex, kind: 'drep_registration', drepId: ogmiosDrepToId(c.delegateRepresentative), deposit: lovelace(c.deposit) });
1256
+ break;
1257
+ case 'delegateRepresentativeUpdate':
1258
+ out.push({ certIndex, kind: 'drep_update', drepId: ogmiosDrepToId(c.delegateRepresentative) });
1259
+ break;
1260
+ case 'delegateRepresentativeRetirement':
1261
+ out.push({ certIndex, kind: 'drep_retirement', drepId: ogmiosDrepToId(c.delegateRepresentative), deposit: lovelace(c.deposit) });
1262
+ break;
1263
+ case 'constitutionalCommitteeDelegation':
1264
+ out.push({ certIndex, kind: 'committee_hot_auth' });
1265
+ break;
1266
+ case 'constitutionalCommitteeRetirement':
1267
+ out.push({ certIndex, kind: 'committee_resign' });
1268
+ break;
1269
+ case 'genesisDelegation':
1270
+ out.push({ certIndex, kind: 'genesis_delegation' });
1271
+ break;
1272
+ default:
1273
+ out.push({ certIndex, kind: c.type });
1274
+ }
1275
+ });
1276
+ return out;
926
1277
  }
927
1278
  }
928
1279
  exports.OgmiosBackend = OgmiosBackend;