@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
@@ -9,6 +9,7 @@ exports.parseCliUtxoEntry = parseCliUtxoEntry;
9
9
  exports.readUtxoSetFile = readUtxoSetFile;
10
10
  exports.aggregateStatements = aggregateStatements;
11
11
  exports.importUtxoSet = importUtxoSet;
12
+ exports.rebuildUtxoSetAggregates = rebuildUtxoSetAggregates;
12
13
  const cds_1 = __importDefault(require("@sap/cds"));
13
14
  const node_fs_1 = require("node:fs");
14
15
  const promises_1 = require("node:fs/promises");
@@ -17,7 +18,7 @@ const ledger_state_1 = require("../ledger-state");
17
18
  const sync_state_1 = require("./sync-state");
18
19
  const cardano_1 = require("#cds-models/odatano/cardano");
19
20
  const collections_1 = require("../../utils/collections");
20
- const { UPSERT, DELETE } = cds_1.default.ql;
21
+ const { UPSERT, DELETE, SELECT } = cds_1.default.ql;
21
22
  const logger = cds_1.default.log('LedgerState');
22
23
  /**
23
24
  * One-off import of the UTxO set at the anchor `crawler.utxoSet` builds on: from Ogmios
@@ -144,11 +145,11 @@ function aggregateStatements() {
144
145
  `INSERT INTO ${T.addresses} (address, stakeAddress, addressType, isScript, totalLovelace, utxoCount, firstSeenSlot, lastActiveSlot) ` +
145
146
  `SELECT address, MIN(stakeAddress), MIN(addressType), ` +
146
147
  `CASE WHEN MAX(CASE WHEN isScript THEN 1 ELSE 0 END) = 1 THEN TRUE ELSE FALSE END, ` +
147
- `SUM(lovelace), COUNT(*), NULL, NULL FROM ${T.utxos} GROUP BY address`,
148
+ `SUM(lovelace), COUNT(*), NULL, NULL FROM ${T.utxos} WHERE spentTxHash IS NULL GROUP BY address`,
148
149
  `INSERT INTO ${T.addressAssets} (address_address, unit, asset_quantity, asset_policyId, asset_assetNameHex, asset_assetName) ` +
149
150
  `SELECT u.address, a.unit, SUM(a.asset_quantity), MIN(a.asset_policyId), MIN(a.asset_assetNameHex), MIN(a.asset_assetName) ` +
150
151
  `FROM ${T.utxoAssets} a JOIN ${T.utxos} u ON a.utxo_txHash = u.txHash AND a.utxo_outputIndex = u.outputIndex ` +
151
- `GROUP BY u.address, a.unit`,
152
+ `WHERE u.spentTxHash IS NULL GROUP BY u.address, a.unit`,
152
153
  `INSERT INTO ${T.accounts} (stakeAddress, controlledAmount, addressCount, utxoCount, lastActiveSlot) ` +
153
154
  `SELECT stakeAddress, SUM(totalLovelace), COUNT(*), SUM(utxoCount), NULL FROM ${T.addresses} ` +
154
155
  `WHERE stakeAddress IS NOT NULL GROUP BY stakeAddress`,
@@ -172,32 +173,9 @@ async function importUtxoSet(opts) {
172
173
  }
173
174
  if (source === 'file' && !opts.filePath)
174
175
  throw new UtxoSetImportError('source "file" needs filePath.');
175
- // Cluster-wide exclusion: hold the cursor lease for the whole import. A crawler start on
176
- // any instance (resumeCrawler, standby) and a second import are refused while it is held;
177
- // renewed on a heartbeat, released in `finally`.
178
- const leaseOwner = `import:${process.pid}:${Date.now().toString(36)}`;
179
- const acquired = await cds_1.default.tx((tx) => (0, sync_state_1.tryAcquireImportLease)(tx, leaseOwner));
180
- if (!acquired)
181
- throw new UtxoSetImportError('Could not take the cursor lease — a crawler or another import holds it.');
182
- let leaseLost = false;
183
- const heartbeat = setInterval(() => {
184
- cds_1.default.tx((tx) => (0, sync_state_1.renewImportLease)(tx, leaseOwner))
185
- .then((ok) => { if (!ok)
186
- leaseLost = true; })
187
- .catch(() => { leaseLost = true; });
188
- }, Math.max(1000, Math.floor(sync_state_1.CRAWLER_LEASE_TTL_MS / 3)));
189
- heartbeat.unref();
190
- /**
191
- * Every write re-takes the lease INSIDE its transaction (conditional UPDATE + read-back), so
192
- * a successor that took the lease between two batches fails this transaction before commit.
193
- */
194
- const writeTx = (fn) => cds_1.default.tx(async (tx) => {
195
- if (leaseLost || !(await (0, sync_state_1.renewImportLease)(tx, leaseOwner)))
196
- throw new UtxoSetLeaseLostError();
197
- return fn(tx);
198
- });
199
- opts.indexer.setUtxoAnchor(null);
200
- try {
176
+ return withImportLease(async (lease) => {
177
+ const { writeTx } = lease;
178
+ opts.indexer.setUtxoAnchor(null);
201
179
  await writeTx(async (tx) => {
202
180
  await (0, sync_state_1.setUtxoSetState)(tx, { status: 'importing', anchorSlot: anchor.slot, anchorHash: anchor.hash, error: null, importedAt: null, appliedSlot: null });
203
181
  await tx.run(DELETE.from(cardano_1.LedgerUTxOAssets));
@@ -235,18 +213,7 @@ async function importUtxoSet(opts) {
235
213
  await flush();
236
214
  }
237
215
  await flush();
238
- // Aggregates + activation in ONE lease-checked transaction: the set can never be
239
- // `active` with sums a successor's import has meanwhile truncated.
240
- const importedAt = new Date().toISOString();
241
- await writeTx(async (tx) => {
242
- for (const sql of aggregateStatements())
243
- await tx.run(sql);
244
- await (0, sync_state_1.setUtxoSetState)(tx, { status: 'active', anchorSlot: anchor.slot, anchorHash: anchor.hash, importedAt, error: null });
245
- });
246
- opts.indexer.setUtxoAnchor(anchor);
247
- // The aggregation leaves paymentCredential empty; filled in the background.
248
- opts.indexer.resetPaymentCredentials();
249
- void opts.indexer.paymentCredentialsReady();
216
+ await activateWithAggregates(lease, opts.indexer, anchor);
250
217
  logger.info(`UTxO set imported: ${imported} entries at anchor ${anchor.slot}/${anchor.hash} (source=${source})`);
251
218
  return { utxos: imported, anchor };
252
219
  }
@@ -255,18 +222,142 @@ async function importUtxoSet(opts) {
255
222
  logger.error(`UTxO set import failed after ${imported} entries: ${message}`);
256
223
  // Only the lease holder may write the failure state; after a takeover the row is the
257
224
  // successor's and the truncated tables are its problem to fill.
258
- if (!(err instanceof UtxoSetLeaseLostError)) {
259
- await cds_1.default.tx(async (tx) => {
260
- if (await (0, sync_state_1.renewImportLease)(tx, leaseOwner))
261
- await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: message.slice(0, 500) });
262
- }).catch(() => undefined);
263
- }
225
+ if (!(err instanceof UtxoSetLeaseLostError))
226
+ await lease.markInvalid(message);
264
227
  throw err;
265
228
  }
229
+ });
230
+ }
231
+ /**
232
+ * Hold the cursor lease for the whole run: a crawler start on any instance and a second import
233
+ * are refused while it is held; renewed on a heartbeat (one at a time), released at the end.
234
+ */
235
+ async function withImportLease(run) {
236
+ const leaseOwner = `import:${process.pid}:${Date.now().toString(36)}`;
237
+ const acquired = await cds_1.default.tx((tx) => (0, sync_state_1.tryAcquireImportLease)(tx, leaseOwner));
238
+ if (!acquired)
239
+ throw new UtxoSetImportError('Could not take the cursor lease — a crawler or another import holds it.');
240
+ let leaseLost = false;
241
+ let renewing = false;
242
+ const heartbeat = setInterval(() => {
243
+ // A renewal still waiting keeps its connection; a second one would only take another from the pool
244
+ if (renewing)
245
+ return;
246
+ renewing = true;
247
+ cds_1.default.tx(async (tx) => { if (!(await (0, sync_state_1.renewImportLease)(tx, leaseOwner)))
248
+ leaseLost = true; })
249
+ .catch(() => { leaseLost = true; })
250
+ .finally(() => { renewing = false; });
251
+ }, Math.max(1000, Math.floor(sync_state_1.CRAWLER_LEASE_TTL_MS / 3)));
252
+ heartbeat.unref();
253
+ const lease = {
254
+ writeTx: (fn) => cds_1.default.tx(async (tx) => {
255
+ if (leaseLost || !(await (0, sync_state_1.renewImportLease)(tx, leaseOwner)))
256
+ throw new UtxoSetLeaseLostError();
257
+ return fn(tx);
258
+ }),
259
+ writeTxLeaseLast: (fn) => cds_1.default.tx(async (tx) => {
260
+ const result = await fn(tx);
261
+ if (!(await (0, sync_state_1.renewImportLease)(tx, leaseOwner)))
262
+ throw new UtxoSetLeaseLostError();
263
+ return result;
264
+ }),
265
+ markInvalid: (message) => cds_1.default.tx(async (tx) => {
266
+ if (await (0, sync_state_1.renewImportLease)(tx, leaseOwner))
267
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: message.slice(0, 500) });
268
+ }).then(() => undefined, () => undefined),
269
+ };
270
+ try {
271
+ return await run(lease);
266
272
  }
267
273
  finally {
268
274
  clearInterval(heartbeat);
269
275
  await cds_1.default.tx((tx) => (0, sync_state_1.releaseImportLease)(tx, leaseOwner)).catch(() => undefined);
270
276
  }
271
277
  }
278
+ /** A bigger sort/hash budget for the GROUP BY over millions of rows (PostgreSQL only). */
279
+ const AGGREGATE_WORK_MEM = '256MB';
280
+ /**
281
+ * Aggregates + activation in ONE transaction, so the set is never `active` with sums a successor's
282
+ * import has meanwhile truncated. `prepare` runs first; `finish` and the activation run last,
283
+ * together with the lease check, so the cursor row is not locked during the aggregation.
284
+ */
285
+ async function activateWithAggregates(lease, indexer, anchor, hooks = {}) {
286
+ const importedAt = new Date().toISOString();
287
+ await lease.writeTxLeaseLast(async (tx) => {
288
+ const raw = tx;
289
+ if (cds_1.default.db?.kind === 'postgres') {
290
+ await raw.run(`SET LOCAL work_mem = '${AGGREGATE_WORK_MEM}'`);
291
+ // The planner overestimates the join and walks the address index row by row; hash join + hash aggregate read each table once.
292
+ await raw.run('SET LOCAL enable_nestloop = off');
293
+ }
294
+ await hooks.prepare?.(tx);
295
+ for (const sql of aggregateStatements())
296
+ await raw.run(sql);
297
+ await hooks.finish?.(tx);
298
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'active', anchorSlot: anchor.slot, anchorHash: anchor.hash, importedAt, error: null });
299
+ });
300
+ indexer.setUtxoAnchor(anchor);
301
+ // The aggregation leaves paymentCredential empty; filled in the background.
302
+ indexer.resetPaymentCredentials();
303
+ void indexer.paymentCredentialsReady();
304
+ }
305
+ /**
306
+ * Rebuild only the sums (LedgerAddresses, LedgerAddressAssets, LedgerAccounts) from the rows an
307
+ * earlier import left at the stored anchor, e.g. after the aggregate phase failed. Nothing may have
308
+ * been applied since the anchor; a cursor past it is set back to the anchor, and the blocks after
309
+ * it are crawled again (idempotent writes) so the set follows them.
310
+ */
311
+ async function rebuildUtxoSetAggregates(opts) {
312
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
313
+ if (!cursor)
314
+ throw new UtxoSetImportError('No crawler cursor yet.');
315
+ if ((0, sync_state_1.isCrawlerLeaseActive)(cursor))
316
+ throw new UtxoSetImportError('Crawler is running — pause it first (pauseCrawler).');
317
+ const { anchorSlot, anchorHash, appliedSlot, status } = cursor.utxoSet;
318
+ if (anchorSlot == null || !anchorHash)
319
+ throw new UtxoSetImportError('No imported UTxO set to rebuild the sums from — run importUtxoSet first.');
320
+ if (status === 'importing')
321
+ throw new UtxoSetImportError('The import is still loading rows (status "importing").');
322
+ if (appliedSlot != null) {
323
+ throw new UtxoSetImportError(`Blocks up to slot ${appliedSlot} were already applied to the set — its rows are past the anchor; import again.`);
324
+ }
325
+ const anchor = { slot: anchorSlot, hash: anchorHash };
326
+ const rows = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.LedgerUTxOs).columns('count(*) as n')));
327
+ const utxos = Number(rows?.n ?? 0);
328
+ if (utxos === 0)
329
+ throw new UtxoSetImportError('LedgerUTxOs is empty — run importUtxoSet first.');
330
+ let rewindTo = null;
331
+ if (cursor.lastSlot > anchor.slot) {
332
+ const block = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.Blocks).columns('height').where({ hash: anchor.hash })));
333
+ if (!block)
334
+ throw new UtxoSetImportError(`Cursor is past the anchor and the anchor block ${anchor.hash} is not stored — cannot set the cursor back.`);
335
+ rewindTo = { slot: anchor.slot, hash: anchor.hash, height: Number(block.height ?? 0) };
336
+ }
337
+ return withImportLease(async (lease) => {
338
+ opts.indexer.setUtxoAnchor(null);
339
+ // The previous failure no longer describes the set; a new one replaces it below
340
+ await lease.writeTx((tx) => (0, sync_state_1.setUtxoSetState)(tx, { error: null }));
341
+ try {
342
+ await activateWithAggregates(lease, opts.indexer, anchor, {
343
+ prepare: async (tx) => {
344
+ await tx.run(DELETE.from(cardano_1.LedgerAddressAssets));
345
+ await tx.run(DELETE.from(cardano_1.LedgerAddresses));
346
+ await tx.run(DELETE.from(cardano_1.LedgerAccounts));
347
+ },
348
+ finish: rewindTo ? (tx) => (0, sync_state_1.resetCursorTo)(tx, rewindTo) : undefined,
349
+ });
350
+ }
351
+ catch (err) {
352
+ const message = err instanceof Error ? err.message : String(err);
353
+ logger.error(`UTxO set aggregate rebuild failed: ${message}`);
354
+ if (!(err instanceof UtxoSetLeaseLostError))
355
+ await lease.markInvalid(message);
356
+ throw err;
357
+ }
358
+ logger.info(`UTxO set sums rebuilt from ${utxos} rows at anchor ${anchor.slot}/${anchor.hash}` +
359
+ (rewindTo ? ` (cursor set back from slot ${cursor.lastSlot})` : ''));
360
+ return { utxos, anchor };
361
+ });
362
+ }
272
363
  //# sourceMappingURL=utxo-set-import.js.map
@@ -58,12 +58,27 @@ export declare function buildLedgerUtxoRows(o: LedgerOutputLike, createdSlot: nu
58
58
  row: LedgerUtxoRow;
59
59
  assets: LedgerUtxoAssetRow[];
60
60
  };
61
+ /** `LedgerUTxOs` rows (+ asset rows) of a set of source transactions, keyed `txHash#outputIndex`. */
62
+ export interface LedgerLookup {
63
+ /** Source transaction hashes this lookup covers (found or not). */
64
+ hashes: Set<string>;
65
+ rows: Map<string, LedgerUtxoRow>;
66
+ assets: Map<string, LedgerUtxoAssetRow[]>;
67
+ }
68
+ /**
69
+ * Read the ledger rows of the given source transactions. Asset rows are read only for
70
+ * transactions with at least one row carrying assets, so an ada-only block costs one SELECT.
71
+ */
72
+ export declare function readLedgerOutputs(tx: CapTransaction, txHashes: Iterable<string>, into?: LedgerLookup): Promise<LedgerLookup>;
73
+ /** Amount list (lovelace + native assets) of a ledger row, the shape a resolved input carries. */
74
+ export declare function ledgerRowAmount(row: LedgerUtxoRow, assets: LedgerUtxoAssetRow[] | undefined): Amount[];
61
75
  /**
62
76
  * Apply one block to the ledger tables. Caller guarantees `block.slot > anchor.slot`.
77
+ * `lookup` may carry rows the caller already read for this block (input resolution).
63
78
  * Never throws for a missing outpoint (it is counted and logged); DB errors propagate so the
64
79
  * block transaction rolls back as a whole.
65
80
  */
66
- export declare function applyBlockToLedger(tx: CapTransaction, block: BlockData, txs: ProviderTransaction[]): Promise<LedgerApplyResult>;
81
+ export declare function applyBlockToLedger(tx: CapTransaction, block: BlockData, txs: ProviderTransaction[], lookup?: LedgerLookup): Promise<LedgerApplyResult>;
67
82
  /**
68
83
  * Reorg undo for a set of rolled-back transactions: drop what they created, reopen what
69
84
  * they spent, then recount every address either side touched from the open rows.
@@ -4,6 +4,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.buildLedgerUtxoRows = buildLedgerUtxoRows;
7
+ exports.readLedgerOutputs = readLedgerOutputs;
8
+ exports.ledgerRowAmount = ledgerRowAmount;
7
9
  exports.applyBlockToLedger = applyBlockToLedger;
8
10
  exports.undoLedgerForTransactions = undoLedgerForTransactions;
9
11
  exports.recountLedgerAddresses = recountLedgerAddresses;
@@ -93,12 +95,46 @@ function applyDelta(d, row, assets, sign) {
93
95
  d.assets.set(unit, (d.assets.get(unit) ?? 0n) + sign * BigInt(qty));
94
96
  }
95
97
  }
98
+ /**
99
+ * Read the ledger rows of the given source transactions. Asset rows are read only for
100
+ * transactions with at least one row carrying assets, so an ada-only block costs one SELECT.
101
+ */
102
+ async function readLedgerOutputs(tx, txHashes, into) {
103
+ const lookup = into ?? { hashes: new Set(), rows: new Map(), assets: new Map() };
104
+ const todo = [...new Set(txHashes)].filter(h => !lookup.hashes.has(h));
105
+ for (const hashChunk of (0, collections_1.chunk)(todo, collections_1.IN_CHUNK)) {
106
+ const rows = await tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ txHash: { in: hashChunk } }));
107
+ for (const r of rows ?? [])
108
+ lookup.rows.set(outpoint(r.txHash, num(r.outputIndex)), r);
109
+ const withAssets = [...new Set((rows ?? []).filter(r => r.hasAssets).map(r => r.txHash))];
110
+ if (withAssets.length) {
111
+ const assets = await tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: withAssets } }));
112
+ for (const a of assets ?? []) {
113
+ const k = outpoint(a.utxo_txHash, num(a.utxo_outputIndex));
114
+ const list = lookup.assets.get(k) ?? [];
115
+ list.push(a);
116
+ lookup.assets.set(k, list);
117
+ }
118
+ }
119
+ for (const h of hashChunk)
120
+ lookup.hashes.add(h);
121
+ }
122
+ return lookup;
123
+ }
124
+ /** Amount list (lovelace + native assets) of a ledger row, the shape a resolved input carries. */
125
+ function ledgerRowAmount(row, assets) {
126
+ return [
127
+ { unit: 'lovelace', quantity: String(row.lovelace ?? '0') },
128
+ ...(assets ?? []).map(a => ({ unit: a.unit, quantity: String(a.asset_quantity) })),
129
+ ];
130
+ }
96
131
  /**
97
132
  * Apply one block to the ledger tables. Caller guarantees `block.slot > anchor.slot`.
133
+ * `lookup` may carry rows the caller already read for this block (input resolution).
98
134
  * Never throws for a missing outpoint (it is counted and logged); DB errors propagate so the
99
135
  * block transaction rolls back as a whole.
100
136
  */
101
- async function applyBlockToLedger(tx, block, txs) {
137
+ async function applyBlockToLedger(tx, block, txs, lookup) {
102
138
  const slot = block.slot ?? 0;
103
139
  // 1) everything this block produces
104
140
  const created = new Map();
@@ -125,23 +161,7 @@ async function applyBlockToLedger(tx, block, txs) {
125
161
  }
126
162
  }
127
163
  }
128
- const dbRows = new Map();
129
- const dbAssets = new Map();
130
- const sourceHashes = [...new Set(lookups.map(l => l.txHash))];
131
- for (const hashChunk of (0, collections_1.chunk)(sourceHashes, collections_1.IN_CHUNK)) {
132
- const [rows, assets] = await Promise.all([
133
- tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ txHash: { in: hashChunk } })),
134
- tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: hashChunk } })),
135
- ]);
136
- for (const r of rows ?? [])
137
- dbRows.set(outpoint(r.txHash, num(r.outputIndex)), r);
138
- for (const a of assets ?? []) {
139
- const k = outpoint(a.utxo_txHash, num(a.utxo_outputIndex));
140
- const list = dbAssets.get(k) ?? [];
141
- list.push(a);
142
- dbAssets.set(k, list);
143
- }
144
- }
164
+ const { rows: dbRows, assets: dbAssets } = await readLedgerOutputs(tx, lookups.map(l => l.txHash), lookup);
145
165
  const spentRows = [];
146
166
  let missing = 0;
147
167
  for (const l of lookups) {
@@ -0,0 +1,28 @@
1
+ import type { UTxO } from '../utils/types';
2
+ /** How long a submitted transaction counts as pending when no crawled block confirms it earlier. */
3
+ export declare const PENDING_TX_TTL_MS: number;
4
+ /**
5
+ * Transactions this process submitted that the ledger view does not show yet. The node's ledger
6
+ * state and the crawled UTxO set both still list their inputs as unspent while they wait in the
7
+ * mempool, so a second build would spend the same outputs. Builders skip those inputs and may
8
+ * spend the pending outputs (change) instead. Process-local; an entry ends when a crawled block
9
+ * holds the transaction or after PENDING_TX_TTL_MS.
10
+ */
11
+ export declare class PendingSpends {
12
+ private readonly now;
13
+ private readonly txs;
14
+ constructor(now?: () => number);
15
+ /** Remember a submitted transaction; unparseable CBOR is ignored (the submit already succeeded). */
16
+ record(signedTxCbor: string): void;
17
+ /** The pending transaction that spends this output, if any. */
18
+ spentBy(txHash: string, outputIndex: number): string | undefined;
19
+ /**
20
+ * The UTxOs of an address as they are after the pending transactions: inputs they spend are
21
+ * removed, their outputs to the address are added. A pending transaction whose outputs already
22
+ * appear in `utxos` has been crawled and is forgotten.
23
+ */
24
+ apply(address: string, utxos: UTxO[]): UTxO[];
25
+ get size(): number;
26
+ private prune;
27
+ }
28
+ //# sourceMappingURL=pending-spends.d.ts.map
@@ -0,0 +1,89 @@
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.PendingSpends = exports.PENDING_TX_TTL_MS = void 0;
7
+ const cds_1 = __importDefault(require("@sap/cds"));
8
+ const parse_1 = require("../cbor/parse");
9
+ const logger = cds_1.default.log('PendingSpends');
10
+ /** How long a submitted transaction counts as pending when no crawled block confirms it earlier. */
11
+ exports.PENDING_TX_TTL_MS = 10 * 60_000;
12
+ const refKey = (txHash, outputIndex) => `${txHash.toLowerCase()}#${outputIndex}`;
13
+ /**
14
+ * Transactions this process submitted that the ledger view does not show yet. The node's ledger
15
+ * state and the crawled UTxO set both still list their inputs as unspent while they wait in the
16
+ * mempool, so a second build would spend the same outputs. Builders skip those inputs and may
17
+ * spend the pending outputs (change) instead. Process-local; an entry ends when a crawled block
18
+ * holds the transaction or after PENDING_TX_TTL_MS.
19
+ */
20
+ class PendingSpends {
21
+ now;
22
+ txs = new Map();
23
+ constructor(now = Date.now) {
24
+ this.now = now;
25
+ }
26
+ /** Remember a submitted transaction; unparseable CBOR is ignored (the submit already succeeded). */
27
+ record(signedTxCbor) {
28
+ try {
29
+ const parsed = (0, parse_1.parseTransaction)(signedTxCbor);
30
+ this.txs.set(parsed.txHash, {
31
+ inputs: parsed.inputs.map((i) => refKey(i.txHash, i.outputIndex)),
32
+ outputs: parsed.outputs.map((o, outputIndex) => ({
33
+ txHash: parsed.txHash,
34
+ outputIndex,
35
+ address: o.address,
36
+ amount: [{ unit: 'lovelace', quantity: o.lovelace }, ...o.assets],
37
+ datumHash: o.datumHash,
38
+ inlineDatum: o.inlineDatumHex,
39
+ scriptRefCbor: o.referenceScriptHex,
40
+ })),
41
+ expiresAt: this.now() + exports.PENDING_TX_TTL_MS,
42
+ });
43
+ }
44
+ catch (err) {
45
+ logger.warn(`submitted transaction not tracked as pending: ${err instanceof Error ? err.message : String(err)}`);
46
+ }
47
+ }
48
+ /** The pending transaction that spends this output, if any. */
49
+ spentBy(txHash, outputIndex) {
50
+ this.prune();
51
+ const key = refKey(txHash, outputIndex);
52
+ for (const [hash, tx] of this.txs)
53
+ if (tx.inputs.includes(key))
54
+ return hash;
55
+ return undefined;
56
+ }
57
+ /**
58
+ * The UTxOs of an address as they are after the pending transactions: inputs they spend are
59
+ * removed, their outputs to the address are added. A pending transaction whose outputs already
60
+ * appear in `utxos` has been crawled and is forgotten.
61
+ */
62
+ apply(address, utxos) {
63
+ this.prune();
64
+ if (this.txs.size === 0)
65
+ return utxos;
66
+ const listed = new Set(utxos.map((u) => u.txHash.toLowerCase()));
67
+ for (const hash of [...this.txs.keys()])
68
+ if (listed.has(hash))
69
+ this.txs.delete(hash);
70
+ const spent = new Set([...this.txs.values()].flatMap((t) => t.inputs));
71
+ const keep = utxos.filter((u) => !spent.has(refKey(u.txHash, u.outputIndex)));
72
+ const pendingOut = [...this.txs.values()]
73
+ .flatMap((t) => t.outputs)
74
+ .filter((o) => o.address === address && !spent.has(refKey(o.txHash, o.outputIndex)));
75
+ return [...keep, ...pendingOut];
76
+ }
77
+ get size() {
78
+ this.prune();
79
+ return this.txs.size;
80
+ }
81
+ prune() {
82
+ const now = this.now();
83
+ for (const [hash, tx] of this.txs)
84
+ if (tx.expiresAt <= now)
85
+ this.txs.delete(hash);
86
+ }
87
+ }
88
+ exports.PendingSpends = PendingSpends;
89
+ //# sourceMappingURL=pending-spends.js.map
@@ -2,8 +2,9 @@ import type { Transaction as CapTransaction } from '@sap/cds';
2
2
  import type { BlockData, MetadataLabelTx, Transaction as ProviderTransaction } from '../utils/types';
3
3
  /**
4
4
  * Stored blocks and transactions back in the provider shape (`BlockData`, `Transaction`), for
5
- * serving other ODATANO instances from what this one has indexed. Not stored, so absent: the
6
- * phase-2 flag (`spendsCollaterals`), `totalCollateral` and `outputAmount`.
5
+ * serving other ODATANO instances from what this one has indexed. The rows hold the ledger view
6
+ * (see ledgerView), so the phase-2 flag follows from them: a valid transaction always spends a
7
+ * regular input. Not stored, so absent: `totalCollateral` and `outputAmount`.
7
8
  */
8
9
  type Row = Record<string, unknown>;
9
10
  /** `Blocks` row -> BlockData. */
@@ -17,6 +18,8 @@ export declare function readBlockByHeight(db: CapTransaction, height: number): P
17
18
  * the first missing height, so a caller never walks over a gap.
18
19
  */
19
20
  export declare function readNextBlocks(db: CapTransaction, afterHeight: number, count: number): Promise<BlockData[]>;
21
+ /** True when a stored input lacks its outpoint (row indexed before outpoints were recorded). */
22
+ export declare function lacksOutpoints(t: ProviderTransaction): boolean;
20
23
  /** Stored transactions by hash (missing hashes are absent from the map). */
21
24
  export declare function readTransactionsByHash(db: CapTransaction, hashes: string[]): Promise<Map<string, ProviderTransaction>>;
22
25
  /**
@@ -7,6 +7,7 @@ exports.blockRowToData = blockRowToData;
7
7
  exports.readBlock = readBlock;
8
8
  exports.readBlockByHeight = readBlockByHeight;
9
9
  exports.readNextBlocks = readNextBlocks;
10
+ exports.lacksOutpoints = lacksOutpoints;
10
11
  exports.readTransactionsByHash = readTransactionsByHash;
11
12
  exports.readBlockTransactions = readBlockTransactions;
12
13
  exports.readTransactionMetadata = readTransactionMetadata;
@@ -48,7 +49,9 @@ async function readBlockByHeight(db, height) {
48
49
  * the first missing height, so a caller never walks over a gap.
49
50
  */
50
51
  async function readNextBlocks(db, afterHeight, count) {
51
- const rows = await db.run(SELECT.from(cardano_1.Blocks).where({ height: { '>': afterHeight, '<=': afterHeight + count } }).orderBy('height asc'));
52
+ const rows = await db.run(
53
+ // one operator per column object: `{ '>': a, '<=': b }` renders as `height > a <= b`
54
+ SELECT.from(cardano_1.Blocks).where({ height: { between: afterHeight + 1, and: afterHeight + count } }).orderBy('height asc'));
52
55
  const out = [];
53
56
  let expected = afterHeight + 1;
54
57
  for (const row of rows ?? []) {
@@ -59,6 +62,10 @@ async function readNextBlocks(db, afterHeight, count) {
59
62
  }
60
63
  return out;
61
64
  }
65
+ /** True when a stored input lacks its outpoint (row indexed before outpoints were recorded). */
66
+ function lacksOutpoints(t) {
67
+ return (t.inputs ?? []).some(i => i.txHash == null);
68
+ }
62
69
  /** Stored transactions by hash (missing hashes are absent from the map). */
63
70
  async function readTransactionsByHash(db, hashes) {
64
71
  const rows = [];
@@ -126,7 +133,7 @@ async function assembleTransactions(db, rows) {
126
133
  }
127
134
  return out;
128
135
  };
129
- const [inputs, inputAssets, outputs, outputAssets, metadata, certificates, withdrawals, mints] = await Promise.all([
136
+ const [inputs, inputAssets, outputs, outputAssets, metadata, certificates, withdrawals, mints, redeemers] = await Promise.all([
130
137
  fetchIn(cardano_1.TransactionInputs, 'txSeq', seqs),
131
138
  fetchIn(cardano_1.TransactionInputAssets, 'input_txSeq', seqs),
132
139
  fetchIn(cardano_1.TransactionOutputs, 'txSeq', seqs),
@@ -135,6 +142,7 @@ async function assembleTransactions(db, rows) {
135
142
  fetchIn(cardano_1.TransactionCertificates, 'tx_hash', hashes),
136
143
  fetchIn(cardano_1.TransactionWithdrawals, 'tx_hash', hashes),
137
144
  fetchIn(cardano_1.AssetHistory_, 'txHash', hashes),
145
+ fetchIn(cardano_1.TransactionRedeemers, 'tx_hash', hashes),
138
146
  ]);
139
147
  const inputsBySeq = groupBy(inputs, r => str(r.txSeq));
140
148
  const inputAssetsByKey = groupBy(inputAssets, r => `${r.input_txSeq}#${r.input_inputIndex}`);
@@ -144,6 +152,7 @@ async function assembleTransactions(db, rows) {
144
152
  const certsByHash = groupBy(certificates, r => str(r.tx_hash));
145
153
  const withdrawalsByHash = groupBy(withdrawals, r => str(r.tx_hash));
146
154
  const mintsByHash = groupBy(mints, r => str(r.txHash));
155
+ const redeemersByHash = groupBy(redeemers, r => str(r.tx_hash));
147
156
  return rows.map((t) => {
148
157
  const seq = str(t.txSeq);
149
158
  const hash = str(t.hash);
@@ -152,14 +161,17 @@ async function assembleTransactions(db, rows) {
152
161
  .map(i => ({
153
162
  address: str(i.address_address),
154
163
  amount: amounts(inputAssetsByKey.get(`${seq}#${i.inputIndex}`) ?? []),
155
- txHash: str(i.spentTxHash),
156
- outputIndex: num(i.spentOutputIndex),
164
+ // null on rows indexed before the outpoint was recorded, never a made-up reference
165
+ txHash: (i.spentTxHash ?? null),
166
+ outputIndex: numOrNull(i.spentOutputIndex),
157
167
  dataHash: i.utxoData_dataHash ?? null,
158
168
  inlineDatum: i.utxoData_inlineDatum ?? null,
159
169
  referenceScriptHash: i.utxoData_referenceScriptHash ?? null,
160
170
  isCollateral: Boolean(i.isCollateral),
161
171
  isReference: Boolean(i.isReference),
162
172
  }));
173
+ // a phase-2 failure keeps only collateral and reference inputs, and its collateral return
174
+ const spendsCollaterals = txInputs.some(i => i.isCollateral) && !txInputs.some(i => !i.isCollateral && !i.isReference);
163
175
  const txOutputs = (outputsBySeq.get(seq) ?? [])
164
176
  .sort((a, b) => num(a.outputIndex) - num(b.outputIndex))
165
177
  .map(o => ({
@@ -169,12 +181,13 @@ async function assembleTransactions(db, rows) {
169
181
  outputIndex: num(o.outputIndex),
170
182
  dataHash: o.utxo_dataHash ?? null,
171
183
  inlineDatum: o.utxo_inlineDatum ?? null,
172
- isCollateral: false,
184
+ isCollateral: spendsCollaterals,
173
185
  referenceScriptHash: o.utxo_referenceScriptHash ?? null,
174
186
  }));
175
187
  const certs = certsByHash.get(hash);
176
188
  const withdrawn = withdrawalsByHash.get(hash);
177
189
  const minted = mintsByHash.get(hash);
190
+ const redeemed = redeemersByHash.get(hash);
178
191
  return {
179
192
  hash,
180
193
  blockHash: str(t.blockHash),
@@ -185,6 +198,7 @@ async function assembleTransactions(db, rows) {
185
198
  deposit: str(t.deposit ?? '0'),
186
199
  size: numOrNull(t.size),
187
200
  blockTime: num(t.blockTime),
201
+ spendsCollaterals,
188
202
  mint: minted?.map(m => ({
189
203
  unit: str(m.unit),
190
204
  quantity: (m.action === 'burn' ? '-' : '') + str(m.quantity),
@@ -202,6 +216,18 @@ async function assembleTransactions(db, rows) {
202
216
  epoch: numOrNull(c.epoch),
203
217
  })),
204
218
  withdrawals: withdrawn?.map((w) => ({ stakeAddress: str(w.stakeAddress), amount: str(w.lovelace) })),
219
+ redeemers: redeemed
220
+ ?.sort((a, b) => str(a.purpose).localeCompare(str(b.purpose)) || num(a.redeemerIndex) - num(b.redeemerIndex))
221
+ .map((r) => ({
222
+ purpose: str(r.purpose),
223
+ index: num(r.redeemerIndex),
224
+ data: str(r.data),
225
+ mem: str(r.mem),
226
+ steps: str(r.steps),
227
+ txHash: r.spentTxHash ?? null,
228
+ outputIndex: numOrNull(r.spentOutputIndex),
229
+ policyId: r.policyId ?? null,
230
+ })),
205
231
  };
206
232
  });
207
233
  }
@@ -1,5 +1,5 @@
1
1
  import type { CardanoTxBuilder } from "./cardano-tx";
2
- import type { TxBuildRequest, TxBuildMintRequest, TxBuildPlutusSpendRequest, TxBuildContext, TxBuildResult, LedgerProtocolParameters } from "../../utils/types";
2
+ import type { TxBuildRequest, TxBuildMintRequest, TxBuildPlutusSpendRequest, TxBuildPlutusRequest, TxBuildContext, TxBuildResult, LedgerProtocolParameters } from "../../utils/types";
3
3
  import { CardanoClient } from "../cardano-client";
4
4
  /** CardanoTxBuilder implementation on top of Buildooor. */
5
5
  export declare class BuildooorTxBuilder implements CardanoTxBuilder {
@@ -35,6 +35,13 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
35
35
  private _buildSimpleTransfer;
36
36
  buildUnsignedMintTransaction(req: TxBuildMintRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
37
37
  buildUnsignedPlutusSpendTransaction(req: TxBuildPlutusSpendRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
38
+ /**
39
+ * Several script inputs in one transaction, each with its own redeemer (inline validator or a
40
+ * reference-script UTxO), the outputs exactly in the given order and change after them.
41
+ */
42
+ buildUnsignedPlutusTransaction(req: TxBuildPlutusRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
43
+ /** Outputs of a BuildPlutusTransaction in the given order: inline datum or datum hash, ref script, min-ADA each. */
44
+ private _appendPlutusOutputs;
38
45
  /** Extract CBOR, hash, fee, size, inputs and outputs from a built Buildooor Tx */
39
46
  private _extractTxDetails;
40
47
  /** Build the standard TxBuildResult object */
@@ -89,6 +96,8 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
89
96
  * refs absent from utxos are ignored (existence is validated upstream).
90
97
  */
91
98
  private _partitionForcedInputs;
99
+ /** Keys (`txhash#index`) of the reference inputs of a build, from the resolved UTxOs and the request refs. */
100
+ private _referencedKeys;
92
101
  /** Map resolved CIP-31 reference input UTxOs to Buildooor LedgerUTxO; empty when none. */
93
102
  private _mapReferenceInputs;
94
103
  /**
@@ -131,8 +140,8 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
131
140
  /** Parse a Plutus V3 CBOR hex into a Buildooor Script for refScript attachment. */
132
141
  private _parseReferenceScript;
133
142
  /**
134
- * Map an input UTxO's scriptRef to a Script. Blockfrost/Ogmios set scriptRef to the 28-byte
135
- * hash (56 hex chars), Koios to the full CBOR bytes; only full bytes are usable locally.
143
+ * Map an input UTxO's reference script to a Script: `scriptRefCbor` (Ogmios), else a full-CBOR
144
+ * `scriptRef` (Koios); Blockfrost and the tables carry the 28-byte hash only, unusable locally.
136
145
  */
137
146
  private _buildInputRefScript;
138
147
  /**