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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,10 +13,19 @@ const CardanoSignService_1 = require("#cds-models/CardanoSignService");
13
13
  const cardano_1 = require("#cds-models/odatano/cardano");
14
14
  const mappers_1 = require("../utils/mappers");
15
15
  const collections_1 = require("../utils/collections");
16
+ const transaction_rows_1 = require("./transaction-rows");
16
17
  const ledger_state_1 = require("./ledger-state");
17
18
  const sync_state_1 = require("./crawler/sync-state");
19
+ const epoch_slots_1 = require("../utils/epoch-slots");
20
+ const const_1 = require("../utils/const");
18
21
  const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
19
22
  const logger = cds_1.default.log('CardanoIndexer');
23
+ /** Lovelace aggregate from the DB (string, number or null) as an integer string. */
24
+ function lovelaceSum(value) {
25
+ if (value === null || value === undefined || value === '')
26
+ return '0';
27
+ return typeof value === 'number' ? BigInt(Math.trunc(value)).toString() : String(value).split('.')[0];
28
+ }
20
29
  /**
21
30
  * Indexes Cardano data into the OData entities: fetches via CardanoClient, maps provider data
22
31
  * to entity rows and UPSERTs them inside the caller's CAP transaction.
@@ -76,6 +85,37 @@ class CardanoIndexer {
76
85
  if (coverage.assetCatalogue !== 'enrich')
77
86
  this.stopAssetEnrichment();
78
87
  }
88
+ /**
89
+ * What the crawled data answers authoritatively: only while a live crawler is at the tip.
90
+ * Every block after `fromSlot` is held; `ledger` = the crawled UTxO set is active.
91
+ */
92
+ async localCoverage(tx) {
93
+ const cursor = await (0, sync_state_1.readCursor)(tx);
94
+ if (!cursor || cursor.syncStatus !== 'synced' || cursor.startSlot == null || !(0, sync_state_1.isCrawlerLeaseActive)(cursor))
95
+ return null;
96
+ return { fromSlot: cursor.startSlot, lastSlot: cursor.lastSlot, ledger: cursor.utxoSet.status === 'active' };
97
+ }
98
+ /**
99
+ * Block counts of a pool from crawled blocks (`slotLeader` = pool id): the current epoch when the
100
+ * crawl covers it from its first slot, the lifetime total when it covers the chain since Shelley.
101
+ */
102
+ async localPoolBlocks(tx, poolId) {
103
+ const coverage = await this.localCoverage(tx);
104
+ if (!coverage)
105
+ return {};
106
+ const network = this.client.network;
107
+ const countSince = async (fromSlot) => {
108
+ const row = await tx.run(SELECT.one.from(CardanoODataService_1.Blocks).columns('count(*) as n').where({ slotLeader: poolId, slot: { '>=': fromSlot } }));
109
+ return Number(row?.n ?? 0);
110
+ };
111
+ const counts = {};
112
+ const epochStart = (0, epoch_slots_1.epochStartSlot)(network, (0, epoch_slots_1.epochOfSlot)(network, coverage.lastSlot));
113
+ if (coverage.fromSlot < epochStart)
114
+ counts.blocksEpoch = await countSince(epochStart);
115
+ if (coverage.fromSlot <= const_1.EPOCH_CONFIG_BY_NETWORK[network].shelleyStartSlot)
116
+ counts.blocksMinted = await countSince(0);
117
+ return counts;
118
+ }
79
119
  /** The anchor the imported UTxO set describes (null = ledger mode inactive). */
80
120
  setUtxoAnchor(anchor) {
81
121
  this.utxoAnchor = anchor;
@@ -179,24 +219,65 @@ class CardanoIndexer {
179
219
  return;
180
220
  if (!force && existing && now < existing.nextRefreshAt)
181
221
  return;
222
+ const crawled = await this.crawledEpochTotals(epochNumber);
182
223
  try {
183
- const row = (0, mappers_1.mapEpoch)(await this.client.getEpoch(epochNumber));
224
+ const provided = (0, mappers_1.mapEpoch)(await this.client.getEpoch(epochNumber));
184
225
  this.crawlEpochCache.set(epochNumber, {
185
- row,
226
+ row: crawled ? { ...provided, ...crawled } : provided,
186
227
  nextRefreshAt: now + CardanoIndexer.CRAWL_EPOCH_REFRESH_MS,
187
228
  finalized,
188
229
  });
189
230
  }
190
231
  catch {
191
- // Keep the last good snapshot, but retry transient/negative results soon rather
192
- // than suppressing enrichment for the rest of the five-day epoch.
232
+ // Keep the last good snapshot (or the crawled totals alone), but retry transient/negative
233
+ // results soon rather than suppressing enrichment for the rest of the five-day epoch.
234
+ const base = existing?.row ?? (crawled ? this.bareEpochRow(epochNumber) : undefined);
193
235
  this.crawlEpochCache.set(epochNumber, {
194
- row: existing?.row,
236
+ row: base && crawled ? { ...base, ...crawled } : base,
195
237
  nextRefreshAt: now + CardanoIndexer.CRAWL_EPOCH_RETRY_MS,
196
238
  finalized: false,
197
239
  });
198
240
  }
199
241
  }
242
+ /**
243
+ * Block, transaction and fee totals of an epoch summed over the crawled blocks, when the crawl
244
+ * covers the epoch from its first slot; null otherwise. Output and active stake stay with the backend.
245
+ */
246
+ async crawledEpochTotals(epochNumber) {
247
+ try {
248
+ const cursor = await (0, sync_state_1.readCursor)(cds_1.default.db);
249
+ if (cursor?.startSlot == null || cursor.startSlot >= (0, epoch_slots_1.epochStartSlot)(this.client.network, epochNumber))
250
+ return null;
251
+ const row = await cds_1.default.db.run(SELECT.one.from(CardanoODataService_1.Blocks)
252
+ .columns('count(*) as blockCount', 'sum(txCount) as txCount', 'sum(fees) as fees', 'min(time) as firstBlockTime', 'max(time) as lastBlockTime')
253
+ .where({ epochNumber }));
254
+ if (!row || Number(row.blockCount ?? 0) === 0)
255
+ return null;
256
+ return {
257
+ blockCount: Number(row.blockCount),
258
+ txCount: Number(row.txCount ?? 0),
259
+ fees: lovelaceSum(row.fees),
260
+ firstBlockTime: row.firstBlockTime != null ? Number(row.firstBlockTime) : null,
261
+ lastBlockTime: row.lastBlockTime != null ? Number(row.lastBlockTime) : null,
262
+ };
263
+ }
264
+ catch (err) {
265
+ logger.debug(`Crawled totals for epoch ${epochNumber} unavailable:`, err);
266
+ return null;
267
+ }
268
+ }
269
+ /** Epoch row with only the slot-derived bounds, for an epoch the backend cannot describe. */
270
+ bareEpochRow(epochNumber) {
271
+ const network = this.client.network;
272
+ const start = (0, epoch_slots_1.epochStartSlot)(network, epochNumber);
273
+ return {
274
+ epoch: epochNumber,
275
+ startTime: (0, epoch_slots_1.slotToPosixSeconds)(network, start),
276
+ endTime: (0, epoch_slots_1.slotToPosixSeconds)(network, (0, epoch_slots_1.epochStartSlot)(network, epochNumber + 1)),
277
+ output: null,
278
+ activeStake: null,
279
+ };
280
+ }
200
281
  constructor(client, txBuilder) {
201
282
  this.client = client;
202
283
  this.txBuilder = txBuilder;
@@ -211,35 +292,31 @@ class CardanoIndexer {
211
292
  const txRow = (0, mappers_1.mapTransaction)(providerTx);
212
293
  await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRow));
213
294
  logger.debug(`indexTransaction: upserted transaction ${txHash}`);
295
+ await this.writeTransactionChildren(tx, providerTx, txRow.txSeq);
296
+ return txRow;
297
+ }
298
+ /** Lazy path: inputs, outputs, their assets and metadata of one transaction. */
299
+ async writeTransactionChildren(tx, providerTx, txSeq) {
214
300
  if (providerTx.inputs) {
215
- // Inputs + InputAssets
216
- const inputRows = (0, mappers_1.mapTransactionInputs)(txHash, providerTx.inputs);
217
- const inputAssetRows = (0, mappers_1.mapTransactionInputAssets)(txHash, providerTx.inputs);
218
- if (inputRows.length) {
301
+ const inputRows = (0, mappers_1.mapTransactionInputs)(txSeq, providerTx.inputs);
302
+ const inputAssetRows = (0, mappers_1.mapTransactionInputAssets)(txSeq, providerTx.inputs);
303
+ if (inputRows.length)
219
304
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputs).entries(inputRows));
220
- logger.debug(`indexTransaction: upserted ${inputRows.length} transaction inputs for ${txHash}`);
221
- }
222
- if (inputAssetRows.length) {
305
+ if (inputAssetRows.length)
223
306
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputAssets).entries(inputAssetRows));
224
- logger.debug(`indexTransaction: upserted ${inputAssetRows.length} transaction input assets for ${txHash}`);
225
- }
226
307
  }
227
- // Outputs + OutputAssets — must not depend on the inputs branch
308
+ // outputs must not depend on the inputs branch
228
309
  if (providerTx.outputs) {
229
- const outputRows = (0, mappers_1.mapTransactionOutputs)(txHash, providerTx.outputs);
230
- const outputAssetRows = (0, mappers_1.mapTransactionOutputAssets)(txHash, providerTx.outputs);
231
- if (outputRows.length) {
310
+ const outputRows = (0, mappers_1.mapTransactionOutputs)(txSeq, providerTx.outputs);
311
+ const outputAssetRows = (0, mappers_1.mapTransactionOutputAssets)(txSeq, providerTx.outputs);
312
+ if (outputRows.length)
232
313
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputs).entries(outputRows));
233
- }
234
- if (outputAssetRows.length) {
314
+ if (outputAssetRows.length)
235
315
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
236
- }
237
316
  }
238
317
  const metadataRows = (0, mappers_1.mapTransactionMetadata)(providerTx.metadata || []);
239
- if (metadataRows.length) {
318
+ if (metadataRows.length)
240
319
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
241
- }
242
- return txRow;
243
320
  }
244
321
  /**
245
322
  * Index address data with assets and UTxOs; transactions are loaded separately via
@@ -457,10 +534,13 @@ class CardanoIndexer {
457
534
  }
458
535
  return rows;
459
536
  }
460
- /** Index the network information. */
537
+ /** Index the network information; circulating supply comes from the crawled UTxO set when it is current. */
461
538
  async indexNetworkInformation(tx) {
462
539
  const netInfo = await this.client.getNetworkInformation();
463
- const netEntity = (0, mappers_1.mapNetworkInfo)(netInfo, this.client.max_age_ms, this.client.network);
540
+ const circulating = (await this.localCoverage(tx))?.ledger
541
+ ? lovelaceSum((await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAddresses).columns('sum(totalLovelace) as total')))?.total)
542
+ : null;
543
+ const netEntity = (0, mappers_1.mapNetworkInfo)(circulating === null ? netInfo : { ...netInfo, supply: { ...netInfo.supply, circulating } }, this.client.max_age_ms, this.client.network);
464
544
  await tx.run(UPSERT.into(CardanoODataService_1.NetworkInformation).entries(netEntity));
465
545
  return netEntity;
466
546
  }
@@ -502,13 +582,15 @@ class CardanoIndexer {
502
582
  await this.resolveInputs(tx, txs);
503
583
  this.applyCollateralFees(blockData, txs);
504
584
  await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
585
+ await this.removeSupersededBlocks(tx, blockData);
586
+ await this.removeStaleTxSeqs(tx, txs);
505
587
  // One bulk UPSERT per table. NUL safety for PostgreSQL is enforced by the db-level hook in
506
588
  // srv/utils/db-sanitize.ts, not per call site.
507
589
  const txRows = txs.map(t => (0, mappers_1.mapTransaction)(t));
508
- const inputRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputs)(t.hash, t.inputs ?? []));
509
- const inputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputAssets)(t.hash, t.inputs ?? []));
510
- const outputRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputs)(t.hash, t.outputs ?? []));
511
- const outputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputAssets)(t.hash, t.outputs ?? []));
590
+ const inputRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputs)((0, mappers_1.txSeqOf)(t.slot, t.index), t.inputs ?? []));
591
+ const inputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionInputAssets)((0, mappers_1.txSeqOf)(t.slot, t.index), t.inputs ?? []));
592
+ const outputRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputs)((0, mappers_1.txSeqOf)(t.slot, t.index), t.outputs ?? []));
593
+ const outputAssetRows = txs.flatMap(t => (0, mappers_1.mapTransactionOutputAssets)((0, mappers_1.txSeqOf)(t.slot, t.index), t.outputs ?? []));
512
594
  const metadataRows = txs.flatMap(t => (0, mappers_1.mapTransactionMetadata)(t.metadata ?? []));
513
595
  // Certificates + withdrawals are keyed (tx, certIndex, kind) / (tx, stakeAddress), so a
514
596
  // re-crawl is idempotent and a reorg removes them with their tx.
@@ -564,6 +646,42 @@ class CardanoIndexer {
564
646
  logger.debug(`indexBlockFull: block ${blockData.hash} — ${txs.length} txs, ${outputRows.length} outputs, ` +
565
647
  `${assetHistoryRows.length} mint/burn, ${newAssets} new assets`);
566
648
  }
649
+ /**
650
+ * Drop other Block rows at the crawled block's height that no transaction references: lazily
651
+ * indexed tips that were rolled back, which no crawler reorg covers.
652
+ */
653
+ async removeSupersededBlocks(tx, blockData) {
654
+ if (blockData.height == null)
655
+ return;
656
+ const others = await tx.run(SELECT.from(CardanoODataService_1.Blocks).columns('hash').where({ height: blockData.height, hash: { '!=': blockData.hash } }));
657
+ if (!others?.length)
658
+ return;
659
+ const hashes = others.map(r => r.hash);
660
+ const referenced = await tx.run(SELECT.distinct.from(CardanoODataService_1.Transactions).columns('blockHash').where({ blockHash: { in: hashes } }));
661
+ const keep = new Set((referenced ?? []).map(r => r.blockHash));
662
+ const stale = hashes.filter(h => !keep.has(h));
663
+ if (!stale.length)
664
+ return;
665
+ await tx.run(DELETE.from(CardanoODataService_1.Blocks).where({ hash: { in: stale } }));
666
+ logger.info(`indexBlockFull: removed ${stale.length} superseded block row(s) at height ${blockData.height}`);
667
+ }
668
+ /**
669
+ * Drop transactions of another fork that hold one of this block's txSeq keys (a lazily indexed
670
+ * tx from a rolled-back block at the same slot); their input/output rows would mix with ours.
671
+ */
672
+ async removeStaleTxSeqs(tx, txs) {
673
+ if (!txs.length)
674
+ return;
675
+ const seqs = txs.map(t => (0, mappers_1.txSeqOf)(t.slot, t.index));
676
+ const rows = await tx.run(SELECT.from(CardanoODataService_1.Transactions).columns('hash', 'txSeq')
677
+ .where({ txSeq: { between: Math.min(...seqs), and: Math.max(...seqs) } }));
678
+ const ours = new Set(txs.map(t => t.hash));
679
+ const stale = (rows ?? []).filter(r => !ours.has(r.hash));
680
+ if (!stale.length)
681
+ return;
682
+ await (0, transaction_rows_1.deleteTransactionRows)(tx, stale);
683
+ logger.info(`indexBlockFull: removed ${stale.length} transaction(s) of another fork at slot ${txs[0].slot}`);
684
+ }
567
685
  /**
568
686
  * Warn once when `crawler.certificates` is on but the source reports none (`certificates`
569
687
  * undefined, as with Blockfrost). `[]` means "none" and is not a warning.
@@ -612,18 +730,23 @@ class CardanoIndexer {
612
730
  // 3. Batch-read prior-block outputs from the DB, chunked so a dense block's input set
613
731
  // never exceeds a driver's bind-variable cap
614
732
  const sourceHashes = [...new Set(unresolved.map(u => u.input.txHash))];
733
+ const hashBySeq = new Map();
734
+ for (const k of await (0, transaction_rows_1.readTxKeys)(tx, sourceHashes)) {
735
+ if (k.txSeq != null)
736
+ hashBySeq.set((0, transaction_rows_1.seqKey)(k.txSeq), k.hash);
737
+ }
615
738
  const addrByKey = new Map();
616
739
  const amtByKey = new Map();
617
- for (const hashChunk of (0, collections_1.chunk)(sourceHashes, collections_1.IN_CHUNK)) {
740
+ for (const seqChunk of (0, collections_1.chunk)([...hashBySeq.keys()].map(Number), collections_1.IN_CHUNK)) {
618
741
  const [outRows, assetRows] = await Promise.all([
619
- tx.run(SELECT.from(CardanoODataService_1.TransactionOutputs).where({ tx_hash: { in: hashChunk } })),
620
- tx.run(SELECT.from(CardanoODataService_1.TransactionOutputAssets).where({ output_tx_hash: { in: hashChunk } })),
742
+ tx.run(SELECT.from(CardanoODataService_1.TransactionOutputs).where({ txSeq: { in: seqChunk } })),
743
+ tx.run(SELECT.from(CardanoODataService_1.TransactionOutputAssets).where({ output_txSeq: { in: seqChunk } })),
621
744
  ]);
622
745
  for (const r of outRows) {
623
- addrByKey.set(`${r.tx_hash}#${r.outputIndex}`, r.address_address);
746
+ addrByKey.set(`${hashBySeq.get((0, transaction_rows_1.seqKey)(r.txSeq))}#${r.outputIndex}`, r.address_address);
624
747
  }
625
748
  for (const r of assetRows) {
626
- const k = `${r.output_tx_hash}#${r.output_outputIndex}`;
749
+ const k = `${hashBySeq.get((0, transaction_rows_1.seqKey)(r.output_txSeq))}#${r.output_outputIndex}`;
627
750
  const list = amtByKey.get(k) ?? [];
628
751
  list.push({ unit: r.unit, quantity: String(r.asset_quantity) });
629
752
  amtByKey.set(k, list);
@@ -857,7 +980,12 @@ class CardanoIndexer {
857
980
  }
858
981
  /** Index an account by stake address, plus its addresses when it has any. */
859
982
  async indexAccount(tx, stakeAddress) {
860
- const accountInfo = await this.client.getAccount(stakeAddress);
983
+ const accountInfo = { ...(await this.client.getAccount(stakeAddress)) };
984
+ // controlled amount = UTxOs under the stake key (crawled set, when current) + reward balance
985
+ if ((await this.localCoverage(tx))?.ledger) {
986
+ const ledger = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAccounts).columns('controlledAmount').where({ stakeAddress }));
987
+ accountInfo.controlledAmount = (BigInt(lovelaceSum(ledger?.controlledAmount)) + BigInt(accountInfo.withdrawableAmount || '0')).toString();
988
+ }
861
989
  const accountEntity = (0, mappers_1.mapAccount)(accountInfo, this.client.max_age_ms);
862
990
  await tx.run(UPSERT.into(CardanoODataService_1.Accounts).entries(accountEntity));
863
991
  const addresses = accountInfo.addresses.map(a => a.address);
@@ -876,7 +1004,7 @@ class CardanoIndexer {
876
1004
  /** Index a pool by id. */
877
1005
  async indexPool(tx, poolId) {
878
1006
  const poolInfo = await this.client.getPool(poolId);
879
- const poolEntity = (0, mappers_1.mapPool)(poolInfo, this.client.max_age_ms);
1007
+ const poolEntity = (0, mappers_1.mapPool)({ ...poolInfo, ...(await this.localPoolBlocks(tx, poolId)) }, this.client.max_age_ms);
880
1008
  await tx.run(UPSERT.into(CardanoODataService_1.Pools).entries(poolEntity));
881
1009
  return poolEntity;
882
1010
  }
@@ -1097,6 +1225,12 @@ class CardanoIndexer {
1097
1225
  // Epoch data may not be available (e.g., Koios drops old/in-progress epochs)
1098
1226
  }
1099
1227
  const blockEntity = (0, mappers_1.mapBlock)(blockInfo, epoch);
1228
+ // A header-only tip is never persisted: its zeros would read as an empty block, overwrite a
1229
+ // crawled row of the same hash, or outlive the block when the tip is rolled back.
1230
+ if (blockInfo.headerOnly) {
1231
+ const stored = await tx.run(SELECT.one.from(CardanoODataService_1.Block).where({ hash: blockInfo.hash }));
1232
+ return stored ?? blockEntity;
1233
+ }
1100
1234
  await tx.run(UPSERT.into(CardanoODataService_1.Block).entries(blockEntity));
1101
1235
  return blockEntity;
1102
1236
  }
@@ -1105,6 +1239,11 @@ class CardanoIndexer {
1105
1239
  //-----------------------------------------------------------------------------
1106
1240
  /** Max addresses to index concurrently (avoid overloading backends) */
1107
1241
  static ADDR_CONCURRENCY = 5;
1242
+ /** Block position of a transaction already in the local index (crawled or cached), or null. */
1243
+ async findIndexedTransaction(tx, txHash) {
1244
+ const row = await tx.run(SELECT.one.from(CardanoODataService_1.Transactions).columns('slot', 'blockHeight').where({ hash: txHash }));
1245
+ return row ?? null;
1246
+ }
1108
1247
  /**
1109
1248
  * Ensure a set of transactions is indexed: DB check, batch fetch of the missing ones, UPSERT.
1110
1249
  * @returns provider transactions for the hashes that had to be fetched
@@ -1123,26 +1262,7 @@ class CardanoIndexer {
1123
1262
  for (const [, providerTx] of fetched) {
1124
1263
  const txRow = (0, mappers_1.mapTransaction)(providerTx);
1125
1264
  await tx.run(UPSERT.into(CardanoODataService_1.Transactions).entries(txRow));
1126
- if (providerTx.inputs) {
1127
- const inputRows = (0, mappers_1.mapTransactionInputs)(providerTx.hash, providerTx.inputs);
1128
- const inputAssetRows = (0, mappers_1.mapTransactionInputAssets)(providerTx.hash, providerTx.inputs);
1129
- if (inputRows.length)
1130
- await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputs).entries(inputRows));
1131
- if (inputAssetRows.length)
1132
- await tx.run(UPSERT.into(CardanoODataService_1.TransactionInputAssets).entries(inputAssetRows));
1133
- }
1134
- // outputs independent of inputs (see indexTransaction)
1135
- if (providerTx.outputs) {
1136
- const outputRows = (0, mappers_1.mapTransactionOutputs)(providerTx.hash, providerTx.outputs);
1137
- const outputAssetRows = (0, mappers_1.mapTransactionOutputAssets)(providerTx.hash, providerTx.outputs);
1138
- if (outputRows.length)
1139
- await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputs).entries(outputRows));
1140
- if (outputAssetRows.length)
1141
- await tx.run(UPSERT.into(CardanoODataService_1.TransactionOutputAssets).entries(outputAssetRows));
1142
- }
1143
- const metadataRows = (0, mappers_1.mapTransactionMetadata)(providerTx.metadata || []);
1144
- if (metadataRows.length)
1145
- await tx.run(UPSERT.into(CardanoODataService_1.TransactionMetadata).entries(metadataRows));
1265
+ await this.writeTransactionChildren(tx, providerTx, txRow.txSeq);
1146
1266
  }
1147
1267
  }
1148
1268
  return fetched;
@@ -27,6 +27,17 @@ export declare class CardanoTransactionBuilder {
27
27
  buildMintTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
28
28
  /** Build a Plutus spending transaction (consume a UTxO at a script address). */
29
29
  buildPlutusSpendTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
30
+ /**
31
+ * Resolve the script UTxO of a Plutus spend from the node's ledger, otherwise from its producing
32
+ * transaction. Spending an already-consumed script UTxO is the most common replay mistake —
33
+ * both paths reject it with a clear 400 instead of a node-side rejection at submit.
34
+ */
35
+ private _resolveScriptUtxo;
36
+ /**
37
+ * Unspent outputs for `refs` from the node's ledger, keyed "txHash#index"; null when no
38
+ * ledger-state backend is usable or the query fails (callers fall back to getTransaction).
39
+ */
40
+ private _lookupUnspent;
30
41
  /**
31
42
  * Verify that an output resolved via getTransaction is still unspent against the live UTxO
32
43
  * set of its address (getTransaction only proves it existed). Lookup failures are tolerated.
@@ -37,9 +48,10 @@ export declare class CardanoTransactionBuilder {
37
48
  /** Resolve CIP-31 reference-input refs (read-only, not merged into the coin-selection set). */
38
49
  private _resolveReferenceInputs;
39
50
  /**
40
- * Resolve {txHash, outputIndex} refs to full UTxO records: known UTxOs first, otherwise the
41
- * producing transaction plus an unspent check. Throws TransactionValidationError (labelled
42
- * by `kind`) for a missing or spent ref. Refs are deduplicated; order is preserved.
51
+ * Resolve {txHash, outputIndex} refs to full UTxO records: known UTxOs first, then the node's
52
+ * ledger, otherwise the producing transaction plus an unspent check. Throws
53
+ * TransactionValidationError (labelled by `kind`) for a missing or spent ref. Refs are
54
+ * deduplicated; order is preserved.
43
55
  */
44
56
  private _resolveInputRefs;
45
57
  /** Fetch the UTxOs of an address; throws InsufficientFundsError when it has none. */
@@ -141,24 +141,7 @@ class CardanoTransactionBuilder {
141
141
  const allUtxos = [...senderUtxos];
142
142
  const alreadyIncluded = senderUtxos.some(u => u.txHash === scriptRef.txHash && u.outputIndex === scriptRef.outputIndex);
143
143
  if (!alreadyIncluded) {
144
- logger.debug(`Script UTxO ${scriptRef.txHash}#${scriptRef.outputIndex} not in sender UTxOs - fetching from backend`);
145
- const tx = await cardanoClient.getTransaction(scriptRef.txHash);
146
- const scriptOutput = tx.outputs?.find(o => o.outputIndex === scriptRef.outputIndex);
147
- if (!scriptOutput) {
148
- throw new errors_1.TransactionValidationError(`Script UTxO output ${scriptRef.txHash}#${scriptRef.outputIndex} not found in transaction`);
149
- }
150
- // spending an already-consumed script UTxO is the most common replay mistake —
151
- // catch it here with a clear 400 instead of a node-side rejection at submit
152
- await this._assertUnspent(scriptRef, scriptOutput.address, 'scriptUtxo', new Map());
153
- allUtxos.push({
154
- txHash: scriptRef.txHash,
155
- outputIndex: scriptRef.outputIndex,
156
- address: scriptOutput.address,
157
- amount: scriptOutput.amount,
158
- inlineDatum: scriptOutput.inlineDatum,
159
- datumHash: scriptOutput.dataHash ?? undefined,
160
- scriptRef: scriptOutput.referenceScriptHash ?? undefined,
161
- });
144
+ allUtxos.push(await this._resolveScriptUtxo(scriptRef));
162
145
  }
163
146
  // Resolve forced inputs (may overlap with sender UTxOs or the script UTxO — dedup below).
164
147
  // The builder itself will skip any forced ref that matches scriptRef.
@@ -185,6 +168,53 @@ class CardanoTransactionBuilder {
185
168
  logger.debug(`Built Plutus spending transaction successfully.`);
186
169
  return txBuildResult;
187
170
  }
171
+ /**
172
+ * Resolve the script UTxO of a Plutus spend from the node's ledger, otherwise from its producing
173
+ * transaction. Spending an already-consumed script UTxO is the most common replay mistake —
174
+ * both paths reject it with a clear 400 instead of a node-side rejection at submit.
175
+ */
176
+ async _resolveScriptUtxo(scriptRef) {
177
+ const ledger = await this._lookupUnspent([scriptRef]);
178
+ if (ledger) {
179
+ const live = ledger.get(outRefKey(scriptRef));
180
+ if (!live) {
181
+ throw new errors_1.TransactionValidationError(`scriptUtxo ${outRefKey(scriptRef)} not found on-chain or already spent`);
182
+ }
183
+ return live;
184
+ }
185
+ logger.debug(`Script UTxO ${outRefKey(scriptRef)} not in sender UTxOs - fetching its transaction`);
186
+ const tx = await this.client.getTransaction(scriptRef.txHash);
187
+ const scriptOutput = tx.outputs?.find(o => o.outputIndex === scriptRef.outputIndex);
188
+ if (!scriptOutput) {
189
+ throw new errors_1.TransactionValidationError(`Script UTxO output ${outRefKey(scriptRef)} not found in transaction`);
190
+ }
191
+ await this._assertUnspent(scriptRef, scriptOutput.address, 'scriptUtxo', new Map());
192
+ return {
193
+ txHash: scriptRef.txHash,
194
+ outputIndex: scriptRef.outputIndex,
195
+ address: scriptOutput.address,
196
+ amount: scriptOutput.amount,
197
+ inlineDatum: scriptOutput.inlineDatum,
198
+ datumHash: scriptOutput.dataHash ?? undefined,
199
+ scriptRef: scriptOutput.referenceScriptHash ?? undefined,
200
+ };
201
+ }
202
+ /**
203
+ * Unspent outputs for `refs` from the node's ledger, keyed "txHash#index"; null when no
204
+ * ledger-state backend is usable or the query fails (callers fall back to getTransaction).
205
+ */
206
+ async _lookupUnspent(refs) {
207
+ if (refs.length === 0)
208
+ return new Map();
209
+ try {
210
+ const utxos = await this.client.getUnspentOutputs(refs);
211
+ return utxos ? new Map(utxos.map(u => [outRefKey(u), u])) : null;
212
+ }
213
+ catch (err) {
214
+ logger.warn(`Ledger lookup of ${refs.length} output reference(s) failed, falling back to the producing transactions: ${err instanceof Error ? err.message : String(err)}`);
215
+ return null;
216
+ }
217
+ }
188
218
  /**
189
219
  * Verify that an output resolved via getTransaction is still unspent against the live UTxO
190
220
  * set of its address (getTransaction only proves it existed). Lookup failures are tolerated.
@@ -219,9 +249,10 @@ class CardanoTransactionBuilder {
219
249
  return this._resolveInputRefs(refs, knownUtxos, 'referenceInput');
220
250
  }
221
251
  /**
222
- * Resolve {txHash, outputIndex} refs to full UTxO records: known UTxOs first, otherwise the
223
- * producing transaction plus an unspent check. Throws TransactionValidationError (labelled
224
- * by `kind`) for a missing or spent ref. Refs are deduplicated; order is preserved.
252
+ * Resolve {txHash, outputIndex} refs to full UTxO records: known UTxOs first, then the node's
253
+ * ledger, otherwise the producing transaction plus an unspent check. Throws
254
+ * TransactionValidationError (labelled by `kind`) for a missing or spent ref. Refs are
255
+ * deduplicated; order is preserved.
225
256
  */
226
257
  async _resolveInputRefs(refs, knownUtxos, kind) {
227
258
  if (!refs || refs.length === 0)
@@ -235,6 +266,8 @@ class CardanoTransactionBuilder {
235
266
  seen.add(key);
236
267
  return true;
237
268
  });
269
+ const isKnown = (r) => knownUtxos.some(u => u.txHash === r.txHash && u.outputIndex === r.outputIndex);
270
+ const ledger = await this._lookupUnspent(dedupedRefs.filter(r => !isKnown(r)));
238
271
  const liveUtxoCache = new Map();
239
272
  const resolved = [];
240
273
  for (const ref of dedupedRefs) {
@@ -244,7 +277,16 @@ class CardanoTransactionBuilder {
244
277
  resolved.push(local);
245
278
  continue;
246
279
  }
247
- // 2) Fallback: fetch the producing transaction and look up the output.
280
+ // 2) The node's ledger answers existence and spendability in one lookup
281
+ if (ledger) {
282
+ const live = ledger.get(outRefKey(ref));
283
+ if (!live) {
284
+ throw new errors_1.TransactionValidationError(`${kind} ${outRefKey(ref)} not found on-chain or already spent`);
285
+ }
286
+ resolved.push(live);
287
+ continue;
288
+ }
289
+ // 3) Fallback: fetch the producing transaction and look up the output.
248
290
  let tx;
249
291
  try {
250
292
  tx = await this.client.getTransaction(ref.txHash);
@@ -282,14 +324,18 @@ class CardanoTransactionBuilder {
282
324
  }
283
325
  }
284
326
  exports.CardanoTransactionBuilder = CardanoTransactionBuilder;
327
+ /** "txHash#outputIndex" key of an output reference. */
328
+ function outRefKey(ref) {
329
+ return `${ref.txHash}#${ref.outputIndex}`;
330
+ }
285
331
  /** Merge two UTxO lists, skipping refs already present in the first. */
286
332
  function mergeUtxosUnique(base, extra) {
287
333
  if (extra.length === 0)
288
334
  return base;
289
- const seen = new Set(base.map(u => `${u.txHash}#${u.outputIndex}`));
335
+ const seen = new Set(base.map(outRefKey));
290
336
  const result = [...base];
291
337
  for (const u of extra) {
292
- const key = `${u.txHash}#${u.outputIndex}`;
338
+ const key = outRefKey(u);
293
339
  if (!seen.has(key)) {
294
340
  seen.add(key);
295
341
  result.push(u);
@@ -10,6 +10,7 @@ const collections_1 = require("../../utils/collections");
10
10
  const const_1 = require("../../utils/const");
11
11
  const hooks_1 = require("./hooks");
12
12
  const ledger_state_1 = require("../ledger-state");
13
+ const transaction_rows_1 = require("../transaction-rows");
13
14
  const cardano_1 = require("#cds-models/odatano/cardano");
14
15
  const sync_state_1 = require("./sync-state");
15
16
  const { SELECT, DELETE, INSERT } = cds_1.default.ql;
@@ -854,7 +855,7 @@ class CardanoCrawler {
854
855
  for (const blockChunk of (0, collections_1.chunk)(blockHashes, collections_1.IN_CHUNK)) {
855
856
  // Only transactions of the rolled-back blocks — resolved via blockHash, so
856
857
  // lazily-indexed txs of unrelated blocks are not collateral damage.
857
- const staleTxs = await tx.run(SELECT.from(cardano_1.Transactions).columns('hash').where({ blockHash: { in: blockChunk } }));
858
+ const staleTxs = await tx.run(SELECT.from(cardano_1.Transactions).columns('hash', 'txSeq').where({ blockHash: { in: blockChunk } }));
858
859
  const txHashes = staleTxs.map((t) => t.hash);
859
860
  txsRolledBack += txHashes.length;
860
861
  rolledBackTxHashes.push(...txHashes);
@@ -865,15 +866,8 @@ class CardanoCrawler {
865
866
  await tx.run(DELETE.from(cardano_1.AddressUTxOs).where({ hash: { in: txChunk } }));
866
867
  await tx.run(DELETE.from(cardano_1.AddressTransactions).where({ tx_hash: { in: txChunk } }));
867
868
  await tx.run(DELETE.from(cardano_1.AssetHistory_).where({ txHash: { in: txChunk } }));
868
- await tx.run(DELETE.from(cardano_1.TransactionInputAssets).where({ input_tx_hash: { in: txChunk } }));
869
- await tx.run(DELETE.from(cardano_1.TransactionOutputAssets).where({ output_tx_hash: { in: txChunk } }));
870
- await tx.run(DELETE.from(cardano_1.TransactionInputs).where({ tx_hash: { in: txChunk } }));
871
- await tx.run(DELETE.from(cardano_1.TransactionOutputs).where({ tx_hash: { in: txChunk } }));
872
- await tx.run(DELETE.from(cardano_1.TransactionMetadata_).where({ tx_hash: { in: txChunk } }));
873
- await tx.run(DELETE.from(cardano_1.TransactionCertificates).where({ tx_hash: { in: txChunk } }));
874
- await tx.run(DELETE.from(cardano_1.TransactionWithdrawals).where({ tx_hash: { in: txChunk } }));
875
- await tx.run(DELETE.from(cardano_1.Transactions).where({ hash: { in: txChunk } }));
876
869
  }
870
+ await (0, transaction_rows_1.deleteTransactionRows)(tx, staleTxs);
877
871
  await tx.run(DELETE.from(cardano_1.Blocks).where({ hash: { in: blockChunk } }));
878
872
  }
879
873
  // Ledger state, driven by the PERSISTED status: a fork after the anchor is undone and the
@@ -0,0 +1,12 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ export interface TxKey {
3
+ hash: string;
4
+ txSeq: number | string | null;
5
+ }
6
+ /** `txSeq` as a stable map key: Int64 columns come back as number or string depending on the driver. */
7
+ export declare const seqKey: (txSeq: number | string) => string;
8
+ /** Hash and txSeq of the given transactions that are indexed. */
9
+ export declare function readTxKeys(tx: CapTransaction, hashes: string[]): Promise<TxKey[]>;
10
+ /** Delete transactions with their input/output, asset, metadata, certificate and withdrawal rows. */
11
+ export declare function deleteTransactionRows(tx: CapTransaction, keys: TxKey[]): Promise<void>;
12
+ //# sourceMappingURL=transaction-rows.d.ts.map
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.seqKey = void 0;
7
+ exports.readTxKeys = readTxKeys;
8
+ exports.deleteTransactionRows = deleteTransactionRows;
9
+ const cds_1 = __importDefault(require("@sap/cds"));
10
+ const cardano_1 = require("#cds-models/odatano/cardano");
11
+ const collections_1 = require("../utils/collections");
12
+ const { SELECT, DELETE } = cds_1.default.ql;
13
+ /** `txSeq` as a stable map key: Int64 columns come back as number or string depending on the driver. */
14
+ const seqKey = (txSeq) => String(Number(txSeq));
15
+ exports.seqKey = seqKey;
16
+ /** Hash and txSeq of the given transactions that are indexed. */
17
+ async function readTxKeys(tx, hashes) {
18
+ const keys = [];
19
+ for (const hashChunk of (0, collections_1.chunk)(hashes, collections_1.IN_CHUNK)) {
20
+ const rows = await tx.run(SELECT.from(cardano_1.Transactions).columns('hash', 'txSeq').where({ hash: { in: hashChunk } }));
21
+ keys.push(...(rows ?? []));
22
+ }
23
+ return keys;
24
+ }
25
+ /** Delete transactions with their input/output, asset, metadata, certificate and withdrawal rows. */
26
+ async function deleteTransactionRows(tx, keys) {
27
+ for (const keyChunk of (0, collections_1.chunk)(keys, collections_1.IN_CHUNK)) {
28
+ const hashes = keyChunk.map(k => k.hash);
29
+ const seqs = keyChunk.filter(k => k.txSeq != null).map(k => k.txSeq);
30
+ if (seqs.length) {
31
+ await tx.run(DELETE.from(cardano_1.TransactionInputAssets).where({ input_txSeq: { in: seqs } }));
32
+ await tx.run(DELETE.from(cardano_1.TransactionOutputAssets).where({ output_txSeq: { in: seqs } }));
33
+ await tx.run(DELETE.from(cardano_1.TransactionInputs).where({ txSeq: { in: seqs } }));
34
+ await tx.run(DELETE.from(cardano_1.TransactionOutputs).where({ txSeq: { in: seqs } }));
35
+ }
36
+ await tx.run(DELETE.from(cardano_1.TransactionMetadata_).where({ tx_hash: { in: hashes } }));
37
+ await tx.run(DELETE.from(cardano_1.TransactionCertificates).where({ tx_hash: { in: hashes } }));
38
+ await tx.run(DELETE.from(cardano_1.TransactionWithdrawals).where({ tx_hash: { in: hashes } }));
39
+ await tx.run(DELETE.from(cardano_1.Transactions).where({ hash: { in: hashes } }));
40
+ }
41
+ }
42
+ //# sourceMappingURL=transaction-rows.js.map
@@ -392,7 +392,12 @@ class CardanoWalletWorker {
392
392
  // A rejection may mean the tx is already on-chain (inputs spent), so the chain decides.
393
393
  let onChain;
394
394
  try {
395
- await this.deps.client.getTransaction(job.txHash);
395
+ // the local index first (filled by the crawler), then the backends
396
+ const txHash = job.txHash;
397
+ const indexed = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((t) => this.deps.indexer.findIndexedTransaction(t, txHash)));
398
+ if (!indexed) {
399
+ await this.deps.client.getTransaction(txHash);
400
+ }
396
401
  onChain = true;
397
402
  }
398
403
  catch (lookupErr) {