@odatano/core 2.0.0-rc.50 → 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 (151) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +14 -3
  2. package/@cds-models/CardanoBackendService/index.js +1 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +98 -0
  4. package/@cds-models/CardanoIndexerService/index.js +10 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +3 -0
  6. package/@cds-models/CardanoSignService/index.d.ts +13 -0
  7. package/@cds-models/CardanoSignService/index.js +1 -0
  8. package/@cds-models/CardanoTransactionService/index.d.ts +12 -0
  9. package/@cds-models/CardanoTransactionService/index.js +1 -0
  10. package/@cds-models/CardanoWorkerService/index.d.ts +28 -0
  11. package/@cds-models/CardanoWorkerService/index.js +2 -0
  12. package/@cds-models/index.d.ts +13 -3
  13. package/@cds-models/index.js +4 -3
  14. package/@cds-models/odatano/cardano/index.d.ts +14 -0
  15. package/README.md +45 -149
  16. package/db/schema.cds +63 -10
  17. package/db/types.cds +10 -0
  18. package/package.json +7 -44
  19. package/scripts/deploy-schema.mjs +113 -0
  20. package/scripts/migrate-schema.mjs +209 -15
  21. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -4
  22. package/srv/blockchain/backends/blockfrost-backend.js +61 -45
  23. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  24. package/srv/blockchain/backends/call-signal.js +22 -0
  25. package/srv/blockchain/backends/cardano-backend.d.ts +6 -3
  26. package/srv/blockchain/backends/koios-backend.d.ts +9 -6
  27. package/srv/blockchain/backends/koios-backend.js +145 -207
  28. package/srv/blockchain/backends/odatano-backend.d.ts +2 -1
  29. package/srv/blockchain/backends/odatano-backend.js +51 -9
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +1 -2
  31. package/srv/blockchain/backends/ogmios-backend.js +82 -48
  32. package/srv/blockchain/cardano-client.d.ts +15 -5
  33. package/srv/blockchain/cardano-client.js +143 -71
  34. package/srv/blockchain/cardano-indexer.d.ts +27 -16
  35. package/srv/blockchain/cardano-indexer.js +223 -102
  36. package/srv/blockchain/circuit-breaker.d.ts +1 -0
  37. package/srv/blockchain/circuit-breaker.js +6 -0
  38. package/srv/blockchain/crawler/account-snapshots.js +22 -2
  39. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +2 -0
  40. package/srv/blockchain/crawler/asset-decimals-backfill.js +29 -29
  41. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +3 -0
  42. package/srv/blockchain/crawler/asset-registry-backfill.js +4 -0
  43. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  44. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  45. package/srv/blockchain/crawler/certificate-backfill.d.ts +4 -0
  46. package/srv/blockchain/crawler/certificate-backfill.js +15 -3
  47. package/srv/blockchain/crawler/crawler.d.ts +22 -1
  48. package/srv/blockchain/crawler/crawler.js +223 -24
  49. package/srv/blockchain/crawler/credential-backfill.d.ts +2 -0
  50. package/srv/blockchain/crawler/credential-backfill.js +43 -66
  51. package/srv/blockchain/crawler/input-asset-copies.d.ts +4 -4
  52. package/srv/blockchain/crawler/input-asset-copies.js +17 -27
  53. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  54. package/srv/blockchain/crawler/key-pages.js +48 -0
  55. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +6 -0
  56. package/srv/blockchain/crawler/metadata-position-backfill.js +23 -19
  57. package/srv/blockchain/crawler/output-datum-backfill.d.ts +3 -1
  58. package/srv/blockchain/crawler/output-datum-backfill.js +8 -18
  59. package/srv/blockchain/crawler/sync-state.d.ts +5 -1
  60. package/srv/blockchain/crawler/sync-state.js +63 -106
  61. package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
  62. package/srv/blockchain/crawler/transaction-backfill.js +6 -13
  63. package/srv/blockchain/crawler/utxo-set-import.js +2 -2
  64. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  65. package/srv/blockchain/crawler/window-plan.js +59 -0
  66. package/srv/blockchain/ledger-state.d.ts +2 -2
  67. package/srv/blockchain/ledger-state.js +139 -37
  68. package/srv/blockchain/signing/external-signer.js +5 -5
  69. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  70. package/srv/blockchain/signing/failed-recheck.js +135 -0
  71. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  72. package/srv/blockchain/signing/landing-proof.js +224 -0
  73. package/srv/blockchain/signing/signature-verifier.js +10 -13
  74. package/srv/blockchain/signing/submission-finalizer.d.ts +17 -3
  75. package/srv/blockchain/signing/submission-finalizer.js +90 -29
  76. package/srv/blockchain/stored-chain.d.ts +1 -2
  77. package/srv/blockchain/stored-chain.js +36 -15
  78. package/srv/blockchain/transaction-building/buildooor-tx.js +16 -10
  79. package/srv/blockchain/transaction-presence.d.ts +8 -1
  80. package/srv/blockchain/transaction-presence.js +12 -12
  81. package/srv/blockchain/wallet-worker/build-request.d.ts +6 -6
  82. package/srv/blockchain/wallet-worker/build-request.js +35 -365
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +23 -2
  84. package/srv/blockchain/wallet-worker/confirmation-tracker.js +140 -23
  85. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  86. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  87. package/srv/blockchain/wallet-worker/job-store.d.ts +28 -2
  88. package/srv/blockchain/wallet-worker/job-store.js +107 -80
  89. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +21 -2
  90. package/srv/blockchain/wallet-worker/wallet-worker.js +241 -57
  91. package/srv/cardano-agent-service.cds +1 -1
  92. package/srv/cardano-agent-service.js +8 -0
  93. package/srv/cardano-backend-service.cds +4 -1
  94. package/srv/cardano-backend-service.js +26 -9
  95. package/srv/cardano-indexer-service.cds +448 -387
  96. package/srv/cardano-indexer-service.js +226 -281
  97. package/srv/cardano-service.cds +7 -5
  98. package/srv/cardano-service.js +404 -69
  99. package/srv/cardano-sign-service.cds +11 -1
  100. package/srv/cardano-sign-service.js +161 -108
  101. package/srv/cardano-tx-service.cds +15 -4
  102. package/srv/cardano-tx-service.js +105 -604
  103. package/srv/cardano-worker-service.cds +25 -2
  104. package/srv/cardano-worker-service.js +56 -4
  105. package/srv/config.d.ts +4 -0
  106. package/srv/config.js +10 -0
  107. package/srv/server.js +5 -7
  108. package/srv/utils/agent-access.d.ts +4 -2
  109. package/srv/utils/agent-access.js +26 -7
  110. package/srv/utils/agent-grants.d.ts +1 -1
  111. package/srv/utils/agent-grants.js +7 -8
  112. package/srv/utils/agent-token-auth.js +45 -5
  113. package/srv/utils/build-request.d.ts +52 -0
  114. package/srv/utils/build-request.js +487 -0
  115. package/srv/utils/collections.d.ts +1 -0
  116. package/srv/utils/collections.js +11 -0
  117. package/srv/utils/const.d.ts +10 -2
  118. package/srv/utils/const.js +13 -6
  119. package/srv/utils/crypto.js +5 -4
  120. package/srv/utils/db-indexes.d.ts +5 -1
  121. package/srv/utils/db-indexes.js +79 -14
  122. package/srv/utils/db-kind.d.ts +23 -0
  123. package/srv/utils/db-kind.js +42 -0
  124. package/srv/utils/detached-run.d.ts +41 -0
  125. package/srv/utils/detached-run.js +101 -0
  126. package/srv/utils/epoch-slots.d.ts +1 -0
  127. package/srv/utils/epoch-slots.js +7 -0
  128. package/srv/utils/error-codes.d.ts +4 -0
  129. package/srv/utils/error-codes.js +4 -0
  130. package/srv/utils/errors.d.ts +10 -1
  131. package/srv/utils/errors.js +51 -9
  132. package/srv/utils/lease.d.ts +20 -0
  133. package/srv/utils/lease.js +62 -0
  134. package/srv/utils/mappers.d.ts +9 -0
  135. package/srv/utils/mappers.js +57 -67
  136. package/srv/utils/navigation.d.ts +17 -0
  137. package/srv/utils/navigation.js +52 -0
  138. package/srv/utils/network-context.d.ts +0 -1
  139. package/srv/utils/network-context.js +8 -3
  140. package/srv/utils/pg-inline-json.js +3 -3
  141. package/srv/utils/pg-order-nulls.js +3 -3
  142. package/srv/utils/resolution.d.ts +13 -0
  143. package/srv/utils/resolution.js +47 -0
  144. package/srv/utils/row-values.d.ts +7 -0
  145. package/srv/utils/row-values.js +27 -0
  146. package/srv/utils/tx-build-helper.d.ts +15 -0
  147. package/srv/utils/tx-build-helper.js +28 -13
  148. package/srv/utils/types.d.ts +35 -43
  149. package/srv/utils/types.js +1 -17
  150. package/srv/utils/validators.d.ts +2 -2
  151. package/srv/utils/validators.js +14 -25
@@ -69,16 +69,19 @@ export declare class KoiosBackend implements CardanoBackend, PaginatingBackend,
69
69
  init(): Promise<boolean>;
70
70
  /** Retry with backoff when Koios briefly returns [] for a valid query. */
71
71
  private fetchWithRetryOnEmpty;
72
- private getWithRetryOn42804;
72
+ private allRows;
73
73
  getTransaction(hash: string): Promise<Transaction>;
74
74
  getBlock(blockHash: string): Promise<BlockData>;
75
75
  getEpoch(epochNumber: number): Promise<EpochData>;
76
76
  /** Address data. Transactions come from getAddressTransactions(). */
77
77
  getAddress(address: string): Promise<Address>;
78
78
  getAddressTransactions(address: string, limit: number): Promise<Transaction[]>;
79
+ /** Every UTxO of an address, paged past the 1000-row cap of a Koios answer. */
79
80
  getAddressUtxos(address: string): Promise<UTxO[]>;
80
- /** UTxOs of every address with this payment credential (56 hex chars). */
81
+ /** Every UTxO of every address with this payment credential (56 hex chars), paged. */
81
82
  getCredentialUtxos(credHash: string): Promise<UTxO[]>;
83
+ /** The newest `limit` transactions of an address, ordered by Koios before it cuts the list. */
84
+ private newestAddressTxs;
82
85
  getNetworkInformation(): Promise<NetworkInformation>;
83
86
  getTransactionMetadata(tx_hash: string): Promise<MetadataLabelTx[]>;
84
87
  getPool(poolId: string): Promise<PoolData>;
@@ -88,7 +91,6 @@ export declare class KoiosBackend implements CardanoBackend, PaginatingBackend,
88
91
  getAssetInfo(unit: string): Promise<AssetInfo>;
89
92
  getAssetHistory(unit: string, limit?: number): Promise<AssetHistoryEntry[]>;
90
93
  getDrep(drepId: string): Promise<DrepData>;
91
- /** Map one Koios /drep_info row to the canonical DrepData. */
92
94
  private _mapKoiosDrep;
93
95
  getAccount(accountId: string): Promise<AccountData>;
94
96
  submitTransaction(signedTxCbor: string): Promise<string>;
@@ -118,8 +120,10 @@ export declare class KoiosBackend implements CardanoBackend, PaginatingBackend,
118
120
  private static readonly INFO_BATCH_SIZE;
119
121
  /** Page cap. 500 pages hold 500 000 ids, far beyond any real pool or DRep set. */
120
122
  private static readonly LIST_MAX_PAGES;
121
- /** Pages through a PostgREST list endpoint for one id column. Stops on the first short page. */
123
+ /** Every value of one id column of a list endpoint, in the order of that column. */
122
124
  private listAllIds;
125
+ /** Rows of a GET list endpoint with only the `select` columns, paged. */
126
+ private allRowsOf;
123
127
  /** Units with a CIP-26 registry entry, from `asset_token_registry` (the whole registry, paged). */
124
128
  getTokenRegistryUnits(): Promise<string[]>;
125
129
  /** All pool ids, including retired ones, so a snapshot does not drop retiring pools. */
@@ -130,8 +134,7 @@ export declare class KoiosBackend implements CardanoBackend, PaginatingBackend,
130
134
  getDrepIds(): Promise<string[]>;
131
135
  /** Resolve DRep ids in batches; unknown ids are omitted (see getPools). */
132
136
  getDreps(drepIds: string[]): Promise<DrepData[]>;
133
- /** All transactions of a block in order. /block_txs may answer flat rows or one `tx_hashes` array. */
134
- getBlockTransactions(blockHash: string): Promise<Transaction[]>;
137
+ getBlockTransactions(blockHash: string, txCount?: number): Promise<Transaction[]>;
135
138
  /** Map a Koios /tx_info row to the normalized Transaction (ledger view, see ledgerView). */
136
139
  private _mapKoiosTx;
137
140
  }
@@ -15,24 +15,30 @@ const const_1 = require("../../utils/const");
15
15
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
16
16
  const logger = cds_1.default.log('KoiosBackend');
17
17
  const reference_script_1 = require("../../utils/reference-script");
18
+ const call_signal_1 = require("./call-signal");
19
+ const const_2 = require("../../utils/const");
18
20
  /** Bounded retries for instance-specific PostgREST server errors (42703, 57014, …). */
19
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;
20
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
+ }
21
30
  const KOIOS_URLS = {
22
31
  mainnet: 'https://api.koios.rest/api/v1',
23
32
  preview: 'https://preview.koios.rest/api/v1',
24
33
  preprod: 'https://preprod.koios.rest/api/v1',
25
34
  };
26
- /** Script CBOR from a Koios `reference_script` object, else its hash. Local Plutus eval needs the CBOR. */
35
+ /** Script CBOR of a Koios `reference_script` object; null for the bare-hash form. */
27
36
  function koiosRefScriptBytes(ref) {
28
- if (!ref)
37
+ if (!ref || typeof ref !== 'object')
29
38
  return null;
30
- if (typeof ref === 'string')
31
- return ref;
32
- const obj = ref;
33
- return obj.bytes || obj.hash || null;
39
+ return ref.bytes || null;
34
40
  }
35
- /** 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. */
36
42
  function koiosRefScriptHash(ref) {
37
43
  if (!ref)
38
44
  return null;
@@ -49,32 +55,25 @@ function koiosRefScriptMeta(ref) {
49
55
  const size = Number(obj.size);
50
56
  return { size: Number.isInteger(size) && size > 0 ? size : null, type: (0, reference_script_1.normalizeScriptType)(obj.type) };
51
57
  }
52
- /** Sort Koios /address_txs rows newest first. Koios gives no ordering guarantee. */
53
- function sortAddressTxsDesc(rows) {
54
- return [...rows].sort((a, b) => Number(b.block_height ?? b.block_time ?? 0) - Number(a.block_height ?? a.block_time ?? 0));
55
- }
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);
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 });
72
63
  }
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);
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
+ };
78
77
  }
79
78
  /** CardanoBackend implementation on the Koios REST API (Axios). */
80
79
  class KoiosBackend {
@@ -92,19 +91,27 @@ class KoiosBackend {
92
91
  headers,
93
92
  });
94
93
  this.network = network;
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.
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.
98
102
  this.api.interceptors.response.use(undefined, async (error) => {
99
103
  const config = error.config;
100
- const pgCode = error.response?.data?.code;
101
- 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)))
102
107
  throw error;
103
108
  const attempt = (config.pgRetryCount ?? 0) + 1;
104
- 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)
105
111
  throw error;
106
112
  config.pgRetryCount = attempt;
107
- 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}`);
108
115
  await new Promise(resolve => setTimeout(resolve, PG_SERVER_ERROR_RETRY_DELAY_MS * attempt));
109
116
  return this.api.request(config);
110
117
  });
@@ -138,27 +145,23 @@ class KoiosBackend {
138
145
  }
139
146
  return [];
140
147
  }
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.
143
- async getWithRetryOn42804(url, config, label) {
144
- const maxRetries = 8;
145
- const baseDelayMs = 300;
146
- for (let attempt = 0;; attempt++) {
147
- try {
148
- return await this.api.get(url, config);
149
- }
150
- catch (err) {
151
- const e = err;
152
- const isSkew = e?.response?.status === 400 &&
153
- (e.response.data?.code === '42804' ||
154
- /structure of query does not match function result type/i.test(e.response.data?.message ?? ''));
155
- if (!isSkew || attempt >= maxRetries)
156
- throw err;
157
- const delay = baseDelayMs * (attempt + 1);
158
- logger.warn(`${label}: Koios transient 42804 (grest version skew), retry ${attempt + 1}/${maxRetries} after ${delay}ms...`);
159
- await new Promise(r => setTimeout(r, delay));
160
- }
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;
161
163
  }
164
+ throw new errors_1.ProviderUnavailableError(`${label}: more than ${KoiosBackend.LIST_MAX_PAGES} pages, the list is not complete`, this.name);
162
165
  }
163
166
  async getTransaction(hash) {
164
167
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
@@ -192,7 +195,7 @@ class KoiosBackend {
192
195
  }
193
196
  async getEpoch(epochNumber) {
194
197
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
195
- 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})`);
196
199
  if (!results || results.length === 0) {
197
200
  throw new errors_1.NotFoundError('Epoch', this.name);
198
201
  }
@@ -220,7 +223,7 @@ class KoiosBackend {
220
223
  }
221
224
  const addressData = data[0];
222
225
  const addressUtxos = await this.getAddressUtxos(address);
223
- // Sum balances from the mapped UTxOs; address_info's utxo_set may carry a null asset_list.
226
+ // Sum the balance over every UTxO; address_info's utxo_set may carry a null asset_list.
224
227
  const totals = new Map();
225
228
  for (const u of addressUtxos) {
226
229
  for (const a of u.amount) {
@@ -244,9 +247,7 @@ class KoiosBackend {
244
247
  }
245
248
  async getAddressTransactions(address, limit) {
246
249
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
247
- const { data: addressTxs } = await this.api.post('/address_txs', { _addresses: [address] });
248
- // newest first, THEN limit (saves API calls); batch instead of unbounded Promise.all
249
- const limitedTxs = sortAddressTxsDesc(addressTxs).slice(0, limit);
250
+ const limitedTxs = await this.newestAddressTxs(address, limit);
250
251
  const batch = await this.getTransactionsBatch(limitedTxs.map(tx => tx.tx_hash));
251
252
  const transactions = [];
252
253
  for (const tx of limitedTxs) {
@@ -257,72 +258,30 @@ class KoiosBackend {
257
258
  return transactions;
258
259
  }, this.name);
259
260
  }
261
+ /** Every UTxO of an address, paged past the 1000-row cap of a Koios answer. */
260
262
  async getAddressUtxos(address) {
261
263
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
262
- const { data } = await this.api.post('/address_utxos', { _addresses: [address], _extended: true });
263
- return data.map((utxo) => {
264
- const amount = [
265
- { unit: 'lovelace', quantity: utxo.value }
266
- ];
267
- // add native asset(s) if present
268
- if (utxo.asset_list && Array.isArray(utxo.asset_list)) {
269
- for (const asset of utxo.asset_list) {
270
- amount.push({
271
- unit: `${asset.policy_id}${asset.asset_name}`,
272
- quantity: asset.quantity
273
- });
274
- }
275
- }
276
- return {
277
- txHash: utxo.tx_hash,
278
- outputIndex: utxo.tx_index,
279
- address: address,
280
- amount: amount,
281
- datumHash: utxo.datum_hash || null,
282
- scriptRef: koiosRefScriptBytes(utxo.reference_script),
283
- scriptRefSize: koiosRefScriptMeta(utxo.reference_script).size,
284
- scriptRefType: koiosRefScriptMeta(utxo.reference_script).type,
285
- inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(utxo.inline_datum),
286
- };
287
- });
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));
288
266
  }, this.name);
289
267
  }
290
- /** UTxOs of every address with this payment credential (56 hex chars). */
268
+ /** Every UTxO of every address with this payment credential (56 hex chars), paged. */
291
269
  async getCredentialUtxos(credHash) {
292
270
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
293
- const { data } = await this.api.post('/credential_utxos', {
294
- _payment_credentials: [credHash],
295
- _extended: true,
296
- });
297
- return data.map((utxo) => {
298
- const amount = [
299
- { unit: 'lovelace', quantity: utxo.value }
300
- ];
301
- if (utxo.asset_list && Array.isArray(utxo.asset_list)) {
302
- for (const asset of utxo.asset_list) {
303
- amount.push({
304
- unit: `${asset.policy_id}${asset.asset_name}`,
305
- quantity: asset.quantity
306
- });
307
- }
308
- }
309
- return {
310
- txHash: utxo.tx_hash,
311
- outputIndex: utxo.tx_index,
312
- address: utxo.address ?? '',
313
- amount: amount,
314
- datumHash: utxo.datum_hash || null,
315
- scriptRef: koiosRefScriptBytes(utxo.reference_script),
316
- scriptRefSize: koiosRefScriptMeta(utxo.reference_script).size,
317
- scriptRefType: koiosRefScriptMeta(utxo.reference_script).type,
318
- inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(utxo.inline_datum),
319
- };
320
- });
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 ?? ''));
321
273
  }, this.name);
322
274
  }
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
+ }
323
282
  async getNetworkInformation() {
324
283
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
325
- // /totals works on mainnet but returns [] on preview/preprod
284
+ // /totals has no locked supply and no stake; those stay null
326
285
  const { data: totalsData } = await this.api.get('/totals', {
327
286
  params: { order: 'epoch_no.desc', limit: 1 }
328
287
  });
@@ -331,38 +290,30 @@ class KoiosBackend {
331
290
  return {
332
291
  supply: {
333
292
  max: const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY,
334
- total: latest.supply || '0',
335
- circulating: latest.circulation || '0',
336
- locked: '0', // Not available in /totals
337
- treasury: latest.treasury || '0',
338
- reserves: latest.reserves || '0',
339
- },
340
- stake: {
341
- live: '0',
342
- 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,
343
298
  },
299
+ stake: { live: null, active: null },
344
300
  };
345
301
  }
346
- // Testnet fallback: max supply from /genesis, remaining fields '0'
302
+ // Without /totals rows only the maximum supply is known, from /genesis.
347
303
  const { data: genesisData } = await this.api.get('/genesis');
348
304
  if (!genesisData || !Array.isArray(genesisData) || genesisData.length === 0) {
349
305
  throw new errors_1.NotFoundError('Genesis', this.name);
350
306
  }
351
- const genesis = genesisData[0];
352
- const maxSupply = genesis.maxlovelacesupply || const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY;
353
307
  return {
354
308
  supply: {
355
- max: maxSupply,
356
- total: maxSupply,
357
- circulating: maxSupply,
358
- locked: '0',
359
- treasury: '0',
360
- reserves: '0',
361
- },
362
- stake: {
363
- live: '0',
364
- 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,
365
315
  },
316
+ stake: { live: null, active: null },
366
317
  };
367
318
  }, this.name);
368
319
  }
@@ -475,7 +426,8 @@ class KoiosBackend {
475
426
  unit,
476
427
  policyId,
477
428
  assetNameHex,
478
- 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),
479
431
  fingerprint: a.fingerprint,
480
432
  totalSupply: a.total_supply ?? '0',
481
433
  mintOrBurnCount: mintCnt + burnCnt,
@@ -538,21 +490,24 @@ class KoiosBackend {
538
490
  return this._mapKoiosDrep(data[0]);
539
491
  }, this.name);
540
492
  }
541
- /** Map one Koios /drep_info row to the canonical DrepData. */
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.
542
496
  _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';
497
+ const retired = drepData.retired ?? drepData.drep_status === 'deregistered';
546
498
  const expired = drepData.expired ?? (drepData.active === false && !retired);
547
499
  return {
548
500
  drepId: drepData.drep_id,
549
501
  hex: drepData.hex,
550
502
  amount: drepData.amount,
551
503
  hasScript: drepData.has_script,
552
- // The newer schema has no last-activity epoch, and `expires_epoch_no` means something else.
504
+ // Koios has no last-activity epoch
553
505
  lastActiveEpoch: drepData.last_active_epoch ?? 0,
554
506
  expired,
555
507
  retired,
508
+ deposit: drepData.deposit ?? null,
509
+ expiresEpoch: drepData.expires_epoch_no ?? null,
510
+ delegatorCount: drepData.live_delegator_count ?? null,
556
511
  };
557
512
  }
558
513
  async getAccount(accountId) {
@@ -564,16 +519,10 @@ class KoiosBackend {
564
519
  if (!Array.isArray(data) || data.length === 0) {
565
520
  throw new errors_1.NotFoundError('Account', this.name);
566
521
  }
567
- const addressDataResponse = await this.api.post('/account_addresses', body);
568
- // Koios returns [{ stake_address, addresses: [...] }], flatten to get all addresses
569
- const addressesFlat = addressDataResponse.data.flatMap((item) => item.addresses);
570
- const addresses = [];
571
- const concurrent = 10;
572
- for (let i = 0; i < addressesFlat.length; i += concurrent) {
573
- const chunk = addressesFlat.slice(i, i + concurrent);
574
- const chunkResults = await Promise.all(chunk.map((addr) => this.getAddress(addr)));
575
- addresses.push(...chunkResults);
576
- }
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 ?? []);
577
526
  const accountData = data[0];
578
527
  return {
579
528
  stakeaddress: accountData.stake_address,
@@ -608,12 +557,7 @@ class KoiosBackend {
608
557
  // 400 carries the node's rejection (e.g. ExtraneousScriptWitnessesUTXOW); keep it
609
558
  const response = err.response;
610
559
  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);
560
+ throw (0, errors_1.submitRejection)((0, errors_1.nodeRejectionReason)(response.data), this.name, err);
617
561
  }
618
562
  throw err;
619
563
  }
@@ -694,8 +638,10 @@ class KoiosBackend {
694
638
  try {
695
639
  return await this.getEpoch(epochNo);
696
640
  }
697
- catch {
698
- // Koios may not have the current epoch yet, so use the previous one
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;
699
645
  return await this.getEpoch(epochNo - 1);
700
646
  }
701
647
  }, this.name);
@@ -734,10 +680,7 @@ class KoiosBackend {
734
680
  /** Most recent tx hashes of an address, without tx details. */
735
681
  async getAddressTransactionHashes(address, limit) {
736
682
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
737
- const { data } = await this.api.post('/address_txs', { _addresses: [address] });
738
- return sortAddressTxsDesc(data)
739
- .slice(0, limit)
740
- .map(tx => tx.tx_hash);
683
+ return (await this.newestAddressTxs(address, limit)).map(tx => tx.tx_hash);
741
684
  }, this.name);
742
685
  }
743
686
  /** crawler.certificates: ask /tx_info for certificates + withdrawals on the crawl's batch call. */
@@ -751,6 +694,7 @@ class KoiosBackend {
751
694
  const BATCH_SIZE = 100;
752
695
  const result = new Map();
753
696
  for (let i = 0; i < txHashes.length; i += BATCH_SIZE) {
697
+ (0, call_signal_1.throwIfCallAborted)();
754
698
  const chunk = txHashes.slice(i, i + BATCH_SIZE);
755
699
  const { data } = await this.api.post('/tx_info', {
756
700
  _tx_hashes: chunk,
@@ -793,6 +737,7 @@ class KoiosBackend {
793
737
  size: data.block_size,
794
738
  txCount: data.tx_count,
795
739
  fees: data.total_fees,
740
+ previousHash: data.parent_hash,
796
741
  };
797
742
  }
798
743
  /** Finds the block in the filtered /blocks list, then reads it from /block_info. */
@@ -831,7 +776,9 @@ class KoiosBackend {
831
776
  }
832
777
  anchorHeight = info[0].block_height;
833
778
  }
834
- 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 : [];
835
782
  if (!rows.length)
836
783
  return [];
837
784
  const requestedHashes = rows.map((r) => r.hash);
@@ -858,47 +805,28 @@ class KoiosBackend {
858
805
  static INFO_BATCH_SIZE = 50;
859
806
  /** Page cap. 500 pages hold 500 000 ids, far beyond any real pool or DRep set. */
860
807
  static LIST_MAX_PAGES = 500;
861
- /** Pages through a PostgREST list endpoint for one id column. Stops on the first short page. */
808
+ /** Every value of one id column of a list endpoint, in the order of that column. */
862
809
  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;
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);
879
816
  }
880
817
  /** Units with a CIP-26 registry entry, from `asset_token_registry` (the whole registry, paged). */
881
818
  async getTokenRegistryUnits() {
882
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');
883
821
  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;
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());
900
829
  }
901
- logger.warn(`getTokenRegistryUnits: stopped after ${KoiosBackend.LIST_MAX_PAGES} pages, the list may be truncated`);
902
830
  return units;
903
831
  }, this.name);
904
832
  }
@@ -911,6 +839,7 @@ class KoiosBackend {
911
839
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
912
840
  const out = [];
913
841
  for (let i = 0; i < poolIds.length; i += KoiosBackend.INFO_BATCH_SIZE) {
842
+ (0, call_signal_1.throwIfCallAborted)();
914
843
  const batch = poolIds.slice(i, i + KoiosBackend.INFO_BATCH_SIZE);
915
844
  const { data } = await this.api.post('/pool_info', { _pool_bech32_ids: batch });
916
845
  if (!Array.isArray(data))
@@ -930,6 +859,7 @@ class KoiosBackend {
930
859
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
931
860
  const out = [];
932
861
  for (let i = 0; i < drepIds.length; i += KoiosBackend.INFO_BATCH_SIZE) {
862
+ (0, call_signal_1.throwIfCallAborted)();
933
863
  const batch = drepIds.slice(i, i + KoiosBackend.INFO_BATCH_SIZE);
934
864
  const { data } = await this.api.post('/drep_info', { _drep_ids: batch });
935
865
  if (!Array.isArray(data))
@@ -940,9 +870,13 @@ class KoiosBackend {
940
870
  return out;
941
871
  }, this.name);
942
872
  }
943
- /** All transactions of a block in order. /block_txs may answer flat rows or one `tx_hashes` array. */
944
- async getBlockTransactions(blockHash) {
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) {
945
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.
946
880
  const rows = await this.fetchWithRetryOnEmpty(() => this.api.post('/block_txs', { _block_hashes: [blockHash] }), `getBlockTransactions(${blockHash})`);
947
881
  const hashes = [];
948
882
  for (const row of rows) {
@@ -951,6 +885,10 @@ class KoiosBackend {
951
885
  else if (row.tx_hash)
952
886
  hashes.push(row.tx_hash);
953
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
+ }
954
892
  if (!hashes.length)
955
893
  return [];
956
894
  const byHash = await this.getTransactionsBatch(hashes);
@@ -34,6 +34,7 @@ export declare class OdatanoBackend implements CardanoBackend, EvaluatingBackend
34
34
  getPool(poolId: string): Promise<PoolData>;
35
35
  getDrep(drepId: string): Promise<DrepData>;
36
36
  getAccount(stakeAddress: string): Promise<AccountData>;
37
+ isRewardAccountRegistered(stakeAddress: string): Promise<boolean | null>;
37
38
  getAssetInfo(unit: string): Promise<AssetInfo>;
38
39
  getAssetHistory(unit: string, limit?: number): Promise<AssetHistoryEntry[]>;
39
40
  getProtocolParameters(): Promise<LedgerProtocolParameters>;
@@ -41,7 +42,7 @@ export declare class OdatanoBackend implements CardanoBackend, EvaluatingBackend
41
42
  evaluateTransaction(unsignedTxCbor: string): Promise<ScriptEvaluationResult[]>;
42
43
  getBlockByHeight(height: number): Promise<BlockData>;
43
44
  getNextBlocks(afterHash: string, count: number, afterHeight?: number): Promise<BlockData[]>;
44
- getBlockTransactions(blockHash: string): Promise<Transaction[]>;
45
+ getBlockTransactions(blockHash: string, txCount?: number): Promise<Transaction[]>;
45
46
  getPoolIds(): Promise<string[]>;
46
47
  getPools(poolIds: string[]): Promise<PoolData[]>;
47
48
  getDrepIds(): Promise<string[]>;