@odatano/core 2.0.0-rc.50 → 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 (151) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +14 -3
  2. package/@cds-models/CardanoBackendService/index.js +1 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +98 -0
  4. package/@cds-models/CardanoIndexerService/index.js +10 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +3 -0
  6. package/@cds-models/CardanoSignService/index.d.ts +13 -0
  7. package/@cds-models/CardanoSignService/index.js +1 -0
  8. package/@cds-models/CardanoTransactionService/index.d.ts +12 -0
  9. package/@cds-models/CardanoTransactionService/index.js +1 -0
  10. package/@cds-models/CardanoWorkerService/index.d.ts +28 -0
  11. package/@cds-models/CardanoWorkerService/index.js +2 -0
  12. package/@cds-models/index.d.ts +13 -3
  13. package/@cds-models/index.js +4 -3
  14. package/@cds-models/odatano/cardano/index.d.ts +14 -0
  15. package/README.md +45 -149
  16. package/db/schema.cds +63 -10
  17. package/db/types.cds +10 -0
  18. package/package.json +7 -44
  19. package/scripts/deploy-schema.mjs +113 -0
  20. package/scripts/migrate-schema.mjs +209 -15
  21. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -4
  22. package/srv/blockchain/backends/blockfrost-backend.js +61 -45
  23. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  24. package/srv/blockchain/backends/call-signal.js +22 -0
  25. package/srv/blockchain/backends/cardano-backend.d.ts +6 -3
  26. package/srv/blockchain/backends/koios-backend.d.ts +9 -6
  27. package/srv/blockchain/backends/koios-backend.js +145 -207
  28. package/srv/blockchain/backends/odatano-backend.d.ts +2 -1
  29. package/srv/blockchain/backends/odatano-backend.js +51 -9
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +1 -2
  31. package/srv/blockchain/backends/ogmios-backend.js +82 -48
  32. package/srv/blockchain/cardano-client.d.ts +15 -5
  33. package/srv/blockchain/cardano-client.js +143 -71
  34. package/srv/blockchain/cardano-indexer.d.ts +27 -16
  35. package/srv/blockchain/cardano-indexer.js +223 -102
  36. package/srv/blockchain/circuit-breaker.d.ts +1 -0
  37. package/srv/blockchain/circuit-breaker.js +6 -0
  38. package/srv/blockchain/crawler/account-snapshots.js +22 -2
  39. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +2 -0
  40. package/srv/blockchain/crawler/asset-decimals-backfill.js +29 -29
  41. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +3 -0
  42. package/srv/blockchain/crawler/asset-registry-backfill.js +4 -0
  43. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  44. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  45. package/srv/blockchain/crawler/certificate-backfill.d.ts +4 -0
  46. package/srv/blockchain/crawler/certificate-backfill.js +15 -3
  47. package/srv/blockchain/crawler/crawler.d.ts +22 -1
  48. package/srv/blockchain/crawler/crawler.js +223 -24
  49. package/srv/blockchain/crawler/credential-backfill.d.ts +2 -0
  50. package/srv/blockchain/crawler/credential-backfill.js +43 -66
  51. package/srv/blockchain/crawler/input-asset-copies.d.ts +4 -4
  52. package/srv/blockchain/crawler/input-asset-copies.js +17 -27
  53. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  54. package/srv/blockchain/crawler/key-pages.js +48 -0
  55. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +6 -0
  56. package/srv/blockchain/crawler/metadata-position-backfill.js +23 -19
  57. package/srv/blockchain/crawler/output-datum-backfill.d.ts +3 -1
  58. package/srv/blockchain/crawler/output-datum-backfill.js +8 -18
  59. package/srv/blockchain/crawler/sync-state.d.ts +5 -1
  60. package/srv/blockchain/crawler/sync-state.js +63 -106
  61. package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
  62. package/srv/blockchain/crawler/transaction-backfill.js +6 -13
  63. package/srv/blockchain/crawler/utxo-set-import.js +2 -2
  64. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  65. package/srv/blockchain/crawler/window-plan.js +59 -0
  66. package/srv/blockchain/ledger-state.d.ts +2 -2
  67. package/srv/blockchain/ledger-state.js +139 -37
  68. package/srv/blockchain/signing/external-signer.js +5 -5
  69. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  70. package/srv/blockchain/signing/failed-recheck.js +135 -0
  71. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  72. package/srv/blockchain/signing/landing-proof.js +224 -0
  73. package/srv/blockchain/signing/signature-verifier.js +10 -13
  74. package/srv/blockchain/signing/submission-finalizer.d.ts +17 -3
  75. package/srv/blockchain/signing/submission-finalizer.js +90 -29
  76. package/srv/blockchain/stored-chain.d.ts +1 -2
  77. package/srv/blockchain/stored-chain.js +36 -15
  78. package/srv/blockchain/transaction-building/buildooor-tx.js +16 -10
  79. package/srv/blockchain/transaction-presence.d.ts +8 -1
  80. package/srv/blockchain/transaction-presence.js +12 -12
  81. package/srv/blockchain/wallet-worker/build-request.d.ts +6 -6
  82. package/srv/blockchain/wallet-worker/build-request.js +35 -365
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +23 -2
  84. package/srv/blockchain/wallet-worker/confirmation-tracker.js +140 -23
  85. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  86. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  87. package/srv/blockchain/wallet-worker/job-store.d.ts +28 -2
  88. package/srv/blockchain/wallet-worker/job-store.js +107 -80
  89. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +21 -2
  90. package/srv/blockchain/wallet-worker/wallet-worker.js +241 -57
  91. package/srv/cardano-agent-service.cds +1 -1
  92. package/srv/cardano-agent-service.js +8 -0
  93. package/srv/cardano-backend-service.cds +4 -1
  94. package/srv/cardano-backend-service.js +26 -9
  95. package/srv/cardano-indexer-service.cds +448 -387
  96. package/srv/cardano-indexer-service.js +226 -281
  97. package/srv/cardano-service.cds +7 -5
  98. package/srv/cardano-service.js +404 -69
  99. package/srv/cardano-sign-service.cds +11 -1
  100. package/srv/cardano-sign-service.js +161 -108
  101. package/srv/cardano-tx-service.cds +15 -4
  102. package/srv/cardano-tx-service.js +105 -604
  103. package/srv/cardano-worker-service.cds +25 -2
  104. package/srv/cardano-worker-service.js +56 -4
  105. package/srv/config.d.ts +4 -0
  106. package/srv/config.js +10 -0
  107. package/srv/server.js +5 -7
  108. package/srv/utils/agent-access.d.ts +4 -2
  109. package/srv/utils/agent-access.js +26 -7
  110. package/srv/utils/agent-grants.d.ts +1 -1
  111. package/srv/utils/agent-grants.js +7 -8
  112. package/srv/utils/agent-token-auth.js +45 -5
  113. package/srv/utils/build-request.d.ts +52 -0
  114. package/srv/utils/build-request.js +487 -0
  115. package/srv/utils/collections.d.ts +1 -0
  116. package/srv/utils/collections.js +11 -0
  117. package/srv/utils/const.d.ts +10 -2
  118. package/srv/utils/const.js +13 -6
  119. package/srv/utils/crypto.js +5 -4
  120. package/srv/utils/db-indexes.d.ts +5 -1
  121. package/srv/utils/db-indexes.js +79 -14
  122. package/srv/utils/db-kind.d.ts +23 -0
  123. package/srv/utils/db-kind.js +42 -0
  124. package/srv/utils/detached-run.d.ts +41 -0
  125. package/srv/utils/detached-run.js +101 -0
  126. package/srv/utils/epoch-slots.d.ts +1 -0
  127. package/srv/utils/epoch-slots.js +7 -0
  128. package/srv/utils/error-codes.d.ts +4 -0
  129. package/srv/utils/error-codes.js +4 -0
  130. package/srv/utils/errors.d.ts +10 -1
  131. package/srv/utils/errors.js +51 -9
  132. package/srv/utils/lease.d.ts +20 -0
  133. package/srv/utils/lease.js +62 -0
  134. package/srv/utils/mappers.d.ts +9 -0
  135. package/srv/utils/mappers.js +57 -67
  136. package/srv/utils/navigation.d.ts +17 -0
  137. package/srv/utils/navigation.js +52 -0
  138. package/srv/utils/network-context.d.ts +0 -1
  139. package/srv/utils/network-context.js +8 -3
  140. package/srv/utils/pg-inline-json.js +3 -3
  141. package/srv/utils/pg-order-nulls.js +3 -3
  142. package/srv/utils/resolution.d.ts +13 -0
  143. package/srv/utils/resolution.js +47 -0
  144. package/srv/utils/row-values.d.ts +7 -0
  145. package/srv/utils/row-values.js +27 -0
  146. package/srv/utils/tx-build-helper.d.ts +15 -0
  147. package/srv/utils/tx-build-helper.js +28 -13
  148. package/srv/utils/types.d.ts +35 -43
  149. package/srv/utils/types.js +1 -17
  150. package/srv/utils/validators.d.ts +2 -2
  151. package/srv/utils/validators.js +14 -25
@@ -4,6 +4,8 @@ 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");
@@ -19,12 +21,30 @@ const tx_utils_1 = require("../utils/tx-utils");
19
21
  const transaction_rows_1 = require("./transaction-rows");
20
22
  const ledger_state_1 = require("./ledger-state");
21
23
  const sync_state_1 = require("./crawler/sync-state");
24
+ const window_plan_1 = require("./crawler/window-plan");
22
25
  const asset_decimals_1 = require("./asset-decimals");
26
+ const cip68_1 = require("../cbor/cip68");
23
27
  const pool_metadata_1 = require("./pool-metadata");
24
28
  const epoch_slots_1 = require("../utils/epoch-slots");
25
29
  const const_1 = require("../utils/const");
26
30
  const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
27
31
  const logger = cds_1.default.log('CardanoIndexer');
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
+ }
28
48
  /** Newest first; the tx hash breaks ties inside one block. */
29
49
  function sortAddressTransactions(rows) {
30
50
  return rows.sort((a, b) => Number(b.blockTime ?? 0) - Number(a.blockTime ?? 0) || String(b.tx_hash).localeCompare(String(a.tx_hash)));
@@ -68,8 +88,8 @@ class CardanoIndexer {
68
88
  // A row is UPSERTed again until a block transaction that wrote it has committed.
69
89
  crawlEpochCache = new Map();
70
90
  crawlEpochCurrent = null;
71
- /** Epoch rows known to be committed; a refresh creates a new row object and is written again. */
72
- crawlEpochWritten = new WeakSet();
91
+ /** Committed epoch rows and the final flag they were written with; a refresh creates a new row object. */
92
+ crawlEpochWritten = new WeakMap();
73
93
  /** Memo updates of the running block transaction, applied only after its commit. */
74
94
  pendingCommit = [];
75
95
  crawlEpochPrevious = null;
@@ -126,7 +146,7 @@ class CardanoIndexer {
126
146
  // ledger is true when the crawled UTxO set is active.
127
147
  async localCoverage(tx) {
128
148
  const cursor = await (0, sync_state_1.readCursor)(tx);
129
- if (!cursor || cursor.syncStatus !== 'synced' || cursor.startSlot == null || !(0, sync_state_1.isCrawlerLeaseActive)(cursor))
149
+ if (!cursor || cursor.syncStatus !== 'synced' || cursor.nodeBehindSince != null || cursor.startSlot == null || !(0, sync_state_1.isCrawlerLeaseActive)(cursor))
130
150
  return null;
131
151
  return { fromSlot: cursor.startSlot, lastSlot: cursor.lastSlot, tipHeight: cursor.tipHeight, ledger: cursor.utxoSet.status === 'active' };
132
152
  }
@@ -190,14 +210,13 @@ class CardanoIndexer {
190
210
  catch { /* unparseable payload: leave empty */ }
191
211
  }
192
212
  }
193
- const policyId = unit.slice(0, 56);
194
- const assetNameHex = unit.slice(56);
213
+ const slice = (0, mappers_1.assetSlice)(unit, supply);
195
214
  return {
196
215
  unit,
197
- policyId,
198
- assetNameHex,
199
- assetName: assetNameHex ? (0, mappers_1.decodeAssetName)(assetNameHex) : null,
200
- fingerprint: (0, mappers_1.computeCip14Fingerprint)(policyId, assetNameHex),
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)),
201
220
  totalSupply: supply.toString(),
202
221
  mintOrBurnCount: ordered.length,
203
222
  initialMintTxHash: first?.txHash ?? null,
@@ -293,12 +312,13 @@ class CardanoIndexer {
293
312
  const complete = known.firstSeenSlot != null;
294
313
  // Candidate transactions by slot; a transaction can touch the address with several outputs.
295
314
  const scan = Math.min(limit * 20, 2000);
296
- const [created, spent] = await Promise.all([
297
- tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('txHash', 'createdSlot')
298
- .where({ address: addr, createdSlot: { '>=': 0 } }).orderBy('createdSlot desc').limit(scan)),
299
- tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('spentTxHash', 'spentSlot')
300
- .where({ address: addr, spentSlot: { '>=': 0 } }).orderBy('spentSlot desc').limit(scan)),
301
- ]);
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)]);
302
322
  const slotOf = new Map();
303
323
  for (const r of created ?? [])
304
324
  slotOf.set(r.txHash, Number(r.createdSlot));
@@ -440,6 +460,11 @@ class CardanoIndexer {
440
460
  await this.refreshCrawlEpoch(previousEpoch, true, true);
441
461
  this.crawlEpochPrevious = previousEpoch;
442
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
+ }
443
468
  else {
444
469
  for (const [cachedEpoch, entry] of this.crawlEpochCache) {
445
470
  if (cachedEpoch !== epochNumber && !entry.finalized) {
@@ -456,6 +481,16 @@ class CardanoIndexer {
456
481
  }
457
482
  }
458
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
+ }
459
494
  async refreshCrawlEpoch(epochNumber, force, finalized) {
460
495
  const now = Date.now();
461
496
  const existing = this.crawlEpochCache.get(epochNumber);
@@ -467,9 +502,10 @@ class CardanoIndexer {
467
502
  try {
468
503
  const provided = (0, mappers_1.mapEpoch)(await this.client.getEpoch(epochNumber));
469
504
  this.crawlEpochCache.set(epochNumber, {
470
- row: crawled ? { ...provided, ...crawled } : provided,
505
+ row: crawled ? { ...provided, ...crawled.totals } : provided,
471
506
  nextRefreshAt: now + CardanoIndexer.CRAWL_EPOCH_REFRESH_MS,
472
507
  finalized,
508
+ crawlComplete: crawled ? crawled.complete : null,
473
509
  });
474
510
  }
475
511
  catch {
@@ -477,32 +513,38 @@ class CardanoIndexer {
477
513
  // results soon rather than suppressing enrichment for the rest of the five-day epoch.
478
514
  const base = existing?.row ?? (crawled ? this.bareEpochRow(epochNumber) : undefined);
479
515
  this.crawlEpochCache.set(epochNumber, {
480
- row: base && crawled ? { ...base, ...crawled } : base,
516
+ row: base && crawled ? { ...base, ...crawled.totals } : base,
481
517
  nextRefreshAt: now + CardanoIndexer.CRAWL_EPOCH_RETRY_MS,
482
518
  finalized: false,
519
+ crawlComplete: crawled ? crawled.complete : (existing?.crawlComplete ?? null),
483
520
  });
484
521
  }
485
522
  }
486
- // Block, tx and fee totals from crawled blocks. Null unless the crawl covers the whole epoch.
487
- // Output and active stake still come from the backend.
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.
488
526
  async crawledEpochTotals(epochNumber) {
489
527
  try {
490
528
  const cursor = await (0, sync_state_1.readCursor)(cds_1.default.db);
491
529
  if (cursor?.startSlot == null || cursor.startSlot >= (0, epoch_slots_1.epochStartSlot)(this.client.network, epochNumber))
492
530
  return null;
531
+ const complete = cursor.lastSlot >= (0, epoch_slots_1.epochStartSlot)(this.client.network, epochNumber + 1);
493
532
  const row = await cds_1.default.db.run(SELECT.one.from(CardanoODataService_1.Blocks)
494
533
  .columns('count(*) as blockCount', 'sum(txCount) as txCount', 'sum(fees) as fees', 'min(slot) as firstSlot', 'max(slot) as lastSlot')
495
534
  .where({ epochNumber }));
496
535
  if (!row || Number(row.blockCount ?? 0) === 0)
497
- return null;
536
+ return { totals: {}, complete };
498
537
  // The slot gives the block time exactly; a time aggregate comes back in the database's own form.
499
538
  const timeOf = (slot) => slot == null ? null : (0, epoch_slots_1.slotToPosixSeconds)(this.client.network, Number(slot));
500
539
  return {
501
- blockCount: Number(row.blockCount),
502
- txCount: Number(row.txCount ?? 0),
503
- fees: lovelaceSum(row.fees),
504
- firstBlockTime: timeOf(row.firstSlot),
505
- lastBlockTime: timeOf(row.lastSlot),
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,
506
548
  };
507
549
  }
508
550
  catch (err) {
@@ -524,7 +566,7 @@ class CardanoIndexer {
524
566
  }
525
567
  // Writes block count, transaction count, fees and first and last block time of every epoch the
526
568
  // crawl covers in full, from the stored blocks. An epoch without a row gets one. No backend.
527
- async backfillEpochs(onProgress) {
569
+ async backfillEpochs(onProgress, shouldStop) {
528
570
  const progress = { atEpoch: 0, toEpoch: 0, updated: 0, created: 0 };
529
571
  const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
530
572
  if (cursor?.startSlot == null)
@@ -532,19 +574,26 @@ class CardanoIndexer {
532
574
  const network = this.client.network;
533
575
  progress.toEpoch = (0, epoch_slots_1.epochOfSlot)(network, cursor.lastSlot);
534
576
  for (let epoch = (0, epoch_slots_1.epochOfSlot)(network, cursor.startSlot); epoch <= progress.toEpoch; epoch++) {
535
- const totals = await this.crawledEpochTotals(epoch);
536
- if (totals) {
537
- const created = await cds_1.default.tx(async (tx) => {
538
- const stored = await tx.run(SELECT.one.from(CardanoODataService_1.Epoch).columns('epoch').where({ 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';
539
588
  if (stored)
540
589
  await tx.run(UPDATE.entity(CardanoODataService_1.Epoch).set(totals).where({ epoch }));
541
590
  else
542
591
  await tx.run(INSERT.into(CardanoODataService_1.Epoch).entries({ ...this.bareEpochRow(epoch), ...totals }));
543
- return !stored;
592
+ return stored ? 'updated' : 'created';
544
593
  });
545
- if (created)
594
+ if (outcome === 'created')
546
595
  progress.created++;
547
- else
596
+ else if (outcome === 'updated')
548
597
  progress.updated++;
549
598
  }
550
599
  progress.atEpoch = epoch;
@@ -831,6 +880,11 @@ class CardanoIndexer {
831
880
  async fetchAddressUtxos(addr) {
832
881
  return this.client.getAddressUtxos(addr);
833
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
+ }
834
888
  /** Stores the UTxOs of an address. Writes no parent Addresses row. */
835
889
  async storeAddressUtxos(tx, addr, utxos) {
836
890
  logger.debug(`indexAddressUtxos: provider returned ${utxos.length} utxos for ${addr}`);
@@ -1034,10 +1088,42 @@ class CardanoIndexer {
1034
1088
  return { block };
1035
1089
  }
1036
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 });
1105
+ }
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
+ }
1037
1123
  /** Stores a block and, when it was read, its epoch. */
1038
1124
  async storeBlock(tx, fetched) {
1039
1125
  if (fetched.epoch)
1040
- await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([fetched.epoch]));
1126
+ await this.storeEpoch(tx, fetched.epoch);
1041
1127
  const blockEntity = (0, mappers_1.mapBlock)(fetched.block, fetched.epoch);
1042
1128
  await tx.run(UPSERT.into(CardanoODataService_1.Block).entries(blockEntity));
1043
1129
  return blockEntity;
@@ -1047,20 +1133,12 @@ class CardanoIndexer {
1047
1133
  async indexBlockFull(tx, blockData, txs) {
1048
1134
  // Memo updates of a rolled-back attempt must not survive into this one.
1049
1135
  this.pendingCommit = [];
1050
- // Epoch from the prefetched memo; if the caller skipped prefetchCrawlEpoch, resolve now
1051
- // (memoized) and accept the in-tx fetch.
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.
1052
1138
  let epoch;
1053
1139
  if (blockData.epoch != null) {
1054
- await this.prefetchCrawlEpoch(blockData.epoch);
1055
1140
  epoch = this.crawlEpochCache.get(blockData.epoch)?.row;
1056
- const epochRows = [...this.crawlEpochCache.values()]
1057
- .map((entry) => entry.row)
1058
- .filter((row) => row !== undefined && !this.crawlEpochWritten.has(row));
1059
- if (epochRows.length) {
1060
- await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries(epochRows));
1061
- this.pendingCommit.push(() => { for (const row of epochRows)
1062
- this.crawlEpochWritten.add(row); });
1063
- }
1141
+ await this.writeCrawlEpochs(tx, blockData.slot ?? 0);
1064
1142
  }
1065
1143
  // Ledger state (crawler.utxoSet): only blocks AFTER the anchor the imported set describes.
1066
1144
  // Decided up front so input resolution and the ledger apply share one read of the set.
@@ -1091,7 +1169,10 @@ class CardanoIndexer {
1091
1169
  await this.referenceStoredOutputs(tx, txs);
1092
1170
  this.applyCollateralFees(blockData, txs);
1093
1171
  this.applyDeposits(txs);
1094
- await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
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 }));
1095
1176
  await this.removeStaleTxSeqs(tx, txs);
1096
1177
  // One bulk UPSERT per table. NUL safety for PostgreSQL is enforced by the db-level hook in
1097
1178
  // srv/utils/db-sanitize.ts, not per call site.
@@ -1159,7 +1240,7 @@ class CardanoIndexer {
1159
1240
  // Catalogue last; collecting the units is skipped entirely when the catalogue is off.
1160
1241
  const newAssets = this.crawlAssetCatalogue === 'off'
1161
1242
  ? 0
1162
- : await this.ensureAssetRows(tx, this.collectBlockUnits(txs, assetHistoryRows));
1243
+ : await this.ensureAssetRows(tx, this.collectBlockUnits(txs, assetHistoryRows), blockData.slot);
1163
1244
  // A reference NFT moved or minted in this block carries the current CIP-68 metadata of its token.
1164
1245
  await (0, asset_decimals_1.applyReferenceDatums)(tx, txs);
1165
1246
  logger.debug(`indexBlockFull: block ${blockData.hash}: ${txs.length} txs, ${outputRows.length} outputs, ` +
@@ -1182,20 +1263,31 @@ class CardanoIndexer {
1182
1263
  await tx.run(DELETE.from(CardanoODataService_1.Blocks).where({ hash: { in: stale } }));
1183
1264
  logger.info(`indexBlockFull: removed ${stale.length} superseded block row(s) at height ${blockData.height}`);
1184
1265
  }
1185
- // Drops transactions of another fork that hold one of this block's txSeq keys.
1186
- // Their input and output rows would mix with ours.
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.
1187
1269
  async removeStaleTxSeqs(tx, txs) {
1188
1270
  if (!txs.length)
1189
1271
  return;
1190
- const seqs = txs.map(t => (0, mappers_1.txSeqOf)(t.slot, t.index));
1191
- const rows = await tx.run(SELECT.from(CardanoODataService_1.Transactions).columns('hash', 'txSeq')
1192
- .where({ txSeq: { between: Math.min(...seqs), and: Math.max(...seqs) } }));
1193
- const ours = new Set(txs.map(t => t.hash));
1194
- const stale = (rows ?? []).filter(r => !ours.has(r.hash));
1195
- if (!stale.length)
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)
1196
1288
  return;
1197
- await (0, transaction_rows_1.deleteTransactionRows)(tx, stale);
1198
- logger.info(`indexBlockFull: removed ${stale.length} transaction(s) of another fork at slot ${txs[0].slot}`);
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`);
1199
1291
  }
1200
1292
  // Warns once when certificates are on but the source does not report them.
1201
1293
  // An empty array means none and is no warning.
@@ -1431,7 +1523,7 @@ class CardanoIndexer {
1431
1523
  }
1432
1524
  // Adds a bare Assets row for every new unit, without provider calls. Its epoch-zero key never hits
1433
1525
  // an enriched row. The existence check reads the DB entity, because the service view hides such rows.
1434
- async ensureAssetRows(tx, units) {
1526
+ async ensureAssetRows(tx, units, slot) {
1435
1527
  if (this.crawlAssetCatalogue === 'off' || !units.size)
1436
1528
  return 0;
1437
1529
  const unknown = [...units].filter(u => !this.assetMemo.has(u));
@@ -1450,7 +1542,8 @@ class CardanoIndexer {
1450
1542
  }
1451
1543
  if (!missing.length)
1452
1544
  return 0;
1453
- const rows = missing.map(mappers_1.mapBareAsset).filter((r) => r !== null);
1545
+ const rows = missing.map(mappers_1.mapBareAsset).filter((r) => r !== null)
1546
+ .map((row) => ({ ...row, firstSeenSlot: slot ?? null }));
1454
1547
  for (const row of rows)
1455
1548
  row.decimals = await (0, asset_decimals_1.cip68Decimals)(tx, row.unit);
1456
1549
  // Chunked like the lookup: a mint-storm block can carry thousands of fresh units.
@@ -1482,12 +1575,39 @@ class CardanoIndexer {
1482
1575
  }
1483
1576
  this.assetMemo.add(unit);
1484
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
+ }
1485
1605
  // Snapshots all pools and DReps of an epoch in its own transaction after the block commit.
1486
1606
  // Ogmios reads the ledger at the given block, Koios the current state. Source null means skipped.
1487
- async snapshotEpoch(epoch, at) {
1607
+ async snapshotEpoch(epoch, at, shouldStop = () => false) {
1488
1608
  const epochState = at.hash ? this.client.getEpochStateBackend() : null;
1489
1609
  if (epochState && at.hash)
1490
- return this.snapshotEpochFromLedger(epochState, epoch, { ...at, hash: at.hash });
1610
+ return this.snapshotEpochFromLedger(epochState, epoch, { ...at, hash: at.hash }, shouldStop);
1491
1611
  const backend = this.client.getEnumeratingBackend();
1492
1612
  if (!backend) {
1493
1613
  logger.warn(`epoch ${epoch} snapshot skipped: no backend can read pools/DReps (Ogmios or Koios required)`);
@@ -1507,6 +1627,8 @@ class CardanoIndexer {
1507
1627
  liveStake: poolData.reduce((sum, p) => sum + BigInt(p.liveStake || '0'), 0n).toString(),
1508
1628
  poolCount: poolData.length, drepCount: drepData.length,
1509
1629
  };
1630
+ if (shouldStop())
1631
+ throw new Error(`epoch ${epoch} snapshot stopped before its write`);
1510
1632
  await cds_1.default.tx(async (tx) => {
1511
1633
  // Chunked so a mainnet-sized set cannot exceed a driver's bind-variable cap.
1512
1634
  for (const rows of (0, collections_1.chunk)(poolSnapshots, collections_1.IN_CHUNK))
@@ -1524,7 +1646,7 @@ class CardanoIndexer {
1524
1646
  }
1525
1647
  // Live Pools and Dreps rows are not refreshed, because the ledger state may be hours old.
1526
1648
  // blocksMinted is set only when the crawl covers the chain since Shelley.
1527
- async snapshotEpochFromLedger(backend, epoch, at) {
1649
+ async snapshotEpochFromLedger(backend, epoch, at, shouldStop) {
1528
1650
  const state = await backend.epochStateAt({ slot: at.slot, hash: at.hash });
1529
1651
  if (state.epoch !== epoch) {
1530
1652
  logger.warn(`epoch snapshot: ledger at slot ${at.slot} reports epoch ${state.epoch}, crawler dated it ${epoch}, stored as ${epoch}`);
@@ -1556,6 +1678,8 @@ class CardanoIndexer {
1556
1678
  drepAbstainStake: state.drepAbstainStake,
1557
1679
  drepNoConfidenceStake: state.drepNoConfidenceStake,
1558
1680
  };
1681
+ if (shouldStop())
1682
+ throw new Error(`epoch ${epoch} snapshot stopped before its write`);
1559
1683
  await cds_1.default.tx(async (tx) => {
1560
1684
  for (const rows of (0, collections_1.chunk)(poolSnapshots, collections_1.IN_CHUNK))
1561
1685
  await tx.run(UPSERT.into(CardanoODataService_1.PoolEpochSnapshots).entries(rows));
@@ -1617,24 +1741,33 @@ class CardanoIndexer {
1617
1741
  return (0, mappers_1.mapEpoch)(await this.client.getEpoch(epochNumber));
1618
1742
  }
1619
1743
  async storeEpoch(tx, epochEntity) {
1620
- await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries([epochEntity]));
1621
- return 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 };
1622
1756
  }
1623
- /** Index an account by stake address, plus its addresses when it has any. */
1757
+ /** Index an account by stake address. Its addresses are read on their own. */
1624
1758
  async indexAccount(tx, stakeAddress) {
1625
1759
  return this.storeAccount(tx, await this.fetchAccount(tx, stakeAddress));
1626
1760
  }
1627
- /** An account and the addresses it controls, read but not stored. */
1761
+ /** An account, read but not stored. */
1628
1762
  async fetchAccount(tx, stakeAddress) {
1629
- const account = await this.resolveAccount(tx, stakeAddress);
1630
- return { account, addresses: await this.fetchAddresses(tx, account.addresses) };
1763
+ return { account: await this.resolveAccount(tx, stakeAddress) };
1631
1764
  }
1632
- /** Stores what fetchAccount read. */
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.
1633
1767
  async storeAccount(tx, fetched) {
1634
- const accountEntity = (0, mappers_1.mapAccount)(fetched.account, this.client.max_age_ms);
1635
- await tx.run(UPSERT.into(CardanoODataService_1.Accounts).entries(accountEntity));
1636
- for (const address of fetched.addresses)
1637
- await this.storeAddress(tx, address);
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) }));
1638
1771
  return accountEntity;
1639
1772
  }
1640
1773
  /** Account from the backend with the crawled overlays (controlled amount, withdrawals). */
@@ -1649,17 +1782,14 @@ class CardanoIndexer {
1649
1782
  ledger,
1650
1783
  controlledAmount: row?.controlledAmount,
1651
1784
  held: ledger ? await this.ledgerAccountUtxos(db, stakeAddress) : { addresses: [], utxos: [] },
1652
- withdrawalsSum: accountInfo.withdrawalsSum === '0' ? await this.localWithdrawalsSum(db, stakeAddress) : null,
1785
+ withdrawalsSum: accountInfo.withdrawalsSum == null || accountInfo.withdrawalsSum === '0' ? await this.localWithdrawalsSum(db, stakeAddress) : null,
1653
1786
  };
1654
1787
  });
1655
1788
  // controlled amount = UTxOs under the stake key (crawled set, when current) + reward balance;
1656
1789
  // the addresses come from the set too (the node has no stake-key -> address index)
1657
1790
  if (local.ledger) {
1658
1791
  accountInfo.controlledAmount = (BigInt(lovelaceSum(local.controlledAmount)) + BigInt(accountInfo.withdrawableAmount || '0')).toString();
1659
- const byAddress = new Map(local.held.addresses.map(a => [a, []]));
1660
- for (const u of await this.unspentAtNode(local.held.utxos))
1661
- byAddress.get(u.address)?.push(u);
1662
- accountInfo.addresses = local.held.addresses.map(a => addressFromUtxos(a, byAddress.get(a)));
1792
+ accountInfo.addresses = local.held.addresses;
1663
1793
  }
1664
1794
  if (local.withdrawalsSum != null)
1665
1795
  accountInfo.withdrawalsSum = local.withdrawalsSum;
@@ -1695,7 +1825,7 @@ class CardanoIndexer {
1695
1825
  const local = await (0, tx_utils_1.readOutside)(tx, async (db) => {
1696
1826
  const blocks = await this.localPoolBlocks(db, poolId);
1697
1827
  // The node's live pool view has no active stake; the epoch snapshot of the current epoch does.
1698
- return backend.activeStake === '0' ? { ...blocks, ...(await this.snapshotActiveStake(db, poolId)) } : blocks;
1828
+ return backend.activeStake == null || backend.activeStake === '0' ? { ...blocks, ...(await this.snapshotActiveStake(db, poolId)) } : blocks;
1699
1829
  });
1700
1830
  const poolInfo = { ...backend, ...local };
1701
1831
  Object.assign(poolInfo, await this.poolMetadataOf(poolInfo));
@@ -1977,13 +2107,6 @@ class CardanoIndexer {
1977
2107
  //-----------------------------------------------------------------------------
1978
2108
  // Batch Methods (N+1 Optimization)
1979
2109
  //-----------------------------------------------------------------------------
1980
- /** Max addresses to index concurrently (avoid overloading backends) */
1981
- static ADDR_CONCURRENCY = 5;
1982
- /** Block position of a transaction already in the local index (crawled or cached), or null. */
1983
- async findIndexedTransaction(tx, txHash) {
1984
- const row = await tx.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('slot', 'blockHeight', 'blockHash').where({ hash: txHash }));
1985
- return row ?? null;
1986
- }
1987
2110
  // Confirmations including the tx's own block, 0 while not on chain. A stored row counts only inside
1988
2111
  // the crawled chain, because the crawler removes those rows on a rollback.
1989
2112
  async resolveTransactionConfirmations(tx, txHash) {
@@ -2013,10 +2136,17 @@ class CardanoIndexer {
2013
2136
  }
2014
2137
  /** Height of a transaction in a crawled block and the crawler's tip; null when the crawl does not hold it. */
2015
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) {
2016
2146
  const coverage = await this.localCoverage(tx);
2017
2147
  if (coverage?.tipHeight == null)
2018
2148
  return null;
2019
- const stored = await this.findIndexedTransaction(tx, txHash);
2149
+ const stored = await tx.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('slot', 'blockHeight', 'blockHash', 'txSeq').where({ hash: txHash }));
2020
2150
  if (stored?.blockHeight == null || stored.slot == null || !stored.blockHash)
2021
2151
  return null;
2022
2152
  const slot = Number(stored.slot);
@@ -2025,8 +2155,13 @@ class CardanoIndexer {
2025
2155
  const block = await tx.run(SELECT.one.from(CardanoODataService_1.Blocks).columns('hash').where({ hash: stored.blockHash }));
2026
2156
  if (!block)
2027
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);
2028
2163
  const blockHeight = Number(stored.blockHeight);
2029
- return { blockHeight, tipHeight: Math.max(coverage.tipHeight, blockHeight) };
2164
+ return { slot, blockHeight, blockHash: stored.blockHash, tipHeight: Math.max(coverage.tipHeight, blockHeight), spendsCollaterals, validityKnown };
2030
2165
  }
2031
2166
  /** Batch-fetches the missing ones, stores them and returns only those. */
2032
2167
  async ensureTransactionsIndexed(tx, txHashes) {
@@ -2054,20 +2189,6 @@ class CardanoIndexer {
2054
2189
  await this.writeTransactionChildren(tx, providerTx, txRow.txSeq);
2055
2190
  }
2056
2191
  }
2057
- //-----------------------------------------------------------------------------
2058
- // Private Helpers
2059
- //-----------------------------------------------------------------------------
2060
- // Uses the address data the account carries, so no request per address.
2061
- // Only an entry without UTxOs is fetched.
2062
- async fetchAddresses(tx, accountAddresses) {
2063
- const fetched = [];
2064
- const concurrency = CardanoIndexer.ADDR_CONCURRENCY;
2065
- for (let i = 0; i < accountAddresses.length; i += concurrency) {
2066
- const chunk = accountAddresses.slice(i, i + concurrency);
2067
- fetched.push(...await Promise.all(chunk.map(a => this.fetchAddress(tx, a.address, Array.isArray(a.utxos) ? a : undefined))));
2068
- }
2069
- return fetched;
2070
- }
2071
2192
  }
2072
2193
  exports.CardanoIndexer = CardanoIndexer;
2073
2194
  //# sourceMappingURL=cardano-indexer.js.map
@@ -15,6 +15,7 @@ export declare class CircuitBreakerManager {
15
15
  shouldAttempt(backendName: string): boolean;
16
16
  /** Record a successful call to a backend. */
17
17
  recordSuccess(backendName: string): void;
18
+ recordVerdict(backendName: string): void;
18
19
  /** Record a failed call to a backend. */
19
20
  recordFailure(backendName: string): void;
20
21
  /** Get the current state of a backend's circuit. */
@@ -66,6 +66,12 @@ class CircuitBreakerManager {
66
66
  entry.failures = 0;
67
67
  }
68
68
  }
69
+ // A verdict about the request (404, 400) shows the backend is up. It counts toward closing a
70
+ // half-open circuit, but in the closed state it does not wipe the count of real failures.
71
+ recordVerdict(backendName) {
72
+ if (this.circuits.get(backendName)?.state === 'half-open')
73
+ this.recordSuccess(backendName);
74
+ }
69
75
  /** Record a failed call to a backend. */
70
76
  recordFailure(backendName) {
71
77
  let entry = this.circuits.get(backendName);