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

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