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

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 (78) 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/README.md +195 -195
  14. package/db/schema.cds +74 -3
  15. package/db/types.cds +27 -0
  16. package/package.json +182 -182
  17. package/srv/blockchain/backends/blockfrost-backend.js +4 -2
  18. package/srv/blockchain/backends/cardano-backend.d.ts +0 -2
  19. package/srv/blockchain/backends/koios-backend.d.ts +1 -1
  20. package/srv/blockchain/backends/koios-backend.js +61 -14
  21. package/srv/blockchain/backends/odatano-backend.d.ts +5 -0
  22. package/srv/blockchain/backends/odatano-backend.js +12 -0
  23. package/srv/blockchain/backends/ogmios-backend.d.ts +12 -2
  24. package/srv/blockchain/backends/ogmios-backend.js +91 -21
  25. package/srv/blockchain/cardano-client.d.ts +11 -5
  26. package/srv/blockchain/cardano-client.js +51 -16
  27. package/srv/blockchain/cardano-indexer.d.ts +43 -15
  28. package/srv/blockchain/cardano-indexer.js +177 -68
  29. package/srv/blockchain/cardano-tx-builder.d.ts +11 -1
  30. package/srv/blockchain/cardano-tx-builder.js +57 -2
  31. package/srv/blockchain/crawler/certificate-backfill.d.ts +22 -0
  32. package/srv/blockchain/crawler/certificate-backfill.js +49 -30
  33. package/srv/blockchain/crawler/crawler.d.ts +3 -1
  34. package/srv/blockchain/crawler/crawler.js +12 -7
  35. package/srv/blockchain/crawler/sync-state.d.ts +3 -1
  36. package/srv/blockchain/crawler/sync-state.js +15 -2
  37. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  38. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  39. package/srv/blockchain/crawler/utxo-set-import.d.ts +9 -0
  40. package/srv/blockchain/crawler/utxo-set-import.js +138 -47
  41. package/srv/blockchain/ledger-state.d.ts +16 -1
  42. package/srv/blockchain/ledger-state.js +38 -18
  43. package/srv/blockchain/pending-spends.d.ts +28 -0
  44. package/srv/blockchain/pending-spends.js +89 -0
  45. package/srv/blockchain/stored-chain.d.ts +5 -2
  46. package/srv/blockchain/stored-chain.js +31 -5
  47. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +12 -3
  48. package/srv/blockchain/transaction-building/buildooor-tx.js +203 -21
  49. package/srv/blockchain/transaction-building/cardano-tx.d.ts +2 -1
  50. package/srv/blockchain/transaction-rows.d.ts +1 -1
  51. package/srv/blockchain/transaction-rows.js +2 -1
  52. package/srv/blockchain/wallet-worker/build-request.js +1 -1
  53. package/srv/cardano-backend-service.js +35 -8
  54. package/srv/cardano-indexer-service.cds +201 -176
  55. package/srv/cardano-indexer-service.js +104 -10
  56. package/srv/cardano-service.cds +5 -0
  57. package/srv/cardano-service.js +3 -1
  58. package/srv/cardano-tx-service.cds +39 -0
  59. package/srv/cardano-tx-service.js +88 -14
  60. package/srv/server.js +4 -1
  61. package/srv/utils/agent-grants.js +1 -0
  62. package/srv/utils/const.d.ts +5 -0
  63. package/srv/utils/const.js +6 -1
  64. package/srv/utils/error-codes.d.ts +2 -0
  65. package/srv/utils/error-codes.js +2 -0
  66. package/srv/utils/errors.d.ts +7 -0
  67. package/srv/utils/errors.js +11 -1
  68. package/srv/utils/mappers.d.ts +24 -2
  69. package/srv/utils/mappers.js +49 -0
  70. package/srv/utils/pg-inline-json.d.ts +8 -0
  71. package/srv/utils/pg-inline-json.js +63 -0
  72. package/srv/utils/tx-build-helper.d.ts +2 -0
  73. package/srv/utils/tx-build-helper.js +12 -0
  74. package/srv/utils/tx-request-parsers.d.ts +46 -5
  75. package/srv/utils/tx-request-parsers.js +227 -16
  76. package/srv/utils/types.d.ts +59 -0
  77. package/srv/utils/validators.d.ts +5 -1
  78. package/srv/utils/validators.js +19 -9
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.CertificateBackfillError = void 0;
7
7
  exports.intersectionBefore = intersectionBefore;
8
+ exports.streamCrawledBlocks = streamCrawledBlocks;
8
9
  exports.backfillCertificates = backfillCertificates;
9
10
  const cds_1 = __importDefault(require("@sap/cds"));
10
11
  const mappers_1 = require("../../utils/mappers");
@@ -42,23 +43,27 @@ async function intersectionBefore(db, slot) {
42
43
  return { slot: floor, hash: cursor.startBlockHash };
43
44
  return 'origin';
44
45
  }
45
- async function backfillCertificates(opts) {
46
+ /**
47
+ * Streams the crawled range `fromSlot..toSlot` over a second chain-sync connection and hands
48
+ * batches of blocks the index holds to `writeBatch`, each in its own DB transaction. A block
49
+ * the index does not know (rolled back since) is skipped. Returns the intersection used.
50
+ */
51
+ async function streamCrawledBlocks(opts, collect, writeBatch, afterBatch) {
46
52
  const { client, fromSlot, toSlot } = opts;
53
+ const Err = opts.errorType ?? CertificateBackfillError;
47
54
  if (!Number.isInteger(fromSlot) || !Number.isInteger(toSlot) || fromSlot < 0 || toSlot < fromSlot) {
48
- throw new CertificateBackfillError(`Invalid slot range ${fromSlot}..${toSlot}`);
55
+ throw new Err(`Invalid slot range ${fromSlot}..${toSlot}`);
49
56
  }
50
57
  const backend = client.getChainSyncBackend();
51
58
  if (!backend)
52
- throw new CertificateBackfillError('No chain-sync backend available (the backfill streams from Ogmios).');
59
+ throw new Err('No chain-sync backend available (the backfill streams from Ogmios).');
53
60
  const batchBlocks = Math.max(1, opts.batchBlocks ?? 200);
54
61
  const intersection = await cds_1.default.tx((tx) => intersectionBefore(tx, fromSlot));
55
62
  const points = intersection === 'origin' ? 'origin' : [intersection];
56
- const progress = { atSlot: intersection === 'origin' ? 0 : intersection.slot, blocks: 0, transactions: 0, certificates: 0, withdrawals: 0 };
57
63
  let pending = [];
58
64
  /**
59
65
  * Writes a batch: the index's blocks of the batch's slot range are read once (a sequential
60
- * index range, not one random lookup per block) and only rows of blocks the index holds
61
- * are written; a block it never had (rolled back since) is skipped.
66
+ * index range, not one random lookup per block) and only blocks the index holds are passed on.
62
67
  */
63
68
  const flush = async () => {
64
69
  if (!pending.length)
@@ -69,26 +74,15 @@ async function backfillCertificates(opts) {
69
74
  await cds_1.default.tx(async (tx) => {
70
75
  const rows = (await tx.run(SELECT.from(cardano_1.Block).columns('hash').where({ slot: { between: fromBatch, and: toBatch } })));
71
76
  const known = new Set(rows.map((r) => r.hash));
72
- const certs = [], withdrawals = [];
73
- for (const b of batch) {
74
- if (!known.has(b.hash)) {
75
- logger.warn(`Block ${b.hash} at slot ${b.slot} is not in the index — skipped`);
76
- continue;
77
- }
78
- certs.push(...b.certs);
79
- withdrawals.push(...b.withdrawals);
80
- progress.blocks++;
81
- progress.transactions += b.transactions;
82
- progress.certificates += b.certs.length;
83
- progress.withdrawals += b.withdrawals.length;
84
- }
85
- if (certs.length)
86
- await tx.run(UPSERT.into(cardano_1.TransactionCertificates).entries(certs));
87
- if (withdrawals.length)
88
- await tx.run(UPSERT.into(cardano_1.TransactionWithdrawals).entries(withdrawals));
77
+ const held = batch.filter((b) => {
78
+ if (known.has(b.hash))
79
+ return true;
80
+ logger.warn(`Block ${b.hash} at slot ${b.slot} is not in the index — skipped`);
81
+ return false;
82
+ });
83
+ await writeBatch(tx, held);
89
84
  });
90
- progress.atSlot = toBatch;
91
- opts.onProgress?.({ ...progress });
85
+ afterBatch(toBatch);
92
86
  };
93
87
  let handle = null;
94
88
  let settled = false;
@@ -112,11 +106,7 @@ async function backfillCertificates(opts) {
112
106
  }
113
107
  if (slot < fromSlot)
114
108
  return; // between the intersection and the range: skipped, not counted
115
- pending.push({
116
- hash: block.hash, slot, transactions: txs.length,
117
- certs: txs.flatMap((t) => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? [])),
118
- withdrawals: txs.flatMap((t) => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? [])),
119
- });
109
+ pending.push({ hash: block.hash, slot, transactions: txs.length, payload: collect(block, txs) });
120
110
  if (pending.length >= batchBlocks)
121
111
  await flush();
122
112
  if (slot === toSlot)
@@ -144,6 +134,35 @@ async function backfillCertificates(opts) {
144
134
  catch { /* best effort */ }
145
135
  }
146
136
  }
137
+ return intersection;
138
+ }
139
+ async function backfillCertificates(opts) {
140
+ const { fromSlot, toSlot } = opts;
141
+ const progress = { atSlot: 0, blocks: 0, transactions: 0, certificates: 0, withdrawals: 0 };
142
+ let started = false;
143
+ const intersection = await streamCrawledBlocks(opts, (_block, txs) => ({
144
+ certs: txs.flatMap((t) => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? [])),
145
+ withdrawals: txs.flatMap((t) => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? [])),
146
+ }), async (tx, blocks) => {
147
+ const certs = blocks.flatMap((b) => b.payload.certs);
148
+ const withdrawals = blocks.flatMap((b) => b.payload.withdrawals);
149
+ for (const b of blocks) {
150
+ progress.blocks++;
151
+ progress.transactions += b.transactions;
152
+ }
153
+ progress.certificates += certs.length;
154
+ progress.withdrawals += withdrawals.length;
155
+ if (certs.length)
156
+ await tx.run(UPSERT.into(cardano_1.TransactionCertificates).entries(certs));
157
+ if (withdrawals.length)
158
+ await tx.run(UPSERT.into(cardano_1.TransactionWithdrawals).entries(withdrawals));
159
+ }, (atSlot) => {
160
+ started = true;
161
+ progress.atSlot = atSlot;
162
+ opts.onProgress?.({ ...progress });
163
+ });
164
+ if (!started)
165
+ progress.atSlot = intersection === 'origin' ? 0 : intersection.slot;
147
166
  logger.info(`Certificate backfill ${fromSlot}..${toSlot}: ${progress.blocks} blocks, ${progress.certificates} certificates, ${progress.withdrawals} withdrawals`);
148
167
  return { ...progress, fromSlot, toSlot, intersection };
149
168
  }
@@ -115,6 +115,8 @@ export declare class CardanoCrawler {
115
115
  private snapshotRetryAfter;
116
116
  private leaseHeld;
117
117
  private leaseHeartbeat;
118
+ /** Last successful lease renewal by a block commit (epoch ms). */
119
+ private leaseRenewedAt;
118
120
  private leaseWake;
119
121
  constructor(client: CardanoClient, indexer: CardanoIndexer, network: string, config: CrawlerConfig,
120
122
  /** Present for production instances created by index.ts; omitted in engine unit tests. */
@@ -217,7 +219,7 @@ export declare class CardanoCrawler {
217
219
  * untouched), reset the cursor to the fork and write a CardanoReorgLog row.
218
220
  */
219
221
  private handleReorg;
220
- /** Renew the lease while an Ogmios stream is idle; block writes renew it transactionally. */
222
+ /** Renew the lease while no block commits; block writes renew it transactionally. */
221
223
  private startLeaseHeartbeat;
222
224
  /** Whether a persist error is deterministic for the block's data (see DATA_REJECTION_PATTERNS). */
223
225
  static isDataRejection(err: unknown): boolean;
@@ -101,6 +101,8 @@ class CardanoCrawler {
101
101
  snapshotRetryAfter = 0;
102
102
  leaseHeld = false;
103
103
  leaseHeartbeat = null;
104
+ /** Last successful lease renewal by a block commit (epoch ms). */
105
+ leaseRenewedAt = 0;
104
106
  leaseWake = null;
105
107
  constructor(client, indexer, network, config,
106
108
  /** Present for production instances created by index.ts; omitted in engine unit tests. */
@@ -735,18 +737,18 @@ class CardanoCrawler {
735
737
  return false;
736
738
  try {
737
739
  await cds_1.default.tx(async (tx) => {
738
- if (this.leaseOwner) {
739
- const renewed = await (0, sync_state_1.renewCrawlerLease)(tx, this.leaseOwner);
740
- if (!renewed)
741
- throw new CrawlerLeaseLostError();
742
- }
743
740
  await this.indexer.indexBlockFull(tx, block, txs);
744
741
  // Ledger progress marker: written in the same statement as the cursor, so "the
745
742
  // cursor is ahead of the marker" always means blocks went by without the set.
746
743
  const anchor = this.indexer.getUtxoAnchor();
747
744
  const ledgerApplied = anchor != null && (block.slot ?? 0) > anchor.slot;
748
- await (0, sync_state_1.advanceCursor)(tx, { slot: block.slot ?? 0, hash: block.hash, height: block.height ?? 0 }, tip ? { slot: tip.slot, height: tip.height } : undefined, isAtTip ? 'synced' : 'syncing', ledgerApplied ? { utxoAppliedSlot: block.slot ?? 0 } : undefined);
745
+ // The cursor UPDATE also renews and fences the lease; a lost lease rolls the block back.
746
+ const leaseHeld = await (0, sync_state_1.advanceCursor)(tx, { slot: block.slot ?? 0, hash: block.hash, height: block.height ?? 0 }, tip ? { slot: tip.slot, height: tip.height } : undefined, isAtTip ? 'synced' : 'syncing', ledgerApplied ? { utxoAppliedSlot: block.slot ?? 0 } : undefined, this.leaseOwner);
747
+ if (!leaseHeld)
748
+ throw new CrawlerLeaseLostError();
749
749
  });
750
+ this.leaseRenewedAt = Date.now();
751
+ this.indexer.confirmBlockCommit();
750
752
  if (CardanoCrawler.poison?.hash === block.hash)
751
753
  CardanoCrawler.poison = null;
752
754
  // A ledger invalidation decided inside the block transaction takes effect in memory
@@ -982,7 +984,7 @@ class CardanoCrawler {
982
984
  (0, hooks_1.emitReorg)({ forkSlot, forkHeight: emittedForkHeight, blocksRolledBack });
983
985
  logger.warn(`Reorg handled: rolled back ${blocksRolledBack} blocks (${txsRolledBack} txs) to slot ${forkSlot}`);
984
986
  }
985
- /** Renew the lease while an Ogmios stream is idle; block writes renew it transactionally. */
987
+ /** Renew the lease while no block commits; block writes renew it transactionally. */
986
988
  startLeaseHeartbeat() {
987
989
  if (!this.leaseOwner || this.leaseHeartbeat)
988
990
  return;
@@ -992,6 +994,9 @@ class CardanoCrawler {
992
994
  await this.leaseSleep(intervalMs);
993
995
  if (!this.running)
994
996
  return;
997
+ // Block commits renew the lease; the heartbeat only covers idle stretches.
998
+ if (Date.now() - this.leaseRenewedAt < intervalMs)
999
+ continue;
995
1000
  try {
996
1001
  const renewed = await cds_1.default.tx((tx) => (0, sync_state_1.renewCrawlerLease)(tx, this.leaseOwner));
997
1002
  if (!renewed) {
@@ -81,13 +81,15 @@ export declare function latchPoisonBlock(db: CapTransaction, message: string): P
81
81
  /**
82
82
  * Advance the cursor to a freshly indexed block, clear the error streak and optionally
83
83
  * record the latest known tip. Pass status 'synced' when the block is at the tip.
84
+ * With `leaseOwner` the same UPDATE renews and fences the crawler lease (see renewCrawlerLease).
85
+ * @returns false when the lease is no longer held; the caller must roll back
84
86
  */
85
87
  export declare function advanceCursor(db: CapTransaction, block: CrawlPoint, tip?: {
86
88
  slot: number;
87
89
  height?: number;
88
90
  }, status?: CrawlSyncStatusValue,
89
91
  /** Extra cursor columns written in the same statement (e.g. the ledger's `utxoAppliedSlot`). */
90
- extra?: Record<string, unknown>): Promise<void>;
92
+ extra?: Record<string, unknown>, leaseOwner?: string, now?: Date, ttlMs?: number): Promise<boolean>;
91
93
  /**
92
94
  * Lease for the UTxO set import, on the crawler's lease columns: a crawler start on any
93
95
  * instance and a second import are refused while it is held. Does not require `desiredRunning`.
@@ -229,10 +229,12 @@ async function latchPoisonBlock(db, message) {
229
229
  /**
230
230
  * Advance the cursor to a freshly indexed block, clear the error streak and optionally
231
231
  * record the latest known tip. Pass status 'synced' when the block is at the tip.
232
+ * With `leaseOwner` the same UPDATE renews and fences the crawler lease (see renewCrawlerLease).
233
+ * @returns false when the lease is no longer held; the caller must roll back
232
234
  */
233
235
  async function advanceCursor(db, block, tip, status = 'syncing',
234
236
  /** Extra cursor columns written in the same statement (e.g. the ledger's `utxoAppliedSlot`). */
235
- extra) {
237
+ extra, leaseOwner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
236
238
  const set = {
237
239
  lastSlot: block.slot,
238
240
  lastBlockHash: block.hash,
@@ -248,7 +250,18 @@ extra) {
248
250
  if (tip.height !== undefined)
249
251
  set.tipHeight = tip.height;
250
252
  }
251
- await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
253
+ if (!leaseOwner) {
254
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
255
+ return true;
256
+ }
257
+ set.leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
258
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({
259
+ ID: exports.SINGLETON_ID,
260
+ leaseOwner,
261
+ desiredRunning: true,
262
+ }));
263
+ const verified = await readCursor(db);
264
+ return leaseDeadlineReached(verified, leaseOwner, now.getTime() + ttlMs);
252
265
  }
253
266
  /**
254
267
  * Lease for the UTxO set import, on the crawler's lease columns: a crawler start on any
@@ -0,0 +1,52 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import type { CardanoClient } from '../cardano-client';
3
+ import type { ChainPoint } from '../backends/cardano-backend';
4
+ import type { Transaction } from '../../utils/types';
5
+ import type { LedgerLookup } from '../ledger-state';
6
+ /**
7
+ * Completes transactions the crawl already holds from a second chain-sync stream: input
8
+ * outpoints (spentTxHash / spentOutputIndex), the spent output's datum and reference-script
9
+ * hash, a missing input address, and the redeemers. Only empty input fields are filled; a
10
+ * transaction whose stored inputs do not line up with the stream is left as it is.
11
+ */
12
+ export declare class TransactionBackfillError extends Error {
13
+ constructor(message: string);
14
+ }
15
+ export interface TransactionBackfillProgress {
16
+ /** Slot of the last block handled. */
17
+ atSlot: number;
18
+ blocks: number;
19
+ transactions: number;
20
+ /** Input rows that got at least one field. */
21
+ inputs: number;
22
+ redeemers: number;
23
+ /** Transactions whose stored rows differed from the ledger view (order, inputs or outputs the ledger did not apply) and were rewritten. */
24
+ rewritten: number;
25
+ /** Transactions left as they are: stored inputs differ from the stream. */
26
+ skipped: number;
27
+ }
28
+ /** Resolves bare chain-sync inputs from the index (CardanoIndexer.resolveInputs). */
29
+ export interface InputResolver {
30
+ resolveInputs(tx: CapTransaction, txs: Transaction[], ledger?: LedgerLookup): Promise<void>;
31
+ }
32
+ export interface TransactionBackfillOptions {
33
+ client: CardanoClient;
34
+ indexer: InputResolver;
35
+ fromSlot: number;
36
+ toSlot: number;
37
+ batchBlocks?: number;
38
+ onProgress?: (p: TransactionBackfillProgress) => void;
39
+ }
40
+ export interface TransactionBackfillResult extends TransactionBackfillProgress {
41
+ fromSlot: number;
42
+ toSlot: number;
43
+ intersection: ChainPoint | 'origin';
44
+ }
45
+ /**
46
+ * One UPDATE per chunk: the fills travel as a JSON array and are joined on (txSeq, inputIndex).
47
+ * COALESCE keeps any value that is already there. Postgres and SQLite; other databases get one
48
+ * UPDATE per row.
49
+ */
50
+ export declare function inputFillStatement(kind: string): string | null;
51
+ export declare function backfillTransactions(opts: TransactionBackfillOptions): Promise<TransactionBackfillResult>;
52
+ //# sourceMappingURL=transaction-backfill.d.ts.map
@@ -0,0 +1,283 @@
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.TransactionBackfillError = void 0;
7
+ exports.inputFillStatement = inputFillStatement;
8
+ exports.backfillTransactions = backfillTransactions;
9
+ const cds_1 = __importDefault(require("@sap/cds"));
10
+ const mappers_1 = require("../../utils/mappers");
11
+ const collections_1 = require("../../utils/collections");
12
+ const certificate_backfill_1 = require("./certificate-backfill");
13
+ const cardano_1 = require("#cds-models/odatano/cardano");
14
+ const { SELECT, UPDATE, UPSERT, DELETE } = cds_1.default.ql;
15
+ const logger = cds_1.default.log('TransactionBackfill');
16
+ /**
17
+ * Completes transactions the crawl already holds from a second chain-sync stream: input
18
+ * outpoints (spentTxHash / spentOutputIndex), the spent output's datum and reference-script
19
+ * hash, a missing input address, and the redeemers. Only empty input fields are filled; a
20
+ * transaction whose stored inputs do not line up with the stream is left as it is.
21
+ */
22
+ class TransactionBackfillError extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = 'TransactionBackfillError';
26
+ }
27
+ }
28
+ exports.TransactionBackfillError = TransactionBackfillError;
29
+ const key = (txSeq, inputIndex) => `${Number(txSeq)}#${Number(inputIndex)}`;
30
+ const lovelaceOf = (i) => i.amount?.find((a) => a.unit === 'lovelace')?.quantity ?? null;
31
+ /**
32
+ * Stored input and streamed input describe the same outpoint: same flags, same outpoint where
33
+ * one is stored, same address and lovelace where both sides know them. A stored address the
34
+ * stream cannot resolve is unverifiable, so it does not match.
35
+ */
36
+ function sameInput(row, fresh, storedLovelace) {
37
+ if (Boolean(row.isCollateral) !== Boolean(fresh.isCollateral) || Boolean(row.isReference) !== Boolean(fresh.isReference))
38
+ return false;
39
+ if (row.spentTxHash != null) {
40
+ return row.spentTxHash === fresh.txHash && Number(row.spentOutputIndex) === fresh.outputIndex;
41
+ }
42
+ if (!row.address_address)
43
+ return true;
44
+ if (!fresh.address)
45
+ return false;
46
+ if (row.address_address !== fresh.address)
47
+ return false;
48
+ const freshLovelace = lovelaceOf(fresh);
49
+ return storedLovelace == null || freshLovelace == null || String(storedLovelace) === String(freshLovelace);
50
+ }
51
+ /**
52
+ * Stored rows in the stream's order when they hold the same outpoints with the same flags, each
53
+ * once; null otherwise (a row without outpoint cannot be placed).
54
+ */
55
+ function reorderByOutpoint(rows, fresh) {
56
+ if (rows.length !== fresh.length || rows.some((r) => r.spentTxHash == null))
57
+ return null;
58
+ const byOutpoint = new Map();
59
+ for (const r of rows) {
60
+ const k = `${r.spentTxHash}#${Number(r.spentOutputIndex)}#${Boolean(r.isCollateral)}#${Boolean(r.isReference)}`;
61
+ byOutpoint.set(k, [...(byOutpoint.get(k) ?? []), r]);
62
+ }
63
+ const ordered = [];
64
+ for (const f of fresh) {
65
+ const k = `${f.txHash}#${f.outputIndex}#${Boolean(f.isCollateral)}#${Boolean(f.isReference)}`;
66
+ const r = byOutpoint.get(k)?.shift();
67
+ if (!r)
68
+ return null;
69
+ ordered.push(r);
70
+ }
71
+ return ordered;
72
+ }
73
+ /** Columns of `row` that are empty and `fresh` can fill. */
74
+ function missingFields(row, fresh) {
75
+ const set = {};
76
+ if (row.spentTxHash == null && fresh.txHash) {
77
+ set.spentTxHash = fresh.txHash;
78
+ set.spentOutputIndex = fresh.outputIndex;
79
+ }
80
+ if (row.utxoData_dataHash == null && fresh.dataHash)
81
+ set.utxoData_dataHash = fresh.dataHash;
82
+ if (row.utxoData_inlineDatum == null && fresh.inlineDatum)
83
+ set.utxoData_inlineDatum = fresh.inlineDatum;
84
+ if (row.utxoData_referenceScriptHash == null && fresh.referenceScriptHash)
85
+ set.utxoData_referenceScriptHash = fresh.referenceScriptHash;
86
+ if (!row.address_address && fresh.address) {
87
+ set.address_address = fresh.address;
88
+ set.hasAddresses = true;
89
+ set.hasAssets = (fresh.amount ?? []).length > 0;
90
+ }
91
+ return set;
92
+ }
93
+ const INPUTS_TABLE = 'odatano_cardano_TransactionInputs';
94
+ /** Rows per statement; one JSON parameter each. */
95
+ const FILL_CHUNK = 5000;
96
+ /** Fill columns in the order the JSON records and the SET list use them. */
97
+ const FILL_COLUMNS = [
98
+ ['spentTxHash', 'text'],
99
+ ['spentOutputIndex', 'integer'],
100
+ ['utxoData_dataHash', 'text'],
101
+ ['utxoData_inlineDatum', 'text'],
102
+ ['utxoData_referenceScriptHash', 'text'],
103
+ ['address_address', 'text'],
104
+ ['hasAddresses', 'boolean'],
105
+ ['hasAssets', 'boolean'],
106
+ ];
107
+ /**
108
+ * One UPDATE per chunk: the fills travel as a JSON array and are joined on (txSeq, inputIndex).
109
+ * COALESCE keeps any value that is already there. Postgres and SQLite; other databases get one
110
+ * UPDATE per row.
111
+ */
112
+ function inputFillStatement(kind) {
113
+ const set = FILL_COLUMNS
114
+ .map(([c]) => c.startsWith('has')
115
+ ? `${c} = CASE WHEN v.address_address IS NOT NULL AND t.address_address IS NULL THEN v.${c} ELSE t.${c} END`
116
+ : `${c} = COALESCE(t.${c}, v.${c})`)
117
+ .join(', ');
118
+ if (kind === 'postgres') {
119
+ const cols = [['txSeq', 'bigint'], ['inputIndex', 'integer'], ...FILL_COLUMNS].map(([c, ty]) => `${c.toLowerCase()} ${ty}`).join(', ');
120
+ return `UPDATE ${INPUTS_TABLE} AS t SET ${set} FROM json_to_recordset($1::json) AS v(${cols}) ` +
121
+ 'WHERE t.txSeq = v.txseq AND t.inputIndex = v.inputindex';
122
+ }
123
+ if (kind === 'sqlite' || kind === 'better-sqlite') {
124
+ const cols = ['txSeq', 'inputIndex', ...FILL_COLUMNS.map(([c]) => c)]
125
+ .map((c) => `json_extract(value, '$.${c.toLowerCase()}') AS ${c}`).join(', ');
126
+ return `UPDATE ${INPUTS_TABLE} AS t SET ${set} FROM (SELECT ${cols} FROM json_each(?)) AS v ` +
127
+ 'WHERE t.txSeq = v.txSeq AND t.inputIndex = v.inputIndex';
128
+ }
129
+ return null;
130
+ }
131
+ /** Writes the fills of a batch: bulk statement where the database has one, else row by row. */
132
+ async function writeInputFills(tx, fills) {
133
+ if (!fills.length)
134
+ return;
135
+ const sql = inputFillStatement(cds_1.default.db?.kind ?? '');
136
+ if (!sql) {
137
+ for (const f of fills)
138
+ await tx.run(UPDATE.entity(cardano_1.TransactionInputs).set(f.set).where({ txSeq: f.txSeq, inputIndex: f.inputIndex }));
139
+ return;
140
+ }
141
+ for (const part of (0, collections_1.chunk)(fills, FILL_CHUNK)) {
142
+ const records = part.map((f) => {
143
+ const r = { txseq: f.txSeq, inputindex: f.inputIndex };
144
+ for (const [c] of FILL_COLUMNS)
145
+ r[c.toLowerCase()] = f.set[c] ?? null;
146
+ return r;
147
+ });
148
+ await tx.run(sql, [JSON.stringify(records)]);
149
+ }
150
+ }
151
+ /**
152
+ * Rewrites the input rows of one transaction as the ledger view: the kept rows (and their assets)
153
+ * move to their position, rows left out are dropped, empty fields are filled on the way.
154
+ */
155
+ async function rewriteInOrder(tx, seq, ordered, fresh) {
156
+ const assets = (await tx.run(SELECT.from(cardano_1.TransactionInputAssets).where({ input_txSeq: seq }))) ?? [];
157
+ const newIndex = new Map(ordered.map((r, i) => [Number(r.inputIndex), i]));
158
+ const rows = ordered.map((r, i) => ({ ...r, ...missingFields(r, fresh[i]), txSeq: seq, inputIndex: i }));
159
+ // assets of rows the ledger view drops go with them
160
+ const movedAssets = assets
161
+ .filter((a) => newIndex.has(Number(a.input_inputIndex)))
162
+ .map((a) => ({ ...a, input_txSeq: seq, input_inputIndex: newIndex.get(Number(a.input_inputIndex)) }));
163
+ await tx.run(DELETE.from(cardano_1.TransactionInputAssets).where({ input_txSeq: seq }));
164
+ await tx.run(DELETE.from(cardano_1.TransactionInputs).where({ txSeq: seq }));
165
+ await tx.run(UPSERT.into(cardano_1.TransactionInputs).entries(rows));
166
+ if (movedAssets.length)
167
+ await tx.run(UPSERT.into(cardano_1.TransactionInputAssets).entries(movedAssets));
168
+ }
169
+ /**
170
+ * Deletes stored outputs the ledger never produced: a provider lists the collateral return of a
171
+ * valid transaction, and the declared outputs of a phase-2 failure. Only when every output of the
172
+ * stream is stored, so a gap is never mistaken for an extra. Returns the transactions touched.
173
+ */
174
+ async function dropUnappliedOutputs(tx, txs) {
175
+ const wanted = new Map(txs.map((t) => [(0, mappers_1.txSeqOf)(t.slot, t.index), new Set((t.outputs ?? []).map((o) => o.outputIndex))]));
176
+ const stored = new Map();
177
+ for (const seqChunk of (0, collections_1.chunk)([...wanted.keys()], collections_1.IN_CHUNK)) {
178
+ const rows = (await tx.run(SELECT.from(cardano_1.TransactionOutputs).columns('txSeq', 'outputIndex').where({ txSeq: { in: seqChunk } })));
179
+ for (const r of rows ?? [])
180
+ stored.set(Number(r.txSeq), [...(stored.get(Number(r.txSeq)) ?? []), Number(r.outputIndex)]);
181
+ }
182
+ const touched = [];
183
+ for (const [seq, indices] of stored) {
184
+ const keep = wanted.get(seq);
185
+ const extra = indices.filter((i) => !keep.has(i));
186
+ if (!extra.length || [...keep].some((i) => !indices.includes(i)))
187
+ continue;
188
+ await tx.run(DELETE.from(cardano_1.TransactionOutputAssets).where({ output_txSeq: seq, output_outputIndex: { in: extra } }));
189
+ await tx.run(DELETE.from(cardano_1.TransactionOutputs).where({ txSeq: seq, outputIndex: { in: extra } }));
190
+ touched.push(seq);
191
+ }
192
+ return touched;
193
+ }
194
+ async function backfillTransactions(opts) {
195
+ const { fromSlot, toSlot, indexer } = opts;
196
+ const progress = { atSlot: 0, blocks: 0, transactions: 0, inputs: 0, redeemers: 0, rewritten: 0, skipped: 0 };
197
+ let started = false;
198
+ const intersection = await (0, certificate_backfill_1.streamCrawledBlocks)({ ...opts, errorType: TransactionBackfillError }, (_block, txs) => txs, async (tx, blocks) => {
199
+ const txs = blocks.flatMap((b) => b.payload);
200
+ progress.blocks += blocks.length;
201
+ progress.transactions += txs.length;
202
+ if (!txs.length)
203
+ return;
204
+ // the UTxO set rows answer too: they keep spent outputs, also those from before the crawl
205
+ await indexer.resolveInputs(tx, txs, { hashes: new Set(), rows: new Map(), assets: new Map() });
206
+ const seqs = txs.map((t) => (0, mappers_1.txSeqOf)(t.slot, t.index));
207
+ const stored = new Map();
208
+ const storedLovelace = new Map();
209
+ const storedCount = new Map();
210
+ const storedBySeq = new Map();
211
+ for (const seqChunk of (0, collections_1.chunk)(seqs, collections_1.IN_CHUNK)) {
212
+ const [rows, lovelace] = await Promise.all([
213
+ tx.run(SELECT.from(cardano_1.TransactionInputs).where({ txSeq: { in: seqChunk } })),
214
+ tx.run(SELECT.from(cardano_1.TransactionInputAssets).columns('input_txSeq', 'input_inputIndex', 'asset_quantity')
215
+ .where({ input_txSeq: { in: seqChunk }, unit: 'lovelace' })),
216
+ ]);
217
+ for (const r of rows ?? []) {
218
+ stored.set(key(r.txSeq, r.inputIndex), r);
219
+ storedCount.set(String(Number(r.txSeq)), (storedCount.get(String(Number(r.txSeq))) ?? 0) + 1);
220
+ storedBySeq.set(String(Number(r.txSeq)), [...(storedBySeq.get(String(Number(r.txSeq))) ?? []), r]);
221
+ }
222
+ for (const a of lovelace ?? [])
223
+ storedLovelace.set(key(a.input_txSeq, a.input_inputIndex), String(a.asset_quantity));
224
+ }
225
+ const fills = [];
226
+ const assetRows = [];
227
+ const reorders = [];
228
+ const rewritten = new Set();
229
+ for (const t of txs) {
230
+ const seq = (0, mappers_1.txSeqOf)(t.slot, t.index);
231
+ const inputs = t.inputs ?? [];
232
+ const rows = inputs.map((_, i) => stored.get(key(seq, i)));
233
+ const lines = (storedCount.get(String(seq)) ?? 0) === inputs.length && rows.every((r, i) => r && sameInput(r, inputs[i], storedLovelace.get(key(seq, i)) ?? null));
234
+ if (!lines) {
235
+ // after a phase-2 failure the ledger applied no regular input: rows a provider stored for them go
236
+ const all = [...(storedBySeq.get(String(seq)) ?? [])].sort((a, b) => Number(a.inputIndex) - Number(b.inputIndex));
237
+ const kept = t.spendsCollaterals ? all.filter((r) => r.isCollateral || r.isReference) : all;
238
+ const inPlace = kept.length === inputs.length &&
239
+ kept.every((r, i) => sameInput(r, inputs[i], storedLovelace.get(key(seq, Number(r.inputIndex))) ?? null));
240
+ const ordered = inPlace ? kept : reorderByOutpoint(kept, inputs);
241
+ if (ordered) {
242
+ reorders.push({ seq, rows: ordered, inputs });
243
+ rewritten.add(seq);
244
+ continue;
245
+ }
246
+ progress.skipped++;
247
+ logger.debug(`Transaction ${t.hash}: stored inputs differ from the stream — left as it is`);
248
+ continue;
249
+ }
250
+ for (let i = 0; i < inputs.length; i++) {
251
+ const set = missingFields(rows[i], inputs[i]);
252
+ if (!Object.keys(set).length)
253
+ continue;
254
+ fills.push({ txSeq: seq, inputIndex: i, set });
255
+ if (set.address_address)
256
+ assetRows.push(...(0, mappers_1.mapTransactionInputAssets)(seq, inputs).filter((a) => a.input_inputIndex === i));
257
+ }
258
+ }
259
+ await writeInputFills(tx, fills);
260
+ progress.inputs += fills.length;
261
+ if (assetRows.length)
262
+ await tx.run(UPSERT.into(cardano_1.TransactionInputAssets).entries(assetRows));
263
+ for (const r of reorders)
264
+ await rewriteInOrder(tx, r.seq, r.rows, r.inputs);
265
+ for (const seq of await dropUnappliedOutputs(tx, txs))
266
+ rewritten.add(seq);
267
+ progress.rewritten += rewritten.size;
268
+ const redeemerRows = txs.flatMap((t) => (0, mappers_1.mapTransactionRedeemers)(t.hash, t.redeemers ?? []));
269
+ progress.redeemers += redeemerRows.length;
270
+ if (redeemerRows.length)
271
+ await tx.run(UPSERT.into(cardano_1.TransactionRedeemers).entries(redeemerRows));
272
+ }, (atSlot) => {
273
+ started = true;
274
+ progress.atSlot = atSlot;
275
+ opts.onProgress?.({ ...progress });
276
+ });
277
+ if (!started)
278
+ progress.atSlot = intersection === 'origin' ? 0 : intersection.slot;
279
+ logger.info(`Transaction backfill ${fromSlot}..${toSlot}: ${progress.blocks} blocks, ${progress.inputs} inputs, ` +
280
+ `${progress.redeemers} redeemers, ${progress.rewritten} transactions rewritten, ${progress.skipped} skipped`);
281
+ return { ...progress, fromSlot, toSlot, intersection };
282
+ }
283
+ //# sourceMappingURL=transaction-backfill.js.map
@@ -66,4 +66,13 @@ export declare function aggregateStatements(): string[];
66
66
  * written; a failure mid-way leaves the set marked `invalid` (never half-`active`).
67
67
  */
68
68
  export declare function importUtxoSet(opts: UtxoSetImportOptions): Promise<UtxoSetImportResult>;
69
+ /**
70
+ * Rebuild only the sums (LedgerAddresses, LedgerAddressAssets, LedgerAccounts) from the rows an
71
+ * earlier import left at the stored anchor, e.g. after the aggregate phase failed. Nothing may have
72
+ * been applied since the anchor; a cursor past it is set back to the anchor, and the blocks after
73
+ * it are crawled again (idempotent writes) so the set follows them.
74
+ */
75
+ export declare function rebuildUtxoSetAggregates(opts: {
76
+ indexer: CardanoIndexer;
77
+ }): Promise<UtxoSetImportResult>;
69
78
  //# sourceMappingURL=utxo-set-import.d.ts.map