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

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 (132) 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 +224 -0
  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 +316 -0
  10. package/@cds-models/odatano/cardano/index.js +33 -0
  11. package/README.md +195 -136
  12. package/db/schema.cds +2121 -1633
  13. package/package.json +179 -173
  14. package/src/index.d.ts +10 -10
  15. package/src/index.js +24 -14
  16. package/src/plugin.js +39 -52
  17. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  18. package/srv/blockchain/backends/blockfrost-backend.js +45 -158
  19. package/srv/blockchain/backends/cardano-backend.d.ts +78 -158
  20. package/srv/blockchain/backends/cardano-backend.js +14 -5
  21. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  22. package/srv/blockchain/backends/koios-backend.js +292 -202
  23. package/srv/blockchain/backends/ogmios-backend.d.ts +59 -96
  24. package/srv/blockchain/backends/ogmios-backend.js +241 -153
  25. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  26. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  27. package/srv/blockchain/cardano-client.d.ts +50 -205
  28. package/srv/blockchain/cardano-client.js +80 -224
  29. package/srv/blockchain/cardano-indexer.d.ts +146 -244
  30. package/srv/blockchain/cardano-indexer.js +442 -285
  31. package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
  32. package/srv/blockchain/cardano-tx-builder.js +21 -107
  33. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  34. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  35. package/srv/blockchain/crawler/crawler.d.ts +121 -53
  36. package/srv/blockchain/crawler/crawler.js +402 -82
  37. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  38. package/srv/blockchain/crawler/index.d.ts +5 -0
  39. package/srv/blockchain/crawler/index.js +35 -7
  40. package/srv/blockchain/crawler/sync-state.d.ts +44 -28
  41. package/srv/blockchain/crawler/sync-state.js +115 -43
  42. package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
  43. package/srv/blockchain/crawler/utxo-set-import.js +269 -0
  44. package/srv/blockchain/ledger-state.d.ts +80 -0
  45. package/srv/blockchain/ledger-state.js +383 -0
  46. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  47. package/srv/blockchain/signing/cose-verifier.js +6 -12
  48. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  49. package/srv/blockchain/signing/external-signer.js +19 -122
  50. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  51. package/srv/blockchain/signing/hsm-signer.js +23 -63
  52. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  53. package/srv/blockchain/signing/signature-verifier.js +13 -54
  54. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  55. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  56. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
  57. package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
  58. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  59. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  60. package/srv/blockchain/wallet-worker/build-request.js +39 -23
  61. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  62. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  63. package/srv/blockchain/wallet-worker/index.js +2 -8
  64. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  65. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  66. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  67. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  68. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  69. package/srv/blockchain/wallet-worker/signers.js +3 -8
  70. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  71. package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
  72. package/srv/cardano-agent-service.cds +146 -0
  73. package/srv/cardano-agent-service.d.ts +2 -0
  74. package/srv/cardano-agent-service.js +12 -0
  75. package/srv/cardano-indexer-service.cds +164 -73
  76. package/srv/cardano-indexer-service.js +156 -11
  77. package/srv/cardano-service.cds +45 -0
  78. package/srv/cardano-service.js +38 -96
  79. package/srv/cardano-sign-service.cds +200 -180
  80. package/srv/cardano-sign-service.js +55 -173
  81. package/srv/cardano-tx-service.cds +32 -26
  82. package/srv/cardano-tx-service.js +133 -195
  83. package/srv/cardano-worker-service.js +7 -15
  84. package/srv/server.d.ts +28 -86
  85. package/srv/server.js +95 -128
  86. package/srv/utils/agent-grants-config.d.ts +37 -0
  87. package/srv/utils/agent-grants-config.js +138 -0
  88. package/srv/utils/agent-grants.d.ts +262 -0
  89. package/srv/utils/agent-grants.js +914 -0
  90. package/srv/utils/agent-token-auth.d.ts +16 -0
  91. package/srv/utils/agent-token-auth.js +78 -0
  92. package/srv/utils/backend-request-handler.d.ts +2 -16
  93. package/srv/utils/backend-request-handler.js +3 -18
  94. package/srv/utils/collections.d.ts +4 -8
  95. package/srv/utils/collections.js +4 -8
  96. package/srv/utils/const.d.ts +19 -68
  97. package/srv/utils/const.js +20 -69
  98. package/srv/utils/crypto.d.ts +3 -12
  99. package/srv/utils/crypto.js +5 -18
  100. package/srv/utils/db-indexes.d.ts +25 -0
  101. package/srv/utils/db-indexes.js +89 -0
  102. package/srv/utils/db-sanitize.d.ts +27 -0
  103. package/srv/utils/db-sanitize.js +85 -0
  104. package/srv/utils/error-codes.d.ts +18 -73
  105. package/srv/utils/error-codes.js +17 -70
  106. package/srv/utils/errors.d.ts +34 -178
  107. package/srv/utils/errors.js +55 -217
  108. package/srv/utils/liveness.d.ts +16 -0
  109. package/srv/utils/liveness.js +41 -0
  110. package/srv/utils/mappers.d.ts +82 -210
  111. package/srv/utils/mappers.js +272 -293
  112. package/srv/utils/network-context.js +2 -11
  113. package/srv/utils/pg-order-nulls.d.ts +14 -0
  114. package/srv/utils/pg-order-nulls.js +57 -0
  115. package/srv/utils/plutus-placeholders.d.ts +6 -18
  116. package/srv/utils/plutus-placeholders.js +6 -20
  117. package/srv/utils/rate-limiter.d.ts +46 -0
  118. package/srv/utils/rate-limiter.js +116 -0
  119. package/srv/utils/service-events.d.ts +2 -22
  120. package/srv/utils/service-events.js +3 -23
  121. package/srv/utils/signing-helper.d.ts +3 -18
  122. package/srv/utils/signing-helper.js +10 -32
  123. package/srv/utils/tx-build-helper.d.ts +18 -92
  124. package/srv/utils/tx-build-helper.js +32 -123
  125. package/srv/utils/tx-request-parsers.d.ts +14 -20
  126. package/srv/utils/tx-request-parsers.js +33 -20
  127. package/srv/utils/tx-utils.d.ts +4 -23
  128. package/srv/utils/tx-utils.js +12 -41
  129. package/srv/utils/types.d.ts +112 -169
  130. package/srv/utils/types.js +2 -6
  131. package/srv/utils/validators.d.ts +19 -89
  132. package/srv/utils/validators.js +31 -138
@@ -8,22 +8,18 @@ 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 ledger_state_1 = require("./ledger-state");
17
+ const sync_state_1 = require("./crawler/sync-state");
13
18
  const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
14
19
  const logger = cds_1.default.log('CardanoIndexer');
15
20
  /**
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.
21
+ * Indexes Cardano data into the OData entities: fetches via CardanoClient, maps provider data
22
+ * to entity rows and UPSERTs them inside the caller's CAP transaction.
27
23
  */
28
24
  class CardanoIndexer {
29
25
  client;
@@ -32,22 +28,124 @@ class CardanoIndexer {
32
28
  static CRAWL_EPOCH_REFRESH_MS = 5 * 60 * 1000;
33
29
  static CRAWL_EPOCH_RETRY_MS = 30 * 1000;
34
30
  /**
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.
31
+ * Crawler epoch memo: refreshed periodically while an epoch is live and once more when the
32
+ * next one starts; holds at most the current and previous epoch. Rows are UPSERTed in every
33
+ * block transaction because the caller owns the commit.
43
34
  */
44
35
  crawlEpochCache = new Map();
45
36
  crawlEpochCurrent = null;
46
37
  crawlEpochPrevious = null;
38
+ /** Analytics coverage of the crawl path; defaults mirror the crawler config defaults. */
39
+ crawlAssetHistory = true;
40
+ crawlAssetCatalogue = 'bare';
41
+ /** Certificates + withdrawals per block (ledger-state coverage). Opt-in. */
42
+ crawlCertificates = false;
43
+ /** Logged once per process: the active source reports no certificates (Blockfrost). */
44
+ certificatesUnreportedWarned = false;
47
45
  /**
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.
46
+ * Crawler-fed ledger state (`crawler.utxoSet`): blocks after `utxoAnchor` are applied to the
47
+ * Ledger* tables; no anchor means configured but inactive.
48
+ */
49
+ crawlUtxoSet = false;
50
+ utxoAnchor = null;
51
+ /** The anchor block was found in the crawled chain (checked once, before the first apply). */
52
+ utxoAnchorVerified = false;
53
+ /**
54
+ * Invalidation decided inside a block transaction; the anchor stays until the crawler confirms
55
+ * the commit (`takeLedgerInvalidation`), so a rolled-back attempt changes nothing.
56
+ */
57
+ ledgerInvalidation = null;
58
+ /** Units known to have an `Assets` row, so a repeat sighting costs no DB round-trip. */
59
+ static ASSET_MEMO_CAP = 200_000;
60
+ assetMemo = new Set();
61
+ /**
62
+ * Background registry enrichment queue (`assetCatalogue: 'enrich'`), drained at a fixed rate
63
+ * outside the block transaction. Above the cap the oldest units are dropped (bare row stays).
64
+ */
65
+ static ENRICH_QUEUE_CAP = 50_000;
66
+ enrichQueue = [];
67
+ enrichTimer = null;
68
+ enrichRate = 2;
69
+ /** Adopt the crawler's coverage settings; the lazy request path never touches these. */
70
+ configureCrawlCoverage(coverage) {
71
+ this.crawlAssetHistory = coverage.assetHistory;
72
+ this.crawlAssetCatalogue = coverage.assetCatalogue;
73
+ this.crawlCertificates = coverage.certificates ?? false;
74
+ this.crawlUtxoSet = coverage.utxoSet ?? false;
75
+ this.enrichRate = coverage.assetEnrichRate ?? this.enrichRate;
76
+ if (coverage.assetCatalogue !== 'enrich')
77
+ this.stopAssetEnrichment();
78
+ }
79
+ /** The anchor the imported UTxO set describes (null = ledger mode inactive). */
80
+ setUtxoAnchor(anchor) {
81
+ this.utxoAnchor = anchor;
82
+ this.utxoAnchorVerified = false;
83
+ this.ledgerInvalidation = null;
84
+ }
85
+ /**
86
+ * The imported set describes the chain AT the anchor block, so before the first block past it
87
+ * is applied the cursor (not yet advanced in this transaction) must equal the anchor exactly;
88
+ * otherwise the snapshot was taken on a fork. Skipped once `utxoAppliedSlot` is set.
89
+ */
90
+ async verifyUtxoAnchor(tx, anchor) {
91
+ const cursor = await (0, sync_state_1.readCursor)(tx);
92
+ if (cursor?.utxoSet.appliedSlot != null)
93
+ return true;
94
+ if (cursor && cursor.lastSlot === anchor.slot && (cursor.lastBlockHash ?? '').toLowerCase() === anchor.hash.toLowerCase())
95
+ return true;
96
+ const reason = cursor
97
+ ? `anchor ${anchor.slot}/${anchor.hash} is not the block the crawler followed (cursor ${cursor.lastSlot}/${cursor.lastBlockHash})`
98
+ : `no crawler cursor to verify the anchor ${anchor.slot}/${anchor.hash} against`;
99
+ logger.error(`UTxO set invalidated: ${reason} — the snapshot describes a fork; re-import at the crawler cursor`);
100
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: reason.slice(0, 500) });
101
+ this.ledgerInvalidation = reason;
102
+ return false;
103
+ }
104
+ /** Null while the mode is off, nothing is imported, or an invalidation awaits its commit. */
105
+ getUtxoAnchor() {
106
+ return this.crawlUtxoSet && !this.ledgerInvalidation ? this.utxoAnchor : null;
107
+ }
108
+ /** Hand out a pending invalidation (dropping the anchor) exactly once after the block commit, or null. */
109
+ takeLedgerInvalidation() {
110
+ const reason = this.ledgerInvalidation;
111
+ if (reason) {
112
+ this.ledgerInvalidation = null;
113
+ this.utxoAnchor = null;
114
+ this.utxoAnchorVerified = false;
115
+ }
116
+ return reason;
117
+ }
118
+ /**
119
+ * Drain the enrichment queue at `enrichRate` units per second, one `indexAsset()` per tick in
120
+ * its own transaction. A failing unit is dropped; its bare row stays for the lazy path.
121
+ */
122
+ startAssetEnrichment() {
123
+ if (this.enrichTimer || this.crawlAssetCatalogue !== 'enrich')
124
+ return;
125
+ const intervalMs = Math.max(1, Math.round(1000 / Math.max(1, this.enrichRate)));
126
+ this.enrichTimer = setInterval(() => {
127
+ const unit = this.enrichQueue.shift();
128
+ if (unit === undefined) {
129
+ this.stopAssetEnrichment();
130
+ return;
131
+ }
132
+ void cds_1.default.tx((tx) => this.indexAsset(tx, unit)).catch((err) => {
133
+ logger.debug(`asset enrichment for ${unit} failed (bare row kept):`, err);
134
+ });
135
+ }, intervalMs);
136
+ this.enrichTimer.unref?.();
137
+ }
138
+ /** Stop the enrichment loop and forget what is still queued (shutdown, crawler halt, mode change). */
139
+ stopAssetEnrichment() {
140
+ if (this.enrichTimer) {
141
+ clearInterval(this.enrichTimer);
142
+ this.enrichTimer = null;
143
+ }
144
+ this.enrichQueue = [];
145
+ }
146
+ /**
147
+ * Network-only epoch prefetch for the crawler. Call BEFORE opening the per-block write
148
+ * transaction so no backend round-trip runs under the DB write lock. Never throws.
51
149
  */
52
150
  async prefetchCrawlEpoch(epochNumber) {
53
151
  const previousEpoch = this.crawlEpochCurrent;
@@ -99,26 +197,16 @@ class CardanoIndexer {
99
197
  });
100
198
  }
101
199
  }
102
- /**
103
- * Create a new CardanoIndexer instance
104
- * @param client - The CardanoClient instance for blockchain queries
105
- * @param txBuilder - The CardanoTransactionBuilder instance for transaction building
106
- */
107
200
  constructor(client, txBuilder) {
108
201
  this.client = client;
109
202
  this.txBuilder = txBuilder;
110
203
  logger.info('CardanoIndexer instance created');
111
204
  }
112
205
  /**
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
206
+ * Index a transaction with inputs/outputs/assets/metadata; all UPSERTs run in the caller's
207
+ * transaction, so either everything persists or nothing does.
119
208
  */
120
209
  async indexTransaction(tx, txHash) {
121
- // getting data from cardano data provider
122
210
  const providerTx = await this.client.getTransaction(txHash);
123
211
  const txRow = (0, mappers_1.mapTransaction)(providerTx);
124
212
  await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRow));
@@ -136,8 +224,7 @@ class CardanoIndexer {
136
224
  logger.debug(`indexTransaction: upserted ${inputAssetRows.length} transaction input assets for ${txHash}`);
137
225
  }
138
226
  }
139
- // Outputs + OutputAssets — independent of inputs (a tx with empty/missing
140
- // `inputs` previously skipped its outputs entirely)
227
+ // Outputs + OutputAssets — must not depend on the inputs branch
141
228
  if (providerTx.outputs) {
142
229
  const outputRows = (0, mappers_1.mapTransactionOutputs)(txHash, providerTx.outputs);
143
230
  const outputAssetRows = (0, mappers_1.mapTransactionOutputAssets)(txHash, providerTx.outputs);
@@ -155,11 +242,8 @@ class CardanoIndexer {
155
242
  return txRow;
156
243
  }
157
244
  /**
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
245
+ * Index address data with assets and UTxOs; transactions are loaded separately via
246
+ * indexAddressTransactions().
163
247
  */
164
248
  async indexAddress(tx, addr) {
165
249
  const addrData = await this.client.getAddress(addr);
@@ -169,8 +253,7 @@ class CardanoIndexer {
169
253
  const validFrom = AddrEntity.validFrom ?? now;
170
254
  const validTo = AddrEntity.validTo ?? now;
171
255
  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
256
+ // Supplement address-level amounts with assets only present in UTxOs
174
257
  const addressAssetUnits = new Set(addrData.amount.filter(a => a.unit !== 'lovelace').map(a => a.unit));
175
258
  for (const utxo of addrData.utxos) {
176
259
  for (const amt of utxo.amount) {
@@ -220,17 +303,8 @@ class CardanoIndexer {
220
303
  return AddrEntity;
221
304
  }
222
305
  /**
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
306
+ * Index UTxOs by 28-byte payment credential (56-char hex), always fresh from Koios. Child
307
+ * rows are UPSERTed without a parent Addresses row (same pattern as TransactionInputs).
234
308
  */
235
309
  async indexCredentialUtxos(tx, credHash) {
236
310
  const utxos = await this.client.getCredentialUtxos(credHash);
@@ -271,17 +345,8 @@ class CardanoIndexer {
271
345
  return allRows;
272
346
  }
273
347
  /**
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)
348
+ * Index only the UTxOs of an address via getAddressUtxos (no getAddress call), so it works on
349
+ * backends without address aggregation such as Ogmios. Writes no parent Addresses row.
285
350
  */
286
351
  async indexAddressUtxos(tx, addr) {
287
352
  const utxos = await this.client.getAddressUtxos(addr);
@@ -307,21 +372,9 @@ class CardanoIndexer {
307
372
  return utxoEntities;
308
373
  }
309
374
  /**
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
375
+ * Evict cached rows a submitted transaction made stale: every consumed input ref (under any
376
+ * address) and all address-level rows of the output addresses plus `extraAddresses`. Only the
377
+ * read cache is touched; lagging backends may still serve pre-submit state on refetch.
325
378
  */
326
379
  async invalidateUtxoCacheForTx(tx, targets, extraAddresses = []) {
327
380
  const addresses = [...new Set([...targets.outputAddresses, ...extraAddresses])];
@@ -339,21 +392,15 @@ class CardanoIndexer {
339
392
  logger.debug(`Invalidated UTxO cache: ${addresses.length} address(es), ${targets.inputs.length} spent input ref(s)`);
340
393
  }
341
394
  }
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
- */
395
+ /** Index address transactions (separate from indexAddress for lazy loading). */
349
396
  async indexAddressTransactions(tx, addr, limit) {
350
397
  logger.debug(`indexAddressTransactions: fetching transactions for ${addr}`);
351
- // Layer 4: Hash-only listing (lightweight, 1 API call)
398
+ // Hash-only listing (one API call)
352
399
  const txHashes = await this.client.getAddressTransactionHashes(addr, limit);
353
400
  logger.debug(`indexAddressTransactions: found ${txHashes.length} tx hashes for ${addr}`);
354
401
  if (txHashes.length === 0)
355
402
  return [];
356
- // Layer 3: DB-first dedup + batch fetch
403
+ // DB-first dedup + batch fetch
357
404
  const batchFetched = await this.ensureTransactionsIndexed(tx, txHashes);
358
405
  // For address-transaction mapping we need full provider tx data (inputs/outputs for net amounts).
359
406
  // Transactions already in DB were not re-fetched — batch-fetch those separately.
@@ -387,41 +434,21 @@ class CardanoIndexer {
387
434
  transactionsEntities.sort((a, b) => (b.blockTime ?? 0) - (a.blockTime ?? 0));
388
435
  return transactionsEntities;
389
436
  }
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
- */
437
+ /** Link an address to a signing request for address-based queries. */
398
438
  async indexAddressSigningRequests(tx, addr, signingRequestId) {
399
439
  logger.debug(`indexAddressSigningRequests: linking address ${addr} to signing request ${signingRequestId}`);
400
440
  const addressSigningRequestEntity = (0, mappers_1.mapAddressSigningRequest)(addr, signingRequestId);
401
441
  await tx.run(UPSERT.into(CardanoSignService_1.AddressSigningRequests).entries(addressSigningRequestEntity));
402
442
  logger.debug(`indexAddressSigningRequests: linked address ${addr} to signing request ${signingRequestId}`);
403
443
  }
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
- */
444
+ /** Link an address to a transaction build for address-based queries. */
412
445
  async indexAddressTransactionBuilds(tx, addr, buildId) {
413
446
  logger.debug(`indexAddressTransactionBuilds: linking address ${addr} to build ${buildId}`);
414
447
  const addressTransactionBuildEntity = (0, mappers_1.mapAddressTransactionBuild)(addr, buildId);
415
448
  await tx.run(UPSERT.into(CardanoTransactionService_1.AddressTransactionBuilds).entries(addressTransactionBuildEntity));
416
449
  logger.debug(`indexAddressTransactionBuilds: linked address ${addr} to build ${buildId}`);
417
450
  }
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
- */
451
+ /** Index the metadata rows of a transaction. */
425
452
  async indexTransactionMetadata(tx, tx_hash) {
426
453
  const metadata = await this.client.getTransactionMetadata(tx_hash);
427
454
  const rows = (0, mappers_1.mapTransactionMetadata)(metadata);
@@ -430,23 +457,14 @@ class CardanoIndexer {
430
457
  }
431
458
  return rows;
432
459
  }
433
- /**
434
- * Index & return the network information data
435
- * @param tx CAP transaction object
436
- * @returns {Promise<NetworkInformation>} network information entity data
437
- */
460
+ /** Index the network information. */
438
461
  async indexNetworkInformation(tx) {
439
462
  const netInfo = await this.client.getNetworkInformation();
440
463
  const netEntity = (0, mappers_1.mapNetworkInfo)(netInfo, this.client.max_age_ms, this.client.network);
441
464
  await tx.run(UPSERT.into(CardanoODataService_1.NetworkInformation).entries(netEntity));
442
465
  return netEntity;
443
466
  }
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
- */
467
+ /** Index a block by hash, with best-effort epoch enrichment. */
450
468
  async indexBlock(tx, blockHash) {
451
469
  const blockInfo = await this.client.getBlock(blockHash);
452
470
  let epoch;
@@ -461,28 +479,13 @@ class CardanoIndexer {
461
479
  return blockEntity;
462
480
  }
463
481
  /**
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)
482
+ * Bulk-index a whole block and its transactions in one pass for the crawler: no per-hash
483
+ * re-fetch, one UPSERT per table, all inside the caller's transaction so the block persists
484
+ * atomically. Bare chain-sync inputs are backfilled by resolveInputs() first.
481
485
  */
482
486
  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.
487
+ // Epoch from the prefetched memo; if the caller skipped prefetchCrawlEpoch, resolve now
488
+ // (memoized) and accept the in-tx fetch.
486
489
  let epoch;
487
490
  if (blockData.epoch != null) {
488
491
  await this.prefetchCrawlEpoch(blockData.epoch);
@@ -493,16 +496,33 @@ class CardanoIndexer {
493
496
  if (epochRows.length)
494
497
  await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries(epochRows));
495
498
  }
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
499
+ // Backfill chain-sync inputs (empty address/amount) from local outputs, then settle
500
+ // the fee of any phase-2 failure. Both run before the block row is written, because a
501
+ // corrected fee changes the block's fee total.
498
502
  await this.resolveInputs(tx, txs);
499
- // Accumulate rows across the whole block, then one bulk UPSERT per table
503
+ this.applyCollateralFees(blockData, txs);
504
+ await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
505
+ // One bulk UPSERT per table. NUL safety for PostgreSQL is enforced by the db-level hook in
506
+ // srv/utils/db-sanitize.ts, not per call site.
500
507
  const txRows = txs.map(t => (0, mappers_1.mapTransaction)(t));
501
508
  const inputRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputs)(t.hash, t.inputs ?? []));
502
509
  const inputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputAssets)(t.hash, t.inputs ?? []));
503
510
  const outputRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputs)(t.hash, t.outputs ?? []));
504
511
  const outputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputAssets)(t.hash, t.outputs ?? []));
505
512
  const metadataRows = txs.flatMap(t => (0, mappers_1.mapTransactionMetadata)(t.metadata ?? []));
513
+ // Certificates + withdrawals are keyed (tx, certIndex, kind) / (tx, stakeAddress), so a
514
+ // re-crawl is idempotent and a reorg removes them with their tx.
515
+ const certificateRows = this.crawlCertificates
516
+ ? txs.flatMap(t => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? []))
517
+ : [];
518
+ const withdrawalRows = this.crawlCertificates
519
+ ? txs.flatMap(t => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? []))
520
+ : [];
521
+ if (this.crawlCertificates)
522
+ this.warnIfCertificatesUnreported(txs);
523
+ // Mint/burn is derived from rows already in hand — keyed (unit, txHash), so a re-crawl is
524
+ // idempotent and a reorg removes these rows with their transactions (crawler handleReorg).
525
+ const assetHistoryRows = this.crawlAssetHistory ? this.buildAssetHistoryRows(blockData, txs) : [];
506
526
  if (txRows.length)
507
527
  await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRows));
508
528
  if (inputRows.length)
@@ -515,13 +535,52 @@ class CardanoIndexer {
515
535
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
516
536
  if (metadataRows.length)
517
537
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
518
- logger.debug(`indexBlockFull: block ${blockData.hash} — ${txs.length} txs, ${outputRows.length} outputs`);
538
+ if (certificateRows.length)
539
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionCertificates).entries(certificateRows));
540
+ if (withdrawalRows.length)
541
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionWithdrawals).entries(withdrawalRows));
542
+ // Ledger state (crawler.utxoSet): only blocks AFTER the anchor the imported set describes;
543
+ // same transaction, so the UTxO set can never be a block ahead of or behind the cursor.
544
+ if (this.crawlUtxoSet && this.utxoAnchor && (blockData.slot ?? 0) > this.utxoAnchor.slot) {
545
+ if (this.ledgerInvalidation) {
546
+ // Decided in an earlier attempt of this block whose transaction rolled back: re-write
547
+ // the verdict so whichever attempt commits carries it; nothing is applied meanwhile.
548
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: this.ledgerInvalidation.slice(0, 500) });
549
+ }
550
+ else if (this.utxoAnchorVerified || (this.utxoAnchorVerified = await this.verifyUtxoAnchor(tx, this.utxoAnchor))) {
551
+ const ledger = await (0, ledger_state_1.applyBlockToLedger)(tx, blockData, txs);
552
+ if (ledger.missing) {
553
+ logger.warn(`ledger: block ${blockData.hash} consumed ${ledger.missing} outpoint(s) with no open row — ` +
554
+ 'the set is incomplete relative to the crawl (snapshot gap?); balances of those addresses drift');
555
+ }
556
+ }
557
+ }
558
+ if (assetHistoryRows.length)
559
+ await tx.run(UPSERT.into(CardanoODataService_1.AssetHistory).entries(assetHistoryRows));
560
+ // Catalogue last; collecting the units is skipped entirely when the catalogue is off.
561
+ const newAssets = this.crawlAssetCatalogue === 'off'
562
+ ? 0
563
+ : await this.ensureAssetRows(tx, this.collectBlockUnits(txs, assetHistoryRows));
564
+ logger.debug(`indexBlockFull: block ${blockData.hash} — ${txs.length} txs, ${outputRows.length} outputs, ` +
565
+ `${assetHistoryRows.length} mint/burn, ${newAssets} new assets`);
519
566
  }
520
567
  /**
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.
568
+ * Warn once when `crawler.certificates` is on but the source reports none (`certificates`
569
+ * undefined, as with Blockfrost). `[]` means "none" and is not a warning.
570
+ */
571
+ warnIfCertificatesUnreported(txs) {
572
+ if (this.certificatesUnreportedWarned || !txs.length)
573
+ return;
574
+ if (txs.some(t => t.certificates !== undefined))
575
+ return;
576
+ this.certificatesUnreportedWarned = true;
577
+ logger.warn('crawler.certificates is enabled but the active source reports no certificates/withdrawals ' +
578
+ '(Blockfrost pagination) — TransactionCertificates/TransactionWithdrawals stay empty until ' +
579
+ 'the crawl runs on Ogmios chain-sync or Koios');
580
+ }
581
+ /**
582
+ * Backfill address/amount of bare chain-sync inputs: from this block's own outputs first,
583
+ * then earlier-indexed outputs from the DB. Inputs that already carry an address are skipped.
525
584
  */
526
585
  async resolveInputs(tx, txs) {
527
586
  // 1. In-memory index of this block's outputs (txHash#outputIndex -> {address, amount})
@@ -550,9 +609,8 @@ class CardanoIndexer {
550
609
  }
551
610
  if (!unresolved.length)
552
611
  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)
612
+ // 3. Batch-read prior-block outputs from the DB, chunked so a dense block's input set
613
+ // never exceeds a driver's bind-variable cap
556
614
  const sourceHashes = [...new Set(unresolved.map(u => u.input.txHash))];
557
615
  const addrByKey = new Map();
558
616
  const amtByKey = new Map();
@@ -581,23 +639,223 @@ class CardanoIndexer {
581
639
  }
582
640
  }
583
641
  /**
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
642
+ * Settle the fee of phase-2-invalid transactions (collateral inputs minus collateral return)
643
+ * and the block total. The declared fee is kept when the mapper already set it via
644
+ * `total_collateral` or a collateral input is not indexed locally (the sum would be short).
645
+ */
646
+ applyCollateralFees(blockData, txs) {
647
+ const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
648
+ let corrected = false;
649
+ for (const t of txs) {
650
+ // totalCollateral set = the mapper already put the charged amount in `fee`
651
+ if (!t.spendsCollaterals || t.totalCollateral != null)
652
+ continue;
653
+ const collateral = (t.inputs ?? []).filter(i => i.isCollateral);
654
+ if (!collateral.length)
655
+ continue; // nothing to derive from — leave the declared fee
656
+ const unresolved = collateral.find(i => !i.address);
657
+ if (unresolved) {
658
+ logger.warn(`collateral fee for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed ` +
659
+ `— keeping the declared fee ${t.fee}, which understates what the ledger charged`);
660
+ continue;
661
+ }
662
+ const consumed = collateral.reduce((sum, i) => sum + lovelaceOf(i.amount), 0n);
663
+ const returned = (t.outputs ?? [])
664
+ .filter(o => o.isCollateral)
665
+ .reduce((sum, o) => sum + lovelaceOf(o.amount), 0n);
666
+ const charged = consumed - returned;
667
+ if (charged < 0n) {
668
+ logger.warn(`collateral fee for ${t.hash}: return ${returned} exceeds collateral ${consumed} ` +
669
+ `— keeping the declared fee ${t.fee}`);
670
+ continue;
671
+ }
672
+ t.fee = charged.toString();
673
+ corrected = true;
674
+ }
675
+ if (corrected) {
676
+ blockData.fees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n).toString();
677
+ }
678
+ }
679
+ /**
680
+ * Mint/burn rows for a block from data in hand: the ledger's mint field when the source
681
+ * reports it (Ogmios, Koios), else Σ outputs − Σ inputs per unit, excluding reference and
682
+ * collateral inputs. A tx with an unresolvable consumed input is skipped and logged.
683
+ */
684
+ buildAssetHistoryRows(blockData, txs) {
685
+ const entries = [];
686
+ let skipped = 0;
687
+ for (const t of txs) {
688
+ let net;
689
+ if (t.mint) {
690
+ // A phase-2 failure never reaches here with a mint: the Ogmios mapper reports none.
691
+ net = new Map();
692
+ for (const m of t.mint) {
693
+ if (m.unit === 'lovelace')
694
+ continue;
695
+ net.set(m.unit, (net.get(m.unit) ?? 0n) + BigInt(m.quantity));
696
+ }
697
+ }
698
+ else {
699
+ if (t.spendsCollaterals)
700
+ continue; // no mint is applied when the script phase failed
701
+ const consumed = (t.inputs ?? []).filter(i => !i.isReference && !i.isCollateral);
702
+ const unresolved = consumed.find(i => !i.address);
703
+ if (unresolved) {
704
+ logger.warn(`mint delta for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed ` +
705
+ `— skipping, mint/burn of this transaction is not recorded`);
706
+ skipped++;
707
+ continue;
708
+ }
709
+ net = new Map();
710
+ const add = (amount, sign) => {
711
+ for (const a of amount ?? []) {
712
+ if (a.unit === 'lovelace')
713
+ continue;
714
+ net.set(a.unit, (net.get(a.unit) ?? 0n) + sign * BigInt(a.quantity));
715
+ }
716
+ };
717
+ for (const o of (t.outputs ?? []).filter(o => !o.isCollateral))
718
+ add(o.amount, 1n);
719
+ for (const i of consumed)
720
+ add(i.amount, -1n);
721
+ }
722
+ for (const [unit, quantity] of net) {
723
+ if (quantity === 0n)
724
+ continue;
725
+ entries.push({
726
+ unit,
727
+ txHash: t.hash,
728
+ action: quantity > 0n ? 'mint' : 'burn',
729
+ quantity: (quantity < 0n ? -quantity : quantity).toString(),
730
+ blockTime: blockData.time ?? null,
731
+ blockHeight: blockData.height ?? null,
732
+ });
733
+ }
734
+ }
735
+ if (skipped) {
736
+ logger.warn(`block ${blockData.hash}: mint/burn not recorded for ${skipped} transaction(s) with unresolved inputs`);
737
+ }
738
+ return (0, mappers_1.mapAssetHistory)(entries);
739
+ }
740
+ /**
741
+ * Keep the `Assets` catalogue complete for every unit the crawl meets, without provider calls.
742
+ * `Assets` is temporal, key `(validFrom, unit)`: the bare row's fixed epoch-zero stamp never
743
+ * aliases an enriched slice, so the UPSERT is safe inside the block transaction. The existence
744
+ * check uses the DB-level entity: the service projection's temporal filter hides such rows.
745
+ */
746
+ async ensureAssetRows(tx, units) {
747
+ if (this.crawlAssetCatalogue === 'off' || !units.size)
748
+ return 0;
749
+ const unknown = [...units].filter(u => !this.assetMemo.has(u));
750
+ if (!unknown.length)
751
+ return 0;
752
+ const missing = [];
753
+ for (const unitChunk of (0, collections_1.chunk)(unknown, collections_1.IN_CHUNK)) {
754
+ const rows = await tx.run(SELECT.from(cardano_1.Assets).columns('unit').where({ unit: { in: unitChunk } }));
755
+ const known = new Set(rows.map(r => r.unit));
756
+ for (const unit of unitChunk) {
757
+ if (known.has(unit))
758
+ this.noteAssetSeen(unit);
759
+ else
760
+ missing.push(unit);
761
+ }
762
+ }
763
+ if (!missing.length)
764
+ return 0;
765
+ const rows = missing.map(mappers_1.mapBareAsset).filter((r) => r !== null);
766
+ // Chunked like the lookup: a mint-storm block can carry thousands of fresh units.
767
+ for (const rowChunk of (0, collections_1.chunk)(rows, collections_1.IN_CHUNK)) {
768
+ await tx.run(UPSERT.into(cardano_1.Assets).entries(rowChunk));
769
+ }
770
+ // Memoize also the units mapBareAsset rejected, so they cost no SELECT per block.
771
+ for (const unit of missing)
772
+ this.noteAssetSeen(unit);
773
+ if (this.crawlAssetCatalogue === 'enrich' && rows.length) {
774
+ for (const row of rows) {
775
+ if (this.enrichQueue.length >= CardanoIndexer.ENRICH_QUEUE_CAP)
776
+ this.enrichQueue.shift();
777
+ this.enrichQueue.push(row.unit);
778
+ }
779
+ this.startAssetEnrichment();
780
+ }
781
+ return rows.length;
782
+ }
783
+ /**
784
+ * Remember a unit as present in the catalogue. Insertion-ordered eviction keeps a long
785
+ * backfill's memory flat; losing an entry costs one SELECT, never a wrong write.
588
786
  */
787
+ noteAssetSeen(unit) {
788
+ if (this.assetMemo.has(unit))
789
+ return;
790
+ if (this.assetMemo.size >= CardanoIndexer.ASSET_MEMO_CAP) {
791
+ const oldest = this.assetMemo.values().next();
792
+ if (!oldest.done)
793
+ this.assetMemo.delete(oldest.value);
794
+ }
795
+ this.assetMemo.add(unit);
796
+ }
797
+ /**
798
+ * Snapshot every pool and DRep for an epoch in its OWN transaction (after the block commit):
799
+ * dated snapshot rows plus a refresh of the live `Pools` / `Dreps` rows. Needs Koios, else a no-op.
800
+ * @returns counts written
801
+ */
802
+ async snapshotEpoch(epoch, at) {
803
+ const backend = this.client.getEnumeratingBackend();
804
+ if (!backend) {
805
+ logger.warn(`epoch ${epoch} snapshot skipped: no backend can enumerate pools/DReps (Koios required)`);
806
+ return { pools: 0, dreps: 0 };
807
+ }
808
+ // Network first, DB second — the provider round-trips must not run with a write lock held.
809
+ const [poolData, drepData] = await Promise.all([
810
+ backend.getPoolIds().then(ids => backend.getPools(ids)),
811
+ backend.getDrepIds().then(ids => backend.getDreps(ids)),
812
+ ]);
813
+ const poolSnapshots = poolData.map(p => (0, mappers_1.mapPoolSnapshot)(p, epoch, at));
814
+ const drepSnapshots = drepData.map(d => (0, mappers_1.mapDrepSnapshot)(d, epoch, at));
815
+ const poolRows = poolData.map(p => (0, mappers_1.mapPool)(p, this.client.max_age_ms));
816
+ const drepRows = drepData.map(d => (0, mappers_1.mapDrep)(d, this.client.max_age_ms));
817
+ await cds_1.default.tx(async (tx) => {
818
+ // Chunked so a mainnet-sized set cannot exceed a driver's bind-variable cap.
819
+ for (const rows of (0, collections_1.chunk)(poolSnapshots, collections_1.IN_CHUNK))
820
+ await tx.run(UPSERT.into(CardanoODataService_1.PoolEpochSnapshots).entries(rows));
821
+ for (const rows of (0, collections_1.chunk)(drepSnapshots, collections_1.IN_CHUNK))
822
+ await tx.run(UPSERT.into(CardanoODataService_1.DrepEpochSnapshots).entries(rows));
823
+ for (const rows of (0, collections_1.chunk)(poolRows, collections_1.IN_CHUNK))
824
+ await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(rows));
825
+ for (const rows of (0, collections_1.chunk)(drepRows, collections_1.IN_CHUNK))
826
+ await tx.run(UPSERT.into(CardanoODataService_1.Dreps).entries(rows));
827
+ });
828
+ logger.info(`epoch ${epoch} snapshot: ${poolSnapshots.length} pools, ${drepSnapshots.length} DReps`);
829
+ return { pools: poolSnapshots.length, dreps: drepSnapshots.length };
830
+ }
831
+ /** Every native-asset unit a block touches: outputs, consumed inputs and mint/burn rows. */
832
+ collectBlockUnits(txs, assetHistoryRows) {
833
+ const units = new Set();
834
+ for (const t of txs) {
835
+ for (const o of t.outputs ?? []) {
836
+ for (const a of o.amount ?? [])
837
+ if (a.unit !== 'lovelace')
838
+ units.add(a.unit);
839
+ }
840
+ for (const i of t.inputs ?? []) {
841
+ for (const a of i.amount ?? [])
842
+ if (a.unit !== 'lovelace')
843
+ units.add(a.unit);
844
+ }
845
+ }
846
+ for (const row of assetHistoryRows)
847
+ if (row.unit)
848
+ units.add(row.unit);
849
+ return units;
850
+ }
851
+ /** Index an epoch by number. */
589
852
  async indexEpoch(tx, epochNumber) {
590
853
  const epochInfo = await this.client.getEpoch(epochNumber);
591
854
  const epochEntity = (0, mappers_1.mapEpoch)(epochInfo);
592
855
  await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([epochEntity]));
593
856
  return epochEntity;
594
857
  }
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
- */
858
+ /** Index an account by stake address, plus its addresses when it has any. */
601
859
  async indexAccount(tx, stakeAddress) {
602
860
  const accountInfo = await this.client.getAccount(stakeAddress);
603
861
  const accountEntity = (0, mappers_1.mapAccount)(accountInfo, this.client.max_age_ms);
@@ -608,36 +866,21 @@ class CardanoIndexer {
608
866
  }
609
867
  return accountEntity;
610
868
  }
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
- */
869
+ /** Index a DRep by bech32 id. */
617
870
  async indexDrep(tx, drepId) {
618
871
  const drepInfo = await this.client.getDrep(drepId);
619
872
  const drepEntity = (0, mappers_1.mapDrep)(drepInfo, this.client.max_age_ms);
620
873
  await tx.run(UPSERT.into(CardanoODataService_1.Dreps).entries(drepEntity));
621
874
  return drepEntity;
622
875
  }
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
- */
876
+ /** Index a pool by id. */
629
877
  async indexPool(tx, poolId) {
630
878
  const poolInfo = await this.client.getPool(poolId);
631
879
  const poolEntity = (0, mappers_1.mapPool)(poolInfo, this.client.max_age_ms);
632
880
  await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(poolEntity));
633
881
  return poolEntity;
634
882
  }
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
- */
883
+ /** Index an asset by unit (policyId + assetNameHex). */
641
884
  async indexAsset(tx, unit) {
642
885
  const assetInfo = await this.client.getAssetInfo(unit);
643
886
  const assetEntity = (0, mappers_1.mapAsset)(assetInfo, this.client.max_age_ms);
@@ -645,14 +888,8 @@ class CardanoIndexer {
645
888
  return assetEntity;
646
889
  }
647
890
  /**
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
891
+ * Index mint/burn history for an asset, always fresh. Rows are keyed (unit, txHash), so a
892
+ * refetch refreshes the recent cap and older cached entries persist.
656
893
  */
657
894
  async indexAssetHistory(tx, unit, limit = 100) {
658
895
  const events = await this.client.getAssetHistory(unit, limit);
@@ -662,14 +899,7 @@ class CardanoIndexer {
662
899
  await tx.run(UPSERT.into(CardanoODataService_1.AssetHistory).entries(rows));
663
900
  return rows;
664
901
  }
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
- */
902
+ /** Build a transaction and persist the build result with inputs/outputs/address association. */
673
903
  async _indexBuildResult(tx, buildreq, buildFn) {
674
904
  const protocolParams = await this.indexProtocolParameters(tx);
675
905
  const txbuildResult = await buildFn(buildreq, protocolParams);
@@ -703,52 +933,36 @@ class CardanoIndexer {
703
933
  async indexPlutusSpendBuildResult(tx, buildreq) {
704
934
  return this._indexBuildResult(tx, buildreq, (req, params) => this.txBuilder.buildPlutusSpendTransaction(req, params));
705
935
  }
706
- /**
707
- * Index & return the protocol parameters data
708
- * @param tx CAP transaction object
709
- * @returns {Promise<LedgerProtocolParameter>} protocol parameters entity data
710
- */
936
+ /** Protocol parameters, served from the DB row within a 5-minute TTL. */
711
937
  async indexProtocolParameters(tx) {
712
938
  const network = this.client.network;
713
939
  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
940
+ const PROTOCOL_PARAMS_TTL_MS = 5 * 60 * 1000; // matches the client cache TTL
716
941
  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.
942
+ // (network, epoch) is the key; order by epoch desc to get the latest row
719
943
  const existing = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerProtocolParameter).where({ network }).orderBy('epoch desc'));
720
944
  if (existing)
721
945
  return existing;
722
946
  }
723
- // Fetch from provider (client has 5-min in-memory TTL cache, so this is cheap)
724
947
  const protocolParamsInfo = await this.client.getProtocolParameters();
725
948
  const protocolParams = (0, mappers_1.mapProtocolParameters)(protocolParamsInfo);
726
949
  await tx.run(UPSERT.into(CardanoODataService_1.LedgerProtocolParameter).entries(protocolParams));
727
950
  this.lastParamsFetchTime = now;
728
951
  return protocolParams;
729
952
  }
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
- */
953
+ /** Persist a transaction submission and flag the build as submitted when linked. */
737
954
  async persistTransactionSubmission(tx, params) {
738
955
  const { signedTxCbor, txHash, buildId } = params;
739
- // Map submission data
740
956
  const indexSubmission = (0, mappers_1.mapTransactionSubmission)(signedTxCbor, txHash);
741
- // Create submission record (status: 'pending' — updated to 'submitted' after blockchain confirms)
957
+ // status 'pending' until the second phase of the submit flow confirms
742
958
  const submissionRecord = {
743
959
  ...indexSubmission,
744
960
  build_id: buildId || null,
745
961
  backendResponse: 'Submitted successfully',
746
962
  status: 'pending',
747
963
  };
748
- // Persist submission
749
964
  await tx.run(INSERT.into(CardanoTransactionService_1.TransactionSubmissions).entries(submissionRecord));
750
965
  logger.debug({ submissionId: submissionRecord.id, txHash }, 'Persisted submission record');
751
- // Update build status if buildId provided
752
966
  if (buildId) {
753
967
  await tx.run(UPDATE.entity(CardanoTransactionService_1.TransactionBuilds)
754
968
  .set({ wasSubmitted: true })
@@ -757,14 +971,7 @@ class CardanoIndexer {
757
971
  }
758
972
  return submissionRecord;
759
973
  }
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
- */
974
+ /** Update a submission's status (two-phase submit: pending → submitted or failed). */
768
975
  async updateSubmissionStatus(tx, submissionId, status, errorMessage) {
769
976
  const updateData = { status };
770
977
  if (errorMessage) {
@@ -775,15 +982,9 @@ class CardanoIndexer {
775
982
  .where({ id: submissionId }));
776
983
  logger.debug({ submissionId, status }, 'Updated submission status');
777
984
  }
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
- */
985
+ /** Persist a new signing request and link it to the build's sender address. */
784
986
  async persistSigningRequest(tx, params) {
785
987
  const { buildId, signingPayload } = params;
786
- // Create signing request record
787
988
  const signingRequestRecord = {
788
989
  id: signingPayload.signingRequestId,
789
990
  build_id: buildId,
@@ -796,26 +997,17 @@ class CardanoIndexer {
796
997
  cardanoCliCommand: signingPayload.signingInstructions.cardanoCliCommand,
797
998
  cip30TxCbor: signingPayload.signingInstructions.cip30SigningRequest?.txCbor,
798
999
  };
799
- // Persist to database
800
1000
  await tx.run(INSERT.into(CardanoSignService_1.SigningRequests).entries(signingRequestRecord));
801
1001
  logger.debug({ signingRequestId: signingRequestRecord.id, buildId }, 'Persisted signing request');
802
- // Index address-signing request association
803
1002
  const build = await tx.run(SELECT.one.from(CardanoTransactionService_1.TransactionBuilds).where({ id: buildId }));
804
1003
  if (build?.senderAddress) {
805
1004
  await this.indexAddressSigningRequests(tx, build.senderAddress, signingRequestRecord.id);
806
1005
  }
807
1006
  return signingRequestRecord;
808
1007
  }
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
- */
1008
+ /** Persist a signature verification and update the signing request status. */
816
1009
  async persistSignatureVerification(tx, params) {
817
1010
  const { signingRequestId, signedTxCbor, verificationResult, signerType, signerInfo } = params;
818
- // Create verification record
819
1011
  const verificationRecord = {
820
1012
  id: cds_1.default.utils.uuid(),
821
1013
  signingRequest_id: signingRequestId,
@@ -828,10 +1020,8 @@ class CardanoIndexer {
828
1020
  warnings: JSON.stringify(verificationResult.warnings),
829
1021
  verifiedAt: new Date().toISOString(),
830
1022
  };
831
- // Persist verification
832
1023
  await tx.run(INSERT.into(CardanoSignService_1.SignatureVerifications).entries(verificationRecord));
833
1024
  logger.debug({ verificationId: verificationRecord.id }, 'Persisted signature verification record');
834
- // Update signing request status
835
1025
  const newStatus = verificationResult.isValid ? 'verified' : 'failed';
836
1026
  await tx.run(UPDATE.entity(CardanoSignService_1.SigningRequests)
837
1027
  .set({
@@ -845,16 +1035,9 @@ class CardanoIndexer {
845
1035
  logger.debug({ signingRequestId, newStatus }, 'Updated signing request status');
846
1036
  return verificationRecord;
847
1037
  }
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
- */
1038
+ /** Persist a verified submission: verification, submission, signing request and build updates. */
855
1039
  async indexVerifiedTransactionSubmission(tx, params) {
856
1040
  const { signingRequestId, buildId, fullSignedTxCbor, txHash, verificationResult, signerType, signerInfo } = params;
857
- // Step 1: Create and persist verification record
858
1041
  const verificationRecord = {
859
1042
  id: cds_1.default.utils.uuid(),
860
1043
  signingRequest_id: signingRequestId,
@@ -869,7 +1052,6 @@ class CardanoIndexer {
869
1052
  };
870
1053
  await tx.run(INSERT.into(CardanoSignService_1.SignatureVerifications).entries(verificationRecord));
871
1054
  logger.debug({ verificationId: verificationRecord.id }, 'Persisted signature verification record');
872
- // Step 2: Create and persist submission record
873
1055
  const indexSubmission = (0, mappers_1.mapTransactionSubmission)(fullSignedTxCbor, txHash);
874
1056
  const submissionRecord = {
875
1057
  ...indexSubmission,
@@ -879,7 +1061,6 @@ class CardanoIndexer {
879
1061
  };
880
1062
  await tx.run(INSERT.into(CardanoTransactionService_1.TransactionSubmissions).entries(submissionRecord));
881
1063
  logger.debug({ submissionId: submissionRecord.id }, 'Persisted submission record');
882
- // Step 3: Update signing request metadata and status
883
1064
  const now = new Date().toISOString();
884
1065
  await tx.run(UPDATE.entity(CardanoSignService_1.SigningRequests)
885
1066
  .set({
@@ -892,29 +1073,20 @@ class CardanoIndexer {
892
1073
  })
893
1074
  .where({ id: signingRequestId }));
894
1075
  logger.debug({ signingRequestId }, 'Updated signing request status to submitted');
895
- // Step 4: Update build status
896
1076
  await tx.run(UPDATE.entity(CardanoTransactionService_1.TransactionBuilds)
897
1077
  .set({ wasSubmitted: true })
898
1078
  .where({ id: buildId }));
899
1079
  logger.debug({ buildId }, 'Updated build wasSubmitted flag');
900
1080
  return submissionRecord;
901
1081
  }
902
- /**
903
- * Index & return the latest epoch information data
904
- * @param tx CAP transaction object
905
- * @returns {Promise<Epoch>} epoch entity data
906
- */
1082
+ /** Index the latest epoch. */
907
1083
  async indexLatestEpoch(tx) {
908
1084
  const epochInfo = await this.client.getLatestEpoch();
909
1085
  const epochEntity = (0, mappers_1.mapEpoch)(epochInfo);
910
1086
  await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([epochEntity]));
911
1087
  return epochEntity;
912
1088
  }
913
- /**
914
- * Index & return the latest block information data
915
- * @param tx CAP transaction object
916
- * @returns {Promise<Block>} block entity data
917
- */
1089
+ /** Index the latest block, with best-effort epoch enrichment. */
918
1090
  async indexLatestBlock(tx) {
919
1091
  const blockInfo = await this.client.getLatestBlock();
920
1092
  let epoch;
@@ -934,30 +1106,20 @@ class CardanoIndexer {
934
1106
  /** Max addresses to index concurrently (avoid overloading backends) */
935
1107
  static ADDR_CONCURRENCY = 5;
936
1108
  /**
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)
1109
+ * Ensure a set of transactions is indexed: DB check, batch fetch of the missing ones, UPSERT.
1110
+ * @returns provider transactions for the hashes that had to be fetched
946
1111
  */
947
1112
  async ensureTransactionsIndexed(tx, txHashes) {
948
1113
  const unique = [...new Set(txHashes)];
949
1114
  if (unique.length === 0)
950
1115
  return new Map();
951
- // DB check — which hashes are already indexed?
952
1116
  const existingRows = await tx.run(SELECT.from(CardanoODataService_1.Transactions).columns('hash').where({ hash: { in: unique } }));
953
1117
  const existingSet = new Set(existingRows.map((r) => r.hash));
954
1118
  const missing = unique.filter(h => !existingSet.has(h));
955
1119
  logger.debug(`ensureTransactionsIndexed: ${unique.length} unique, ${existingSet.size} cached, ${missing.length} to fetch`);
956
- // Batch-fetch missing from backend
957
1120
  let fetched = new Map();
958
1121
  if (missing.length > 0) {
959
1122
  fetched = await this.client.getTransactionsBatch(missing);
960
- // UPSERT all fetched transactions + child entities
961
1123
  for (const [, providerTx] of fetched) {
962
1124
  const txRow = (0, mappers_1.mapTransaction)(providerTx);
963
1125
  await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRow));
@@ -988,12 +1150,7 @@ class CardanoIndexer {
988
1150
  //-----------------------------------------------------------------------------
989
1151
  // Private Helpers
990
1152
  //-----------------------------------------------------------------------------
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
- */
1153
+ /** Index addresses with bounded concurrency. */
997
1154
  async _ensureAddresses(tx, bech32List) {
998
1155
  const concurrency = CardanoIndexer.ADDR_CONCURRENCY;
999
1156
  for (let i = 0; i < bech32List.length; i += concurrency) {