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

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 +1191 -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 +108 -160
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +620 -285
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +17 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +50 -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 +127 -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,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;
@@ -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) {
@@ -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 () => {
@@ -365,7 +353,7 @@ class KoiosBackend {
365
353
  */
366
354
  async getNetworkInformation() {
367
355
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
368
- // Try /totals endpoint (works on mainnet, but returns empty array on preview/preprod testnet)
356
+ // /totals works on mainnet but returns [] on preview/preprod
369
357
  const { data: totalsData } = await this.api.get('/totals', {
370
358
  params: { order: 'epoch_no.desc', limit: 1 }
371
359
  });
@@ -386,8 +374,7 @@ class KoiosBackend {
386
374
  },
387
375
  };
388
376
  }
389
- // Fallback for preview/preprod network where /totals doesn't work
390
- // Use genesis endpoint to get max supply; remaining fields default to '0'
377
+ // Testnet fallback: max supply from /genesis, remaining fields '0'
391
378
  const { data: genesisData } = await this.api.get('/genesis');
392
379
  if (!genesisData || !Array.isArray(genesisData) || genesisData.length === 0) {
393
380
  throw new errors_1.NotFoundError('Genesis', this.name);
@@ -450,34 +437,35 @@ class KoiosBackend {
450
437
  if (!Array.isArray(data) || data.length === 0) {
451
438
  throw new errors_1.NotFoundError('Pool', this.name);
452
439
  }
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
- };
440
+ return this._mapKoiosPool(data[0], poolId);
473
441
  }, this.name);
474
442
  }
443
+ /** Map one Koios /pool_info row to the canonical PoolData. */
444
+ _mapKoiosPool(poolData, fallbackId) {
445
+ return {
446
+ poolId: poolData.pool_id_bech32 || poolData.pool_id_hex || fallbackId,
447
+ vrfKeyHash: poolData.vrf_key_hash || '',
448
+ blocksMinted: poolData.block_count || 0,
449
+ // Koios pool_info has no blocks-in-current-epoch figure. null = not available;
450
+ // a 0 would be indistinguishable from a real zero downstream.
451
+ blocksEpoch: null,
452
+ liveStake: poolData.live_stake || '0',
453
+ liveSize: poolData.live_size || 0,
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: poolData.active_size || 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 [];
@@ -605,27 +580,26 @@ class KoiosBackend {
605
580
  if (!Array.isArray(data) || data.length === 0) {
606
581
  throw new errors_1.NotFoundError('Drep', this.name);
607
582
  }
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
- };
583
+ return this._mapKoiosDrep(data[0]);
627
584
  }, this.name);
628
585
  }
586
+ /** Map one Koios /drep_info row to the canonical DrepData. */
587
+ _mapKoiosDrep(drepData) {
588
+ // Koios /drep_info exposes either `expired`/`retired`/`last_active_epoch` (older schema)
589
+ // or `drep_status` ('registered' | 'retired'), `active` and `expires_epoch_no`; read both.
590
+ const retired = drepData.retired ?? drepData.drep_status === 'retired';
591
+ const expired = drepData.expired ?? (drepData.active === false && !retired);
592
+ return {
593
+ drepId: drepData.drep_id,
594
+ hex: drepData.hex,
595
+ amount: drepData.amount,
596
+ hasScript: drepData.has_script,
597
+ // The newer schema has no last-activity epoch (`expires_epoch_no` differs in meaning) — 0 then.
598
+ lastActiveEpoch: drepData.last_active_epoch ?? 0,
599
+ expired,
600
+ retired,
601
+ };
602
+ }
629
603
  /**
630
604
  * Get Account Data for specified stake address
631
605
  * @param accountId account id
@@ -640,7 +614,6 @@ class KoiosBackend {
640
614
  if (!Array.isArray(data) || data.length === 0) {
641
615
  throw new errors_1.NotFoundError('Account', this.name);
642
616
  }
643
- // Fetch associated addresses
644
617
  const addressDataResponse = await this.api.post('/account_addresses', body);
645
618
  // Koios returns [{ stake_address, addresses: [...] }], flatten to get all addresses
646
619
  const addressesFlat = addressDataResponse.data.flatMap((item) => item.addresses);
@@ -677,12 +650,27 @@ class KoiosBackend {
677
650
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
678
651
  // Koios /submittx expects raw CBOR bytes with Content-Type: application/cbor
679
652
  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, '');
653
+ try {
654
+ const { data } = await this.api.post('/submittx', cborBytes, {
655
+ headers: { 'Content-Type': 'application/cbor' },
656
+ // Prevent axios from JSON-serializing the Buffer
657
+ transformRequest: [(d) => d],
658
+ });
659
+ return data.trim().replace(/^"|"$/g, '');
660
+ }
661
+ catch (err) {
662
+ // 400 carries the node's rejection (e.g. ExtraneousScriptWitnessesUTXOW); keep it
663
+ const response = err.response;
664
+ if (response?.status === 400 && response.data) {
665
+ const reason = nodeRejection(response.data);
666
+ // known kinds keep their class (already submitted = 409, script failure = 400)
667
+ const known = (0, errors_1.normalizeBackendError)(new Error(reason), this.name);
668
+ if (known.statusCode === 409 || known instanceof errors_1.ScriptValidationError)
669
+ throw known;
670
+ throw new errors_1.TransactionValidationError(`node rejected the transaction: ${reason}`, err);
671
+ }
672
+ throw err;
673
+ }
686
674
  }, this.name);
687
675
  }
688
676
  /**
@@ -691,10 +679,17 @@ class KoiosBackend {
691
679
  */
692
680
  async getProtocolParameters() {
693
681
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
694
- const { data } = await this.api.get('/cli_protocol_params');
682
+ // /cli_protocol_params carries no epoch; the tip does. Without it the epoch stays 0.
683
+ const [{ data }, epoch] = await Promise.all([
684
+ this.api.get('/cli_protocol_params'),
685
+ this.api.get('/tip').then((r) => Number(r.data?.[0]?.epoch_no ?? 0), (err) => {
686
+ logger.warn(`Koios /tip failed, protocol parameters without epoch: ${err instanceof Error ? err.message : String(err)}`);
687
+ return 0;
688
+ }),
689
+ ]);
695
690
  return {
696
691
  network: this.network,
697
- epoch: 0, // Koios doesn't provide current epoch in this endpoint
692
+ epoch,
698
693
  // --- Fees / Sizes ---
699
694
  minFeeA: data.txFeePerByte,
700
695
  minFeeB: data.txFeeFixed,
@@ -823,12 +818,12 @@ class KoiosBackend {
823
818
  .map(tx => tx.tx_hash);
824
819
  }, this.name);
825
820
  }
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
- */
821
+ /** crawler.certificates: ask /tx_info for certificates + withdrawals on the crawl's batch call. */
822
+ crawlCertificates = false;
823
+ configureCrawl(options) {
824
+ this.crawlCertificates = Boolean(options.certificates);
825
+ }
826
+ /** Batch fetch transactions via POST /tx_info, chunked at 100 hashes (Koios limit). */
832
827
  async getTransactionsBatch(txHashes) {
833
828
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
834
829
  const BATCH_SIZE = 100;
@@ -840,8 +835,9 @@ class KoiosBackend {
840
835
  _inputs: true,
841
836
  _metadata: true,
842
837
  _assets: true,
843
- _withdrawals: false,
844
- _certs: false,
838
+ // certificates + withdrawals only when the crawl will write them (larger payload)
839
+ _withdrawals: this.crawlCertificates,
840
+ _certs: this.crawlCertificates,
845
841
  _scripts: false,
846
842
  _bytecode: false,
847
843
  });
@@ -860,12 +856,9 @@ class KoiosBackend {
860
856
  }, this.name);
861
857
  }
862
858
  // ---------------------------------------------------------------------------
863
- // PaginatingBackend — forward iteration for the chain crawler (v2.0)
859
+ // PaginatingBackend — forward iteration for the chain crawler
864
860
  // ---------------------------------------------------------------------------
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
- */
861
+ /** Map a Koios /block_info row to BlockData. */
869
862
  mapKoiosBlockInfo(data) {
870
863
  return {
871
864
  time: data.block_time,
@@ -874,7 +867,7 @@ class KoiosBackend {
874
867
  slot: data.abs_slot,
875
868
  epoch: data.epoch_no,
876
869
  epochSlot: data.epoch_slot,
877
- slotLeader: data.vrf_key,
870
+ slotLeader: data.pool ?? '',
878
871
  size: data.block_size,
879
872
  txCount: data.tx_count,
880
873
  fees: data.total_fees,
@@ -893,21 +886,17 @@ class KoiosBackend {
893
886
  }, this.name);
894
887
  }
895
888
  /**
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.
889
+ * Up to `count` blocks after `afterHash`, ascending. Koios has no "next after hash" endpoint:
890
+ * list blocks above the anchor height (PostgREST gt + order + limit), then batch /block_info.
891
+ * A known `afterHeight` skips the hash→height round-trip.
901
892
  */
902
893
  async getNextBlocks(afterHash, count, afterHeight) {
903
894
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
904
895
  let anchorHeight = afterHeight;
905
896
  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.
897
+ // A height hint is not proof the cursor is still canonical: after a rollback Koios
898
+ // keeps listing blocks above H while `afterHash` is orphaned. Validate the hash first
899
+ // so the crawler enters reorg recovery.
911
900
  const canonical = await this.fetchWithRetryOnEmpty(() => this.api.get(`/blocks?block_height=eq.${anchorHeight}&limit=1`), `getNextBlocks/anchor(${anchorHeight})`);
912
901
  const canonicalHash = canonical[0]?.hash;
913
902
  if (!canonicalHash) {
@@ -921,6 +910,9 @@ class KoiosBackend {
921
910
  const info = await this.fetchWithRetryOnEmpty(() => this.api.post('/block_info', { _block_hashes: [afterHash] }), `getNextBlocks/height(${afterHash})`);
922
911
  if (!info.length)
923
912
  throw new errors_1.NotFoundError('Block', this.name);
913
+ if (info[0].block_height == null) {
914
+ throw new errors_1.ProviderUnavailableError(`Block ${afterHash} has no height on Koios and cannot anchor pagination`, this.name);
915
+ }
924
916
  anchorHeight = info[0].block_height;
925
917
  }
926
918
  const rows = await this.fetchWithRetryOnEmpty(() => this.api.get(`/blocks?block_height=gt.${anchorHeight}&order=block_height.asc&limit=${count}`), `getNextBlocks(${afterHash})`);
@@ -928,12 +920,9 @@ class KoiosBackend {
928
920
  return [];
929
921
  const requestedHashes = rows.map((r) => r.hash);
930
922
  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.
923
+ // Load-balanced instances can return a PARTIAL /block_info batch. Returning the subset
924
+ // would advance the cursor past the missing block and leave a permanent hole (crawled
925
+ // entities are never re-fetched), so fail the round as transient instead.
937
926
  if (infos.length < requestedHashes.length) {
938
927
  const returned = new Set(infos.map((d) => d.hash));
939
928
  const missing = requestedHashes.filter((h) => !returned.has(h));
@@ -944,10 +933,84 @@ class KoiosBackend {
944
933
  .sort((a, b) => (a.height ?? 0) - (b.height ?? 0));
945
934
  }, this.name);
946
935
  }
936
+ // ---------------------------------------------------------------------------
937
+ // EnumeratingBackend — full pool/DRep set for the crawler's epoch snapshots
938
+ // ---------------------------------------------------------------------------
939
+ /** Rows per page when listing ids (PostgREST caps a response at 1000 rows). */
940
+ static LIST_PAGE_SIZE = 1000;
941
+ /** Ids resolved per /pool_info / /drep_info request. */
942
+ static INFO_BATCH_SIZE = 50;
943
+ /** Page cap — 500 pages is 500 000 ids, far beyond any real pool or DRep set. */
944
+ static LIST_MAX_PAGES = 500;
945
+ /**
946
+ * Page through a PostgREST list endpoint and collect one id column. Stops on the first
947
+ * short page, so a complete set costs exactly ceil(n / 1000) + 1 requests.
948
+ */
949
+ async listAllIds(path, column, label) {
950
+ const ids = [];
951
+ for (let page = 0; page < KoiosBackend.LIST_MAX_PAGES; page++) {
952
+ const offset = page * KoiosBackend.LIST_PAGE_SIZE;
953
+ const { data } = await this.getWithRetryOn42804(`${path}?select=${column}&limit=${KoiosBackend.LIST_PAGE_SIZE}&offset=${offset}`, {}, label);
954
+ if (!Array.isArray(data) || data.length === 0)
955
+ return ids;
956
+ for (const row of data) {
957
+ const id = row[column];
958
+ if (typeof id === 'string' && id)
959
+ ids.push(id);
960
+ }
961
+ if (data.length < KoiosBackend.LIST_PAGE_SIZE)
962
+ return ids;
963
+ }
964
+ logger.warn(`${label}: stopped after ${KoiosBackend.LIST_MAX_PAGES} pages — the list may be truncated`);
965
+ return ids;
966
+ }
967
+ /**
968
+ * All stake-pool ids known to Koios (bech32), including retired ones — a snapshot that
969
+ * silently dropped retiring pools would misreport the epoch's pool set.
970
+ */
971
+ async getPoolIds() {
972
+ return (0, backend_request_handler_1.handleBackendRequest)(() => this.listAllIds('/pool_list', 'pool_id_bech32', 'getPoolIds'), this.name);
973
+ }
974
+ /**
975
+ * Resolve pool ids in batches. Ids Koios does not return are omitted rather than
976
+ * substituted with empty rows — a missing pool is better than an invented one.
977
+ */
978
+ async getPools(poolIds) {
979
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
980
+ const out = [];
981
+ for (let i = 0; i < poolIds.length; i += KoiosBackend.INFO_BATCH_SIZE) {
982
+ const batch = poolIds.slice(i, i + KoiosBackend.INFO_BATCH_SIZE);
983
+ const { data } = await this.api.post('/pool_info', { _pool_bech32_ids: batch });
984
+ if (!Array.isArray(data))
985
+ continue;
986
+ for (const row of data)
987
+ out.push(this._mapKoiosPool(row, ''));
988
+ }
989
+ return out;
990
+ }, this.name);
991
+ }
992
+ /** All DRep ids known to Koios (bech32). */
993
+ async getDrepIds() {
994
+ return (0, backend_request_handler_1.handleBackendRequest)(() => this.listAllIds('/drep_list', 'drep_id', 'getDrepIds'), this.name);
995
+ }
996
+ /** Resolve DRep ids in batches; unknown ids are omitted (see getPools). */
997
+ async getDreps(drepIds) {
998
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
999
+ const out = [];
1000
+ for (let i = 0; i < drepIds.length; i += KoiosBackend.INFO_BATCH_SIZE) {
1001
+ const batch = drepIds.slice(i, i + KoiosBackend.INFO_BATCH_SIZE);
1002
+ const { data } = await this.api.post('/drep_info', { _drep_ids: batch });
1003
+ if (!Array.isArray(data))
1004
+ continue;
1005
+ for (const row of data)
1006
+ out.push(this._mapKoiosDrep(row));
1007
+ }
1008
+ return out;
1009
+ }, this.name);
1010
+ }
947
1011
  /**
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.
1012
+ * Full transaction list of a block in block order via /block_txs → /tx_info batch.
1013
+ * Accepts both the flattened ({tx_hash} per row) and the {tx_hashes:[...]} shape.
951
1014
  */
952
1015
  async getBlockTransactions(blockHash) {
953
1016
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
@@ -964,9 +1027,8 @@ class KoiosBackend {
964
1027
  const byHash = await this.getTransactionsBatch(hashes);
965
1028
  const missing = hashes.filter(h => !byHash.has(h));
966
1029
  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.
1030
+ // A partial /tx_info would make the omitted transactions permanent — 503 so the
1031
+ // crawler retries the whole block without persisting it.
970
1032
  throw new errors_1.ProviderUnavailableError(`Incomplete transaction data for block ${blockHash}: ${missing.length}/${hashes.length} transaction(s) missing`, this.name);
971
1033
  }
972
1034
  return hashes.map(h => byHash.get(h));
@@ -975,9 +1037,7 @@ class KoiosBackend {
975
1037
  //-----------------------------------------------------------------------------
976
1038
  // Private Helpers
977
1039
  //-----------------------------------------------------------------------------
978
- /**
979
- * Map a Koios /tx_info response object to the normalized Transaction type.
980
- */
1040
+ /** Map a Koios /tx_info row to the normalized Transaction (ledger view, see ledgerView). */
981
1041
  _mapKoiosTx(tx) {
982
1042
  let labels = [];
983
1043
  if (tx.metadata) {
@@ -987,67 +1047,146 @@ class KoiosBackend {
987
1047
  json: json,
988
1048
  }));
989
1049
  }
990
- return {
1050
+ return (0, mappers_1.ledgerView)({
991
1051
  hash: tx.tx_hash,
992
1052
  blockHash: tx.block_hash,
993
1053
  blockHeight: Number(tx.block_height),
994
1054
  blockTime: tx.tx_timestamp ?? tx.block_time ?? 0,
995
1055
  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'
1056
+ // Koios spells these `tx_block_index` and `fee` (not `tx_index` / `tx_fee`)
999
1057
  index: tx.tx_block_index ?? 0,
1000
1058
  fee: tx.fee || '0',
1001
1059
  deposit: tx.deposit || '0',
1060
+ // undefined (not []) when Koios does not report the field at all — the indexer then
1061
+ // falls back to the input/output delta instead of reading "no mint" into a gap.
1062
+ mint: Array.isArray(tx.assets_minted)
1063
+ ? tx.assets_minted
1064
+ .filter((a) => a?.policy_id && a.quantity != null)
1065
+ .map((a) => ({
1066
+ unit: `${a.policy_id}${a.asset_name ?? ''}`,
1067
+ quantity: String(a.quantity),
1068
+ }))
1069
+ : undefined,
1002
1070
  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
- };
1071
+ // Phase-2 validity as db-sync records it; undefined on a Koios without the field, so the
1072
+ // indexer keeps treating such a source as "no phase-2 information".
1073
+ spendsCollaterals: typeof tx.valid_contract === 'boolean' ? tx.valid_contract === false : undefined,
1074
+ // Koios lists inputs in its own order; ledgerView sorts them like the ledger
1075
+ inputs: [
1076
+ ...asKoiosList(tx.inputs).map((input) => mapKoiosInput(input)),
1077
+ ...asKoiosList(tx.collateral_inputs).map((input) => mapKoiosInput(input, { isCollateral: true })),
1078
+ ...asKoiosList(tx.reference_inputs).map((input) => mapKoiosInput(input, { isReference: true })),
1079
+ ],
1080
+ outputs: [
1081
+ ...asKoiosList(tx.outputs).map((output) => mapKoiosOutput(tx.tx_hash, output, false)),
1082
+ // CIP-40 collateral return: produced only when the script phase failed (ledgerView keeps it then)
1083
+ ...asKoiosList(tx.collateral_output).map((output) => mapKoiosOutput(tx.tx_hash, output, true)),
1084
+ ],
1085
+ metadata: labels,
1086
+ // undefined (not []) when the call did not ask for them (`_certs: false` on the lazy
1087
+ // path) — the indexer tells "none" from "not reported" by exactly this.
1088
+ certificates: Array.isArray(tx.certificates) ? mapKoiosCertificates(tx.certificates) : undefined,
1089
+ withdrawals: Array.isArray(tx.withdrawals)
1090
+ ? tx.withdrawals
1091
+ .filter((w) => !!w.stake_addr)
1092
+ .map((w) => ({ stakeAddress: String(w.stake_addr), amount: String(w.amount ?? '0') }))
1093
+ : undefined,
1094
+ });
1050
1095
  }
1051
1096
  }
1052
1097
  exports.KoiosBackend = KoiosBackend;
1098
+ /**
1099
+ * Koios is loose about shapes: `collateral_output` arrives as one object (the spec says
1100
+ * array) and `asset_list` on it as the JSON STRING "[]". Normalize both before mapping.
1101
+ */
1102
+ function asKoiosList(v) {
1103
+ if (Array.isArray(v))
1104
+ return v;
1105
+ if (typeof v === 'string') {
1106
+ try {
1107
+ const parsed = JSON.parse(v);
1108
+ return Array.isArray(parsed) ? parsed : [];
1109
+ }
1110
+ catch {
1111
+ return [];
1112
+ }
1113
+ }
1114
+ return v && typeof v === 'object' ? [v] : [];
1115
+ }
1116
+ function koiosAmount(io) {
1117
+ const amount = [{ unit: 'lovelace', quantity: io.value }];
1118
+ for (const asset of asKoiosList(io.asset_list)) {
1119
+ amount.push({ unit: `${asset.policy_id}${asset.asset_name}`, quantity: asset.quantity });
1120
+ }
1121
+ return amount;
1122
+ }
1123
+ function mapKoiosInput(input, flags = {}) {
1124
+ return {
1125
+ address: input.payment_addr?.bech32 || input.address || '',
1126
+ txHash: input.tx_hash,
1127
+ outputIndex: input.tx_index,
1128
+ amount: koiosAmount(input),
1129
+ dataHash: input.datum_hash || null,
1130
+ inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(input.inline_datum),
1131
+ referenceScriptHash: koiosRefScriptHash(input.reference_script),
1132
+ ...flags,
1133
+ };
1134
+ }
1135
+ function mapKoiosOutput(txHash, output, isCollateral) {
1136
+ return {
1137
+ address: output.payment_addr?.bech32 || output.address || '',
1138
+ amount: koiosAmount(output),
1139
+ txHash,
1140
+ outputIndex: output.tx_index,
1141
+ dataHash: output.datum_hash || null,
1142
+ inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(output.inline_datum),
1143
+ isCollateral,
1144
+ referenceScriptHash: koiosRefScriptHash(output.reference_script),
1145
+ };
1146
+ }
1147
+ /** Koios certificate `type` → shared `CertificateKind`; anything else passes through raw. */
1148
+ const KOIOS_CERT_KINDS = {
1149
+ stake_registration: 'stake_registration',
1150
+ stake_deregistration: 'stake_deregistration',
1151
+ pool_delegation: 'pool_delegation',
1152
+ // older Koios releases named the pool delegation plainly
1153
+ delegation: 'pool_delegation',
1154
+ vote_delegation: 'vote_delegation',
1155
+ pool_update: 'pool_registration',
1156
+ pool_retire: 'pool_retirement',
1157
+ drep_registration: 'drep_registration',
1158
+ drep_update: 'drep_update',
1159
+ drep_retire: 'drep_retirement',
1160
+ drep_deregistration: 'drep_retirement',
1161
+ committee_hot_auth: 'committee_hot_auth',
1162
+ committee_resign: 'committee_resign',
1163
+ treasury_MIR: 'treasury_mir',
1164
+ reserve_MIR: 'reserve_mir',
1165
+ pot_transfer: 'pot_transfer',
1166
+ param_proposal: 'param_proposal',
1167
+ };
1168
+ /**
1169
+ * Normalize Koios `/tx_info` certificates (`_certs: true`). Field names inside `info` differ
1170
+ * per type (`retiring_epoch` is spelled `retiring epoch` in current Koios), so every alias is read.
1171
+ */
1172
+ function mapKoiosCertificates(certs) {
1173
+ const str = (v) => (typeof v === 'string' && v.length ? v : null);
1174
+ const num = (v) => {
1175
+ const n = typeof v === 'string' ? Number(v) : v;
1176
+ return typeof n === 'number' && Number.isFinite(n) ? n : null;
1177
+ };
1178
+ return certs.map((c, position) => {
1179
+ const info = c.info ?? {};
1180
+ const deposit = info.deposit;
1181
+ return {
1182
+ certIndex: num(c.index) ?? position,
1183
+ kind: (c.type && KOIOS_CERT_KINDS[c.type]) || c.type || 'other',
1184
+ stakeAddress: str(info.stake_address) ?? str(info.stake_addr),
1185
+ poolId: str(info.pool_id_bech32) ?? str(info.pool),
1186
+ drepId: str(info.drep_id),
1187
+ deposit: deposit != null && deposit !== '' ? String(deposit) : null,
1188
+ epoch: num(info.retiring_epoch) ?? num(info['retiring epoch']),
1189
+ };
1190
+ });
1191
+ }
1053
1192
  //# sourceMappingURL=koios-backend.js.map