@odatano/core 2.0.0-rc.44 → 2.0.0-rc.45

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 (168) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +0 -46
  2. package/@cds-models/CardanoBackendService/index.d.ts +0 -10
  3. package/@cds-models/CardanoIndexerService/index.d.ts +5 -20
  4. package/@cds-models/CardanoODataService/index.d.ts +18 -47
  5. package/@cds-models/CardanoSignService/index.d.ts +3 -18
  6. package/@cds-models/CardanoTransactionService/index.d.ts +9 -31
  7. package/@cds-models/CardanoWorkerService/index.d.ts +3 -19
  8. package/@cds-models/index.d.ts +17 -0
  9. package/@cds-models/index.js +2 -0
  10. package/@cds-models/odatano/cardano/index.d.ts +0 -34
  11. package/README.md +6 -6
  12. package/db/schema.cds +25 -44
  13. package/db/types.cds +22 -5
  14. package/package.json +3 -1
  15. package/scripts/migrate-slot-leader.mjs +3 -11
  16. package/scripts/migrate-txseq.mjs +3 -12
  17. package/src/index.d.ts +0 -4
  18. package/src/index.js +3 -5
  19. package/src/plugin.js +4 -8
  20. package/srv/blockchain/asset-decimals.d.ts +0 -9
  21. package/srv/blockchain/asset-decimals.js +21 -16
  22. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -10
  23. package/srv/blockchain/backends/blockfrost-backend.js +15 -21
  24. package/srv/blockchain/backends/cardano-backend.d.ts +12 -71
  25. package/srv/blockchain/backends/koios-backend.d.ts +14 -147
  26. package/srv/blockchain/backends/koios-backend.js +40 -164
  27. package/srv/blockchain/backends/odatano-backend.d.ts +1 -11
  28. package/srv/blockchain/backends/odatano-backend.js +11 -12
  29. package/srv/blockchain/backends/ogmios-backend.d.ts +13 -160
  30. package/srv/blockchain/backends/ogmios-backend.js +48 -175
  31. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +2 -18
  32. package/srv/blockchain/backends/ogmios-frame-guard.js +8 -20
  33. package/srv/blockchain/cardano-client.d.ts +12 -80
  34. package/srv/blockchain/cardano-client.js +36 -88
  35. package/srv/blockchain/cardano-indexer.d.ts +12 -192
  36. package/srv/blockchain/cardano-indexer.js +126 -222
  37. package/srv/blockchain/cardano-tx-builder.d.ts +1 -28
  38. package/srv/blockchain/cardano-tx-builder.js +17 -34
  39. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  40. package/srv/blockchain/circuit-breaker.js +5 -15
  41. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +0 -5
  42. package/srv/blockchain/crawler/asset-decimals-backfill.js +2 -5
  43. package/srv/blockchain/crawler/certificate-backfill.d.ts +0 -17
  44. package/srv/blockchain/crawler/certificate-backfill.js +8 -22
  45. package/srv/blockchain/crawler/crawler.d.ts +16 -93
  46. package/srv/blockchain/crawler/crawler.js +85 -160
  47. package/srv/blockchain/crawler/credential-backfill.d.ts +0 -10
  48. package/srv/blockchain/crawler/credential-backfill.js +2 -4
  49. package/srv/blockchain/crawler/hooks.d.ts +1 -5
  50. package/srv/blockchain/crawler/index.d.ts +0 -12
  51. package/srv/blockchain/crawler/index.js +6 -20
  52. package/srv/blockchain/crawler/sync-state.d.ts +6 -44
  53. package/srv/blockchain/crawler/sync-state.js +18 -53
  54. package/srv/blockchain/crawler/transaction-backfill.d.ts +0 -11
  55. package/srv/blockchain/crawler/transaction-backfill.js +11 -30
  56. package/srv/blockchain/crawler/utxo-set-import.d.ts +1 -30
  57. package/srv/blockchain/crawler/utxo-set-import.js +27 -53
  58. package/srv/blockchain/ledger-state.d.ts +10 -54
  59. package/srv/blockchain/ledger-state.js +11 -27
  60. package/srv/blockchain/pending-spends.d.ts +0 -12
  61. package/srv/blockchain/pending-spends.js +4 -12
  62. package/srv/blockchain/request-coalescer.d.ts +2 -16
  63. package/srv/blockchain/request-coalescer.js +2 -16
  64. package/srv/blockchain/signing/cose-verifier.d.ts +0 -9
  65. package/srv/blockchain/signing/cose-verifier.js +4 -10
  66. package/srv/blockchain/signing/external-signer.d.ts +1 -4
  67. package/srv/blockchain/signing/external-signer.js +2 -8
  68. package/srv/blockchain/signing/hsm-signer.d.ts +6 -18
  69. package/srv/blockchain/signing/hsm-signer.js +16 -28
  70. package/srv/blockchain/signing/signature-verifier.d.ts +1 -8
  71. package/srv/blockchain/signing/signature-verifier.js +9 -19
  72. package/srv/blockchain/signing/submission-finalizer.d.ts +10 -16
  73. package/srv/blockchain/signing/submission-finalizer.js +48 -19
  74. package/srv/blockchain/stored-chain.d.ts +1 -14
  75. package/srv/blockchain/stored-chain.js +3 -8
  76. package/srv/blockchain/transaction-building/buildooor-fee-patch.d.ts +0 -4
  77. package/srv/blockchain/transaction-building/buildooor-fee-patch.js +4 -9
  78. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +7 -150
  79. package/srv/blockchain/transaction-building/buildooor-tx.js +91 -196
  80. package/srv/blockchain/transaction-building/caller-datums.d.ts +0 -14
  81. package/srv/blockchain/transaction-building/caller-datums.js +3 -9
  82. package/srv/blockchain/transaction-building/cardano-tx.d.ts +1 -4
  83. package/srv/blockchain/wallet-worker/build-request.d.ts +0 -5
  84. package/srv/blockchain/wallet-worker/build-request.js +6 -9
  85. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -23
  86. package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -20
  87. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  88. package/srv/blockchain/wallet-worker/index.js +3 -5
  89. package/srv/blockchain/wallet-worker/job-store.d.ts +15 -65
  90. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  91. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -10
  92. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -12
  93. package/srv/blockchain/wallet-worker/signers.d.ts +3 -11
  94. package/srv/blockchain/wallet-worker/signers.js +3 -6
  95. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +3 -21
  96. package/srv/blockchain/wallet-worker/wallet-worker.js +47 -54
  97. package/srv/cardano-agent-service.cds +123 -146
  98. package/srv/cardano-agent-service.js +2 -5
  99. package/srv/cardano-backend-service.cds +10 -17
  100. package/srv/cardano-backend-service.js +7 -12
  101. package/srv/cardano-indexer-service.cds +16 -37
  102. package/srv/cardano-indexer-service.d.ts +5 -1
  103. package/srv/cardano-indexer-service.js +44 -35
  104. package/srv/cardano-service.cds +56 -40
  105. package/srv/cardano-service.js +42 -69
  106. package/srv/cardano-sign-service.cds +14 -23
  107. package/srv/cardano-sign-service.js +18 -24
  108. package/srv/cardano-tx-service.cds +27 -29
  109. package/srv/cardano-tx-service.js +60 -122
  110. package/srv/cardano-worker-service.cds +109 -125
  111. package/srv/cardano-worker-service.js +21 -31
  112. package/srv/cbor/cip68.d.ts +0 -4
  113. package/srv/cbor/cip68.js +2 -4
  114. package/srv/cbor/parse.d.ts +3 -18
  115. package/srv/cbor/parse.js +2 -7
  116. package/srv/cbor/plutus-data-json.d.ts +0 -4
  117. package/srv/server.d.ts +5 -36
  118. package/srv/server.js +30 -51
  119. package/srv/utils/agent-grants-config.d.ts +0 -18
  120. package/srv/utils/agent-grants-config.js +6 -13
  121. package/srv/utils/agent-grants.d.ts +14 -68
  122. package/srv/utils/agent-grants.js +42 -60
  123. package/srv/utils/agent-token-auth.d.ts +0 -5
  124. package/srv/utils/agent-token-auth.js +2 -5
  125. package/srv/utils/backend-request-handler.d.ts +1 -1
  126. package/srv/utils/collections.d.ts +1 -4
  127. package/srv/utils/collections.js +1 -4
  128. package/srv/utils/const.d.ts +0 -18
  129. package/srv/utils/const.js +7 -18
  130. package/srv/utils/crypto.js +3 -5
  131. package/srv/utils/db-indexes.d.ts +2 -0
  132. package/srv/utils/db-indexes.js +22 -9
  133. package/srv/utils/db-sanitize.d.ts +1 -8
  134. package/srv/utils/db-sanitize.js +3 -8
  135. package/srv/utils/epoch-slots.d.ts +1 -8
  136. package/srv/utils/epoch-slots.js +3 -8
  137. package/srv/utils/error-codes.d.ts +0 -4
  138. package/srv/utils/error-codes.js +2 -4
  139. package/srv/utils/errors.d.ts +2 -22
  140. package/srv/utils/errors.js +13 -27
  141. package/srv/utils/liveness.d.ts +0 -4
  142. package/srv/utils/liveness.js +2 -4
  143. package/srv/utils/mappers.d.ts +0 -37
  144. package/srv/utils/mappers.js +19 -39
  145. package/srv/utils/network-context.js +2 -4
  146. package/srv/utils/paging.d.ts +31 -0
  147. package/srv/utils/paging.js +43 -0
  148. package/srv/utils/pg-inline-json.js +3 -7
  149. package/srv/utils/pg-order-nulls.js +2 -5
  150. package/srv/utils/plutus-placeholders.d.ts +0 -13
  151. package/srv/utils/plutus-placeholders.js +6 -13
  152. package/srv/utils/rate-limiter.d.ts +0 -8
  153. package/srv/utils/rate-limiter.js +2 -4
  154. package/srv/utils/reference-script.d.ts +0 -18
  155. package/srv/utils/reference-script.js +8 -19
  156. package/srv/utils/service-events.d.ts +0 -4
  157. package/srv/utils/service-events.js +2 -4
  158. package/srv/utils/signing-helper.d.ts +1 -8
  159. package/srv/utils/signing-helper.js +3 -8
  160. package/srv/utils/tx-build-helper.d.ts +2 -32
  161. package/srv/utils/tx-build-helper.js +26 -40
  162. package/srv/utils/tx-request-parsers.d.ts +1 -25
  163. package/srv/utils/tx-request-parsers.js +10 -25
  164. package/srv/utils/tx-utils.d.ts +0 -8
  165. package/srv/utils/tx-utils.js +10 -13
  166. package/srv/utils/types.d.ts +2 -37
  167. package/srv/utils/validators.d.ts +0 -4
  168. package/srv/utils/validators.js +2 -4
@@ -22,11 +22,8 @@ const cardano_1 = require("#cds-models/odatano/cardano");
22
22
  const collections_1 = require("../../utils/collections");
23
23
  const { UPSERT, DELETE, SELECT, UPDATE } = cds_1.default.ql;
24
24
  const logger = cds_1.default.log('LedgerState');
25
- /**
26
- * One-off import of the UTxO set at the anchor `crawler.utxoSet` builds on: from Ogmios
27
- * (`queryLedgerState/utxo` at the cursor point) or a `cardano-cli query utxo --whole-utxo`
28
- * dump (`.json` parsed whole; `.ndjson`/`.jsonl` streamed, one entry or `{key,value}` per line).
29
- */
25
+ // One-off import of the UTxO set that `crawler.utxoSet` builds on, from Ogmios or a cardano-cli dump.
26
+ // A `.json` dump is parsed whole. Other files are streamed with one entry or `{key,value}` per line.
30
27
  class UtxoSetImportError extends Error {
31
28
  constructor(message) {
32
29
  super(message);
@@ -36,16 +33,13 @@ class UtxoSetImportError extends Error {
36
33
  exports.UtxoSetImportError = UtxoSetImportError;
37
34
  /** The cursor lease went to someone else: nothing more may be written, not even `invalid`. */
38
35
  class UtxoSetLeaseLostError extends UtxoSetImportError {
39
- constructor(message = 'Lost the cursor lease during the import — aborted without further writes.') {
36
+ constructor(message = 'Lost the cursor lease during the import. Aborted without further writes.') {
40
37
  super(message);
41
38
  this.name = 'UtxoSetLeaseLostError';
42
39
  }
43
40
  }
44
41
  exports.UtxoSetLeaseLostError = UtxoSetLeaseLostError;
45
- /**
46
- * `JSON.parse` for a cardano-cli dump that keeps every integer exact: integer literals outside
47
- * strings are quoted before parsing, so a quantity above 2^53 is never rounded.
48
- */
42
+ /** `JSON.parse` that quotes integer literals first, so quantities above 2^53 are never rounded. */
49
43
  function parseJsonLossless(text) {
50
44
  // string literals pass through untouched; floats keep their JSON meaning
51
45
  const rewritten = text.replace(/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g, (m) => (m[0] === '"' || !/^-?\d+$/.test(m) ? m : `"${m}"`));
@@ -116,7 +110,7 @@ async function* readUtxoSetFile(filePath) {
116
110
  async function* readFromOgmios(client, anchor) {
117
111
  const backend = client.getLedgerStateBackend();
118
112
  if (!backend) {
119
- throw new UtxoSetImportError('No Ogmios backend available for source "ogmios" — configure one or import a cardano-cli file.');
113
+ throw new UtxoSetImportError('No Ogmios backend available for source "ogmios". Configure one or import a cardano-cli file.');
120
114
  }
121
115
  const utxos = await backend.queryUtxoSetAt({ slot: anchor.slot, hash: anchor.hash });
122
116
  for (const u of utxos) {
@@ -141,11 +135,8 @@ const T = {
141
135
  addressAssets: 'odatano_cardano_LedgerAddressAssets',
142
136
  accounts: 'odatano_cardano_LedgerAccounts',
143
137
  };
144
- /**
145
- * The three aggregate statements that derive the running sums from the imported rows.
146
- * Plain SQL because millions of addresses do not fit an in-memory map and a per-row
147
- * UPSERT would take hours; the syntax is the portable subset (sqlite, PostgreSQL, HANA).
148
- */
138
+ // Derive the running sums from the imported rows. Plain SQL, because millions of addresses
139
+ // do not fit in memory and per-row UPSERTs take hours. Portable across SQLite, PostgreSQL and HANA.
149
140
  function aggregateStatements() {
150
141
  return [
151
142
  `INSERT INTO ${T.addresses} (address, stakeAddress, addressType, isScript, totalLovelace, utxoCount, firstSeenSlot, lastActiveSlot) ` +
@@ -161,20 +152,17 @@ function aggregateStatements() {
161
152
  `WHERE stakeAddress IS NOT NULL GROUP BY stakeAddress`,
162
153
  ];
163
154
  }
164
- /**
165
- * Run the import. Throws `UtxoSetImportError` on a precondition failure before anything is
166
- * written; a failure mid-way leaves the set marked `invalid` (never half-`active`).
167
- */
155
+ // Precondition failures throw before any write. A failure mid-way marks the set `invalid`.
168
156
  async function importUtxoSet(opts) {
169
157
  const { anchor, source } = opts;
170
158
  const batchSize = opts.batchSize ?? 2000;
171
159
  const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
172
160
  if (!cursor)
173
- throw new UtxoSetImportError('No crawler cursor yet — start the crawler once before importing.');
161
+ throw new UtxoSetImportError('No crawler cursor yet. Start the crawler once before importing.');
174
162
  if ((0, sync_state_1.isCrawlerLeaseActive)(cursor))
175
- throw new UtxoSetImportError('Crawler is running — pause it first (pauseCrawler).');
163
+ throw new UtxoSetImportError('Crawler is running. Pause it first (pauseCrawler).');
176
164
  if (cursor.lastSlot > anchor.slot) {
177
- throw new UtxoSetImportError(`Crawler cursor (slot ${cursor.lastSlot}) is past the anchor (slot ${anchor.slot}) — blocks after the anchor were ` +
165
+ throw new UtxoSetImportError(`Crawler cursor (slot ${cursor.lastSlot}) is past the anchor (slot ${anchor.slot}). Blocks after the anchor were ` +
178
166
  'already crawled without a set to apply them to. Dump the set at or after the cursor.');
179
167
  }
180
168
  if (source === 'file' && !opts.filePath)
@@ -234,15 +222,12 @@ async function importUtxoSet(opts) {
234
222
  }
235
223
  });
236
224
  }
237
- /**
238
- * Hold the cursor lease for the whole run: a crawler start on any instance and a second import
239
- * are refused while it is held; renewed on a heartbeat (one at a time), released at the end.
240
- */
225
+ /** Hold the cursor lease for the whole run, so no crawler and no second import can start. */
241
226
  async function withImportLease(run) {
242
227
  const leaseOwner = `import:${process.pid}:${Date.now().toString(36)}`;
243
228
  const acquired = await cds_1.default.tx((tx) => (0, sync_state_1.tryAcquireImportLease)(tx, leaseOwner));
244
229
  if (!acquired)
245
- throw new UtxoSetImportError('Could not take the cursor lease — a crawler or another import holds it.');
230
+ throw new UtxoSetImportError('Could not take the cursor lease: a crawler or another import holds it.');
246
231
  let leaseLost = false;
247
232
  let renewing = false;
248
233
  const heartbeat = setInterval(() => {
@@ -283,11 +268,8 @@ async function withImportLease(run) {
283
268
  }
284
269
  /** A bigger sort/hash budget for the GROUP BY over millions of rows (PostgreSQL only). */
285
270
  const AGGREGATE_WORK_MEM = '256MB';
286
- /**
287
- * Aggregates + activation in ONE transaction, so the set is never `active` with sums a successor's
288
- * import has meanwhile truncated. `prepare` runs first; `finish` and the activation run last,
289
- * together with the lease check, so the cursor row is not locked during the aggregation.
290
- */
271
+ // Aggregates and activation share one transaction, so `active` never shows truncated sums.
272
+ // The lease check runs last, so the cursor row is not locked during the aggregation.
291
273
  async function activateWithAggregates(lease, indexer, anchor, hooks = {}) {
292
274
  const importedAt = new Date().toISOString();
293
275
  await lease.writeTxLeaseLast(async (tx) => {
@@ -308,36 +290,32 @@ async function activateWithAggregates(lease, indexer, anchor, hooks = {}) {
308
290
  indexer.resetPaymentCredentials();
309
291
  void indexer.paymentCredentialsReady();
310
292
  }
311
- /**
312
- * Rebuild only the sums (LedgerAddresses, LedgerAddressAssets, LedgerAccounts) from the rows an
313
- * earlier import left at the stored anchor, e.g. after the aggregate phase failed. Nothing may have
314
- * been applied since the anchor; a cursor past it is set back to the anchor, and the blocks after
315
- * it are crawled again (idempotent writes) so the set follows them.
316
- */
293
+ // Rebuild only the sums from rows an earlier import left, e.g. after the aggregate step failed.
294
+ // A cursor past the snapshot slot is set back, so the blocks after it are crawled again.
317
295
  async function rebuildUtxoSetAggregates(opts) {
318
296
  const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
319
297
  if (!cursor)
320
298
  throw new UtxoSetImportError('No crawler cursor yet.');
321
299
  if ((0, sync_state_1.isCrawlerLeaseActive)(cursor))
322
- throw new UtxoSetImportError('Crawler is running — pause it first (pauseCrawler).');
300
+ throw new UtxoSetImportError('Crawler is running. Pause it first (pauseCrawler).');
323
301
  const { anchorSlot, anchorHash, appliedSlot, status } = cursor.utxoSet;
324
302
  if (anchorSlot == null || !anchorHash)
325
- throw new UtxoSetImportError('No imported UTxO set to rebuild the sums from — run importUtxoSet first.');
303
+ throw new UtxoSetImportError('No imported UTxO set to rebuild the sums from: run importUtxoSet first.');
326
304
  if (status === 'importing')
327
305
  throw new UtxoSetImportError('The import is still loading rows (status "importing").');
328
306
  if (appliedSlot != null) {
329
- throw new UtxoSetImportError(`Blocks up to slot ${appliedSlot} were already applied to the set — its rows are past the anchor; import again.`);
307
+ throw new UtxoSetImportError(`Blocks up to slot ${appliedSlot} were already applied to the set. Its rows are past the anchor; import again.`);
330
308
  }
331
309
  const anchor = { slot: anchorSlot, hash: anchorHash };
332
310
  const rows = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.LedgerUTxOs).columns('count(*) as n')));
333
311
  const utxos = Number(rows?.n ?? 0);
334
312
  if (utxos === 0)
335
- throw new UtxoSetImportError('LedgerUTxOs is empty — run importUtxoSet first.');
313
+ throw new UtxoSetImportError('LedgerUTxOs is empty: run importUtxoSet first.');
336
314
  let rewindTo = null;
337
315
  if (cursor.lastSlot > anchor.slot) {
338
316
  const block = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.Blocks).columns('height').where({ hash: anchor.hash })));
339
317
  if (!block)
340
- throw new UtxoSetImportError(`Cursor is past the anchor and the anchor block ${anchor.hash} is not stored — cannot set the cursor back.`);
318
+ throw new UtxoSetImportError(`Cursor is past the anchor and the anchor block ${anchor.hash} is not stored, cannot set the cursor back.`);
341
319
  rewindTo = { slot: anchor.slot, hash: anchor.hash, height: Number(block.height ?? 0) };
342
320
  }
343
321
  return withImportLease(async (lease) => {
@@ -366,20 +344,16 @@ async function rebuildUtxoSetAggregates(opts) {
366
344
  return { utxos, anchor };
367
345
  });
368
346
  }
369
- /**
370
- * Fill the reference-script columns (hash, size, type) of `LedgerUTxOs` rows an earlier import
371
- * left empty: from the same cardano-cli dump, or, without a file, from the node for the unspent
372
- * rows that hold a hash but no size. Takes the cursor lease like an import, so the crawler must
373
- * be paused; the set stays `active` throughout.
374
- */
347
+ // Fill reference-script columns an earlier import left empty, from the dump or from the node.
348
+ // Takes the cursor lease, so the crawler must be paused. The set stays `active`.
375
349
  async function refreshUtxoSetReferenceScripts(opts) {
376
350
  const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
377
351
  if (!cursor)
378
352
  throw new UtxoSetImportError('No crawler cursor yet.');
379
353
  if ((0, sync_state_1.isCrawlerLeaseActive)(cursor))
380
- throw new UtxoSetImportError('Crawler is running — pause it first (pauseCrawler).');
354
+ throw new UtxoSetImportError('Crawler is running. Pause it first (pauseCrawler).');
381
355
  if (cursor.utxoSet.anchorSlot == null)
382
- throw new UtxoSetImportError('No imported UTxO set — run importUtxoSet first.');
356
+ throw new UtxoSetImportError('No imported UTxO set: run importUtxoSet first.');
383
357
  const batchSize = opts.batchSize ?? 2000;
384
358
  return withImportLease(async (lease) => {
385
359
  let candidates = 0;
@@ -413,7 +387,7 @@ async function refreshUtxoSetReferenceScripts(opts) {
413
387
  else {
414
388
  const backend = opts.client.getLedgerStateBackend();
415
389
  if (!backend)
416
- throw new UtxoSetImportError('No Ogmios backend available — pass the cardano-cli dump as filePath instead.');
390
+ throw new UtxoSetImportError('No Ogmios backend available. Pass the cardano-cli dump as filePath instead.');
417
391
  const rows = await cds_1.default.tx((tx) => tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('txHash', 'outputIndex')
418
392
  .where({ spentTxHash: null, utxo_referenceScriptHash: { '!=': null }, utxo_referenceScriptSize: null })));
419
393
  candidates = rows?.length ?? 0;
@@ -1,10 +1,6 @@
1
1
  import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import { type LedgerUTxO, type LedgerUTxOAsset } from '#cds-models/odatano/cardano';
2
3
  import type { Amount, BlockData, Transaction as ProviderTransaction, ReferenceScriptType } from '../utils/types';
3
- /**
4
- * Crawler-fed ledger state (`crawler.utxoSet`): UTxO set + per-address/per-stake-key running
5
- * sums in non-temporal tables. Only blocks AFTER the imported anchor are applied; a reorg past
6
- * the anchor invalidates the set, one after it is undone by a recount of the open rows.
7
- */
8
4
  /** The point the imported UTxO set describes; blocks with slot > anchor.slot are applied. */
9
5
  export interface LedgerAnchor {
10
6
  slot: number;
@@ -13,40 +9,24 @@ export interface LedgerAnchor {
13
9
  export interface LedgerApplyResult {
14
10
  created: number;
15
11
  spent: number;
16
- /** Consumed outpoints with no open row — a gap between snapshot and crawl, never expected. */
12
+ /** Consumed outputs with no open row. Means a gap between snapshot and crawl, never expected. */
17
13
  missing: number;
18
14
  addresses: number;
19
15
  }
20
- /** DB row of `LedgerUTxOs` (flattened struct columns as CAP names them). */
21
- export interface LedgerUtxoRow {
22
- txHash: string;
23
- outputIndex: number;
16
+ /** A `LedgerUTxOs` row as the block path writes it: every column set, lovelace as an exact string. */
17
+ export type LedgerUtxoRow = Required<Omit<LedgerUTxO, 'assets' | 'lovelace' | 'utxo_referenceScriptType' | 'address' | 'addressType' | 'isScript' | 'hasAssets'>> & {
24
18
  address: string;
25
- stakeAddress: string | null;
26
19
  addressType: string;
27
20
  isScript: boolean;
21
+ hasAssets: boolean;
28
22
  lovelace: string;
29
- createdSlot: number | null;
30
- spentTxHash: string | null;
31
- spentSlot: number | null;
32
- utxo_dataHash: string | null;
33
- utxo_inlineDatum: string | null;
34
- utxo_referenceScriptHash: string | null;
35
- utxo_referenceScriptSize: number | null;
36
23
  utxo_referenceScriptType: ReferenceScriptType | null;
37
- utxo_paymentCredential: string | null;
38
- hasAssets: boolean;
39
- }
40
- export interface LedgerUtxoAssetRow {
41
- utxo_txHash: string;
42
- utxo_outputIndex: number;
43
- unit: string;
24
+ };
25
+ /** A `LedgerUTxOAssets` row as the block path writes it. */
26
+ export type LedgerUtxoAssetRow = Required<Omit<LedgerUTxOAsset, 'utxo' | 'asset_fingerprint' | 'asset_quantity'>> & {
44
27
  asset_quantity: string;
45
- asset_policyId: string | null;
46
- asset_assetNameHex: string | null;
47
- asset_assetName: string | null;
48
- }
49
- /** Minimal output shape the row builder needs — shared by the block path and the import. */
28
+ };
29
+ /** Minimal output shape the row builder needs, shared by the block path and the import. */
50
30
  export interface LedgerOutputLike {
51
31
  txHash: string;
52
32
  outputIndex: number;
@@ -70,37 +50,13 @@ export interface LedgerLookup {
70
50
  rows: Map<string, LedgerUtxoRow>;
71
51
  assets: Map<string, LedgerUtxoAssetRow[]>;
72
52
  }
73
- /**
74
- * Read the ledger rows of the given source transactions. Asset rows are read only for
75
- * transactions with at least one row carrying assets, so an ada-only block costs one SELECT.
76
- */
77
53
  export declare function readLedgerOutputs(tx: CapTransaction, txHashes: Iterable<string>, into?: LedgerLookup): Promise<LedgerLookup>;
78
54
  /** Amount list (lovelace + native assets) of a ledger row, the shape a resolved input carries. */
79
55
  export declare function ledgerRowAmount(row: LedgerUtxoRow, assets: LedgerUtxoAssetRow[] | undefined): Amount[];
80
- /**
81
- * Apply one block to the ledger tables. Caller guarantees `block.slot > anchor.slot`.
82
- * `lookup` may carry rows the caller already read for this block (input resolution).
83
- * Never throws for a missing outpoint (it is counted and logged); DB errors propagate so the
84
- * block transaction rolls back as a whole.
85
- */
86
56
  export declare function applyBlockToLedger(tx: CapTransaction, block: BlockData, txs: ProviderTransaction[], lookup?: LedgerLookup): Promise<LedgerApplyResult>;
87
- /**
88
- * Reorg undo for a set of rolled-back transactions: drop what they created, reopen what
89
- * they spent, then recount every address either side touched from the open rows.
90
- * @returns the recounted addresses
91
- */
92
57
  export declare function undoLedgerForTransactions(tx: CapTransaction, txHashes: string[]): Promise<string[]>;
93
- /**
94
- * Recount running sums for the given addresses from their open UTxO rows, then the
95
- * stake keys those addresses belong to. Also the repair path for a drifted sum.
96
- */
97
58
  export declare function recountLedgerAddresses(tx: CapTransaction, addresses: string[]): Promise<void>;
98
59
  /** Recount `LedgerAccounts` for the given stake keys from `LedgerAddresses`. */
99
60
  export declare function recountLedgerAccounts(tx: CapTransaction, stakeAddresses: string[]): Promise<void>;
100
- /**
101
- * Fill `LedgerAddresses.paymentCredential` where it is missing (rows from the import's SQL
102
- * aggregation, or written before the column existed). One transaction per chunk, idempotent.
103
- * @returns rows updated
104
- */
105
61
  export declare function backfillPaymentCredentials(chunkSize?: number): Promise<number>;
106
62
  //# sourceMappingURL=ledger-state.d.ts.map
@@ -27,7 +27,7 @@ function decodeAssetName(hex) {
27
27
  return null;
28
28
  try {
29
29
  const text = Buffer.from(hex, 'hex').toString('utf8');
30
- // printable only — a binary asset name has no useful decoded form
30
+ // printable only, a binary asset name has no useful decoded form
31
31
  return /^[\x20-\x7e]*$/.test(text) ? text : null;
32
32
  }
33
33
  catch {
@@ -98,10 +98,8 @@ function applyDelta(d, row, assets, sign) {
98
98
  d.assets.set(unit, (d.assets.get(unit) ?? 0n) + sign * BigInt(qty));
99
99
  }
100
100
  }
101
- /**
102
- * Read the ledger rows of the given source transactions. Asset rows are read only for
103
- * transactions with at least one row carrying assets, so an ada-only block costs one SELECT.
104
- */
101
+ // Read the ledger rows of the given source transactions. Asset rows are read only where a row
102
+ // has assets, so an ada-only block costs one SELECT.
105
103
  async function readLedgerOutputs(tx, txHashes, into) {
106
104
  const lookup = into ?? { hashes: new Set(), rows: new Map(), assets: new Map() };
107
105
  const todo = [...new Set(txHashes)].filter(h => !lookup.hashes.has(h));
@@ -131,12 +129,8 @@ function ledgerRowAmount(row, assets) {
131
129
  ...(assets ?? []).map(a => ({ unit: a.unit, quantity: String(a.asset_quantity) })),
132
130
  ];
133
131
  }
134
- /**
135
- * Apply one block to the ledger tables. Caller guarantees `block.slot > anchor.slot`.
136
- * `lookup` may carry rows the caller already read for this block (input resolution).
137
- * Never throws for a missing outpoint (it is counted and logged); DB errors propagate so the
138
- * block transaction rolls back as a whole.
139
- */
132
+ // Apply one block after the anchor. `lookup` may carry rows the caller already read.
133
+ // A missing output is counted, not thrown. DB errors propagate so the block transaction rolls back.
140
134
  async function applyBlockToLedger(tx, block, txs, lookup) {
141
135
  const slot = block.slot ?? 0;
142
136
  // 1) everything this block produces
@@ -147,7 +141,7 @@ async function applyBlockToLedger(tx, block, txs, lookup) {
147
141
  created.set(outpoint(t.hash, o.outputIndex), built);
148
142
  }
149
143
  }
150
- // 2) everything this block consumes — same-block outputs first, the rest from the DB
144
+ // 2) everything this block consumes, same-block outputs first, the rest from the DB
151
145
  const lookups = [];
152
146
  const spentInBlock = new Set();
153
147
  for (const t of txs) {
@@ -172,7 +166,7 @@ async function applyBlockToLedger(tx, block, txs, lookup) {
172
166
  if (!row || row.spentTxHash) {
173
167
  missing++;
174
168
  if (missing <= 3) {
175
- logger.warn(`ledger: ${l.spender} consumes ${l.key} which has no open row (${row ? 'already spent' : 'unknown'}) — snapshot gap?`);
169
+ logger.warn(`ledger: ${l.spender} consumes ${l.key} which has no open row (${row ? 'already spent' : 'unknown'}), snapshot gap?`);
176
170
  }
177
171
  continue;
178
172
  }
@@ -297,11 +291,8 @@ async function applyBlockToLedger(tx, block, txs, lookup) {
297
291
  }
298
292
  return { created: created.size, spent: spentInBlock.size + spentRows.length, missing, addresses: touched.length };
299
293
  }
300
- /**
301
- * Reorg undo for a set of rolled-back transactions: drop what they created, reopen what
302
- * they spent, then recount every address either side touched from the open rows.
303
- * @returns the recounted addresses
304
- */
294
+ // Undo rolled-back transactions: drop what they created, reopen what they spent,
295
+ // then recount every touched address. Returns the recounted addresses.
305
296
  async function undoLedgerForTransactions(tx, txHashes) {
306
297
  if (!txHashes.length)
307
298
  return [];
@@ -321,10 +312,7 @@ async function undoLedgerForTransactions(tx, txHashes) {
321
312
  await recountLedgerAddresses(tx, addresses);
322
313
  return addresses;
323
314
  }
324
- /**
325
- * Recount running sums for the given addresses from their open UTxO rows, then the
326
- * stake keys those addresses belong to. Also the repair path for a drifted sum.
327
- */
315
+ // Recount the sums of these addresses and their stake keys from open rows. Also repairs a drifted sum.
328
316
  async function recountLedgerAddresses(tx, addresses) {
329
317
  const stakes = new Set();
330
318
  for (const address of addresses) {
@@ -408,11 +396,7 @@ async function recountLedgerAccounts(tx, stakeAddresses) {
408
396
  }
409
397
  /** Address types that carry a payment credential. */
410
398
  const CREDENTIAL_ADDRESS_TYPES = ['base', 'pointer', 'enterprise'];
411
- /**
412
- * Fill `LedgerAddresses.paymentCredential` where it is missing (rows from the import's SQL
413
- * aggregation, or written before the column existed). One transaction per chunk, idempotent.
414
- * @returns rows updated
415
- */
399
+ // Fill a missing `LedgerAddresses.paymentCredential`, one transaction per chunk. Returns rows updated.
416
400
  async function backfillPaymentCredentials(chunkSize = 1000) {
417
401
  let updated = 0;
418
402
  for (;;) {
@@ -1,13 +1,6 @@
1
1
  import type { UTxO } from '../utils/types';
2
2
  /** How long a submitted transaction counts as pending when no crawled block confirms it earlier. */
3
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
4
  export declare class PendingSpends {
12
5
  private readonly now;
13
6
  private readonly txs;
@@ -16,11 +9,6 @@ export declare class PendingSpends {
16
9
  record(signedTxCbor: string): void;
17
10
  /** The pending transaction that spends this output, if any. */
18
11
  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
12
  apply(address: string, utxos: UTxO[]): UTxO[];
25
13
  get size(): number;
26
14
  private prune;
@@ -10,13 +10,8 @@ const logger = cds_1.default.log('PendingSpends');
10
10
  /** How long a submitted transaction counts as pending when no crawled block confirms it earlier. */
11
11
  exports.PENDING_TX_TTL_MS = 10 * 60_000;
12
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
- */
13
+ // Submitted transactions still in the mempool, whose inputs still look unspent. Builders skip
14
+ // those inputs and may spend the pending change. Entries end when crawled or after PENDING_TX_TTL_MS.
20
15
  class PendingSpends {
21
16
  now;
22
17
  txs = new Map();
@@ -54,11 +49,8 @@ class PendingSpends {
54
49
  return hash;
55
50
  return undefined;
56
51
  }
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
- */
52
+ // The address's UTxOs after the pending transactions. One whose outputs already appear in `utxos`
53
+ // has been crawled and is forgotten.
62
54
  apply(address, utxos) {
63
55
  this.prune();
64
56
  if (this.txs.size === 0)
@@ -1,21 +1,7 @@
1
- /**
2
- * RequestCoalescer — Deduplicates concurrent requests for the same resource key.
3
- *
4
- * When multiple callers request the same key simultaneously (e.g., same txHash
5
- * during parallel address indexing), only one backend call is made. All callers
6
- * receive the same Promise/result.
7
- */
1
+ /** Concurrent requests for the same key share one backend call and its result. */
8
2
  export declare class RequestCoalescer<T> {
9
3
  private pending;
10
- /**
11
- * Get a value by key, deduplicating concurrent requests.
12
- * If a request for this key is already in-flight, returns the existing Promise.
13
- * Otherwise, calls the fetcher and caches the Promise until it resolves.
14
- *
15
- * @param key Unique identifier (e.g., txHash, bech32 address)
16
- * @param fetcher Function that performs the actual fetch
17
- * @returns The fetched value
18
- */
4
+ /** Returns the in-flight promise for this key, or starts the fetcher. */
19
5
  get(key: string, fetcher: () => Promise<T>): Promise<T>;
20
6
  /** Number of currently in-flight requests */
21
7
  get size(): number;
@@ -1,24 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RequestCoalescer = void 0;
4
- /**
5
- * RequestCoalescer — Deduplicates concurrent requests for the same resource key.
6
- *
7
- * When multiple callers request the same key simultaneously (e.g., same txHash
8
- * during parallel address indexing), only one backend call is made. All callers
9
- * receive the same Promise/result.
10
- */
4
+ /** Concurrent requests for the same key share one backend call and its result. */
11
5
  class RequestCoalescer {
12
6
  pending = new Map();
13
- /**
14
- * Get a value by key, deduplicating concurrent requests.
15
- * If a request for this key is already in-flight, returns the existing Promise.
16
- * Otherwise, calls the fetcher and caches the Promise until it resolves.
17
- *
18
- * @param key Unique identifier (e.g., txHash, bech32 address)
19
- * @param fetcher Function that performs the actual fetch
20
- * @returns The fetched value
21
- */
7
+ /** Returns the in-flight promise for this key, or starts the fetcher. */
22
8
  async get(key, fetcher) {
23
9
  const existing = this.pending.get(key);
24
10
  if (existing)
@@ -1,7 +1,3 @@
1
- /**
2
- * Input to {@link verifyDataSignature}, mirroring the CIP-30 `signData` result:
3
- * `coseSignature` = hex `signature` field (COSE_Sign1), `coseKey` = hex `key` field (COSE_Key).
4
- */
5
1
  export interface CoseVerifyInput {
6
2
  address: string;
7
3
  coseSignature: string;
@@ -18,10 +14,5 @@ export interface CoseVerifyResult {
18
14
  /** hex blake2b-224 of the signer public key (empty until the key is parsed) */
19
15
  signerVkh: string;
20
16
  }
21
- /**
22
- * Verify a CIP-30 `signData` (COSE_Sign1) signature against a bech32 address: signer key hash
23
- * (blake2b-224) must equal the address payment key credential, optional payload check, then
24
- * Ed25519 over the Sig_structure. Stateless, no nonce/replay handling; never throws (`{ valid: false, reason }`).
25
- */
26
17
  export declare function verifyDataSignature(input: CoseVerifyInput): CoseVerifyResult;
27
18
  //# sourceMappingURL=cose-verifier.d.ts.map
@@ -56,11 +56,8 @@ function parseCoseKey(hex) {
56
56
  }
57
57
  return x.bytes;
58
58
  }
59
- /**
60
- * Build the COSE Sig_structure that was actually signed and CBOR-encode it:
61
- * [ "Signature1" (tstr), protected (bstr, exact bytes), external_aad (h''), payload (bstr) ]
62
- * external_aad is empty for CIP-8 / CIP-30 signData.
63
- */
59
+ // The signed COSE Sig_structure: ["Signature1", protected, external_aad, payload].
60
+ // external_aad is empty for CIP-8 and CIP-30 signData.
64
61
  function buildSigStructure(protectedBytes, payload) {
65
62
  const sigStruct = new cbor_1.CborArray([
66
63
  new cbor_1.CborText('Signature1'),
@@ -70,11 +67,8 @@ function buildSigStructure(protectedBytes, payload) {
70
67
  ]);
71
68
  return cbor_1.Cbor.encode(sigStruct);
72
69
  }
73
- /**
74
- * Verify a CIP-30 `signData` (COSE_Sign1) signature against a bech32 address: signer key hash
75
- * (blake2b-224) must equal the address payment key credential, optional payload check, then
76
- * Ed25519 over the Sig_structure. Stateless, no nonce/replay handling; never throws (`{ valid: false, reason }`).
77
- */
70
+ // The signer key hash must equal the address's payment credential, then Ed25519 is checked.
71
+ // Stateless, with no replay protection. Never throws, failures return `valid: false`.
78
72
  function verifyDataSignature(input) {
79
73
  const result = { valid: false, reason: '', signedPayload: '', signerVkh: '' };
80
74
  try {
@@ -1,9 +1,6 @@
1
1
  import { SignatureVerifier } from './signature-verifier';
2
2
  import { ExternalSignerType, UnsignedTxExportPayload, SignedTxPayload, SigningWorkflowState, SignatureVerificationResult, VerificationOptions } from '../../utils/types';
3
- /**
4
- * External signing workflow: create signing request → export unsigned tx → verify the
5
- * signed tx → prepare submission. No private keys are ever handled here.
6
- */
3
+ /** External signing workflow. No private keys are ever handled here. */
7
4
  export declare class ExternalSignerModule {
8
5
  private verifier;
9
6
  private signingTtlMs;
@@ -19,10 +19,7 @@ const CLI_NETWORK_FLAG = {
19
19
  preprod: '--testnet-magic 1',
20
20
  preview: '--testnet-magic 2',
21
21
  };
22
- /**
23
- * Copy-pasteable cardano-cli signing recipe for the unsigned tx (network flag and CBOR
24
- * filled in; the caller supplies the signing key file).
25
- */
22
+ /** cardano-cli signing recipe for the unsigned tx. The caller supplies the key file. */
26
23
  function buildCardanoCliCommand(network, unsignedTxCbor) {
27
24
  const netFlag = CLI_NETWORK_FLAG[network] ?? '--testnet-magic <MAGIC>';
28
25
  return [
@@ -33,10 +30,7 @@ function buildCardanoCliCommand(network, unsignedTxCbor) {
33
30
  '# 3) Submit the cborHex from tx.signed via SubmitSignedTransaction / SubmitVerifiedTransaction',
34
31
  ].join('\n');
35
32
  }
36
- /**
37
- * External signing workflow: create signing request → export unsigned tx → verify the
38
- * signed tx → prepare submission. No private keys are ever handled here.
39
- */
33
+ /** External signing workflow. No private keys are ever handled here. */
40
34
  class ExternalSignerModule {
41
35
  verifier;
42
36
  signingTtlMs;
@@ -29,10 +29,7 @@ type Pkcs11JsModule = {
29
29
  type Pkcs11Loader = () => Pkcs11JsModule;
30
30
  /** Test seam: inject a fake pkcs11js module loader (null restores the default). */
31
31
  export declare function setPkcs11Loader(loader: Pkcs11Loader | null): void;
32
- /**
33
- * Ed25519 transaction signing through a PKCS#11 HSM (YubiHSM 2, CloudHSM, Luna, …); private
34
- * keys never leave the device. Lifecycle: init(network) → sign()/signTransaction() → shutdown().
35
- */
32
+ /** Ed25519 signing through a PKCS#11 HSM. Private keys never leave the device. */
36
33
  export declare class HsmSigner {
37
34
  private pkcs11;
38
35
  private session;
@@ -43,17 +40,11 @@ export declare class HsmSigner {
43
40
  private config;
44
41
  private connected;
45
42
  constructor(config: HsmConfig);
46
- /**
47
- * Open the PKCS#11 session, locate the key, export the public key and derive the
48
- * enterprise address for `network`. Called once at startup.
49
- */
43
+ /** Opens the session, exports the public key and derives the enterprise address. */
50
44
  init(network: 'mainnet' | 'preview' | 'preprod' | string): Promise<void>;
51
45
  /** Sign a 32-byte tx body hash in the HSM; returns Ed25519 signature + public key for the witness. */
52
46
  sign(txBodyHash: Buffer): HsmSignResult;
53
- /**
54
- * Sign the body hash (hex) in the HSM, build the VKey witness [publicKey, signature] and
55
- * splice it into the witness set at the raw CBOR level. Returns the signed tx CBOR (hex).
56
- */
47
+ /** Signs the body hash and splices the VKey witness in at the raw CBOR level. */
57
48
  signTransaction(unsignedTxCbor: string, txBodyHash: string): string;
58
49
  /** Get the HSM-derived Cardano enterprise address */
59
50
  getAddress(): string;
@@ -69,14 +60,11 @@ export declare class HsmSigner {
69
60
  publicKeyHash?: string;
70
61
  address?: string;
71
62
  };
72
- /** Graceful shutdown — close PKCS#11 session */
63
+ /** Closes the PKCS#11 session. */
73
64
  shutdown(): void;
74
- /** Find an Ed25519 key object (private or public) in the HSM by label and/or ID. */
65
+ /** Finds an Ed25519 key object in the HSM by label or ID. */
75
66
  private _findKey;
76
- /**
77
- * Export the Ed25519 public key from the HSM.
78
- * Handles both DER-wrapped (04 20 <32 bytes>) and raw 32-byte formats.
79
- */
67
+ /** Accepts a DER-wrapped and a raw 32-byte Ed25519 public key. */
80
68
  private _exportPublicKey;
81
69
  }
82
70
  /** The initialized HsmSigner, or null when HSM is not configured. */