@odatano/core 2.0.0-rc.24 → 2.0.0-rc.25

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 (76) hide show
  1. package/@cds-models/CardanoIndexerService/index.d.ts +37 -0
  2. package/@cds-models/CardanoIndexerService/index.js +4 -0
  3. package/@cds-models/CardanoODataService/index.d.ts +27 -2
  4. package/@cds-models/CardanoODataService/index.js +3 -0
  5. package/@cds-models/CardanoSignService/index.d.ts +23 -1
  6. package/@cds-models/CardanoSignService/index.js +3 -0
  7. package/@cds-models/CardanoTransactionService/index.d.ts +34 -1
  8. package/@cds-models/CardanoTransactionService/index.js +4 -0
  9. package/@cds-models/index.d.ts +18 -0
  10. package/@cds-models/index.js +3 -0
  11. package/@cds-models/odatano/cardano/index.d.ts +49 -2
  12. package/@cds-models/odatano/cardano/index.js +6 -0
  13. package/db/schema.cds +74 -3
  14. package/db/types.cds +27 -0
  15. package/package.json +182 -182
  16. package/srv/blockchain/backends/blockfrost-backend.js +4 -2
  17. package/srv/blockchain/backends/cardano-backend.d.ts +0 -2
  18. package/srv/blockchain/backends/koios-backend.d.ts +1 -1
  19. package/srv/blockchain/backends/koios-backend.js +61 -14
  20. package/srv/blockchain/backends/odatano-backend.d.ts +5 -0
  21. package/srv/blockchain/backends/odatano-backend.js +12 -0
  22. package/srv/blockchain/backends/ogmios-backend.d.ts +12 -2
  23. package/srv/blockchain/backends/ogmios-backend.js +91 -21
  24. package/srv/blockchain/cardano-client.d.ts +11 -5
  25. package/srv/blockchain/cardano-client.js +51 -16
  26. package/srv/blockchain/cardano-indexer.d.ts +43 -15
  27. package/srv/blockchain/cardano-indexer.js +177 -68
  28. package/srv/blockchain/cardano-tx-builder.d.ts +11 -1
  29. package/srv/blockchain/cardano-tx-builder.js +57 -2
  30. package/srv/blockchain/crawler/certificate-backfill.d.ts +22 -0
  31. package/srv/blockchain/crawler/certificate-backfill.js +49 -30
  32. package/srv/blockchain/crawler/crawler.d.ts +3 -1
  33. package/srv/blockchain/crawler/crawler.js +12 -7
  34. package/srv/blockchain/crawler/sync-state.d.ts +3 -1
  35. package/srv/blockchain/crawler/sync-state.js +15 -2
  36. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  37. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  38. package/srv/blockchain/crawler/utxo-set-import.d.ts +9 -0
  39. package/srv/blockchain/crawler/utxo-set-import.js +138 -47
  40. package/srv/blockchain/ledger-state.d.ts +16 -1
  41. package/srv/blockchain/ledger-state.js +38 -18
  42. package/srv/blockchain/pending-spends.d.ts +28 -0
  43. package/srv/blockchain/pending-spends.js +89 -0
  44. package/srv/blockchain/stored-chain.d.ts +5 -2
  45. package/srv/blockchain/stored-chain.js +31 -5
  46. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +12 -3
  47. package/srv/blockchain/transaction-building/buildooor-tx.js +203 -21
  48. package/srv/blockchain/transaction-building/cardano-tx.d.ts +2 -1
  49. package/srv/blockchain/transaction-rows.d.ts +1 -1
  50. package/srv/blockchain/transaction-rows.js +2 -1
  51. package/srv/blockchain/wallet-worker/build-request.js +1 -1
  52. package/srv/cardano-backend-service.js +35 -8
  53. package/srv/cardano-indexer-service.cds +201 -176
  54. package/srv/cardano-indexer-service.js +104 -10
  55. package/srv/cardano-service.cds +5 -0
  56. package/srv/cardano-tx-service.cds +39 -0
  57. package/srv/cardano-tx-service.js +88 -14
  58. package/srv/server.js +4 -1
  59. package/srv/utils/agent-grants.js +1 -0
  60. package/srv/utils/const.d.ts +5 -0
  61. package/srv/utils/const.js +6 -1
  62. package/srv/utils/error-codes.d.ts +2 -0
  63. package/srv/utils/error-codes.js +2 -0
  64. package/srv/utils/errors.d.ts +7 -0
  65. package/srv/utils/errors.js +11 -1
  66. package/srv/utils/mappers.d.ts +24 -2
  67. package/srv/utils/mappers.js +49 -0
  68. package/srv/utils/pg-inline-json.d.ts +8 -0
  69. package/srv/utils/pg-inline-json.js +63 -0
  70. package/srv/utils/tx-build-helper.d.ts +2 -0
  71. package/srv/utils/tx-build-helper.js +12 -0
  72. package/srv/utils/tx-request-parsers.d.ts +46 -5
  73. package/srv/utils/tx-request-parsers.js +227 -16
  74. package/srv/utils/types.d.ts +59 -0
  75. package/srv/utils/validators.d.ts +5 -1
  76. package/srv/utils/validators.js +19 -9
@@ -21,12 +21,22 @@ const epoch_slots_1 = require("../utils/epoch-slots");
21
21
  const const_1 = require("../utils/const");
22
22
  const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
23
23
  const logger = cds_1.default.log('CardanoIndexer');
24
- /** Lovelace aggregate from the DB (string, number or null) as an integer string. */
24
+ /** Datum hash, inline datum and reference-script hash of the spent output onto its input. */
25
+ function copyUtxoData(input, dataHash, inlineDatum, referenceScriptHash) {
26
+ input.dataHash = input.dataHash ?? dataHash ?? null;
27
+ input.inlineDatum = input.inlineDatum ?? inlineDatum ?? null;
28
+ input.referenceScriptHash = input.referenceScriptHash ?? referenceScriptHash ?? null;
29
+ }
25
30
  function lovelaceSum(value) {
26
31
  if (value === null || value === undefined || value === '')
27
32
  return '0';
28
33
  return typeof value === 'number' ? BigInt(Math.trunc(value)).toString() : String(value).split('.')[0];
29
34
  }
35
+ /** Provider-shaped address from its unspent outputs: type and stake address decoded from the address. */
36
+ function addressFromUtxos(address, utxos) {
37
+ const decoded = (0, mappers_1.decodeShelleyAddress)(address);
38
+ return { address, stakeAddress: decoded.stakeAddress, type: decoded.type, isScript: decoded.isScript, amount: (0, mappers_1.sumUtxoAmounts)(utxos), utxos };
39
+ }
30
40
  /**
31
41
  * Indexes Cardano data into the OData entities: fetches via CardanoClient, maps provider data
32
42
  * to entity rows and UPSERTs them inside the caller's CAP transaction.
@@ -39,11 +49,15 @@ class CardanoIndexer {
39
49
  static CRAWL_EPOCH_RETRY_MS = 30 * 1000;
40
50
  /**
41
51
  * Crawler epoch memo: refreshed periodically while an epoch is live and once more when the
42
- * next one starts; holds at most the current and previous epoch. Rows are UPSERTed in every
43
- * block transaction because the caller owns the commit.
52
+ * next one starts; holds at most the current and previous epoch. A row is UPSERTed until a
53
+ * block transaction that wrote it has committed (`confirmBlockCommit`).
44
54
  */
45
55
  crawlEpochCache = new Map();
46
56
  crawlEpochCurrent = null;
57
+ /** Epoch rows known to be committed; a refresh creates a new row object and is written again. */
58
+ crawlEpochWritten = new WeakSet();
59
+ /** Memo updates of the running block transaction, applied only after its commit. */
60
+ pendingCommit = [];
47
61
  crawlEpochPrevious = null;
48
62
  /** Analytics coverage of the crawl path; defaults mirror the crawler config defaults. */
49
63
  crawlAssetHistory = true;
@@ -73,6 +87,8 @@ class CardanoIndexer {
73
87
  ledgerInvalidation = null;
74
88
  /** Units known to have an `Assets` row, so a repeat sighting costs no DB round-trip. */
75
89
  static ASSET_MEMO_CAP = 200_000;
90
+ /** Output references per node lookup when checking crawled UTxOs. */
91
+ static OUTREF_CHUNK = 500;
76
92
  assetMemo = new Set();
77
93
  /**
78
94
  * Background registry enrichment queue (`assetCatalogue: 'enrich'`), drained at a fixed rate
@@ -194,7 +210,7 @@ class CardanoIndexer {
194
210
  async resolveAddress(tx, addr) {
195
211
  return (await this.localAddress(tx, addr)) ?? await this.client.getAddress(addr);
196
212
  }
197
- /** UTxOs of an address: the crawled set (outputs from the node at the tip) when it answers, else the backend. */
213
+ /** UTxOs of an address: the crawled set (checked unspent at the node) when it answers, else the backend. */
198
214
  async resolveAddressUtxos(tx, addr) {
199
215
  return (await this.localAddress(tx, addr))?.utxos ?? await this.client.getAddressUtxos(addr);
200
216
  }
@@ -242,30 +258,25 @@ class CardanoIndexer {
242
258
  return Boolean((await this.localCoverage(tx))?.ledger);
243
259
  }
244
260
  /**
245
- * Address from the crawled UTxO set: outputs from the node at the tip (Ogmios) or the unspent
246
- * `LedgerUTxOs`, type and stake address decoded from the address. An address the set has never
261
+ * Address from the crawled UTxO set: the unspent `LedgerUTxOs` (see openLedgerUtxos), type and
262
+ * stake address decoded from the address. An address the set has never
247
263
  * seen is an empty address, not an error. null = the set cannot answer.
248
264
  */
249
265
  async localAddress(tx, addr) {
250
266
  if (!(await this.localCoverage(tx))?.ledger)
251
267
  return null;
252
- let utxos = null;
253
- try {
254
- utxos = await this.client.getUtxosByAddresses([addr]);
255
- }
256
- catch (err) {
257
- logger.warn(`address ${addr}: node UTxO query failed, answering from the crawled set: ${err?.message ?? err}`);
258
- }
259
- utxos ??= await this.ledgerUtxosOf(tx, [addr]);
260
- const decoded = (0, mappers_1.decodeShelleyAddress)(addr);
261
- return {
262
- address: addr,
263
- stakeAddress: decoded.stakeAddress,
264
- type: decoded.type,
265
- isScript: decoded.isScript,
266
- amount: (0, mappers_1.sumUtxoAmounts)(utxos),
267
- utxos,
268
- };
268
+ return addressFromUtxos(addr, await this.openLedgerUtxos(tx, [addr]));
269
+ }
270
+ /** Addresses of a stake key from the crawled UTxO set, with their unspent outputs (one read for all). */
271
+ async localAccountAddresses(tx, stakeAddress) {
272
+ const rows = await tx.run(SELECT.from(CardanoODataService_1.LedgerAddresses).columns('address').where({ stakeAddress }));
273
+ const addresses = (rows ?? []).map(r => r.address);
274
+ if (addresses.length === 0)
275
+ return [];
276
+ const byAddress = new Map(addresses.map(a => [a, []]));
277
+ for (const u of await this.openLedgerUtxos(tx, addresses))
278
+ byAddress.get(u.address)?.push(u);
279
+ return addresses.map(a => addressFromUtxos(a, byAddress.get(a)));
269
280
  }
270
281
  /**
271
282
  * Latest transactions of an address from the crawled UTxO set: the outputs it received
@@ -382,6 +393,13 @@ class CardanoIndexer {
382
393
  getUtxoAnchor() {
383
394
  return this.crawlUtxoSet && !this.ledgerInvalidation ? this.utxoAnchor : null;
384
395
  }
396
+ /** Apply the memo updates of the block transaction that just committed. */
397
+ confirmBlockCommit() {
398
+ const pending = this.pendingCommit;
399
+ this.pendingCommit = [];
400
+ for (const apply of pending)
401
+ apply();
402
+ }
385
403
  /** Hand out a pending invalidation (dropping the anchor) exactly once after the block commit, or null. */
386
404
  takeLedgerInvalidation() {
387
405
  const reason = this.ledgerInvalidation;
@@ -518,8 +536,16 @@ class CardanoIndexer {
518
536
  constructor(client, txBuilder) {
519
537
  this.client = client;
520
538
  this.txBuilder = txBuilder;
539
+ txBuilder.setAddressUtxoSource?.((address) => this.localAddressUtxos(address));
521
540
  logger.info('CardanoIndexer instance created');
522
541
  }
542
+ /**
543
+ * Unspent outputs of an address from the crawled set for the transaction builder; null = the set
544
+ * cannot answer. Runs on `cds.db`, i.e. inside the caller's request transaction when there is one.
545
+ */
546
+ async localAddressUtxos(address) {
547
+ return (await this.localAddress(cds_1.default.db, address))?.utxos ?? null;
548
+ }
523
549
  /**
524
550
  * Index a transaction with inputs/outputs/assets/metadata; all UPSERTs run in the caller's
525
551
  * transaction, so either everything persists or nothing does.
@@ -558,10 +584,10 @@ class CardanoIndexer {
558
584
  }
559
585
  /**
560
586
  * Index address data with assets and UTxOs; transactions are loaded separately via
561
- * indexAddressTransactions().
587
+ * indexAddressTransactions(). `prefetched` = address data the caller already fetched in a batch.
562
588
  */
563
- async indexAddress(tx, addr) {
564
- const addrData = await this.resolveAddress(tx, addr);
589
+ async indexAddress(tx, addr, prefetched) {
590
+ const addrData = prefetched ?? await this.resolveAddress(tx, addr);
565
591
  logger.debug(`indexAddress: provider response for ${addr}: ${addrData.amount?.length ?? 0} amounts, ${addrData.utxos?.length ?? 0} utxos`);
566
592
  const AddrEntity = (0, mappers_1.mapAddress)(addr, addrData, this.client.max_age_ms);
567
593
  const now = new Date().toISOString();
@@ -661,8 +687,8 @@ class CardanoIndexer {
661
687
  return allRows;
662
688
  }
663
689
  /**
664
- * UTxOs of a payment credential without a provider: addresses from the crawled UTxO set, outputs
665
- * from the node at the tip (Ogmios) or, without one, the unspent `LedgerUTxOs` as of the cursor.
690
+ * UTxOs of a payment credential without a provider: addresses and unspent outputs from the crawled
691
+ * UTxO set (see openLedgerUtxos).
666
692
  * null = the crawled set cannot answer (not synced, no set, credential column still filling).
667
693
  * An address first used in the last `confirmationDepth` blocks is not in the set yet.
668
694
  */
@@ -673,15 +699,38 @@ class CardanoIndexer {
673
699
  const addresses = (rows ?? []).map(r => r.address);
674
700
  if (addresses.length === 0)
675
701
  return [];
702
+ return this.openLedgerUtxos(tx, addresses);
703
+ }
704
+ /**
705
+ * Unspent outputs of addresses from the crawled set, checked against the node by output reference
706
+ * (a keyed lookup; the node's address query scans its whole UTxO set): drops what was spent after
707
+ * the cursor. Without a usable node, or when the check fails, the set as of the cursor.
708
+ */
709
+ async openLedgerUtxos(tx, addresses) {
710
+ const rows = await this.ledgerUtxosOf(tx, addresses);
711
+ if (rows.length === 0)
712
+ return rows;
676
713
  try {
677
- const live = await this.client.getUtxosByAddresses(addresses);
678
- if (live)
679
- return live;
714
+ const unspent = new Map();
715
+ for (const refChunk of (0, collections_1.chunk)(rows, CardanoIndexer.OUTREF_CHUNK)) {
716
+ const live = await this.client.getUnspentOutputs(refChunk.map(u => ({ txHash: u.txHash, outputIndex: u.outputIndex })));
717
+ if (live === null)
718
+ return rows;
719
+ for (const u of live)
720
+ unspent.set(`${u.txHash}#${u.outputIndex}`, u);
721
+ }
722
+ // The node's answer names the reference script, which a snapshot row from a file import lacks
723
+ return rows.flatMap(u => {
724
+ const live = unspent.get(`${u.txHash}#${u.outputIndex}`);
725
+ if (!live)
726
+ return [];
727
+ return [{ ...u, scriptRef: u.scriptRef ?? live.scriptRef ?? undefined, scriptRefCbor: live.scriptRefCbor ?? u.scriptRefCbor }];
728
+ });
680
729
  }
681
730
  catch (err) {
682
- logger.warn(`credential ${credHash}: node UTxO query failed, answering from the crawled set: ${err?.message ?? err}`);
731
+ logger.warn(`unspent check of ${rows.length} crawled outputs failed, answering as of the cursor: ${err?.message ?? err}`);
732
+ return rows;
683
733
  }
684
- return this.ledgerUtxosOf(tx, addresses);
685
734
  }
686
735
  /** Unspent `LedgerUTxOs` (+ assets) of the given addresses in the provider UTxO shape. */
687
736
  async ledgerUtxosOf(tx, addresses) {
@@ -905,6 +954,8 @@ class CardanoIndexer {
905
954
  * atomically. Bare chain-sync inputs are backfilled by resolveInputs() first.
906
955
  */
907
956
  async indexBlockFull(tx, blockData, txs) {
957
+ // Memo updates of a rolled-back attempt must not survive into this one.
958
+ this.pendingCommit = [];
908
959
  // Epoch from the prefetched memo; if the caller skipped prefetchCrawlEpoch, resolve now
909
960
  // (memoized) and accept the in-tx fetch.
910
961
  let epoch;
@@ -913,14 +964,36 @@ class CardanoIndexer {
913
964
  epoch = this.crawlEpochCache.get(blockData.epoch)?.row;
914
965
  const epochRows = [...this.crawlEpochCache.values()]
915
966
  .map((entry) => entry.row)
916
- .filter((row) => row !== undefined);
917
- if (epochRows.length)
967
+ .filter((row) => row !== undefined && !this.crawlEpochWritten.has(row));
968
+ if (epochRows.length) {
918
969
  await tx.run(UPSERT.into(CardanoODataService_1.Epoch).entries(epochRows));
970
+ this.pendingCommit.push(() => { for (const row of epochRows)
971
+ this.crawlEpochWritten.add(row); });
972
+ }
919
973
  }
974
+ // Ledger state (crawler.utxoSet): only blocks AFTER the anchor the imported set describes.
975
+ // Decided up front so input resolution and the ledger apply share one read of the set.
976
+ const ledgerDue = this.crawlUtxoSet && this.utxoAnchor != null && (blockData.slot ?? 0) > this.utxoAnchor.slot;
977
+ const priorInvalidation = ledgerDue ? this.ledgerInvalidation : null;
978
+ let anchorVerified = false;
979
+ if (ledgerDue && !priorInvalidation) {
980
+ anchorVerified = this.utxoAnchorVerified;
981
+ if (!anchorVerified) {
982
+ const anchor = this.utxoAnchor;
983
+ anchorVerified = await this.verifyUtxoAnchor(tx, anchor);
984
+ // Remembered only once this transaction commits, like the other crawl memos.
985
+ if (anchorVerified)
986
+ this.pendingCommit.push(() => { if (this.utxoAnchor === anchor)
987
+ this.utxoAnchorVerified = true; });
988
+ }
989
+ }
990
+ const ledgerLookup = anchorVerified
991
+ ? { hashes: new Set(), rows: new Map(), assets: new Map() }
992
+ : undefined;
920
993
  // Backfill chain-sync inputs (empty address/amount) from local outputs, then settle
921
994
  // the fee of any phase-2 failure. Both run before the block row is written, because a
922
995
  // corrected fee changes the block's fee total.
923
- await this.resolveInputs(tx, txs);
996
+ await this.resolveInputs(tx, txs, ledgerLookup);
924
997
  this.applyCollateralFees(blockData, txs);
925
998
  await tx.run(UPSERT.into(CardanoODataService_1.Block).entries((0, mappers_1.mapBlock)(blockData, epoch)));
926
999
  await this.removeSupersededBlocks(tx, blockData);
@@ -943,6 +1016,8 @@ class CardanoIndexer {
943
1016
  : [];
944
1017
  if (this.crawlCertificates)
945
1018
  this.warnIfCertificatesUnreported(txs);
1019
+ // Redeemers come with the block on chain-sync; keyed (tx, purpose, index) like the certificates.
1020
+ const redeemerRows = txs.flatMap(t => (0, mappers_1.mapTransactionRedeemers)(t.hash, t.redeemers ?? []));
946
1021
  // Mint/burn is derived from rows already in hand — keyed (unit, txHash), so a re-crawl is
947
1022
  // idempotent and a reorg removes these rows with their transactions (crawler handleReorg).
948
1023
  const assetHistoryRows = this.crawlAssetHistory ? this.buildAssetHistoryRows(blockData, txs) : [];
@@ -962,16 +1037,17 @@ class CardanoIndexer {
962
1037
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionCertificates).entries(certificateRows));
963
1038
  if (withdrawalRows.length)
964
1039
  await tx.run(UPSERT.into(CardanoODataService_1.TransactionWithdrawals).entries(withdrawalRows));
965
- // Ledger state (crawler.utxoSet): only blocks AFTER the anchor the imported set describes;
966
- // same transaction, so the UTxO set can never be a block ahead of or behind the cursor.
967
- if (this.crawlUtxoSet && this.utxoAnchor && (blockData.slot ?? 0) > this.utxoAnchor.slot) {
968
- if (this.ledgerInvalidation) {
1040
+ if (redeemerRows.length)
1041
+ await tx.run(UPSERT.into(CardanoODataService_1.TransactionRedeemers).entries(redeemerRows));
1042
+ // Same transaction, so the UTxO set can never be a block ahead of or behind the cursor.
1043
+ if (ledgerDue) {
1044
+ if (priorInvalidation) {
969
1045
  // Decided in an earlier attempt of this block whose transaction rolled back: re-write
970
1046
  // the verdict so whichever attempt commits carries it; nothing is applied meanwhile.
971
- await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: this.ledgerInvalidation.slice(0, 500) });
1047
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: priorInvalidation.slice(0, 500) });
972
1048
  }
973
- else if (this.utxoAnchorVerified || (this.utxoAnchorVerified = await this.verifyUtxoAnchor(tx, this.utxoAnchor))) {
974
- const ledger = await (0, ledger_state_1.applyBlockToLedger)(tx, blockData, txs);
1049
+ else if (ledgerLookup) {
1050
+ const ledger = await (0, ledger_state_1.applyBlockToLedger)(tx, blockData, txs, ledgerLookup);
975
1051
  if (ledger.missing) {
976
1052
  logger.warn(`ledger: block ${blockData.hash} consumed ${ledger.missing} outpoint(s) with no open row — ` +
977
1053
  'the set is incomplete relative to the crawl (snapshot gap?); balances of those addresses drift');
@@ -1038,16 +1114,16 @@ class CardanoIndexer {
1038
1114
  'the crawl runs on Ogmios chain-sync or Koios');
1039
1115
  }
1040
1116
  /**
1041
- * Backfill address/amount of bare chain-sync inputs: from this block's own outputs first,
1042
- * then earlier-indexed outputs from the DB. Inputs that already carry an address are skipped.
1117
+ * Backfill address, amount and datum/script fields of bare chain-sync inputs: from this block's
1118
+ * own outputs first, then the UTxO set, then earlier-indexed outputs from the DB. Inputs that
1119
+ * already carry an address are skipped.
1043
1120
  */
1044
- async resolveInputs(tx, txs) {
1045
- // 1. In-memory index of this block's outputs (txHash#outputIndex -> {address, amount})
1121
+ async resolveInputs(tx, txs, ledger) {
1122
+ // 1. In-memory index of this block's outputs (txHash#outputIndex -> output)
1046
1123
  const blockOutputs = new Map();
1047
1124
  for (const t of txs) {
1048
- for (const o of t.outputs ?? []) {
1049
- blockOutputs.set(`${t.hash}#${o.outputIndex}`, { address: o.address, amount: o.amount ?? [] });
1050
- }
1125
+ for (const o of t.outputs ?? [])
1126
+ blockOutputs.set(`${t.hash}#${o.outputIndex}`, o);
1051
1127
  }
1052
1128
  // 2. Collect inputs still needing resolution after the same-block pass
1053
1129
  const unresolved = [];
@@ -1059,7 +1135,8 @@ class CardanoIndexer {
1059
1135
  const local = blockOutputs.get(key);
1060
1136
  if (local) {
1061
1137
  input.address = local.address;
1062
- input.amount = local.amount;
1138
+ input.amount = local.amount ?? [];
1139
+ copyUtxoData(input, local.dataHash, local.inlineDatum, local.referenceScriptHash);
1063
1140
  }
1064
1141
  else {
1065
1142
  unresolved.push({ input, key });
@@ -1068,7 +1145,23 @@ class CardanoIndexer {
1068
1145
  }
1069
1146
  if (!unresolved.length)
1070
1147
  return;
1071
- // 3. Batch-read prior-block outputs from the DB, chunked so a dense block's input set
1148
+ // 3. With the ledger due for this block, its UTxO rows answer first; the ledger apply
1149
+ // reuses the same lookup instead of reading these outpoints a second time.
1150
+ if (ledger) {
1151
+ await (0, ledger_state_1.readLedgerOutputs)(tx, unresolved.map(u => u.input.txHash), ledger);
1152
+ for (let i = unresolved.length - 1; i >= 0; i--) {
1153
+ const row = ledger.rows.get(unresolved[i].key);
1154
+ if (!row)
1155
+ continue;
1156
+ unresolved[i].input.address = row.address;
1157
+ unresolved[i].input.amount = (0, ledger_state_1.ledgerRowAmount)(row, ledger.assets.get(unresolved[i].key));
1158
+ copyUtxoData(unresolved[i].input, row.utxo_dataHash, row.utxo_inlineDatum, row.utxo_referenceScriptHash);
1159
+ unresolved.splice(i, 1);
1160
+ }
1161
+ if (!unresolved.length)
1162
+ return;
1163
+ }
1164
+ // 4. Batch-read prior-block outputs from the DB, chunked so a dense block's input set
1072
1165
  // never exceeds a driver's bind-variable cap
1073
1166
  const sourceHashes = [...new Set(unresolved.map(u => u.input.txHash))];
1074
1167
  const hashBySeq = new Map();
@@ -1076,7 +1169,7 @@ class CardanoIndexer {
1076
1169
  if (k.txSeq != null)
1077
1170
  hashBySeq.set((0, transaction_rows_1.seqKey)(k.txSeq), k.hash);
1078
1171
  }
1079
- const addrByKey = new Map();
1172
+ const outByKey = new Map();
1080
1173
  const amtByKey = new Map();
1081
1174
  for (const seqChunk of (0, collections_1.chunk)([...hashBySeq.keys()].map(Number), collections_1.IN_CHUNK)) {
1082
1175
  const [outRows, assetRows] = await Promise.all([
@@ -1084,7 +1177,7 @@ class CardanoIndexer {
1084
1177
  tx.run(SELECT.from(CardanoODataService_1.TransactionOutputAssets).where({ output_txSeq: { in: seqChunk } })),
1085
1178
  ]);
1086
1179
  for (const r of outRows) {
1087
- addrByKey.set(`${hashBySeq.get((0, transaction_rows_1.seqKey)(r.txSeq))}#${r.outputIndex}`, r.address_address);
1180
+ outByKey.set(`${hashBySeq.get((0, transaction_rows_1.seqKey)(r.txSeq))}#${r.outputIndex}`, r);
1088
1181
  }
1089
1182
  for (const r of assetRows) {
1090
1183
  const k = `${hashBySeq.get((0, transaction_rows_1.seqKey)(r.output_txSeq))}#${r.output_outputIndex}`;
@@ -1094,9 +1187,11 @@ class CardanoIndexer {
1094
1187
  }
1095
1188
  }
1096
1189
  for (const { input, key } of unresolved) {
1097
- const addr = addrByKey.get(key);
1098
- if (addr != null)
1099
- input.address = addr;
1190
+ const out = outByKey.get(key);
1191
+ if (out?.address_address != null)
1192
+ input.address = out.address_address;
1193
+ if (out)
1194
+ copyUtxoData(input, out.utxo_dataHash, out.utxo_inlineDatum, out.utxo_referenceScriptHash);
1100
1195
  const amt = amtByKey.get(key);
1101
1196
  if (amt)
1102
1197
  input.amount = amt;
@@ -1231,9 +1326,10 @@ class CardanoIndexer {
1231
1326
  for (const rowChunk of (0, collections_1.chunk)(rows, collections_1.IN_CHUNK)) {
1232
1327
  await tx.run(UPSERT.into(cardano_1.Assets).entries(rowChunk));
1233
1328
  }
1234
- // Memoize also the units mapBareAsset rejected, so they cost no SELECT per block.
1235
- for (const unit of missing)
1236
- this.noteAssetSeen(unit);
1329
+ // Memoize also the units mapBareAsset rejected, so they cost no SELECT per block. Only after
1330
+ // the commit: a rolled-back block must write its bare rows again.
1331
+ this.pendingCommit.push(() => { for (const unit of missing)
1332
+ this.noteAssetSeen(unit); });
1237
1333
  if (this.crawlAssetCatalogue === 'enrich' && rows.length) {
1238
1334
  for (const row of rows) {
1239
1335
  if (this.enrichQueue.length >= CardanoIndexer.ENRICH_QUEUE_CAP)
@@ -1406,19 +1502,20 @@ class CardanoIndexer {
1406
1502
  const accountInfo = await this.resolveAccount(tx, stakeAddress);
1407
1503
  const accountEntity = (0, mappers_1.mapAccount)(accountInfo, this.client.max_age_ms);
1408
1504
  await tx.run(UPSERT.into(CardanoODataService_1.Accounts).entries(accountEntity));
1409
- const addresses = accountInfo.addresses.map(a => a.address);
1410
1505
  if (accountEntity.hasAddresses) {
1411
- await this._ensureAddresses(tx, addresses);
1506
+ await this._ensureAddresses(tx, accountInfo.addresses);
1412
1507
  }
1413
1508
  return accountEntity;
1414
1509
  }
1415
1510
  /** Account from the backend with the crawled overlays (controlled amount, withdrawals). */
1416
1511
  async resolveAccount(tx, stakeAddress) {
1417
1512
  const accountInfo = { ...(await this.client.getAccount(stakeAddress)) };
1418
- // controlled amount = UTxOs under the stake key (crawled set, when current) + reward balance
1513
+ // controlled amount = UTxOs under the stake key (crawled set, when current) + reward balance;
1514
+ // the addresses come from the set too (the node has no stake-key -> address index)
1419
1515
  if ((await this.localCoverage(tx))?.ledger) {
1420
1516
  const ledger = await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAccounts).columns('controlledAmount').where({ stakeAddress }));
1421
1517
  accountInfo.controlledAmount = (BigInt(lovelaceSum(ledger?.controlledAmount)) + BigInt(accountInfo.withdrawableAmount || '0')).toString();
1518
+ accountInfo.addresses = await this.localAccountAddresses(tx, stakeAddress);
1422
1519
  }
1423
1520
  if (accountInfo.withdrawalsSum === '0') {
1424
1521
  const local = await this.localWithdrawalsSum(tx, stakeAddress);
@@ -1484,6 +1581,10 @@ class CardanoIndexer {
1484
1581
  const outputRows = (0, mappers_1.mapBuildOutputs)(buildResult.id, txbuildResult.outputs, buildreq.changeAddress || buildreq.senderAddress);
1485
1582
  await tx.run(UPSERT.into(CardanoTransactionService_1.TransactionBuildOutputs).entries(outputRows));
1486
1583
  }
1584
+ if (buildResult.id && txbuildResult.redeemers && txbuildResult.redeemers.length > 0) {
1585
+ const buildId = buildResult.id;
1586
+ 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) }))));
1587
+ }
1487
1588
  if (buildResult.id && buildreq.senderAddress) {
1488
1589
  await this.indexAddressTransactionBuilds(tx, buildreq.senderAddress, buildResult.id);
1489
1590
  }
@@ -1504,6 +1605,10 @@ class CardanoIndexer {
1504
1605
  async indexPlutusSpendBuildResult(tx, buildreq) {
1505
1606
  return this._indexBuildResult(tx, buildreq, (req, params) => this.txBuilder.buildPlutusSpendTransaction(req, params));
1506
1607
  }
1608
+ /** BuildPlutusTransaction: several script inputs; the redeemers are stored with the build. */
1609
+ async indexPlutusBuildResult(tx, buildreq) {
1610
+ return this._indexBuildResult(tx, buildreq, (req, params) => this.txBuilder.buildPlutusTransaction(req, params));
1611
+ }
1507
1612
  /** Protocol parameters, served from the DB row within a 5-minute TTL. */
1508
1613
  async indexProtocolParameters(tx) {
1509
1614
  const network = this.client.network;
@@ -1713,12 +1818,16 @@ class CardanoIndexer {
1713
1818
  //-----------------------------------------------------------------------------
1714
1819
  // Private Helpers
1715
1820
  //-----------------------------------------------------------------------------
1716
- /** Index addresses with bounded concurrency. */
1717
- async _ensureAddresses(tx, bech32List) {
1821
+ /**
1822
+ * Index the addresses of an account with bounded concurrency. The address data the account
1823
+ * carries (from the backend, or from the crawled set) is used as is, so an account costs no
1824
+ * request per address; an entry without UTxOs is fetched.
1825
+ */
1826
+ async _ensureAddresses(tx, accountAddresses) {
1718
1827
  const concurrency = CardanoIndexer.ADDR_CONCURRENCY;
1719
- for (let i = 0; i < bech32List.length; i += concurrency) {
1720
- const chunk = bech32List.slice(i, i + concurrency);
1721
- await Promise.all(chunk.map(addr => this.indexAddress(tx, addr)));
1828
+ for (let i = 0; i < accountAddresses.length; i += concurrency) {
1829
+ const chunk = accountAddresses.slice(i, i + concurrency);
1830
+ await Promise.all(chunk.map(a => this.indexAddress(tx, a.address, Array.isArray(a.utxos) ? a : undefined)));
1722
1831
  }
1723
1832
  }
1724
1833
  }
@@ -1,5 +1,6 @@
1
1
  import type { CardanoClient } from './cardano-client';
2
- import type { TxBuildRequest, TxBuildResult, LedgerProtocolParameters } from '../utils/types';
2
+ import type { UTxO } from '../utils/types';
3
+ import type { TxBuildRequest, TxBuildPlutusRequest, TxBuildResult, LedgerProtocolParameters } from '../utils/types';
3
4
  import type { CardanoTxBuilder } from './transaction-building/cardano-tx';
4
5
  import { LedgerProtocolParameter } from '#cds-models/CardanoODataService';
5
6
  /** High-level transaction builder delegating to the Buildooor `CardanoTxBuilder`. */
@@ -9,6 +10,10 @@ export declare class CardanoTransactionBuilder {
9
10
  private initialized;
10
11
  /** @param client UTxO source for coin selection */
11
12
  constructor(client: CardanoClient);
13
+ /** Unspent outputs of an address from local data (the crawled UTxO set); null = it cannot answer. */
14
+ private addressUtxoSource;
15
+ /** Read sender UTxOs from `source` first; the node's address query is the fallback. */
16
+ setAddressUtxoSource(source: (address: string) => Promise<UTxO[] | null>): void;
12
17
  /** @param protocolParams optional; fetched from the backend when omitted */
13
18
  init(protocolParams?: LedgerProtocolParameters): Promise<void>;
14
19
  /** Lazily initialize and return the builder. */
@@ -27,6 +32,11 @@ export declare class CardanoTransactionBuilder {
27
32
  buildMintTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
28
33
  /** Build a Plutus spending transaction (consume a UTxO at a script address). */
29
34
  buildPlutusSpendTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
35
+ /**
36
+ * Several script inputs in one transaction: resolve every script UTxO and every reference-script
37
+ * UTxO (one ledger lookup each), plus the sender's UTxOs, forced and reference inputs.
38
+ */
39
+ buildPlutusTransaction(req: TxBuildPlutusRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
30
40
  /**
31
41
  * Resolve the script UTxO of a Plutus spend from the node's ledger, otherwise from its producing
32
42
  * transaction. Spending an already-consumed script UTxO is the most common replay mistake —
@@ -18,6 +18,12 @@ class CardanoTransactionBuilder {
18
18
  this.client = client;
19
19
  logger.debug('CardanoTransactionBuilder instance created');
20
20
  }
21
+ /** Unspent outputs of an address from local data (the crawled UTxO set); null = it cannot answer. */
22
+ addressUtxoSource = null;
23
+ /** Read sender UTxOs from `source` first; the node's address query is the fallback. */
24
+ setAddressUtxoSource(source) {
25
+ this.addressUtxoSource = source;
26
+ }
21
27
  /** @param protocolParams optional; fetched from the backend when omitted */
22
28
  async init(protocolParams) {
23
29
  if (this.initialized && this.txBuilder)
@@ -168,12 +174,41 @@ class CardanoTransactionBuilder {
168
174
  logger.debug(`Built Plutus spending transaction successfully.`);
169
175
  return txBuildResult;
170
176
  }
177
+ /**
178
+ * Several script inputs in one transaction: resolve every script UTxO and every reference-script
179
+ * UTxO (one ledger lookup each), plus the sender's UTxOs, forced and reference inputs.
180
+ */
181
+ async buildPlutusTransaction(req, protocolParameters) {
182
+ const builder = await this.ensureInitialized();
183
+ const cardanoClient = this.client;
184
+ const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
185
+ const scriptUtxos = await this._resolveInputRefs(req.scriptInputs.map(s => ({ txHash: s.txHash, outputIndex: s.outputIndex })), senderUtxos, 'scriptInput');
186
+ const allUtxos = mergeUtxosUnique(senderUtxos, scriptUtxos);
187
+ const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], allUtxos);
188
+ // Reference-script UTxOs always from the ledger: a known sender UTxO may carry only the script hash
189
+ const refScriptUtxos = await this._resolveInputRefs(req.scriptInputs.flatMap(s => (s.referenceScript ? [s.referenceScript] : [])), [], 'referenceScript');
190
+ const callerRefUtxos = await this._resolveReferenceInputs(req.referenceInputs ?? [], allUtxos);
191
+ const referenceInputUtxos = mergeUtxosUnique(callerRefUtxos, refScriptUtxos);
192
+ const txContext = {
193
+ utxos: mergeUtxosUnique(allUtxos, forcedUtxos),
194
+ protocolParameters,
195
+ evaluateTransaction: cardanoClient.hasEvaluatingBackend()
196
+ ? (cbor) => cardanoClient.evaluateTransaction(cbor)
197
+ : undefined,
198
+ referenceInputUtxos: referenceInputUtxos.length > 0 ? referenceInputUtxos : undefined,
199
+ };
200
+ logger.debug(`Prepared multi-script build context: ${senderUtxos.length} sender + ${scriptUtxos.length} script + ${forcedUtxos.length} forced UTxOs, ${referenceInputUtxos.length} reference inputs`);
201
+ return builder.buildUnsignedPlutusTransaction(req, txContext);
202
+ }
171
203
  /**
172
204
  * Resolve the script UTxO of a Plutus spend from the node's ledger, otherwise from its producing
173
205
  * transaction. Spending an already-consumed script UTxO is the most common replay mistake —
174
206
  * both paths reject it with a clear 400 instead of a node-side rejection at submit.
175
207
  */
176
208
  async _resolveScriptUtxo(scriptRef) {
209
+ const by = this.client.pendingSpends?.spentBy(scriptRef.txHash, scriptRef.outputIndex);
210
+ if (by)
211
+ throw new errors_1.TransactionValidationError(`scriptUtxo ${outRefKey(scriptRef)} is spent by transaction ${by}, submitted and not yet on chain`);
177
212
  const ledger = await this._lookupUnspent([scriptRef]);
178
213
  if (ledger) {
179
214
  const live = ledger.get(outRefKey(scriptRef));
@@ -257,6 +292,11 @@ class CardanoTransactionBuilder {
257
292
  async _resolveInputRefs(refs, knownUtxos, kind) {
258
293
  if (!refs || refs.length === 0)
259
294
  return [];
295
+ for (const r of refs) {
296
+ const by = this.client.pendingSpends?.spentBy(r.txHash, r.outputIndex);
297
+ if (by)
298
+ throw new errors_1.TransactionValidationError(`${kind} ${r.txHash}#${r.outputIndex} is spent by transaction ${by}, submitted and not yet on chain`);
299
+ }
260
300
  // Dedup by "txHash#index" key
261
301
  const seen = new Set();
262
302
  const dedupedRefs = refs.filter(r => {
@@ -315,10 +355,25 @@ class CardanoTransactionBuilder {
315
355
  /** Fetch the UTxOs of an address; throws InsufficientFundsError when it has none. */
316
356
  async _fetchUtxosForAddress(address) {
317
357
  logger.debug(`Fetching UTxOs for address: ${address}`);
318
- const utxos = await this.client.getAddressUtxos(address);
358
+ // The crawled set answers with an index lookup; the node's address query scans its whole
359
+ // UTxO set. An empty answer from the set is re-checked there (funded in the last block).
360
+ const local = await this.addressUtxoSource?.(address).catch((err) => {
361
+ logger.warn(`Local UTxO lookup for ${address} failed, asking the node: ${err instanceof Error ? err.message : String(err)}`);
362
+ return null;
363
+ });
364
+ const ledger = local && local.length > 0 ? local : await this.client.getAddressUtxos(address);
365
+ // the ledger view still lists what our own submitted transactions spend while they wait in the mempool
366
+ const all = this.client.pendingSpends?.apply(address, ledger) ?? ledger;
367
+ // A UTxO carrying a reference script is deployed on purpose, not change to spend; only a
368
+ // forced input consumes it (the fee of a spent reference script is also not counted by the builder).
369
+ const utxos = all.filter(u => !u.scriptRef && !u.scriptRefCbor);
370
+ if (utxos.length < all.length)
371
+ logger.debug(`${all.length - utxos.length} UTxO(s) with a reference script left out of coin selection`);
319
372
  logger.debug(`Found ${utxos.length} UTxOs for address ${address.substring(0, 20)}...`);
320
373
  if (utxos.length === 0) {
321
- throw new errors_1.InsufficientFundsError('lovelace', BigInt(0), BigInt(0), undefined, `address ${address} has no UTxOs — verify this is the correct sender address and that it has been funded`);
374
+ throw new errors_1.InsufficientFundsError('lovelace', BigInt(0), BigInt(0), undefined, all.length > 0
375
+ ? `address ${address} holds only UTxOs with a reference script — they are not spent as funding; pass one in forceInputsJson to consume it`
376
+ : `address ${address} has no UTxOs — verify this is the correct sender address and that it has been funded`);
322
377
  }
323
378
  return utxos;
324
379
  }
@@ -1,6 +1,7 @@
1
1
  import type { Transaction as CapTransaction } from '@sap/cds';
2
2
  import type { CardanoClient } from '../cardano-client';
3
3
  import type { ChainPoint } from '../backends/cardano-backend';
4
+ import type { BlockData, Transaction } from '../../utils/types';
4
5
  /**
5
6
  * Fills `TransactionCertificates` and `TransactionWithdrawals` for blocks the crawl already
6
7
  * holds, from a second chain-sync stream. Only those two tables are written, keyed so a
@@ -41,5 +42,26 @@ export interface CertificateBackfillResult extends CertificateBackfillProgress {
41
42
  * they may lie far back or on a fork the node no longer knows.
42
43
  */
43
44
  export declare function intersectionBefore(db: CapTransaction, slot: number): Promise<ChainPoint | 'origin'>;
45
+ /** One streamed block of a backfill, with what the collector took from it. */
46
+ export interface StreamedBlock<T> {
47
+ hash: string;
48
+ slot: number;
49
+ transactions: number;
50
+ payload: T;
51
+ }
52
+ export interface CrawledBlockStreamOptions {
53
+ client: CardanoClient;
54
+ fromSlot: number;
55
+ toSlot: number;
56
+ batchBlocks?: number;
57
+ /** Error class the range and backend checks throw. */
58
+ errorType?: new (message: string) => Error;
59
+ }
60
+ /**
61
+ * Streams the crawled range `fromSlot..toSlot` over a second chain-sync connection and hands
62
+ * batches of blocks the index holds to `writeBatch`, each in its own DB transaction. A block
63
+ * the index does not know (rolled back since) is skipped. Returns the intersection used.
64
+ */
65
+ export declare function streamCrawledBlocks<T>(opts: CrawledBlockStreamOptions, collect: (block: BlockData, txs: Transaction[]) => T, writeBatch: (tx: CapTransaction, blocks: StreamedBlock<T>[]) => Promise<void>, afterBatch: (toSlot: number) => void): Promise<ChainPoint | 'origin'>;
44
66
  export declare function backfillCertificates(opts: CertificateBackfillOptions): Promise<CertificateBackfillResult>;
45
67
  //# sourceMappingURL=certificate-backfill.d.ts.map