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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +358 -0
  4. package/@cds-models/CardanoBackendService/index.js +41 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
  6. package/@cds-models/CardanoIndexerService/index.js +74 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +417 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +45 -19
  10. package/@cds-models/CardanoSignService/index.js +4 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
  12. package/@cds-models/CardanoTransactionService/index.js +5 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
  14. package/@cds-models/CardanoWorkerService/index.js +2 -0
  15. package/@cds-models/index.d.ts +114 -4
  16. package/@cds-models/index.js +20 -4
  17. package/@cds-models/odatano/cardano/index.d.ts +451 -32
  18. package/@cds-models/odatano/cardano/index.js +48 -0
  19. package/README.md +103 -167
  20. package/db/schema.cds +2455 -1705
  21. package/db/types.cds +456 -295
  22. package/package.json +41 -53
  23. package/scripts/deploy-schema.mjs +113 -0
  24. package/scripts/migrate-schema.mjs +528 -0
  25. package/scripts/migrate-slot-leader.mjs +96 -0
  26. package/src/index.d.ts +20 -21
  27. package/src/index.js +45 -31
  28. package/src/plugin.js +17 -35
  29. package/srv/blockchain/asset-decimals.d.ts +7 -0
  30. package/srv/blockchain/asset-decimals.js +91 -0
  31. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
  32. package/srv/blockchain/backends/blockfrost-backend.js +125 -215
  33. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  34. package/srv/blockchain/backends/call-signal.js +22 -0
  35. package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
  36. package/srv/blockchain/backends/cardano-backend.js +29 -5
  37. package/srv/blockchain/backends/koios-backend.d.ts +108 -170
  38. package/srv/blockchain/backends/koios-backend.js +488 -482
  39. package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
  40. package/srv/blockchain/backends/odatano-backend.js +211 -0
  41. package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
  42. package/srv/blockchain/backends/ogmios-backend.js +683 -327
  43. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  44. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  45. package/srv/blockchain/cardano-client.d.ts +71 -241
  46. package/srv/blockchain/cardano-client.js +354 -322
  47. package/srv/blockchain/cardano-indexer.d.ts +295 -283
  48. package/srv/blockchain/cardano-indexer.js +1690 -502
  49. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  50. package/srv/blockchain/cardano-tx-builder.js +164 -140
  51. package/srv/blockchain/circuit-breaker.d.ts +2 -13
  52. package/srv/blockchain/circuit-breaker.js +11 -15
  53. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  54. package/srv/blockchain/crawler/account-snapshots.js +173 -0
  55. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
  56. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  57. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
  58. package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
  59. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  60. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  61. package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
  62. package/srv/blockchain/crawler/certificate-backfill.js +174 -0
  63. package/srv/blockchain/crawler/crawler.d.ts +125 -81
  64. package/srv/blockchain/crawler/crawler.js +738 -167
  65. package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
  66. package/srv/blockchain/crawler/credential-backfill.js +101 -0
  67. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  68. package/srv/blockchain/crawler/index.d.ts +1 -8
  69. package/srv/blockchain/crawler/index.js +31 -17
  70. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  71. package/srv/blockchain/crawler/input-asset-copies.js +161 -0
  72. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  73. package/srv/blockchain/crawler/key-pages.js +48 -0
  74. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
  75. package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
  76. package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
  77. package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
  78. package/srv/blockchain/crawler/sync-state.d.ts +31 -47
  79. package/srv/blockchain/crawler/sync-state.js +135 -128
  80. package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
  81. package/srv/blockchain/crawler/transaction-backfill.js +271 -0
  82. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  83. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  84. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  85. package/srv/blockchain/crawler/window-plan.js +59 -0
  86. package/srv/blockchain/ledger-state.d.ts +62 -0
  87. package/srv/blockchain/ledger-state.js +521 -0
  88. package/srv/blockchain/pending-spends.d.ts +16 -0
  89. package/srv/blockchain/pending-spends.js +81 -0
  90. package/srv/blockchain/pool-metadata.d.ts +15 -0
  91. package/srv/blockchain/pool-metadata.js +132 -0
  92. package/srv/blockchain/request-coalescer.d.ts +2 -16
  93. package/srv/blockchain/request-coalescer.js +2 -16
  94. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  95. package/srv/blockchain/signing/cose-verifier.js +146 -70
  96. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  97. package/srv/blockchain/signing/external-signer.js +22 -131
  98. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  99. package/srv/blockchain/signing/failed-recheck.js +135 -0
  100. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  101. package/srv/blockchain/signing/hsm-signer.js +28 -79
  102. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  103. package/srv/blockchain/signing/landing-proof.js +224 -0
  104. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  105. package/srv/blockchain/signing/signature-verifier.js +71 -87
  106. package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
  107. package/srv/blockchain/signing/submission-finalizer.js +280 -86
  108. package/srv/blockchain/stored-chain.d.ts +19 -0
  109. package/srv/blockchain/stored-chain.js +258 -0
  110. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  111. package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
  112. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  113. package/srv/blockchain/transaction-presence.d.ts +12 -0
  114. package/srv/blockchain/transaction-presence.js +29 -0
  115. package/srv/blockchain/transaction-rows.d.ts +12 -0
  116. package/srv/blockchain/transaction-rows.js +44 -0
  117. package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
  118. package/srv/blockchain/wallet-worker/build-request.js +40 -353
  119. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
  120. package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
  121. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  122. package/srv/blockchain/wallet-worker/index.js +3 -11
  123. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  124. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  125. package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
  126. package/srv/blockchain/wallet-worker/job-store.js +200 -273
  127. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  128. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  129. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  130. package/srv/blockchain/wallet-worker/signers.js +4 -12
  131. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
  132. package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
  133. package/srv/cardano-agent-service.cds +122 -84
  134. package/srv/cardano-agent-service.js +12 -9
  135. package/srv/cardano-backend-service.cds +81 -0
  136. package/srv/cardano-backend-service.d.ts +2 -0
  137. package/srv/cardano-backend-service.js +259 -0
  138. package/srv/cardano-indexer-service.cds +393 -18
  139. package/srv/cardano-indexer-service.d.ts +5 -1
  140. package/srv/cardano-indexer-service.js +477 -16
  141. package/srv/cardano-service.cds +426 -269
  142. package/srv/cardano-service.js +640 -217
  143. package/srv/cardano-sign-service.cds +211 -180
  144. package/srv/cardano-sign-service.js +210 -287
  145. package/srv/cardano-tx-service.cds +462 -370
  146. package/srv/cardano-tx-service.js +283 -800
  147. package/srv/cardano-ui.cds +16 -16
  148. package/srv/cardano-worker-service.cds +141 -125
  149. package/srv/cardano-worker-service.js +104 -61
  150. package/srv/cbor/cip68.d.ts +13 -0
  151. package/srv/cbor/cip68.js +56 -0
  152. package/srv/cbor/index.d.ts +3 -1
  153. package/srv/cbor/index.js +9 -1
  154. package/srv/cbor/parse.d.ts +30 -18
  155. package/srv/cbor/parse.js +44 -9
  156. package/srv/cbor/plutus-data-json.d.ts +20 -0
  157. package/srv/cbor/plutus-data-json.js +32 -0
  158. package/srv/config.d.ts +117 -0
  159. package/srv/config.js +419 -0
  160. package/srv/server.d.ts +15 -110
  161. package/srv/server.js +83 -405
  162. package/srv/utils/agent-access.d.ts +11 -0
  163. package/srv/utils/agent-access.js +86 -0
  164. package/srv/utils/agent-grants-config.d.ts +0 -46
  165. package/srv/utils/agent-grants-config.js +17 -85
  166. package/srv/utils/agent-grants.d.ts +106 -122
  167. package/srv/utils/agent-grants.js +538 -237
  168. package/srv/utils/agent-token-auth.d.ts +4 -99
  169. package/srv/utils/agent-token-auth.js +62 -186
  170. package/srv/utils/backend-request-handler.d.ts +3 -17
  171. package/srv/utils/backend-request-handler.js +3 -18
  172. package/srv/utils/build-request.d.ts +52 -0
  173. package/srv/utils/build-request.js +487 -0
  174. package/srv/utils/collections.d.ts +4 -10
  175. package/srv/utils/collections.js +14 -10
  176. package/srv/utils/const.d.ts +32 -75
  177. package/srv/utils/const.js +40 -80
  178. package/srv/utils/crypto.d.ts +3 -12
  179. package/srv/utils/crypto.js +11 -25
  180. package/srv/utils/db-indexes.d.ts +31 -0
  181. package/srv/utils/db-indexes.js +185 -0
  182. package/srv/utils/db-kind.d.ts +23 -0
  183. package/srv/utils/db-kind.js +42 -0
  184. package/srv/utils/db-sanitize.d.ts +20 -0
  185. package/srv/utils/db-sanitize.js +80 -0
  186. package/srv/utils/deep-json.d.ts +6 -0
  187. package/srv/utils/deep-json.js +240 -0
  188. package/srv/utils/detached-run.d.ts +41 -0
  189. package/srv/utils/detached-run.js +101 -0
  190. package/srv/utils/epoch-slots.d.ts +14 -0
  191. package/srv/utils/epoch-slots.js +45 -0
  192. package/srv/utils/error-codes.d.ts +26 -75
  193. package/srv/utils/error-codes.js +27 -72
  194. package/srv/utils/errors.d.ts +55 -187
  195. package/srv/utils/errors.js +161 -235
  196. package/srv/utils/lease.d.ts +20 -0
  197. package/srv/utils/lease.js +62 -0
  198. package/srv/utils/liveness.d.ts +12 -0
  199. package/srv/utils/liveness.js +35 -0
  200. package/srv/utils/mappers.d.ts +111 -223
  201. package/srv/utils/mappers.js +432 -371
  202. package/srv/utils/navigation.d.ts +17 -0
  203. package/srv/utils/navigation.js +52 -0
  204. package/srv/utils/network-context.d.ts +0 -1
  205. package/srv/utils/network-context.js +9 -15
  206. package/srv/utils/paging.d.ts +31 -0
  207. package/srv/utils/paging.js +43 -0
  208. package/srv/utils/pg-inline-json.d.ts +8 -0
  209. package/srv/utils/pg-inline-json.js +58 -0
  210. package/srv/utils/pg-order-nulls.d.ts +14 -0
  211. package/srv/utils/pg-order-nulls.js +54 -0
  212. package/srv/utils/plutus-placeholders.d.ts +16 -22
  213. package/srv/utils/plutus-placeholders.js +62 -33
  214. package/srv/utils/rate-limiter.d.ts +2 -21
  215. package/srv/utils/rate-limiter.js +5 -17
  216. package/srv/utils/readiness.d.ts +12 -0
  217. package/srv/utils/readiness.js +29 -0
  218. package/srv/utils/reference-script.d.ts +19 -0
  219. package/srv/utils/reference-script.js +84 -0
  220. package/srv/utils/resolution.d.ts +13 -0
  221. package/srv/utils/resolution.js +47 -0
  222. package/srv/utils/result-numbers.d.ts +15 -0
  223. package/srv/utils/result-numbers.js +61 -0
  224. package/srv/utils/row-values.d.ts +7 -0
  225. package/srv/utils/row-values.js +27 -0
  226. package/srv/utils/service-events.d.ts +0 -24
  227. package/srv/utils/service-events.js +3 -25
  228. package/srv/utils/signing-helper.d.ts +3 -20
  229. package/srv/utils/signing-helper.js +35 -64
  230. package/srv/utils/tx-build-helper.d.ts +25 -105
  231. package/srv/utils/tx-build-helper.js +108 -156
  232. package/srv/utils/tx-request-parsers.d.ts +82 -33
  233. package/srv/utils/tx-request-parsers.js +401 -49
  234. package/srv/utils/tx-utils.d.ts +3 -27
  235. package/srv/utils/tx-utils.js +32 -50
  236. package/srv/utils/types.d.ts +294 -232
  237. package/srv/utils/types.js +2 -22
  238. package/srv/utils/validators.d.ts +22 -92
  239. package/srv/utils/validators.js +60 -170
@@ -4,38 +4,41 @@ 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");
10
11
  const errors_1 = require("../../utils/errors");
11
12
  const mappers_1 = require("../../utils/mappers");
13
+ const pool_metadata_1 = require("../pool-metadata");
12
14
  const const_1 = require("../../utils/const");
13
15
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
14
16
  const logger = cds_1.default.log('KoiosBackend');
17
+ const reference_script_1 = require("../../utils/reference-script");
18
+ const call_signal_1 = require("./call-signal");
19
+ const const_2 = require("../../utils/const");
15
20
  /** Bounded retries for instance-specific PostgREST server errors (42703, 57014, …). */
16
21
  const PG_SERVER_ERROR_MAX_RETRIES = 2;
22
+ /** Retries for 42804, which outdated instances behind the load balancer answer for valid requests. */
23
+ const PG_VERSION_SKEW_MAX_RETRIES = 8;
17
24
  const PG_SERVER_ERROR_RETRY_DELAY_MS = 300;
25
+ /** True for the PostgREST error an instance on an older Koios schema answers (42804). */
26
+ function isVersionSkew(data) {
27
+ return data?.code === '42804'
28
+ || /structure of query does not match function result type/i.test(typeof data?.message === 'string' ? data.message : '');
29
+ }
18
30
  const KOIOS_URLS = {
19
31
  mainnet: 'https://api.koios.rest/api/v1',
20
32
  preview: 'https://preview.koios.rest/api/v1',
21
33
  preprod: 'https://preprod.koios.rest/api/v1',
22
34
  };
23
- /**
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).
29
- */
35
+ /** Script CBOR of a Koios `reference_script` object; null for the bare-hash form. */
30
36
  function koiosRefScriptBytes(ref) {
31
- if (!ref)
37
+ if (!ref || typeof ref !== 'object')
32
38
  return null;
33
- if (typeof ref === 'string')
34
- return ref;
35
- const obj = ref;
36
- return obj.bytes || obj.hash || null;
39
+ return ref.bytes || null;
37
40
  }
38
- /** Like koiosRefScriptBytes, but strictly the script HASH (for *Hash fields). */
41
+ /** Script hash of a Koios `reference_script`, which is an object or the bare hash. */
39
42
  function koiosRefScriptHash(ref) {
40
43
  if (!ref)
41
44
  return null;
@@ -44,28 +47,41 @@ function koiosRefScriptHash(ref) {
44
47
  const obj = ref;
45
48
  return obj.hash || null;
46
49
  }
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
- */
52
- function sortAddressTxsDesc(rows) {
53
- return [...rows].sort((a, b) => Number(b.block_height ?? b.block_time ?? 0) - Number(a.block_height ?? a.block_time ?? 0));
50
+ /** Size and type of a Koios `reference_script` object; both null for the bare-hash form. */
51
+ function koiosRefScriptMeta(ref) {
52
+ if (!ref || typeof ref !== 'object')
53
+ return { size: null, type: null };
54
+ const obj = ref;
55
+ const size = Number(obj.size);
56
+ return { size: Number.isInteger(size) && size > 0 ? size : null, type: (0, reference_script_1.normalizeScriptType)(obj.type) };
57
+ }
58
+ /** Koios `/address_utxos` and `/credential_utxos` row, mapped to a UTxO. */
59
+ function mapKoiosUtxo(utxo, address) {
60
+ const amount = [{ unit: 'lovelace', quantity: utxo.value }];
61
+ for (const asset of utxo.asset_list ?? []) {
62
+ amount.push({ unit: `${asset.policy_id}${asset.asset_name}`, quantity: asset.quantity });
63
+ }
64
+ const meta = koiosRefScriptMeta(utxo.reference_script);
65
+ return {
66
+ txHash: utxo.tx_hash,
67
+ outputIndex: utxo.tx_index,
68
+ address,
69
+ amount,
70
+ datumHash: utxo.datum_hash || null,
71
+ scriptRef: koiosRefScriptHash(utxo.reference_script),
72
+ scriptRefCbor: koiosRefScriptBytes(utxo.reference_script),
73
+ scriptRefSize: meta.size,
74
+ scriptRefType: meta.type,
75
+ inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(utxo.inline_datum),
76
+ };
54
77
  }
55
- /**
56
- * KoiosBackend Implementation for CardanoBackend Interface
57
- * Implements the CardanoBackend interface using Koios API with Axios
58
- */
78
+ /** CardanoBackend implementation on the Koios REST API (Axios). */
59
79
  class KoiosBackend {
60
80
  name = 'koios';
61
81
  api;
62
82
  network;
63
- /**
64
- * Constructor
65
- */
66
83
  constructor(network, timeoutMs, apiKey) {
67
84
  const headers = {};
68
- // Add Authorization header if API key is configured
69
85
  if (apiKey) {
70
86
  headers['Authorization'] = `Bearer ${apiKey}`;
71
87
  }
@@ -75,31 +91,33 @@ class KoiosBackend {
75
91
  headers,
76
92
  });
77
93
  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.
94
+ // a request stops when the client gives up the call it belongs to
95
+ this.api.interceptors.request.use((config) => {
96
+ config.signal ??= (0, call_signal_1.callSignal)();
97
+ return config;
98
+ });
99
+ // Koios is load-balanced. Single instances serve broken SQL functions (PostgREST 400, e.g. 42703),
100
+ // statement timeouts (57014) or an older schema (42804) while others are healthy, so a bounded
101
+ // retry usually lands on a healthy instance. This is the only retry layer; client-input errors are not retried.
84
102
  this.api.interceptors.response.use(undefined, async (error) => {
85
103
  const config = error.config;
86
- const pgCode = error.response?.data?.code;
87
- if (!config || !(0, errors_1.isPostgrestServerErrorCode)(pgCode))
104
+ const body = error.response?.data;
105
+ const skew = error.response?.status === 400 && isVersionSkew(body);
106
+ if (!config || !(skew || (0, errors_1.isPostgrestServerErrorCode)(body?.code)))
88
107
  throw error;
89
108
  const attempt = (config.pgRetryCount ?? 0) + 1;
90
- if (attempt > PG_SERVER_ERROR_MAX_RETRIES)
109
+ const maxRetries = skew ? PG_VERSION_SKEW_MAX_RETRIES : PG_SERVER_ERROR_MAX_RETRIES;
110
+ if (attempt > maxRetries)
91
111
  throw error;
92
112
  config.pgRetryCount = attempt;
93
- logger.warn(`Koios instance returned server-side SQL error ${pgCode} for ${config.url} — retry ${attempt}/${PG_SERVER_ERROR_MAX_RETRIES}`);
113
+ const pgCode = body?.code;
114
+ logger.warn(`Koios instance returned server-side SQL error ${pgCode} for ${config.url}, retry ${attempt}/${maxRetries}`);
94
115
  await new Promise(resolve => setTimeout(resolve, PG_SERVER_ERROR_RETRY_DELAY_MS * attempt));
95
116
  return this.api.request(config);
96
117
  });
97
118
  }
98
- /**
99
- * Initialize the backend
100
- */
119
+ /** Probe /tip to verify connectivity. */
101
120
  async init() {
102
- // Test connection by fetching latest block
103
121
  try {
104
122
  await this.api.get('/tip');
105
123
  }
@@ -108,19 +126,8 @@ class KoiosBackend {
108
126
  }
109
127
  return true;
110
128
  }
111
- /**
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
- */
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) {
129
+ /** Retry with backoff when Koios briefly returns [] for a valid query. */
130
+ async fetchWithRetryOnEmpty(fn, label) {
124
131
  const maxRetries = 3;
125
132
  const baseDelayMs = 500;
126
133
  const result = await fn();
@@ -138,40 +145,24 @@ class KoiosBackend {
138
145
  }
139
146
  return [];
140
147
  }
141
- /**
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.
149
- */
150
- async getWithRetryOn42804(url, config, label) {
151
- const maxRetries = 8;
152
- const baseDelayMs = 300;
153
- for (let attempt = 0;; attempt++) {
154
- try {
155
- return await this.api.get(url, config);
156
- }
157
- catch (err) {
158
- const e = err;
159
- const isSkew = e?.response?.status === 400 &&
160
- (e.response.data?.code === '42804' ||
161
- /structure of query does not match function result type/i.test(e.response.data?.message ?? ''));
162
- if (!isSkew || attempt >= maxRetries)
163
- throw err;
164
- const delay = baseDelayMs * (attempt + 1);
165
- logger.warn(`${label}: Koios transient 42804 (grest version skew), retry ${attempt + 1}/${maxRetries} after ${delay}ms...`);
166
- await new Promise(r => setTimeout(r, delay));
167
- }
148
+ // Every row of a list. PostgREST answers at most LIST_PAGE_SIZE rows per request, so this pages
149
+ // with `order`, which must name a unique key: without one, load-balanced instances may repeat or skip rows.
150
+ async allRows(path, order, body, label = path) {
151
+ const rows = [];
152
+ for (let page = 0; page < KoiosBackend.LIST_MAX_PAGES; page++) {
153
+ (0, call_signal_1.throwIfCallAborted)();
154
+ const params = { order, limit: KoiosBackend.LIST_PAGE_SIZE, offset: page * KoiosBackend.LIST_PAGE_SIZE };
155
+ const { data } = body
156
+ ? await this.api.post(path, body, { params })
157
+ : await this.api.get(path, { params });
158
+ if (!Array.isArray(data))
159
+ return rows;
160
+ rows.push(...data);
161
+ if (data.length < KoiosBackend.LIST_PAGE_SIZE)
162
+ return rows;
168
163
  }
164
+ throw new errors_1.ProviderUnavailableError(`${label}: more than ${KoiosBackend.LIST_MAX_PAGES} pages, the list is not complete`, this.name);
169
165
  }
170
- /**
171
- * Get Transaction Data for specified transaction hash
172
- * @param hash transaction hash (hex)
173
- * @returns {Promise<Transaction>} transaction data
174
- */
175
166
  async getTransaction(hash) {
176
167
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
177
168
  const body = {
@@ -181,8 +172,9 @@ class KoiosBackend {
181
172
  _assets: true,
182
173
  _withdrawals: false,
183
174
  _certs: false,
184
- _scripts: false,
185
- _bytecode: false,
175
+ // Koios sends inline datum bytes and reference scripts only with both flags.
176
+ _scripts: true,
177
+ _bytecode: true,
186
178
  };
187
179
  const { data } = await this.api.post('/tx_info', body);
188
180
  if (!data || !Array.isArray(data) || data.length === 0) {
@@ -192,11 +184,6 @@ class KoiosBackend {
192
184
  return this._mapKoiosTx(tx);
193
185
  }, this.name);
194
186
  }
195
- /**
196
- * Get Block Data for specified block hash
197
- * @param blockHash block hash (hex)
198
- * @returns {Promise<BlockData>} block data
199
- */
200
187
  async getBlock(blockHash) {
201
188
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
202
189
  const results = await this.fetchWithRetryOnEmpty(() => this.api.post('/block_info', { _block_hashes: [blockHash] }), `getBlock(${blockHash})`);
@@ -206,14 +193,9 @@ class KoiosBackend {
206
193
  return this.mapKoiosBlockInfo(results[0]);
207
194
  }, this.name);
208
195
  }
209
- /**
210
- * Get Epoch Data for specified epoch number
211
- * @param epochNumber epoch number
212
- * @returns {Promise<EpochData>} epoch data
213
- */
214
196
  async getEpoch(epochNumber) {
215
197
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
216
- const results = await this.fetchWithRetryOnEmpty(() => this.getWithRetryOn42804('/epoch_info', { params: { _epoch_no: epochNumber } }, `getEpoch(${epochNumber})`), `getEpoch(${epochNumber})`);
198
+ const results = await this.fetchWithRetryOnEmpty(() => this.api.get('/epoch_info', { params: { _epoch_no: epochNumber } }), `getEpoch(${epochNumber})`);
217
199
  if (!results || results.length === 0) {
218
200
  throw new errors_1.NotFoundError('Epoch', this.name);
219
201
  }
@@ -224,19 +206,15 @@ class KoiosBackend {
224
206
  end_time: data.end_time,
225
207
  first_block_time: data.first_block_time,
226
208
  last_block_time: data.last_block_time,
227
- block_count: data.block_count,
209
+ block_count: data.blk_count,
228
210
  tx_count: data.tx_count,
229
- output: data.total_output,
230
- fees: data.total_fees,
211
+ output: data.out_sum,
212
+ fees: data.fees,
231
213
  active_stake: data.active_stake,
232
214
  };
233
215
  }, this.name);
234
216
  }
235
- /**
236
- * Get Address Data (without transactions - use getAddressTransactions() separately)
237
- * @param address bech32 address
238
- * @returns {Promise<Address>} address data
239
- */
217
+ /** Address data. Transactions come from getAddressTransactions(). */
240
218
  async getAddress(address) {
241
219
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
242
220
  const { data } = await this.api.post('/address_info', { _addresses: [address] });
@@ -245,8 +223,7 @@ class KoiosBackend {
245
223
  }
246
224
  const addressData = data[0];
247
225
  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).
226
+ // Sum the balance over every UTxO; address_info's utxo_set may carry a null asset_list.
250
227
  const totals = new Map();
251
228
  for (const u of addressUtxos) {
252
229
  for (const a of u.amount) {
@@ -260,23 +237,17 @@ class KoiosBackend {
260
237
  return {
261
238
  address: address,
262
239
  stakeAddress: addressData.stake_address || null,
263
- type: addressData.address_type,
264
- isScript: addressData.is_script,
240
+ // /address_info has no address type; it follows from the address itself
241
+ type: (0, mappers_1.decodeShelleyAddress)(address).type,
242
+ isScript: addressData.script_address,
265
243
  amount: amount,
266
244
  utxos: addressUtxos,
267
245
  };
268
246
  }, this.name);
269
247
  }
270
- /**
271
- * Get Address Transactions
272
- * @param address bech32 address
273
- * @returns {Promise<Transaction[]>} list of transactions for this address
274
- */
275
248
  async getAddressTransactions(address, limit) {
276
249
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
277
- const { data: addressTxs } = await this.api.post('/address_txs', { _addresses: [address] });
278
- // newest first, THEN limit (saves API calls); batch instead of unbounded Promise.all
279
- const limitedTxs = sortAddressTxsDesc(addressTxs).slice(0, limit);
250
+ const limitedTxs = await this.newestAddressTxs(address, limit);
280
251
  const batch = await this.getTransactionsBatch(limitedTxs.map(tx => tx.tx_hash));
281
252
  const transactions = [];
282
253
  for (const tx of limitedTxs) {
@@ -287,85 +258,30 @@ class KoiosBackend {
287
258
  return transactions;
288
259
  }, this.name);
289
260
  }
290
- /**
291
- * Get Address UTxOs for specified address
292
- * @param address bech32 address
293
- * @returns {Promise<UTxO[]>} list of UTxOs
294
- */
261
+ /** Every UTxO of an address, paged past the 1000-row cap of a Koios answer. */
295
262
  async getAddressUtxos(address) {
296
263
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
297
- const { data } = await this.api.post('/address_utxos', { _addresses: [address], _extended: true });
298
- return data.map((utxo) => {
299
- const amount = [
300
- { unit: 'lovelace', quantity: utxo.value }
301
- ];
302
- // add native asset(s) if present
303
- if (utxo.asset_list && Array.isArray(utxo.asset_list)) {
304
- for (const asset of utxo.asset_list) {
305
- amount.push({
306
- unit: `${asset.policy_id}${asset.asset_name}`,
307
- quantity: asset.quantity
308
- });
309
- }
310
- }
311
- return {
312
- txHash: utxo.tx_hash,
313
- outputIndex: utxo.tx_index,
314
- address: address,
315
- amount: amount,
316
- blockHash: utxo.block_hash,
317
- datumHash: utxo.datum_hash || null,
318
- scriptRef: koiosRefScriptBytes(utxo.reference_script),
319
- inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(utxo.inline_datum),
320
- };
321
- });
264
+ const rows = await this.allRows('/address_utxos', 'tx_hash.asc,tx_index.asc', { _addresses: [address], _extended: true }, 'getAddressUtxos');
265
+ return rows.map((utxo) => mapKoiosUtxo(utxo, address));
322
266
  }, this.name);
323
267
  }
324
- /**
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.
328
- * @param credHash 28-byte payment credential as 56-char lowercase hex
329
- * @returns {Promise<UTxO[]>} list of UTxOs across all bech32 forms
330
- */
268
+ /** Every UTxO of every address with this payment credential (56 hex chars), paged. */
331
269
  async getCredentialUtxos(credHash) {
332
270
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
333
- const { data } = await this.api.post('/credential_utxos', {
334
- _payment_credentials: [credHash],
335
- _extended: true,
336
- });
337
- return data.map((utxo) => {
338
- const amount = [
339
- { unit: 'lovelace', quantity: utxo.value }
340
- ];
341
- if (utxo.asset_list && Array.isArray(utxo.asset_list)) {
342
- for (const asset of utxo.asset_list) {
343
- amount.push({
344
- unit: `${asset.policy_id}${asset.asset_name}`,
345
- quantity: asset.quantity
346
- });
347
- }
348
- }
349
- return {
350
- txHash: utxo.tx_hash,
351
- outputIndex: utxo.tx_index,
352
- address: utxo.address ?? '',
353
- amount: amount,
354
- blockHash: utxo.block_hash,
355
- datumHash: utxo.datum_hash || null,
356
- scriptRef: koiosRefScriptBytes(utxo.reference_script),
357
- inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(utxo.inline_datum),
358
- };
359
- });
271
+ const rows = await this.allRows('/credential_utxos', 'tx_hash.asc,tx_index.asc', { _payment_credentials: [credHash], _extended: true }, 'getCredentialUtxos');
272
+ return rows.map((utxo) => mapKoiosUtxo(utxo, utxo.address ?? ''));
360
273
  }, this.name);
361
274
  }
362
- /**
363
- * Get Network Information
364
- * @returns {Promise<Network>} network information
365
- */
275
+ /** The newest `limit` transactions of an address, ordered by Koios before it cuts the list. */
276
+ async newestAddressTxs(address, limit) {
277
+ const { data } = await this.api.post('/address_txs', { _addresses: [address] }, {
278
+ params: { order: 'block_height.desc,tx_hash.asc', limit: Math.max(1, limit) },
279
+ });
280
+ return Array.isArray(data) ? data : [];
281
+ }
366
282
  async getNetworkInformation() {
367
283
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
368
- // Try /totals endpoint (works on mainnet, but returns empty array on preview/preprod testnet)
284
+ // /totals has no locked supply and no stake; those stay null
369
285
  const { data: totalsData } = await this.api.get('/totals', {
370
286
  params: { order: 'epoch_no.desc', limit: 1 }
371
287
  });
@@ -374,47 +290,33 @@ class KoiosBackend {
374
290
  return {
375
291
  supply: {
376
292
  max: const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY,
377
- total: latest.supply || '0',
378
- circulating: latest.circulation || '0',
379
- locked: '0', // Not available in /totals
380
- treasury: latest.treasury || '0',
381
- reserves: latest.reserves || '0',
382
- },
383
- stake: {
384
- live: '0',
385
- active: '0',
293
+ total: latest.supply ?? null,
294
+ circulating: latest.circulation ?? null,
295
+ locked: null,
296
+ treasury: latest.treasury ?? null,
297
+ reserves: latest.reserves ?? null,
386
298
  },
299
+ stake: { live: null, active: null },
387
300
  };
388
301
  }
389
- // Fallback for preview/preprod network where /totals doesn't work
390
- // Use genesis endpoint to get max supply; remaining fields default to '0'
302
+ // Without /totals rows only the maximum supply is known, from /genesis.
391
303
  const { data: genesisData } = await this.api.get('/genesis');
392
304
  if (!genesisData || !Array.isArray(genesisData) || genesisData.length === 0) {
393
305
  throw new errors_1.NotFoundError('Genesis', this.name);
394
306
  }
395
- const genesis = genesisData[0];
396
- const maxSupply = genesis.maxlovelacesupply || const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY;
397
307
  return {
398
308
  supply: {
399
- max: maxSupply,
400
- total: maxSupply,
401
- circulating: maxSupply,
402
- locked: '0',
403
- treasury: '0',
404
- reserves: '0',
405
- },
406
- stake: {
407
- live: '0',
408
- active: '0',
309
+ max: genesisData[0].maxlovelacesupply || const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY,
310
+ total: null,
311
+ circulating: null,
312
+ locked: null,
313
+ treasury: null,
314
+ reserves: null,
409
315
  },
316
+ stake: { live: null, active: null },
410
317
  };
411
318
  }, this.name);
412
319
  }
413
- /**
414
- * Get Transaction Metadata for specified transaction hash
415
- * @param tx_hash transaction hash (hex)
416
- * @returns {Promise<MetadataLabelTx[]>} transaction metadata list
417
- */
418
320
  async getTransactionMetadata(tx_hash) {
419
321
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
420
322
  const body = {
@@ -439,46 +341,47 @@ class KoiosBackend {
439
341
  return labels;
440
342
  }, this.name);
441
343
  }
442
- /**
443
- * Get Pool Data for specified pool id
444
- * @param poolId pool id
445
- * @returns {Promise<PoolData>} pool data
446
- */
447
344
  async getPool(poolId) {
448
345
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
449
346
  const { data } = await this.api.post('/pool_info', { _pool_bech32_ids: [poolId] });
450
347
  if (!Array.isArray(data) || data.length === 0) {
451
348
  throw new errors_1.NotFoundError('Pool', this.name);
452
349
  }
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
- };
350
+ return this._mapKoiosPool(data[0], poolId);
473
351
  }, this.name);
474
352
  }
475
- /**
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.
479
- * @param unit policyId + assetNameHex (concatenated hex)
480
- * @returns {Promise<AssetInfo>} canonical asset info
481
- */
353
+ /** Map one Koios /pool_info row to the canonical PoolData. */
354
+ _mapKoiosPool(poolData, fallbackId) {
355
+ const metadata = (0, pool_metadata_1.validPoolMetadata)(poolData.meta_json);
356
+ return {
357
+ poolId: poolData.pool_id_bech32 || poolData.pool_id_hex || fallbackId,
358
+ vrfKeyHash: poolData.vrf_key_hash || '',
359
+ blocksMinted: poolData.block_count || 0,
360
+ // Koios pool_info has no blocks-in-current-epoch figure. null = not available;
361
+ // a 0 would be indistinguishable from a real zero downstream.
362
+ blocksEpoch: null,
363
+ liveStake: poolData.live_stake || '0',
364
+ // /pool_info has no live share
365
+ liveSize: null,
366
+ liveDelegators: poolData.live_delegators || 0,
367
+ // Koios reports saturation in percent (75.42). PoolData holds a fraction (0.7542),
368
+ // because the percent value would overflow the Decimal(9, 4) column.
369
+ liveSaturation: (Number(poolData.live_saturation) || 0) / 100,
370
+ activeStake: poolData.active_stake || '0',
371
+ activeSize: Number(poolData.sigma) || 0,
372
+ pledge: poolData.pledge || '0',
373
+ margin: poolData.margin || 0,
374
+ fixedCost: poolData.fixed_cost || '0',
375
+ rewardAccount: poolData.reward_addr || '',
376
+ metadataUrl: poolData.meta_url ?? null,
377
+ metadataHash: poolData.meta_hash ?? null,
378
+ name: metadata?.name ?? null,
379
+ ticker: metadata?.ticker ?? null,
380
+ homepage: metadata?.homepage ?? null,
381
+ description: metadata?.description ?? null,
382
+ };
383
+ }
384
+ /** Asset info from Koios `asset_info`. */
482
385
  async getAssetInfo(unit) {
483
386
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
484
387
  if (unit.length < 56 || !/^[a-f0-9]+$/i.test(unit)) {
@@ -494,16 +397,13 @@ class KoiosBackend {
494
397
  }
495
398
  const a = data[0];
496
399
  // Koios token_registry_metadata fields are typically strings, but the
497
- // CIP-26 registry permits {value, signatures} envelopes — accept either.
400
+ // CIP-26 registry entries may be wrapped in {value, signatures}. Accept either form.
498
401
  const regRaw = (a.token_registry_metadata ?? null);
402
+ // Koios sends an empty string for a registry field the entry does not carry.
499
403
  const regStr = (key) => {
500
404
  const v = regRaw?.[key];
501
- if (typeof v === 'string')
502
- return v;
503
- if (v && typeof v === 'object' && typeof v.value === 'string') {
504
- return v.value;
505
- }
506
- return null;
405
+ const text = v && typeof v === 'object' ? v.value : v;
406
+ return typeof text === 'string' && text !== '' ? text : null;
507
407
  };
508
408
  const regNum = (key) => {
509
409
  const v = regRaw?.[key];
@@ -519,23 +419,15 @@ class KoiosBackend {
519
419
  const onchainMetadata = mintMeta && typeof mintMeta === 'object'
520
420
  ? (mintMeta['721'] ?? mintMeta)
521
421
  : 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
- };
422
+ const decodeUtf8 = (hex) => (hex ? (0, mappers_1.decodeAssetName)(hex) : null);
532
423
  const mintCnt = typeof a.mint_cnt === 'number' ? a.mint_cnt : 0;
533
424
  const burnCnt = typeof a.burn_cnt === 'number' ? a.burn_cnt : 0;
534
425
  return {
535
426
  unit,
536
427
  policyId,
537
428
  assetNameHex,
538
- assetName: a.asset_name_ascii ?? decodeUtf8(assetNameHex),
429
+ // Koios has '' for an asset without a name; every asset row stores null there
430
+ assetName: a.asset_name_ascii || decodeUtf8(assetNameHex),
539
431
  fingerprint: a.fingerprint,
540
432
  totalSupply: a.total_supply ?? '0',
541
433
  mintOrBurnCount: mintCnt + burnCnt,
@@ -551,16 +443,8 @@ class KoiosBackend {
551
443
  };
552
444
  }, this.name);
553
445
  }
554
- /**
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)
563
- */
446
+ // Koios `asset_history` returns all events with a signed quantity. A negative one is a burn.
447
+ // `limit` is applied here after sorting newest first.
564
448
  async getAssetHistory(unit, limit = 100) {
565
449
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
566
450
  if (unit.length < 56 || !/^[a-f0-9]+$/i.test(unit)) {
@@ -568,8 +452,9 @@ class KoiosBackend {
568
452
  }
569
453
  const policyId = unit.slice(0, 56);
570
454
  const assetNameHex = unit.slice(56);
571
- const { data } = await this.api.post('/asset_history', {
572
- _asset_list: [[policyId, assetNameHex]],
455
+ // GET only: Koios answers a POST to /asset_history with 404
456
+ const { data } = await this.api.get('/asset_history', {
457
+ params: { _asset_policy: policyId, _asset_name: assetNameHex },
573
458
  });
574
459
  if (!Array.isArray(data) || data.length === 0)
575
460
  return [];
@@ -583,19 +468,16 @@ class KoiosBackend {
583
468
  action: isNegative ? 'burn' : 'mint',
584
469
  quantity: isNegative ? rawQty.slice(1) : rawQty,
585
470
  blockTime: typeof entry.block_time === 'number' ? entry.block_time : null,
586
- blockHeight: typeof entry.block_height === 'number' ? entry.block_height : null,
471
+ // minting_txs carry no block height
472
+ blockHeight: null,
587
473
  };
588
474
  });
589
- // Sort newest-first and cap at limit (defensive — Koios may return ascending)
590
- events.sort((a, b) => (b.blockTime ?? 0) - (a.blockTime ?? 0));
591
- return events.slice(0, Math.max(1, limit));
475
+ // Koios may return ascending order and may list one transaction twice
476
+ const unique = [...new Map(events.map(e => [e.txHash, e])).values()];
477
+ unique.sort((a, b) => (b.blockTime ?? 0) - (a.blockTime ?? 0));
478
+ return unique.slice(0, Math.max(1, limit));
592
479
  }, this.name);
593
480
  }
594
- /**
595
- * Get Drep Data for specified drep id
596
- * @param drepId drep id
597
- * @returns {Promise<DrepData>} drep data
598
- */
599
481
  async getDrep(drepId) {
600
482
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
601
483
  const body = {
@@ -605,32 +487,29 @@ class KoiosBackend {
605
487
  if (!Array.isArray(data) || data.length === 0) {
606
488
  throw new errors_1.NotFoundError('Drep', this.name);
607
489
  }
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
- };
490
+ return this._mapKoiosDrep(data[0]);
627
491
  }, this.name);
628
492
  }
629
- /**
630
- * Get Account Data for specified stake address
631
- * @param accountId account id
632
- * @returns {Promise<AccountData>} account data
633
- */
493
+ // Map one Koios /drep_info row to the canonical DrepData. `drep_status` is registered,
494
+ // deregistered or not_registered; a deregistered DRep is retired. Older instances answer
495
+ // `retired` and `expired` instead, and those win where present.
496
+ _mapKoiosDrep(drepData) {
497
+ const retired = drepData.retired ?? drepData.drep_status === 'deregistered';
498
+ const expired = drepData.expired ?? (drepData.active === false && !retired);
499
+ return {
500
+ drepId: drepData.drep_id,
501
+ hex: drepData.hex,
502
+ amount: drepData.amount,
503
+ hasScript: drepData.has_script,
504
+ // Koios has no last-activity epoch
505
+ lastActiveEpoch: drepData.last_active_epoch ?? 0,
506
+ expired,
507
+ retired,
508
+ deposit: drepData.deposit ?? null,
509
+ expiresEpoch: drepData.expires_epoch_no ?? null,
510
+ delegatorCount: drepData.live_delegator_count ?? null,
511
+ };
512
+ }
634
513
  async getAccount(accountId) {
635
514
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
636
515
  const body = {
@@ -640,61 +519,63 @@ class KoiosBackend {
640
519
  if (!Array.isArray(data) || data.length === 0) {
641
520
  throw new errors_1.NotFoundError('Account', this.name);
642
521
  }
643
- // Fetch associated addresses
644
- const addressDataResponse = await this.api.post('/account_addresses', body);
645
- // Koios returns [{ stake_address, addresses: [...] }], flatten to get all addresses
646
- const addressesFlat = addressDataResponse.data.flatMap((item) => item.addresses);
647
- const addresses = [];
648
- const concurrent = 10;
649
- for (let i = 0; i < addressesFlat.length; i += concurrent) {
650
- const chunk = addressesFlat.slice(i, i + concurrent);
651
- const chunkResults = await Promise.all(chunk.map((addr) => this.getAddress(addr)));
652
- addresses.push(...chunkResults);
653
- }
522
+ // one row per stake address with all its addresses; their UTxOs are read separately.
523
+ // `_empty: true` lists addresses without UTxOs too, as Blockfrost does.
524
+ const addressDataResponse = await this.api.post('/account_addresses', { ...body, _empty: true });
525
+ const addresses = addressDataResponse.data.flatMap(item => item.addresses ?? []);
654
526
  const accountData = data[0];
655
527
  return {
656
528
  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,
529
+ active: accountData.status === 'registered',
530
+ // /account_info has no registration epoch
531
+ activeEpoch: 0,
532
+ controlledAmount: accountData.total_balance,
533
+ rewardsSum: accountData.rewards,
534
+ withdrawalsSum: accountData.withdrawals,
535
+ reservesSum: accountData.reserves,
536
+ treasurySum: accountData.treasury,
537
+ withdrawableAmount: accountData.rewards_available,
538
+ poolId: accountData.delegated_pool || null,
539
+ drepId: accountData.delegated_drep || null,
667
540
  addresses: addresses,
668
541
  };
669
542
  }, this.name);
670
543
  }
671
- /**
672
- * Submit Transaction
673
- * @param signedTxCbor signed transaction in CBOR hex format
674
- * @returns {Promise<string>} transaction hash
675
- */
676
544
  async submitTransaction(signedTxCbor) {
677
545
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
678
546
  // Koios /submittx expects raw CBOR bytes with Content-Type: application/cbor
679
547
  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, '');
548
+ try {
549
+ const { data } = await this.api.post('/submittx', cborBytes, {
550
+ headers: { 'Content-Type': 'application/cbor' },
551
+ // Prevent axios from JSON-serializing the Buffer
552
+ transformRequest: [(d) => d],
553
+ });
554
+ return data.trim().replace(/^"|"$/g, '');
555
+ }
556
+ catch (err) {
557
+ // 400 carries the node's rejection (e.g. ExtraneousScriptWitnessesUTXOW); keep it
558
+ const response = err.response;
559
+ if (response?.status === 400 && response.data) {
560
+ throw (0, errors_1.submitRejection)((0, errors_1.nodeRejectionReason)(response.data), this.name, err);
561
+ }
562
+ throw err;
563
+ }
686
564
  }, this.name);
687
565
  }
688
- /**
689
- * Get Protocol Parameters
690
- * @returns {Promise<any>} protocol parameters
691
- */
692
566
  async getProtocolParameters() {
693
567
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
694
- const { data } = await this.api.get('/cli_protocol_params');
568
+ // /cli_protocol_params carries no epoch; the tip does. Without it the epoch stays 0.
569
+ const [{ data }, epoch] = await Promise.all([
570
+ this.api.get('/cli_protocol_params'),
571
+ this.api.get('/tip').then((r) => Number(r.data?.[0]?.epoch_no ?? 0), (err) => {
572
+ logger.warn(`Koios /tip failed, protocol parameters without epoch: ${err instanceof Error ? err.message : String(err)}`);
573
+ return 0;
574
+ }),
575
+ ]);
695
576
  return {
696
577
  network: this.network,
697
- epoch: 0, // Koios doesn't provide current epoch in this endpoint
578
+ epoch,
698
579
  // --- Fees / Sizes ---
699
580
  minFeeA: data.txFeePerByte,
700
581
  minFeeB: data.txFeeFixed,
@@ -730,16 +611,14 @@ class KoiosBackend {
730
611
  collateralPercent: data.collateralPercentage,
731
612
  maxCollateralInputs: data.maxCollateralInputs,
732
613
  coinsPerUtxoSize: data.utxoCostPerByte.toString(),
614
+ // cardano-cli spelling, as /cli_protocol_params publishes it
615
+ minFeeRefScriptCostPerByte: data.minFeeRefScriptCostPerByte ?? null,
733
616
  // --- Housekeeping ---
734
617
  fetchedAt: new Date().toISOString(),
735
618
  source: this.name
736
619
  };
737
620
  }, this.name);
738
621
  }
739
- /**
740
- * Get Latest Block Data
741
- * @returns {Promise<BlockData>} latest block data
742
- */
743
622
  async getLatestBlock() {
744
623
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
745
624
  const tipData = await this.fetchWithRetryOnEmpty(() => this.api.get('/tip'), 'getLatestBlock');
@@ -749,10 +628,6 @@ class KoiosBackend {
749
628
  return await this.getBlock(tipData[0].hash);
750
629
  }, this.name);
751
630
  }
752
- /**
753
- * Get Latest Epoch Data
754
- * @returns {Promise<EpochData>} latest epoch data
755
- */
756
631
  async getLatestEpoch() {
757
632
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
758
633
  const tipData = await this.fetchWithRetryOnEmpty(() => this.api.get('/tip'), 'getLatestEpoch');
@@ -763,16 +638,14 @@ class KoiosBackend {
763
638
  try {
764
639
  return await this.getEpoch(epochNo);
765
640
  }
766
- catch {
767
- // Current epoch may not be available yet on Koios — fall back to previous
641
+ catch (err) {
642
+ // Right after the boundary Koios may not list the new epoch yet. Any other error is not that.
643
+ if (!(err instanceof errors_1.NotFoundError))
644
+ throw err;
768
645
  return await this.getEpoch(epochNo - 1);
769
646
  }
770
647
  }, this.name);
771
648
  }
772
- /**
773
- * Get the latest chain tip slot.
774
- * @returns {Promise<number>} current chain slot
775
- */
776
649
  async getCurrentSlot() {
777
650
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
778
651
  const tipData = await this.fetchWithRetryOnEmpty(() => this.api.get('/tip'), 'getCurrentSlot');
@@ -786,12 +659,7 @@ class KoiosBackend {
786
659
  return slot;
787
660
  }, this.name);
788
661
  }
789
- /**
790
- * Check whether a UTxO is still unspent via Koios `POST /utxo_info`.
791
- * @param txHash 64-char lowercase hex
792
- * @param outputIndex non-negative integer
793
- * @returns {Promise<boolean>} true iff the UTxO exists and is unspent
794
- */
662
+ /** Whether a UTxO exists and is unspent, via Koios `POST /utxo_info`. */
795
663
  async isUtxoUnspent(txHash, outputIndex) {
796
664
  if (!Number.isInteger(outputIndex) || outputIndex < 0)
797
665
  return false;
@@ -809,41 +677,35 @@ class KoiosBackend {
809
677
  //-----------------------------------------------------------------------------
810
678
  // Batch Methods (N+1 Optimization)
811
679
  //-----------------------------------------------------------------------------
812
- /**
813
- * Get transaction hashes for an address (lightweight — no full tx details).
814
- * @param address bech32 address
815
- * @param limit maximum number of hashes
816
- * @returns {Promise<string[]>} most recent tx hashes
817
- */
680
+ /** Most recent tx hashes of an address, without tx details. */
818
681
  async getAddressTransactionHashes(address, limit) {
819
682
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
820
- const { data } = await this.api.post('/address_txs', { _addresses: [address] });
821
- return sortAddressTxsDesc(data)
822
- .slice(0, limit)
823
- .map(tx => tx.tx_hash);
683
+ return (await this.newestAddressTxs(address, limit)).map(tx => tx.tx_hash);
824
684
  }, this.name);
825
685
  }
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
- */
686
+ /** crawler.certificates: ask /tx_info for certificates + withdrawals on the crawl's batch call. */
687
+ crawlCertificates = false;
688
+ configureCrawl(options) {
689
+ this.crawlCertificates = Boolean(options.certificates);
690
+ }
691
+ /** Batch fetch transactions via POST /tx_info, chunked at 100 hashes (Koios limit). */
832
692
  async getTransactionsBatch(txHashes) {
833
693
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
834
694
  const BATCH_SIZE = 100;
835
695
  const result = new Map();
836
696
  for (let i = 0; i < txHashes.length; i += BATCH_SIZE) {
697
+ (0, call_signal_1.throwIfCallAborted)();
837
698
  const chunk = txHashes.slice(i, i + BATCH_SIZE);
838
699
  const { data } = await this.api.post('/tx_info', {
839
700
  _tx_hashes: chunk,
840
701
  _inputs: true,
841
702
  _metadata: true,
842
703
  _assets: true,
843
- _withdrawals: false,
844
- _certs: false,
845
- _scripts: false,
846
- _bytecode: false,
704
+ // certificates + withdrawals only when the crawl will write them (larger payload)
705
+ _withdrawals: this.crawlCertificates,
706
+ _certs: this.crawlCertificates,
707
+ _scripts: true,
708
+ _bytecode: true,
847
709
  });
848
710
  if (data && Array.isArray(data)) {
849
711
  for (const tx of data) {
@@ -860,12 +722,9 @@ class KoiosBackend {
860
722
  }, this.name);
861
723
  }
862
724
  // ---------------------------------------------------------------------------
863
- // PaginatingBackend — forward iteration for the chain crawler (v2.0)
725
+ // PaginatingBackend: forward iteration for the chain crawler
864
726
  // ---------------------------------------------------------------------------
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
- */
727
+ /** Map a Koios /block_info row to BlockData. */
869
728
  mapKoiosBlockInfo(data) {
870
729
  return {
871
730
  time: data.block_time,
@@ -874,16 +733,14 @@ class KoiosBackend {
874
733
  slot: data.abs_slot,
875
734
  epoch: data.epoch_no,
876
735
  epochSlot: data.epoch_slot,
877
- slotLeader: data.vrf_key,
736
+ slotLeader: data.pool ?? '',
878
737
  size: data.block_size,
879
738
  txCount: data.tx_count,
880
739
  fees: data.total_fees,
740
+ previousHash: data.parent_hash,
881
741
  };
882
742
  }
883
- /**
884
- * Get a block by its height via the PostgREST-filtered /blocks list, then resolve
885
- * full data through /block_info.
886
- */
743
+ /** Finds the block in the filtered /blocks list, then reads it from /block_info. */
887
744
  async getBlockByHeight(height) {
888
745
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
889
746
  const rows = await this.fetchWithRetryOnEmpty(() => this.api.get(`/blocks?block_height=eq.${height}&limit=1`), `getBlockByHeight(${height})`);
@@ -892,22 +749,15 @@ class KoiosBackend {
892
749
  return await this.getBlock(rows[0].hash);
893
750
  }, this.name);
894
751
  }
895
- /**
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.
901
- */
752
+ // Koios has no "blocks after hash" endpoint. This lists blocks above the start height
753
+ // and reads them in one /block_info batch. A known `afterHeight` saves the height lookup.
902
754
  async getNextBlocks(afterHash, count, afterHeight) {
903
755
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
904
756
  let anchorHeight = afterHeight;
905
757
  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.
758
+ // A height hint is not proof the cursor is still canonical: after a rollback Koios
759
+ // keeps listing blocks above H while `afterHash` is orphaned. Validate the hash first
760
+ // so the crawler enters reorg recovery.
911
761
  const canonical = await this.fetchWithRetryOnEmpty(() => this.api.get(`/blocks?block_height=eq.${anchorHeight}&limit=1`), `getNextBlocks/anchor(${anchorHeight})`);
912
762
  const canonicalHash = canonical[0]?.hash;
913
763
  if (!canonicalHash) {
@@ -921,19 +771,21 @@ class KoiosBackend {
921
771
  const info = await this.fetchWithRetryOnEmpty(() => this.api.post('/block_info', { _block_hashes: [afterHash] }), `getNextBlocks/height(${afterHash})`);
922
772
  if (!info.length)
923
773
  throw new errors_1.NotFoundError('Block', this.name);
774
+ if (info[0].block_height == null) {
775
+ throw new errors_1.ProviderUnavailableError(`Block ${afterHash} has no height on Koios and cannot anchor pagination`, this.name);
776
+ }
924
777
  anchorHeight = info[0].block_height;
925
778
  }
926
- const rows = await this.fetchWithRetryOnEmpty(() => this.api.get(`/blocks?block_height=gt.${anchorHeight}&order=block_height.asc&limit=${count}`), `getNextBlocks(${afterHash})`);
779
+ // at the tip an empty list is the answer, not a lagging instance
780
+ const { data: listed } = await this.api.get(`/blocks?block_height=gt.${anchorHeight}&order=block_height.asc&limit=${count}`);
781
+ const rows = Array.isArray(listed) ? listed : [];
927
782
  if (!rows.length)
928
783
  return [];
929
784
  const requestedHashes = rows.map((r) => r.hash);
930
785
  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.
786
+ // Load-balanced instances can return a PARTIAL /block_info batch. Returning the subset
787
+ // would advance the cursor past the missing block and leave a permanent hole (crawled
788
+ // entities are never re-fetched), so fail the round as transient instead.
937
789
  if (infos.length < requestedHashes.length) {
938
790
  const returned = new Set(infos.map((d) => d.hash));
939
791
  const missing = requestedHashes.filter((h) => !returned.has(h));
@@ -944,13 +796,87 @@ class KoiosBackend {
944
796
  .sort((a, b) => (a.height ?? 0) - (b.height ?? 0));
945
797
  }, this.name);
946
798
  }
947
- /**
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.
951
- */
952
- async getBlockTransactions(blockHash) {
799
+ // ---------------------------------------------------------------------------
800
+ // EnumeratingBackend: all pools and DReps for the crawler's epoch snapshots
801
+ // ---------------------------------------------------------------------------
802
+ /** Rows per page when listing ids (PostgREST caps a response at 1000 rows). */
803
+ static LIST_PAGE_SIZE = 1000;
804
+ /** Ids resolved per /pool_info / /drep_info request. */
805
+ static INFO_BATCH_SIZE = 50;
806
+ /** Page cap. 500 pages hold 500 000 ids, far beyond any real pool or DRep set. */
807
+ static LIST_MAX_PAGES = 500;
808
+ /** Every value of one id column of a list endpoint, in the order of that column. */
809
+ async listAllIds(path, column, label) {
810
+ const rows = await this.allRowsOf(path, column, `${column}.asc`, label);
811
+ return rows.map(row => row[column]).filter((id) => typeof id === 'string' && id.length > 0);
812
+ }
813
+ /** Rows of a GET list endpoint with only the `select` columns, paged. */
814
+ allRowsOf(path, select, order, label) {
815
+ return this.allRows(`${path}?select=${select}`, order, undefined, label);
816
+ }
817
+ /** Units with a CIP-26 registry entry, from `asset_token_registry` (the whole registry, paged). */
818
+ async getTokenRegistryUnits() {
819
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
820
+ const rows = await this.allRowsOf('/asset_token_registry', 'policy_id,asset_name', 'policy_id.asc,asset_name.asc', 'getTokenRegistryUnits');
821
+ const units = [];
822
+ for (const r of rows) {
823
+ if (typeof r.policy_id !== 'string' || !const_2.HEX_56_REGEX.test(r.policy_id.toLowerCase()))
824
+ continue;
825
+ const name = typeof r.asset_name === 'string' ? r.asset_name : '';
826
+ if (!/^([0-9a-f]{2}){0,32}$/i.test(name))
827
+ continue;
828
+ units.push((r.policy_id + name).toLowerCase());
829
+ }
830
+ return units;
831
+ }, this.name);
832
+ }
833
+ /** All pool ids, including retired ones, so a snapshot does not drop retiring pools. */
834
+ async getPoolIds() {
835
+ return (0, backend_request_handler_1.handleBackendRequest)(() => this.listAllIds('/pool_list', 'pool_id_bech32', 'getPoolIds'), this.name);
836
+ }
837
+ /** Resolve pool ids in batches. Ids Koios does not return are omitted, never filled with empty rows. */
838
+ async getPools(poolIds) {
839
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
840
+ const out = [];
841
+ for (let i = 0; i < poolIds.length; i += KoiosBackend.INFO_BATCH_SIZE) {
842
+ (0, call_signal_1.throwIfCallAborted)();
843
+ const batch = poolIds.slice(i, i + KoiosBackend.INFO_BATCH_SIZE);
844
+ const { data } = await this.api.post('/pool_info', { _pool_bech32_ids: batch });
845
+ if (!Array.isArray(data))
846
+ continue;
847
+ for (const row of data)
848
+ out.push(this._mapKoiosPool(row, ''));
849
+ }
850
+ return out;
851
+ }, this.name);
852
+ }
853
+ /** All DRep ids known to Koios (bech32). */
854
+ async getDrepIds() {
855
+ return (0, backend_request_handler_1.handleBackendRequest)(() => this.listAllIds('/drep_list', 'drep_id', 'getDrepIds'), this.name);
856
+ }
857
+ /** Resolve DRep ids in batches; unknown ids are omitted (see getPools). */
858
+ async getDreps(drepIds) {
859
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
860
+ const out = [];
861
+ for (let i = 0; i < drepIds.length; i += KoiosBackend.INFO_BATCH_SIZE) {
862
+ (0, call_signal_1.throwIfCallAborted)();
863
+ const batch = drepIds.slice(i, i + KoiosBackend.INFO_BATCH_SIZE);
864
+ const { data } = await this.api.post('/drep_info', { _drep_ids: batch });
865
+ if (!Array.isArray(data))
866
+ continue;
867
+ for (const row of data)
868
+ out.push(this._mapKoiosDrep(row));
869
+ }
870
+ return out;
871
+ }, this.name);
872
+ }
873
+ // All transactions of a block in order. /block_txs may answer flat rows or one `tx_hashes` array.
874
+ // An empty block needs no request. Only a block known to hold transactions is retried on [].
875
+ async getBlockTransactions(blockHash, txCount) {
953
876
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
877
+ if (txCount === 0)
878
+ return [];
879
+ // An empty answer for a block with transactions comes from an instance that lags; ask again.
954
880
  const rows = await this.fetchWithRetryOnEmpty(() => this.api.post('/block_txs', { _block_hashes: [blockHash] }), `getBlockTransactions(${blockHash})`);
955
881
  const hashes = [];
956
882
  for (const row of rows) {
@@ -959,14 +885,17 @@ class KoiosBackend {
959
885
  else if (row.tx_hash)
960
886
  hashes.push(row.tx_hash);
961
887
  }
888
+ // With the count known, a short list would store the block without some of its transactions.
889
+ if (txCount !== undefined && hashes.length !== txCount) {
890
+ throw new errors_1.ProviderUnavailableError(`Incomplete transaction list for block ${blockHash}: ${hashes.length}/${txCount} transaction(s)`, this.name);
891
+ }
962
892
  if (!hashes.length)
963
893
  return [];
964
894
  const byHash = await this.getTransactionsBatch(hashes);
965
895
  const missing = hashes.filter(h => !byHash.has(h));
966
896
  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.
897
+ // A partial /tx_info would lose the missing transactions for good.
898
+ // A 503 makes the crawler retry the whole block without storing it.
970
899
  throw new errors_1.ProviderUnavailableError(`Incomplete transaction data for block ${blockHash}: ${missing.length}/${hashes.length} transaction(s) missing`, this.name);
971
900
  }
972
901
  return hashes.map(h => byHash.get(h));
@@ -975,9 +904,7 @@ class KoiosBackend {
975
904
  //-----------------------------------------------------------------------------
976
905
  // Private Helpers
977
906
  //-----------------------------------------------------------------------------
978
- /**
979
- * Map a Koios /tx_info response object to the normalized Transaction type.
980
- */
907
+ /** Map a Koios /tx_info row to the normalized Transaction (ledger view, see ledgerView). */
981
908
  _mapKoiosTx(tx) {
982
909
  let labels = [];
983
910
  if (tx.metadata) {
@@ -987,67 +914,146 @@ class KoiosBackend {
987
914
  json: json,
988
915
  }));
989
916
  }
990
- return {
917
+ return (0, mappers_1.ledgerView)({
991
918
  hash: tx.tx_hash,
992
919
  blockHash: tx.block_hash,
993
920
  blockHeight: Number(tx.block_height),
994
921
  blockTime: tx.tx_timestamp ?? tx.block_time ?? 0,
995
922
  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'
923
+ // Koios spells these `tx_block_index` and `fee` (not `tx_index` / `tx_fee`)
999
924
  index: tx.tx_block_index ?? 0,
1000
925
  fee: tx.fee || '0',
1001
926
  deposit: tx.deposit || '0',
927
+ // undefined when Koios omits the field, so the indexer uses the input and output delta.
928
+ // [] would wrongly mean "no mint".
929
+ mint: Array.isArray(tx.assets_minted)
930
+ ? tx.assets_minted
931
+ .filter((a) => a?.policy_id && a.quantity != null)
932
+ .map((a) => ({
933
+ unit: `${a.policy_id}${a.asset_name ?? ''}`,
934
+ quantity: String(a.quantity),
935
+ }))
936
+ : undefined,
1002
937
  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
- };
938
+ // Phase-2 validity as db-sync records it; undefined on a Koios without the field, so the
939
+ // indexer keeps treating such a source as "no phase-2 information".
940
+ spendsCollaterals: typeof tx.valid_contract === 'boolean' ? tx.valid_contract === false : undefined,
941
+ // Koios lists inputs in its own order; ledgerView sorts them like the ledger
942
+ inputs: [
943
+ ...asKoiosList(tx.inputs).map((input) => mapKoiosInput(input)),
944
+ ...asKoiosList(tx.collateral_inputs).map((input) => mapKoiosInput(input, { isCollateral: true })),
945
+ ...asKoiosList(tx.reference_inputs).map((input) => mapKoiosInput(input, { isReference: true })),
946
+ ],
947
+ outputs: [
948
+ ...asKoiosList(tx.outputs).map((output) => mapKoiosOutput(tx.tx_hash, output, false)),
949
+ // CIP-40 collateral return: produced only when the script phase failed (ledgerView keeps it then)
950
+ ...asKoiosList(tx.collateral_output).map((output) => mapKoiosOutput(tx.tx_hash, output, true)),
951
+ ],
952
+ metadata: labels,
953
+ // undefined when the call did not ask for them. The indexer tells "none" from
954
+ // "not reported" by this.
955
+ certificates: Array.isArray(tx.certificates) ? mapKoiosCertificates(tx.certificates) : undefined,
956
+ withdrawals: Array.isArray(tx.withdrawals)
957
+ ? tx.withdrawals
958
+ .filter((w) => !!w.stake_addr)
959
+ .map((w) => ({ stakeAddress: String(w.stake_addr), amount: String(w.amount ?? '0') }))
960
+ : undefined,
961
+ });
1050
962
  }
1051
963
  }
1052
964
  exports.KoiosBackend = KoiosBackend;
965
+ // Koios sends `collateral_output` as one object although the spec says array.
966
+ // Its `asset_list` may be the JSON string "[]". This turns both into arrays.
967
+ function asKoiosList(v) {
968
+ if (Array.isArray(v))
969
+ return v;
970
+ if (typeof v === 'string') {
971
+ try {
972
+ const parsed = JSON.parse(v);
973
+ return Array.isArray(parsed) ? parsed : [];
974
+ }
975
+ catch {
976
+ return [];
977
+ }
978
+ }
979
+ return v && typeof v === 'object' ? [v] : [];
980
+ }
981
+ function koiosAmount(io) {
982
+ const amount = [{ unit: 'lovelace', quantity: io.value }];
983
+ for (const asset of asKoiosList(io.asset_list)) {
984
+ amount.push({ unit: `${asset.policy_id}${asset.asset_name}`, quantity: asset.quantity });
985
+ }
986
+ return amount;
987
+ }
988
+ function mapKoiosInput(input, flags = {}) {
989
+ return {
990
+ address: input.payment_addr?.bech32 || input.address || '',
991
+ txHash: input.tx_hash,
992
+ outputIndex: input.tx_index,
993
+ amount: koiosAmount(input),
994
+ dataHash: input.datum_hash || null,
995
+ inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(input.inline_datum),
996
+ referenceScriptHash: koiosRefScriptHash(input.reference_script),
997
+ referenceScriptSize: koiosRefScriptMeta(input.reference_script).size,
998
+ referenceScriptType: koiosRefScriptMeta(input.reference_script).type,
999
+ ...flags,
1000
+ };
1001
+ }
1002
+ function mapKoiosOutput(txHash, output, isCollateral) {
1003
+ return {
1004
+ address: output.payment_addr?.bech32 || output.address || '',
1005
+ amount: koiosAmount(output),
1006
+ txHash,
1007
+ outputIndex: output.tx_index,
1008
+ dataHash: output.datum_hash || null,
1009
+ inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(output.inline_datum),
1010
+ isCollateral,
1011
+ referenceScriptHash: koiosRefScriptHash(output.reference_script),
1012
+ referenceScriptSize: koiosRefScriptMeta(output.reference_script).size,
1013
+ referenceScriptType: koiosRefScriptMeta(output.reference_script).type,
1014
+ };
1015
+ }
1016
+ /** Koios certificate `type` → shared `CertificateKind`; anything else passes through raw. */
1017
+ const KOIOS_CERT_KINDS = {
1018
+ stake_registration: 'stake_registration',
1019
+ stake_deregistration: 'stake_deregistration',
1020
+ pool_delegation: 'pool_delegation',
1021
+ // older Koios releases named the pool delegation plainly
1022
+ delegation: 'pool_delegation',
1023
+ vote_delegation: 'vote_delegation',
1024
+ pool_update: 'pool_registration',
1025
+ pool_retire: 'pool_retirement',
1026
+ drep_registration: 'drep_registration',
1027
+ drep_update: 'drep_update',
1028
+ drep_retire: 'drep_retirement',
1029
+ drep_deregistration: 'drep_retirement',
1030
+ committee_hot_auth: 'committee_hot_auth',
1031
+ committee_resign: 'committee_resign',
1032
+ treasury_MIR: 'treasury_mir',
1033
+ reserve_MIR: 'reserve_mir',
1034
+ pot_transfer: 'pot_transfer',
1035
+ param_proposal: 'param_proposal',
1036
+ };
1037
+ // Normalize Koios `/tx_info` certificates. Field names inside `info` vary by type and
1038
+ // version, for example `retiring epoch` with a space, so every alias is read.
1039
+ function mapKoiosCertificates(certs) {
1040
+ const str = (v) => (typeof v === 'string' && v.length ? v : null);
1041
+ const num = (v) => {
1042
+ const n = typeof v === 'string' ? Number(v) : v;
1043
+ return typeof n === 'number' && Number.isFinite(n) ? n : null;
1044
+ };
1045
+ return certs.map((c, position) => {
1046
+ const info = c.info ?? {};
1047
+ const deposit = info.deposit;
1048
+ return {
1049
+ certIndex: num(c.index) ?? position,
1050
+ kind: (c.type && KOIOS_CERT_KINDS[c.type]) || c.type || 'other',
1051
+ stakeAddress: str(info.stake_address) ?? str(info.stake_addr),
1052
+ poolId: str(info.pool_id_bech32) ?? str(info.pool),
1053
+ drepId: str(info.drep_id),
1054
+ deposit: deposit != null && deposit !== '' ? String(deposit) : null,
1055
+ epoch: num(info.retiring_epoch) ?? num(info['retiring epoch']),
1056
+ };
1057
+ });
1058
+ }
1053
1059
  //# sourceMappingURL=koios-backend.js.map