@odatano/core 2.0.0-rc.43 → 2.0.0-rc.45

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 (171) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +0 -46
  2. package/@cds-models/CardanoBackendService/index.d.ts +0 -10
  3. package/@cds-models/CardanoIndexerService/index.d.ts +36 -20
  4. package/@cds-models/CardanoIndexerService/index.js +4 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +19 -47
  6. package/@cds-models/CardanoSignService/index.d.ts +3 -18
  7. package/@cds-models/CardanoTransactionService/index.d.ts +9 -31
  8. package/@cds-models/CardanoWorkerService/index.d.ts +3 -19
  9. package/@cds-models/index.d.ts +17 -0
  10. package/@cds-models/index.js +2 -0
  11. package/@cds-models/odatano/cardano/index.d.ts +1 -34
  12. package/README.md +6 -6
  13. package/db/schema.cds +29 -44
  14. package/db/types.cds +22 -5
  15. package/package.json +3 -1
  16. package/scripts/migrate-slot-leader.mjs +3 -11
  17. package/scripts/migrate-txseq.mjs +3 -12
  18. package/src/index.d.ts +0 -4
  19. package/src/index.js +3 -5
  20. package/src/plugin.js +4 -8
  21. package/srv/blockchain/asset-decimals.d.ts +7 -0
  22. package/srv/blockchain/asset-decimals.js +91 -0
  23. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -10
  24. package/srv/blockchain/backends/blockfrost-backend.js +15 -21
  25. package/srv/blockchain/backends/cardano-backend.d.ts +12 -71
  26. package/srv/blockchain/backends/koios-backend.d.ts +14 -147
  27. package/srv/blockchain/backends/koios-backend.js +40 -164
  28. package/srv/blockchain/backends/odatano-backend.d.ts +1 -11
  29. package/srv/blockchain/backends/odatano-backend.js +11 -12
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +13 -160
  31. package/srv/blockchain/backends/ogmios-backend.js +48 -175
  32. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +2 -18
  33. package/srv/blockchain/backends/ogmios-frame-guard.js +8 -20
  34. package/srv/blockchain/cardano-client.d.ts +12 -80
  35. package/srv/blockchain/cardano-client.js +36 -88
  36. package/srv/blockchain/cardano-indexer.d.ts +12 -192
  37. package/srv/blockchain/cardano-indexer.js +132 -222
  38. package/srv/blockchain/cardano-tx-builder.d.ts +1 -28
  39. package/srv/blockchain/cardano-tx-builder.js +17 -34
  40. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  41. package/srv/blockchain/circuit-breaker.js +5 -15
  42. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  43. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +0 -17
  45. package/srv/blockchain/crawler/certificate-backfill.js +8 -22
  46. package/srv/blockchain/crawler/crawler.d.ts +16 -93
  47. package/srv/blockchain/crawler/crawler.js +85 -160
  48. package/srv/blockchain/crawler/credential-backfill.d.ts +0 -9
  49. package/srv/blockchain/crawler/credential-backfill.js +6 -6
  50. package/srv/blockchain/crawler/hooks.d.ts +1 -5
  51. package/srv/blockchain/crawler/index.d.ts +0 -12
  52. package/srv/blockchain/crawler/index.js +6 -20
  53. package/srv/blockchain/crawler/sync-state.d.ts +6 -44
  54. package/srv/blockchain/crawler/sync-state.js +18 -53
  55. package/srv/blockchain/crawler/transaction-backfill.d.ts +0 -11
  56. package/srv/blockchain/crawler/transaction-backfill.js +11 -30
  57. package/srv/blockchain/crawler/utxo-set-import.d.ts +1 -30
  58. package/srv/blockchain/crawler/utxo-set-import.js +27 -53
  59. package/srv/blockchain/ledger-state.d.ts +10 -54
  60. package/srv/blockchain/ledger-state.js +11 -27
  61. package/srv/blockchain/pending-spends.d.ts +0 -12
  62. package/srv/blockchain/pending-spends.js +4 -12
  63. package/srv/blockchain/request-coalescer.d.ts +2 -16
  64. package/srv/blockchain/request-coalescer.js +2 -16
  65. package/srv/blockchain/signing/cose-verifier.d.ts +0 -9
  66. package/srv/blockchain/signing/cose-verifier.js +4 -10
  67. package/srv/blockchain/signing/external-signer.d.ts +1 -4
  68. package/srv/blockchain/signing/external-signer.js +2 -8
  69. package/srv/blockchain/signing/hsm-signer.d.ts +6 -18
  70. package/srv/blockchain/signing/hsm-signer.js +16 -28
  71. package/srv/blockchain/signing/signature-verifier.d.ts +1 -8
  72. package/srv/blockchain/signing/signature-verifier.js +9 -19
  73. package/srv/blockchain/signing/submission-finalizer.d.ts +10 -16
  74. package/srv/blockchain/signing/submission-finalizer.js +48 -19
  75. package/srv/blockchain/stored-chain.d.ts +1 -14
  76. package/srv/blockchain/stored-chain.js +3 -8
  77. package/srv/blockchain/transaction-building/buildooor-fee-patch.d.ts +0 -4
  78. package/srv/blockchain/transaction-building/buildooor-fee-patch.js +4 -9
  79. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +7 -150
  80. package/srv/blockchain/transaction-building/buildooor-tx.js +91 -196
  81. package/srv/blockchain/transaction-building/caller-datums.d.ts +0 -14
  82. package/srv/blockchain/transaction-building/caller-datums.js +3 -9
  83. package/srv/blockchain/transaction-building/cardano-tx.d.ts +1 -4
  84. package/srv/blockchain/wallet-worker/build-request.d.ts +0 -5
  85. package/srv/blockchain/wallet-worker/build-request.js +6 -9
  86. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -23
  87. package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -20
  88. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  89. package/srv/blockchain/wallet-worker/index.js +3 -5
  90. package/srv/blockchain/wallet-worker/job-store.d.ts +15 -65
  91. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  92. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -10
  93. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -12
  94. package/srv/blockchain/wallet-worker/signers.d.ts +3 -11
  95. package/srv/blockchain/wallet-worker/signers.js +3 -6
  96. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +3 -21
  97. package/srv/blockchain/wallet-worker/wallet-worker.js +47 -54
  98. package/srv/cardano-agent-service.cds +123 -146
  99. package/srv/cardano-agent-service.js +2 -5
  100. package/srv/cardano-backend-service.cds +10 -17
  101. package/srv/cardano-backend-service.js +7 -12
  102. package/srv/cardano-indexer-service.cds +35 -37
  103. package/srv/cardano-indexer-service.d.ts +5 -1
  104. package/srv/cardano-indexer-service.js +64 -33
  105. package/srv/cardano-service.cds +56 -40
  106. package/srv/cardano-service.js +42 -69
  107. package/srv/cardano-sign-service.cds +14 -23
  108. package/srv/cardano-sign-service.js +18 -24
  109. package/srv/cardano-tx-service.cds +27 -29
  110. package/srv/cardano-tx-service.js +60 -122
  111. package/srv/cardano-worker-service.cds +109 -125
  112. package/srv/cardano-worker-service.js +21 -31
  113. package/srv/cbor/cip68.d.ts +13 -0
  114. package/srv/cbor/cip68.js +56 -0
  115. package/srv/cbor/index.d.ts +1 -0
  116. package/srv/cbor/index.js +6 -1
  117. package/srv/cbor/parse.d.ts +3 -18
  118. package/srv/cbor/parse.js +2 -7
  119. package/srv/cbor/plutus-data-json.d.ts +0 -4
  120. package/srv/server.d.ts +5 -36
  121. package/srv/server.js +30 -51
  122. package/srv/utils/agent-grants-config.d.ts +0 -18
  123. package/srv/utils/agent-grants-config.js +6 -13
  124. package/srv/utils/agent-grants.d.ts +14 -68
  125. package/srv/utils/agent-grants.js +42 -60
  126. package/srv/utils/agent-token-auth.d.ts +0 -5
  127. package/srv/utils/agent-token-auth.js +2 -5
  128. package/srv/utils/backend-request-handler.d.ts +1 -1
  129. package/srv/utils/collections.d.ts +1 -4
  130. package/srv/utils/collections.js +1 -4
  131. package/srv/utils/const.d.ts +0 -18
  132. package/srv/utils/const.js +7 -18
  133. package/srv/utils/crypto.js +3 -5
  134. package/srv/utils/db-indexes.d.ts +2 -0
  135. package/srv/utils/db-indexes.js +22 -9
  136. package/srv/utils/db-sanitize.d.ts +1 -8
  137. package/srv/utils/db-sanitize.js +3 -8
  138. package/srv/utils/epoch-slots.d.ts +1 -8
  139. package/srv/utils/epoch-slots.js +3 -8
  140. package/srv/utils/error-codes.d.ts +0 -4
  141. package/srv/utils/error-codes.js +2 -4
  142. package/srv/utils/errors.d.ts +2 -22
  143. package/srv/utils/errors.js +13 -27
  144. package/srv/utils/liveness.d.ts +0 -4
  145. package/srv/utils/liveness.js +2 -4
  146. package/srv/utils/mappers.d.ts +0 -37
  147. package/srv/utils/mappers.js +22 -39
  148. package/srv/utils/network-context.js +2 -4
  149. package/srv/utils/paging.d.ts +31 -0
  150. package/srv/utils/paging.js +43 -0
  151. package/srv/utils/pg-inline-json.js +3 -7
  152. package/srv/utils/pg-order-nulls.js +2 -5
  153. package/srv/utils/plutus-placeholders.d.ts +0 -13
  154. package/srv/utils/plutus-placeholders.js +6 -13
  155. package/srv/utils/rate-limiter.d.ts +0 -8
  156. package/srv/utils/rate-limiter.js +2 -4
  157. package/srv/utils/reference-script.d.ts +0 -18
  158. package/srv/utils/reference-script.js +8 -19
  159. package/srv/utils/service-events.d.ts +0 -4
  160. package/srv/utils/service-events.js +2 -4
  161. package/srv/utils/signing-helper.d.ts +1 -8
  162. package/srv/utils/signing-helper.js +3 -8
  163. package/srv/utils/tx-build-helper.d.ts +2 -32
  164. package/srv/utils/tx-build-helper.js +26 -40
  165. package/srv/utils/tx-request-parsers.d.ts +1 -25
  166. package/srv/utils/tx-request-parsers.js +10 -25
  167. package/srv/utils/tx-utils.d.ts +0 -8
  168. package/srv/utils/tx-utils.js +10 -13
  169. package/srv/utils/types.d.ts +2 -37
  170. package/srv/utils/validators.d.ts +0 -4
  171. package/srv/utils/validators.js +2 -4
@@ -17,11 +17,16 @@ const collections_1 = require("../utils/collections");
17
17
  const transaction_rows_1 = require("./transaction-rows");
18
18
  const ledger_state_1 = require("./ledger-state");
19
19
  const sync_state_1 = require("./crawler/sync-state");
20
+ const asset_decimals_1 = require("./asset-decimals");
20
21
  const epoch_slots_1 = require("../utils/epoch-slots");
21
22
  const const_1 = require("../utils/const");
22
23
  const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
23
24
  const logger = cds_1.default.log('CardanoIndexer');
24
25
  /** Datum hash, inline datum and reference script of the spent output onto its input. */
26
+ /** Newest first; the tx hash breaks ties inside one block. */
27
+ function sortAddressTransactions(rows) {
28
+ return rows.sort((a, b) => Number(b.blockTime ?? 0) - Number(a.blockTime ?? 0) || String(b.tx_hash).localeCompare(String(a.tx_hash)));
29
+ }
25
30
  function copyUtxoData(input, out) {
26
31
  input.dataHash = input.dataHash ?? out.utxo_dataHash ?? null;
27
32
  input.inlineDatum = input.inlineDatum ?? out.utxo_inlineDatum ?? null;
@@ -49,21 +54,15 @@ function addressFromUtxos(address, utxos) {
49
54
  const decoded = (0, mappers_1.decodeShelleyAddress)(address);
50
55
  return { address, stakeAddress: decoded.stakeAddress, type: decoded.type, isScript: decoded.isScript, amount: (0, mappers_1.sumUtxoAmounts)(utxos), utxos };
51
56
  }
52
- /**
53
- * Indexes Cardano data into the OData entities: fetches via CardanoClient, maps provider data
54
- * to entity rows and UPSERTs them inside the caller's CAP transaction.
55
- */
57
+ /** Fetches chain data, maps it to entity rows and UPSERTs them in the caller's transaction. */
56
58
  class CardanoIndexer {
57
59
  client;
58
60
  txBuilder;
59
61
  lastParamsFetchTime = 0;
60
62
  static CRAWL_EPOCH_REFRESH_MS = 5 * 60 * 1000;
61
63
  static CRAWL_EPOCH_RETRY_MS = 30 * 1000;
62
- /**
63
- * Crawler epoch memo: refreshed periodically while an epoch is live and once more when the
64
- * next one starts; holds at most the current and previous epoch. A row is UPSERTed until a
65
- * block transaction that wrote it has committed (`confirmBlockCommit`).
66
- */
64
+ // Crawler epoch memo for the current and previous epoch, refreshed while an epoch is live.
65
+ // A row is UPSERTed again until a block transaction that wrote it has committed.
67
66
  crawlEpochCache = new Map();
68
67
  crawlEpochCurrent = null;
69
68
  /** Epoch rows known to be committed; a refresh creates a new row object and is written again. */
@@ -78,10 +77,7 @@ class CardanoIndexer {
78
77
  crawlCertificates = false;
79
78
  /** Logged once per process: the active source reports no certificates (Blockfrost). */
80
79
  certificatesUnreportedWarned = false;
81
- /**
82
- * Crawler-fed ledger state (`crawler.utxoSet`): blocks after `utxoAnchor` are applied to the
83
- * Ledger* tables; no anchor means configured but inactive.
84
- */
80
+ /** Blocks after utxoAnchor are applied to the Ledger* tables. Without an anchor the mode is inactive. */
85
81
  crawlUtxoSet = false;
86
82
  /** crawler.authoritative: misses in the crawled chain are 404, no provider call. */
87
83
  crawlAuthoritative = false;
@@ -92,20 +88,15 @@ class CardanoIndexer {
92
88
  credentialGeneration = 0;
93
89
  /** The anchor block was found in the crawled chain (checked once, before the first apply). */
94
90
  utxoAnchorVerified = false;
95
- /**
96
- * Invalidation decided inside a block transaction; the anchor stays until the crawler confirms
97
- * the commit (`takeLedgerInvalidation`), so a rolled-back attempt changes nothing.
98
- */
91
+ /** Kept until the crawler confirms the block commit, so a rolled-back attempt changes nothing. */
99
92
  ledgerInvalidation = null;
100
93
  /** Units known to have an `Assets` row, so a repeat sighting costs no DB round-trip. */
101
94
  static ASSET_MEMO_CAP = 200_000;
102
95
  /** Output references per node lookup when checking crawled UTxOs. */
103
96
  static OUTREF_CHUNK = 500;
104
97
  assetMemo = new Set();
105
- /**
106
- * Background registry enrichment queue (`assetCatalogue: 'enrich'`), drained at a fixed rate
107
- * outside the block transaction. Above the cap the oldest units are dropped (bare row stays).
108
- */
98
+ // Registry enrichment queue, drained at a fixed rate outside the block transaction.
99
+ // Above the cap the oldest units are dropped and keep their bare row.
109
100
  static ENRICH_QUEUE_CAP = 50_000;
110
101
  enrichQueue = [];
111
102
  enrichTimer = null;
@@ -121,20 +112,16 @@ class CardanoIndexer {
121
112
  if (coverage.assetCatalogue !== 'enrich')
122
113
  this.stopAssetEnrichment();
123
114
  }
124
- /**
125
- * What the crawled data answers authoritatively: only while a live crawler is at the tip.
126
- * Every block after `fromSlot` is held; `ledger` = the crawled UTxO set is active.
127
- */
115
+ // Range the crawled data answers authoritatively, only while a live crawler is at the tip.
116
+ // ledger is true when the crawled UTxO set is active.
128
117
  async localCoverage(tx) {
129
118
  const cursor = await (0, sync_state_1.readCursor)(tx);
130
119
  if (!cursor || cursor.syncStatus !== 'synced' || cursor.startSlot == null || !(0, sync_state_1.isCrawlerLeaseActive)(cursor))
131
120
  return null;
132
121
  return { fromSlot: cursor.startSlot, lastSlot: cursor.lastSlot, tipHeight: cursor.tipHeight, ledger: cursor.utxoSet.status === 'active' };
133
122
  }
134
- /**
135
- * Block counts of a pool from crawled blocks (`slotLeader` = pool id): the current epoch when the
136
- * crawl covers it from its first slot, the lifetime total when it covers the chain since Shelley.
137
- */
123
+ // Block counts of a pool from crawled blocks. The epoch count needs the whole current epoch
124
+ // crawled, the lifetime count the whole chain since Shelley.
138
125
  async localPoolBlocks(tx, poolId) {
139
126
  const coverage = await this.localCoverage(tx);
140
127
  if (!coverage)
@@ -152,10 +139,8 @@ class CardanoIndexer {
152
139
  counts.blocksMinted = await countSince(0);
153
140
  return counts;
154
141
  }
155
- /**
156
- * The crawled chain answers `method` on its own: live crawler at the tip, crawl from the Shelley
157
- * start, and either crawler.authoritative or no configured backend can serve the method.
158
- */
142
+ // Non-null when the crawled chain answers method alone. Needs a live crawler at the tip, a crawl
143
+ // from Shelley, and either crawler.authoritative or no backend that serves the method.
159
144
  async crawlAnswers(tx, method) {
160
145
  const coverage = await this.localCoverage(tx);
161
146
  if (!coverage || coverage.fromSlot > const_1.EPOCH_CONFIG_BY_NETWORK[this.client.network].shelleyStartSlot)
@@ -170,10 +155,8 @@ class CardanoIndexer {
170
155
  if (coverage)
171
156
  throw new errors_1.NotFoundError(`${what} (not in the crawled chain up to slot ${coverage.lastSlot})`);
172
157
  }
173
- /**
174
- * Asset from crawled mint/burn rows: supply = mints − burns, first mint, CIP-25 payload (label 721)
175
- * of the latest mint. Registry fields stay null. null = the crawled chain does not answer.
176
- */
158
+ // Asset from crawled mint and burn rows. Registry fields stay null.
159
+ // Null when the crawled chain does not answer.
177
160
  async localAssetInfo(tx, unit) {
178
161
  if (!this.crawlAssetHistory || !(await this.crawlAnswers(tx, 'getAssetInfo')))
179
162
  return null;
@@ -233,7 +216,7 @@ class CardanoIndexer {
233
216
  /** Mint/burn events, newest first: crawled rows when the crawled chain answers, else the backend. */
234
217
  async resolveAssetHistory(tx, unit, limit) {
235
218
  if (this.crawlAssetHistory && await this.crawlAnswers(tx, 'getAssetHistory')) {
236
- const rows = await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).where({ unit }).orderBy('blockHeight desc').limit(limit));
219
+ const rows = await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).where({ unit }).orderBy('blockHeight desc', 'txHash desc').limit(limit));
237
220
  return (rows ?? []).map(r => ({
238
221
  unit: String(r.unit),
239
222
  txHash: String(r.txHash),
@@ -269,11 +252,8 @@ class CardanoIndexer {
269
252
  async ledgerCoverageActive(tx) {
270
253
  return Boolean((await this.localCoverage(tx))?.ledger);
271
254
  }
272
- /**
273
- * Address from the crawled UTxO set: the unspent `LedgerUTxOs` (see openLedgerUtxos), type and
274
- * stake address decoded from the address. An address the set has never
275
- * seen is an empty address, not an error. null = the set cannot answer.
276
- */
255
+ // Address from the crawled UTxO set. An address the set never saw is empty, not an error.
256
+ // Null when the set cannot answer.
277
257
  async localAddress(tx, addr) {
278
258
  if (!(await this.localCoverage(tx))?.ledger)
279
259
  return null;
@@ -290,11 +270,8 @@ class CardanoIndexer {
290
270
  byAddress.get(u.address)?.push(u);
291
271
  return addresses.map(a => addressFromUtxos(a, byAddress.get(a)));
292
272
  }
293
- /**
294
- * Latest transactions of an address from the crawled UTxO set: the outputs it received
295
- * (`LedgerUTxOs.txHash`) and spent (`spentTxHash`) since the anchor. `complete` = the address was
296
- * first seen after the anchor, so nothing older exists. null = the set cannot answer.
297
- */
273
+ // Transactions that paid to or spent from the address since the anchor. complete is true when the
274
+ // address first appeared after the anchor, so nothing older exists. Null when the set cannot answer.
298
275
  async localAddressTransactions(tx, addr, limit) {
299
276
  if (!(await this.localCoverage(tx))?.ledger)
300
277
  return null;
@@ -331,8 +308,7 @@ class CardanoIndexer {
331
308
  outputs: (outRows ?? []).filter(r => r.txHash === hash).map(r => ({ address: addr, amount: amountOf(r) })),
332
309
  }));
333
310
  const rows = (0, mappers_1.mapAddressTransactions)(addr, txs);
334
- rows.sort((a, b) => Number(b.blockTime ?? 0) - Number(a.blockTime ?? 0));
335
- return { rows: rows, complete };
311
+ return { rows: sortAddressTransactions(rows), complete };
336
312
  }
337
313
  /** Amount lists (lovelace + assets) of `LedgerUTxOs` rows, keyed `txHash#outputIndex`. */
338
314
  async ledgerAmounts(tx, rows) {
@@ -349,10 +325,8 @@ class CardanoIndexer {
349
325
  }
350
326
  return out;
351
327
  }
352
- /**
353
- * Active stake of a pool from the Ogmios epoch snapshot of the running epoch (constant within
354
- * an epoch). Empty when the crawler is not at the tip or the epoch has no such snapshot.
355
- */
328
+ // Active stake from the Ogmios snapshot of the running epoch.
329
+ // Empty when the crawler is not at the tip or that snapshot is missing.
356
330
  async snapshotActiveStake(tx, poolId) {
357
331
  const coverage = await this.localCoverage(tx);
358
332
  if (!coverage)
@@ -363,10 +337,8 @@ class CardanoIndexer {
363
337
  return {};
364
338
  return { activeStake: lovelaceSum(row.activeStake), activeSize: Number(row.activeSize ?? 0) };
365
339
  }
366
- /**
367
- * Lifetime withdrawals of a stake key from crawled withdrawals — only when certificates are
368
- * crawled and the crawl covers the chain since Shelley; null otherwise.
369
- */
340
+ // Lifetime withdrawals from crawled rows. Null unless certificates are crawled
341
+ // and the crawl covers the chain since Shelley.
370
342
  async localWithdrawalsSum(tx, stakeAddress) {
371
343
  const coverage = await this.localCoverage(tx);
372
344
  if (!coverage || !this.crawlCertificates)
@@ -382,11 +354,8 @@ class CardanoIndexer {
382
354
  this.utxoAnchorVerified = false;
383
355
  this.ledgerInvalidation = null;
384
356
  }
385
- /**
386
- * The imported set describes the chain AT the anchor block, so before the first block past it
387
- * is applied the cursor (not yet advanced in this transaction) must equal the anchor exactly;
388
- * otherwise the snapshot was taken on a fork. Skipped once `utxoAppliedSlot` is set.
389
- */
357
+ // The imported set describes the chain at the anchor block. Before the first block past it, the
358
+ // cursor must equal the anchor, else the snapshot came from a fork. Skipped once a block applied.
390
359
  async verifyUtxoAnchor(tx, anchor) {
391
360
  const cursor = await (0, sync_state_1.readCursor)(tx);
392
361
  if (cursor?.utxoSet.appliedSlot != null)
@@ -396,7 +365,7 @@ class CardanoIndexer {
396
365
  const reason = cursor
397
366
  ? `anchor ${anchor.slot}/${anchor.hash} is not the block the crawler followed (cursor ${cursor.lastSlot}/${cursor.lastBlockHash})`
398
367
  : `no crawler cursor to verify the anchor ${anchor.slot}/${anchor.hash} against`;
399
- logger.error(`UTxO set invalidated: ${reason} — the snapshot describes a fork; re-import at the crawler cursor`);
368
+ logger.error(`UTxO set invalidated: ${reason}. The snapshot describes a fork; re-import at the crawler cursor`);
400
369
  await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: reason.slice(0, 500) });
401
370
  this.ledgerInvalidation = reason;
402
371
  return false;
@@ -422,10 +391,8 @@ class CardanoIndexer {
422
391
  }
423
392
  return reason;
424
393
  }
425
- /**
426
- * Drain the enrichment queue at `enrichRate` units per second, one `indexAsset()` per tick in
427
- * its own transaction. A failing unit is dropped; its bare row stays for the lazy path.
428
- */
394
+ // Drains the queue at enrichRate units per second, each in its own transaction.
395
+ // A failing unit is dropped and its bare row stays for the lazy path.
429
396
  startAssetEnrichment() {
430
397
  if (this.enrichTimer || this.crawlAssetCatalogue !== 'enrich')
431
398
  return;
@@ -450,10 +417,8 @@ class CardanoIndexer {
450
417
  }
451
418
  this.enrichQueue = [];
452
419
  }
453
- /**
454
- * Network-only epoch prefetch for the crawler. Call BEFORE opening the per-block write
455
- * transaction so no backend round-trip runs under the DB write lock. Never throws.
456
- */
420
+ // Call before opening the block write transaction, so no backend round trip
421
+ // runs under the DB write lock. Never throws.
457
422
  async prefetchCrawlEpoch(epochNumber) {
458
423
  const previousEpoch = this.crawlEpochCurrent;
459
424
  const enteringNewEpoch = previousEpoch !== null && previousEpoch !== epochNumber;
@@ -506,10 +471,8 @@ class CardanoIndexer {
506
471
  });
507
472
  }
508
473
  }
509
- /**
510
- * Block, transaction and fee totals of an epoch summed over the crawled blocks, when the crawl
511
- * covers the epoch from its first slot; null otherwise. Output and active stake stay with the backend.
512
- */
474
+ // Block, tx and fee totals from crawled blocks. Null unless the crawl covers the whole epoch.
475
+ // Output and active stake still come from the backend.
513
476
  async crawledEpochTotals(epochNumber) {
514
477
  try {
515
478
  const cursor = await (0, sync_state_1.readCursor)(cds_1.default.db);
@@ -551,19 +514,14 @@ class CardanoIndexer {
551
514
  txBuilder.setAddressUtxoSource?.((address) => this.localAddressUtxos(address));
552
515
  logger.info('CardanoIndexer instance created');
553
516
  }
554
- /**
555
- * Unspent outputs of an address from the crawled set for the transaction builder; null = the set
556
- * cannot answer. Runs on `cds.db`, i.e. inside the caller's request transaction when there is one.
557
- */
517
+ // Unspent outputs for the transaction builder. Null when the set cannot answer.
518
+ // Runs on cds.db, so inside the caller's request transaction when there is one.
558
519
  async localAddressUtxos(address) {
559
520
  if (!cds_1.default.db)
560
521
  return null;
561
522
  return (await this.localAddress(cds_1.default.db, address))?.utxos ?? null;
562
523
  }
563
- /**
564
- * Index a transaction with inputs/outputs/assets/metadata; all UPSERTs run in the caller's
565
- * transaction, so either everything persists or nothing does.
566
- */
524
+ /** All UPSERTs run in the caller's transaction, so everything persists or nothing does. */
567
525
  async indexTransaction(tx, txHash) {
568
526
  await this.refuseOutsideCrawl(tx, 'getTransaction', `Transaction ${txHash}`);
569
527
  const providerTx = await this.client.getTransaction(txHash);
@@ -596,10 +554,8 @@ class CardanoIndexer {
596
554
  if (metadataRows.length)
597
555
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
598
556
  }
599
- /**
600
- * Index address data with assets and UTxOs; transactions are loaded separately via
601
- * indexAddressTransactions(). `prefetched` = address data the caller already fetched in a batch.
602
- */
557
+ // Transactions are loaded separately by indexAddressTransactions().
558
+ // prefetched is address data the caller already fetched in a batch.
603
559
  async indexAddress(tx, addr, prefetched) {
604
560
  const addrData = prefetched ?? await this.resolveAddress(tx, addr);
605
561
  logger.debug(`indexAddress: provider response for ${addr}: ${addrData.amount?.length ?? 0} amounts, ${addrData.utxos?.length ?? 0} utxos`);
@@ -657,18 +613,15 @@ class CardanoIndexer {
657
613
  }
658
614
  return AddrEntity;
659
615
  }
660
- /**
661
- * Index UTxOs by 28-byte payment credential (56-char hex), always fresh from Koios. Child
662
- * rows are UPSERTed without a parent Addresses row (same pattern as TransactionInputs).
663
- */
616
+ /** Always fresh from the backend. Rows are written without a parent Addresses row. */
664
617
  async indexCredentialUtxos(tx, credHash) {
665
618
  const local = await this.localCredentialUtxos(tx, credHash);
666
619
  const utxos = local ?? await this.client.getCredentialUtxos(credHash);
667
620
  logger.debug(`indexCredentialUtxos: ${local ? 'crawled UTxO set' : 'provider'} returned ${utxos.length} utxos for credential ${credHash}`);
668
621
  if (utxos.length === 0)
669
622
  return [];
670
- // Group by bech32 address — Koios returns UTxOs across all bech32 forms
671
- // sharing the credential; mapAddressUtxos keys rows by address parameter.
623
+ // Koios returns UTxOs of every address form sharing the credential.
624
+ // mapAddressUtxos keys rows by address, so group them first.
672
625
  const byAddress = new Map();
673
626
  for (const u of utxos) {
674
627
  const list = byAddress.get(u.address) ?? [];
@@ -700,12 +653,8 @@ class CardanoIndexer {
700
653
  logger.debug(`indexCredentialUtxos: indexed ${allRows.length} utxos across ${byAddress.size} addresses`);
701
654
  return allRows;
702
655
  }
703
- /**
704
- * UTxOs of a payment credential without a provider: addresses and unspent outputs from the crawled
705
- * UTxO set (see openLedgerUtxos).
706
- * null = the crawled set cannot answer (not synced, no set, credential column still filling).
707
- * An address first used in the last `confirmationDepth` blocks is not in the set yet.
708
- */
656
+ // Credential UTxOs from the crawled set. Null when the set cannot answer yet.
657
+ // An address first used in the last confirmationDepth blocks is not in the set yet.
709
658
  async localCredentialUtxos(tx, credHash) {
710
659
  if (!(await this.localCoverage(tx))?.ledger || !(await this.paymentCredentialsReady()))
711
660
  return null;
@@ -715,11 +664,8 @@ class CardanoIndexer {
715
664
  return [];
716
665
  return this.openLedgerUtxos(tx, addresses);
717
666
  }
718
- /**
719
- * Unspent outputs of addresses from the crawled set, checked against the node by output reference
720
- * (a keyed lookup; the node's address query scans its whole UTxO set): drops what was spent after
721
- * the cursor. Without a usable node, or when the check fails, the set as of the cursor.
722
- */
667
+ // Crawled outputs checked against the node by output reference, to drop what was spent after
668
+ // the cursor. The node's address query would scan its whole UTxO set. Falls back to the set as is.
723
669
  async openLedgerUtxos(tx, addresses) {
724
670
  const rows = await this.ledgerUtxosOf(tx, addresses);
725
671
  if (rows.length === 0)
@@ -771,10 +717,8 @@ class CardanoIndexer {
771
717
  }
772
718
  return out;
773
719
  }
774
- /**
775
- * True once every Shelley-type `LedgerAddresses` row carries its payment credential. Until then
776
- * the fill runs in the background (started once per process) and callers use the provider.
777
- */
720
+ // True once every Shelley address row has its payment credential.
721
+ // Until then a background fill runs and callers use the provider.
778
722
  async paymentCredentialsReady() {
779
723
  if (this.credentialsReady)
780
724
  return true;
@@ -798,10 +742,8 @@ class CardanoIndexer {
798
742
  this.credentialGeneration++;
799
743
  this.credentialsReady = false;
800
744
  }
801
- /**
802
- * Index only the UTxOs of an address via getAddressUtxos (no getAddress call), so it works on
803
- * backends without address aggregation such as Ogmios. Writes no parent Addresses row.
804
- */
745
+ // Skips getAddress, so it works on backends without address aggregation such as Ogmios.
746
+ // Writes no parent Addresses row.
805
747
  async indexAddressUtxos(tx, addr) {
806
748
  const utxos = await this.client.getAddressUtxos(addr);
807
749
  logger.debug(`indexAddressUtxos: provider returned ${utxos.length} utxos for ${addr}`);
@@ -825,11 +767,8 @@ class CardanoIndexer {
825
767
  }
826
768
  return utxoEntities;
827
769
  }
828
- /**
829
- * Evict cached rows a submitted transaction made stale: every consumed input ref (under any
830
- * address) and all address-level rows of the output addresses plus `extraAddresses`. Only the
831
- * read cache is touched; lagging backends may still serve pre-submit state on refetch.
832
- */
770
+ // Evicts cached rows a submitted tx made stale: its spent inputs and its output addresses.
771
+ // A lagging backend may still return the old state on refetch.
833
772
  async invalidateUtxoCacheForTx(tx, targets, extraAddresses = []) {
834
773
  const addresses = [...new Set([...targets.outputAddresses, ...extraAddresses])];
835
774
  for (const address of addresses) {
@@ -871,13 +810,19 @@ class CardanoIndexer {
871
810
  logger.debug(`indexAddressTransactions: found ${txHashes.length} tx hashes for ${addr}`);
872
811
  if (txHashes.length === 0)
873
812
  return [];
813
+ // Rows this address already has stay as stored; only new hashes are fetched.
814
+ const known = await tx.run(SELECT.from(CardanoODataService_1.AddressTransactions).where({ address_address: addr, tx_hash: { in: txHashes } }));
815
+ const knownHashes = new Set((known ?? []).map(r => r.tx_hash));
816
+ const newHashes = txHashes.filter(h => !knownHashes.has(h));
817
+ if (!newHashes.length)
818
+ return sortAddressTransactions(known ?? []);
874
819
  // DB-first dedup + batch fetch
875
- const batchFetched = await this.ensureTransactionsIndexed(tx, txHashes);
820
+ const batchFetched = await this.ensureTransactionsIndexed(tx, newHashes);
876
821
  // For address-transaction mapping we need full provider tx data (inputs/outputs for net amounts).
877
- // Transactions already in DB were not re-fetched — batch-fetch those separately.
822
+ // Transactions already in the DB were not fetched again, so batch-fetch them separately.
878
823
  const allTxData = [];
879
824
  const missingFromBatch = [];
880
- for (const hash of txHashes) {
825
+ for (const hash of newHashes) {
881
826
  const fromBatch = batchFetched.get(hash);
882
827
  if (fromBatch) {
883
828
  allTxData.push(fromBatch);
@@ -894,16 +839,13 @@ class CardanoIndexer {
894
839
  allTxData.push(providerTx);
895
840
  }
896
841
  }
897
- // Create address-transaction mapping entries (no TTL — keyed by (address, tx),
898
- // immutable per confirmed tx; the entity has no temporal columns)
842
+ // No TTL, because a row per address and confirmed tx never changes.
899
843
  const transactionsEntities = (0, mappers_1.mapAddressTransactions)(addr, allTxData);
900
844
  logger.debug({ count: transactionsEntities.length }, 'indexAddressTransactions: transaction entities');
901
845
  if (transactionsEntities.length) {
902
846
  await tx.run(UPSERT.into(CardanoODataService_1.AddressTransactions).entries(transactionsEntities));
903
847
  }
904
- // Sort by blockTime descending for consistency with GetLatestTransactionsByAddress
905
- transactionsEntities.sort((a, b) => (b.blockTime ?? 0) - (a.blockTime ?? 0));
906
- return transactionsEntities;
848
+ return sortAddressTransactions([...(known ?? []), ...transactionsEntities]);
907
849
  }
908
850
  /** Link an address to a signing request for address-based queries. */
909
851
  async indexAddressSigningRequests(tx, addr, signingRequestId) {
@@ -928,7 +870,16 @@ class CardanoIndexer {
928
870
  return [];
929
871
  await this.refuseOutsideCrawl(tx, 'getTransactionMetadata', `Transaction ${tx_hash}`);
930
872
  }
931
- const metadata = await this.client.getTransactionMetadata(tx_hash);
873
+ let metadata;
874
+ try {
875
+ metadata = await this.client.getTransactionMetadata(tx_hash);
876
+ }
877
+ catch (err) {
878
+ // providers answer "not found" for a transaction without metadata; a stored transaction has none
879
+ if ((0, errors_1.isNotFoundOnAllBackends)(err) && await tx.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('hash').where({ hash: tx_hash })))
880
+ return [];
881
+ throw err;
882
+ }
932
883
  const rows = (0, mappers_1.mapTransactionMetadata)(metadata);
933
884
  if (rows.length) {
934
885
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(rows));
@@ -964,11 +915,8 @@ class CardanoIndexer {
964
915
  await tx.run(UPSERT.into(CardanoODataService_1.Block).entries(blockEntity));
965
916
  return blockEntity;
966
917
  }
967
- /**
968
- * Bulk-index a whole block and its transactions in one pass for the crawler: no per-hash
969
- * re-fetch, one UPSERT per table, all inside the caller's transaction so the block persists
970
- * atomically. Bare chain-sync inputs are backfilled by resolveInputs() first.
971
- */
918
+ // Indexes a whole block for the crawler with one UPSERT per table in the caller's transaction.
919
+ // The block persists atomically. resolveInputs() fills bare chain-sync inputs first.
972
920
  async indexBlockFull(tx, blockData, txs) {
973
921
  // Memo updates of a rolled-back attempt must not survive into this one.
974
922
  this.pendingCommit = [];
@@ -1012,7 +960,6 @@ class CardanoIndexer {
1012
960
  await this.resolveInputs(tx, txs, ledgerLookup);
1013
961
  this.applyCollateralFees(blockData, txs);
1014
962
  await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
1015
- await this.removeSupersededBlocks(tx, blockData);
1016
963
  await this.removeStaleTxSeqs(tx, txs);
1017
964
  // One bulk UPSERT per table. NUL safety for PostgreSQL is enforced by the db-level hook in
1018
965
  // srv/utils/db-sanitize.ts, not per call site.
@@ -1035,8 +982,8 @@ class CardanoIndexer {
1035
982
  // Redeemers and witness datums come with the block on chain-sync; keyed by tx like the certificates.
1036
983
  const redeemerRows = txs.flatMap(t => (0, mappers_1.mapTransactionRedeemers)(t.hash, t.redeemers ?? []));
1037
984
  const datumRows = txs.flatMap(t => (0, mappers_1.mapTransactionDatums)(t.hash, t.datums ?? []));
1038
- // Mint/burn is derived from rows already in hand — keyed (unit, txHash), so a re-crawl is
1039
- // idempotent and a reorg removes these rows with their transactions (crawler handleReorg).
985
+ // Mint and burn rows are keyed by unit and tx, so a re-crawl is idempotent.
986
+ // A reorg removes them with their transactions.
1040
987
  const assetHistoryRows = this.crawlAssetHistory ? this.buildAssetHistoryRows(blockData, txs) : [];
1041
988
  if (txRows.length)
1042
989
  await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRows));
@@ -1058,6 +1005,8 @@ class CardanoIndexer {
1058
1005
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionRedeemers).entries(redeemerRows));
1059
1006
  if (datumRows.length)
1060
1007
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionDatums).entries(datumRows));
1008
+ // after the transactions moved here, so a rolled-back block they pointed at is no longer kept
1009
+ await this.removeSupersededBlocks(tx, blockData);
1061
1010
  // Same transaction, so the UTxO set can never be a block ahead of or behind the cursor.
1062
1011
  if (ledgerDue) {
1063
1012
  if (priorInvalidation) {
@@ -1068,7 +1017,7 @@ class CardanoIndexer {
1068
1017
  else if (ledgerLookup) {
1069
1018
  const ledger = await (0, ledger_state_1.applyBlockToLedger)(tx, blockData, txs, ledgerLookup);
1070
1019
  if (ledger.missing) {
1071
- logger.warn(`ledger: block ${blockData.hash} consumed ${ledger.missing} outpoint(s) with no open row — ` +
1020
+ logger.warn(`ledger: block ${blockData.hash} consumed ${ledger.missing} outpoint(s) with no open row: ` +
1072
1021
  'the set is incomplete relative to the crawl (snapshot gap?); balances of those addresses drift');
1073
1022
  }
1074
1023
  }
@@ -1079,13 +1028,13 @@ class CardanoIndexer {
1079
1028
  const newAssets = this.crawlAssetCatalogue === 'off'
1080
1029
  ? 0
1081
1030
  : await this.ensureAssetRows(tx, this.collectBlockUnits(txs, assetHistoryRows));
1082
- logger.debug(`indexBlockFull: block ${blockData.hash} — ${txs.length} txs, ${outputRows.length} outputs, ` +
1031
+ // A reference NFT moved or minted in this block carries the current CIP-68 metadata of its token.
1032
+ await (0, asset_decimals_1.applyReferenceDatums)(tx, txs);
1033
+ logger.debug(`indexBlockFull: block ${blockData.hash}: ${txs.length} txs, ${outputRows.length} outputs, ` +
1083
1034
  `${assetHistoryRows.length} mint/burn, ${newAssets} new assets`);
1084
1035
  }
1085
- /**
1086
- * Drop other Block rows at the crawled block's height that no transaction references: lazily
1087
- * indexed tips that were rolled back, which no crawler reorg covers.
1088
- */
1036
+ // Drops unreferenced Block rows at the same height. They are lazily indexed tips
1037
+ // that were rolled back, which no crawler reorg covers.
1089
1038
  async removeSupersededBlocks(tx, blockData) {
1090
1039
  if (blockData.height == null)
1091
1040
  return;
@@ -1101,10 +1050,8 @@ class CardanoIndexer {
1101
1050
  await tx.run(DELETE.from(CardanoODataService_1.Blocks).where({ hash: { in: stale } }));
1102
1051
  logger.info(`indexBlockFull: removed ${stale.length} superseded block row(s) at height ${blockData.height}`);
1103
1052
  }
1104
- /**
1105
- * Drop transactions of another fork that hold one of this block's txSeq keys (a lazily indexed
1106
- * tx from a rolled-back block at the same slot); their input/output rows would mix with ours.
1107
- */
1053
+ // Drops transactions of another fork that hold one of this block's txSeq keys.
1054
+ // Their input and output rows would mix with ours.
1108
1055
  async removeStaleTxSeqs(tx, txs) {
1109
1056
  if (!txs.length)
1110
1057
  return;
@@ -1118,10 +1065,8 @@ class CardanoIndexer {
1118
1065
  await (0, transaction_rows_1.deleteTransactionRows)(tx, stale);
1119
1066
  logger.info(`indexBlockFull: removed ${stale.length} transaction(s) of another fork at slot ${txs[0].slot}`);
1120
1067
  }
1121
- /**
1122
- * Warn once when `crawler.certificates` is on but the source reports none (`certificates`
1123
- * undefined, as with Blockfrost). `[]` means "none" and is not a warning.
1124
- */
1068
+ // Warns once when certificates are on but the source does not report them.
1069
+ // An empty array means none and is no warning.
1125
1070
  warnIfCertificatesUnreported(txs) {
1126
1071
  if (this.certificatesUnreportedWarned || !txs.length)
1127
1072
  return;
@@ -1129,14 +1074,11 @@ class CardanoIndexer {
1129
1074
  return;
1130
1075
  this.certificatesUnreportedWarned = true;
1131
1076
  logger.warn('crawler.certificates is enabled but the active source reports no certificates/withdrawals ' +
1132
- '(Blockfrost pagination) — TransactionCertificates/TransactionWithdrawals stay empty until ' +
1077
+ '(Blockfrost pagination). TransactionCertificates/TransactionWithdrawals stay empty until ' +
1133
1078
  'the crawl runs on Ogmios chain-sync or Koios');
1134
1079
  }
1135
- /**
1136
- * Backfill address, amount and datum/script fields of bare chain-sync inputs: from this block's
1137
- * own outputs first, then the UTxO set, then earlier-indexed outputs from the DB. Inputs that
1138
- * already carry an address are skipped.
1139
- */
1080
+ // Fills bare chain-sync inputs from this block's outputs, then the UTxO set, then the DB.
1081
+ // Inputs that already carry an address are skipped.
1140
1082
  async resolveInputs(tx, txs, ledger) {
1141
1083
  // 1. In-memory index of this block's outputs (txHash#outputIndex -> output)
1142
1084
  const blockOutputs = new Map();
@@ -1216,11 +1158,8 @@ class CardanoIndexer {
1216
1158
  input.amount = amt;
1217
1159
  }
1218
1160
  }
1219
- /**
1220
- * Settle the fee of phase-2-invalid transactions (collateral inputs minus collateral return)
1221
- * and the block total. The declared fee is kept when the mapper already set it via
1222
- * `total_collateral` or a collateral input is not indexed locally (the sum would be short).
1223
- */
1161
+ // Fee of a phase-2 failure is collateral inputs minus collateral return. The declared fee
1162
+ // stays when total_collateral set it or a collateral input is not indexed.
1224
1163
  applyCollateralFees(blockData, txs) {
1225
1164
  const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
1226
1165
  let corrected = false;
@@ -1230,11 +1169,11 @@ class CardanoIndexer {
1230
1169
  continue;
1231
1170
  const collateral = (t.inputs ?? []).filter(i => i.isCollateral);
1232
1171
  if (!collateral.length)
1233
- continue; // nothing to derive from — leave the declared fee
1172
+ continue; // nothing to derive from, keep the declared fee
1234
1173
  const unresolved = collateral.find(i => !i.address);
1235
1174
  if (unresolved) {
1236
- logger.warn(`collateral fee for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed ` +
1237
- `— keeping the declared fee ${t.fee}, which understates what the ledger charged`);
1175
+ logger.warn(`collateral fee for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed` +
1176
+ `, keeping the declared fee ${t.fee}, which understates what the ledger charged`);
1238
1177
  continue;
1239
1178
  }
1240
1179
  const consumed = collateral.reduce((sum, i) => sum + lovelaceOf(i.amount), 0n);
@@ -1243,8 +1182,8 @@ class CardanoIndexer {
1243
1182
  .reduce((sum, o) => sum + lovelaceOf(o.amount), 0n);
1244
1183
  const charged = consumed - returned;
1245
1184
  if (charged < 0n) {
1246
- logger.warn(`collateral fee for ${t.hash}: return ${returned} exceeds collateral ${consumed} ` +
1247
- `— keeping the declared fee ${t.fee}`);
1185
+ logger.warn(`collateral fee for ${t.hash}: return ${returned} exceeds collateral ${consumed}` +
1186
+ `, keeping the declared fee ${t.fee}`);
1248
1187
  continue;
1249
1188
  }
1250
1189
  t.fee = charged.toString();
@@ -1254,11 +1193,8 @@ class CardanoIndexer {
1254
1193
  blockData.fees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n).toString();
1255
1194
  }
1256
1195
  }
1257
- /**
1258
- * Mint/burn rows for a block from data in hand: the ledger's mint field when the source
1259
- * reports it (Ogmios, Koios), else Σ outputs − Σ inputs per unit, excluding reference and
1260
- * collateral inputs. A tx with an unresolvable consumed input is skipped and logged.
1261
- */
1196
+ // Uses the ledger's mint field when the source reports it, else outputs minus spent inputs per unit.
1197
+ // A tx with an unresolvable spent input is skipped and logged.
1262
1198
  buildAssetHistoryRows(blockData, txs) {
1263
1199
  const entries = [];
1264
1200
  let skipped = 0;
@@ -1279,8 +1215,8 @@ class CardanoIndexer {
1279
1215
  const consumed = (t.inputs ?? []).filter(i => !i.isReference && !i.isCollateral);
1280
1216
  const unresolved = consumed.find(i => !i.address);
1281
1217
  if (unresolved) {
1282
- logger.warn(`mint delta for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed ` +
1283
- `— skipping, mint/burn of this transaction is not recorded`);
1218
+ logger.warn(`mint delta for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed` +
1219
+ `, skipping, mint/burn of this transaction is not recorded`);
1284
1220
  skipped++;
1285
1221
  continue;
1286
1222
  }
@@ -1315,12 +1251,8 @@ class CardanoIndexer {
1315
1251
  }
1316
1252
  return (0, mappers_1.mapAssetHistory)(entries);
1317
1253
  }
1318
- /**
1319
- * Keep the `Assets` catalogue complete for every unit the crawl meets, without provider calls.
1320
- * `Assets` is temporal, key `(validFrom, unit)`: the bare row's fixed epoch-zero stamp never
1321
- * aliases an enriched slice, so the UPSERT is safe inside the block transaction. The existence
1322
- * check uses the DB-level entity: the service projection's temporal filter hides such rows.
1323
- */
1254
+ // Adds a bare Assets row for every new unit, without provider calls. Its epoch-zero key never hits
1255
+ // an enriched row. The existence check reads the DB entity, because the service view hides such rows.
1324
1256
  async ensureAssetRows(tx, units) {
1325
1257
  if (this.crawlAssetCatalogue === 'off' || !units.size)
1326
1258
  return 0;
@@ -1341,6 +1273,8 @@ class CardanoIndexer {
1341
1273
  if (!missing.length)
1342
1274
  return 0;
1343
1275
  const rows = missing.map(mappers_1.mapBareAsset).filter((r) => r !== null);
1276
+ for (const row of rows)
1277
+ row.decimals = await (0, asset_decimals_1.cip68Decimals)(tx, row.unit);
1344
1278
  // Chunked like the lookup: a mint-storm block can carry thousands of fresh units.
1345
1279
  for (const rowChunk of (0, collections_1.chunk)(rows, collections_1.IN_CHUNK)) {
1346
1280
  await tx.run(UPSERT.into(cardano_1.Assets).entries(rowChunk));
@@ -1359,10 +1293,7 @@ class CardanoIndexer {
1359
1293
  }
1360
1294
  return rows.length;
1361
1295
  }
1362
- /**
1363
- * Remember a unit as present in the catalogue. Insertion-ordered eviction keeps a long
1364
- * backfill's memory flat; losing an entry costs one SELECT, never a wrong write.
1365
- */
1296
+ // Oldest entries are evicted to keep memory flat. A lost entry costs one SELECT, never a wrong write.
1366
1297
  noteAssetSeen(unit) {
1367
1298
  if (this.assetMemo.has(unit))
1368
1299
  return;
@@ -1373,13 +1304,8 @@ class CardanoIndexer {
1373
1304
  }
1374
1305
  this.assetMemo.add(unit);
1375
1306
  }
1376
- /**
1377
- * Snapshot every pool and DRep for an epoch in its OWN transaction (after the block commit), plus
1378
- * one EpochLedgerSnapshots row that marks the epoch as observed. With a block hash and an Ogmios
1379
- * backend the node's ledger state AT that block is read; otherwise Koios reports current state
1380
- * (and the live `Pools` / `Dreps` rows are refreshed). Neither available: no-op.
1381
- * @returns counts written and the source used (null = skipped)
1382
- */
1307
+ // Snapshots all pools and DReps of an epoch in its own transaction after the block commit.
1308
+ // Ogmios reads the ledger at the given block, Koios the current state. Source null means skipped.
1383
1309
  async snapshotEpoch(epoch, at) {
1384
1310
  const epochState = at.hash ? this.client.getEpochStateBackend() : null;
1385
1311
  if (epochState && at.hash)
@@ -1389,7 +1315,7 @@ class CardanoIndexer {
1389
1315
  logger.warn(`epoch ${epoch} snapshot skipped: no backend can read pools/DReps (Ogmios or Koios required)`);
1390
1316
  return { pools: 0, dreps: 0, source: null };
1391
1317
  }
1392
- // Network first, DB second — the provider round-trips must not run with a write lock held.
1318
+ // Network first, DB second, so provider round trips never run under a write lock.
1393
1319
  const [poolData, drepData] = await Promise.all([
1394
1320
  backend.getPoolIds().then(ids => backend.getPools(ids)),
1395
1321
  backend.getDrepIds().then(ids => backend.getDreps(ids)),
@@ -1418,15 +1344,12 @@ class CardanoIndexer {
1418
1344
  logger.info(`epoch ${epoch} snapshot (koios): ${poolSnapshots.length} pools, ${drepSnapshots.length} DReps`);
1419
1345
  return { pools: poolSnapshots.length, dreps: drepSnapshots.length, source: 'koios' };
1420
1346
  }
1421
- /**
1422
- * Epoch snapshot from the node's ledger state at block `at`. The live `Pools` / `Dreps` rows are
1423
- * NOT refreshed: the acquired state may be hours old. `blocksMinted` counts crawled blocks up to
1424
- * `at`, only when the crawl covers the chain since Shelley.
1425
- */
1347
+ // Live Pools and Dreps rows are not refreshed, because the ledger state may be hours old.
1348
+ // blocksMinted is set only when the crawl covers the chain since Shelley.
1426
1349
  async snapshotEpochFromLedger(backend, epoch, at) {
1427
1350
  const state = await backend.epochStateAt({ slot: at.slot, hash: at.hash });
1428
1351
  if (state.epoch !== epoch) {
1429
- logger.warn(`epoch snapshot: ledger at slot ${at.slot} reports epoch ${state.epoch}, crawler dated it ${epoch} — stored as ${epoch}`);
1352
+ logger.warn(`epoch snapshot: ledger at slot ${at.slot} reports epoch ${state.epoch}, crawler dated it ${epoch}, stored as ${epoch}`);
1430
1353
  }
1431
1354
  const minted = await this.crawledBlocksByPool(at.slot);
1432
1355
  const previous = await this.previousLiveStake(epoch);
@@ -1465,10 +1388,8 @@ class CardanoIndexer {
1465
1388
  logger.info(`epoch ${epoch} snapshot (ogmios @ slot ${at.slot}): ${poolSnapshots.length} pools, ${drepSnapshots.length} DReps`);
1466
1389
  return { pools: poolSnapshots.length, dreps: drepSnapshots.length, source: 'ogmios' };
1467
1390
  }
1468
- /**
1469
- * Active stake of epoch E = the stake distribution taken at the E-1 boundary, which is the live
1470
- * stake the Ogmios snapshot of E-1 recorded at its first block. null without that snapshot.
1471
- */
1391
+ // Active stake of epoch E is the live stake in the snapshot of epoch E-1.
1392
+ // Null without that snapshot.
1472
1393
  async previousLiveStake(epoch) {
1473
1394
  const rows = await cds_1.default.db.run(SELECT.from(CardanoODataService_1.PoolEpochSnapshots).columns('poolId', 'liveStake').where({ epoch: epoch - 1, source: 'ogmios' }));
1474
1395
  if (!rows?.length)
@@ -1568,21 +1489,20 @@ class CardanoIndexer {
1568
1489
  async indexAsset(tx, unit) {
1569
1490
  const assetInfo = await this.resolveAssetInfo(tx, unit);
1570
1491
  const assetEntity = (0, mappers_1.mapAsset)(assetInfo, this.client.max_age_ms);
1492
+ assetEntity.decimals = (await (0, asset_decimals_1.cip68Decimals)(tx, unit, assetInfo.initialMintTxHash)) ?? assetInfo.registryDecimals;
1571
1493
  await tx.run(UPSERT.into(CardanoODataService_1.Assets).entries(assetEntity));
1572
1494
  return assetEntity;
1573
1495
  }
1574
- /**
1575
- * Index mint/burn history for an asset, always fresh. Rows are keyed (unit, txHash), so a
1576
- * refetch refreshes the recent cap and older cached entries persist.
1577
- */
1496
+ /** Always fresh. Rows are keyed by unit and tx, so older cached entries persist. */
1578
1497
  async indexAssetHistory(tx, unit, limit = 100) {
1579
1498
  if (this.crawlAssetHistory && await this.crawlAnswers(tx, 'getAssetHistory')) {
1580
- return await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).where({ unit }).orderBy('blockHeight desc').limit(limit));
1499
+ return await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).where({ unit }).orderBy('blockHeight desc', 'txHash desc').limit(limit));
1581
1500
  }
1582
1501
  const events = await this.client.getAssetHistory(unit, limit);
1583
1502
  if (events.length === 0)
1584
1503
  return [];
1585
- const rows = (0, mappers_1.mapAssetHistory)(events);
1504
+ // a provider can list one transaction twice; Postgres refuses an UPSERT that hits a key twice
1505
+ const rows = [...new Map((0, mappers_1.mapAssetHistory)(events).map(r => [`${r.unit}|${r.txHash}`, r])).values()];
1586
1506
  await tx.run(UPSERT.into(CardanoODataService_1.AssetHistory).entries(rows));
1587
1507
  return rows;
1588
1508
  }
@@ -1649,12 +1569,11 @@ class CardanoIndexer {
1649
1569
  async persistTransactionSubmission(tx, params) {
1650
1570
  const { signedTxCbor, txHash, buildId } = params;
1651
1571
  const indexSubmission = (0, mappers_1.mapTransactionSubmission)(signedTxCbor, txHash);
1652
- // status 'pending' until the second phase of the submit flow confirms
1653
1572
  const submissionRecord = {
1654
1573
  ...indexSubmission,
1655
1574
  build_id: buildId || null,
1656
1575
  backendResponse: 'Submitted successfully',
1657
- status: 'pending',
1576
+ status: params.status ?? 'pending',
1658
1577
  };
1659
1578
  await tx.run(INSERT.into(CardanoTransactionService_1.TransactionSubmissions).entries(submissionRecord));
1660
1579
  logger.debug({ submissionId: submissionRecord.id, txHash }, 'Persisted submission record');
@@ -1811,11 +1730,8 @@ class CardanoIndexer {
1811
1730
  const row = await tx.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('slot', 'blockHeight', 'blockHash').where({ hash: txHash }));
1812
1731
  return row ?? null;
1813
1732
  }
1814
- /**
1815
- * Blocks on top of a transaction, its own block included; 0 while it is not on chain.
1816
- * A stored row counts only when its block lies in the crawled chain, because the crawler
1817
- * removes those rows on a rollback. Otherwise height and tip come from the backends.
1818
- */
1733
+ // Confirmations including the tx's own block, 0 while not on chain. A stored row counts only inside
1734
+ // the crawled chain, because the crawler removes those rows on a rollback.
1819
1735
  async resolveTransactionConfirmations(tx, txHash) {
1820
1736
  const crawled = await this.crawledTransactionDepth(tx, txHash);
1821
1737
  if (crawled)
@@ -1856,10 +1772,7 @@ class CardanoIndexer {
1856
1772
  const blockHeight = Number(stored.blockHeight);
1857
1773
  return { blockHeight, tipHeight: Math.max(coverage.tipHeight, blockHeight) };
1858
1774
  }
1859
- /**
1860
- * Ensure a set of transactions is indexed: DB check, batch fetch of the missing ones, UPSERT.
1861
- * @returns provider transactions for the hashes that had to be fetched
1862
- */
1775
+ /** Batch-fetches the missing ones and returns only those. */
1863
1776
  async ensureTransactionsIndexed(tx, txHashes) {
1864
1777
  const unique = [...new Set(txHashes)];
1865
1778
  if (unique.length === 0)
@@ -1882,11 +1795,8 @@ class CardanoIndexer {
1882
1795
  //-----------------------------------------------------------------------------
1883
1796
  // Private Helpers
1884
1797
  //-----------------------------------------------------------------------------
1885
- /**
1886
- * Index the addresses of an account with bounded concurrency. The address data the account
1887
- * carries (from the backend, or from the crawled set) is used as is, so an account costs no
1888
- * request per address; an entry without UTxOs is fetched.
1889
- */
1798
+ // Uses the address data the account carries, so no request per address.
1799
+ // Only an entry without UTxOs is fetched.
1890
1800
  async _ensureAddresses(tx, accountAddresses) {
1891
1801
  const concurrency = CardanoIndexer.ADDR_CONCURRENCY;
1892
1802
  for (let i = 0; i < accountAddresses.length; i += concurrency) {