@odatano/core 2.0.0-rc.44 → 2.0.0-rc.46

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