@odatano/core 2.0.0-rc.5 → 2.0.0-rc.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +358 -0
  4. package/@cds-models/CardanoBackendService/index.js +41 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
  6. package/@cds-models/CardanoIndexerService/index.js +74 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +417 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +45 -19
  10. package/@cds-models/CardanoSignService/index.js +4 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
  12. package/@cds-models/CardanoTransactionService/index.js +5 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
  14. package/@cds-models/CardanoWorkerService/index.js +2 -0
  15. package/@cds-models/index.d.ts +114 -4
  16. package/@cds-models/index.js +20 -4
  17. package/@cds-models/odatano/cardano/index.d.ts +451 -32
  18. package/@cds-models/odatano/cardano/index.js +48 -0
  19. package/README.md +103 -167
  20. package/db/schema.cds +2455 -1705
  21. package/db/types.cds +456 -295
  22. package/package.json +41 -53
  23. package/scripts/deploy-schema.mjs +113 -0
  24. package/scripts/migrate-schema.mjs +528 -0
  25. package/scripts/migrate-slot-leader.mjs +96 -0
  26. package/src/index.d.ts +20 -21
  27. package/src/index.js +45 -31
  28. package/src/plugin.js +17 -35
  29. package/srv/blockchain/asset-decimals.d.ts +7 -0
  30. package/srv/blockchain/asset-decimals.js +91 -0
  31. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
  32. package/srv/blockchain/backends/blockfrost-backend.js +125 -215
  33. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  34. package/srv/blockchain/backends/call-signal.js +22 -0
  35. package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
  36. package/srv/blockchain/backends/cardano-backend.js +29 -5
  37. package/srv/blockchain/backends/koios-backend.d.ts +108 -170
  38. package/srv/blockchain/backends/koios-backend.js +488 -482
  39. package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
  40. package/srv/blockchain/backends/odatano-backend.js +211 -0
  41. package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
  42. package/srv/blockchain/backends/ogmios-backend.js +683 -327
  43. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  44. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  45. package/srv/blockchain/cardano-client.d.ts +71 -241
  46. package/srv/blockchain/cardano-client.js +354 -322
  47. package/srv/blockchain/cardano-indexer.d.ts +295 -283
  48. package/srv/blockchain/cardano-indexer.js +1690 -502
  49. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  50. package/srv/blockchain/cardano-tx-builder.js +164 -140
  51. package/srv/blockchain/circuit-breaker.d.ts +2 -13
  52. package/srv/blockchain/circuit-breaker.js +11 -15
  53. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  54. package/srv/blockchain/crawler/account-snapshots.js +173 -0
  55. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
  56. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  57. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
  58. package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
  59. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  60. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  61. package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
  62. package/srv/blockchain/crawler/certificate-backfill.js +174 -0
  63. package/srv/blockchain/crawler/crawler.d.ts +125 -81
  64. package/srv/blockchain/crawler/crawler.js +738 -167
  65. package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
  66. package/srv/blockchain/crawler/credential-backfill.js +101 -0
  67. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  68. package/srv/blockchain/crawler/index.d.ts +1 -8
  69. package/srv/blockchain/crawler/index.js +31 -17
  70. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  71. package/srv/blockchain/crawler/input-asset-copies.js +161 -0
  72. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  73. package/srv/blockchain/crawler/key-pages.js +48 -0
  74. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
  75. package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
  76. package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
  77. package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
  78. package/srv/blockchain/crawler/sync-state.d.ts +31 -47
  79. package/srv/blockchain/crawler/sync-state.js +135 -128
  80. package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
  81. package/srv/blockchain/crawler/transaction-backfill.js +271 -0
  82. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  83. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  84. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  85. package/srv/blockchain/crawler/window-plan.js +59 -0
  86. package/srv/blockchain/ledger-state.d.ts +62 -0
  87. package/srv/blockchain/ledger-state.js +521 -0
  88. package/srv/blockchain/pending-spends.d.ts +16 -0
  89. package/srv/blockchain/pending-spends.js +81 -0
  90. package/srv/blockchain/pool-metadata.d.ts +15 -0
  91. package/srv/blockchain/pool-metadata.js +132 -0
  92. package/srv/blockchain/request-coalescer.d.ts +2 -16
  93. package/srv/blockchain/request-coalescer.js +2 -16
  94. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  95. package/srv/blockchain/signing/cose-verifier.js +146 -70
  96. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  97. package/srv/blockchain/signing/external-signer.js +22 -131
  98. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  99. package/srv/blockchain/signing/failed-recheck.js +135 -0
  100. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  101. package/srv/blockchain/signing/hsm-signer.js +28 -79
  102. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  103. package/srv/blockchain/signing/landing-proof.js +224 -0
  104. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  105. package/srv/blockchain/signing/signature-verifier.js +71 -87
  106. package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
  107. package/srv/blockchain/signing/submission-finalizer.js +280 -86
  108. package/srv/blockchain/stored-chain.d.ts +19 -0
  109. package/srv/blockchain/stored-chain.js +258 -0
  110. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  111. package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
  112. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  113. package/srv/blockchain/transaction-presence.d.ts +12 -0
  114. package/srv/blockchain/transaction-presence.js +29 -0
  115. package/srv/blockchain/transaction-rows.d.ts +12 -0
  116. package/srv/blockchain/transaction-rows.js +44 -0
  117. package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
  118. package/srv/blockchain/wallet-worker/build-request.js +40 -353
  119. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
  120. package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
  121. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  122. package/srv/blockchain/wallet-worker/index.js +3 -11
  123. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  124. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  125. package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
  126. package/srv/blockchain/wallet-worker/job-store.js +200 -273
  127. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  128. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  129. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  130. package/srv/blockchain/wallet-worker/signers.js +4 -12
  131. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
  132. package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
  133. package/srv/cardano-agent-service.cds +122 -84
  134. package/srv/cardano-agent-service.js +12 -9
  135. package/srv/cardano-backend-service.cds +81 -0
  136. package/srv/cardano-backend-service.d.ts +2 -0
  137. package/srv/cardano-backend-service.js +259 -0
  138. package/srv/cardano-indexer-service.cds +393 -18
  139. package/srv/cardano-indexer-service.d.ts +5 -1
  140. package/srv/cardano-indexer-service.js +477 -16
  141. package/srv/cardano-service.cds +426 -269
  142. package/srv/cardano-service.js +640 -217
  143. package/srv/cardano-sign-service.cds +211 -180
  144. package/srv/cardano-sign-service.js +210 -287
  145. package/srv/cardano-tx-service.cds +462 -370
  146. package/srv/cardano-tx-service.js +283 -800
  147. package/srv/cardano-ui.cds +16 -16
  148. package/srv/cardano-worker-service.cds +141 -125
  149. package/srv/cardano-worker-service.js +104 -61
  150. package/srv/cbor/cip68.d.ts +13 -0
  151. package/srv/cbor/cip68.js +56 -0
  152. package/srv/cbor/index.d.ts +3 -1
  153. package/srv/cbor/index.js +9 -1
  154. package/srv/cbor/parse.d.ts +30 -18
  155. package/srv/cbor/parse.js +44 -9
  156. package/srv/cbor/plutus-data-json.d.ts +20 -0
  157. package/srv/cbor/plutus-data-json.js +32 -0
  158. package/srv/config.d.ts +117 -0
  159. package/srv/config.js +419 -0
  160. package/srv/server.d.ts +15 -110
  161. package/srv/server.js +83 -405
  162. package/srv/utils/agent-access.d.ts +11 -0
  163. package/srv/utils/agent-access.js +86 -0
  164. package/srv/utils/agent-grants-config.d.ts +0 -46
  165. package/srv/utils/agent-grants-config.js +17 -85
  166. package/srv/utils/agent-grants.d.ts +106 -122
  167. package/srv/utils/agent-grants.js +538 -237
  168. package/srv/utils/agent-token-auth.d.ts +4 -99
  169. package/srv/utils/agent-token-auth.js +62 -186
  170. package/srv/utils/backend-request-handler.d.ts +3 -17
  171. package/srv/utils/backend-request-handler.js +3 -18
  172. package/srv/utils/build-request.d.ts +52 -0
  173. package/srv/utils/build-request.js +487 -0
  174. package/srv/utils/collections.d.ts +4 -10
  175. package/srv/utils/collections.js +14 -10
  176. package/srv/utils/const.d.ts +32 -75
  177. package/srv/utils/const.js +40 -80
  178. package/srv/utils/crypto.d.ts +3 -12
  179. package/srv/utils/crypto.js +11 -25
  180. package/srv/utils/db-indexes.d.ts +31 -0
  181. package/srv/utils/db-indexes.js +185 -0
  182. package/srv/utils/db-kind.d.ts +23 -0
  183. package/srv/utils/db-kind.js +42 -0
  184. package/srv/utils/db-sanitize.d.ts +20 -0
  185. package/srv/utils/db-sanitize.js +80 -0
  186. package/srv/utils/deep-json.d.ts +6 -0
  187. package/srv/utils/deep-json.js +240 -0
  188. package/srv/utils/detached-run.d.ts +41 -0
  189. package/srv/utils/detached-run.js +101 -0
  190. package/srv/utils/epoch-slots.d.ts +14 -0
  191. package/srv/utils/epoch-slots.js +45 -0
  192. package/srv/utils/error-codes.d.ts +26 -75
  193. package/srv/utils/error-codes.js +27 -72
  194. package/srv/utils/errors.d.ts +55 -187
  195. package/srv/utils/errors.js +161 -235
  196. package/srv/utils/lease.d.ts +20 -0
  197. package/srv/utils/lease.js +62 -0
  198. package/srv/utils/liveness.d.ts +12 -0
  199. package/srv/utils/liveness.js +35 -0
  200. package/srv/utils/mappers.d.ts +111 -223
  201. package/srv/utils/mappers.js +432 -371
  202. package/srv/utils/navigation.d.ts +17 -0
  203. package/srv/utils/navigation.js +52 -0
  204. package/srv/utils/network-context.d.ts +0 -1
  205. package/srv/utils/network-context.js +9 -15
  206. package/srv/utils/paging.d.ts +31 -0
  207. package/srv/utils/paging.js +43 -0
  208. package/srv/utils/pg-inline-json.d.ts +8 -0
  209. package/srv/utils/pg-inline-json.js +58 -0
  210. package/srv/utils/pg-order-nulls.d.ts +14 -0
  211. package/srv/utils/pg-order-nulls.js +54 -0
  212. package/srv/utils/plutus-placeholders.d.ts +16 -22
  213. package/srv/utils/plutus-placeholders.js +62 -33
  214. package/srv/utils/rate-limiter.d.ts +2 -21
  215. package/srv/utils/rate-limiter.js +5 -17
  216. package/srv/utils/readiness.d.ts +12 -0
  217. package/srv/utils/readiness.js +29 -0
  218. package/srv/utils/reference-script.d.ts +19 -0
  219. package/srv/utils/reference-script.js +84 -0
  220. package/srv/utils/resolution.d.ts +13 -0
  221. package/srv/utils/resolution.js +47 -0
  222. package/srv/utils/result-numbers.d.ts +15 -0
  223. package/srv/utils/result-numbers.js +61 -0
  224. package/srv/utils/row-values.d.ts +7 -0
  225. package/srv/utils/row-values.js +27 -0
  226. package/srv/utils/service-events.d.ts +0 -24
  227. package/srv/utils/service-events.js +3 -25
  228. package/srv/utils/signing-helper.d.ts +3 -20
  229. package/srv/utils/signing-helper.js +35 -64
  230. package/srv/utils/tx-build-helper.d.ts +25 -105
  231. package/srv/utils/tx-build-helper.js +108 -156
  232. package/srv/utils/tx-request-parsers.d.ts +82 -33
  233. package/srv/utils/tx-request-parsers.js +401 -49
  234. package/srv/utils/tx-utils.d.ts +3 -27
  235. package/srv/utils/tx-utils.js +32 -50
  236. package/srv/utils/types.d.ts +294 -232
  237. package/srv/utils/types.js +2 -22
  238. package/srv/utils/validators.d.ts +22 -92
  239. package/srv/utils/validators.js +60 -170
@@ -4,51 +4,453 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.CardanoIndexer = void 0;
7
+ exports.accountAddressList = accountAddressList;
8
+ exports.parseAccountAddressList = parseAccountAddressList;
7
9
  const cds_1 = __importDefault(require("@sap/cds"));
8
10
  const CardanoODataService_1 = require("#cds-models/CardanoODataService");
9
11
  const CardanoTransactionService_1 = require("#cds-models/CardanoTransactionService");
10
12
  const CardanoSignService_1 = require("#cds-models/CardanoSignService");
13
+ // DB-level entity: the catalogue's existence check must bypass the temporal filter that the
14
+ // service projection carries (see ensureAssetRows).
15
+ const cardano_1 = require("#cds-models/odatano/cardano");
11
16
  const mappers_1 = require("../utils/mappers");
17
+ const errors_1 = require("../utils/errors");
12
18
  const collections_1 = require("../utils/collections");
19
+ const deep_json_1 = require("../utils/deep-json");
20
+ const tx_utils_1 = require("../utils/tx-utils");
21
+ const transaction_rows_1 = require("./transaction-rows");
22
+ const ledger_state_1 = require("./ledger-state");
23
+ const sync_state_1 = require("./crawler/sync-state");
24
+ const window_plan_1 = require("./crawler/window-plan");
25
+ const asset_decimals_1 = require("./asset-decimals");
26
+ const cip68_1 = require("../cbor/cip68");
27
+ const pool_metadata_1 = require("./pool-metadata");
28
+ const epoch_slots_1 = require("../utils/epoch-slots");
29
+ const const_1 = require("../utils/const");
13
30
  const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
14
31
  const logger = cds_1.default.log('CardanoIndexer');
15
- /**
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.
27
- */
32
+ /** The address list of an account as stored: unique and sorted. */
33
+ function accountAddressList(addresses) {
34
+ return [...new Set(addresses)].sort();
35
+ }
36
+ /** Reads `Accounts.addressList`; null when the column is empty or not a list of addresses. */
37
+ function parseAccountAddressList(json) {
38
+ if (typeof json !== 'string' || !json)
39
+ return null;
40
+ try {
41
+ const list = JSON.parse(json);
42
+ return Array.isArray(list) && list.every((a) => typeof a === 'string') ? accountAddressList(list) : null;
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
48
+ /** Newest first; the tx hash breaks ties inside one block. */
49
+ function sortAddressTransactions(rows) {
50
+ return rows.sort((a, b) => Number(b.blockTime ?? 0) - Number(a.blockTime ?? 0) || String(b.tx_hash).localeCompare(String(a.tx_hash)));
51
+ }
52
+ /** Datum hash, inline datum and reference script of the spent output onto its input. */
53
+ function copyUtxoData(input, out) {
54
+ input.dataHash = input.dataHash ?? out.utxo_dataHash ?? null;
55
+ input.inlineDatum = input.inlineDatum ?? out.utxo_inlineDatum ?? null;
56
+ input.referenceScriptHash = input.referenceScriptHash ?? out.utxo_referenceScriptHash ?? null;
57
+ input.referenceScriptSize = input.referenceScriptSize ?? out.utxo_referenceScriptSize ?? null;
58
+ input.referenceScriptType = input.referenceScriptType ?? out.utxo_referenceScriptType ?? null;
59
+ }
60
+ /** A provider output in the stored-column shape, for copyUtxoData. */
61
+ function utxoDataOf(o) {
62
+ return {
63
+ utxo_dataHash: o.dataHash,
64
+ utxo_inlineDatum: o.inlineDatum,
65
+ utxo_referenceScriptHash: o.referenceScriptHash,
66
+ utxo_referenceScriptSize: o.referenceScriptSize,
67
+ utxo_referenceScriptType: o.referenceScriptType,
68
+ };
69
+ }
70
+ function lovelaceSum(value) {
71
+ if (value === null || value === undefined || value === '')
72
+ return '0';
73
+ return typeof value === 'number' ? BigInt(Math.trunc(value)).toString() : String(value).split('.')[0];
74
+ }
75
+ /** Provider-shaped address from its unspent outputs: type and stake address decoded from the address. */
76
+ function addressFromUtxos(address, utxos) {
77
+ const decoded = (0, mappers_1.decodeShelleyAddress)(address);
78
+ return { address, stakeAddress: decoded.stakeAddress, type: decoded.type, isScript: decoded.isScript, amount: (0, mappers_1.sumUtxoAmounts)(utxos), utxos };
79
+ }
80
+ /** Fetches chain data, maps it to entity rows and UPSERTs them in the caller's transaction. */
28
81
  class CardanoIndexer {
29
82
  client;
30
83
  txBuilder;
31
84
  lastParamsFetchTime = 0;
32
85
  static CRAWL_EPOCH_REFRESH_MS = 5 * 60 * 1000;
33
86
  static CRAWL_EPOCH_RETRY_MS = 30 * 1000;
34
- /**
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.
43
- */
87
+ // Crawler epoch memo for the current and previous epoch, refreshed while an epoch is live.
88
+ // A row is UPSERTed again until a block transaction that wrote it has committed.
44
89
  crawlEpochCache = new Map();
45
90
  crawlEpochCurrent = null;
91
+ /** Committed epoch rows and the final flag they were written with; a refresh creates a new row object. */
92
+ crawlEpochWritten = new WeakMap();
93
+ /** Memo updates of the running block transaction, applied only after its commit. */
94
+ pendingCommit = [];
46
95
  crawlEpochPrevious = null;
47
- /**
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.
51
- */
96
+ /** Analytics coverage of the crawl path; defaults mirror the crawler config defaults. */
97
+ crawlAssetHistory = true;
98
+ crawlAssetCatalogue = 'bare';
99
+ /** Certificates + withdrawals per block (ledger-state coverage). Opt-in. */
100
+ crawlCertificates = false;
101
+ /** Logged once per process: the active source reports no certificates (Blockfrost). */
102
+ certificatesUnreportedWarned = false;
103
+ /** Blocks after utxoAnchor are applied to the Ledger* tables. Without an anchor the mode is inactive. */
104
+ crawlUtxoSet = false;
105
+ /** crawler.authoritative: misses in the crawled chain are 404, no provider call. */
106
+ crawlAuthoritative = false;
107
+ /** crawler.inputAssetCopies: every crawled input keeps a copy of its assets and points at no output. */
108
+ crawlInputAssetCopies = false;
109
+ utxoAnchor = null;
110
+ /** `LedgerAddresses.paymentCredential` is complete; the running fill and its table generation. */
111
+ credentialsReady = false;
112
+ credentialFill = null;
113
+ credentialGeneration = 0;
114
+ /** The anchor block was found in the crawled chain (checked once, before the first apply). */
115
+ utxoAnchorVerified = false;
116
+ /** Kept until the crawler confirms the block commit, so a rolled-back attempt changes nothing. */
117
+ ledgerInvalidation = null;
118
+ /** Load pool metadata files from their registered URL. Off unless configured. */
119
+ poolMetadataFetch = false;
120
+ poolMetadataByHash = new Map();
121
+ static POOL_METADATA_MEMO_CAP = 10_000;
122
+ /** Units known to have an `Assets` row, so a repeat sighting costs no DB round-trip. */
123
+ static ASSET_MEMO_CAP = 200_000;
124
+ /** Output references per node lookup when checking crawled UTxOs. */
125
+ static OUTREF_CHUNK = 500;
126
+ assetMemo = new Set();
127
+ // Registry enrichment queue, drained at a fixed rate outside the block transaction.
128
+ // Above the cap the oldest units are dropped and keep their bare row.
129
+ static ENRICH_QUEUE_CAP = 50_000;
130
+ enrichQueue = [];
131
+ enrichTimer = null;
132
+ enrichRate = 2;
133
+ /** Adopt the crawler's coverage settings; the lazy request path never touches these. */
134
+ configureCrawlCoverage(coverage) {
135
+ this.crawlAuthoritative = coverage.authoritative ?? false;
136
+ this.crawlInputAssetCopies = coverage.inputAssetCopies ?? false;
137
+ this.crawlAssetHistory = coverage.assetHistory;
138
+ this.crawlAssetCatalogue = coverage.assetCatalogue;
139
+ this.crawlCertificates = coverage.certificates ?? false;
140
+ this.crawlUtxoSet = coverage.utxoSet ?? false;
141
+ this.enrichRate = coverage.assetEnrichRate ?? this.enrichRate;
142
+ if (coverage.assetCatalogue !== 'enrich')
143
+ this.stopAssetEnrichment();
144
+ }
145
+ // Range the crawled data answers authoritatively, only while a live crawler is at the tip.
146
+ // ledger is true when the crawled UTxO set is active.
147
+ async localCoverage(tx) {
148
+ const cursor = await (0, sync_state_1.readCursor)(tx);
149
+ if (!cursor || cursor.syncStatus !== 'synced' || cursor.nodeBehindSince != null || cursor.startSlot == null || !(0, sync_state_1.isCrawlerLeaseActive)(cursor))
150
+ return null;
151
+ return { fromSlot: cursor.startSlot, lastSlot: cursor.lastSlot, tipHeight: cursor.tipHeight, ledger: cursor.utxoSet.status === 'active' };
152
+ }
153
+ // Block counts of a pool from crawled blocks. The epoch count needs the whole current epoch
154
+ // crawled, the lifetime count the whole chain since Shelley.
155
+ async localPoolBlocks(tx, poolId) {
156
+ const coverage = await this.localCoverage(tx);
157
+ if (!coverage)
158
+ return {};
159
+ const network = this.client.network;
160
+ const countSince = async (fromSlot) => {
161
+ const row = await tx.run(SELECT.one.from(CardanoODataService_1.Blocks).columns('count(*) as n').where({ slotLeader: poolId, slot: { '>=': fromSlot } }));
162
+ return Number(row?.n ?? 0);
163
+ };
164
+ const counts = {};
165
+ const epochStart = (0, epoch_slots_1.epochStartSlot)(network, (0, epoch_slots_1.epochOfSlot)(network, coverage.lastSlot));
166
+ if (coverage.fromSlot < epochStart)
167
+ counts.blocksEpoch = await countSince(epochStart);
168
+ if (coverage.fromSlot <= const_1.EPOCH_CONFIG_BY_NETWORK[network].shelleyStartSlot)
169
+ counts.blocksMinted = await countSince(0);
170
+ return counts;
171
+ }
172
+ // Non-null when the crawled chain answers method alone. Needs a live crawler at the tip, a crawl
173
+ // from Shelley, and either crawler.authoritative or no backend that serves the method.
174
+ async crawlAnswers(tx, method) {
175
+ const coverage = await this.localCoverage(tx);
176
+ if (!coverage || coverage.fromSlot > const_1.EPOCH_CONFIG_BY_NETWORK[this.client.network].shelleyStartSlot)
177
+ return null;
178
+ if (!this.crawlAuthoritative && this.client.hasBackendFor(method))
179
+ return null;
180
+ return { lastSlot: coverage.lastSlot };
181
+ }
182
+ /** 404 for a lookup the crawled chain answers on its own (the caller already missed in the DB). */
183
+ async refuseOutsideCrawl(tx, method, what) {
184
+ const coverage = await this.crawlAnswers(tx, method);
185
+ if (coverage)
186
+ throw new errors_1.NotFoundError(`${what} (not in the crawled chain up to slot ${coverage.lastSlot})`);
187
+ }
188
+ // Asset from crawled mint and burn rows. Registry fields stay null.
189
+ // Null when the crawled chain does not answer.
190
+ async localAssetInfo(tx, unit) {
191
+ if (!this.crawlAssetHistory || !(await this.crawlAnswers(tx, 'getAssetInfo')))
192
+ return null;
193
+ const events = await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).columns('txHash', 'action', 'quantity', 'blockTime', 'blockHeight').where({ unit }));
194
+ if (!events?.length)
195
+ throw new errors_1.NotFoundError(`Asset ${unit} (never minted in the crawled chain)`);
196
+ const ordered = [...events].sort((a, b) => Number(a.blockHeight ?? 0) - Number(b.blockHeight ?? 0));
197
+ let supply = 0n;
198
+ for (const e of ordered)
199
+ supply += (e.action === 'burn' ? -1n : 1n) * BigInt(String(e.quantity ?? '0'));
200
+ const mints = ordered.filter(e => e.action !== 'burn');
201
+ const first = mints[0];
202
+ const latest = mints[mints.length - 1];
203
+ let onchainMetadata = null;
204
+ if (latest) {
205
+ const meta = await tx.run(SELECT.one.from(CardanoODataService_1.TransactionMetadata).columns('payload').where({ tx_hash: latest.txHash, label: '721' }));
206
+ if (meta?.payload) {
207
+ try {
208
+ onchainMetadata = (0, deep_json_1.parseJson)(meta.payload);
209
+ }
210
+ catch { /* unparseable payload: leave empty */ }
211
+ }
212
+ }
213
+ const slice = (0, mappers_1.assetSlice)(unit, supply);
214
+ return {
215
+ unit,
216
+ policyId: slice.asset_policyId ?? unit.slice(0, 56),
217
+ assetNameHex: slice.asset_assetNameHex ?? unit.slice(56),
218
+ assetName: slice.asset_assetName,
219
+ fingerprint: slice.asset_fingerprint ?? (0, mappers_1.computeCip14Fingerprint)(unit.slice(0, 56), unit.slice(56)),
220
+ totalSupply: supply.toString(),
221
+ mintOrBurnCount: ordered.length,
222
+ initialMintTxHash: first?.txHash ?? null,
223
+ initialMintTime: first?.blockTime == null ? null : Number(first.blockTime),
224
+ onchainMetadata,
225
+ registryName: null,
226
+ registryTicker: null,
227
+ registryDecimals: null,
228
+ registryDescription: null,
229
+ registryUrl: null,
230
+ registryLogo: null,
231
+ };
232
+ }
233
+ /** Address from the crawled UTxO set when it answers, else from the backend. */
234
+ async resolveAddress(tx, addr) {
235
+ return (await this.localAddress(tx, addr)) ?? await this.client.getAddress(addr);
236
+ }
237
+ /** UTxOs of an address: the crawled set (checked unspent at the node) when it answers, else the backend. */
238
+ async resolveAddressUtxos(tx, addr) {
239
+ return (await this.localAddress(tx, addr))?.utxos ?? await this.client.getAddressUtxos(addr);
240
+ }
241
+ /** Asset from the crawled chain when it answers, else from the backend. */
242
+ async resolveAssetInfo(tx, unit) {
243
+ return (await (0, tx_utils_1.readOutside)(tx, (db) => this.localAssetInfo(db, unit))) ?? await this.client.getAssetInfo(unit);
244
+ }
245
+ /** Stored mint/burn rows, newest first. Null when the crawled chain does not answer for them. */
246
+ async crawledAssetHistory(tx, unit, limit) {
247
+ if (!this.crawlAssetHistory || !(await this.crawlAnswers(tx, 'getAssetHistory')))
248
+ return null;
249
+ const rows = await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).where({ unit }).orderBy('blockHeight desc', 'txHash desc').limit(limit));
250
+ return rows ?? [];
251
+ }
252
+ /** Mint/burn events, newest first: crawled rows when the crawled chain answers, else the backend. */
253
+ async resolveAssetHistory(tx, unit, limit) {
254
+ const rows = await (0, tx_utils_1.readOutside)(tx, (db) => this.crawledAssetHistory(db, unit, limit));
255
+ if (!rows)
256
+ return this.client.getAssetHistory(unit, limit);
257
+ return rows.map(r => ({
258
+ unit: String(r.unit),
259
+ txHash: String(r.txHash),
260
+ action: r.action === 'burn' ? 'burn' : 'mint',
261
+ quantity: String(r.quantity),
262
+ blockTime: r.blockTime == null ? null : Number(r.blockTime),
263
+ blockHeight: r.blockHeight == null ? null : Number(r.blockHeight),
264
+ }));
265
+ }
266
+ /** UTxOs of a payment credential: the crawled set when it answers, else Koios. */
267
+ async resolveCredentialUtxos(tx, credHash) {
268
+ return (await this.localCredentialUtxos(tx, credHash)) ?? await this.client.getCredentialUtxos(credHash);
269
+ }
270
+ /** Latest transaction hashes of an address: the crawled set when it has enough, else the backend. */
271
+ async resolveAddressTransactionHashes(tx, addr, limit) {
272
+ const local = await (0, tx_utils_1.readOutside)(tx, (db) => this.localAddressTransactions(db, addr, limit));
273
+ if (local && (local.complete || local.rows.length >= limit)) {
274
+ return local.rows.map(r => String(r.tx_hash));
275
+ }
276
+ try {
277
+ return await this.client.getAddressTransactionHashes(addr, limit);
278
+ }
279
+ catch (err) {
280
+ if (local && (err instanceof errors_1.ProviderUnavailableError || err instanceof errors_1.AllBackendsFailedError)) {
281
+ return local.rows.map(r => String(r.tx_hash));
282
+ }
283
+ throw err;
284
+ }
285
+ }
286
+ /** True while the crawled UTxO set answers address queries (live crawler at the tip, set active). */
287
+ async ledgerCoverageActive(tx) {
288
+ return Boolean((await this.localCoverage(tx))?.ledger);
289
+ }
290
+ // Address from the crawled UTxO set. An address the set never saw is empty, not an error.
291
+ // Null when the set cannot answer.
292
+ async localAddress(tx, addr) {
293
+ const rows = await (0, tx_utils_1.readOutside)(tx, async (db) => (await this.localCoverage(db))?.ledger ? this.ledgerUtxosOf(db, [addr]) : null);
294
+ if (!rows)
295
+ return null;
296
+ return addressFromUtxos(addr, await this.unspentAtNode(rows));
297
+ }
298
+ /** Addresses of a stake key in the crawled UTxO set, with their stored unspent outputs (one read for all). */
299
+ async ledgerAccountUtxos(tx, stakeAddress) {
300
+ const rows = await tx.run(SELECT.from(CardanoODataService_1.LedgerAddresses).columns('address').where({ stakeAddress }));
301
+ const addresses = (rows ?? []).map(r => r.address);
302
+ return { addresses, utxos: addresses.length ? await this.ledgerUtxosOf(tx, addresses) : [] };
303
+ }
304
+ // Transactions that paid to or spent from the address since the anchor. complete is true when the
305
+ // address first appeared after the anchor, so nothing older exists. Null when the set cannot answer.
306
+ async localAddressTransactions(tx, addr, limit) {
307
+ if (!(await this.localCoverage(tx))?.ledger)
308
+ return null;
309
+ const known = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAddresses).columns('firstSeenSlot').where({ address: addr }));
310
+ if (!known)
311
+ return { rows: [], complete: false };
312
+ const complete = known.firstSeenSlot != null;
313
+ // Candidate transactions by slot; a transaction can touch the address with several outputs.
314
+ const scan = Math.min(limit * 20, 2000);
315
+ // NULLS FIRST is the order a backward scan of the (address, slot) indexes delivers; the
316
+ // filters exclude NULL anyway, and a plain DESC would make PostgreSQL sort every row.
317
+ const createdQuery = SELECT.from(cardano_1.LedgerUTxOs).columns('txHash', 'createdSlot').where({ address: addr, createdSlot: { '>=': 0 } }).limit(scan);
318
+ createdQuery.SELECT.orderBy = [{ ref: ['createdSlot'], sort: 'desc', nulls: 'first' }];
319
+ const spentQuery = SELECT.from(cardano_1.LedgerUTxOs).columns('spentTxHash', 'spentSlot').where({ address: addr, spentSlot: { '>=': 0 } }).limit(scan);
320
+ spentQuery.SELECT.orderBy = [{ ref: ['spentSlot'], sort: 'desc', nulls: 'first' }];
321
+ const [created, spent] = await Promise.all([tx.run(createdQuery), tx.run(spentQuery)]);
322
+ const slotOf = new Map();
323
+ for (const r of created ?? [])
324
+ slotOf.set(r.txHash, Number(r.createdSlot));
325
+ for (const r of spent ?? [])
326
+ slotOf.set(r.spentTxHash, Number(r.spentSlot));
327
+ const selected = [...slotOf].sort((a, b) => b[1] - a[1]).slice(0, limit).map(([hash]) => hash);
328
+ if (selected.length === 0)
329
+ return { rows: [], complete };
330
+ const [outRows, inRows] = await Promise.all([
331
+ tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ address: addr, txHash: { in: selected } })),
332
+ tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ address: addr, spentTxHash: { in: selected } })),
333
+ ]);
334
+ const amounts = await this.ledgerAmounts(tx, [...(outRows ?? []), ...(inRows ?? [])]);
335
+ const amountOf = (r) => amounts.get(`${r.txHash}#${Number(r.outputIndex)}`) ?? [];
336
+ const txs = selected.map((hash) => ({
337
+ hash,
338
+ blockTime: (0, epoch_slots_1.slotToPosixSeconds)(this.client.network, slotOf.get(hash)),
339
+ inputs: (inRows ?? []).filter(r => r.spentTxHash === hash).map(r => ({ address: addr, amount: amountOf(r) })),
340
+ outputs: (outRows ?? []).filter(r => r.txHash === hash).map(r => ({ address: addr, amount: amountOf(r) })),
341
+ }));
342
+ const rows = (0, mappers_1.mapAddressTransactions)(addr, txs);
343
+ return { rows: sortAddressTransactions(rows), complete };
344
+ }
345
+ /** Amount lists (lovelace + assets) of `LedgerUTxOs` rows, keyed `txHash#outputIndex`. */
346
+ async ledgerAmounts(tx, rows) {
347
+ const out = new Map();
348
+ for (const r of rows)
349
+ out.set(`${r.txHash}#${Number(r.outputIndex)}`, [{ unit: 'lovelace', quantity: String(r.lovelace ?? '0') }]);
350
+ const withAssets = [...new Set(rows.filter(r => r.hasAssets).map(r => String(r.txHash)))];
351
+ for (const hashChunk of (0, collections_1.chunk)(withAssets, collections_1.IN_CHUNK)) {
352
+ const assetRows = await tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).columns('utxo_txHash', 'utxo_outputIndex', 'unit', 'asset_quantity')
353
+ .where({ utxo_txHash: { in: hashChunk } }));
354
+ for (const a of assetRows ?? []) {
355
+ out.get(`${a.utxo_txHash}#${Number(a.utxo_outputIndex)}`)?.push({ unit: a.unit, quantity: String(a.asset_quantity) });
356
+ }
357
+ }
358
+ return out;
359
+ }
360
+ // Active stake from the Ogmios snapshot of the running epoch.
361
+ // Empty when the crawler is not at the tip or that snapshot is missing.
362
+ async snapshotActiveStake(tx, poolId) {
363
+ const coverage = await this.localCoverage(tx);
364
+ if (!coverage)
365
+ return {};
366
+ const epoch = (0, epoch_slots_1.epochOfSlot)(this.client.network, coverage.lastSlot);
367
+ const row = await tx.run(SELECT.one.from(CardanoODataService_1.PoolEpochSnapshots).columns('activeStake', 'activeSize').where({ poolId, epoch, source: 'ogmios' }));
368
+ if (!row || row.activeStake == null)
369
+ return {};
370
+ return { activeStake: lovelaceSum(row.activeStake), activeSize: Number(row.activeSize ?? 0) };
371
+ }
372
+ // Lifetime withdrawals from crawled rows. Null unless certificates are crawled
373
+ // and the crawl covers the chain since Shelley.
374
+ async localWithdrawalsSum(tx, stakeAddress) {
375
+ const coverage = await this.localCoverage(tx);
376
+ if (!coverage || !this.crawlCertificates)
377
+ return null;
378
+ if (coverage.fromSlot > const_1.EPOCH_CONFIG_BY_NETWORK[this.client.network].shelleyStartSlot)
379
+ return null;
380
+ const row = await tx.run(SELECT.one.from(CardanoODataService_1.TransactionWithdrawals).columns('sum(lovelace) as total').where({ stakeAddress }));
381
+ return lovelaceSum(row?.total);
382
+ }
383
+ /** The anchor the imported UTxO set describes (null = ledger mode inactive). */
384
+ setUtxoAnchor(anchor) {
385
+ this.utxoAnchor = anchor;
386
+ this.utxoAnchorVerified = false;
387
+ this.ledgerInvalidation = null;
388
+ }
389
+ // The imported set describes the chain at the anchor block. Before the first block past it, the
390
+ // cursor must equal the anchor, else the snapshot came from a fork. Skipped once a block applied.
391
+ async verifyUtxoAnchor(tx, anchor) {
392
+ const cursor = await (0, sync_state_1.readCursor)(tx);
393
+ if (cursor?.utxoSet.appliedSlot != null)
394
+ return true;
395
+ if (cursor && cursor.lastSlot === anchor.slot && (cursor.lastBlockHash ?? '').toLowerCase() === anchor.hash.toLowerCase())
396
+ return true;
397
+ const reason = cursor
398
+ ? `anchor ${anchor.slot}/${anchor.hash} is not the block the crawler followed (cursor ${cursor.lastSlot}/${cursor.lastBlockHash})`
399
+ : `no crawler cursor to verify the anchor ${anchor.slot}/${anchor.hash} against`;
400
+ logger.error(`UTxO set invalidated: ${reason}. The snapshot describes a fork; re-import at the crawler cursor`);
401
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: reason.slice(0, 500) });
402
+ this.ledgerInvalidation = reason;
403
+ return false;
404
+ }
405
+ /** Null while the mode is off, nothing is imported, or an invalidation awaits its commit. */
406
+ getUtxoAnchor() {
407
+ return this.crawlUtxoSet && !this.ledgerInvalidation ? this.utxoAnchor : null;
408
+ }
409
+ /** Apply the memo updates of the block transaction that just committed. */
410
+ confirmBlockCommit() {
411
+ const pending = this.pendingCommit;
412
+ this.pendingCommit = [];
413
+ for (const apply of pending)
414
+ apply();
415
+ }
416
+ /** Hand out a pending invalidation (dropping the anchor) exactly once after the block commit, or null. */
417
+ takeLedgerInvalidation() {
418
+ const reason = this.ledgerInvalidation;
419
+ if (reason) {
420
+ this.ledgerInvalidation = null;
421
+ this.utxoAnchor = null;
422
+ this.utxoAnchorVerified = false;
423
+ }
424
+ return reason;
425
+ }
426
+ // Drains the queue at enrichRate units per second, each in its own transaction.
427
+ // A failing unit is dropped and its bare row stays for the lazy path.
428
+ startAssetEnrichment() {
429
+ if (this.enrichTimer || this.crawlAssetCatalogue !== 'enrich')
430
+ return;
431
+ const intervalMs = Math.max(1, Math.round(1000 / Math.max(1, this.enrichRate)));
432
+ this.enrichTimer = setInterval(() => {
433
+ const unit = this.enrichQueue.shift();
434
+ if (unit === undefined) {
435
+ this.stopAssetEnrichment();
436
+ return;
437
+ }
438
+ void cds_1.default.tx((tx) => this.indexAsset(tx, unit)).catch((err) => {
439
+ logger.debug(`asset enrichment for ${unit} failed (bare row kept):`, err);
440
+ });
441
+ }, intervalMs);
442
+ this.enrichTimer.unref?.();
443
+ }
444
+ /** Stop the enrichment loop and forget what is still queued (shutdown, crawler halt, mode change). */
445
+ stopAssetEnrichment() {
446
+ if (this.enrichTimer) {
447
+ clearInterval(this.enrichTimer);
448
+ this.enrichTimer = null;
449
+ }
450
+ this.enrichQueue = [];
451
+ }
452
+ // Call before opening the block write transaction, so no backend round trip
453
+ // runs under the DB write lock. Never throws.
52
454
  async prefetchCrawlEpoch(epochNumber) {
53
455
  const previousEpoch = this.crawlEpochCurrent;
54
456
  const enteringNewEpoch = previousEpoch !== null && previousEpoch !== epochNumber;
@@ -58,6 +460,11 @@ class CardanoIndexer {
58
460
  await this.refreshCrawlEpoch(previousEpoch, true, true);
59
461
  this.crawlEpochPrevious = previousEpoch;
60
462
  }
463
+ else if (previousEpoch === null && epochNumber > 0 && await this.storedOpenEpoch(epochNumber - 1)) {
464
+ // After a start the epoch before is not in the memo; its stored row may still wait to turn final.
465
+ await this.refreshCrawlEpoch(epochNumber - 1, true, true);
466
+ this.crawlEpochPrevious = epochNumber - 1;
467
+ }
61
468
  else {
62
469
  for (const [cachedEpoch, entry] of this.crawlEpochCache) {
63
470
  if (cachedEpoch !== epochNumber && !entry.finalized) {
@@ -74,6 +481,16 @@ class CardanoIndexer {
74
481
  }
75
482
  }
76
483
  }
484
+ /** True when the epoch has a stored row that is not final yet. Never throws. */
485
+ async storedOpenEpoch(epochNumber) {
486
+ try {
487
+ const row = await cds_1.default.db.run(SELECT.one.from(CardanoODataService_1.Epoch).columns('final').where({ epoch: epochNumber }));
488
+ return row != null && !row.final;
489
+ }
490
+ catch {
491
+ return false;
492
+ }
493
+ }
77
494
  async refreshCrawlEpoch(epochNumber, force, finalized) {
78
495
  const now = Date.now();
79
496
  const existing = this.crawlEpochCache.get(epochNumber);
@@ -81,96 +498,191 @@ class CardanoIndexer {
81
498
  return;
82
499
  if (!force && existing && now < existing.nextRefreshAt)
83
500
  return;
501
+ const crawled = await this.crawledEpochTotals(epochNumber);
84
502
  try {
85
- const row = (0, mappers_1.mapEpoch)(await this.client.getEpoch(epochNumber));
503
+ const provided = (0, mappers_1.mapEpoch)(await this.client.getEpoch(epochNumber));
86
504
  this.crawlEpochCache.set(epochNumber, {
87
- row,
505
+ row: crawled ? { ...provided, ...crawled.totals } : provided,
88
506
  nextRefreshAt: now + CardanoIndexer.CRAWL_EPOCH_REFRESH_MS,
89
507
  finalized,
508
+ crawlComplete: crawled ? crawled.complete : null,
90
509
  });
91
510
  }
92
511
  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.
512
+ // Keep the last good snapshot (or the crawled totals alone), but retry transient/negative
513
+ // results soon rather than suppressing enrichment for the rest of the five-day epoch.
514
+ const base = existing?.row ?? (crawled ? this.bareEpochRow(epochNumber) : undefined);
95
515
  this.crawlEpochCache.set(epochNumber, {
96
- row: existing?.row,
516
+ row: base && crawled ? { ...base, ...crawled.totals } : base,
97
517
  nextRefreshAt: now + CardanoIndexer.CRAWL_EPOCH_RETRY_MS,
98
518
  finalized: false,
519
+ crawlComplete: crawled ? crawled.complete : (existing?.crawlComplete ?? null),
99
520
  });
100
521
  }
101
522
  }
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
- */
523
+ // Block, tx and fee totals from crawled blocks. Null unless the crawl started before the epoch;
524
+ // complete once the cursor is past the epoch's last slot. Output and active stake come from the backend.
525
+ // Before the epoch's first crawled block the totals are empty, but the epoch is still not complete.
526
+ async crawledEpochTotals(epochNumber) {
527
+ try {
528
+ const cursor = await (0, sync_state_1.readCursor)(cds_1.default.db);
529
+ if (cursor?.startSlot == null || cursor.startSlot >= (0, epoch_slots_1.epochStartSlot)(this.client.network, epochNumber))
530
+ return null;
531
+ const complete = cursor.lastSlot >= (0, epoch_slots_1.epochStartSlot)(this.client.network, epochNumber + 1);
532
+ const row = await cds_1.default.db.run(SELECT.one.from(CardanoODataService_1.Blocks)
533
+ .columns('count(*) as blockCount', 'sum(txCount) as txCount', 'sum(fees) as fees', 'min(slot) as firstSlot', 'max(slot) as lastSlot')
534
+ .where({ epochNumber }));
535
+ if (!row || Number(row.blockCount ?? 0) === 0)
536
+ return { totals: {}, complete };
537
+ // The slot gives the block time exactly; a time aggregate comes back in the database's own form.
538
+ const timeOf = (slot) => slot == null ? null : (0, epoch_slots_1.slotToPosixSeconds)(this.client.network, Number(slot));
539
+ return {
540
+ totals: {
541
+ blockCount: Number(row.blockCount),
542
+ txCount: Number(row.txCount ?? 0),
543
+ fees: lovelaceSum(row.fees),
544
+ firstBlockTime: timeOf(row.firstSlot),
545
+ lastBlockTime: timeOf(row.lastSlot),
546
+ },
547
+ complete,
548
+ };
549
+ }
550
+ catch (err) {
551
+ logger.debug(`Crawled totals for epoch ${epochNumber} unavailable:`, err);
552
+ return null;
553
+ }
554
+ }
555
+ /** Epoch row with only the slot-derived bounds, for an epoch the backend cannot describe. */
556
+ bareEpochRow(epochNumber) {
557
+ const network = this.client.network;
558
+ const start = (0, epoch_slots_1.epochStartSlot)(network, epochNumber);
559
+ return {
560
+ epoch: epochNumber,
561
+ startTime: (0, epoch_slots_1.slotToPosixSeconds)(network, start),
562
+ endTime: (0, epoch_slots_1.slotToPosixSeconds)(network, (0, epoch_slots_1.epochStartSlot)(network, epochNumber + 1)),
563
+ output: null,
564
+ activeStake: null,
565
+ };
566
+ }
567
+ // Writes block count, transaction count, fees and first and last block time of every epoch the
568
+ // crawl covers in full, from the stored blocks. An epoch without a row gets one. No backend.
569
+ async backfillEpochs(onProgress, shouldStop) {
570
+ const progress = { atEpoch: 0, toEpoch: 0, updated: 0, created: 0 };
571
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
572
+ if (cursor?.startSlot == null)
573
+ return progress;
574
+ const network = this.client.network;
575
+ progress.toEpoch = (0, epoch_slots_1.epochOfSlot)(network, cursor.lastSlot);
576
+ for (let epoch = (0, epoch_slots_1.epochOfSlot)(network, cursor.startSlot); epoch <= progress.toEpoch; epoch++) {
577
+ await (0, window_plan_1.yieldToEventLoop)();
578
+ if (shouldStop?.())
579
+ break;
580
+ const crawled = await this.crawledEpochTotals(epoch);
581
+ if (crawled) {
582
+ const totals = { ...crawled.totals, final: this.withFinal(this.bareEpochRow(epoch), Date.now(), crawled.complete).final };
583
+ const outcome = await cds_1.default.tx(async (tx) => {
584
+ const stored = await tx.run(SELECT.one.from(CardanoODataService_1.Epoch).columns('epoch', 'final').where({ epoch }));
585
+ // partial crawled totals never replace a row that is already final
586
+ if (stored?.final && !totals.final)
587
+ return 'kept';
588
+ if (stored)
589
+ await tx.run(UPDATE.entity(CardanoODataService_1.Epoch).set(totals).where({ epoch }));
590
+ else
591
+ await tx.run(INSERT.into(CardanoODataService_1.Epoch).entries({ ...this.bareEpochRow(epoch), ...totals }));
592
+ return stored ? 'updated' : 'created';
593
+ });
594
+ if (outcome === 'created')
595
+ progress.created++;
596
+ else if (outcome === 'updated')
597
+ progress.updated++;
598
+ }
599
+ progress.atEpoch = epoch;
600
+ onProgress?.({ ...progress });
601
+ }
602
+ logger.info(`epochs rebuilt from crawled blocks: ${progress.updated} updated, ${progress.created} created, up to epoch ${progress.toEpoch}`);
603
+ return progress;
604
+ }
107
605
  constructor(client, txBuilder) {
108
606
  this.client = client;
109
607
  this.txBuilder = txBuilder;
608
+ txBuilder.setAddressUtxoSource?.((address) => this.localAddressUtxos(address));
110
609
  logger.info('CardanoIndexer instance created');
111
610
  }
112
- /**
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
119
- */
120
- async indexTransaction(tx, txHash) {
121
- // getting data from cardano data provider
122
- const providerTx = await this.client.getTransaction(txHash);
611
+ // Unspent outputs for the transaction builder. Null when the set cannot answer.
612
+ // Reads through the running request's transaction, which stays idle unless it already holds its connection.
613
+ async localAddressUtxos(address) {
614
+ if (!cds_1.default.db)
615
+ return null;
616
+ const tx = (cds_1.default.context ? cds_1.default.tx(cds_1.default.context) : cds_1.default.db);
617
+ return (await this.localAddress(tx, address))?.utxos ?? null;
618
+ }
619
+ /** A transaction from the backend. 404 when the crawled chain answers for it alone. */
620
+ async fetchTransaction(tx, txHash) {
621
+ await (0, tx_utils_1.readOutside)(tx, (db) => this.refuseOutsideCrawl(db, 'getTransaction', `Transaction ${txHash}`));
622
+ return this.client.getTransaction(txHash);
623
+ }
624
+ /** All UPSERTs run in the caller's transaction, so everything persists or nothing does. */
625
+ async storeTransaction(tx, providerTx) {
123
626
  const txRow = (0, mappers_1.mapTransaction)(providerTx);
124
627
  await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRow));
125
- logger.debug(`indexTransaction: upserted transaction ${txHash}`);
628
+ logger.debug(`indexTransaction: upserted transaction ${providerTx.hash}`);
629
+ await this.writeTransactionChildren(tx, providerTx, txRow.txSeq);
630
+ return txRow;
631
+ }
632
+ /** Reads a transaction from the backend and stores it. */
633
+ async indexTransaction(tx, txHash) {
634
+ return this.storeTransaction(tx, await this.fetchTransaction(tx, txHash));
635
+ }
636
+ /** Lazy path: inputs, outputs, their assets and metadata of one transaction. */
637
+ async writeTransactionChildren(tx, providerTx, txSeq) {
126
638
  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) {
639
+ const inputRows = (0, mappers_1.mapTransactionInputs)(txSeq, providerTx.inputs);
640
+ const inputAssetRows = (0, mappers_1.mapTransactionInputAssets)(txSeq, providerTx.inputs);
641
+ if (inputRows.length)
131
642
  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) {
135
- await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputAssets).entries(inputAssetRows));
136
- logger.debug(`indexTransaction: upserted ${inputAssetRows.length} transaction input assets for ${txHash}`);
137
- }
643
+ if (inputAssetRows.length)
644
+ await tx.run(UPSERT.into(cardano_1.TransactionInputAssetCopies).entries(inputAssetRows));
138
645
  }
139
- // Outputs + OutputAssets — independent of inputs (a tx with empty/missing
140
- // `inputs` previously skipped its outputs entirely)
646
+ // outputs must not depend on the inputs branch
141
647
  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) {
648
+ const outputRows = (0, mappers_1.mapTransactionOutputs)(txSeq, providerTx.outputs);
649
+ const outputAssetRows = (0, mappers_1.mapTransactionOutputAssets)(txSeq, providerTx.outputs);
650
+ if (outputRows.length)
145
651
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputs).entries(outputRows));
146
- }
147
- if (outputAssetRows.length) {
652
+ if (outputAssetRows.length)
148
653
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
149
- }
150
654
  }
151
- const metadataRows = (0, mappers_1.mapTransactionMetadata)(providerTx.metadata || []);
152
- if (metadataRows.length) {
655
+ const metadataRows = (0, mappers_1.mapTransactionMetadata)(providerTx.metadata || [], txSeq);
656
+ if (metadataRows.length)
153
657
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
658
+ }
659
+ // An address and its ten newest transactions, read but not stored.
660
+ // prefetched is address data the caller already fetched in a batch.
661
+ async fetchAddress(tx, addr, prefetched) {
662
+ const data = prefetched ?? await this.resolveAddress(tx, addr);
663
+ logger.debug(`indexAddress: provider response for ${addr}: ${data.amount?.length ?? 0} amounts, ${data.utxos?.length ?? 0} utxos`);
664
+ let transactions = null;
665
+ try {
666
+ transactions = await this.fetchAddressTransactions(tx, addr, 10);
154
667
  }
155
- return txRow;
668
+ catch (err) {
669
+ logger.error(`indexAddressTransactions failed for address ${addr}: ${err.message}`);
670
+ }
671
+ return { address: addr, data, transactions };
672
+ }
673
+ /** Reads an address and its newest transactions, then stores them. */
674
+ async indexAddress(tx, addr, prefetched) {
675
+ return this.storeAddress(tx, await this.fetchAddress(tx, addr, prefetched));
156
676
  }
157
- /**
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
163
- */
164
- async indexAddress(tx, addr) {
165
- const addrData = await this.client.getAddress(addr);
166
- logger.debug(`indexAddress: provider response for ${addr}: ${addrData.amount?.length ?? 0} amounts, ${addrData.utxos?.length ?? 0} utxos`);
677
+ /** Stores what fetchAddress read: the address, its assets, UTxOs and newest transactions. */
678
+ async storeAddress(tx, fetched) {
679
+ const { address: addr, data: addrData } = fetched;
167
680
  const AddrEntity = (0, mappers_1.mapAddress)(addr, addrData, this.client.max_age_ms);
168
681
  const now = new Date().toISOString();
169
682
  const validFrom = AddrEntity.validFrom ?? now;
170
683
  const validTo = AddrEntity.validTo ?? now;
171
684
  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
685
+ // Supplement address-level amounts with assets only present in UTxOs
174
686
  const addressAssetUnits = new Set(addrData.amount.filter(a => a.unit !== 'lovelace').map(a => a.unit));
175
687
  for (const utxo of addrData.utxos) {
176
688
  for (const amt of utxo.amount) {
@@ -206,39 +718,38 @@ class CardanoIndexer {
206
718
  logger.debug(`indexAddress: ${utxoAssetEntities.length} assets, ${uniqueAssets.length} unique (removed ${utxoAssetEntities.length - uniqueAssets.length} duplicates)`);
207
719
  await tx.run(UPSERT.into(CardanoODataService_1.UTxOAssets).entries(uniqueAssets));
208
720
  }
209
- // Always pre-index recent transactions (regardless of asset presence)
210
- try {
211
- const txEntities = await this.indexAddressTransactions(tx, addr, 10);
212
- if (txEntities.length > 0) {
213
- await tx.run(UPDATE.entity(CardanoODataService_1.Addresses).set({ hasTransactions: true }).where({ address: addr }));
214
- AddrEntity.hasTransactions = true;
721
+ // Recent transactions are always stored with the address (regardless of asset presence)
722
+ if (fetched.transactions) {
723
+ try {
724
+ const txEntities = await this.storeAddressTransactions(tx, fetched.transactions);
725
+ if (txEntities.length > 0) {
726
+ await tx.run(UPDATE.entity(CardanoODataService_1.Addresses).set({ hasTransactions: true }).where({ address: addr }));
727
+ AddrEntity.hasTransactions = true;
728
+ }
729
+ }
730
+ catch (err) {
731
+ logger.error(`indexAddressTransactions failed for address ${addr}: ${err.message}`);
215
732
  }
216
- }
217
- catch (err) {
218
- logger.error(`indexAddressTransactions failed for address ${addr}: ${err.message}`);
219
733
  }
220
734
  return AddrEntity;
221
735
  }
222
- /**
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
234
- */
736
+ /** UTxOs of a payment credential, always fresh: the crawled set when it answers, else the backend. */
737
+ async fetchCredentialUtxos(tx, credHash) {
738
+ const local = await this.localCredentialUtxos(tx, credHash);
739
+ const utxos = local ?? await this.client.getCredentialUtxos(credHash);
740
+ logger.debug(`indexCredentialUtxos: ${local ? 'crawled UTxO set' : 'provider'} returned ${utxos.length} utxos for credential ${credHash}`);
741
+ return utxos;
742
+ }
743
+ /** Reads the UTxOs of a payment credential and stores them. */
235
744
  async indexCredentialUtxos(tx, credHash) {
236
- const utxos = await this.client.getCredentialUtxos(credHash);
237
- logger.debug(`indexCredentialUtxos: provider returned ${utxos.length} utxos for credential ${credHash}`);
745
+ return this.storeCredentialUtxos(tx, await this.fetchCredentialUtxos(tx, credHash));
746
+ }
747
+ /** Stores credential UTxOs. Rows are written without a parent Addresses row. */
748
+ async storeCredentialUtxos(tx, utxos) {
238
749
  if (utxos.length === 0)
239
750
  return [];
240
- // Group by bech32 address — Koios returns UTxOs across all bech32 forms
241
- // sharing the credential; mapAddressUtxos keys rows by address parameter.
751
+ // Koios returns UTxOs of every address form sharing the credential.
752
+ // mapAddressUtxos keys rows by address, so group them first.
242
753
  const byAddress = new Map();
243
754
  for (const u of utxos) {
244
755
  const list = byAddress.get(u.address) ?? [];
@@ -270,21 +781,112 @@ class CardanoIndexer {
270
781
  logger.debug(`indexCredentialUtxos: indexed ${allRows.length} utxos across ${byAddress.size} addresses`);
271
782
  return allRows;
272
783
  }
273
- /**
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)
285
- */
784
+ // Credential UTxOs from the crawled set. Null when the set cannot answer yet.
785
+ // An address first used in the last confirmationDepth blocks is not in the set yet.
786
+ async localCredentialUtxos(tx, credHash) {
787
+ const stored = await (0, tx_utils_1.readOutside)(tx, async (db) => {
788
+ if (!(await this.localCoverage(db))?.ledger || !(await this.paymentCredentialsReady()))
789
+ return null;
790
+ const rows = await db.run(SELECT.from(CardanoODataService_1.LedgerAddresses).columns('address').where({ paymentCredential: credHash }));
791
+ const addresses = (rows ?? []).map(r => r.address);
792
+ return addresses.length ? this.ledgerUtxosOf(db, addresses) : [];
793
+ });
794
+ if (!stored)
795
+ return null;
796
+ return this.unspentAtNode(stored);
797
+ }
798
+ // Crawled outputs checked against the node by output reference, to drop what was spent after
799
+ // the cursor. The node's address query would scan its whole UTxO set. Falls back to the set as is.
800
+ async unspentAtNode(rows) {
801
+ if (rows.length === 0)
802
+ return rows;
803
+ try {
804
+ const unspent = new Map();
805
+ for (const refChunk of (0, collections_1.chunk)(rows, CardanoIndexer.OUTREF_CHUNK)) {
806
+ const live = await this.client.getUnspentOutputs(refChunk.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })));
807
+ if (live === null)
808
+ return rows;
809
+ for (const u of live)
810
+ unspent.set(`${u.txHash}#${u.outputIndex}`, u);
811
+ }
812
+ // The node's answer names the reference script, which a snapshot row from a file import lacks
813
+ return rows.flatMap(u => {
814
+ const live = unspent.get(`${u.txHash}#${u.outputIndex}`);
815
+ if (!live)
816
+ return [];
817
+ return [{ ...u, scriptRef: u.scriptRef ?? live.scriptRef ?? undefined, scriptRefCbor: live.scriptRefCbor ?? u.scriptRefCbor }];
818
+ });
819
+ }
820
+ catch (err) {
821
+ logger.warn(`unspent check of ${rows.length} crawled outputs failed, answering as of the cursor: ${err?.message ?? err}`);
822
+ return rows;
823
+ }
824
+ }
825
+ /** Unspent `LedgerUTxOs` (+ assets) of the given addresses in the provider UTxO shape. */
826
+ async ledgerUtxosOf(tx, addresses) {
827
+ const out = [];
828
+ for (const addrChunk of (0, collections_1.chunk)(addresses, collections_1.IN_CHUNK)) {
829
+ const utxos = await tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ address: { in: addrChunk }, spentTxHash: null }));
830
+ const amounts = await this.ledgerAmounts(tx, utxos ?? []);
831
+ for (const u of utxos ?? []) {
832
+ const txHash = String(u.txHash);
833
+ const outputIndex = Number(u.outputIndex);
834
+ out.push({
835
+ txHash,
836
+ outputIndex,
837
+ address: String(u.address),
838
+ amount: amounts.get(`${txHash}#${outputIndex}`) ?? [],
839
+ blockHash: '',
840
+ datumHash: u.utxo_dataHash ?? undefined,
841
+ inlineDatum: u.utxo_inlineDatum ?? null,
842
+ scriptRef: u.utxo_referenceScriptHash ?? undefined,
843
+ scriptRefSize: u.utxo_referenceScriptSize == null ? null : Number(u.utxo_referenceScriptSize),
844
+ scriptRefType: u.utxo_referenceScriptType ?? null,
845
+ });
846
+ }
847
+ }
848
+ return out;
849
+ }
850
+ // True once every Shelley address row has its payment credential.
851
+ // Until then a background fill runs and callers use the provider.
852
+ async paymentCredentialsReady() {
853
+ if (this.credentialsReady)
854
+ return true;
855
+ if (!this.credentialFill) {
856
+ const generation = this.credentialGeneration;
857
+ this.credentialFill = (0, ledger_state_1.backfillPaymentCredentials)()
858
+ .then((n) => {
859
+ if (generation !== this.credentialGeneration)
860
+ return;
861
+ this.credentialsReady = true;
862
+ if (n > 0)
863
+ logger.info(`payment credentials filled for ${n} ledger addresses`);
864
+ })
865
+ .catch((err) => logger.error('payment credential fill failed (retried on the next lookup):', err))
866
+ .finally(() => { this.credentialFill = null; });
867
+ }
868
+ return false;
869
+ }
870
+ /** The ledger tables were replaced (re-import): the credential column has to be filled again. */
871
+ resetPaymentCredentials() {
872
+ this.credentialGeneration++;
873
+ this.credentialsReady = false;
874
+ }
875
+ // Skips getAddress, so it works on backends without address aggregation such as Ogmios.
286
876
  async indexAddressUtxos(tx, addr) {
287
- const utxos = await this.client.getAddressUtxos(addr);
877
+ return this.storeAddressUtxos(tx, addr, await this.fetchAddressUtxos(addr));
878
+ }
879
+ /** The UTxOs of an address from the backend. */
880
+ async fetchAddressUtxos(addr) {
881
+ return this.client.getAddressUtxos(addr);
882
+ }
883
+ // Stores an address known only from its UTxOs, for backends without address aggregation such as
884
+ // Ogmios: the Addresses row with balance and type, its assets and UTxOs, no transactions.
885
+ async storeAddressFromUtxos(tx, addr, utxos) {
886
+ return this.storeAddress(tx, { address: addr, data: addressFromUtxos(addr, utxos), transactions: null });
887
+ }
888
+ /** Stores the UTxOs of an address. Writes no parent Addresses row. */
889
+ async storeAddressUtxos(tx, addr, utxos) {
288
890
  logger.debug(`indexAddressUtxos: provider returned ${utxos.length} utxos for ${addr}`);
289
891
  const validFrom = new Date().toISOString();
290
892
  const validTo = new Date(Date.now() + this.client.max_age_ms).toISOString();
@@ -306,23 +908,8 @@ class CardanoIndexer {
306
908
  }
307
909
  return utxoEntities;
308
910
  }
309
- /**
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
325
- */
911
+ // Evicts cached rows a submitted tx made stale: its spent inputs and its output addresses.
912
+ // A lagging backend may still return the old state on refetch.
326
913
  async invalidateUtxoCacheForTx(tx, targets, extraAddresses = []) {
327
914
  const addresses = [...new Set([...targets.outputAddresses, ...extraAddresses])];
328
915
  for (const address of addresses) {
@@ -339,28 +926,50 @@ class CardanoIndexer {
339
926
  logger.debug(`Invalidated UTxO cache: ${addresses.length} address(es), ${targets.inputs.length} spent input ref(s)`);
340
927
  }
341
928
  }
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
- */
929
+ /** Index address transactions (separate from indexAddress for lazy loading). */
349
930
  async indexAddressTransactions(tx, addr, limit) {
931
+ return this.storeAddressTransactions(tx, await this.fetchAddressTransactions(tx, addr, limit));
932
+ }
933
+ // The newest transactions of an address, read but not stored.
934
+ // Rows this address already has stay as stored; only new hashes are fetched.
935
+ async fetchAddressTransactions(tx, addr, limit) {
350
936
  logger.debug(`indexAddressTransactions: fetching transactions for ${addr}`);
351
- // Layer 4: Hash-only listing (lightweight, 1 API call)
352
- const txHashes = await this.client.getAddressTransactionHashes(addr, limit);
937
+ const local = await (0, tx_utils_1.readOutside)(tx, (db) => this.localAddressTransactions(db, addr, limit));
938
+ const keepLocal = () => ({ rows: local.rows, newRows: local.rows, transactions: new Map() });
939
+ if (local && (local.complete || local.rows.length >= limit))
940
+ return keepLocal();
941
+ // Hash-only listing (one API call)
942
+ let txHashes;
943
+ try {
944
+ txHashes = await this.client.getAddressTransactionHashes(addr, limit);
945
+ }
946
+ catch (err) {
947
+ // No backend with address history: what the crawled set holds is the best answer there is.
948
+ if (local && (err instanceof errors_1.ProviderUnavailableError || err instanceof errors_1.AllBackendsFailedError))
949
+ return keepLocal();
950
+ throw err;
951
+ }
353
952
  logger.debug(`indexAddressTransactions: found ${txHashes.length} tx hashes for ${addr}`);
354
953
  if (txHashes.length === 0)
355
- return [];
356
- // Layer 3: DB-first dedup + batch fetch
357
- const batchFetched = await this.ensureTransactionsIndexed(tx, txHashes);
358
- // For address-transaction mapping we need full provider tx data (inputs/outputs for net amounts).
359
- // Transactions already in DB were not re-fetched — batch-fetch those separately.
954
+ return { rows: [], newRows: [], transactions: new Map() };
955
+ const stored = await (0, tx_utils_1.readOutside)(tx, async (db) => {
956
+ const known = await db.run(SELECT.from(CardanoODataService_1.AddressTransactions).where({ address_address: addr, tx_hash: { in: txHashes } })) ?? [];
957
+ const knownHashes = new Set(known.map(r => r.tx_hash));
958
+ const newHashes = txHashes.filter(h => !knownHashes.has(h));
959
+ return { known, newHashes, unstored: newHashes.length ? await this.unstoredTransactionHashes(db, newHashes) : [] };
960
+ });
961
+ const { known, newHashes } = stored;
962
+ if (!newHashes.length)
963
+ return { rows: sortAddressTransactions(known), newRows: [], transactions: new Map() };
964
+ const transactions = stored.unstored.length
965
+ ? await this.client.getTransactionsBatch(stored.unstored)
966
+ : new Map();
967
+ // The net amounts need the inputs and outputs of every new transaction.
968
+ // A transaction that is stored already is read again, but not written.
360
969
  const allTxData = [];
361
970
  const missingFromBatch = [];
362
- for (const hash of txHashes) {
363
- const fromBatch = batchFetched.get(hash);
971
+ for (const hash of newHashes) {
972
+ const fromBatch = transactions.get(hash);
364
973
  if (fromBatch) {
365
974
  allTxData.push(fromBatch);
366
975
  }
@@ -376,172 +985,348 @@ class CardanoIndexer {
376
985
  allTxData.push(providerTx);
377
986
  }
378
987
  }
379
- // Create address-transaction mapping entries (no TTL — keyed by (address, tx),
380
- // immutable per confirmed tx; the entity has no temporal columns)
381
- const transactionsEntities = (0, mappers_1.mapAddressTransactions)(addr, allTxData);
382
- logger.debug({ count: transactionsEntities.length }, 'indexAddressTransactions: transaction entities');
383
- if (transactionsEntities.length) {
384
- await tx.run(UPSERT.into(CardanoODataService_1.AddressTransactions).entries(transactionsEntities));
385
- }
386
- // Sort by blockTime descending for consistency with GetLatestTransactionsByAddress
387
- transactionsEntities.sort((a, b) => (b.blockTime ?? 0) - (a.blockTime ?? 0));
388
- return transactionsEntities;
389
- }
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
- */
988
+ const newRows = (0, mappers_1.mapAddressTransactions)(addr, allTxData);
989
+ logger.debug({ count: newRows.length }, 'indexAddressTransactions: transaction entities');
990
+ return { rows: sortAddressTransactions([...known, ...newRows]), newRows, transactions };
991
+ }
992
+ // Stores what fetchAddressTransactions read and returns the rows to answer with.
993
+ // No TTL, because a row per address and confirmed tx never changes.
994
+ async storeAddressTransactions(tx, fetched) {
995
+ await this.storeTransactions(tx, fetched.transactions);
996
+ if (fetched.newRows.length)
997
+ await tx.run(UPSERT.into(CardanoODataService_1.AddressTransactions).entries(fetched.newRows));
998
+ return fetched.rows;
999
+ }
1000
+ /** Link an address to a signing request for address-based queries. */
398
1001
  async indexAddressSigningRequests(tx, addr, signingRequestId) {
399
1002
  logger.debug(`indexAddressSigningRequests: linking address ${addr} to signing request ${signingRequestId}`);
400
1003
  const addressSigningRequestEntity = (0, mappers_1.mapAddressSigningRequest)(addr, signingRequestId);
401
1004
  await tx.run(UPSERT.into(CardanoSignService_1.AddressSigningRequests).entries(addressSigningRequestEntity));
402
1005
  logger.debug(`indexAddressSigningRequests: linked address ${addr} to signing request ${signingRequestId}`);
403
1006
  }
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
- */
1007
+ /** Link an address to a transaction build for address-based queries. */
412
1008
  async indexAddressTransactionBuilds(tx, addr, buildId) {
413
1009
  logger.debug(`indexAddressTransactionBuilds: linking address ${addr} to build ${buildId}`);
414
1010
  const addressTransactionBuildEntity = (0, mappers_1.mapAddressTransactionBuild)(addr, buildId);
415
1011
  await tx.run(UPSERT.into(CardanoTransactionService_1.AddressTransactionBuilds).entries(addressTransactionBuildEntity));
416
1012
  logger.debug(`indexAddressTransactionBuilds: linked address ${addr} to build ${buildId}`);
417
1013
  }
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
- */
1014
+ /** Index the metadata rows of a transaction. */
425
1015
  async indexTransactionMetadata(tx, tx_hash) {
426
- const metadata = await this.client.getTransactionMetadata(tx_hash);
427
- const rows = (0, mappers_1.mapTransactionMetadata)(metadata);
1016
+ return this.storeTransactionMetadata(tx, await this.fetchTransactionMetadata(tx, tx_hash));
1017
+ }
1018
+ /** Metadata of a transaction from the backend. Null when the transaction is known to have none. */
1019
+ async fetchTransactionMetadata(tx, tx_hash) {
1020
+ const isStored = (db) => db.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('hash').where({ hash: tx_hash }));
1021
+ // A crawled transaction without metadata rows has no metadata.
1022
+ const crawledWithout = await (0, tx_utils_1.readOutside)(tx, async (db) => {
1023
+ if (!(await this.crawlAnswers(db, 'getTransactionMetadata')))
1024
+ return false;
1025
+ if (await isStored(db))
1026
+ return true;
1027
+ await this.refuseOutsideCrawl(db, 'getTransactionMetadata', `Transaction ${tx_hash}`);
1028
+ return false;
1029
+ });
1030
+ if (crawledWithout)
1031
+ return null;
1032
+ try {
1033
+ return { txHash: tx_hash, metadata: await this.client.getTransactionMetadata(tx_hash) };
1034
+ }
1035
+ catch (err) {
1036
+ // providers answer "not found" for a transaction without metadata; a stored transaction has none
1037
+ if ((0, errors_1.isNotFoundOnAllBackends)(err) && await (0, tx_utils_1.readOutside)(tx, isStored))
1038
+ return null;
1039
+ throw err;
1040
+ }
1041
+ }
1042
+ /** Stores the metadata rows of a transaction and returns them. */
1043
+ async storeTransactionMetadata(tx, fetched) {
1044
+ if (!fetched)
1045
+ return [];
1046
+ const stored = await tx.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('txSeq').where({ hash: fetched.txHash }));
1047
+ const rows = (0, mappers_1.mapTransactionMetadata)(fetched.metadata, stored?.txSeq == null ? null : Number(stored.txSeq));
428
1048
  if (rows.length) {
429
1049
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(rows));
430
1050
  }
431
1051
  return rows;
432
1052
  }
433
- /**
434
- * Index & return the network information data
435
- * @param tx CAP transaction object
436
- * @returns {Promise<NetworkInformation>} network information entity data
437
- */
1053
+ /** Index the network information; circulating supply comes from the crawled UTxO set when it is current. */
438
1054
  async indexNetworkInformation(tx) {
439
- const netInfo = await this.client.getNetworkInformation();
440
- const netEntity = (0, mappers_1.mapNetworkInfo)(netInfo, this.client.max_age_ms, this.client.network);
1055
+ return this.storeNetworkInformation(tx, await this.fetchNetworkInformation(tx));
1056
+ }
1057
+ /** The network information row, read but not stored. */
1058
+ async fetchNetworkInformation(tx) {
1059
+ return (0, mappers_1.mapNetworkInfo)(await this.resolveNetworkInformation(tx), this.client.max_age_ms, this.client.network);
1060
+ }
1061
+ async storeNetworkInformation(tx, netEntity) {
441
1062
  await tx.run(UPSERT.into(CardanoODataService_1.NetworkInformation).entries(netEntity));
442
1063
  return netEntity;
443
1064
  }
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
- */
1065
+ /** Network information from the backend; circulating supply from the crawled UTxO set when current. */
1066
+ async resolveNetworkInformation(tx) {
1067
+ const netInfo = await this.client.getNetworkInformation();
1068
+ const circulating = (await this.localCoverage(tx))?.ledger
1069
+ ? lovelaceSum((await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAddresses).columns('sum(totalLovelace) as total')))?.total)
1070
+ : null;
1071
+ return circulating === null ? netInfo : { ...netInfo, supply: { ...netInfo.supply, circulating } };
1072
+ }
1073
+ /** Index a block by hash, with best-effort epoch enrichment. */
450
1074
  async indexBlock(tx, blockHash) {
451
- const blockInfo = await this.client.getBlock(blockHash);
452
- let epoch;
1075
+ return this.storeBlock(tx, await this.fetchBlock(tx, blockHash));
1076
+ }
1077
+ /** A block and its epoch from the backend. 404 when the crawled chain answers for it alone. */
1078
+ async fetchBlock(tx, blockHash) {
1079
+ await (0, tx_utils_1.readOutside)(tx, (db) => this.refuseOutsideCrawl(db, 'getBlock', `Block ${blockHash}`));
1080
+ return this.withEpoch(await this.client.getBlock(blockHash));
1081
+ }
1082
+ async withEpoch(block) {
453
1083
  try {
454
- epoch = await this.indexEpoch(tx, blockInfo.epoch);
1084
+ return { block, epoch: (0, mappers_1.mapEpoch)(await this.client.getEpoch(block.epoch)) };
455
1085
  }
456
1086
  catch {
457
1087
  // Epoch data may not be available (e.g., Koios drops old/in-progress epochs)
1088
+ return { block };
1089
+ }
1090
+ }
1091
+ // Writes the memo's epoch rows that are new, or that turn final with this block. Their totals were
1092
+ // read before the write, so a block in a later epoch completes them. A row already final keeps them.
1093
+ async writeCrawlEpochs(tx, slot) {
1094
+ const now = Date.now();
1095
+ const due = [];
1096
+ for (const [epochNo, entry] of this.crawlEpochCache) {
1097
+ if (!entry.row)
1098
+ continue;
1099
+ const complete = entry.crawlComplete === false && slot >= (0, epoch_slots_1.epochStartSlot)(this.client.network, epochNo + 1) ? true : entry.crawlComplete;
1100
+ const row = this.withFinal(entry.row, now, complete ?? undefined);
1101
+ const written = this.crawlEpochWritten.get(entry.row);
1102
+ if (written !== undefined && (written || !row.final))
1103
+ continue;
1104
+ due.push({ entry: entry, row, complete });
458
1105
  }
459
- const blockEntity = (0, mappers_1.mapBlock)(blockInfo, epoch);
1106
+ if (!due.length)
1107
+ return;
1108
+ const open = due.filter((d) => !d.row.final).map((d) => Number(d.row.epoch));
1109
+ const finalRows = open.length
1110
+ ? await tx.run(SELECT.from(CardanoODataService_1.Epoch).columns('epoch').where({ epoch: { in: open }, final: true }))
1111
+ : [];
1112
+ const finalStored = new Set((finalRows ?? []).map((r) => Number(r.epoch)));
1113
+ const writable = due.filter((d) => d.row.final || !finalStored.has(Number(d.row.epoch))).map((d) => d.row);
1114
+ if (writable.length)
1115
+ await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries(writable));
1116
+ this.pendingCommit.push(() => {
1117
+ for (const d of due) {
1118
+ d.entry.crawlComplete = d.complete;
1119
+ this.crawlEpochWritten.set(d.entry.row, d.row.final === true);
1120
+ }
1121
+ });
1122
+ }
1123
+ /** Stores a block and, when it was read, its epoch. */
1124
+ async storeBlock(tx, fetched) {
1125
+ if (fetched.epoch)
1126
+ await this.storeEpoch(tx, fetched.epoch);
1127
+ const blockEntity = (0, mappers_1.mapBlock)(fetched.block, fetched.epoch);
460
1128
  await tx.run(UPSERT.into(CardanoODataService_1.Block).entries(blockEntity));
461
1129
  return blockEntity;
462
1130
  }
463
- /**
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)
481
- */
1131
+ // Indexes a whole block for the crawler with one UPSERT per table in the caller's transaction.
1132
+ // The block persists atomically. resolveInputs() fills bare chain-sync inputs first.
482
1133
  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.
1134
+ // Memo updates of a rolled-back attempt must not survive into this one.
1135
+ this.pendingCommit = [];
1136
+ // Epoch from the memo prefetchCrawlEpoch filled before the transaction. No backend call runs
1137
+ // here: a block whose epoch is not cached is stored without it, the next prefetch fills it.
486
1138
  let epoch;
487
1139
  if (blockData.epoch != null) {
488
- await this.prefetchCrawlEpoch(blockData.epoch);
489
1140
  epoch = this.crawlEpochCache.get(blockData.epoch)?.row;
490
- const epochRows = [...this.crawlEpochCache.values()]
491
- .map((entry) => entry.row)
492
- .filter((row) => row !== undefined);
493
- if (epochRows.length)
494
- await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries(epochRows));
495
- }
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
498
- await this.resolveInputs(tx, txs);
499
- // Accumulate rows across the whole block, then one bulk UPSERT per table
1141
+ await this.writeCrawlEpochs(tx, blockData.slot ?? 0);
1142
+ }
1143
+ // Ledger state (crawler.utxoSet): only blocks AFTER the anchor the imported set describes.
1144
+ // Decided up front so input resolution and the ledger apply share one read of the set.
1145
+ const ledgerDue = this.crawlUtxoSet && this.utxoAnchor != null && (blockData.slot ?? 0) > this.utxoAnchor.slot;
1146
+ const priorInvalidation = ledgerDue ? this.ledgerInvalidation : null;
1147
+ let anchorVerified = false;
1148
+ if (ledgerDue && !priorInvalidation) {
1149
+ anchorVerified = this.utxoAnchorVerified;
1150
+ if (!anchorVerified) {
1151
+ const anchor = this.utxoAnchor;
1152
+ anchorVerified = await this.verifyUtxoAnchor(tx, anchor);
1153
+ // Remembered only once this transaction commits, like the other crawl memos.
1154
+ if (anchorVerified)
1155
+ this.pendingCommit.push(() => { if (this.utxoAnchor === anchor)
1156
+ this.utxoAnchorVerified = true; });
1157
+ }
1158
+ }
1159
+ const ledgerLookup = anchorVerified
1160
+ ? { hashes: new Set(), rows: new Map(), assets: new Map() }
1161
+ : undefined;
1162
+ // Backfill chain-sync inputs (empty address/amount) from local outputs, then settle
1163
+ // the fee of any phase-2 failure. Both run before the block row is written, because a
1164
+ // corrected fee changes the block's fee total.
1165
+ await this.resolveInputs(tx, txs, ledgerLookup);
1166
+ // an input without a copy reads its assets from its output, so every stored output must be found
1167
+ const byReference = !this.crawlInputAssetCopies;
1168
+ if (byReference)
1169
+ await this.referenceStoredOutputs(tx, txs);
1170
+ this.applyCollateralFees(blockData, txs);
1171
+ this.applyDeposits(txs);
1172
+ // The account snapshot derives credited amounts only over blocks whose withdrawals are stored.
1173
+ const withdrawalsReported = this.crawlCertificates && txs.every(t => t.withdrawals !== undefined);
1174
+ // the table itself: the read projection does not carry this bookkeeping column
1175
+ await tx.run(UPSERT.into(cardano_1.Blocks).entries({ ...(0, mappers_1.mapBlock)(blockData, epoch), withdrawalsReported }));
1176
+ await this.removeStaleTxSeqs(tx, txs);
1177
+ // One bulk UPSERT per table. NUL safety for PostgreSQL is enforced by the db-level hook in
1178
+ // srv/utils/db-sanitize.ts, not per call site.
500
1179
  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 ?? []));
505
- const metadataRows = txs.flatMap(t => (0, mappers_1.mapTransactionMetadata)(t.metadata ?? []));
1180
+ const inputRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputs)((0, mappers_1.txSeqOf)(t.slot, t.index), t.inputs ?? [], byReference));
1181
+ const inputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputAssets)((0, mappers_1.txSeqOf)(t.slot, t.index), t.inputs ?? [], byReference));
1182
+ const outputRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputs)((0, mappers_1.txSeqOf)(t.slot, t.index), t.outputs ?? []));
1183
+ const outputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputAssets)((0, mappers_1.txSeqOf)(t.slot, t.index), t.outputs ?? []));
1184
+ const metadataRows = txs.flatMap(t => (0, mappers_1.mapTransactionMetadata)(t.metadata ?? [], (0, mappers_1.txSeqOf)(t.slot, t.index)));
1185
+ // Certificates + withdrawals are keyed (tx, certIndex, kind) / (tx, stakeAddress), so a
1186
+ // re-crawl is idempotent and a reorg removes them with their tx.
1187
+ const certificateRows = this.crawlCertificates
1188
+ ? txs.flatMap(t => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? []))
1189
+ : [];
1190
+ const withdrawalRows = this.crawlCertificates
1191
+ ? txs.flatMap(t => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? []))
1192
+ : [];
1193
+ if (this.crawlCertificates)
1194
+ this.warnIfCertificatesUnreported(txs);
1195
+ // Redeemers and witness datums come with the block on chain-sync; keyed by tx like the certificates.
1196
+ const redeemerRows = txs.flatMap(t => (0, mappers_1.mapTransactionRedeemers)(t.hash, t.redeemers ?? []));
1197
+ const datumRows = txs.flatMap(t => (0, mappers_1.mapTransactionDatums)(t.hash, t.datums ?? []));
1198
+ // Mint and burn rows are keyed by unit and tx, so a re-crawl is idempotent.
1199
+ // A reorg removes them with their transactions.
1200
+ const assetHistoryRows = this.crawlAssetHistory ? this.buildAssetHistoryRows(blockData, txs) : [];
506
1201
  if (txRows.length)
507
1202
  await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRows));
508
1203
  if (inputRows.length)
509
1204
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputs).entries(inputRows));
510
1205
  if (inputAssetRows.length)
511
- await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputAssets).entries(inputAssetRows));
1206
+ await tx.run(UPSERT.into(cardano_1.TransactionInputAssetCopies).entries(inputAssetRows));
512
1207
  if (outputRows.length)
513
1208
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputs).entries(outputRows));
514
1209
  if (outputAssetRows.length)
515
1210
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
516
1211
  if (metadataRows.length)
517
1212
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
518
- logger.debug(`indexBlockFull: block ${blockData.hash} — ${txs.length} txs, ${outputRows.length} outputs`);
519
- }
520
- /**
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.
525
- */
526
- async resolveInputs(tx, txs) {
527
- // 1. In-memory index of this block's outputs (txHash#outputIndex -> {address, amount})
1213
+ if (certificateRows.length)
1214
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionCertificates).entries(certificateRows));
1215
+ if (withdrawalRows.length)
1216
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionWithdrawals).entries(withdrawalRows));
1217
+ if (redeemerRows.length)
1218
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionRedeemers).entries(redeemerRows));
1219
+ if (datumRows.length)
1220
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionDatums).entries(datumRows));
1221
+ // after the transactions moved here, so a rolled-back block they pointed at is no longer kept
1222
+ await this.removeSupersededBlocks(tx, blockData);
1223
+ // Same transaction, so the UTxO set can never be a block ahead of or behind the cursor.
1224
+ if (ledgerDue) {
1225
+ if (priorInvalidation) {
1226
+ // Decided in an earlier attempt of this block whose transaction rolled back: re-write
1227
+ // the verdict so whichever attempt commits carries it; nothing is applied meanwhile.
1228
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: priorInvalidation.slice(0, 500) });
1229
+ }
1230
+ else if (ledgerLookup) {
1231
+ const ledger = await (0, ledger_state_1.applyBlockToLedger)(tx, blockData, txs, ledgerLookup);
1232
+ if (ledger.missing) {
1233
+ logger.warn(`ledger: block ${blockData.hash} consumed ${ledger.missing} outpoint(s) with no open row: ` +
1234
+ 'the set is incomplete relative to the crawl (snapshot gap?); balances of those addresses drift');
1235
+ }
1236
+ }
1237
+ }
1238
+ if (assetHistoryRows.length)
1239
+ await tx.run(UPSERT.into(CardanoODataService_1.AssetHistory).entries(assetHistoryRows));
1240
+ // Catalogue last; collecting the units is skipped entirely when the catalogue is off.
1241
+ const newAssets = this.crawlAssetCatalogue === 'off'
1242
+ ? 0
1243
+ : await this.ensureAssetRows(tx, this.collectBlockUnits(txs, assetHistoryRows), blockData.slot);
1244
+ // A reference NFT moved or minted in this block carries the current CIP-68 metadata of its token.
1245
+ await (0, asset_decimals_1.applyReferenceDatums)(tx, txs);
1246
+ logger.debug(`indexBlockFull: block ${blockData.hash}: ${txs.length} txs, ${outputRows.length} outputs, ` +
1247
+ `${assetHistoryRows.length} mint/burn, ${newAssets} new assets`);
1248
+ }
1249
+ // Drops unreferenced Block rows at the same height. They are lazily indexed tips
1250
+ // that were rolled back, which no crawler reorg covers.
1251
+ async removeSupersededBlocks(tx, blockData) {
1252
+ if (blockData.height == null)
1253
+ return;
1254
+ const others = await tx.run(SELECT.from(CardanoODataService_1.Blocks).columns('hash').where({ height: blockData.height, hash: { '!=': blockData.hash } }));
1255
+ if (!others?.length)
1256
+ return;
1257
+ const hashes = others.map(r => r.hash);
1258
+ const referenced = await tx.run(SELECT.distinct.from(CardanoODataService_1.Transactions).columns('blockHash').where({ blockHash: { in: hashes } }));
1259
+ const keep = new Set((referenced ?? []).map(r => r.blockHash));
1260
+ const stale = hashes.filter(h => !keep.has(h));
1261
+ if (!stale.length)
1262
+ return;
1263
+ await tx.run(DELETE.from(CardanoODataService_1.Blocks).where({ hash: { in: stale } }));
1264
+ logger.info(`indexBlockFull: removed ${stale.length} superseded block row(s) at height ${blockData.height}`);
1265
+ }
1266
+ // Drops the rows of transactions that do not belong where this block puts them: another fork's
1267
+ // transactions in this block's slot, and this block's transactions stored at another position.
1268
+ // Their input and output rows would mix with ours or stay behind without a transaction.
1269
+ async removeStaleTxSeqs(tx, txs) {
1270
+ if (!txs.length)
1271
+ return;
1272
+ const ours = new Map(txs.map(t => [t.hash, (0, mappers_1.txSeqOf)(t.slot, t.index)]));
1273
+ const slot = txs[0].slot;
1274
+ const inSlot = await tx.run(SELECT.from(CardanoODataService_1.Transactions).columns('hash', 'txSeq')
1275
+ .where({ txSeq: { between: (0, mappers_1.txSeqOf)(slot, 0), and: (0, mappers_1.txSeqOf)(slot + 1, 0) - 1 } }));
1276
+ const stale = new Map();
1277
+ const note = (r) => { if (Number(r.txSeq) !== ours.get(r.hash))
1278
+ stale.set(`${r.hash}|${r.txSeq}`, r); };
1279
+ for (const r of inSlot ?? [])
1280
+ note(r);
1281
+ for (const hashChunk of (0, collections_1.chunk)([...ours.keys()], collections_1.IN_CHUNK)) {
1282
+ const stored = await tx.run(SELECT.from(CardanoODataService_1.Transactions).columns('hash', 'txSeq').where({ hash: { in: hashChunk } }));
1283
+ for (const r of stored ?? [])
1284
+ if (r.txSeq != null)
1285
+ note(r);
1286
+ }
1287
+ if (!stale.size)
1288
+ return;
1289
+ await (0, transaction_rows_1.deleteTransactionRows)(tx, [...stale.values()]);
1290
+ logger.info(`indexBlockFull: removed ${stale.size} transaction(s) stored at another position than slot ${slot} gives them`);
1291
+ }
1292
+ // Warns once when certificates are on but the source does not report them.
1293
+ // An empty array means none and is no warning.
1294
+ warnIfCertificatesUnreported(txs) {
1295
+ if (this.certificatesUnreportedWarned || !txs.length)
1296
+ return;
1297
+ if (txs.some(t => t.certificates !== undefined))
1298
+ return;
1299
+ this.certificatesUnreportedWarned = true;
1300
+ logger.warn('crawler.certificates is enabled but the active source reports no certificates/withdrawals ' +
1301
+ '(Blockfrost pagination). TransactionCertificates/TransactionWithdrawals stay empty until ' +
1302
+ 'the crawl runs on Ogmios chain-sync or Koios');
1303
+ }
1304
+ // Fills bare chain-sync inputs from this block's outputs, then the UTxO set, then the DB.
1305
+ // Inputs that already carry an address are skipped.
1306
+ async resolveInputs(tx, txs, ledger) {
1307
+ // 1. In-memory index of this block's outputs (txHash#outputIndex -> output)
528
1308
  const blockOutputs = new Map();
1309
+ const blockSeqs = new Map();
529
1310
  for (const t of txs) {
530
- for (const o of t.outputs ?? []) {
531
- blockOutputs.set(`${t.hash}#${o.outputIndex}`, { address: o.address, amount: o.amount ?? [] });
532
- }
1311
+ blockSeqs.set(t.hash, (0, mappers_1.txSeqOf)(t.slot, t.index));
1312
+ for (const o of t.outputs ?? [])
1313
+ blockOutputs.set(`${t.hash}#${o.outputIndex}`, o);
533
1314
  }
534
1315
  // 2. Collect inputs still needing resolution after the same-block pass
535
1316
  const unresolved = [];
536
1317
  for (const t of txs) {
537
1318
  for (const input of t.inputs ?? []) {
538
- if (input.address)
539
- continue; // already resolved by the backend (Blockfrost/Koios)
540
1319
  const key = `${input.txHash}#${input.outputIndex}`;
541
1320
  const local = blockOutputs.get(key);
1321
+ // an output of this block is stored with it
1322
+ if (local)
1323
+ input.spentTxSeq = blockSeqs.get(input.txHash) ?? null;
1324
+ if (input.address)
1325
+ continue; // already resolved by the backend (Blockfrost/Koios)
542
1326
  if (local) {
543
1327
  input.address = local.address;
544
- input.amount = local.amount;
1328
+ input.amount = local.amount ?? [];
1329
+ copyUtxoData(input, utxoDataOf(local));
545
1330
  }
546
1331
  else {
547
1332
  unresolved.push({ input, key });
@@ -550,130 +1335,560 @@ class CardanoIndexer {
550
1335
  }
551
1336
  if (!unresolved.length)
552
1337
  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)
1338
+ // 3. With the ledger due for this block, its UTxO rows answer first; the ledger apply
1339
+ // reuses the same lookup instead of reading these outpoints a second time.
1340
+ if (ledger) {
1341
+ await (0, ledger_state_1.readLedgerOutputs)(tx, unresolved.map(u => u.input.txHash), ledger);
1342
+ for (let i = unresolved.length - 1; i >= 0; i--) {
1343
+ const row = ledger.rows.get(unresolved[i].key);
1344
+ if (!row)
1345
+ continue;
1346
+ unresolved[i].input.address = row.address;
1347
+ unresolved[i].input.amount = (0, ledger_state_1.ledgerRowAmount)(row, ledger.assets.get(unresolved[i].key));
1348
+ copyUtxoData(unresolved[i].input, row);
1349
+ unresolved.splice(i, 1);
1350
+ }
1351
+ if (!unresolved.length)
1352
+ return;
1353
+ }
1354
+ // 4. Batch-read prior-block outputs from the DB, chunked so a dense block's input set
1355
+ // never exceeds a driver's bind-variable cap
556
1356
  const sourceHashes = [...new Set(unresolved.map(u => u.input.txHash))];
557
- const addrByKey = new Map();
1357
+ const hashBySeq = new Map();
1358
+ for (const k of await (0, transaction_rows_1.readTxKeys)(tx, sourceHashes)) {
1359
+ if (k.txSeq != null)
1360
+ hashBySeq.set((0, transaction_rows_1.seqKey)(k.txSeq), k.hash);
1361
+ }
1362
+ const outByKey = new Map();
558
1363
  const amtByKey = new Map();
559
- for (const hashChunk of (0, collections_1.chunk)(sourceHashes, collections_1.IN_CHUNK)) {
1364
+ for (const seqChunk of (0, collections_1.chunk)([...hashBySeq.keys()].map(Number), collections_1.IN_CHUNK)) {
560
1365
  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 } })),
1366
+ tx.run(SELECT.from(CardanoODataService_1.TransactionOutputs).where({ txSeq: { in: seqChunk } })),
1367
+ tx.run(SELECT.from(CardanoODataService_1.TransactionOutputAssets).where({ output_txSeq: { in: seqChunk } })),
563
1368
  ]);
564
1369
  for (const r of outRows) {
565
- addrByKey.set(`${r.tx_hash}#${r.outputIndex}`, r.address_address);
1370
+ outByKey.set(`${hashBySeq.get((0, transaction_rows_1.seqKey)(r.txSeq))}#${r.outputIndex}`, r);
566
1371
  }
567
1372
  for (const r of assetRows) {
568
- const k = `${r.output_tx_hash}#${r.output_outputIndex}`;
1373
+ const k = `${hashBySeq.get((0, transaction_rows_1.seqKey)(r.output_txSeq))}#${r.output_outputIndex}`;
569
1374
  const list = amtByKey.get(k) ?? [];
570
1375
  list.push({ unit: r.unit, quantity: String(r.asset_quantity) });
571
1376
  amtByKey.set(k, list);
572
1377
  }
573
1378
  }
574
1379
  for (const { input, key } of unresolved) {
575
- const addr = addrByKey.get(key);
576
- if (addr != null)
577
- input.address = addr;
1380
+ const out = outByKey.get(key);
1381
+ if (out?.address_address != null)
1382
+ input.address = out.address_address;
1383
+ if (out) {
1384
+ copyUtxoData(input, out);
1385
+ input.spentTxSeq = Number(out.txSeq);
1386
+ }
578
1387
  const amt = amtByKey.get(key);
579
1388
  if (amt)
580
1389
  input.amount = amt;
581
1390
  }
582
1391
  }
583
- /**
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
588
- */
1392
+ // Marks the inputs whose spent output is stored from an earlier block, so they can point at it.
1393
+ async referenceStoredOutputs(tx, txs) {
1394
+ const open = txs.flatMap(t => t.inputs ?? []).filter(i => i.spentTxSeq == null && i.txHash);
1395
+ if (!open.length)
1396
+ return;
1397
+ const seqByHash = new Map();
1398
+ for (const k of await (0, transaction_rows_1.readTxKeys)(tx, [...new Set(open.map(i => i.txHash))])) {
1399
+ if (k.txSeq != null)
1400
+ seqByHash.set(k.hash, Number(k.txSeq));
1401
+ }
1402
+ const stored = new Set();
1403
+ for (const seqChunk of (0, collections_1.chunk)([...new Set(seqByHash.values())], collections_1.IN_CHUNK)) {
1404
+ const rows = await tx.run(SELECT.from(CardanoODataService_1.TransactionOutputs).columns('txSeq', 'outputIndex').where({ txSeq: { in: seqChunk } }));
1405
+ for (const r of rows ?? [])
1406
+ stored.add(`${(0, transaction_rows_1.seqKey)(r.txSeq)}#${Number(r.outputIndex)}`);
1407
+ }
1408
+ for (const input of open) {
1409
+ const seq = seqByHash.get(input.txHash);
1410
+ if (seq != null && stored.has(`${(0, transaction_rows_1.seqKey)(seq)}#${input.outputIndex}`))
1411
+ input.spentTxSeq = seq;
1412
+ }
1413
+ }
1414
+ // Deposit of a transaction whose source left it open, from the ledger's balance: spent inputs
1415
+ // plus withdrawals, minus outputs, fee and treasury donation. Stays null while an input is not indexed.
1416
+ applyDeposits(txs) {
1417
+ const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
1418
+ for (const t of txs) {
1419
+ if (t.deposit != null)
1420
+ continue;
1421
+ const spent = (t.inputs ?? []).filter(i => !i.isCollateral && !i.isReference);
1422
+ if (spent.some(i => !i.address))
1423
+ continue;
1424
+ const consumed = spent.reduce((sum, i) => sum + lovelaceOf(i.amount), 0n)
1425
+ + (t.withdrawals ?? []).reduce((sum, w) => sum + BigInt(w.amount), 0n);
1426
+ const produced = (t.outputs ?? []).filter(o => !o.isCollateral).reduce((sum, o) => sum + lovelaceOf(o.amount), 0n)
1427
+ + BigInt(t.fee) + BigInt(t.treasuryDonation ?? '0');
1428
+ t.deposit = (consumed - produced).toString();
1429
+ }
1430
+ }
1431
+ // Fee of a phase-2 failure is collateral inputs minus collateral return. The declared fee
1432
+ // stays when total_collateral set it or a collateral input is not indexed.
1433
+ applyCollateralFees(blockData, txs) {
1434
+ const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
1435
+ let corrected = false;
1436
+ for (const t of txs) {
1437
+ // totalCollateral set = the mapper already put the charged amount in `fee`
1438
+ if (!t.spendsCollaterals || t.totalCollateral != null)
1439
+ continue;
1440
+ const collateral = (t.inputs ?? []).filter(i => i.isCollateral);
1441
+ if (!collateral.length)
1442
+ continue; // nothing to derive from, keep the declared fee
1443
+ const unresolved = collateral.find(i => !i.address);
1444
+ if (unresolved) {
1445
+ logger.warn(`collateral fee for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed` +
1446
+ `, keeping the declared fee ${t.fee}, which understates what the ledger charged`);
1447
+ continue;
1448
+ }
1449
+ const consumed = collateral.reduce((sum, i) => sum + lovelaceOf(i.amount), 0n);
1450
+ const returned = (t.outputs ?? [])
1451
+ .filter(o => o.isCollateral)
1452
+ .reduce((sum, o) => sum + lovelaceOf(o.amount), 0n);
1453
+ const charged = consumed - returned;
1454
+ if (charged < 0n) {
1455
+ logger.warn(`collateral fee for ${t.hash}: return ${returned} exceeds collateral ${consumed}` +
1456
+ `, keeping the declared fee ${t.fee}`);
1457
+ continue;
1458
+ }
1459
+ t.fee = charged.toString();
1460
+ corrected = true;
1461
+ }
1462
+ if (corrected) {
1463
+ blockData.fees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n).toString();
1464
+ }
1465
+ }
1466
+ // Uses the ledger's mint field when the source reports it, else outputs minus spent inputs per unit.
1467
+ // A tx with an unresolvable spent input is skipped and logged.
1468
+ buildAssetHistoryRows(blockData, txs) {
1469
+ const entries = [];
1470
+ let skipped = 0;
1471
+ for (const t of txs) {
1472
+ let net;
1473
+ if (t.mint) {
1474
+ // A phase-2 failure never reaches here with a mint: the Ogmios mapper reports none.
1475
+ net = new Map();
1476
+ for (const m of t.mint) {
1477
+ if (m.unit === 'lovelace')
1478
+ continue;
1479
+ net.set(m.unit, (net.get(m.unit) ?? 0n) + BigInt(m.quantity));
1480
+ }
1481
+ }
1482
+ else {
1483
+ if (t.spendsCollaterals)
1484
+ continue; // no mint is applied when the script phase failed
1485
+ const consumed = (t.inputs ?? []).filter(i => !i.isReference && !i.isCollateral);
1486
+ const unresolved = consumed.find(i => !i.address);
1487
+ if (unresolved) {
1488
+ logger.warn(`mint delta for ${t.hash}: input ${unresolved.txHash}#${unresolved.outputIndex} is not indexed` +
1489
+ `, skipping, mint/burn of this transaction is not recorded`);
1490
+ skipped++;
1491
+ continue;
1492
+ }
1493
+ net = new Map();
1494
+ const add = (amount, sign) => {
1495
+ for (const a of amount ?? []) {
1496
+ if (a.unit === 'lovelace')
1497
+ continue;
1498
+ net.set(a.unit, (net.get(a.unit) ?? 0n) + sign * BigInt(a.quantity));
1499
+ }
1500
+ };
1501
+ for (const o of (t.outputs ?? []).filter(o => !o.isCollateral))
1502
+ add(o.amount, 1n);
1503
+ for (const i of consumed)
1504
+ add(i.amount, -1n);
1505
+ }
1506
+ for (const [unit, quantity] of net) {
1507
+ if (quantity === 0n)
1508
+ continue;
1509
+ entries.push({
1510
+ unit,
1511
+ txHash: t.hash,
1512
+ action: quantity > 0n ? 'mint' : 'burn',
1513
+ quantity: (quantity < 0n ? -quantity : quantity).toString(),
1514
+ blockTime: blockData.time ?? null,
1515
+ blockHeight: blockData.height ?? null,
1516
+ });
1517
+ }
1518
+ }
1519
+ if (skipped) {
1520
+ logger.warn(`block ${blockData.hash}: mint/burn not recorded for ${skipped} transaction(s) with unresolved inputs`);
1521
+ }
1522
+ return (0, mappers_1.mapAssetHistory)(entries);
1523
+ }
1524
+ // Adds a bare Assets row for every new unit, without provider calls. Its epoch-zero key never hits
1525
+ // an enriched row. The existence check reads the DB entity, because the service view hides such rows.
1526
+ async ensureAssetRows(tx, units, slot) {
1527
+ if (this.crawlAssetCatalogue === 'off' || !units.size)
1528
+ return 0;
1529
+ const unknown = [...units].filter(u => !this.assetMemo.has(u));
1530
+ if (!unknown.length)
1531
+ return 0;
1532
+ const missing = [];
1533
+ for (const unitChunk of (0, collections_1.chunk)(unknown, collections_1.IN_CHUNK)) {
1534
+ const rows = await tx.run(SELECT.from(cardano_1.Assets).columns('unit').where({ unit: { in: unitChunk } }));
1535
+ const known = new Set(rows.map(r => r.unit));
1536
+ for (const unit of unitChunk) {
1537
+ if (known.has(unit))
1538
+ this.noteAssetSeen(unit);
1539
+ else
1540
+ missing.push(unit);
1541
+ }
1542
+ }
1543
+ if (!missing.length)
1544
+ return 0;
1545
+ const rows = missing.map(mappers_1.mapBareAsset).filter((r) => r !== null)
1546
+ .map((row) => ({ ...row, firstSeenSlot: slot ?? null }));
1547
+ for (const row of rows)
1548
+ row.decimals = await (0, asset_decimals_1.cip68Decimals)(tx, row.unit);
1549
+ // Chunked like the lookup: a mint-storm block can carry thousands of fresh units.
1550
+ for (const rowChunk of (0, collections_1.chunk)(rows, collections_1.IN_CHUNK)) {
1551
+ await tx.run(UPSERT.into(cardano_1.Assets).entries(rowChunk));
1552
+ }
1553
+ // Memoize also the units mapBareAsset rejected, so they cost no SELECT per block. Only after
1554
+ // the commit: a rolled-back block must write its bare rows again.
1555
+ this.pendingCommit.push(() => { for (const unit of missing)
1556
+ this.noteAssetSeen(unit); });
1557
+ if (this.crawlAssetCatalogue === 'enrich' && rows.length) {
1558
+ for (const row of rows) {
1559
+ if (this.enrichQueue.length >= CardanoIndexer.ENRICH_QUEUE_CAP)
1560
+ this.enrichQueue.shift();
1561
+ this.enrichQueue.push(row.unit);
1562
+ }
1563
+ this.startAssetEnrichment();
1564
+ }
1565
+ return rows.length;
1566
+ }
1567
+ // Oldest entries are evicted to keep memory flat. A lost entry costs one SELECT, never a wrong write.
1568
+ noteAssetSeen(unit) {
1569
+ if (this.assetMemo.has(unit))
1570
+ return;
1571
+ if (this.assetMemo.size >= CardanoIndexer.ASSET_MEMO_CAP) {
1572
+ const oldest = this.assetMemo.values().next();
1573
+ if (!oldest.done)
1574
+ this.assetMemo.delete(oldest.value);
1575
+ }
1576
+ this.assetMemo.add(unit);
1577
+ }
1578
+ /** Forgets the epoch totals in memory. A rollback removed blocks they counted. */
1579
+ forgetCrawlEpochs() {
1580
+ this.crawlEpochCache.clear();
1581
+ this.crawlEpochCurrent = null;
1582
+ this.crawlEpochPrevious = null;
1583
+ this.crawlEpochWritten = new WeakMap();
1584
+ }
1585
+ // After a rollback in the caller's transaction: a bare catalogue row a rolled-back block wrote is
1586
+ // removed, found by its key. A CIP-68 token reads its decimals again from the reference datum
1587
+ // that is still stored. `units` are the units of the rolled-back outputs.
1588
+ async reconcileRolledBackAssets(tx, units, forkSlot) {
1589
+ for (const unitChunk of (0, collections_1.chunk)(units, collections_1.IN_CHUNK)) {
1590
+ await tx.run(DELETE.from(cardano_1.Assets).where({ validFrom: mappers_1.BARE_ASSET_STAMP, unit: { in: unitChunk }, firstSeenSlot: { '>': forkSlot } }));
1591
+ }
1592
+ // A memo entry dropped too early costs one SELECT later, never a wrong write.
1593
+ for (const unit of units)
1594
+ this.assetMemo.delete(unit);
1595
+ const tokens = new Set(units.flatMap(unit => (0, cip68_1.cip68UserUnits)(unit) ?? []));
1596
+ for (const unit of tokens) {
1597
+ const decimals = await (0, asset_decimals_1.cip68Decimals)(tx, unit);
1598
+ if (decimals != null)
1599
+ await (0, asset_decimals_1.setAssetDecimals)(tx, unit, decimals);
1600
+ // without a reference datum the registry value applies, as when the row was written
1601
+ else
1602
+ await tx.run(UPDATE.entity(cardano_1.Assets).set `decimals = registryDecimals`.where({ unit }));
1603
+ }
1604
+ }
1605
+ // Snapshots all pools and DReps of an epoch in its own transaction after the block commit.
1606
+ // Ogmios reads the ledger at the given block, Koios the current state. Source null means skipped.
1607
+ async snapshotEpoch(epoch, at, shouldStop = () => false) {
1608
+ const epochState = at.hash ? this.client.getEpochStateBackend() : null;
1609
+ if (epochState && at.hash)
1610
+ return this.snapshotEpochFromLedger(epochState, epoch, { ...at, hash: at.hash }, shouldStop);
1611
+ const backend = this.client.getEnumeratingBackend();
1612
+ if (!backend) {
1613
+ logger.warn(`epoch ${epoch} snapshot skipped: no backend can read pools/DReps (Ogmios or Koios required)`);
1614
+ return { pools: 0, dreps: 0, source: null };
1615
+ }
1616
+ // Network first, DB second, so provider round trips never run under a write lock.
1617
+ const [poolData, drepData] = await Promise.all([
1618
+ backend.getPoolIds().then(ids => backend.getPools(ids)),
1619
+ backend.getDrepIds().then(ids => backend.getDreps(ids)),
1620
+ ]);
1621
+ const poolSnapshots = poolData.map(p => (0, mappers_1.mapPoolSnapshot)(p, epoch, at));
1622
+ const drepSnapshots = drepData.map(d => (0, mappers_1.mapDrepSnapshot)(d, epoch, at));
1623
+ const poolRows = poolData.map(p => (0, mappers_1.mapPool)(p, this.client.max_age_ms));
1624
+ const drepRows = drepData.map(d => (0, mappers_1.mapDrep)(d, this.client.max_age_ms));
1625
+ const ledgerRow = {
1626
+ epoch, snapshotSlot: at.slot, snapshotTime: at.time, snapshotHash: null, source: 'koios',
1627
+ liveStake: poolData.reduce((sum, p) => sum + BigInt(p.liveStake || '0'), 0n).toString(),
1628
+ poolCount: poolData.length, drepCount: drepData.length,
1629
+ };
1630
+ if (shouldStop())
1631
+ throw new Error(`epoch ${epoch} snapshot stopped before its write`);
1632
+ await cds_1.default.tx(async (tx) => {
1633
+ // Chunked so a mainnet-sized set cannot exceed a driver's bind-variable cap.
1634
+ for (const rows of (0, collections_1.chunk)(poolSnapshots, collections_1.IN_CHUNK))
1635
+ await tx.run(UPSERT.into(CardanoODataService_1.PoolEpochSnapshots).entries(rows));
1636
+ for (const rows of (0, collections_1.chunk)(drepSnapshots, collections_1.IN_CHUNK))
1637
+ await tx.run(UPSERT.into(CardanoODataService_1.DrepEpochSnapshots).entries(rows));
1638
+ for (const rows of (0, collections_1.chunk)(poolRows, collections_1.IN_CHUNK))
1639
+ await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(rows));
1640
+ for (const rows of (0, collections_1.chunk)(drepRows, collections_1.IN_CHUNK))
1641
+ await tx.run(UPSERT.into(CardanoODataService_1.Dreps).entries(rows));
1642
+ await tx.run(UPSERT.into(CardanoODataService_1.EpochLedgerSnapshots).entries(ledgerRow));
1643
+ });
1644
+ logger.info(`epoch ${epoch} snapshot (koios): ${poolSnapshots.length} pools, ${drepSnapshots.length} DReps`);
1645
+ return { pools: poolSnapshots.length, dreps: drepSnapshots.length, source: 'koios' };
1646
+ }
1647
+ // Live Pools and Dreps rows are not refreshed, because the ledger state may be hours old.
1648
+ // blocksMinted is set only when the crawl covers the chain since Shelley.
1649
+ async snapshotEpochFromLedger(backend, epoch, at, shouldStop) {
1650
+ const state = await backend.epochStateAt({ slot: at.slot, hash: at.hash });
1651
+ if (state.epoch !== epoch) {
1652
+ logger.warn(`epoch snapshot: ledger at slot ${at.slot} reports epoch ${state.epoch}, crawler dated it ${epoch}, stored as ${epoch}`);
1653
+ }
1654
+ const minted = await this.crawledBlocksByPool(at.slot);
1655
+ const previous = await this.previousLiveStake(epoch);
1656
+ const activeTotal = previous ? [...previous.values()].reduce((a, b) => a + b, 0n) : 0n;
1657
+ const origin = { source: 'ogmios', hash: at.hash };
1658
+ const poolSnapshots = state.pools.map(p => {
1659
+ const active = previous?.get(p.poolId);
1660
+ return {
1661
+ ...(0, mappers_1.mapPoolSnapshot)(p, epoch, at, origin),
1662
+ blocksMinted: minted ? (minted.get(p.poolId) ?? 0) : null,
1663
+ activeStake: active == null ? null : active.toString(),
1664
+ activeSize: active == null || activeTotal === 0n ? null : Number((active * 1000000n) / activeTotal) / 1_000_000,
1665
+ };
1666
+ });
1667
+ const drepSnapshots = state.dreps.map(d => (0, mappers_1.mapDrepSnapshot)(d, epoch, at, origin));
1668
+ const reserves = state.reserves == null ? null : BigInt(state.reserves);
1669
+ const ledgerRow = {
1670
+ epoch, snapshotSlot: at.slot, snapshotTime: at.time, snapshotHash: at.hash, source: 'ogmios',
1671
+ treasury: state.treasury,
1672
+ reserves: state.reserves,
1673
+ totalSupply: reserves == null ? null : (BigInt(const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY) - reserves).toString(),
1674
+ liveStake: state.pools.reduce((sum, p) => sum + BigInt(p.liveStake || '0'), 0n).toString(),
1675
+ activeStake: previous ? activeTotal.toString() : null,
1676
+ poolCount: state.pools.length,
1677
+ drepCount: state.dreps.length,
1678
+ drepAbstainStake: state.drepAbstainStake,
1679
+ drepNoConfidenceStake: state.drepNoConfidenceStake,
1680
+ };
1681
+ if (shouldStop())
1682
+ throw new Error(`epoch ${epoch} snapshot stopped before its write`);
1683
+ await cds_1.default.tx(async (tx) => {
1684
+ for (const rows of (0, collections_1.chunk)(poolSnapshots, collections_1.IN_CHUNK))
1685
+ await tx.run(UPSERT.into(CardanoODataService_1.PoolEpochSnapshots).entries(rows));
1686
+ for (const rows of (0, collections_1.chunk)(drepSnapshots, collections_1.IN_CHUNK))
1687
+ await tx.run(UPSERT.into(CardanoODataService_1.DrepEpochSnapshots).entries(rows));
1688
+ await tx.run(UPSERT.into(CardanoODataService_1.EpochLedgerSnapshots).entries(ledgerRow));
1689
+ });
1690
+ logger.info(`epoch ${epoch} snapshot (ogmios @ slot ${at.slot}): ${poolSnapshots.length} pools, ${drepSnapshots.length} DReps`);
1691
+ return { pools: poolSnapshots.length, dreps: drepSnapshots.length, source: 'ogmios' };
1692
+ }
1693
+ // Active stake of epoch E is the live stake in the snapshot of epoch E-1.
1694
+ // Null without that snapshot.
1695
+ async previousLiveStake(epoch) {
1696
+ const rows = await cds_1.default.db.run(SELECT.from(CardanoODataService_1.PoolEpochSnapshots).columns('poolId', 'liveStake').where({ epoch: epoch - 1, source: 'ogmios' }));
1697
+ if (!rows?.length)
1698
+ return null;
1699
+ return new Map(rows.map(r => [r.poolId, BigInt(lovelaceSum(r.liveStake))]));
1700
+ }
1701
+ /** Crawled blocks per pool up to `slot`; null unless the crawl started at or before Shelley. */
1702
+ async crawledBlocksByPool(slot) {
1703
+ const db = cds_1.default.db;
1704
+ const cursor = await (0, sync_state_1.readCursor)(db);
1705
+ const shelley = const_1.EPOCH_CONFIG_BY_NETWORK[this.client.network].shelleyStartSlot;
1706
+ if (cursor?.startSlot == null || cursor.startSlot > shelley)
1707
+ return null;
1708
+ const rows = await db.run(SELECT.from(CardanoODataService_1.Blocks).columns('slotLeader', 'count(*) as n').where({ slot: { '<=': slot } }).groupBy('slotLeader'));
1709
+ const out = new Map();
1710
+ for (const r of rows ?? [])
1711
+ if (r.slotLeader)
1712
+ out.set(r.slotLeader, Number(r.n));
1713
+ return out;
1714
+ }
1715
+ /** Every native-asset unit a block touches: outputs, consumed inputs and mint/burn rows. */
1716
+ collectBlockUnits(txs, assetHistoryRows) {
1717
+ const units = new Set();
1718
+ for (const t of txs) {
1719
+ for (const o of t.outputs ?? []) {
1720
+ for (const a of o.amount ?? [])
1721
+ if (a.unit !== 'lovelace')
1722
+ units.add(a.unit);
1723
+ }
1724
+ for (const i of t.inputs ?? []) {
1725
+ for (const a of i.amount ?? [])
1726
+ if (a.unit !== 'lovelace')
1727
+ units.add(a.unit);
1728
+ }
1729
+ }
1730
+ for (const row of assetHistoryRows)
1731
+ if (row.unit)
1732
+ units.add(row.unit);
1733
+ return units;
1734
+ }
1735
+ /** Index an epoch by number. */
589
1736
  async indexEpoch(tx, epochNumber) {
590
- const epochInfo = await this.client.getEpoch(epochNumber);
591
- const epochEntity = (0, mappers_1.mapEpoch)(epochInfo);
592
- await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([epochEntity]));
593
- return epochEntity;
594
- }
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
- */
1737
+ return this.storeEpoch(tx, await this.fetchEpoch(epochNumber));
1738
+ }
1739
+ /** An epoch row from the backend. */
1740
+ async fetchEpoch(epochNumber) {
1741
+ return (0, mappers_1.mapEpoch)(await this.client.getEpoch(epochNumber));
1742
+ }
1743
+ async storeEpoch(tx, epochEntity) {
1744
+ const row = this.withFinal(epochEntity);
1745
+ await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([row]));
1746
+ return row;
1747
+ }
1748
+ // An epoch row is final once the epoch has ended and its last blocks are past the rollback
1749
+ // horizon. A row with crawled totals also needs the crawl past the epoch. Until then a read refreshes it.
1750
+ withFinal(epochEntity, now = Date.now(), crawlComplete) {
1751
+ const end = epochEntity.endTime == null ? null : Number(epochEntity.endTime);
1752
+ const network = this.client.network;
1753
+ const settle = ((0, epoch_slots_1.rollbackHorizonSlots)(network) * const_1.GENESIS_INFOS_BY_NETWORK[network].slotLengthMs) / 1000;
1754
+ const settled = end != null && Number.isFinite(end) && now / 1000 >= end + settle;
1755
+ return { ...epochEntity, final: settled && crawlComplete !== false };
1756
+ }
1757
+ /** Index an account by stake address. Its addresses are read on their own. */
601
1758
  async indexAccount(tx, stakeAddress) {
602
- const accountInfo = await this.client.getAccount(stakeAddress);
603
- const accountEntity = (0, mappers_1.mapAccount)(accountInfo, this.client.max_age_ms);
604
- await tx.run(UPSERT.into(CardanoODataService_1.Accounts).entries(accountEntity));
605
- const addresses = accountInfo.addresses.map(a => a.address);
606
- if (accountEntity.hasAddresses) {
607
- await this._ensureAddresses(tx, addresses);
608
- }
1759
+ return this.storeAccount(tx, await this.fetchAccount(tx, stakeAddress));
1760
+ }
1761
+ /** An account, read but not stored. */
1762
+ async fetchAccount(tx, stakeAddress) {
1763
+ return { account: await this.resolveAccount(tx, stakeAddress) };
1764
+ }
1765
+ // Stores the account row with its address list. An account can hold thousands of addresses, so
1766
+ // they are indexed when a read names them, never as part of the account.
1767
+ async storeAccount(tx, fetched) {
1768
+ const addresses = accountAddressList(fetched.account.addresses);
1769
+ const accountEntity = { ...(0, mappers_1.mapAccount)(fetched.account, this.client.max_age_ms), addressCount: addresses.length };
1770
+ await tx.run(UPSERT.into(cardano_1.Accounts).entries({ ...accountEntity, addressList: JSON.stringify(addresses) }));
609
1771
  return accountEntity;
610
1772
  }
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
- */
1773
+ /** Account from the backend with the crawled overlays (controlled amount, withdrawals). */
1774
+ async resolveAccount(tx, stakeAddress) {
1775
+ const accountInfo = { ...(await this.client.getAccount(stakeAddress)) };
1776
+ const local = await (0, tx_utils_1.readOutside)(tx, async (db) => {
1777
+ const ledger = Boolean((await this.localCoverage(db))?.ledger);
1778
+ const row = ledger
1779
+ ? await db.run(SELECT.one.from(CardanoODataService_1.LedgerAccounts).columns('controlledAmount').where({ stakeAddress }))
1780
+ : undefined;
1781
+ return {
1782
+ ledger,
1783
+ controlledAmount: row?.controlledAmount,
1784
+ held: ledger ? await this.ledgerAccountUtxos(db, stakeAddress) : { addresses: [], utxos: [] },
1785
+ withdrawalsSum: accountInfo.withdrawalsSum == null || accountInfo.withdrawalsSum === '0' ? await this.localWithdrawalsSum(db, stakeAddress) : null,
1786
+ };
1787
+ });
1788
+ // controlled amount = UTxOs under the stake key (crawled set, when current) + reward balance;
1789
+ // the addresses come from the set too (the node has no stake-key -> address index)
1790
+ if (local.ledger) {
1791
+ accountInfo.controlledAmount = (BigInt(lovelaceSum(local.controlledAmount)) + BigInt(accountInfo.withdrawableAmount || '0')).toString();
1792
+ accountInfo.addresses = local.held.addresses;
1793
+ }
1794
+ if (local.withdrawalsSum != null)
1795
+ accountInfo.withdrawalsSum = local.withdrawalsSum;
1796
+ return accountInfo;
1797
+ }
1798
+ /** Index a DRep by bech32 id. */
617
1799
  async indexDrep(tx, drepId) {
618
- const drepInfo = await this.client.getDrep(drepId);
619
- const drepEntity = (0, mappers_1.mapDrep)(drepInfo, this.client.max_age_ms);
1800
+ return this.storeDrep(tx, await this.fetchDrep(drepId));
1801
+ }
1802
+ /** A DRep row from the backend. */
1803
+ async fetchDrep(drepId) {
1804
+ return (0, mappers_1.mapDrep)(await this.client.getDrep(drepId), this.client.max_age_ms);
1805
+ }
1806
+ async storeDrep(tx, drepEntity) {
620
1807
  await tx.run(UPSERT.into(CardanoODataService_1.Dreps).entries(drepEntity));
621
1808
  return drepEntity;
622
1809
  }
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
- */
1810
+ /** Index a pool by id. */
629
1811
  async indexPool(tx, poolId) {
630
- const poolInfo = await this.client.getPool(poolId);
631
- const poolEntity = (0, mappers_1.mapPool)(poolInfo, this.client.max_age_ms);
1812
+ return this.storePool(tx, await this.fetchPool(tx, poolId));
1813
+ }
1814
+ /** A pool row, read but not stored. */
1815
+ async fetchPool(tx, poolId) {
1816
+ return (0, mappers_1.mapPool)(await this.resolvePool(tx, poolId), this.client.max_age_ms);
1817
+ }
1818
+ async storePool(tx, poolEntity) {
632
1819
  await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(poolEntity));
633
1820
  return poolEntity;
634
1821
  }
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
- */
1822
+ /** Pool from the backend with crawled block counts, the snapshot's active stake and its metadata file. */
1823
+ async resolvePool(tx, poolId) {
1824
+ const backend = await this.client.getPool(poolId);
1825
+ const local = await (0, tx_utils_1.readOutside)(tx, async (db) => {
1826
+ const blocks = await this.localPoolBlocks(db, poolId);
1827
+ // The node's live pool view has no active stake; the epoch snapshot of the current epoch does.
1828
+ return backend.activeStake == null || backend.activeStake === '0' ? { ...blocks, ...(await this.snapshotActiveStake(db, poolId)) } : blocks;
1829
+ });
1830
+ const poolInfo = { ...backend, ...local };
1831
+ Object.assign(poolInfo, await this.poolMetadataOf(poolInfo));
1832
+ return poolInfo;
1833
+ }
1834
+ // Name, ticker, homepage and description of a pool whose backend gave only the file's URL and hash.
1835
+ // Loads the file when `poolMetadataFetch` is on. A file is memoized by its hash.
1836
+ async poolMetadataOf(pool) {
1837
+ if (!this.poolMetadataFetch || pool.name != null || !pool.metadataUrl || !pool.metadataHash)
1838
+ return undefined;
1839
+ const known = this.poolMetadataByHash.get(pool.metadataHash);
1840
+ if (known)
1841
+ return known;
1842
+ const metadata = await (0, pool_metadata_1.fetchPoolMetadata)(pool.metadataUrl, pool.metadataHash);
1843
+ if (!metadata)
1844
+ return undefined;
1845
+ if (this.poolMetadataByHash.size >= CardanoIndexer.POOL_METADATA_MEMO_CAP)
1846
+ this.poolMetadataByHash.clear();
1847
+ this.poolMetadataByHash.set(pool.metadataHash, metadata);
1848
+ return metadata;
1849
+ }
1850
+ /** Turns the loading of pool metadata files on or off (`poolMetadataFetch`). */
1851
+ setPoolMetadataFetch(enabled) {
1852
+ this.poolMetadataFetch = enabled;
1853
+ }
1854
+ /** Index an asset by unit (policyId + assetNameHex). */
641
1855
  async indexAsset(tx, unit) {
642
- const assetInfo = await this.client.getAssetInfo(unit);
1856
+ return this.writeAsset(tx, unit, await this.resolveAssetInfo(tx, unit));
1857
+ }
1858
+ /** Stores an asset read with resolveAssetInfo. */
1859
+ async storeAsset(tx, assetInfo) {
1860
+ return this.writeAsset(tx, assetInfo.unit, assetInfo);
1861
+ }
1862
+ /** Like indexAsset, but always from the backend: the crawled chain has no CIP-26 registry fields. */
1863
+ async indexAssetFromBackend(tx, unit) {
1864
+ return this.writeAsset(tx, unit, await this.client.getAssetInfo(unit));
1865
+ }
1866
+ async writeAsset(tx, unit, assetInfo) {
643
1867
  const assetEntity = (0, mappers_1.mapAsset)(assetInfo, this.client.max_age_ms);
1868
+ assetEntity.decimals = (await (0, asset_decimals_1.cip68Decimals)(tx, unit, assetInfo.initialMintTxHash)) ?? assetInfo.registryDecimals;
644
1869
  await tx.run(UPSERT.into(CardanoODataService_1.Assets).entries(assetEntity));
645
1870
  return assetEntity;
646
1871
  }
647
- /**
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
656
- */
1872
+ /** Always fresh. Rows are keyed by unit and tx, so older cached entries persist. */
657
1873
  async indexAssetHistory(tx, unit, limit = 100) {
1874
+ const crawled = await (0, tx_utils_1.readOutside)(tx, (db) => this.crawledAssetHistory(db, unit, limit));
1875
+ if (crawled)
1876
+ return crawled;
658
1877
  const events = await this.client.getAssetHistory(unit, limit);
659
1878
  if (events.length === 0)
660
1879
  return [];
661
- const rows = (0, mappers_1.mapAssetHistory)(events);
1880
+ // a provider can list one transaction twice; Postgres refuses an UPSERT that hits a key twice
1881
+ const rows = [...new Map((0, mappers_1.mapAssetHistory)(events).map(r => [`${r.unit}|${r.txHash}`, r])).values()];
662
1882
  await tx.run(UPSERT.into(CardanoODataService_1.AssetHistory).entries(rows));
663
1883
  return rows;
664
1884
  }
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
- */
1885
+ /** Build a transaction and persist the build result with inputs/outputs/address association. */
673
1886
  async _indexBuildResult(tx, buildreq, buildFn) {
674
- const protocolParams = await this.indexProtocolParameters(tx);
675
- const txbuildResult = await buildFn(buildreq, protocolParams);
1887
+ // The build talks to the backend: nothing is written before it returns.
1888
+ const protocolParams = await this.fetchProtocolParameters(tx);
1889
+ const txbuildResult = await buildFn(buildreq, protocolParams.row);
676
1890
  const buildResult = (0, mappers_1.mapBuildResult)(txbuildResult, this.client.max_age_ms);
1891
+ await this.storeProtocolParameters(tx, protocolParams);
677
1892
  await tx.run(UPSERT.into(CardanoTransactionService_1.TransactionBuild).entries(buildResult));
678
1893
  if (buildResult.id && txbuildResult.inputs && txbuildResult.inputs.length > 0) {
679
1894
  const inputRows = (0, mappers_1.mapBuildInputs)(buildResult.id, txbuildResult.inputs);
@@ -683,6 +1898,10 @@ class CardanoIndexer {
683
1898
  const outputRows = (0, mappers_1.mapBuildOutputs)(buildResult.id, txbuildResult.outputs, buildreq.changeAddress || buildreq.senderAddress);
684
1899
  await tx.run(UPSERT.into(CardanoTransactionService_1.TransactionBuildOutputs).entries(outputRows));
685
1900
  }
1901
+ if (buildResult.id && txbuildResult.redeemers && txbuildResult.redeemers.length > 0) {
1902
+ const buildId = buildResult.id;
1903
+ await tx.run(UPSERT.into(CardanoTransactionService_1.TransactionBuildRedeemers).entries(txbuildResult.redeemers.map(r => ({ build_id: buildId, tag: r.tag, redeemerIndex: r.index, mem: Number(r.mem), steps: Number(r.steps) }))));
1904
+ }
686
1905
  if (buildResult.id && buildreq.senderAddress) {
687
1906
  await this.indexAddressTransactionBuilds(tx, buildreq.senderAddress, buildResult.id);
688
1907
  }
@@ -703,52 +1922,45 @@ class CardanoIndexer {
703
1922
  async indexPlutusSpendBuildResult(tx, buildreq) {
704
1923
  return this._indexBuildResult(tx, buildreq, (req, params) => this.txBuilder.buildPlutusSpendTransaction(req, params));
705
1924
  }
706
- /**
707
- * Index & return the protocol parameters data
708
- * @param tx CAP transaction object
709
- * @returns {Promise<LedgerProtocolParameter>} protocol parameters entity data
710
- */
1925
+ /** BuildPlutusTransaction: several script inputs; the redeemers are stored with the build. */
1926
+ async indexPlutusBuildResult(tx, buildreq) {
1927
+ return this._indexBuildResult(tx, buildreq, (req, params) => this.txBuilder.buildPlutusTransaction(req, params));
1928
+ }
1929
+ /** Protocol parameters, served from the DB row within a 5-minute TTL. */
711
1930
  async indexProtocolParameters(tx) {
1931
+ return this.storeProtocolParameters(tx, await this.fetchProtocolParameters(tx));
1932
+ }
1933
+ /** The stored row within its TTL, else the parameters from the backend. Nothing is written. */
1934
+ async fetchProtocolParameters(tx) {
712
1935
  const network = this.client.network;
713
- 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
716
- 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.
719
- const existing = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerProtocolParameter).where({ network }).orderBy('epoch desc'));
1936
+ if (Date.now() - this.lastParamsFetchTime < const_1.PROTOCOL_PARAMS_TTL_MS) {
1937
+ // (network, epoch) is the key; order by epoch desc to get the latest row
1938
+ const existing = await (0, tx_utils_1.readOutside)(tx, (db) => db.run(SELECT.one.from(CardanoODataService_1.LedgerProtocolParameter).where({ network }).orderBy('epoch desc')));
720
1939
  if (existing)
721
- return existing;
722
- }
723
- // Fetch from provider (client has 5-min in-memory TTL cache, so this is cheap)
724
- const protocolParamsInfo = await this.client.getProtocolParameters();
725
- const protocolParams = (0, mappers_1.mapProtocolParameters)(protocolParamsInfo);
726
- await tx.run(UPSERT.into(CardanoODataService_1.LedgerProtocolParameter).entries(protocolParams));
727
- this.lastParamsFetchTime = now;
728
- return protocolParams;
729
- }
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
- */
1940
+ return { row: existing, fresh: false };
1941
+ }
1942
+ return { row: (0, mappers_1.mapProtocolParameters)(await this.client.getProtocolParameters()), fresh: true };
1943
+ }
1944
+ /** Stores parameters that came from the backend and restarts their TTL. */
1945
+ async storeProtocolParameters(tx, fetched) {
1946
+ if (fetched.fresh) {
1947
+ await tx.run(UPSERT.into(CardanoODataService_1.LedgerProtocolParameter).entries(fetched.row));
1948
+ this.lastParamsFetchTime = Date.now();
1949
+ }
1950
+ return fetched.row;
1951
+ }
1952
+ /** Persist a transaction submission and flag the build as submitted when linked. */
737
1953
  async persistTransactionSubmission(tx, params) {
738
1954
  const { signedTxCbor, txHash, buildId } = params;
739
- // Map submission data
740
1955
  const indexSubmission = (0, mappers_1.mapTransactionSubmission)(signedTxCbor, txHash);
741
- // Create submission record (status: 'pending' — updated to 'submitted' after blockchain confirms)
742
1956
  const submissionRecord = {
743
1957
  ...indexSubmission,
744
1958
  build_id: buildId || null,
745
1959
  backendResponse: 'Submitted successfully',
746
- status: 'pending',
1960
+ status: params.status ?? 'pending',
747
1961
  };
748
- // Persist submission
749
1962
  await tx.run(INSERT.into(CardanoTransactionService_1.TransactionSubmissions).entries(submissionRecord));
750
1963
  logger.debug({ submissionId: submissionRecord.id, txHash }, 'Persisted submission record');
751
- // Update build status if buildId provided
752
1964
  if (buildId) {
753
1965
  await tx.run(UPDATE.entity(CardanoTransactionService_1.TransactionBuilds)
754
1966
  .set({ wasSubmitted: true })
@@ -757,33 +1969,30 @@ class CardanoIndexer {
757
1969
  }
758
1970
  return submissionRecord;
759
1971
  }
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
- */
768
- async updateSubmissionStatus(tx, submissionId, status, errorMessage) {
1972
+ /** Update a submission's status. With onlyFrom the row changes only while it has that status. */
1973
+ async updateSubmissionStatus(tx, submissionId, status, errorMessage, onlyFrom) {
769
1974
  const updateData = { status };
770
1975
  if (errorMessage) {
771
1976
  updateData.errorMessage = errorMessage;
772
1977
  }
773
1978
  await tx.run(UPDATE.entity(CardanoTransactionService_1.TransactionSubmissions)
774
1979
  .set(updateData)
775
- .where({ id: submissionId }));
1980
+ .where(onlyFrom ? { id: submissionId, status: onlyFrom } : { id: submissionId }));
776
1981
  logger.debug({ submissionId, status }, 'Updated submission status');
777
1982
  }
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
- */
1983
+ /** Deletes a resubmit's row when the transaction already has a submitted or confirmed row. */
1984
+ async dropDuplicateSubmission(tx, submissionId, txHash) {
1985
+ const existing = await tx.run(SELECT.one.from(CardanoTransactionService_1.TransactionSubmissions).columns('id')
1986
+ .where({ txHash, status: { in: ['submitted', 'confirmed'] }, id: { '!=': submissionId } }));
1987
+ if (!existing)
1988
+ return false;
1989
+ await tx.run(DELETE.from(CardanoTransactionService_1.TransactionSubmissions).where({ id: submissionId }));
1990
+ logger.debug({ submissionId, existingId: existing.id, txHash }, 'Dropped duplicate submission row');
1991
+ return true;
1992
+ }
1993
+ /** Persist a new signing request and link it to the build's sender address. */
784
1994
  async persistSigningRequest(tx, params) {
785
1995
  const { buildId, signingPayload } = params;
786
- // Create signing request record
787
1996
  const signingRequestRecord = {
788
1997
  id: signingPayload.signingRequestId,
789
1998
  build_id: buildId,
@@ -796,26 +2005,17 @@ class CardanoIndexer {
796
2005
  cardanoCliCommand: signingPayload.signingInstructions.cardanoCliCommand,
797
2006
  cip30TxCbor: signingPayload.signingInstructions.cip30SigningRequest?.txCbor,
798
2007
  };
799
- // Persist to database
800
2008
  await tx.run(INSERT.into(CardanoSignService_1.SigningRequests).entries(signingRequestRecord));
801
2009
  logger.debug({ signingRequestId: signingRequestRecord.id, buildId }, 'Persisted signing request');
802
- // Index address-signing request association
803
2010
  const build = await tx.run(SELECT.one.from(CardanoTransactionService_1.TransactionBuilds).where({ id: buildId }));
804
2011
  if (build?.senderAddress) {
805
2012
  await this.indexAddressSigningRequests(tx, build.senderAddress, signingRequestRecord.id);
806
2013
  }
807
2014
  return signingRequestRecord;
808
2015
  }
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
- */
2016
+ /** Persist a signature verification and update the signing request status. */
816
2017
  async persistSignatureVerification(tx, params) {
817
2018
  const { signingRequestId, signedTxCbor, verificationResult, signerType, signerInfo } = params;
818
- // Create verification record
819
2019
  const verificationRecord = {
820
2020
  id: cds_1.default.utils.uuid(),
821
2021
  signingRequest_id: signingRequestId,
@@ -828,10 +2028,8 @@ class CardanoIndexer {
828
2028
  warnings: JSON.stringify(verificationResult.warnings),
829
2029
  verifiedAt: new Date().toISOString(),
830
2030
  };
831
- // Persist verification
832
2031
  await tx.run(INSERT.into(CardanoSignService_1.SignatureVerifications).entries(verificationRecord));
833
2032
  logger.debug({ verificationId: verificationRecord.id }, 'Persisted signature verification record');
834
- // Update signing request status
835
2033
  const newStatus = verificationResult.isValid ? 'verified' : 'failed';
836
2034
  await tx.run(UPDATE.entity(CardanoSignService_1.SigningRequests)
837
2035
  .set({
@@ -845,16 +2043,9 @@ class CardanoIndexer {
845
2043
  logger.debug({ signingRequestId, newStatus }, 'Updated signing request status');
846
2044
  return verificationRecord;
847
2045
  }
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
- */
2046
+ /** Persist a verified submission: verification, submission, signing request and build updates. */
855
2047
  async indexVerifiedTransactionSubmission(tx, params) {
856
2048
  const { signingRequestId, buildId, fullSignedTxCbor, txHash, verificationResult, signerType, signerInfo } = params;
857
- // Step 1: Create and persist verification record
858
2049
  const verificationRecord = {
859
2050
  id: cds_1.default.utils.uuid(),
860
2051
  signingRequest_id: signingRequestId,
@@ -869,7 +2060,6 @@ class CardanoIndexer {
869
2060
  };
870
2061
  await tx.run(INSERT.into(CardanoSignService_1.SignatureVerifications).entries(verificationRecord));
871
2062
  logger.debug({ verificationId: verificationRecord.id }, 'Persisted signature verification record');
872
- // Step 2: Create and persist submission record
873
2063
  const indexSubmission = (0, mappers_1.mapTransactionSubmission)(fullSignedTxCbor, txHash);
874
2064
  const submissionRecord = {
875
2065
  ...indexSubmission,
@@ -879,7 +2069,6 @@ class CardanoIndexer {
879
2069
  };
880
2070
  await tx.run(INSERT.into(CardanoTransactionService_1.TransactionSubmissions).entries(submissionRecord));
881
2071
  logger.debug({ submissionId: submissionRecord.id }, 'Persisted submission record');
882
- // Step 3: Update signing request metadata and status
883
2072
  const now = new Date().toISOString();
884
2073
  await tx.run(UPDATE.entity(CardanoSignService_1.SigningRequests)
885
2074
  .set({
@@ -892,113 +2081,112 @@ class CardanoIndexer {
892
2081
  })
893
2082
  .where({ id: signingRequestId }));
894
2083
  logger.debug({ signingRequestId }, 'Updated signing request status to submitted');
895
- // Step 4: Update build status
896
2084
  await tx.run(UPDATE.entity(CardanoTransactionService_1.TransactionBuilds)
897
2085
  .set({ wasSubmitted: true })
898
2086
  .where({ id: buildId }));
899
2087
  logger.debug({ buildId }, 'Updated build wasSubmitted flag');
900
2088
  return submissionRecord;
901
2089
  }
902
- /**
903
- * Index & return the latest epoch information data
904
- * @param tx CAP transaction object
905
- * @returns {Promise<Epoch>} epoch entity data
906
- */
2090
+ /** Index the latest epoch. */
907
2091
  async indexLatestEpoch(tx) {
908
- const epochInfo = await this.client.getLatestEpoch();
909
- const epochEntity = (0, mappers_1.mapEpoch)(epochInfo);
910
- await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([epochEntity]));
911
- return epochEntity;
912
- }
913
- /**
914
- * Index & return the latest block information data
915
- * @param tx CAP transaction object
916
- * @returns {Promise<Block>} block entity data
917
- */
2092
+ return this.storeEpoch(tx, (0, mappers_1.mapEpoch)(await this.client.getLatestEpoch()));
2093
+ }
2094
+ /** Index the latest block, with best-effort epoch enrichment. */
918
2095
  async indexLatestBlock(tx) {
919
- const blockInfo = await this.client.getLatestBlock();
920
- let epoch;
921
- try {
922
- epoch = await this.indexEpoch(tx, blockInfo.epoch);
2096
+ const fetched = await this.withEpoch(await this.client.getLatestBlock());
2097
+ // A header-only tip is never persisted: its zeros would read as an empty block, overwrite a
2098
+ // crawled row of the same hash, or outlive the block when the tip is rolled back.
2099
+ if (fetched.block.headerOnly) {
2100
+ if (fetched.epoch)
2101
+ await this.storeEpoch(tx, fetched.epoch);
2102
+ const stored = await tx.run(SELECT.one.from(CardanoODataService_1.Block).where({ hash: fetched.block.hash }));
2103
+ return stored ?? (0, mappers_1.mapBlock)(fetched.block, fetched.epoch);
923
2104
  }
924
- catch {
925
- // Epoch data may not be available (e.g., Koios drops old/in-progress epochs)
926
- }
927
- const blockEntity = (0, mappers_1.mapBlock)(blockInfo, epoch);
928
- await tx.run(UPSERT.into(CardanoODataService_1.Block).entries(blockEntity));
929
- return blockEntity;
2105
+ return this.storeBlock(tx, fetched);
930
2106
  }
931
2107
  //-----------------------------------------------------------------------------
932
2108
  // Batch Methods (N+1 Optimization)
933
2109
  //-----------------------------------------------------------------------------
934
- /** Max addresses to index concurrently (avoid overloading backends) */
935
- static ADDR_CONCURRENCY = 5;
936
- /**
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)
946
- */
2110
+ // Confirmations including the tx's own block, 0 while not on chain. A stored row counts only inside
2111
+ // the crawled chain, because the crawler removes those rows on a rollback.
2112
+ async resolveTransactionConfirmations(tx, txHash) {
2113
+ const crawled = await (0, tx_utils_1.readOutside)(tx, (db) => this.crawledTransactionDepth(db, txHash));
2114
+ if (crawled)
2115
+ return { txHash, ...crawled, confirmations: crawled.tipHeight - crawled.blockHeight + 1 };
2116
+ let providerTx = null;
2117
+ try {
2118
+ providerTx = await this.fetchTransaction(tx, txHash);
2119
+ }
2120
+ catch (err) {
2121
+ if (!(0, errors_1.isNotFoundOnAllBackends)(err))
2122
+ throw err;
2123
+ }
2124
+ const blockHeight = providerTx?.blockHeight == null ? null : Number(providerTx.blockHeight);
2125
+ // The tip is read before the transaction is stored, so no write is open during that call.
2126
+ const tip = blockHeight == null ? null : await this.client.getLatestBlock();
2127
+ if (providerTx)
2128
+ await this.storeTransaction(tx, providerTx);
2129
+ if (blockHeight == null || !tip)
2130
+ return { txHash, blockHeight: null, tipHeight: null, confirmations: 0 };
2131
+ if (tip.height == null)
2132
+ throw new errors_1.ProviderUnavailableError('Chain tip height unknown');
2133
+ // a tip from a backend that lags the one that found the tx counts the tx block only
2134
+ const tipHeight = Math.max(tip.height, blockHeight);
2135
+ return { txHash, blockHeight, tipHeight, confirmations: tipHeight - blockHeight + 1 };
2136
+ }
2137
+ /** Height of a transaction in a crawled block and the crawler's tip; null when the crawl does not hold it. */
2138
+ async crawledTransactionDepth(tx, txHash) {
2139
+ const crawled = await this.findCrawledTransaction(tx, txHash);
2140
+ return crawled ? { blockHeight: crawled.blockHeight, tipHeight: crawled.tipHeight } : null;
2141
+ }
2142
+ // A stored transaction that counts as on chain: inside the crawled chain with its block stored,
2143
+ // because the crawler removes those rows on a rollback. A row the lazy path stored proves nothing.
2144
+ // spendsCollaterals is true when it landed with failing scripts and spent only its collateral.
2145
+ async findCrawledTransaction(tx, txHash) {
2146
+ const coverage = await this.localCoverage(tx);
2147
+ if (coverage?.tipHeight == null)
2148
+ return null;
2149
+ const stored = await tx.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('slot', 'blockHeight', 'blockHash', 'txSeq').where({ hash: txHash }));
2150
+ if (stored?.blockHeight == null || stored.slot == null || !stored.blockHash)
2151
+ return null;
2152
+ const slot = Number(stored.slot);
2153
+ if (slot < coverage.fromSlot || slot > coverage.lastSlot)
2154
+ return null;
2155
+ const block = await tx.run(SELECT.one.from(CardanoODataService_1.Blocks).columns('hash').where({ hash: stored.blockHash }));
2156
+ if (!block)
2157
+ return null;
2158
+ const inputs = stored.txSeq == null ? [] : await tx.run(SELECT.from(CardanoODataService_1.TransactionInputs).columns('isCollateral', 'isReference').where({ txSeq: stored.txSeq }));
2159
+ // the stored chain keeps only collateral and reference inputs for a failed script phase
2160
+ const spendsCollaterals = inputs.some(i => i.isCollateral) && !inputs.some(i => !i.isCollateral && !i.isReference);
2161
+ // a passing phase with collateral looks like a source that reported no validity
2162
+ const validityKnown = spendsCollaterals || !inputs.some(i => i.isCollateral);
2163
+ const blockHeight = Number(stored.blockHeight);
2164
+ return { slot, blockHeight, blockHash: stored.blockHash, tipHeight: Math.max(coverage.tipHeight, blockHeight), spendsCollaterals, validityKnown };
2165
+ }
2166
+ /** Batch-fetches the missing ones, stores them and returns only those. */
947
2167
  async ensureTransactionsIndexed(tx, txHashes) {
2168
+ const missing = await (0, tx_utils_1.readOutside)(tx, (db) => this.unstoredTransactionHashes(db, txHashes));
2169
+ const fetched = missing.length ? await this.client.getTransactionsBatch(missing) : new Map();
2170
+ await this.storeTransactions(tx, fetched);
2171
+ return fetched;
2172
+ }
2173
+ /** The hashes among the given ones that have no stored transaction. */
2174
+ async unstoredTransactionHashes(tx, txHashes) {
948
2175
  const unique = [...new Set(txHashes)];
949
2176
  if (unique.length === 0)
950
- return new Map();
951
- // DB check — which hashes are already indexed?
2177
+ return [];
952
2178
  const existingRows = await tx.run(SELECT.from(CardanoODataService_1.Transactions).columns('hash').where({ hash: { in: unique } }));
953
2179
  const existingSet = new Set(existingRows.map((r) => r.hash));
954
2180
  const missing = unique.filter(h => !existingSet.has(h));
955
2181
  logger.debug(`ensureTransactionsIndexed: ${unique.length} unique, ${existingSet.size} cached, ${missing.length} to fetch`);
956
- // Batch-fetch missing from backend
957
- let fetched = new Map();
958
- if (missing.length > 0) {
959
- fetched = await this.client.getTransactionsBatch(missing);
960
- // UPSERT all fetched transactions + child entities
961
- for (const [, providerTx] of fetched) {
962
- const txRow = (0, mappers_1.mapTransaction)(providerTx);
963
- 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));
984
- }
985
- }
986
- return fetched;
2182
+ return missing;
987
2183
  }
988
- //-----------------------------------------------------------------------------
989
- // Private Helpers
990
- //-----------------------------------------------------------------------------
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
- */
997
- async _ensureAddresses(tx, bech32List) {
998
- const concurrency = CardanoIndexer.ADDR_CONCURRENCY;
999
- for (let i = 0; i < bech32List.length; i += concurrency) {
1000
- const chunk = bech32List.slice(i, i + concurrency);
1001
- await Promise.all(chunk.map(addr => this.indexAddress(tx, addr)));
2184
+ /** Stores transactions read from a backend, each with its inputs, outputs and metadata. */
2185
+ async storeTransactions(tx, fetched) {
2186
+ for (const [, providerTx] of fetched) {
2187
+ const txRow = (0, mappers_1.mapTransaction)(providerTx);
2188
+ await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRow));
2189
+ await this.writeTransactionChildren(tx, providerTx, txRow.txSeq);
1002
2190
  }
1003
2191
  }
1004
2192
  }