@odatano/core 2.0.0-rc.4 → 2.0.0-rc.40

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 (166) 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 +305 -7
  8. package/@cds-models/CardanoODataService/index.js +34 -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 +46 -13
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +72 -0
  14. package/@cds-models/index.js +12 -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 +2297 -1633
  19. package/db/types.cds +114 -0
  20. package/package.json +27 -6
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +18 -11
  24. package/src/index.js +44 -14
  25. package/src/plugin.js +42 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +53 -162
  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 +376 -235
  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 +556 -201
  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 +87 -202
  39. package/srv/blockchain/cardano-client.js +210 -240
  40. package/srv/blockchain/cardano-indexer.d.ts +311 -242
  41. package/srv/blockchain/cardano-indexer.js +1238 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +44 -81
  43. package/srv/blockchain/cardano-tx-builder.js +173 -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 +14 -45
  68. package/srv/blockchain/signing/signature-verifier.js +73 -76
  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 +111 -173
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +649 -326
  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 +18 -23
  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 +65 -2
  102. package/srv/cardano-service.js +170 -129
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +57 -184
  105. package/srv/cardano-tx-service.cds +439 -370
  106. package/srv/cardano-tx-service.js +231 -190
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/index.d.ts +1 -1
  110. package/srv/cbor/parse.d.ts +27 -0
  111. package/srv/cbor/parse.js +63 -2
  112. package/srv/server.d.ts +28 -86
  113. package/srv/server.js +132 -135
  114. package/srv/utils/agent-grants-config.d.ts +37 -0
  115. package/srv/utils/agent-grants-config.js +138 -0
  116. package/srv/utils/agent-grants.d.ts +262 -0
  117. package/srv/utils/agent-grants.js +922 -0
  118. package/srv/utils/agent-token-auth.d.ts +16 -0
  119. package/srv/utils/agent-token-auth.js +78 -0
  120. package/srv/utils/backend-request-handler.d.ts +2 -16
  121. package/srv/utils/backend-request-handler.js +3 -18
  122. package/srv/utils/collections.d.ts +4 -8
  123. package/srv/utils/collections.js +4 -8
  124. package/srv/utils/const.d.ts +30 -67
  125. package/srv/utils/const.js +32 -72
  126. package/srv/utils/crypto.d.ts +3 -12
  127. package/srv/utils/crypto.js +5 -18
  128. package/srv/utils/db-indexes.d.ts +25 -0
  129. package/srv/utils/db-indexes.js +94 -0
  130. package/srv/utils/db-sanitize.d.ts +27 -0
  131. package/srv/utils/db-sanitize.js +85 -0
  132. package/srv/utils/epoch-slots.d.ts +20 -0
  133. package/srv/utils/epoch-slots.js +43 -0
  134. package/srv/utils/error-codes.d.ts +20 -73
  135. package/srv/utils/error-codes.js +19 -70
  136. package/srv/utils/errors.d.ts +50 -177
  137. package/srv/utils/errors.js +94 -218
  138. package/srv/utils/legacy-service-paths.d.ts +11 -0
  139. package/srv/utils/legacy-service-paths.js +58 -0
  140. package/srv/utils/liveness.d.ts +16 -0
  141. package/srv/utils/liveness.js +40 -0
  142. package/srv/utils/mappers.d.ts +128 -214
  143. package/srv/utils/mappers.js +354 -299
  144. package/srv/utils/network-context.js +2 -11
  145. package/srv/utils/pg-inline-json.d.ts +8 -0
  146. package/srv/utils/pg-inline-json.js +62 -0
  147. package/srv/utils/pg-order-nulls.d.ts +14 -0
  148. package/srv/utils/pg-order-nulls.js +56 -0
  149. package/srv/utils/plutus-placeholders.d.ts +23 -16
  150. package/srv/utils/plutus-placeholders.js +63 -27
  151. package/srv/utils/rate-limiter.d.ts +46 -0
  152. package/srv/utils/rate-limiter.js +116 -0
  153. package/srv/utils/service-events.d.ts +2 -22
  154. package/srv/utils/service-events.js +3 -23
  155. package/srv/utils/signing-helper.d.ts +6 -16
  156. package/srv/utils/signing-helper.js +36 -60
  157. package/srv/utils/tx-build-helper.d.ts +28 -93
  158. package/srv/utils/tx-build-helper.js +75 -124
  159. package/srv/utils/tx-request-parsers.d.ts +101 -28
  160. package/srv/utils/tx-request-parsers.js +410 -43
  161. package/srv/utils/tx-utils.d.ts +4 -23
  162. package/srv/utils/tx-utils.js +12 -41
  163. package/srv/utils/types.d.ts +252 -179
  164. package/srv/utils/types.js +2 -6
  165. package/srv/utils/validators.d.ts +24 -90
  166. package/srv/utils/validators.js +50 -147
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.KoiosBackend = void 0;
7
+ exports.mapKoiosCertificates = mapKoiosCertificates;
7
8
  const cds_1 = __importDefault(require("@sap/cds"));
8
9
  const axios_1 = __importDefault(require("axios"));
9
10
  const backend_request_handler_1 = require("../../utils/backend-request-handler");
@@ -21,11 +22,8 @@ const KOIOS_URLS = {
21
22
  preprod: 'https://preprod.koios.rest/api/v1',
22
23
  };
23
24
  /**
24
- * Koios `reference_script` (with `_extended: true`) is an OBJECT
25
- * `{ hash, size, type, bytes, value }` — the previous `as string` cast handed
26
- * that object downstream and broke the v1.6.1 input-side refScript feature.
27
- * Returns the full script CBOR bytes when present (what the local Plutus eval
28
- * needs), falling back to the hash (resolved on-chain only).
25
+ * Koios `reference_script` (`_extended: true`) is an object `{ hash, size, type, bytes, value }`.
26
+ * Returns the full script CBOR when present (needed for local Plutus eval), else the hash.
29
27
  */
30
28
  function koiosRefScriptBytes(ref) {
31
29
  if (!ref)
@@ -44,28 +42,40 @@ function koiosRefScriptHash(ref) {
44
42
  const obj = ref;
45
43
  return obj.hash || null;
46
44
  }
47
- /**
48
- * Sort Koios /address_txs rows newest-first. Koios gives no ordering guarantee —
49
- * a bare `slice(0, limit)` returned ARBITRARY rather than recent transactions
50
- * (Blockfrost requests `order: 'desc'` for the same data).
51
- */
45
+ /** Sort Koios /address_txs rows newest-first — Koios gives no ordering guarantee. */
52
46
  function sortAddressTxsDesc(rows) {
53
47
  return [...rows].sort((a, b) => Number(b.block_height ?? b.block_time ?? 0) - Number(a.block_height ?? a.block_time ?? 0));
54
48
  }
55
- /**
56
- * KoiosBackend Implementation for CardanoBackend Interface
57
- * Implements the CardanoBackend interface using Koios API with Axios
58
- */
49
+ /** The `error` entries of a cardano-submit-api rejection, else the body as text. */
50
+ function nodeRejection(body) {
51
+ const errors = [];
52
+ const walk = (v) => {
53
+ if (!v || typeof v !== 'object')
54
+ return;
55
+ const o = v;
56
+ if (Array.isArray(o.error))
57
+ errors.push(...o.error.map(String));
58
+ else if (typeof o.error === 'string')
59
+ errors.push(o.error);
60
+ for (const child of Object.values(o))
61
+ walk(child);
62
+ };
63
+ walk(typeof body === 'string' ? (() => { try {
64
+ return JSON.parse(body);
65
+ }
66
+ catch {
67
+ return undefined;
68
+ } })() : body);
69
+ const text = errors.length > 0 ? errors.join('; ') : (typeof body === 'string' ? body : JSON.stringify(body));
70
+ return text.slice(0, 1000);
71
+ }
72
+ /** CardanoBackend implementation on the Koios REST API (Axios). */
59
73
  class KoiosBackend {
60
74
  name = 'koios';
61
75
  api;
62
76
  network;
63
- /**
64
- * Constructor
65
- */
66
77
  constructor(network, timeoutMs, apiKey) {
67
78
  const headers = {};
68
- // Add Authorization header if API key is configured
69
79
  if (apiKey) {
70
80
  headers['Authorization'] = `Bearer ${apiKey}`;
71
81
  }
@@ -75,12 +85,9 @@ class KoiosBackend {
75
85
  headers,
76
86
  });
77
87
  this.network = network;
78
- // Koios runs multiple instances behind a load balancer; during their schema
79
- // migrations single instances serve broken SQL functions (PostgREST 400,
80
- // e.g. code 42703 "column … does not exist") or hit statement timeouts
81
- // (57014) while the rest are healthy. Such failures are instance-specific,
82
- // so a short bounded retry usually lands on a healthy instance. Genuine
83
- // client-input errors (PG class 22 etc.) are not retried.
88
+ // Koios is load-balanced; single instances serve broken SQL functions (PostgREST 400,
89
+ // e.g. 42703) or statement timeouts (57014) while others are healthy, so a short
90
+ // bounded retry usually lands on a healthy instance. Client-input errors are not retried.
84
91
  this.api.interceptors.response.use(undefined, async (error) => {
85
92
  const config = error.config;
86
93
  const pgCode = error.response?.data?.code;
@@ -95,11 +102,8 @@ class KoiosBackend {
95
102
  return this.api.request(config);
96
103
  });
97
104
  }
98
- /**
99
- * Initialize the backend
100
- */
105
+ /** Probe /tip to verify connectivity. */
101
106
  async init() {
102
- // Test connection by fetching latest block
103
107
  try {
104
108
  await this.api.get('/tip');
105
109
  }
@@ -109,18 +113,10 @@ class KoiosBackend {
109
113
  return true;
110
114
  }
111
115
  /**
112
- * Retry a Koios API call up to 3 times with exponential backoff if the
113
- * result is an empty array. Koios sometimes returns [] transiently for
114
- * valid queries — a single retry is not always sufficient for historical
115
- * epoch lookups, so we retry with increasing delays (500 → 1000 → 2000 ms).
116
+ * Retry (500 → 1000 → 2000 ms) when Koios transiently returns [] for a valid query.
117
+ * Only non-emptiness is checked here; rows keep the caller's element type.
116
118
  */
117
- // Type-agnostic retry helper: it only checks that `.data` is a non-empty
118
- // array, so the element type is intentionally `any` to avoid forcing every
119
- // Koios endpoint call site (block_info, epoch_info, account_info, …) to
120
- // declare a row shape just for the empty-array retry path. Row narrowing
121
- // happens at the use sites.
122
- async fetchWithRetryOnEmpty(fn, // eslint-disable-line @typescript-eslint/no-explicit-any
123
- label) {
119
+ async fetchWithRetryOnEmpty(fn, label) {
124
120
  const maxRetries = 3;
125
121
  const baseDelayMs = 500;
126
122
  const result = await fn();
@@ -139,13 +135,9 @@ class KoiosBackend {
139
135
  return [];
140
136
  }
141
137
  /**
142
- * Koios runs several load-balanced grest instances and they are occasionally
143
- * version-skewed: some return HTTP 400 with Postgres error 42804 ("structure
144
- * of query does not match function result type", e.g. `out_sum_lovelace`
145
- * word128 vs numeric on /epoch_info) while healthy instances serve the
146
- * IDENTICAL request fine. The same request therefore flips 200/400 between
147
- * calls. Retrying a few times lands on a healthy instance. Scoped strictly to
148
- * the 42804 type-skew error so genuine 400s (bad params) still fail fast.
138
+ * Retry on Postgres 42804 ("structure of query does not match function result type"):
139
+ * version-skewed Koios instances behind the load balancer return it for a request that
140
+ * healthy instances serve fine. Other 400s still fail fast.
149
141
  */
150
142
  async getWithRetryOn42804(url, config, label) {
151
143
  const maxRetries = 8;
@@ -224,10 +216,10 @@ class KoiosBackend {
224
216
  end_time: data.end_time,
225
217
  first_block_time: data.first_block_time,
226
218
  last_block_time: data.last_block_time,
227
- block_count: data.block_count,
219
+ block_count: data.blk_count,
228
220
  tx_count: data.tx_count,
229
- output: data.total_output,
230
- fees: data.total_fees,
221
+ output: data.out_sum,
222
+ fees: data.fees,
231
223
  active_stake: data.active_stake,
232
224
  };
233
225
  }, this.name);
@@ -245,8 +237,7 @@ class KoiosBackend {
245
237
  }
246
238
  const addressData = data[0];
247
239
  const addressUtxos = await this.getAddressUtxos(address);
248
- // Sum balances from the already-mapped UTxOs instead of re-iterating
249
- // address_info's utxo_set (whose asset_list can be null → crashed here).
240
+ // Sum balances from the mapped UTxOs; address_info's utxo_set may carry a null asset_list.
250
241
  const totals = new Map();
251
242
  for (const u of addressUtxos) {
252
243
  for (const a of u.amount) {
@@ -260,8 +251,9 @@ class KoiosBackend {
260
251
  return {
261
252
  address: address,
262
253
  stakeAddress: addressData.stake_address || null,
263
- type: addressData.address_type,
264
- isScript: addressData.is_script,
254
+ // /address_info has no address type; it follows from the address itself
255
+ type: (0, mappers_1.decodeShelleyAddress)(address).type,
256
+ isScript: addressData.script_address,
265
257
  amount: amount,
266
258
  utxos: addressUtxos,
267
259
  };
@@ -313,7 +305,6 @@ class KoiosBackend {
313
305
  outputIndex: utxo.tx_index,
314
306
  address: address,
315
307
  amount: amount,
316
- blockHash: utxo.block_hash,
317
308
  datumHash: utxo.datum_hash || null,
318
309
  scriptRef: koiosRefScriptBytes(utxo.reference_script),
319
310
  inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(utxo.inline_datum),
@@ -322,11 +313,8 @@ class KoiosBackend {
322
313
  }, this.name);
323
314
  }
324
315
  /**
325
- * Get UTxOs by payment credential. Returns UTxOs across all bech32 addresses
326
- * sharing the given 28-byte payment credential (key hash or script hash).
327
- * Native Koios endpoint — single round-trip with inline-datum hydration.
316
+ * UTxOs across all bech32 addresses sharing a payment credential (native Koios endpoint).
328
317
  * @param credHash 28-byte payment credential as 56-char lowercase hex
329
- * @returns {Promise<UTxO[]>} list of UTxOs across all bech32 forms
330
318
  */
331
319
  async getCredentialUtxos(credHash) {
332
320
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
@@ -351,7 +339,6 @@ class KoiosBackend {
351
339
  outputIndex: utxo.tx_index,
352
340
  address: utxo.address ?? '',
353
341
  amount: amount,
354
- blockHash: utxo.block_hash,
355
342
  datumHash: utxo.datum_hash || null,
356
343
  scriptRef: koiosRefScriptBytes(utxo.reference_script),
357
344
  inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(utxo.inline_datum),
@@ -365,7 +352,7 @@ class KoiosBackend {
365
352
  */
366
353
  async getNetworkInformation() {
367
354
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
368
- // Try /totals endpoint (works on mainnet, but returns empty array on preview/preprod testnet)
355
+ // /totals works on mainnet but returns [] on preview/preprod
369
356
  const { data: totalsData } = await this.api.get('/totals', {
370
357
  params: { order: 'epoch_no.desc', limit: 1 }
371
358
  });
@@ -386,8 +373,7 @@ class KoiosBackend {
386
373
  },
387
374
  };
388
375
  }
389
- // Fallback for preview/preprod network where /totals doesn't work
390
- // Use genesis endpoint to get max supply; remaining fields default to '0'
376
+ // Testnet fallback: max supply from /genesis, remaining fields '0'
391
377
  const { data: genesisData } = await this.api.get('/genesis');
392
378
  if (!genesisData || !Array.isArray(genesisData) || genesisData.length === 0) {
393
379
  throw new errors_1.NotFoundError('Genesis', this.name);
@@ -450,34 +436,36 @@ class KoiosBackend {
450
436
  if (!Array.isArray(data) || data.length === 0) {
451
437
  throw new errors_1.NotFoundError('Pool', this.name);
452
438
  }
453
- const poolData = data[0];
454
- return {
455
- poolId: poolData.pool_id_bech32 || poolData.pool_id_hex || poolId,
456
- vrfKeyHash: poolData.vrf_key_hash,
457
- blocksMinted: poolData.block_count,
458
- // Koios pool_info has no blocks-in-current-epoch figure — epoch_no
459
- // (the epoch NUMBER) was mapped here before, which is a different
460
- // semantic than Blockfrost's blocks_epoch. 0 = not available.
461
- blocksEpoch: 0,
462
- liveStake: poolData.live_stake || '0',
463
- liveSize: poolData.live_size || 0,
464
- liveDelegators: poolData.live_delegators || 0,
465
- liveSaturation: poolData.live_saturation || 0,
466
- activeStake: poolData.active_stake || '0',
467
- activeSize: poolData.active_size || 0,
468
- pledge: poolData.pledge || '0',
469
- margin: poolData.margin || 0,
470
- fixedCost: poolData.fixed_cost || '0',
471
- rewardAccount: poolData.reward_addr,
472
- };
439
+ return this._mapKoiosPool(data[0], poolId);
473
440
  }, this.name);
474
441
  }
442
+ /** Map one Koios /pool_info row to the canonical PoolData. */
443
+ _mapKoiosPool(poolData, fallbackId) {
444
+ return {
445
+ poolId: poolData.pool_id_bech32 || poolData.pool_id_hex || fallbackId,
446
+ vrfKeyHash: poolData.vrf_key_hash || '',
447
+ blocksMinted: poolData.block_count || 0,
448
+ // Koios pool_info has no blocks-in-current-epoch figure. null = not available;
449
+ // a 0 would be indistinguishable from a real zero downstream.
450
+ blocksEpoch: null,
451
+ liveStake: poolData.live_stake || '0',
452
+ // /pool_info has no live share
453
+ liveSize: null,
454
+ liveDelegators: poolData.live_delegators || 0,
455
+ // Koios reports saturation in PERCENT (75.42); PoolData holds a fraction (0.7542)
456
+ // stored in Decimal(9, 4) — the percent value would overflow the column.
457
+ liveSaturation: (Number(poolData.live_saturation) || 0) / 100,
458
+ activeStake: poolData.active_stake || '0',
459
+ activeSize: Number(poolData.sigma) || 0,
460
+ pledge: poolData.pledge || '0',
461
+ margin: poolData.margin || 0,
462
+ fixedCost: poolData.fixed_cost || '0',
463
+ rewardAccount: poolData.reward_addr || '',
464
+ };
465
+ }
475
466
  /**
476
- * Get Asset Info (supply, mint history, CIP-25 + CIP-26 metadata).
477
- * Koios's `asset_info` returns total_supply, mint/burn counts split,
478
- * minting tx + creation_time, and both on-chain and registry metadata.
467
+ * Asset info from Koios `asset_info`: supply, mint/burn counts, minting tx, CIP-25 + CIP-26 metadata.
479
468
  * @param unit policyId + assetNameHex (concatenated hex)
480
- * @returns {Promise<AssetInfo>} canonical asset info
481
469
  */
482
470
  async getAssetInfo(unit) {
483
471
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
@@ -519,16 +507,7 @@ class KoiosBackend {
519
507
  const onchainMetadata = mintMeta && typeof mintMeta === 'object'
520
508
  ? (mintMeta['721'] ?? mintMeta)
521
509
  : null;
522
- const decodeUtf8 = (hex) => {
523
- if (!hex)
524
- return null;
525
- try {
526
- return Buffer.from(hex, 'hex').toString('utf8');
527
- }
528
- catch {
529
- return null;
530
- }
531
- };
510
+ const decodeUtf8 = (hex) => (hex ? (0, mappers_1.decodeAssetName)(hex) : null);
532
511
  const mintCnt = typeof a.mint_cnt === 'number' ? a.mint_cnt : 0;
533
512
  const burnCnt = typeof a.burn_cnt === 'number' ? a.burn_cnt : 0;
534
513
  return {
@@ -552,14 +531,9 @@ class KoiosBackend {
552
531
  }, this.name);
553
532
  }
554
533
  /**
555
- * Get latest mint/burn events for an asset.
556
- * Koios's `asset_history` returns minting_txs[{ tx_hash, block_time, quantity }]
557
- * with `quantity` SIGNED (negative = burn). Action is derived from sign;
558
- * the canonical `quantity` field stores absolute value.
559
- * @param unit policyId + assetNameHex (concatenated hex)
560
- * @param limit max number of events (default 100). Note: Koios returns ALL events;
561
- * limit is applied client-side after sort-by-block_time desc.
562
- * @returns {Promise<AssetHistoryEntry[]>} list of mint/burn events (most recent first)
534
+ * Latest mint/burn events. Koios `asset_history` returns ALL events with `quantity` SIGNED
535
+ * (negative = burn): action derives from the sign, `quantity` stores the absolute value,
536
+ * `limit` is applied client-side after sorting by block_time desc.
563
537
  */
564
538
  async getAssetHistory(unit, limit = 100) {
565
539
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
@@ -568,8 +542,9 @@ class KoiosBackend {
568
542
  }
569
543
  const policyId = unit.slice(0, 56);
570
544
  const assetNameHex = unit.slice(56);
571
- const { data } = await this.api.post('/asset_history', {
572
- _asset_list: [[policyId, assetNameHex]],
545
+ // GET only: Koios answers a POST to /asset_history with 404
546
+ const { data } = await this.api.get('/asset_history', {
547
+ params: { _asset_policy: policyId, _asset_name: assetNameHex },
573
548
  });
574
549
  if (!Array.isArray(data) || data.length === 0)
575
550
  return [];
@@ -583,7 +558,8 @@ class KoiosBackend {
583
558
  action: isNegative ? 'burn' : 'mint',
584
559
  quantity: isNegative ? rawQty.slice(1) : rawQty,
585
560
  blockTime: typeof entry.block_time === 'number' ? entry.block_time : null,
586
- blockHeight: typeof entry.block_height === 'number' ? entry.block_height : null,
561
+ // minting_txs carry no block height
562
+ blockHeight: null,
587
563
  };
588
564
  });
589
565
  // Sort newest-first and cap at limit (defensive — Koios may return ascending)
@@ -605,27 +581,26 @@ class KoiosBackend {
605
581
  if (!Array.isArray(data) || data.length === 0) {
606
582
  throw new errors_1.NotFoundError('Drep', this.name);
607
583
  }
608
- const drepData = data[0];
609
- // Koios changed the /drep_info schema (observed 2026-07): the old
610
- // `expired`/`retired`/`last_active_epoch` fields were replaced by
611
- // `drep_status` ('registered' | 'retired'), `active` (boolean) and
612
- // `expires_epoch_no`. Read the old fields first (mainnet/preprod may
613
- // lag the migration), then derive from the new ones.
614
- const retired = drepData.retired ?? drepData.drep_status === 'retired';
615
- const expired = drepData.expired ?? (drepData.active === false && !retired);
616
- return {
617
- drepId: drepData.drep_id,
618
- hex: drepData.hex,
619
- amount: drepData.amount,
620
- hasScript: drepData.has_script,
621
- // The new schema no longer reports the last-activity epoch (only
622
- // `expires_epoch_no`, which has different semantics) — keep 0 there.
623
- lastActiveEpoch: drepData.last_active_epoch ?? 0,
624
- expired,
625
- retired,
626
- };
584
+ return this._mapKoiosDrep(data[0]);
627
585
  }, this.name);
628
586
  }
587
+ /** Map one Koios /drep_info row to the canonical DrepData. */
588
+ _mapKoiosDrep(drepData) {
589
+ // Koios /drep_info exposes either `expired`/`retired`/`last_active_epoch` (older schema)
590
+ // or `drep_status` ('registered' | 'retired'), `active` and `expires_epoch_no`; read both.
591
+ const retired = drepData.retired ?? drepData.drep_status === 'retired';
592
+ const expired = drepData.expired ?? (drepData.active === false && !retired);
593
+ return {
594
+ drepId: drepData.drep_id,
595
+ hex: drepData.hex,
596
+ amount: drepData.amount,
597
+ hasScript: drepData.has_script,
598
+ // The newer schema has no last-activity epoch (`expires_epoch_no` differs in meaning) — 0 then.
599
+ lastActiveEpoch: drepData.last_active_epoch ?? 0,
600
+ expired,
601
+ retired,
602
+ };
603
+ }
629
604
  /**
630
605
  * Get Account Data for specified stake address
631
606
  * @param accountId account id
@@ -640,7 +615,6 @@ class KoiosBackend {
640
615
  if (!Array.isArray(data) || data.length === 0) {
641
616
  throw new errors_1.NotFoundError('Account', this.name);
642
617
  }
643
- // Fetch associated addresses
644
618
  const addressDataResponse = await this.api.post('/account_addresses', body);
645
619
  // Koios returns [{ stake_address, addresses: [...] }], flatten to get all addresses
646
620
  const addressesFlat = addressDataResponse.data.flatMap((item) => item.addresses);
@@ -654,16 +628,17 @@ class KoiosBackend {
654
628
  const accountData = data[0];
655
629
  return {
656
630
  stakeaddress: accountData.stake_address,
657
- active: accountData.active ?? false,
658
- activeEpoch: accountData.active_epoch ?? 0,
659
- controlledAmount: accountData.controlled_amount,
660
- rewardsSum: accountData.rewards_sum,
661
- withdrawalsSum: accountData.withdrawals_sum,
662
- reservesSum: accountData.reserves_sum,
663
- treasurySum: accountData.treasury_sum,
664
- withdrawableAmount: accountData.withdrawable_amount,
665
- poolId: accountData.pool_id || null,
666
- drepId: accountData.drep_id || null,
631
+ active: accountData.status === 'registered',
632
+ // /account_info has no registration epoch
633
+ activeEpoch: 0,
634
+ controlledAmount: accountData.total_balance,
635
+ rewardsSum: accountData.rewards,
636
+ withdrawalsSum: accountData.withdrawals,
637
+ reservesSum: accountData.reserves,
638
+ treasurySum: accountData.treasury,
639
+ withdrawableAmount: accountData.rewards_available,
640
+ poolId: accountData.delegated_pool || null,
641
+ drepId: accountData.delegated_drep || null,
667
642
  addresses: addresses,
668
643
  };
669
644
  }, this.name);
@@ -677,12 +652,27 @@ class KoiosBackend {
677
652
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
678
653
  // Koios /submittx expects raw CBOR bytes with Content-Type: application/cbor
679
654
  const cborBytes = Buffer.from(signedTxCbor, 'hex');
680
- const { data } = await this.api.post('/submittx', cborBytes, {
681
- headers: { 'Content-Type': 'application/cbor' },
682
- // Prevent axios from JSON-serializing the Buffer
683
- transformRequest: [(d) => d],
684
- });
685
- return data.trim().replace(/^"|"$/g, '');
655
+ try {
656
+ const { data } = await this.api.post('/submittx', cborBytes, {
657
+ headers: { 'Content-Type': 'application/cbor' },
658
+ // Prevent axios from JSON-serializing the Buffer
659
+ transformRequest: [(d) => d],
660
+ });
661
+ return data.trim().replace(/^"|"$/g, '');
662
+ }
663
+ catch (err) {
664
+ // 400 carries the node's rejection (e.g. ExtraneousScriptWitnessesUTXOW); keep it
665
+ const response = err.response;
666
+ if (response?.status === 400 && response.data) {
667
+ const reason = nodeRejection(response.data);
668
+ // known kinds keep their class (already submitted = 409, script failure = 400)
669
+ const known = (0, errors_1.normalizeBackendError)(new Error(reason), this.name);
670
+ if (known.statusCode === 409 || known instanceof errors_1.ScriptValidationError)
671
+ throw known;
672
+ throw new errors_1.TransactionValidationError(`node rejected the transaction: ${reason}`, err);
673
+ }
674
+ throw err;
675
+ }
686
676
  }, this.name);
687
677
  }
688
678
  /**
@@ -691,10 +681,17 @@ class KoiosBackend {
691
681
  */
692
682
  async getProtocolParameters() {
693
683
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
694
- const { data } = await this.api.get('/cli_protocol_params');
684
+ // /cli_protocol_params carries no epoch; the tip does. Without it the epoch stays 0.
685
+ const [{ data }, epoch] = await Promise.all([
686
+ this.api.get('/cli_protocol_params'),
687
+ this.api.get('/tip').then((r) => Number(r.data?.[0]?.epoch_no ?? 0), (err) => {
688
+ logger.warn(`Koios /tip failed, protocol parameters without epoch: ${err instanceof Error ? err.message : String(err)}`);
689
+ return 0;
690
+ }),
691
+ ]);
695
692
  return {
696
693
  network: this.network,
697
- epoch: 0, // Koios doesn't provide current epoch in this endpoint
694
+ epoch,
698
695
  // --- Fees / Sizes ---
699
696
  minFeeA: data.txFeePerByte,
700
697
  minFeeB: data.txFeeFixed,
@@ -823,12 +820,12 @@ class KoiosBackend {
823
820
  .map(tx => tx.tx_hash);
824
821
  }, this.name);
825
822
  }
826
- /**
827
- * Batch fetch multiple transactions by hash using Koios POST /tx_info.
828
- * Sends all hashes in one request (chunked at 100 per Koios limit).
829
- * @param txHashes array of transaction hashes
830
- * @returns {Promise<Map<string, Transaction>>} map of hash -> Transaction
831
- */
823
+ /** crawler.certificates: ask /tx_info for certificates + withdrawals on the crawl's batch call. */
824
+ crawlCertificates = false;
825
+ configureCrawl(options) {
826
+ this.crawlCertificates = Boolean(options.certificates);
827
+ }
828
+ /** Batch fetch transactions via POST /tx_info, chunked at 100 hashes (Koios limit). */
832
829
  async getTransactionsBatch(txHashes) {
833
830
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
834
831
  const BATCH_SIZE = 100;
@@ -840,8 +837,9 @@ class KoiosBackend {
840
837
  _inputs: true,
841
838
  _metadata: true,
842
839
  _assets: true,
843
- _withdrawals: false,
844
- _certs: false,
840
+ // certificates + withdrawals only when the crawl will write them (larger payload)
841
+ _withdrawals: this.crawlCertificates,
842
+ _certs: this.crawlCertificates,
845
843
  _scripts: false,
846
844
  _bytecode: false,
847
845
  });
@@ -860,12 +858,9 @@ class KoiosBackend {
860
858
  }, this.name);
861
859
  }
862
860
  // ---------------------------------------------------------------------------
863
- // PaginatingBackend — forward iteration for the chain crawler (v2.0)
861
+ // PaginatingBackend — forward iteration for the chain crawler
864
862
  // ---------------------------------------------------------------------------
865
- /**
866
- * Map a Koios /block_info response object to our BlockData (same shape getBlock
867
- * maps inline; kept private to avoid touching getBlock).
868
- */
863
+ /** Map a Koios /block_info row to BlockData. */
869
864
  mapKoiosBlockInfo(data) {
870
865
  return {
871
866
  time: data.block_time,
@@ -874,7 +869,7 @@ class KoiosBackend {
874
869
  slot: data.abs_slot,
875
870
  epoch: data.epoch_no,
876
871
  epochSlot: data.epoch_slot,
877
- slotLeader: data.vrf_key,
872
+ slotLeader: data.pool ?? '',
878
873
  size: data.block_size,
879
874
  txCount: data.tx_count,
880
875
  fees: data.total_fees,
@@ -893,21 +888,17 @@ class KoiosBackend {
893
888
  }, this.name);
894
889
  }
895
890
  /**
896
- * Get up to `count` blocks following `afterHash`, in ascending chain order.
897
- * Koios has no "next after hash" endpoint, so we list blocks above the anchor height
898
- * (PostgREST gt + order + limit), then batch /block_info. When the caller already
899
- * knows the anchor height (the crawler's cursor), the hash→height resolution
900
- * round-trip is skipped entirely.
891
+ * Up to `count` blocks after `afterHash`, ascending. Koios has no "next after hash" endpoint:
892
+ * list blocks above the anchor height (PostgREST gt + order + limit), then batch /block_info.
893
+ * A known `afterHeight` skips the hash→height round-trip.
901
894
  */
902
895
  async getNextBlocks(afterHash, count, afterHeight) {
903
896
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
904
897
  let anchorHeight = afterHeight;
905
898
  if (anchorHeight != null && anchorHeight > 0) {
906
- // A height hint saves the hash -> height lookup, but it must never be
907
- // trusted as proof that the cursor is still on the canonical chain.
908
- // After a rollback Koios can continue listing canonical blocks above H
909
- // even though `afterHash` is the now-orphaned block at H. Validate the
910
- // canonical hash first so the crawler enters its reorg-recovery path.
899
+ // A height hint is not proof the cursor is still canonical: after a rollback Koios
900
+ // keeps listing blocks above H while `afterHash` is orphaned. Validate the hash first
901
+ // so the crawler enters reorg recovery.
911
902
  const canonical = await this.fetchWithRetryOnEmpty(() => this.api.get(`/blocks?block_height=eq.${anchorHeight}&limit=1`), `getNextBlocks/anchor(${anchorHeight})`);
912
903
  const canonicalHash = canonical[0]?.hash;
913
904
  if (!canonicalHash) {
@@ -921,6 +912,9 @@ class KoiosBackend {
921
912
  const info = await this.fetchWithRetryOnEmpty(() => this.api.post('/block_info', { _block_hashes: [afterHash] }), `getNextBlocks/height(${afterHash})`);
922
913
  if (!info.length)
923
914
  throw new errors_1.NotFoundError('Block', this.name);
915
+ if (info[0].block_height == null) {
916
+ throw new errors_1.ProviderUnavailableError(`Block ${afterHash} has no height on Koios and cannot anchor pagination`, this.name);
917
+ }
924
918
  anchorHeight = info[0].block_height;
925
919
  }
926
920
  const rows = await this.fetchWithRetryOnEmpty(() => this.api.get(`/blocks?block_height=gt.${anchorHeight}&order=block_height.asc&limit=${count}`), `getNextBlocks(${afterHash})`);
@@ -928,12 +922,9 @@ class KoiosBackend {
928
922
  return [];
929
923
  const requestedHashes = rows.map((r) => r.hash);
930
924
  const infos = await this.fetchWithRetryOnEmpty(() => this.api.post('/block_info', { _block_hashes: requestedHashes }), `getNextBlocks/info(${afterHash})`);
931
- // Completeness guard: Koios' load-balanced instances can return a PARTIAL
932
- // /block_info batch (fetchWithRetryOnEmpty only retries fully empty
933
- // responses). Returning the subset would let the crawler advance its cursor
934
- // past the missing block, leaving a permanent hole in the pre-synced range
935
- // (crawled entities are non-temporal — nothing re-fetches them). Fail the
936
- // round as transient instead; the next round retries the same anchor.
925
+ // Load-balanced instances can return a PARTIAL /block_info batch. Returning the subset
926
+ // would advance the cursor past the missing block and leave a permanent hole (crawled
927
+ // entities are never re-fetched), so fail the round as transient instead.
937
928
  if (infos.length < requestedHashes.length) {
938
929
  const returned = new Set(infos.map((d) => d.hash));
939
930
  const missing = requestedHashes.filter((h) => !returned.has(h));
@@ -944,10 +935,84 @@ class KoiosBackend {
944
935
  .sort((a, b) => (a.height ?? 0) - (b.height ?? 0));
945
936
  }, this.name);
946
937
  }
938
+ // ---------------------------------------------------------------------------
939
+ // EnumeratingBackend — full pool/DRep set for the crawler's epoch snapshots
940
+ // ---------------------------------------------------------------------------
941
+ /** Rows per page when listing ids (PostgREST caps a response at 1000 rows). */
942
+ static LIST_PAGE_SIZE = 1000;
943
+ /** Ids resolved per /pool_info / /drep_info request. */
944
+ static INFO_BATCH_SIZE = 50;
945
+ /** Page cap — 500 pages is 500 000 ids, far beyond any real pool or DRep set. */
946
+ static LIST_MAX_PAGES = 500;
947
+ /**
948
+ * Page through a PostgREST list endpoint and collect one id column. Stops on the first
949
+ * short page, so a complete set costs exactly ceil(n / 1000) + 1 requests.
950
+ */
951
+ async listAllIds(path, column, label) {
952
+ const ids = [];
953
+ for (let page = 0; page < KoiosBackend.LIST_MAX_PAGES; page++) {
954
+ const offset = page * KoiosBackend.LIST_PAGE_SIZE;
955
+ const { data } = await this.getWithRetryOn42804(`${path}?select=${column}&limit=${KoiosBackend.LIST_PAGE_SIZE}&offset=${offset}`, {}, label);
956
+ if (!Array.isArray(data) || data.length === 0)
957
+ return ids;
958
+ for (const row of data) {
959
+ const id = row[column];
960
+ if (typeof id === 'string' && id)
961
+ ids.push(id);
962
+ }
963
+ if (data.length < KoiosBackend.LIST_PAGE_SIZE)
964
+ return ids;
965
+ }
966
+ logger.warn(`${label}: stopped after ${KoiosBackend.LIST_MAX_PAGES} pages — the list may be truncated`);
967
+ return ids;
968
+ }
969
+ /**
970
+ * All stake-pool ids known to Koios (bech32), including retired ones — a snapshot that
971
+ * silently dropped retiring pools would misreport the epoch's pool set.
972
+ */
973
+ async getPoolIds() {
974
+ return (0, backend_request_handler_1.handleBackendRequest)(() => this.listAllIds('/pool_list', 'pool_id_bech32', 'getPoolIds'), this.name);
975
+ }
976
+ /**
977
+ * Resolve pool ids in batches. Ids Koios does not return are omitted rather than
978
+ * substituted with empty rows — a missing pool is better than an invented one.
979
+ */
980
+ async getPools(poolIds) {
981
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
982
+ const out = [];
983
+ for (let i = 0; i < poolIds.length; i += KoiosBackend.INFO_BATCH_SIZE) {
984
+ const batch = poolIds.slice(i, i + KoiosBackend.INFO_BATCH_SIZE);
985
+ const { data } = await this.api.post('/pool_info', { _pool_bech32_ids: batch });
986
+ if (!Array.isArray(data))
987
+ continue;
988
+ for (const row of data)
989
+ out.push(this._mapKoiosPool(row, ''));
990
+ }
991
+ return out;
992
+ }, this.name);
993
+ }
994
+ /** All DRep ids known to Koios (bech32). */
995
+ async getDrepIds() {
996
+ return (0, backend_request_handler_1.handleBackendRequest)(() => this.listAllIds('/drep_list', 'drep_id', 'getDrepIds'), this.name);
997
+ }
998
+ /** Resolve DRep ids in batches; unknown ids are omitted (see getPools). */
999
+ async getDreps(drepIds) {
1000
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
1001
+ const out = [];
1002
+ for (let i = 0; i < drepIds.length; i += KoiosBackend.INFO_BATCH_SIZE) {
1003
+ const batch = drepIds.slice(i, i + KoiosBackend.INFO_BATCH_SIZE);
1004
+ const { data } = await this.api.post('/drep_info', { _drep_ids: batch });
1005
+ if (!Array.isArray(data))
1006
+ continue;
1007
+ for (const row of data)
1008
+ out.push(this._mapKoiosDrep(row));
1009
+ }
1010
+ return out;
1011
+ }, this.name);
1012
+ }
947
1013
  /**
948
- * Get the full transaction list of a block in block order via /block_txs → /tx_info
949
- * batch. Handles both the current flattened shape ({tx_hash} per row) and the older
950
- * {tx_hashes:[...]} shape defensively.
1014
+ * Full transaction list of a block in block order via /block_txs → /tx_info batch.
1015
+ * Accepts both the flattened ({tx_hash} per row) and the {tx_hashes:[...]} shape.
951
1016
  */
952
1017
  async getBlockTransactions(blockHash) {
953
1018
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
@@ -964,9 +1029,8 @@ class KoiosBackend {
964
1029
  const byHash = await this.getTransactionsBatch(hashes);
965
1030
  const missing = hashes.filter(h => !byHash.has(h));
966
1031
  if (missing.length > 0) {
967
- // Advancing the block cursor with only a subset of /tx_info would make
968
- // the omitted transactions permanent. Surface a 503 so the crawler
969
- // retries the whole block without persisting it.
1032
+ // A partial /tx_info would make the omitted transactions permanent — 503 so the
1033
+ // crawler retries the whole block without persisting it.
970
1034
  throw new errors_1.ProviderUnavailableError(`Incomplete transaction data for block ${blockHash}: ${missing.length}/${hashes.length} transaction(s) missing`, this.name);
971
1035
  }
972
1036
  return hashes.map(h => byHash.get(h));
@@ -975,9 +1039,7 @@ class KoiosBackend {
975
1039
  //-----------------------------------------------------------------------------
976
1040
  // Private Helpers
977
1041
  //-----------------------------------------------------------------------------
978
- /**
979
- * Map a Koios /tx_info response object to the normalized Transaction type.
980
- */
1042
+ /** Map a Koios /tx_info row to the normalized Transaction (ledger view, see ledgerView). */
981
1043
  _mapKoiosTx(tx) {
982
1044
  let labels = [];
983
1045
  if (tx.metadata) {
@@ -987,67 +1049,146 @@ class KoiosBackend {
987
1049
  json: json,
988
1050
  }));
989
1051
  }
990
- return {
1052
+ return (0, mappers_1.ledgerView)({
991
1053
  hash: tx.tx_hash,
992
1054
  blockHash: tx.block_hash,
993
1055
  blockHeight: Number(tx.block_height),
994
1056
  blockTime: tx.tx_timestamp ?? tx.block_time ?? 0,
995
1057
  slot: tx.absolute_slot ?? tx.slot_no ?? 0,
996
- // Koios /tx_info fields are `tx_block_index` and `fee` (verified against
997
- // the live OpenAPI spec) — `tx_index`/`tx_fee` never existed, so the fee
998
- // was always reported as '0'
1058
+ // Koios spells these `tx_block_index` and `fee` (not `tx_index` / `tx_fee`)
999
1059
  index: tx.tx_block_index ?? 0,
1000
1060
  fee: tx.fee || '0',
1001
1061
  deposit: tx.deposit || '0',
1062
+ // undefined (not []) when Koios does not report the field at all — the indexer then
1063
+ // falls back to the input/output delta instead of reading "no mint" into a gap.
1064
+ mint: Array.isArray(tx.assets_minted)
1065
+ ? tx.assets_minted
1066
+ .filter((a) => a?.policy_id && a.quantity != null)
1067
+ .map((a) => ({
1068
+ unit: `${a.policy_id}${a.asset_name ?? ''}`,
1069
+ quantity: String(a.quantity),
1070
+ }))
1071
+ : undefined,
1002
1072
  size: tx.tx_size,
1003
- inputs: tx.inputs.map((input) => {
1004
- const amount = [
1005
- { unit: 'lovelace', quantity: input.value }
1006
- ];
1007
- if (input.asset_list && Array.isArray(input.asset_list)) {
1008
- for (const asset of input.asset_list) {
1009
- amount.push({
1010
- unit: `${asset.policy_id}${asset.asset_name}`,
1011
- quantity: asset.quantity
1012
- });
1013
- }
1014
- }
1015
- return {
1016
- address: input.payment_addr?.bech32 || input.address || '',
1017
- txHash: input.tx_hash,
1018
- outputIndex: input.tx_index,
1019
- amount: amount,
1020
- dataHash: input.datum_hash || null,
1021
- inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(input.inline_datum),
1022
- referenceScriptHash: koiosRefScriptHash(input.reference_script),
1023
- };
1024
- }),
1025
- outputs: tx.outputs.map((output) => {
1026
- const amount = [
1027
- { unit: 'lovelace', quantity: output.value }
1028
- ];
1029
- if (output.asset_list && Array.isArray(output.asset_list)) {
1030
- for (const asset of output.asset_list) {
1031
- amount.push({
1032
- unit: `${asset.policy_id}${asset.asset_name}`,
1033
- quantity: asset.quantity
1034
- });
1035
- }
1036
- }
1037
- return {
1038
- address: output.payment_addr?.bech32 || output.address || '',
1039
- amount: amount,
1040
- txHash: tx.tx_hash,
1041
- outputIndex: output.tx_index,
1042
- dataHash: output.datum_hash || null,
1043
- inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(output.inline_datum),
1044
- isCollateral: false,
1045
- referenceScriptHash: koiosRefScriptHash(output.reference_script),
1046
- };
1047
- }),
1048
- metadata: labels
1049
- };
1073
+ // Phase-2 validity as db-sync records it; undefined on a Koios without the field, so the
1074
+ // indexer keeps treating such a source as "no phase-2 information".
1075
+ spendsCollaterals: typeof tx.valid_contract === 'boolean' ? tx.valid_contract === false : undefined,
1076
+ // Koios lists inputs in its own order; ledgerView sorts them like the ledger
1077
+ inputs: [
1078
+ ...asKoiosList(tx.inputs).map((input) => mapKoiosInput(input)),
1079
+ ...asKoiosList(tx.collateral_inputs).map((input) => mapKoiosInput(input, { isCollateral: true })),
1080
+ ...asKoiosList(tx.reference_inputs).map((input) => mapKoiosInput(input, { isReference: true })),
1081
+ ],
1082
+ outputs: [
1083
+ ...asKoiosList(tx.outputs).map((output) => mapKoiosOutput(tx.tx_hash, output, false)),
1084
+ // CIP-40 collateral return: produced only when the script phase failed (ledgerView keeps it then)
1085
+ ...asKoiosList(tx.collateral_output).map((output) => mapKoiosOutput(tx.tx_hash, output, true)),
1086
+ ],
1087
+ metadata: labels,
1088
+ // undefined (not []) when the call did not ask for them (`_certs: false` on the lazy
1089
+ // path) — the indexer tells "none" from "not reported" by exactly this.
1090
+ certificates: Array.isArray(tx.certificates) ? mapKoiosCertificates(tx.certificates) : undefined,
1091
+ withdrawals: Array.isArray(tx.withdrawals)
1092
+ ? tx.withdrawals
1093
+ .filter((w) => !!w.stake_addr)
1094
+ .map((w) => ({ stakeAddress: String(w.stake_addr), amount: String(w.amount ?? '0') }))
1095
+ : undefined,
1096
+ });
1050
1097
  }
1051
1098
  }
1052
1099
  exports.KoiosBackend = KoiosBackend;
1100
+ /**
1101
+ * Koios is loose about shapes: `collateral_output` arrives as one object (the spec says
1102
+ * array) and `asset_list` on it as the JSON STRING "[]". Normalize both before mapping.
1103
+ */
1104
+ function asKoiosList(v) {
1105
+ if (Array.isArray(v))
1106
+ return v;
1107
+ if (typeof v === 'string') {
1108
+ try {
1109
+ const parsed = JSON.parse(v);
1110
+ return Array.isArray(parsed) ? parsed : [];
1111
+ }
1112
+ catch {
1113
+ return [];
1114
+ }
1115
+ }
1116
+ return v && typeof v === 'object' ? [v] : [];
1117
+ }
1118
+ function koiosAmount(io) {
1119
+ const amount = [{ unit: 'lovelace', quantity: io.value }];
1120
+ for (const asset of asKoiosList(io.asset_list)) {
1121
+ amount.push({ unit: `${asset.policy_id}${asset.asset_name}`, quantity: asset.quantity });
1122
+ }
1123
+ return amount;
1124
+ }
1125
+ function mapKoiosInput(input, flags = {}) {
1126
+ return {
1127
+ address: input.payment_addr?.bech32 || input.address || '',
1128
+ txHash: input.tx_hash,
1129
+ outputIndex: input.tx_index,
1130
+ amount: koiosAmount(input),
1131
+ dataHash: input.datum_hash || null,
1132
+ inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(input.inline_datum),
1133
+ referenceScriptHash: koiosRefScriptHash(input.reference_script),
1134
+ ...flags,
1135
+ };
1136
+ }
1137
+ function mapKoiosOutput(txHash, output, isCollateral) {
1138
+ return {
1139
+ address: output.payment_addr?.bech32 || output.address || '',
1140
+ amount: koiosAmount(output),
1141
+ txHash,
1142
+ outputIndex: output.tx_index,
1143
+ dataHash: output.datum_hash || null,
1144
+ inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(output.inline_datum),
1145
+ isCollateral,
1146
+ referenceScriptHash: koiosRefScriptHash(output.reference_script),
1147
+ };
1148
+ }
1149
+ /** Koios certificate `type` → shared `CertificateKind`; anything else passes through raw. */
1150
+ const KOIOS_CERT_KINDS = {
1151
+ stake_registration: 'stake_registration',
1152
+ stake_deregistration: 'stake_deregistration',
1153
+ pool_delegation: 'pool_delegation',
1154
+ // older Koios releases named the pool delegation plainly
1155
+ delegation: 'pool_delegation',
1156
+ vote_delegation: 'vote_delegation',
1157
+ pool_update: 'pool_registration',
1158
+ pool_retire: 'pool_retirement',
1159
+ drep_registration: 'drep_registration',
1160
+ drep_update: 'drep_update',
1161
+ drep_retire: 'drep_retirement',
1162
+ drep_deregistration: 'drep_retirement',
1163
+ committee_hot_auth: 'committee_hot_auth',
1164
+ committee_resign: 'committee_resign',
1165
+ treasury_MIR: 'treasury_mir',
1166
+ reserve_MIR: 'reserve_mir',
1167
+ pot_transfer: 'pot_transfer',
1168
+ param_proposal: 'param_proposal',
1169
+ };
1170
+ /**
1171
+ * Normalize Koios `/tx_info` certificates (`_certs: true`). Field names inside `info` differ
1172
+ * per type (`retiring_epoch` is spelled `retiring epoch` in current Koios), so every alias is read.
1173
+ */
1174
+ function mapKoiosCertificates(certs) {
1175
+ const str = (v) => (typeof v === 'string' && v.length ? v : null);
1176
+ const num = (v) => {
1177
+ const n = typeof v === 'string' ? Number(v) : v;
1178
+ return typeof n === 'number' && Number.isFinite(n) ? n : null;
1179
+ };
1180
+ return certs.map((c, position) => {
1181
+ const info = c.info ?? {};
1182
+ const deposit = info.deposit;
1183
+ return {
1184
+ certIndex: num(c.index) ?? position,
1185
+ kind: (c.type && KOIOS_CERT_KINDS[c.type]) || c.type || 'other',
1186
+ stakeAddress: str(info.stake_address) ?? str(info.stake_addr),
1187
+ poolId: str(info.pool_id_bech32) ?? str(info.pool),
1188
+ drepId: str(info.drep_id),
1189
+ deposit: deposit != null && deposit !== '' ? String(deposit) : null,
1190
+ epoch: num(info.retiring_epoch) ?? num(info['retiring epoch']),
1191
+ };
1192
+ });
1193
+ }
1053
1194
  //# sourceMappingURL=koios-backend.js.map