@odatano/core 2.0.0-rc.2 → 2.0.0-rc.21

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 (138) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +139 -2
  4. package/@cds-models/CardanoIndexerService/index.js +18 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +231 -6
  6. package/@cds-models/CardanoODataService/index.js +27 -0
  7. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  8. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  9. package/@cds-models/odatano/cardano/index.d.ts +323 -6
  10. package/@cds-models/odatano/cardano/index.js +33 -0
  11. package/README.md +195 -136
  12. package/db/schema.cds +2133 -1633
  13. package/package.json +181 -173
  14. package/scripts/migrate-slot-leader.mjs +104 -0
  15. package/scripts/migrate-txseq.mjs +147 -0
  16. package/src/index.d.ts +10 -10
  17. package/src/index.js +24 -14
  18. package/src/plugin.js +39 -52
  19. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  20. package/srv/blockchain/backends/blockfrost-backend.js +45 -158
  21. package/srv/blockchain/backends/cardano-backend.d.ts +83 -158
  22. package/srv/blockchain/backends/cardano-backend.js +14 -5
  23. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  24. package/srv/blockchain/backends/koios-backend.js +293 -203
  25. package/srv/blockchain/backends/ogmios-backend.d.ts +69 -94
  26. package/srv/blockchain/backends/ogmios-backend.js +319 -185
  27. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  28. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  29. package/srv/blockchain/cardano-client.d.ts +57 -204
  30. package/srv/blockchain/cardano-client.js +94 -226
  31. package/srv/blockchain/cardano-indexer.d.ts +176 -240
  32. package/srv/blockchain/cardano-indexer.js +615 -338
  33. package/srv/blockchain/cardano-tx-builder.d.ts +29 -82
  34. package/srv/blockchain/cardano-tx-builder.js +88 -128
  35. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  36. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  37. package/srv/blockchain/crawler/crawler.d.ts +121 -53
  38. package/srv/blockchain/crawler/crawler.js +403 -89
  39. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  40. package/srv/blockchain/crawler/index.d.ts +5 -0
  41. package/srv/blockchain/crawler/index.js +35 -7
  42. package/srv/blockchain/crawler/sync-state.d.ts +44 -28
  43. package/srv/blockchain/crawler/sync-state.js +115 -43
  44. package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
  45. package/srv/blockchain/crawler/utxo-set-import.js +269 -0
  46. package/srv/blockchain/ledger-state.d.ts +80 -0
  47. package/srv/blockchain/ledger-state.js +383 -0
  48. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  49. package/srv/blockchain/signing/cose-verifier.js +6 -12
  50. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  51. package/srv/blockchain/signing/external-signer.js +19 -122
  52. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  53. package/srv/blockchain/signing/hsm-signer.js +23 -63
  54. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  55. package/srv/blockchain/signing/signature-verifier.js +13 -54
  56. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  57. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  58. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
  59. package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
  60. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  61. package/srv/blockchain/transaction-rows.d.ts +12 -0
  62. package/srv/blockchain/transaction-rows.js +42 -0
  63. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  64. package/srv/blockchain/wallet-worker/build-request.js +39 -23
  65. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  66. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  67. package/srv/blockchain/wallet-worker/index.js +2 -8
  68. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  69. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  70. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  71. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  72. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  73. package/srv/blockchain/wallet-worker/signers.js +3 -8
  74. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  75. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  76. package/srv/cardano-agent-service.cds +146 -0
  77. package/srv/cardano-agent-service.d.ts +2 -0
  78. package/srv/cardano-agent-service.js +12 -0
  79. package/srv/cardano-indexer-service.cds +164 -73
  80. package/srv/cardano-indexer-service.js +156 -11
  81. package/srv/cardano-service.cds +45 -0
  82. package/srv/cardano-service.js +38 -96
  83. package/srv/cardano-sign-service.cds +200 -180
  84. package/srv/cardano-sign-service.js +55 -173
  85. package/srv/cardano-tx-service.cds +32 -26
  86. package/srv/cardano-tx-service.js +136 -196
  87. package/srv/cardano-worker-service.js +7 -15
  88. package/srv/server.d.ts +28 -86
  89. package/srv/server.js +95 -128
  90. package/srv/utils/agent-grants-config.d.ts +37 -0
  91. package/srv/utils/agent-grants-config.js +138 -0
  92. package/srv/utils/agent-grants.d.ts +262 -0
  93. package/srv/utils/agent-grants.js +914 -0
  94. package/srv/utils/agent-token-auth.d.ts +16 -0
  95. package/srv/utils/agent-token-auth.js +78 -0
  96. package/srv/utils/backend-request-handler.d.ts +2 -16
  97. package/srv/utils/backend-request-handler.js +3 -18
  98. package/srv/utils/collections.d.ts +4 -8
  99. package/srv/utils/collections.js +4 -8
  100. package/srv/utils/const.d.ts +19 -68
  101. package/srv/utils/const.js +20 -69
  102. package/srv/utils/crypto.d.ts +3 -12
  103. package/srv/utils/crypto.js +5 -18
  104. package/srv/utils/db-indexes.d.ts +25 -0
  105. package/srv/utils/db-indexes.js +93 -0
  106. package/srv/utils/db-sanitize.d.ts +27 -0
  107. package/srv/utils/db-sanitize.js +85 -0
  108. package/srv/utils/epoch-slots.d.ts +13 -0
  109. package/srv/utils/epoch-slots.js +25 -0
  110. package/srv/utils/error-codes.d.ts +18 -73
  111. package/srv/utils/error-codes.js +17 -70
  112. package/srv/utils/errors.d.ts +36 -179
  113. package/srv/utils/errors.js +62 -220
  114. package/srv/utils/liveness.d.ts +16 -0
  115. package/srv/utils/liveness.js +41 -0
  116. package/srv/utils/mappers.d.ts +89 -214
  117. package/srv/utils/mappers.js +289 -301
  118. package/srv/utils/network-context.js +2 -11
  119. package/srv/utils/pg-order-nulls.d.ts +14 -0
  120. package/srv/utils/pg-order-nulls.js +57 -0
  121. package/srv/utils/plutus-placeholders.d.ts +6 -18
  122. package/srv/utils/plutus-placeholders.js +6 -20
  123. package/srv/utils/rate-limiter.d.ts +46 -0
  124. package/srv/utils/rate-limiter.js +116 -0
  125. package/srv/utils/service-events.d.ts +2 -22
  126. package/srv/utils/service-events.js +3 -23
  127. package/srv/utils/signing-helper.d.ts +3 -18
  128. package/srv/utils/signing-helper.js +10 -32
  129. package/srv/utils/tx-build-helper.d.ts +18 -92
  130. package/srv/utils/tx-build-helper.js +32 -123
  131. package/srv/utils/tx-request-parsers.d.ts +14 -20
  132. package/srv/utils/tx-request-parsers.js +33 -20
  133. package/srv/utils/tx-utils.d.ts +4 -23
  134. package/srv/utils/tx-utils.js +12 -41
  135. package/srv/utils/types.d.ts +114 -169
  136. package/srv/utils/types.js +2 -6
  137. package/srv/utils/validators.d.ts +19 -89
  138. package/srv/utils/validators.js +31 -138
@@ -8,22 +8,27 @@ const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const CardanoODataService_1 = require("#cds-models/CardanoODataService");
9
9
  const CardanoTransactionService_1 = require("#cds-models/CardanoTransactionService");
10
10
  const CardanoSignService_1 = require("#cds-models/CardanoSignService");
11
+ // DB-level entity: the catalogue's existence check must bypass the temporal filter that the
12
+ // service projection carries (see ensureAssetRows).
13
+ const cardano_1 = require("#cds-models/odatano/cardano");
11
14
  const mappers_1 = require("../utils/mappers");
12
15
  const collections_1 = require("../utils/collections");
16
+ const transaction_rows_1 = require("./transaction-rows");
17
+ const ledger_state_1 = require("./ledger-state");
18
+ const sync_state_1 = require("./crawler/sync-state");
19
+ const epoch_slots_1 = require("../utils/epoch-slots");
20
+ const const_1 = require("../utils/const");
13
21
  const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
14
22
  const logger = cds_1.default.log('CardanoIndexer');
23
+ /** Lovelace aggregate from the DB (string, number or null) as an integer string. */
24
+ function lovelaceSum(value) {
25
+ if (value === null || value === undefined || value === '')
26
+ return '0';
27
+ return typeof value === 'number' ? BigInt(Math.trunc(value)).toString() : String(value).split('.')[0];
28
+ }
15
29
  /**
16
- * CardanoIndexer - Indexer for Cardano blockchain data into OData entities
17
- *
18
- * Provides methods to index & manage db consistency for various Cardano blockchain data (transactions, addresses, blocks, epochs, accounts, pools, dreps)
19
- * 1. Fetches data from the configured Cardano data provider via the CardanoClient
20
- * 2. Maps the provider data into corresponding OData entity rows
21
- * 3. Upserts the data rows into the database via CAP transactions
22
- * 4. Ensures referential integrity and consistency across related entities (e.g., addresses in transactions, UTxOs in addresses)
23
- * 5. Returns the indexed entity data for further processing
24
- *
25
- * Each method corresponds to a specific Cardano Entity type and handles the necessary mapping and persistence
26
- * into the corresponding OData entities defined in the CardanoODataService(M1) and CardanoTransactionService(M2) models.
30
+ * Indexes Cardano data into the OData entities: fetches via CardanoClient, maps provider data
31
+ * to entity rows and UPSERTs them inside the caller's CAP transaction.
27
32
  */
28
33
  class CardanoIndexer {
29
34
  client;
@@ -32,22 +37,155 @@ class CardanoIndexer {
32
37
  static CRAWL_EPOCH_REFRESH_MS = 5 * 60 * 1000;
33
38
  static CRAWL_EPOCH_RETRY_MS = 30 * 1000;
34
39
  /**
35
- * Crawler epoch memo. Network reads are refreshed periodically while an epoch is
36
- * live and once more when the next epoch starts, so counters such as block_count,
37
- * fees and lastBlockTime do not remain frozen at their first observed value.
38
- *
39
- * At most the current and immediately previous epoch are retained. The rows are
40
- * intentionally UPSERTed in every block transaction: the caller owns that
41
- * transaction, so an in-memory "persisted" bit cannot know whether its commit later
42
- * succeeded. Repeating one local UPSERT is cheap and remains correct after rollback.
40
+ * Crawler epoch memo: refreshed periodically while an epoch is live and once more when the
41
+ * next one starts; holds at most the current and previous epoch. Rows are UPSERTed in every
42
+ * block transaction because the caller owns the commit.
43
43
  */
44
44
  crawlEpochCache = new Map();
45
45
  crawlEpochCurrent = null;
46
46
  crawlEpochPrevious = null;
47
+ /** Analytics coverage of the crawl path; defaults mirror the crawler config defaults. */
48
+ crawlAssetHistory = true;
49
+ crawlAssetCatalogue = 'bare';
50
+ /** Certificates + withdrawals per block (ledger-state coverage). Opt-in. */
51
+ crawlCertificates = false;
52
+ /** Logged once per process: the active source reports no certificates (Blockfrost). */
53
+ certificatesUnreportedWarned = false;
54
+ /**
55
+ * Crawler-fed ledger state (`crawler.utxoSet`): blocks after `utxoAnchor` are applied to the
56
+ * Ledger* tables; no anchor means configured but inactive.
57
+ */
58
+ crawlUtxoSet = false;
59
+ utxoAnchor = null;
60
+ /** The anchor block was found in the crawled chain (checked once, before the first apply). */
61
+ utxoAnchorVerified = false;
62
+ /**
63
+ * Invalidation decided inside a block transaction; the anchor stays until the crawler confirms
64
+ * the commit (`takeLedgerInvalidation`), so a rolled-back attempt changes nothing.
65
+ */
66
+ ledgerInvalidation = null;
67
+ /** Units known to have an `Assets` row, so a repeat sighting costs no DB round-trip. */
68
+ static ASSET_MEMO_CAP = 200_000;
69
+ assetMemo = new Set();
70
+ /**
71
+ * Background registry enrichment queue (`assetCatalogue: 'enrich'`), drained at a fixed rate
72
+ * outside the block transaction. Above the cap the oldest units are dropped (bare row stays).
73
+ */
74
+ static ENRICH_QUEUE_CAP = 50_000;
75
+ enrichQueue = [];
76
+ enrichTimer = null;
77
+ enrichRate = 2;
78
+ /** Adopt the crawler's coverage settings; the lazy request path never touches these. */
79
+ configureCrawlCoverage(coverage) {
80
+ this.crawlAssetHistory = coverage.assetHistory;
81
+ this.crawlAssetCatalogue = coverage.assetCatalogue;
82
+ this.crawlCertificates = coverage.certificates ?? false;
83
+ this.crawlUtxoSet = coverage.utxoSet ?? false;
84
+ this.enrichRate = coverage.assetEnrichRate ?? this.enrichRate;
85
+ if (coverage.assetCatalogue !== 'enrich')
86
+ this.stopAssetEnrichment();
87
+ }
88
+ /**
89
+ * What the crawled data answers authoritatively: only while a live crawler is at the tip.
90
+ * Every block after `fromSlot` is held; `ledger` = the crawled UTxO set is active.
91
+ */
92
+ async localCoverage(tx) {
93
+ const cursor = await (0, sync_state_1.readCursor)(tx);
94
+ if (!cursor || cursor.syncStatus !== 'synced' || cursor.startSlot == null || !(0, sync_state_1.isCrawlerLeaseActive)(cursor))
95
+ return null;
96
+ return { fromSlot: cursor.startSlot, lastSlot: cursor.lastSlot, ledger: cursor.utxoSet.status === 'active' };
97
+ }
98
+ /**
99
+ * Block counts of a pool from crawled blocks (`slotLeader` = pool id): the current epoch when the
100
+ * crawl covers it from its first slot, the lifetime total when it covers the chain since Shelley.
101
+ */
102
+ async localPoolBlocks(tx, poolId) {
103
+ const coverage = await this.localCoverage(tx);
104
+ if (!coverage)
105
+ return {};
106
+ const network = this.client.network;
107
+ const countSince = async (fromSlot) => {
108
+ const row = await tx.run(SELECT.one.from(CardanoODataService_1.Blocks).columns('count(*) as n').where({ slotLeader: poolId, slot: { '>=': fromSlot } }));
109
+ return Number(row?.n ?? 0);
110
+ };
111
+ const counts = {};
112
+ const epochStart = (0, epoch_slots_1.epochStartSlot)(network, (0, epoch_slots_1.epochOfSlot)(network, coverage.lastSlot));
113
+ if (coverage.fromSlot < epochStart)
114
+ counts.blocksEpoch = await countSince(epochStart);
115
+ if (coverage.fromSlot <= const_1.EPOCH_CONFIG_BY_NETWORK[network].shelleyStartSlot)
116
+ counts.blocksMinted = await countSince(0);
117
+ return counts;
118
+ }
119
+ /** The anchor the imported UTxO set describes (null = ledger mode inactive). */
120
+ setUtxoAnchor(anchor) {
121
+ this.utxoAnchor = anchor;
122
+ this.utxoAnchorVerified = false;
123
+ this.ledgerInvalidation = null;
124
+ }
125
+ /**
126
+ * The imported set describes the chain AT the anchor block, so before the first block past it
127
+ * is applied the cursor (not yet advanced in this transaction) must equal the anchor exactly;
128
+ * otherwise the snapshot was taken on a fork. Skipped once `utxoAppliedSlot` is set.
129
+ */
130
+ async verifyUtxoAnchor(tx, anchor) {
131
+ const cursor = await (0, sync_state_1.readCursor)(tx);
132
+ if (cursor?.utxoSet.appliedSlot != null)
133
+ return true;
134
+ if (cursor && cursor.lastSlot === anchor.slot && (cursor.lastBlockHash ?? '').toLowerCase() === anchor.hash.toLowerCase())
135
+ return true;
136
+ const reason = cursor
137
+ ? `anchor ${anchor.slot}/${anchor.hash} is not the block the crawler followed (cursor ${cursor.lastSlot}/${cursor.lastBlockHash})`
138
+ : `no crawler cursor to verify the anchor ${anchor.slot}/${anchor.hash} against`;
139
+ logger.error(`UTxO set invalidated: ${reason} — the snapshot describes a fork; re-import at the crawler cursor`);
140
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: reason.slice(0, 500) });
141
+ this.ledgerInvalidation = reason;
142
+ return false;
143
+ }
144
+ /** Null while the mode is off, nothing is imported, or an invalidation awaits its commit. */
145
+ getUtxoAnchor() {
146
+ return this.crawlUtxoSet && !this.ledgerInvalidation ? this.utxoAnchor : null;
147
+ }
148
+ /** Hand out a pending invalidation (dropping the anchor) exactly once after the block commit, or null. */
149
+ takeLedgerInvalidation() {
150
+ const reason = this.ledgerInvalidation;
151
+ if (reason) {
152
+ this.ledgerInvalidation = null;
153
+ this.utxoAnchor = null;
154
+ this.utxoAnchorVerified = false;
155
+ }
156
+ return reason;
157
+ }
158
+ /**
159
+ * Drain the enrichment queue at `enrichRate` units per second, one `indexAsset()` per tick in
160
+ * its own transaction. A failing unit is dropped; its bare row stays for the lazy path.
161
+ */
162
+ startAssetEnrichment() {
163
+ if (this.enrichTimer || this.crawlAssetCatalogue !== 'enrich')
164
+ return;
165
+ const intervalMs = Math.max(1, Math.round(1000 / Math.max(1, this.enrichRate)));
166
+ this.enrichTimer = setInterval(() => {
167
+ const unit = this.enrichQueue.shift();
168
+ if (unit === undefined) {
169
+ this.stopAssetEnrichment();
170
+ return;
171
+ }
172
+ void cds_1.default.tx((tx) => this.indexAsset(tx, unit)).catch((err) => {
173
+ logger.debug(`asset enrichment for ${unit} failed (bare row kept):`, err);
174
+ });
175
+ }, intervalMs);
176
+ this.enrichTimer.unref?.();
177
+ }
178
+ /** Stop the enrichment loop and forget what is still queued (shutdown, crawler halt, mode change). */
179
+ stopAssetEnrichment() {
180
+ if (this.enrichTimer) {
181
+ clearInterval(this.enrichTimer);
182
+ this.enrichTimer = null;
183
+ }
184
+ this.enrichQueue = [];
185
+ }
47
186
  /**
48
- * Network-only epoch prefetch for the crawler. Call BEFORE opening the per-block
49
- * write transaction — the backend round-trip must never run while the DB write
50
- * lock is held (indexBlockFull then serves the epoch from this memo). Never throws.
187
+ * Network-only epoch prefetch for the crawler. Call BEFORE opening the per-block write
188
+ * transaction so no backend round-trip runs under the DB write lock. Never throws.
51
189
  */
52
190
  async prefetchCrawlEpoch(epochNumber) {
53
191
  const previousEpoch = this.crawlEpochCurrent;
@@ -81,85 +219,108 @@ class CardanoIndexer {
81
219
  return;
82
220
  if (!force && existing && now < existing.nextRefreshAt)
83
221
  return;
222
+ const crawled = await this.crawledEpochTotals(epochNumber);
84
223
  try {
85
- const row = (0, mappers_1.mapEpoch)(await this.client.getEpoch(epochNumber));
224
+ const provided = (0, mappers_1.mapEpoch)(await this.client.getEpoch(epochNumber));
86
225
  this.crawlEpochCache.set(epochNumber, {
87
- row,
226
+ row: crawled ? { ...provided, ...crawled } : provided,
88
227
  nextRefreshAt: now + CardanoIndexer.CRAWL_EPOCH_REFRESH_MS,
89
228
  finalized,
90
229
  });
91
230
  }
92
231
  catch {
93
- // Keep the last good snapshot, but retry transient/negative results soon rather
94
- // than suppressing enrichment for the rest of the five-day epoch.
232
+ // Keep the last good snapshot (or the crawled totals alone), but retry transient/negative
233
+ // results soon rather than suppressing enrichment for the rest of the five-day epoch.
234
+ const base = existing?.row ?? (crawled ? this.bareEpochRow(epochNumber) : undefined);
95
235
  this.crawlEpochCache.set(epochNumber, {
96
- row: existing?.row,
236
+ row: base && crawled ? { ...base, ...crawled } : base,
97
237
  nextRefreshAt: now + CardanoIndexer.CRAWL_EPOCH_RETRY_MS,
98
238
  finalized: false,
99
239
  });
100
240
  }
101
241
  }
102
242
  /**
103
- * Create a new CardanoIndexer instance
104
- * @param client - The CardanoClient instance for blockchain queries
105
- * @param txBuilder - The CardanoTransactionBuilder instance for transaction building
243
+ * Block, transaction and fee totals of an epoch summed over the crawled blocks, when the crawl
244
+ * covers the epoch from its first slot; null otherwise. Output and active stake stay with the backend.
106
245
  */
246
+ async crawledEpochTotals(epochNumber) {
247
+ try {
248
+ const cursor = await (0, sync_state_1.readCursor)(cds_1.default.db);
249
+ if (cursor?.startSlot == null || cursor.startSlot >= (0, epoch_slots_1.epochStartSlot)(this.client.network, epochNumber))
250
+ return null;
251
+ const row = await cds_1.default.db.run(SELECT.one.from(CardanoODataService_1.Blocks)
252
+ .columns('count(*) as blockCount', 'sum(txCount) as txCount', 'sum(fees) as fees', 'min(time) as firstBlockTime', 'max(time) as lastBlockTime')
253
+ .where({ epochNumber }));
254
+ if (!row || Number(row.blockCount ?? 0) === 0)
255
+ return null;
256
+ return {
257
+ blockCount: Number(row.blockCount),
258
+ txCount: Number(row.txCount ?? 0),
259
+ fees: lovelaceSum(row.fees),
260
+ firstBlockTime: row.firstBlockTime != null ? Number(row.firstBlockTime) : null,
261
+ lastBlockTime: row.lastBlockTime != null ? Number(row.lastBlockTime) : null,
262
+ };
263
+ }
264
+ catch (err) {
265
+ logger.debug(`Crawled totals for epoch ${epochNumber} unavailable:`, err);
266
+ return null;
267
+ }
268
+ }
269
+ /** Epoch row with only the slot-derived bounds, for an epoch the backend cannot describe. */
270
+ bareEpochRow(epochNumber) {
271
+ const network = this.client.network;
272
+ const start = (0, epoch_slots_1.epochStartSlot)(network, epochNumber);
273
+ return {
274
+ epoch: epochNumber,
275
+ startTime: (0, epoch_slots_1.slotToPosixSeconds)(network, start),
276
+ endTime: (0, epoch_slots_1.slotToPosixSeconds)(network, (0, epoch_slots_1.epochStartSlot)(network, epochNumber + 1)),
277
+ output: null,
278
+ activeStake: null,
279
+ };
280
+ }
107
281
  constructor(client, txBuilder) {
108
282
  this.client = client;
109
283
  this.txBuilder = txBuilder;
110
284
  logger.info('CardanoIndexer instance created');
111
285
  }
112
286
  /**
113
- * Index & return a single transaction with inputs/outputs/assets/UTxOs/addresses
114
- * All UPSERTs execute within the same CAP transaction (cds.tx), which ensures
115
- * atomicity: either all entities are persisted or none are (automatic rollback on error).
116
- * @param tx CAP transaction (cds.tx(req))
117
- * @param txHash Cardano transaction hash (hex)
118
- * @returns {Promise<CardanoTransaction>} transaction entity data
287
+ * Index a transaction with inputs/outputs/assets/metadata; all UPSERTs run in the caller's
288
+ * transaction, so either everything persists or nothing does.
119
289
  */
120
290
  async indexTransaction(tx, txHash) {
121
- // getting data from cardano data provider
122
291
  const providerTx = await this.client.getTransaction(txHash);
123
292
  const txRow = (0, mappers_1.mapTransaction)(providerTx);
124
293
  await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRow));
125
294
  logger.debug(`indexTransaction: upserted transaction ${txHash}`);
295
+ await this.writeTransactionChildren(tx, providerTx, txRow.txSeq);
296
+ return txRow;
297
+ }
298
+ /** Lazy path: inputs, outputs, their assets and metadata of one transaction. */
299
+ async writeTransactionChildren(tx, providerTx, txSeq) {
126
300
  if (providerTx.inputs) {
127
- // Inputs + InputAssets
128
- const inputRows = (0, mappers_1.mapTransactionInputs)(txHash, providerTx.inputs);
129
- const inputAssetRows = (0, mappers_1.mapTransactionInputAssets)(txHash, providerTx.inputs);
130
- if (inputRows.length) {
301
+ const inputRows = (0, mappers_1.mapTransactionInputs)(txSeq, providerTx.inputs);
302
+ const inputAssetRows = (0, mappers_1.mapTransactionInputAssets)(txSeq, providerTx.inputs);
303
+ if (inputRows.length)
131
304
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputs).entries(inputRows));
132
- logger.debug(`indexTransaction: upserted ${inputRows.length} transaction inputs for ${txHash}`);
133
- }
134
- if (inputAssetRows.length) {
305
+ if (inputAssetRows.length)
135
306
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputAssets).entries(inputAssetRows));
136
- logger.debug(`indexTransaction: upserted ${inputAssetRows.length} transaction input assets for ${txHash}`);
137
- }
138
307
  }
139
- // Outputs + OutputAssets — independent of inputs (a tx with empty/missing
140
- // `inputs` previously skipped its outputs entirely)
308
+ // outputs must not depend on the inputs branch
141
309
  if (providerTx.outputs) {
142
- const outputRows = (0, mappers_1.mapTransactionOutputs)(txHash, providerTx.outputs);
143
- const outputAssetRows = (0, mappers_1.mapTransactionOutputAssets)(txHash, providerTx.outputs);
144
- if (outputRows.length) {
310
+ const outputRows = (0, mappers_1.mapTransactionOutputs)(txSeq, providerTx.outputs);
311
+ const outputAssetRows = (0, mappers_1.mapTransactionOutputAssets)(txSeq, providerTx.outputs);
312
+ if (outputRows.length)
145
313
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputs).entries(outputRows));
146
- }
147
- if (outputAssetRows.length) {
314
+ if (outputAssetRows.length)
148
315
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
149
- }
150
316
  }
151
317
  const metadataRows = (0, mappers_1.mapTransactionMetadata)(providerTx.metadata || []);
152
- if (metadataRows.length) {
318
+ if (metadataRows.length)
153
319
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
154
- }
155
- return txRow;
156
320
  }
157
321
  /**
158
- * Index & return address data with assets and UTxOs (without transactions)
159
- * Transactions are loaded separately via indexAddressTransactions() for better performance
160
- * @param tx CAP transaction
161
- * @param addr bech32 address
162
- * @return {Promise<Address>} address entity data
322
+ * Index address data with assets and UTxOs; transactions are loaded separately via
323
+ * indexAddressTransactions().
163
324
  */
164
325
  async indexAddress(tx, addr) {
165
326
  const addrData = await this.client.getAddress(addr);
@@ -169,8 +330,7 @@ class CardanoIndexer {
169
330
  const validFrom = AddrEntity.validFrom ?? now;
170
331
  const validTo = AddrEntity.validTo ?? now;
171
332
  await tx.run(UPSERT.into(CardanoODataService_1.Addresses).entries(AddrEntity));
172
- // Also insert child entities for new address
173
- // Supplement address-level amounts with assets found in UTxOs but missing from addresses endpoint
333
+ // Supplement address-level amounts with assets only present in UTxOs
174
334
  const addressAssetUnits = new Set(addrData.amount.filter(a => a.unit !== 'lovelace').map(a => a.unit));
175
335
  for (const utxo of addrData.utxos) {
176
336
  for (const amt of utxo.amount) {
@@ -220,17 +380,8 @@ class CardanoIndexer {
220
380
  return AddrEntity;
221
381
  }
222
382
  /**
223
- * Index UTxOs by 28-byte payment credential. Always-fresh fetch from Koios
224
- * (bypasses cache) — credential queries serve dApp-state use cases that require
225
- * current data. Underlying AddressUTxOs/UTxOAssets rows are UPSERTed and stay
226
- * available for follow-up address-keyed queries within the TTL.
227
- *
228
- * Does NOT upsert parent Addresses rows; child rows reference bech32 addresses
229
- * that may not yet have a parent stub. Same pattern as TransactionInputs.
230
- *
231
- * @param tx CAP transaction
232
- * @param credHash 28-byte payment credential as 56-char lowercase hex
233
- * @return UTxO entity rows across all bech32 addresses sharing the credential
383
+ * Index UTxOs by 28-byte payment credential (56-char hex), always fresh from Koios. Child
384
+ * rows are UPSERTed without a parent Addresses row (same pattern as TransactionInputs).
234
385
  */
235
386
  async indexCredentialUtxos(tx, credHash) {
236
387
  const utxos = await this.client.getCredentialUtxos(credHash);
@@ -271,17 +422,8 @@ class CardanoIndexer {
271
422
  return allRows;
272
423
  }
273
424
  /**
274
- * Index ONLY the UTxOs at a bech32 address via getAddressUtxos — deliberately
275
- * WITHOUT a getAddress (address-detail) call, so it works on backends that serve
276
- * the live UTxO set but not address aggregation (e.g. Ogmios). Used as the
277
- * GetUTxOsByAddress fallback when no configured backend supports getAddress.
278
- *
279
- * Does NOT upsert a parent Addresses row (same pattern as indexCredentialUtxos);
280
- * AddressUTxOs/UTxOAssets reference the bech32 address directly.
281
- *
282
- * @param tx CAP transaction
283
- * @param addr bech32 address
284
- * @return UTxO entity rows for the address (empty when the address holds none)
425
+ * Index only the UTxOs of an address via getAddressUtxos (no getAddress call), so it works on
426
+ * backends without address aggregation such as Ogmios. Writes no parent Addresses row.
285
427
  */
286
428
  async indexAddressUtxos(tx, addr) {
287
429
  const utxos = await this.client.getAddressUtxos(addr);
@@ -307,21 +449,9 @@ class CardanoIndexer {
307
449
  return utxoEntities;
308
450
  }
309
451
  /**
310
- * Evict cached rows a submitted transaction made stale, so the next read
311
- * refetches instead of serving spent UTxOs for up to indexTtlMs:
312
- * - every consumed input ref (spent under WHATEVER address cached it),
313
- * - all address-level rows of the output addresses (their UTxO set gained
314
- * the new outputs — sender change included) and of `extraAddresses`
315
- * (e.g. the build's sender when the CBOR could not be parsed).
316
- *
317
- * Only the read cache is touched; submissions/builds stay untouched. Note the
318
- * next refetch may STILL see pre-submit state on lagging backends
319
- * (Blockfrost/Koios propagation) — that matches cache-less behaviour and is
320
- * not recoverable server-side.
321
- *
322
- * @param tx CAP transaction
323
- * @param targets input refs + output addresses from extractTxCacheTargets
324
- * @param extraAddresses additional bech32 addresses to evict
452
+ * Evict cached rows a submitted transaction made stale: every consumed input ref (under any
453
+ * address) and all address-level rows of the output addresses plus `extraAddresses`. Only the
454
+ * read cache is touched; lagging backends may still serve pre-submit state on refetch.
325
455
  */
326
456
  async invalidateUtxoCacheForTx(tx, targets, extraAddresses = []) {
327
457
  const addresses = [...new Set([...targets.outputAddresses, ...extraAddresses])];
@@ -339,21 +469,15 @@ class CardanoIndexer {
339
469
  logger.debug(`Invalidated UTxO cache: ${addresses.length} address(es), ${targets.inputs.length} spent input ref(s)`);
340
470
  }
341
471
  }
342
- /**
343
- * Index & return address transactions (separate from indexAddress for lazy loading)
344
- * @param tx CAP transaction
345
- * @param addr bech32 address
346
- * @param limit maximum number of transactions to fetch
347
- * @return {Promise<AddressTransactions[]>} address transaction entities
348
- */
472
+ /** Index address transactions (separate from indexAddress for lazy loading). */
349
473
  async indexAddressTransactions(tx, addr, limit) {
350
474
  logger.debug(`indexAddressTransactions: fetching transactions for ${addr}`);
351
- // Layer 4: Hash-only listing (lightweight, 1 API call)
475
+ // Hash-only listing (one API call)
352
476
  const txHashes = await this.client.getAddressTransactionHashes(addr, limit);
353
477
  logger.debug(`indexAddressTransactions: found ${txHashes.length} tx hashes for ${addr}`);
354
478
  if (txHashes.length === 0)
355
479
  return [];
356
- // Layer 3: DB-first dedup + batch fetch
480
+ // DB-first dedup + batch fetch
357
481
  const batchFetched = await this.ensureTransactionsIndexed(tx, txHashes);
358
482
  // For address-transaction mapping we need full provider tx data (inputs/outputs for net amounts).
359
483
  // Transactions already in DB were not re-fetched — batch-fetch those separately.
@@ -387,41 +511,21 @@ class CardanoIndexer {
387
511
  transactionsEntities.sort((a, b) => (b.blockTime ?? 0) - (a.blockTime ?? 0));
388
512
  return transactionsEntities;
389
513
  }
390
- /**
391
- * Index & return address signing request association
392
- * Links an address to a signing request for address-based queries
393
- * @param tx CAP transaction
394
- * @param addr bech32 address
395
- * @param signingRequestId signing request UUID
396
- * @return {Promise<void>}
397
- */
514
+ /** Link an address to a signing request for address-based queries. */
398
515
  async indexAddressSigningRequests(tx, addr, signingRequestId) {
399
516
  logger.debug(`indexAddressSigningRequests: linking address ${addr} to signing request ${signingRequestId}`);
400
517
  const addressSigningRequestEntity = (0, mappers_1.mapAddressSigningRequest)(addr, signingRequestId);
401
518
  await tx.run(UPSERT.into(CardanoSignService_1.AddressSigningRequests).entries(addressSigningRequestEntity));
402
519
  logger.debug(`indexAddressSigningRequests: linked address ${addr} to signing request ${signingRequestId}`);
403
520
  }
404
- /**
405
- * Index & return address transaction build association
406
- * Links an address to a transaction build for address-based queries
407
- * @param tx CAP transaction
408
- * @param addr bech32 address
409
- * @param buildId transaction build UUID
410
- * @return {Promise<void>}
411
- */
521
+ /** Link an address to a transaction build for address-based queries. */
412
522
  async indexAddressTransactionBuilds(tx, addr, buildId) {
413
523
  logger.debug(`indexAddressTransactionBuilds: linking address ${addr} to build ${buildId}`);
414
524
  const addressTransactionBuildEntity = (0, mappers_1.mapAddressTransactionBuild)(addr, buildId);
415
525
  await tx.run(UPSERT.into(CardanoTransactionService_1.AddressTransactionBuilds).entries(addressTransactionBuildEntity));
416
526
  logger.debug(`indexAddressTransactionBuilds: linked address ${addr} to build ${buildId}`);
417
527
  }
418
- /**
419
- * Index & return metadata for a single transaction (Metadata)
420
- * @param tx CAP transaction
421
- * @param txHash transaction hash
422
- * @param metadata raw metadata object (label -> JSONValue)
423
- * @return {Promise<TransactionMetadata[]>} array of transaction metadata rows
424
- */
528
+ /** Index the metadata rows of a transaction. */
425
529
  async indexTransactionMetadata(tx, tx_hash) {
426
530
  const metadata = await this.client.getTransactionMetadata(tx_hash);
427
531
  const rows = (0, mappers_1.mapTransactionMetadata)(metadata);
@@ -430,23 +534,17 @@ class CardanoIndexer {
430
534
  }
431
535
  return rows;
432
536
  }
433
- /**
434
- * Index & return the network information data
435
- * @param tx CAP transaction object
436
- * @returns {Promise<NetworkInformation>} network information entity data
437
- */
537
+ /** Index the network information; circulating supply comes from the crawled UTxO set when it is current. */
438
538
  async indexNetworkInformation(tx) {
439
539
  const netInfo = await this.client.getNetworkInformation();
440
- const netEntity = (0, mappers_1.mapNetworkInfo)(netInfo, this.client.max_age_ms, this.client.network);
540
+ const circulating = (await this.localCoverage(tx))?.ledger
541
+ ? lovelaceSum((await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAddresses).columns('sum(totalLovelace) as total')))?.total)
542
+ : null;
543
+ const netEntity = (0, mappers_1.mapNetworkInfo)(circulating === null ? netInfo : { ...netInfo, supply: { ...netInfo.supply, circulating } }, this.client.max_age_ms, this.client.network);
441
544
  await tx.run(UPSERT.into(CardanoODataService_1.NetworkInformation).entries(netEntity));
442
545
  return netEntity;
443
546
  }
444
- /**
445
- * Index & return the block information data
446
- * @param tx CAP transaction object
447
- * @param blockHash block hash (hex)
448
- * @returns {Promise<Block>} block entity data
449
- */
547
+ /** Index a block by hash, with best-effort epoch enrichment. */
450
548
  async indexBlock(tx, blockHash) {
451
549
  const blockInfo = await this.client.getBlock(blockHash);
452
550
  let epoch;
@@ -461,28 +559,13 @@ class CardanoIndexer {
461
559
  return blockEntity;
462
560
  }
463
561
  /**
464
- * Bulk-index a whole block and all of its transactions in ONE pass (chain crawler,
465
- * v2.0). Unlike indexTransaction()/indexBlock() this does NOT re-fetch per hash — the
466
- * crawler already carries the block + full tx list from the stream/page. Rows are
467
- * accumulated across the block's txs and UPSERTed once per table (few statements).
468
- *
469
- * All writes run inside the caller's CAP transaction (`tx`), so a block is persisted
470
- * atomically — a failure mid-block rolls the whole block back, keeping the cursor and
471
- * the data consistent.
472
- *
473
- * Inputs from the Ogmios chain-sync path arrive as bare references (no address/amount);
474
- * resolveInputs() backfills them from this block's own outputs and previously-indexed
475
- * outputs before mapping. Blockfrost/Koios inputs already carry address/amount and are
476
- * left untouched.
477
- *
478
- * @param tx CAP transaction (one per block, committed by the crawler)
479
- * @param blockData block header/summary from the crawler source
480
- * @param txs the block's full transaction list (in block order)
562
+ * Bulk-index a whole block and its transactions in one pass for the crawler: no per-hash
563
+ * re-fetch, one UPSERT per table, all inside the caller's transaction so the block persists
564
+ * atomically. Bare chain-sync inputs are backfilled by resolveInputs() first.
481
565
  */
482
566
  async indexBlockFull(tx, blockData, txs) {
483
- // Block row — best-effort epoch enrichment from the prefetched memo. The network
484
- // fetch happens in prefetchCrawlEpoch() BEFORE the caller opened this write tx;
485
- // if the caller skipped it, resolve now (memoized) and accept the in-tx fetch.
567
+ // Epoch from the prefetched memo; if the caller skipped prefetchCrawlEpoch, resolve now
568
+ // (memoized) and accept the in-tx fetch.
486
569
  let epoch;
487
570
  if (blockData.epoch != null) {
488
571
  await this.prefetchCrawlEpoch(blockData.epoch);
@@ -493,16 +576,35 @@ class CardanoIndexer {
493
576
  if (epochRows.length)
494
577
  await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries(epochRows));
495
578
  }
496
- await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
497
- // Backfill chain-sync inputs (empty address/amount) from local outputs
579
+ // Backfill chain-sync inputs (empty address/amount) from local outputs, then settle
580
+ // the fee of any phase-2 failure. Both run before the block row is written, because a
581
+ // corrected fee changes the block's fee total.
498
582
  await this.resolveInputs(tx, txs);
499
- // Accumulate rows across the whole block, then one bulk UPSERT per table
583
+ this.applyCollateralFees(blockData, txs);
584
+ await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
585
+ await this.removeSupersededBlocks(tx, blockData);
586
+ await this.removeStaleTxSeqs(tx, txs);
587
+ // One bulk UPSERT per table. NUL safety for PostgreSQL is enforced by the db-level hook in
588
+ // srv/utils/db-sanitize.ts, not per call site.
500
589
  const txRows = txs.map(t => (0, mappers_1.mapTransaction)(t));
501
- const inputRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputs)(t.hash, t.inputs ?? []));
502
- const inputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputAssets)(t.hash, t.inputs ?? []));
503
- const outputRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputs)(t.hash, t.outputs ?? []));
504
- const outputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputAssets)(t.hash, t.outputs ?? []));
590
+ const inputRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputs)((0, mappers_1.txSeqOf)(t.slot, t.index), t.inputs ?? []));
591
+ const inputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputAssets)((0, mappers_1.txSeqOf)(t.slot, t.index), t.inputs ?? []));
592
+ const outputRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputs)((0, mappers_1.txSeqOf)(t.slot, t.index), t.outputs ?? []));
593
+ const outputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputAssets)((0, mappers_1.txSeqOf)(t.slot, t.index), t.outputs ?? []));
505
594
  const metadataRows = txs.flatMap(t => (0, mappers_1.mapTransactionMetadata)(t.metadata ?? []));
595
+ // Certificates + withdrawals are keyed (tx, certIndex, kind) / (tx, stakeAddress), so a
596
+ // re-crawl is idempotent and a reorg removes them with their tx.
597
+ const certificateRows = this.crawlCertificates
598
+ ? txs.flatMap(t => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? []))
599
+ : [];
600
+ const withdrawalRows = this.crawlCertificates
601
+ ? txs.flatMap(t => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? []))
602
+ : [];
603
+ if (this.crawlCertificates)
604
+ this.warnIfCertificatesUnreported(txs);
605
+ // Mint/burn is derived from rows already in hand — keyed (unit, txHash), so a re-crawl is
606
+ // idempotent and a reorg removes these rows with their transactions (crawler handleReorg).
607
+ const assetHistoryRows = this.crawlAssetHistory ? this.buildAssetHistoryRows(blockData, txs) : [];
506
608
  if (txRows.length)
507
609
  await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRows));
508
610
  if (inputRows.length)
@@ -515,13 +617,88 @@ class CardanoIndexer {
515
617
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
516
618
  if (metadataRows.length)
517
619
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
518
- logger.debug(`indexBlockFull: block ${blockData.hash} — ${txs.length} txs, ${outputRows.length} outputs`);
620
+ if (certificateRows.length)
621
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionCertificates).entries(certificateRows));
622
+ if (withdrawalRows.length)
623
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionWithdrawals).entries(withdrawalRows));
624
+ // Ledger state (crawler.utxoSet): only blocks AFTER the anchor the imported set describes;
625
+ // same transaction, so the UTxO set can never be a block ahead of or behind the cursor.
626
+ if (this.crawlUtxoSet && this.utxoAnchor && (blockData.slot ?? 0) > this.utxoAnchor.slot) {
627
+ if (this.ledgerInvalidation) {
628
+ // Decided in an earlier attempt of this block whose transaction rolled back: re-write
629
+ // the verdict so whichever attempt commits carries it; nothing is applied meanwhile.
630
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: this.ledgerInvalidation.slice(0, 500) });
631
+ }
632
+ else if (this.utxoAnchorVerified || (this.utxoAnchorVerified = await this.verifyUtxoAnchor(tx, this.utxoAnchor))) {
633
+ const ledger = await (0, ledger_state_1.applyBlockToLedger)(tx, blockData, txs);
634
+ if (ledger.missing) {
635
+ logger.warn(`ledger: block ${blockData.hash} consumed ${ledger.missing} outpoint(s) with no open row — ` +
636
+ 'the set is incomplete relative to the crawl (snapshot gap?); balances of those addresses drift');
637
+ }
638
+ }
639
+ }
640
+ if (assetHistoryRows.length)
641
+ await tx.run(UPSERT.into(CardanoODataService_1.AssetHistory).entries(assetHistoryRows));
642
+ // Catalogue last; collecting the units is skipped entirely when the catalogue is off.
643
+ const newAssets = this.crawlAssetCatalogue === 'off'
644
+ ? 0
645
+ : await this.ensureAssetRows(tx, this.collectBlockUnits(txs, assetHistoryRows));
646
+ logger.debug(`indexBlockFull: block ${blockData.hash} — ${txs.length} txs, ${outputRows.length} outputs, ` +
647
+ `${assetHistoryRows.length} mint/burn, ${newAssets} new assets`);
648
+ }
649
+ /**
650
+ * Drop other Block rows at the crawled block's height that no transaction references: lazily
651
+ * indexed tips that were rolled back, which no crawler reorg covers.
652
+ */
653
+ async removeSupersededBlocks(tx, blockData) {
654
+ if (blockData.height == null)
655
+ return;
656
+ const others = await tx.run(SELECT.from(CardanoODataService_1.Blocks).columns('hash').where({ height: blockData.height, hash: { '!=': blockData.hash } }));
657
+ if (!others?.length)
658
+ return;
659
+ const hashes = others.map(r => r.hash);
660
+ const referenced = await tx.run(SELECT.distinct.from(CardanoODataService_1.Transactions).columns('blockHash').where({ blockHash: { in: hashes } }));
661
+ const keep = new Set((referenced ?? []).map(r => r.blockHash));
662
+ const stale = hashes.filter(h => !keep.has(h));
663
+ if (!stale.length)
664
+ return;
665
+ await tx.run(DELETE.from(CardanoODataService_1.Blocks).where({ hash: { in: stale } }));
666
+ logger.info(`indexBlockFull: removed ${stale.length} superseded block row(s) at height ${blockData.height}`);
667
+ }
668
+ /**
669
+ * Drop transactions of another fork that hold one of this block's txSeq keys (a lazily indexed
670
+ * tx from a rolled-back block at the same slot); their input/output rows would mix with ours.
671
+ */
672
+ async removeStaleTxSeqs(tx, txs) {
673
+ if (!txs.length)
674
+ return;
675
+ const seqs = txs.map(t => (0, mappers_1.txSeqOf)(t.slot, t.index));
676
+ const rows = await tx.run(SELECT.from(CardanoODataService_1.Transactions).columns('hash', 'txSeq')
677
+ .where({ txSeq: { between: Math.min(...seqs), and: Math.max(...seqs) } }));
678
+ const ours = new Set(txs.map(t => t.hash));
679
+ const stale = (rows ?? []).filter(r => !ours.has(r.hash));
680
+ if (!stale.length)
681
+ return;
682
+ await (0, transaction_rows_1.deleteTransactionRows)(tx, stale);
683
+ logger.info(`indexBlockFull: removed ${stale.length} transaction(s) of another fork at slot ${txs[0].slot}`);
519
684
  }
520
685
  /**
521
- * Backfill input address/amount for chain-sync transactions whose inputs are bare
522
- * references. Resolves first from this block's own outputs (a tx may spend an earlier
523
- * tx's output in the same block), then batch-reads previously-indexed outputs from the
524
- * DB. Inputs that already carry an address (Blockfrost/Koios) are skipped.
686
+ * Warn once when `crawler.certificates` is on but the source reports none (`certificates`
687
+ * undefined, as with Blockfrost). `[]` means "none" and is not a warning.
688
+ */
689
+ warnIfCertificatesUnreported(txs) {
690
+ if (this.certificatesUnreportedWarned || !txs.length)
691
+ return;
692
+ if (txs.some(t => t.certificates !== undefined))
693
+ return;
694
+ this.certificatesUnreportedWarned = true;
695
+ logger.warn('crawler.certificates is enabled but the active source reports no certificates/withdrawals ' +
696
+ '(Blockfrost pagination) — TransactionCertificates/TransactionWithdrawals stay empty until ' +
697
+ 'the crawl runs on Ogmios chain-sync or Koios');
698
+ }
699
+ /**
700
+ * Backfill address/amount of bare chain-sync inputs: from this block's own outputs first,
701
+ * then earlier-indexed outputs from the DB. Inputs that already carry an address are skipped.
525
702
  */
526
703
  async resolveInputs(tx, txs) {
527
704
  // 1. In-memory index of this block's outputs (txHash#outputIndex -> {address, amount})
@@ -550,22 +727,26 @@ class CardanoIndexer {
550
727
  }
551
728
  if (!unresolved.length)
552
729
  return;
553
- // 3. Batch-read prior-block outputs from the DB — chunked so a dense block's
554
- // input set can never exceed a driver's bind-variable cap (same IN_CHUNK
555
- // discipline as the crawler's reorg deletes)
730
+ // 3. Batch-read prior-block outputs from the DB, chunked so a dense block's input set
731
+ // never exceeds a driver's bind-variable cap
556
732
  const sourceHashes = [...new Set(unresolved.map(u => u.input.txHash))];
733
+ const hashBySeq = new Map();
734
+ for (const k of await (0, transaction_rows_1.readTxKeys)(tx, sourceHashes)) {
735
+ if (k.txSeq != null)
736
+ hashBySeq.set((0, transaction_rows_1.seqKey)(k.txSeq), k.hash);
737
+ }
557
738
  const addrByKey = new Map();
558
739
  const amtByKey = new Map();
559
- for (const hashChunk of (0, collections_1.chunk)(sourceHashes, collections_1.IN_CHUNK)) {
740
+ for (const seqChunk of (0, collections_1.chunk)([...hashBySeq.keys()].map(Number), collections_1.IN_CHUNK)) {
560
741
  const [outRows, assetRows] = await Promise.all([
561
- tx.run(SELECT.from(CardanoODataService_1.TransactionOutputs).where({ tx_hash: { in: hashChunk } })),
562
- tx.run(SELECT.from(CardanoODataService_1.TransactionOutputAssets).where({ output_tx_hash: { in: hashChunk } })),
742
+ tx.run(SELECT.from(CardanoODataService_1.TransactionOutputs).where({ txSeq: { in: seqChunk } })),
743
+ tx.run(SELECT.from(CardanoODataService_1.TransactionOutputAssets).where({ output_txSeq: { in: seqChunk } })),
563
744
  ]);
564
745
  for (const r of outRows) {
565
- addrByKey.set(`${r.tx_hash}#${r.outputIndex}`, r.address_address);
746
+ addrByKey.set(`${hashBySeq.get((0, transaction_rows_1.seqKey)(r.txSeq))}#${r.outputIndex}`, r.address_address);
566
747
  }
567
748
  for (const r of assetRows) {
568
- const k = `${r.output_tx_hash}#${r.output_outputIndex}`;
749
+ const k = `${hashBySeq.get((0, transaction_rows_1.seqKey)(r.output_txSeq))}#${r.output_outputIndex}`;
569
750
  const list = amtByKey.get(k) ?? [];
570
751
  list.push({ unit: r.unit, quantity: String(r.asset_quantity) });
571
752
  amtByKey.set(k, list);
@@ -581,25 +762,230 @@ class CardanoIndexer {
581
762
  }
582
763
  }
583
764
  /**
584
- * Index & return the epoch information data
585
- * @param tx CAP transaction object
586
- * @param epochNumber epoch number
587
- * @returns {Promise<Epoch>} epoch entity data
765
+ * Settle the fee of phase-2-invalid transactions (collateral inputs minus collateral return)
766
+ * and the block total. The declared fee is kept when the mapper already set it via
767
+ * `total_collateral` or a collateral input is not indexed locally (the sum would be short).
768
+ */
769
+ applyCollateralFees(blockData, txs) {
770
+ const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
771
+ let corrected = false;
772
+ for (const t of txs) {
773
+ // totalCollateral set = the mapper already put the charged amount in `fee`
774
+ if (!t.spendsCollaterals || t.totalCollateral != null)
775
+ continue;
776
+ const collateral = (t.inputs ?? []).filter(i => i.isCollateral);
777
+ if (!collateral.length)
778
+ continue; // nothing to derive from — leave the declared fee
779
+ const unresolved = collateral.find(i => !i.address);
780
+ if (unresolved) {
781
+ logger.warn(`collateral fee for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed ` +
782
+ `— keeping the declared fee ${t.fee}, which understates what the ledger charged`);
783
+ continue;
784
+ }
785
+ const consumed = collateral.reduce((sum, i) => sum + lovelaceOf(i.amount), 0n);
786
+ const returned = (t.outputs ?? [])
787
+ .filter(o => o.isCollateral)
788
+ .reduce((sum, o) => sum + lovelaceOf(o.amount), 0n);
789
+ const charged = consumed - returned;
790
+ if (charged < 0n) {
791
+ logger.warn(`collateral fee for ${t.hash}: return ${returned} exceeds collateral ${consumed} ` +
792
+ `— keeping the declared fee ${t.fee}`);
793
+ continue;
794
+ }
795
+ t.fee = charged.toString();
796
+ corrected = true;
797
+ }
798
+ if (corrected) {
799
+ blockData.fees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n).toString();
800
+ }
801
+ }
802
+ /**
803
+ * Mint/burn rows for a block from data in hand: the ledger's mint field when the source
804
+ * reports it (Ogmios, Koios), else Σ outputs − Σ inputs per unit, excluding reference and
805
+ * collateral inputs. A tx with an unresolvable consumed input is skipped and logged.
806
+ */
807
+ buildAssetHistoryRows(blockData, txs) {
808
+ const entries = [];
809
+ let skipped = 0;
810
+ for (const t of txs) {
811
+ let net;
812
+ if (t.mint) {
813
+ // A phase-2 failure never reaches here with a mint: the Ogmios mapper reports none.
814
+ net = new Map();
815
+ for (const m of t.mint) {
816
+ if (m.unit === 'lovelace')
817
+ continue;
818
+ net.set(m.unit, (net.get(m.unit) ?? 0n) + BigInt(m.quantity));
819
+ }
820
+ }
821
+ else {
822
+ if (t.spendsCollaterals)
823
+ continue; // no mint is applied when the script phase failed
824
+ const consumed = (t.inputs ?? []).filter(i => !i.isReference && !i.isCollateral);
825
+ const unresolved = consumed.find(i => !i.address);
826
+ if (unresolved) {
827
+ logger.warn(`mint delta for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed ` +
828
+ `— skipping, mint/burn of this transaction is not recorded`);
829
+ skipped++;
830
+ continue;
831
+ }
832
+ net = new Map();
833
+ const add = (amount, sign) => {
834
+ for (const a of amount ?? []) {
835
+ if (a.unit === 'lovelace')
836
+ continue;
837
+ net.set(a.unit, (net.get(a.unit) ?? 0n) + sign * BigInt(a.quantity));
838
+ }
839
+ };
840
+ for (const o of (t.outputs ?? []).filter(o => !o.isCollateral))
841
+ add(o.amount, 1n);
842
+ for (const i of consumed)
843
+ add(i.amount, -1n);
844
+ }
845
+ for (const [unit, quantity] of net) {
846
+ if (quantity === 0n)
847
+ continue;
848
+ entries.push({
849
+ unit,
850
+ txHash: t.hash,
851
+ action: quantity > 0n ? 'mint' : 'burn',
852
+ quantity: (quantity < 0n ? -quantity : quantity).toString(),
853
+ blockTime: blockData.time ?? null,
854
+ blockHeight: blockData.height ?? null,
855
+ });
856
+ }
857
+ }
858
+ if (skipped) {
859
+ logger.warn(`block ${blockData.hash}: mint/burn not recorded for ${skipped} transaction(s) with unresolved inputs`);
860
+ }
861
+ return (0, mappers_1.mapAssetHistory)(entries);
862
+ }
863
+ /**
864
+ * Keep the `Assets` catalogue complete for every unit the crawl meets, without provider calls.
865
+ * `Assets` is temporal, key `(validFrom, unit)`: the bare row's fixed epoch-zero stamp never
866
+ * aliases an enriched slice, so the UPSERT is safe inside the block transaction. The existence
867
+ * check uses the DB-level entity: the service projection's temporal filter hides such rows.
868
+ */
869
+ async ensureAssetRows(tx, units) {
870
+ if (this.crawlAssetCatalogue === 'off' || !units.size)
871
+ return 0;
872
+ const unknown = [...units].filter(u => !this.assetMemo.has(u));
873
+ if (!unknown.length)
874
+ return 0;
875
+ const missing = [];
876
+ for (const unitChunk of (0, collections_1.chunk)(unknown, collections_1.IN_CHUNK)) {
877
+ const rows = await tx.run(SELECT.from(cardano_1.Assets).columns('unit').where({ unit: { in: unitChunk } }));
878
+ const known = new Set(rows.map(r => r.unit));
879
+ for (const unit of unitChunk) {
880
+ if (known.has(unit))
881
+ this.noteAssetSeen(unit);
882
+ else
883
+ missing.push(unit);
884
+ }
885
+ }
886
+ if (!missing.length)
887
+ return 0;
888
+ const rows = missing.map(mappers_1.mapBareAsset).filter((r) => r !== null);
889
+ // Chunked like the lookup: a mint-storm block can carry thousands of fresh units.
890
+ for (const rowChunk of (0, collections_1.chunk)(rows, collections_1.IN_CHUNK)) {
891
+ await tx.run(UPSERT.into(cardano_1.Assets).entries(rowChunk));
892
+ }
893
+ // Memoize also the units mapBareAsset rejected, so they cost no SELECT per block.
894
+ for (const unit of missing)
895
+ this.noteAssetSeen(unit);
896
+ if (this.crawlAssetCatalogue === 'enrich' && rows.length) {
897
+ for (const row of rows) {
898
+ if (this.enrichQueue.length >= CardanoIndexer.ENRICH_QUEUE_CAP)
899
+ this.enrichQueue.shift();
900
+ this.enrichQueue.push(row.unit);
901
+ }
902
+ this.startAssetEnrichment();
903
+ }
904
+ return rows.length;
905
+ }
906
+ /**
907
+ * Remember a unit as present in the catalogue. Insertion-ordered eviction keeps a long
908
+ * backfill's memory flat; losing an entry costs one SELECT, never a wrong write.
909
+ */
910
+ noteAssetSeen(unit) {
911
+ if (this.assetMemo.has(unit))
912
+ return;
913
+ if (this.assetMemo.size >= CardanoIndexer.ASSET_MEMO_CAP) {
914
+ const oldest = this.assetMemo.values().next();
915
+ if (!oldest.done)
916
+ this.assetMemo.delete(oldest.value);
917
+ }
918
+ this.assetMemo.add(unit);
919
+ }
920
+ /**
921
+ * Snapshot every pool and DRep for an epoch in its OWN transaction (after the block commit):
922
+ * dated snapshot rows plus a refresh of the live `Pools` / `Dreps` rows. Needs Koios, else a no-op.
923
+ * @returns counts written
588
924
  */
925
+ async snapshotEpoch(epoch, at) {
926
+ const backend = this.client.getEnumeratingBackend();
927
+ if (!backend) {
928
+ logger.warn(`epoch ${epoch} snapshot skipped: no backend can enumerate pools/DReps (Koios required)`);
929
+ return { pools: 0, dreps: 0 };
930
+ }
931
+ // Network first, DB second — the provider round-trips must not run with a write lock held.
932
+ const [poolData, drepData] = await Promise.all([
933
+ backend.getPoolIds().then(ids => backend.getPools(ids)),
934
+ backend.getDrepIds().then(ids => backend.getDreps(ids)),
935
+ ]);
936
+ const poolSnapshots = poolData.map(p => (0, mappers_1.mapPoolSnapshot)(p, epoch, at));
937
+ const drepSnapshots = drepData.map(d => (0, mappers_1.mapDrepSnapshot)(d, epoch, at));
938
+ const poolRows = poolData.map(p => (0, mappers_1.mapPool)(p, this.client.max_age_ms));
939
+ const drepRows = drepData.map(d => (0, mappers_1.mapDrep)(d, this.client.max_age_ms));
940
+ await cds_1.default.tx(async (tx) => {
941
+ // Chunked so a mainnet-sized set cannot exceed a driver's bind-variable cap.
942
+ for (const rows of (0, collections_1.chunk)(poolSnapshots, collections_1.IN_CHUNK))
943
+ await tx.run(UPSERT.into(CardanoODataService_1.PoolEpochSnapshots).entries(rows));
944
+ for (const rows of (0, collections_1.chunk)(drepSnapshots, collections_1.IN_CHUNK))
945
+ await tx.run(UPSERT.into(CardanoODataService_1.DrepEpochSnapshots).entries(rows));
946
+ for (const rows of (0, collections_1.chunk)(poolRows, collections_1.IN_CHUNK))
947
+ await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(rows));
948
+ for (const rows of (0, collections_1.chunk)(drepRows, collections_1.IN_CHUNK))
949
+ await tx.run(UPSERT.into(CardanoODataService_1.Dreps).entries(rows));
950
+ });
951
+ logger.info(`epoch ${epoch} snapshot: ${poolSnapshots.length} pools, ${drepSnapshots.length} DReps`);
952
+ return { pools: poolSnapshots.length, dreps: drepSnapshots.length };
953
+ }
954
+ /** Every native-asset unit a block touches: outputs, consumed inputs and mint/burn rows. */
955
+ collectBlockUnits(txs, assetHistoryRows) {
956
+ const units = new Set();
957
+ for (const t of txs) {
958
+ for (const o of t.outputs ?? []) {
959
+ for (const a of o.amount ?? [])
960
+ if (a.unit !== 'lovelace')
961
+ units.add(a.unit);
962
+ }
963
+ for (const i of t.inputs ?? []) {
964
+ for (const a of i.amount ?? [])
965
+ if (a.unit !== 'lovelace')
966
+ units.add(a.unit);
967
+ }
968
+ }
969
+ for (const row of assetHistoryRows)
970
+ if (row.unit)
971
+ units.add(row.unit);
972
+ return units;
973
+ }
974
+ /** Index an epoch by number. */
589
975
  async indexEpoch(tx, epochNumber) {
590
976
  const epochInfo = await this.client.getEpoch(epochNumber);
591
977
  const epochEntity = (0, mappers_1.mapEpoch)(epochInfo);
592
978
  await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([epochEntity]));
593
979
  return epochEntity;
594
980
  }
595
- /**
596
- * Index & return the account information data
597
- * @param tx CAP transaction object
598
- * @param stakeAddress stake address (bech32)
599
- * @returns {Promise<Account>} account entity data
600
- */
981
+ /** Index an account by stake address, plus its addresses when it has any. */
601
982
  async indexAccount(tx, stakeAddress) {
602
- const accountInfo = await this.client.getAccount(stakeAddress);
983
+ const accountInfo = { ...(await this.client.getAccount(stakeAddress)) };
984
+ // controlled amount = UTxOs under the stake key (crawled set, when current) + reward balance
985
+ if ((await this.localCoverage(tx))?.ledger) {
986
+ const ledger = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAccounts).columns('controlledAmount').where({ stakeAddress }));
987
+ accountInfo.controlledAmount = (BigInt(lovelaceSum(ledger?.controlledAmount)) + BigInt(accountInfo.withdrawableAmount || '0')).toString();
988
+ }
603
989
  const accountEntity = (0, mappers_1.mapAccount)(accountInfo, this.client.max_age_ms);
604
990
  await tx.run(UPSERT.into(CardanoODataService_1.Accounts).entries(accountEntity));
605
991
  const addresses = accountInfo.addresses.map(a => a.address);
@@ -608,36 +994,21 @@ class CardanoIndexer {
608
994
  }
609
995
  return accountEntity;
610
996
  }
611
- /**
612
- * Index & return the drep information data
613
- * @param tx CAP transaction object
614
- * @param drepId drep id (bech32)
615
- * @returns {Promise<Drep>} drep entity data
616
- */
997
+ /** Index a DRep by bech32 id. */
617
998
  async indexDrep(tx, drepId) {
618
999
  const drepInfo = await this.client.getDrep(drepId);
619
1000
  const drepEntity = (0, mappers_1.mapDrep)(drepInfo, this.client.max_age_ms);
620
1001
  await tx.run(UPSERT.into(CardanoODataService_1.Dreps).entries(drepEntity));
621
1002
  return drepEntity;
622
1003
  }
623
- /**
624
- * Index & return the pool information data
625
- * @param tx CAP transaction object
626
- * @param poolId pool id (hex)
627
- * @returns {Promise<Pool>} pool entity data
628
- */
1004
+ /** Index a pool by id. */
629
1005
  async indexPool(tx, poolId) {
630
1006
  const poolInfo = await this.client.getPool(poolId);
631
- const poolEntity = (0, mappers_1.mapPool)(poolInfo, this.client.max_age_ms);
1007
+ const poolEntity = (0, mappers_1.mapPool)({ ...poolInfo, ...(await this.localPoolBlocks(tx, poolId)) }, this.client.max_age_ms);
632
1008
  await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(poolEntity));
633
1009
  return poolEntity;
634
1010
  }
635
- /**
636
- * Index & return the asset information data
637
- * @param tx CAP transaction object
638
- * @param unit asset unit (policyId + assetNameHex)
639
- * @returns {Promise<Asset>} asset entity data
640
- */
1011
+ /** Index an asset by unit (policyId + assetNameHex). */
641
1012
  async indexAsset(tx, unit) {
642
1013
  const assetInfo = await this.client.getAssetInfo(unit);
643
1014
  const assetEntity = (0, mappers_1.mapAsset)(assetInfo, this.client.max_age_ms);
@@ -645,14 +1016,8 @@ class CardanoIndexer {
645
1016
  return assetEntity;
646
1017
  }
647
1018
  /**
648
- * Index & return mint/burn history for an asset. Always-fresh from the
649
- * preferred backend (Koios for block timestamps, Blockfrost as fallback).
650
- * UPSERTs entries by (unit, txHash) — events are immutable, so re-fetching
651
- * just refreshes the cap of recent entries; older cached entries persist.
652
- * @param tx CAP transaction object
653
- * @param unit asset unit (policyId + assetNameHex)
654
- * @param limit max number of recent events to fetch (default 100)
655
- * @returns {Promise<AssetHistory[]>} list of mint/burn event entity rows
1019
+ * Index mint/burn history for an asset, always fresh. Rows are keyed (unit, txHash), so a
1020
+ * refetch refreshes the recent cap and older cached entries persist.
656
1021
  */
657
1022
  async indexAssetHistory(tx, unit, limit = 100) {
658
1023
  const events = await this.client.getAssetHistory(unit, limit);
@@ -662,14 +1027,7 @@ class CardanoIndexer {
662
1027
  await tx.run(UPSERT.into(CardanoODataService_1.AssetHistory).entries(rows));
663
1028
  return rows;
664
1029
  }
665
- /**
666
- * Common method: build a transaction, persist build result with inputs/outputs/address associations.
667
- * All four public indexBuild*Result methods delegate to this to eliminate duplication.
668
- * @param tx CAP transaction object
669
- * @param buildreq transaction build request data
670
- * @param buildFn the specific builder method to call
671
- * @returns {Promise<TransactionBuild>} transaction build entity data
672
- */
1030
+ /** Build a transaction and persist the build result with inputs/outputs/address association. */
673
1031
  async _indexBuildResult(tx, buildreq, buildFn) {
674
1032
  const protocolParams = await this.indexProtocolParameters(tx);
675
1033
  const txbuildResult = await buildFn(buildreq, protocolParams);
@@ -703,52 +1061,36 @@ class CardanoIndexer {
703
1061
  async indexPlutusSpendBuildResult(tx, buildreq) {
704
1062
  return this._indexBuildResult(tx, buildreq, (req, params) => this.txBuilder.buildPlutusSpendTransaction(req, params));
705
1063
  }
706
- /**
707
- * Index & return the protocol parameters data
708
- * @param tx CAP transaction object
709
- * @returns {Promise<LedgerProtocolParameter>} protocol parameters entity data
710
- */
1064
+ /** Protocol parameters, served from the DB row within a 5-minute TTL. */
711
1065
  async indexProtocolParameters(tx) {
712
1066
  const network = this.client.network;
713
1067
  const now = Date.now();
714
- // Return cached DB row if within TTL (protocol params only change at epoch boundaries ~5 days)
715
- const PROTOCOL_PARAMS_TTL_MS = 5 * 60 * 1000; // 5 minutes — matches client cache TTL
1068
+ const PROTOCOL_PARAMS_TTL_MS = 5 * 60 * 1000; // matches the client cache TTL
716
1069
  if (now - this.lastParamsFetchTime < PROTOCOL_PARAMS_TTL_MS) {
717
- // (network, epoch) is the composite key — old epochs accumulate as rows, so
718
- // order by epoch desc to return the LATEST instead of an arbitrary row.
1070
+ // (network, epoch) is the key; order by epoch desc to get the latest row
719
1071
  const existing = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerProtocolParameter).where({ network }).orderBy('epoch desc'));
720
1072
  if (existing)
721
1073
  return existing;
722
1074
  }
723
- // Fetch from provider (client has 5-min in-memory TTL cache, so this is cheap)
724
1075
  const protocolParamsInfo = await this.client.getProtocolParameters();
725
1076
  const protocolParams = (0, mappers_1.mapProtocolParameters)(protocolParamsInfo);
726
1077
  await tx.run(UPSERT.into(CardanoODataService_1.LedgerProtocolParameter).entries(protocolParams));
727
1078
  this.lastParamsFetchTime = now;
728
1079
  return protocolParams;
729
1080
  }
730
- /**
731
- * Persist a transaction submission with optional build association
732
- * Handles: TransactionSubmission insert, optional Build status update
733
- * @param tx CAP transaction object
734
- * @param params submission parameters
735
- * @returns {Promise<TransactionSubmission>} persisted transaction submission entity
736
- */
1081
+ /** Persist a transaction submission and flag the build as submitted when linked. */
737
1082
  async persistTransactionSubmission(tx, params) {
738
1083
  const { signedTxCbor, txHash, buildId } = params;
739
- // Map submission data
740
1084
  const indexSubmission = (0, mappers_1.mapTransactionSubmission)(signedTxCbor, txHash);
741
- // Create submission record (status: 'pending' — updated to 'submitted' after blockchain confirms)
1085
+ // status 'pending' until the second phase of the submit flow confirms
742
1086
  const submissionRecord = {
743
1087
  ...indexSubmission,
744
1088
  build_id: buildId || null,
745
1089
  backendResponse: 'Submitted successfully',
746
1090
  status: 'pending',
747
1091
  };
748
- // Persist submission
749
1092
  await tx.run(INSERT.into(CardanoTransactionService_1.TransactionSubmissions).entries(submissionRecord));
750
1093
  logger.debug({ submissionId: submissionRecord.id, txHash }, 'Persisted submission record');
751
- // Update build status if buildId provided
752
1094
  if (buildId) {
753
1095
  await tx.run(UPDATE.entity(CardanoTransactionService_1.TransactionBuilds)
754
1096
  .set({ wasSubmitted: true })
@@ -757,14 +1099,7 @@ class CardanoIndexer {
757
1099
  }
758
1100
  return submissionRecord;
759
1101
  }
760
- /**
761
- * Update the status of a transaction submission
762
- * Used for the two-phase submit flow: pending → submitted (or failed)
763
- * @param tx CAP transaction object
764
- * @param submissionId the submission to update
765
- * @param status new status value
766
- * @param errorMessage optional error message for failed status
767
- */
1102
+ /** Update a submission's status (two-phase submit: pending → submitted or failed). */
768
1103
  async updateSubmissionStatus(tx, submissionId, status, errorMessage) {
769
1104
  const updateData = { status };
770
1105
  if (errorMessage) {
@@ -775,15 +1110,9 @@ class CardanoIndexer {
775
1110
  .where({ id: submissionId }));
776
1111
  logger.debug({ submissionId, status }, 'Updated submission status');
777
1112
  }
778
- /**
779
- * Persist a new signing request
780
- * @param tx CAP transaction object
781
- * @param params signing request parameters from external signer module
782
- * @returns persisted signing request record
783
- */
1113
+ /** Persist a new signing request and link it to the build's sender address. */
784
1114
  async persistSigningRequest(tx, params) {
785
1115
  const { buildId, signingPayload } = params;
786
- // Create signing request record
787
1116
  const signingRequestRecord = {
788
1117
  id: signingPayload.signingRequestId,
789
1118
  build_id: buildId,
@@ -796,26 +1125,17 @@ class CardanoIndexer {
796
1125
  cardanoCliCommand: signingPayload.signingInstructions.cardanoCliCommand,
797
1126
  cip30TxCbor: signingPayload.signingInstructions.cip30SigningRequest?.txCbor,
798
1127
  };
799
- // Persist to database
800
1128
  await tx.run(INSERT.into(CardanoSignService_1.SigningRequests).entries(signingRequestRecord));
801
1129
  logger.debug({ signingRequestId: signingRequestRecord.id, buildId }, 'Persisted signing request');
802
- // Index address-signing request association
803
1130
  const build = await tx.run(SELECT.one.from(CardanoTransactionService_1.TransactionBuilds).where({ id: buildId }));
804
1131
  if (build?.senderAddress) {
805
1132
  await this.indexAddressSigningRequests(tx, build.senderAddress, signingRequestRecord.id);
806
1133
  }
807
1134
  return signingRequestRecord;
808
1135
  }
809
- /**
810
- * Persist a signature verification with signing request status update
811
- * Handles: SignatureVerification insert, SigningRequest status update
812
- * @param tx CAP transaction object
813
- * @param params verification parameters
814
- * @returns persisted signature verification record
815
- */
1136
+ /** Persist a signature verification and update the signing request status. */
816
1137
  async persistSignatureVerification(tx, params) {
817
1138
  const { signingRequestId, signedTxCbor, verificationResult, signerType, signerInfo } = params;
818
- // Create verification record
819
1139
  const verificationRecord = {
820
1140
  id: cds_1.default.utils.uuid(),
821
1141
  signingRequest_id: signingRequestId,
@@ -828,10 +1148,8 @@ class CardanoIndexer {
828
1148
  warnings: JSON.stringify(verificationResult.warnings),
829
1149
  verifiedAt: new Date().toISOString(),
830
1150
  };
831
- // Persist verification
832
1151
  await tx.run(INSERT.into(CardanoSignService_1.SignatureVerifications).entries(verificationRecord));
833
1152
  logger.debug({ verificationId: verificationRecord.id }, 'Persisted signature verification record');
834
- // Update signing request status
835
1153
  const newStatus = verificationResult.isValid ? 'verified' : 'failed';
836
1154
  await tx.run(UPDATE.entity(CardanoSignService_1.SigningRequests)
837
1155
  .set({
@@ -845,16 +1163,9 @@ class CardanoIndexer {
845
1163
  logger.debug({ signingRequestId, newStatus }, 'Updated signing request status');
846
1164
  return verificationRecord;
847
1165
  }
848
- /**
849
- * Index a verified transaction submission with all related records
850
- * Handles persistence of: SignatureVerification, TransactionSubmission, SigningRequest update, Build update
851
- * @param tx CAP transaction object
852
- * @param params submission parameters
853
- * @returns {Promise<TransactionSubmission>} transaction submission entity data
854
- */
1166
+ /** Persist a verified submission: verification, submission, signing request and build updates. */
855
1167
  async indexVerifiedTransactionSubmission(tx, params) {
856
1168
  const { signingRequestId, buildId, fullSignedTxCbor, txHash, verificationResult, signerType, signerInfo } = params;
857
- // Step 1: Create and persist verification record
858
1169
  const verificationRecord = {
859
1170
  id: cds_1.default.utils.uuid(),
860
1171
  signingRequest_id: signingRequestId,
@@ -869,7 +1180,6 @@ class CardanoIndexer {
869
1180
  };
870
1181
  await tx.run(INSERT.into(CardanoSignService_1.SignatureVerifications).entries(verificationRecord));
871
1182
  logger.debug({ verificationId: verificationRecord.id }, 'Persisted signature verification record');
872
- // Step 2: Create and persist submission record
873
1183
  const indexSubmission = (0, mappers_1.mapTransactionSubmission)(fullSignedTxCbor, txHash);
874
1184
  const submissionRecord = {
875
1185
  ...indexSubmission,
@@ -879,7 +1189,6 @@ class CardanoIndexer {
879
1189
  };
880
1190
  await tx.run(INSERT.into(CardanoTransactionService_1.TransactionSubmissions).entries(submissionRecord));
881
1191
  logger.debug({ submissionId: submissionRecord.id }, 'Persisted submission record');
882
- // Step 3: Update signing request metadata and status
883
1192
  const now = new Date().toISOString();
884
1193
  await tx.run(UPDATE.entity(CardanoSignService_1.SigningRequests)
885
1194
  .set({
@@ -892,29 +1201,20 @@ class CardanoIndexer {
892
1201
  })
893
1202
  .where({ id: signingRequestId }));
894
1203
  logger.debug({ signingRequestId }, 'Updated signing request status to submitted');
895
- // Step 4: Update build status
896
1204
  await tx.run(UPDATE.entity(CardanoTransactionService_1.TransactionBuilds)
897
1205
  .set({ wasSubmitted: true })
898
1206
  .where({ id: buildId }));
899
1207
  logger.debug({ buildId }, 'Updated build wasSubmitted flag');
900
1208
  return submissionRecord;
901
1209
  }
902
- /**
903
- * Index & return the latest epoch information data
904
- * @param tx CAP transaction object
905
- * @returns {Promise<Epoch>} epoch entity data
906
- */
1210
+ /** Index the latest epoch. */
907
1211
  async indexLatestEpoch(tx) {
908
1212
  const epochInfo = await this.client.getLatestEpoch();
909
1213
  const epochEntity = (0, mappers_1.mapEpoch)(epochInfo);
910
1214
  await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([epochEntity]));
911
1215
  return epochEntity;
912
1216
  }
913
- /**
914
- * Index & return the latest block information data
915
- * @param tx CAP transaction object
916
- * @returns {Promise<Block>} block entity data
917
- */
1217
+ /** Index the latest block, with best-effort epoch enrichment. */
918
1218
  async indexLatestBlock(tx) {
919
1219
  const blockInfo = await this.client.getLatestBlock();
920
1220
  let epoch;
@@ -925,6 +1225,12 @@ class CardanoIndexer {
925
1225
  // Epoch data may not be available (e.g., Koios drops old/in-progress epochs)
926
1226
  }
927
1227
  const blockEntity = (0, mappers_1.mapBlock)(blockInfo, epoch);
1228
+ // A header-only tip is never persisted: its zeros would read as an empty block, overwrite a
1229
+ // crawled row of the same hash, or outlive the block when the tip is rolled back.
1230
+ if (blockInfo.headerOnly) {
1231
+ const stored = await tx.run(SELECT.one.from(CardanoODataService_1.Block).where({ hash: blockInfo.hash }));
1232
+ return stored ?? blockEntity;
1233
+ }
928
1234
  await tx.run(UPSERT.into(CardanoODataService_1.Block).entries(blockEntity));
929
1235
  return blockEntity;
930
1236
  }
@@ -933,54 +1239,30 @@ class CardanoIndexer {
933
1239
  //-----------------------------------------------------------------------------
934
1240
  /** Max addresses to index concurrently (avoid overloading backends) */
935
1241
  static ADDR_CONCURRENCY = 5;
1242
+ /** Block position of a transaction already in the local index (crawled or cached), or null. */
1243
+ async findIndexedTransaction(tx, txHash) {
1244
+ const row = await tx.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('slot', 'blockHeight').where({ hash: txHash }));
1245
+ return row ?? null;
1246
+ }
936
1247
  /**
937
- * Ensure a set of transactions are indexed — batch DB-check + batch fetch.
938
- * 1. Deduplicate hashes
939
- * 2. Check which hashes already exist in DB
940
- * 3. Batch-fetch missing transactions from backend
941
- * 4. UPSERT all entities (Transactions, Inputs, Outputs, Assets, Metadata)
942
- *
943
- * @param tx CAP transaction (cds.tx)
944
- * @param txHashes array of transaction hashes to ensure
945
- * @returns Map of txHash → provider Transaction (all requested, from DB fetch or backend)
1248
+ * Ensure a set of transactions is indexed: DB check, batch fetch of the missing ones, UPSERT.
1249
+ * @returns provider transactions for the hashes that had to be fetched
946
1250
  */
947
1251
  async ensureTransactionsIndexed(tx, txHashes) {
948
1252
  const unique = [...new Set(txHashes)];
949
1253
  if (unique.length === 0)
950
1254
  return new Map();
951
- // DB check — which hashes are already indexed?
952
1255
  const existingRows = await tx.run(SELECT.from(CardanoODataService_1.Transactions).columns('hash').where({ hash: { in: unique } }));
953
1256
  const existingSet = new Set(existingRows.map((r) => r.hash));
954
1257
  const missing = unique.filter(h => !existingSet.has(h));
955
1258
  logger.debug(`ensureTransactionsIndexed: ${unique.length} unique, ${existingSet.size} cached, ${missing.length} to fetch`);
956
- // Batch-fetch missing from backend
957
1259
  let fetched = new Map();
958
1260
  if (missing.length > 0) {
959
1261
  fetched = await this.client.getTransactionsBatch(missing);
960
- // UPSERT all fetched transactions + child entities
961
1262
  for (const [, providerTx] of fetched) {
962
1263
  const txRow = (0, mappers_1.mapTransaction)(providerTx);
963
1264
  await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRow));
964
- if (providerTx.inputs) {
965
- const inputRows = (0, mappers_1.mapTransactionInputs)(providerTx.hash, providerTx.inputs);
966
- const inputAssetRows = (0, mappers_1.mapTransactionInputAssets)(providerTx.hash, providerTx.inputs);
967
- if (inputRows.length)
968
- await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputs).entries(inputRows));
969
- if (inputAssetRows.length)
970
- await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputAssets).entries(inputAssetRows));
971
- }
972
- // outputs independent of inputs (see indexTransaction)
973
- if (providerTx.outputs) {
974
- const outputRows = (0, mappers_1.mapTransactionOutputs)(providerTx.hash, providerTx.outputs);
975
- const outputAssetRows = (0, mappers_1.mapTransactionOutputAssets)(providerTx.hash, providerTx.outputs);
976
- if (outputRows.length)
977
- await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputs).entries(outputRows));
978
- if (outputAssetRows.length)
979
- await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
980
- }
981
- const metadataRows = (0, mappers_1.mapTransactionMetadata)(providerTx.metadata || []);
982
- if (metadataRows.length)
983
- await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
1265
+ await this.writeTransactionChildren(tx, providerTx, txRow.txSeq);
984
1266
  }
985
1267
  }
986
1268
  return fetched;
@@ -988,12 +1270,7 @@ class CardanoIndexer {
988
1270
  //-----------------------------------------------------------------------------
989
1271
  // Private Helpers
990
1272
  //-----------------------------------------------------------------------------
991
- /**
992
- * Index multiple addresses with concurrency-limited parallelism.
993
- * Processes addresses in chunks to avoid overwhelming backends.
994
- * @param tx CAP transaction object
995
- * @param bech32List array of bech32 addresses
996
- */
1273
+ /** Index addresses with bounded concurrency. */
997
1274
  async _ensureAddresses(tx, bech32List) {
998
1275
  const concurrency = CardanoIndexer.ADDR_CONCURRENCY;
999
1276
  for (let i = 0; i < bech32List.length; i += concurrency) {