@odatano/core 2.0.0-rc.43 → 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 (171) 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 +36 -20
  4. package/@cds-models/CardanoIndexerService/index.js +4 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +19 -47
  6. package/@cds-models/CardanoSignService/index.d.ts +3 -18
  7. package/@cds-models/CardanoTransactionService/index.d.ts +9 -31
  8. package/@cds-models/CardanoWorkerService/index.d.ts +3 -19
  9. package/@cds-models/index.d.ts +17 -0
  10. package/@cds-models/index.js +2 -0
  11. package/@cds-models/odatano/cardano/index.d.ts +1 -34
  12. package/README.md +6 -6
  13. package/db/schema.cds +29 -44
  14. package/db/types.cds +22 -5
  15. package/package.json +3 -1
  16. package/scripts/migrate-slot-leader.mjs +3 -11
  17. package/scripts/migrate-txseq.mjs +3 -12
  18. package/src/index.d.ts +0 -4
  19. package/src/index.js +3 -5
  20. package/src/plugin.js +4 -8
  21. package/srv/blockchain/asset-decimals.d.ts +7 -0
  22. package/srv/blockchain/asset-decimals.js +91 -0
  23. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -10
  24. package/srv/blockchain/backends/blockfrost-backend.js +15 -21
  25. package/srv/blockchain/backends/cardano-backend.d.ts +12 -71
  26. package/srv/blockchain/backends/koios-backend.d.ts +14 -147
  27. package/srv/blockchain/backends/koios-backend.js +40 -164
  28. package/srv/blockchain/backends/odatano-backend.d.ts +1 -11
  29. package/srv/blockchain/backends/odatano-backend.js +11 -12
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +13 -160
  31. package/srv/blockchain/backends/ogmios-backend.js +48 -175
  32. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +2 -18
  33. package/srv/blockchain/backends/ogmios-frame-guard.js +8 -20
  34. package/srv/blockchain/cardano-client.d.ts +12 -80
  35. package/srv/blockchain/cardano-client.js +36 -88
  36. package/srv/blockchain/cardano-indexer.d.ts +12 -192
  37. package/srv/blockchain/cardano-indexer.js +132 -222
  38. package/srv/blockchain/cardano-tx-builder.d.ts +1 -28
  39. package/srv/blockchain/cardano-tx-builder.js +17 -34
  40. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  41. package/srv/blockchain/circuit-breaker.js +5 -15
  42. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  43. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +0 -17
  45. package/srv/blockchain/crawler/certificate-backfill.js +8 -22
  46. package/srv/blockchain/crawler/crawler.d.ts +16 -93
  47. package/srv/blockchain/crawler/crawler.js +85 -160
  48. package/srv/blockchain/crawler/credential-backfill.d.ts +0 -9
  49. package/srv/blockchain/crawler/credential-backfill.js +6 -6
  50. package/srv/blockchain/crawler/hooks.d.ts +1 -5
  51. package/srv/blockchain/crawler/index.d.ts +0 -12
  52. package/srv/blockchain/crawler/index.js +6 -20
  53. package/srv/blockchain/crawler/sync-state.d.ts +6 -44
  54. package/srv/blockchain/crawler/sync-state.js +18 -53
  55. package/srv/blockchain/crawler/transaction-backfill.d.ts +0 -11
  56. package/srv/blockchain/crawler/transaction-backfill.js +11 -30
  57. package/srv/blockchain/crawler/utxo-set-import.d.ts +1 -30
  58. package/srv/blockchain/crawler/utxo-set-import.js +27 -53
  59. package/srv/blockchain/ledger-state.d.ts +10 -54
  60. package/srv/blockchain/ledger-state.js +11 -27
  61. package/srv/blockchain/pending-spends.d.ts +0 -12
  62. package/srv/blockchain/pending-spends.js +4 -12
  63. package/srv/blockchain/request-coalescer.d.ts +2 -16
  64. package/srv/blockchain/request-coalescer.js +2 -16
  65. package/srv/blockchain/signing/cose-verifier.d.ts +0 -9
  66. package/srv/blockchain/signing/cose-verifier.js +4 -10
  67. package/srv/blockchain/signing/external-signer.d.ts +1 -4
  68. package/srv/blockchain/signing/external-signer.js +2 -8
  69. package/srv/blockchain/signing/hsm-signer.d.ts +6 -18
  70. package/srv/blockchain/signing/hsm-signer.js +16 -28
  71. package/srv/blockchain/signing/signature-verifier.d.ts +1 -8
  72. package/srv/blockchain/signing/signature-verifier.js +9 -19
  73. package/srv/blockchain/signing/submission-finalizer.d.ts +10 -16
  74. package/srv/blockchain/signing/submission-finalizer.js +48 -19
  75. package/srv/blockchain/stored-chain.d.ts +1 -14
  76. package/srv/blockchain/stored-chain.js +3 -8
  77. package/srv/blockchain/transaction-building/buildooor-fee-patch.d.ts +0 -4
  78. package/srv/blockchain/transaction-building/buildooor-fee-patch.js +4 -9
  79. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +7 -150
  80. package/srv/blockchain/transaction-building/buildooor-tx.js +91 -196
  81. package/srv/blockchain/transaction-building/caller-datums.d.ts +0 -14
  82. package/srv/blockchain/transaction-building/caller-datums.js +3 -9
  83. package/srv/blockchain/transaction-building/cardano-tx.d.ts +1 -4
  84. package/srv/blockchain/wallet-worker/build-request.d.ts +0 -5
  85. package/srv/blockchain/wallet-worker/build-request.js +6 -9
  86. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -23
  87. package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -20
  88. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  89. package/srv/blockchain/wallet-worker/index.js +3 -5
  90. package/srv/blockchain/wallet-worker/job-store.d.ts +15 -65
  91. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  92. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -10
  93. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -12
  94. package/srv/blockchain/wallet-worker/signers.d.ts +3 -11
  95. package/srv/blockchain/wallet-worker/signers.js +3 -6
  96. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +3 -21
  97. package/srv/blockchain/wallet-worker/wallet-worker.js +47 -54
  98. package/srv/cardano-agent-service.cds +123 -146
  99. package/srv/cardano-agent-service.js +2 -5
  100. package/srv/cardano-backend-service.cds +10 -17
  101. package/srv/cardano-backend-service.js +7 -12
  102. package/srv/cardano-indexer-service.cds +35 -37
  103. package/srv/cardano-indexer-service.d.ts +5 -1
  104. package/srv/cardano-indexer-service.js +64 -33
  105. package/srv/cardano-service.cds +56 -40
  106. package/srv/cardano-service.js +42 -69
  107. package/srv/cardano-sign-service.cds +14 -23
  108. package/srv/cardano-sign-service.js +18 -24
  109. package/srv/cardano-tx-service.cds +27 -29
  110. package/srv/cardano-tx-service.js +60 -122
  111. package/srv/cardano-worker-service.cds +109 -125
  112. package/srv/cardano-worker-service.js +21 -31
  113. package/srv/cbor/cip68.d.ts +13 -0
  114. package/srv/cbor/cip68.js +56 -0
  115. package/srv/cbor/index.d.ts +1 -0
  116. package/srv/cbor/index.js +6 -1
  117. package/srv/cbor/parse.d.ts +3 -18
  118. package/srv/cbor/parse.js +2 -7
  119. package/srv/cbor/plutus-data-json.d.ts +0 -4
  120. package/srv/server.d.ts +5 -36
  121. package/srv/server.js +30 -51
  122. package/srv/utils/agent-grants-config.d.ts +0 -18
  123. package/srv/utils/agent-grants-config.js +6 -13
  124. package/srv/utils/agent-grants.d.ts +14 -68
  125. package/srv/utils/agent-grants.js +42 -60
  126. package/srv/utils/agent-token-auth.d.ts +0 -5
  127. package/srv/utils/agent-token-auth.js +2 -5
  128. package/srv/utils/backend-request-handler.d.ts +1 -1
  129. package/srv/utils/collections.d.ts +1 -4
  130. package/srv/utils/collections.js +1 -4
  131. package/srv/utils/const.d.ts +0 -18
  132. package/srv/utils/const.js +7 -18
  133. package/srv/utils/crypto.js +3 -5
  134. package/srv/utils/db-indexes.d.ts +2 -0
  135. package/srv/utils/db-indexes.js +22 -9
  136. package/srv/utils/db-sanitize.d.ts +1 -8
  137. package/srv/utils/db-sanitize.js +3 -8
  138. package/srv/utils/epoch-slots.d.ts +1 -8
  139. package/srv/utils/epoch-slots.js +3 -8
  140. package/srv/utils/error-codes.d.ts +0 -4
  141. package/srv/utils/error-codes.js +2 -4
  142. package/srv/utils/errors.d.ts +2 -22
  143. package/srv/utils/errors.js +13 -27
  144. package/srv/utils/liveness.d.ts +0 -4
  145. package/srv/utils/liveness.js +2 -4
  146. package/srv/utils/mappers.d.ts +0 -37
  147. package/srv/utils/mappers.js +22 -39
  148. package/srv/utils/network-context.js +2 -4
  149. package/srv/utils/paging.d.ts +31 -0
  150. package/srv/utils/paging.js +43 -0
  151. package/srv/utils/pg-inline-json.js +3 -7
  152. package/srv/utils/pg-order-nulls.js +2 -5
  153. package/srv/utils/plutus-placeholders.d.ts +0 -13
  154. package/srv/utils/plutus-placeholders.js +6 -13
  155. package/srv/utils/rate-limiter.d.ts +0 -8
  156. package/srv/utils/rate-limiter.js +2 -4
  157. package/srv/utils/reference-script.d.ts +0 -18
  158. package/srv/utils/reference-script.js +8 -19
  159. package/srv/utils/service-events.d.ts +0 -4
  160. package/srv/utils/service-events.js +2 -4
  161. package/srv/utils/signing-helper.d.ts +1 -8
  162. package/srv/utils/signing-helper.js +3 -8
  163. package/srv/utils/tx-build-helper.d.ts +2 -32
  164. package/srv/utils/tx-build-helper.js +26 -40
  165. package/srv/utils/tx-request-parsers.d.ts +1 -25
  166. package/srv/utils/tx-request-parsers.js +10 -25
  167. package/srv/utils/tx-utils.d.ts +0 -8
  168. package/srv/utils/tx-utils.js +10 -13
  169. package/srv/utils/types.d.ts +2 -37
  170. package/srv/utils/validators.d.ts +0 -4
  171. package/srv/utils/validators.js +2 -4
@@ -32,43 +32,16 @@ export declare class CardanoTransactionBuilder {
32
32
  buildMintTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
33
33
  /** Build a Plutus spending transaction (consume a UTxO at a script address). */
34
34
  buildPlutusSpendTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
35
- /**
36
- * Several script inputs in one transaction: resolve every script UTxO and every reference-script
37
- * UTxO (one ledger lookup each), plus the sender's UTxOs, forced and reference inputs.
38
- */
35
+ /** Several script inputs in one transaction. */
39
36
  buildPlutusTransaction(req: TxBuildPlutusRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
40
- /**
41
- * The ledger rejects a withdrawal from an unregistered reward account (also a zero one), so the
42
- * build fails here with the account named. A provider failure is passed on as it is. When no
43
- * backend can tell, the build goes on and the node decides at submit.
44
- */
45
37
  private _assertRewardAccountsRegistered;
46
- /**
47
- * Resolve the script UTxO of a Plutus spend from the node's ledger, otherwise from its producing
48
- * transaction. Spending an already-consumed script UTxO is the most common replay mistake —
49
- * both paths reject it with a clear 400 instead of a node-side rejection at submit.
50
- */
51
38
  private _resolveScriptUtxo;
52
- /**
53
- * Unspent outputs for `refs` from the node's ledger, keyed "txHash#index"; null when no
54
- * ledger-state backend is usable or the query fails (callers fall back to getTransaction).
55
- */
56
39
  private _lookupUnspent;
57
- /**
58
- * Verify that an output resolved via getTransaction is still unspent against the live UTxO
59
- * set of its address (getTransaction only proves it existed). Lookup failures are tolerated.
60
- */
61
40
  private _assertUnspent;
62
41
  /** Resolve forced-input refs (consumed) to full UTxO records. */
63
42
  private _resolveForceInputs;
64
43
  /** Resolve CIP-31 reference-input refs (read-only, not merged into the coin-selection set). */
65
44
  private _resolveReferenceInputs;
66
- /**
67
- * Resolve {txHash, outputIndex} refs to full UTxO records: known UTxOs first, then the node's
68
- * ledger, otherwise the producing transaction plus an unspent check. Throws
69
- * TransactionValidationError (labelled by `kind`) for a missing or spent ref. Refs are
70
- * deduplicated; order is preserved.
71
- */
72
45
  private _resolveInputRefs;
73
46
  /** Fetch the UTxOs of an address; throws InsufficientFundsError when it has none. */
74
47
  private _fetchUtxosForAddress;
@@ -110,7 +110,7 @@ class CardanoTransactionBuilder {
110
110
  const cardanoClient = this.client;
111
111
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
112
112
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
113
- // Resolve CIP-31 reference inputs (read-only, not consumed — kept separate from coin-selection set)
113
+ // CIP-31 reference inputs are not consumed, so they stay out of coin selection.
114
114
  const referenceInputUtxos = await this._resolveReferenceInputs(req.referenceInputs ?? [], senderUtxos);
115
115
  const txContext = {
116
116
  utxos: mergeUtxosUnique(senderUtxos, forcedUtxos),
@@ -149,11 +149,11 @@ class CardanoTransactionBuilder {
149
149
  if (!alreadyIncluded) {
150
150
  allUtxos.push(await this._resolveScriptUtxo(scriptRef));
151
151
  }
152
- // Resolve forced inputs (may overlap with sender UTxOs or the script UTxO — dedup below).
153
- // The builder itself will skip any forced ref that matches scriptRef.
152
+ // Forced inputs may overlap with sender UTxOs, dedup below.
153
+ // The builder skips a forced ref that matches scriptRef.
154
154
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], allUtxos);
155
155
  const mergedUtxos = mergeUtxosUnique(allUtxos, forcedUtxos);
156
- // Resolve CIP-31 reference inputs (read-only, not consumed — kept separate from coin-selection set)
156
+ // CIP-31 reference inputs are not consumed, so they stay out of coin selection.
157
157
  const referenceInputUtxos = await this._resolveReferenceInputs(req.referenceInputs ?? [], allUtxos);
158
158
  const txContext = {
159
159
  utxos: mergedUtxos,
@@ -174,10 +174,7 @@ class CardanoTransactionBuilder {
174
174
  logger.debug(`Built Plutus spending transaction successfully.`);
175
175
  return txBuildResult;
176
176
  }
177
- /**
178
- * Several script inputs in one transaction: resolve every script UTxO and every reference-script
179
- * UTxO (one ledger lookup each), plus the sender's UTxOs, forced and reference inputs.
180
- */
177
+ /** Several script inputs in one transaction. */
181
178
  async buildPlutusTransaction(req, protocolParameters) {
182
179
  const builder = await this.ensureInitialized();
183
180
  const cardanoClient = this.client;
@@ -208,11 +205,8 @@ class CardanoTransactionBuilder {
208
205
  logger.debug(`Prepared multi-script build context: ${senderUtxos.length} sender + ${scriptUtxos.length} script + ${forcedUtxos.length} forced UTxOs, ${referenceInputUtxos.length} reference inputs`);
209
206
  return builder.buildUnsignedPlutusTransaction(req, txContext);
210
207
  }
211
- /**
212
- * The ledger rejects a withdrawal from an unregistered reward account (also a zero one), so the
213
- * build fails here with the account named. A provider failure is passed on as it is. When no
214
- * backend can tell, the build goes on and the node decides at submit.
215
- */
208
+ // The ledger rejects a withdrawal from an unregistered reward account, even a zero one.
209
+ // When no backend can tell, the build goes on and the node decides at submit.
216
210
  async _assertRewardAccountsRegistered(withdrawals, registeredHere = new Set()) {
217
211
  for (const [i, w] of withdrawals.entries()) {
218
212
  if (registeredHere.has(w.rewardAddress.toLowerCase()))
@@ -226,11 +220,8 @@ class CardanoTransactionBuilder {
226
220
  }
227
221
  }
228
222
  }
229
- /**
230
- * Resolve the script UTxO of a Plutus spend from the node's ledger, otherwise from its producing
231
- * transaction. Spending an already-consumed script UTxO is the most common replay mistake —
232
- * both paths reject it with a clear 400 instead of a node-side rejection at submit.
233
- */
223
+ // Spending an already-consumed script UTxO is a common replay mistake.
224
+ // Both lookup paths reject it with a clear 400 instead of a node rejection at submit.
234
225
  async _resolveScriptUtxo(scriptRef) {
235
226
  const by = this.client.pendingSpends?.spentBy(scriptRef.txHash, scriptRef.outputIndex);
236
227
  if (by)
@@ -260,10 +251,8 @@ class CardanoTransactionBuilder {
260
251
  scriptRef: scriptOutput.referenceScriptHash ?? undefined,
261
252
  };
262
253
  }
263
- /**
264
- * Unspent outputs for `refs` from the node's ledger, keyed "txHash#index"; null when no
265
- * ledger-state backend is usable or the query fails (callers fall back to getTransaction).
266
- */
254
+ // Null when no ledger-state backend is usable or the query fails.
255
+ // Callers then fall back to getTransaction.
267
256
  async _lookupUnspent(refs) {
268
257
  if (refs.length === 0)
269
258
  return new Map();
@@ -276,10 +265,8 @@ class CardanoTransactionBuilder {
276
265
  return null;
277
266
  }
278
267
  }
279
- /**
280
- * Verify that an output resolved via getTransaction is still unspent against the live UTxO
281
- * set of its address (getTransaction only proves it existed). Lookup failures are tolerated.
282
- */
268
+ // getTransaction only proves an output existed, so check the address's live UTxO set.
269
+ // Lookup failures are tolerated.
283
270
  async _assertUnspent(ref, address, kind, liveUtxoCache) {
284
271
  let live;
285
272
  try {
@@ -309,12 +296,8 @@ class CardanoTransactionBuilder {
309
296
  _resolveReferenceInputs(refs, knownUtxos) {
310
297
  return this._resolveInputRefs(refs, knownUtxos, 'referenceInput');
311
298
  }
312
- /**
313
- * Resolve {txHash, outputIndex} refs to full UTxO records: known UTxOs first, then the node's
314
- * ledger, otherwise the producing transaction plus an unspent check. Throws
315
- * TransactionValidationError (labelled by `kind`) for a missing or spent ref. Refs are
316
- * deduplicated; order is preserved.
317
- */
299
+ // Known UTxOs first, then the node's ledger, else the producing transaction plus an unspent check.
300
+ // Throws for a missing or spent ref. Refs are deduplicated in order.
318
301
  async _resolveInputRefs(refs, knownUtxos, kind) {
319
302
  if (!refs || refs.length === 0)
320
303
  return [];
@@ -398,8 +381,8 @@ class CardanoTransactionBuilder {
398
381
  logger.debug(`Found ${utxos.length} UTxOs for address ${address.substring(0, 20)}...`);
399
382
  if (utxos.length === 0) {
400
383
  throw new errors_1.InsufficientFundsError('lovelace', BigInt(0), BigInt(0), undefined, all.length > 0
401
- ? `address ${address} holds only UTxOs with a reference script — they are not spent as funding; pass one in forceInputsJson to consume it`
402
- : `address ${address} has no UTxOs — verify this is the correct sender address and that it has been funded`);
384
+ ? `address ${address} holds only UTxOs with a reference script; they are not spent as funding, pass one in forceInputsJson to consume it`
385
+ : `address ${address} has no UTxOs; verify this is the correct sender address and that it has been funded`);
403
386
  }
404
387
  return utxos;
405
388
  }
@@ -7,23 +7,11 @@ export interface CircuitBreakerConfig {
7
7
  /** Time in ms before transitioning from open to half-open (default: 30000) */
8
8
  resetTimeoutMs: number;
9
9
  }
10
- /**
11
- * Circuit Breaker for backend failover.
12
- * Tracks per-backend failure counts and prevents hammering unhealthy backends.
13
- *
14
- * States:
15
- * closed → normal operation, requests pass through
16
- * open → backend is unhealthy, requests are skipped
17
- * half-open → probe period, limited requests allowed to test recovery
18
- */
19
10
  export declare class CircuitBreakerManager {
20
11
  private circuits;
21
12
  private config;
22
13
  constructor(config?: Partial<CircuitBreakerConfig>);
23
- /**
24
- * Check if a backend should be attempted.
25
- * Transitions open → half-open if reset timeout has elapsed.
26
- */
14
+ /** Moves an open circuit to half-open once the reset timeout has elapsed. */
27
15
  shouldAttempt(backendName: string): boolean;
28
16
  /** Record a successful call to a backend. */
29
17
  recordSuccess(backendName: string): void;
@@ -11,25 +11,15 @@ const DEFAULT_CONFIG = {
11
11
  successThreshold: 2,
12
12
  resetTimeoutMs: 30_000,
13
13
  };
14
- /**
15
- * Circuit Breaker for backend failover.
16
- * Tracks per-backend failure counts and prevents hammering unhealthy backends.
17
- *
18
- * States:
19
- * closed → normal operation, requests pass through
20
- * open → backend is unhealthy, requests are skipped
21
- * half-open → probe period, limited requests allowed to test recovery
22
- */
14
+ // Per-backend circuit breaker. Closed passes requests, open skips the backend.
15
+ // Half-open lets a few probe requests through to test recovery.
23
16
  class CircuitBreakerManager {
24
17
  circuits = new Map();
25
18
  config;
26
19
  constructor(config) {
27
20
  this.config = { ...DEFAULT_CONFIG, ...config };
28
21
  }
29
- /**
30
- * Check if a backend should be attempted.
31
- * Transitions open → half-open if reset timeout has elapsed.
32
- */
22
+ /** Moves an open circuit to half-open once the reset timeout has elapsed. */
33
23
  shouldAttempt(backendName) {
34
24
  const entry = this.circuits.get(backendName);
35
25
  if (!entry)
@@ -47,8 +37,8 @@ class CircuitBreakerManager {
47
37
  }
48
38
  return false;
49
39
  }
50
- // half-open: cap in-flight probes at successThreshold — previously a burst
51
- // of concurrent requests all probed a barely-recovering backend at once
40
+ // half-open: cap in-flight probes at successThreshold, so a burst of
41
+ // concurrent requests does not all probe a barely-recovering backend
52
42
  if (entry.halfOpenProbes >= this.config.successThreshold) {
53
43
  return false;
54
44
  }
@@ -0,0 +1,15 @@
1
+ export interface DecimalsBackfillProgress {
2
+ /** Catalogue rows read. */
3
+ scanned: number;
4
+ /** Units with label 333 or 444. */
5
+ candidates: number;
6
+ /** Units that received a decimals value. */
7
+ filled: number;
8
+ }
9
+ export interface DecimalsBackfillOptions {
10
+ /** Rows per page. */
11
+ chunkSize?: number;
12
+ onProgress?: (p: DecimalsBackfillProgress) => void;
13
+ }
14
+ export declare function backfillAssetDecimals(opts?: DecimalsBackfillOptions): Promise<DecimalsBackfillProgress>;
15
+ //# sourceMappingURL=asset-decimals-backfill.d.ts.map
@@ -0,0 +1,56 @@
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.backfillAssetDecimals = backfillAssetDecimals;
7
+ const cds_1 = __importDefault(require("@sap/cds"));
8
+ const cardano_1 = require("#cds-models/odatano/cardano");
9
+ const cip68_1 = require("../../cbor/cip68");
10
+ const asset_decimals_1 = require("../asset-decimals");
11
+ const { SELECT } = cds_1.default.ql;
12
+ const logger = cds_1.default.log('DecimalsBackfill');
13
+ // Fill Assets.decimals from the CIP-68 reference datum for label 333 and 444 units. Pages by unit
14
+ // only, so the query plan never depends on column statistics. A repeat run refreshes the values.
15
+ async function backfillAssetDecimals(opts = {}) {
16
+ const chunkSize = opts.chunkSize ?? 5000;
17
+ const progress = { scanned: 0, candidates: 0, filled: 0 };
18
+ let cursor = null;
19
+ for (;;) {
20
+ const done = await cds_1.default.tx(async (tx) => {
21
+ const rows = (await tx.run(SELECT.from(cardano_1.Assets).columns('unit', 'initialMintTxHash').where(cursor ? { unit: { '>': cursor } } : {}).orderBy('unit').limit(chunkSize))) ?? [];
22
+ if (!rows.length)
23
+ return true;
24
+ const full = rows.length === chunkSize;
25
+ const lastUnit = rows[rows.length - 1].unit;
26
+ const allSame = rows.every((r) => r.unit === lastUnit);
27
+ // The slices of a unit are adjacent. The last unit of a full page may continue on the next
28
+ // one, so its rows wait there; a page holding one unit only is resolved as a whole.
29
+ const complete = full && !allSame ? rows.filter((r) => r.unit !== lastUnit) : rows;
30
+ const mints = new Map();
31
+ for (const r of complete) {
32
+ if (!(0, cip68_1.cip68ReferenceUnit)(r.unit))
33
+ continue;
34
+ if (!mints.has(r.unit) || r.initialMintTxHash)
35
+ mints.set(r.unit, r.initialMintTxHash ?? null);
36
+ }
37
+ for (const [unit, mintTxHash] of mints) {
38
+ const decimals = await (0, asset_decimals_1.cip68Decimals)(tx, unit, mintTxHash);
39
+ if (decimals == null)
40
+ continue;
41
+ await (0, asset_decimals_1.setAssetDecimals)(tx, unit, decimals);
42
+ progress.filled++;
43
+ }
44
+ progress.scanned += complete.length;
45
+ progress.candidates += mints.size;
46
+ cursor = complete[complete.length - 1].unit;
47
+ return !full;
48
+ });
49
+ opts.onProgress?.({ ...progress });
50
+ if (done)
51
+ break;
52
+ }
53
+ logger.info(`asset decimals filled: ${progress.filled} of ${progress.candidates} CIP-68 units, ${progress.scanned} catalogue rows read`);
54
+ return progress;
55
+ }
56
+ //# sourceMappingURL=asset-decimals-backfill.js.map
@@ -2,13 +2,6 @@ import type { Transaction as CapTransaction } from '@sap/cds';
2
2
  import type { CardanoClient } from '../cardano-client';
3
3
  import type { ChainPoint } from '../backends/cardano-backend';
4
4
  import type { BlockData, Transaction } from '../../utils/types';
5
- /**
6
- * Fills `TransactionCertificates` and `TransactionWithdrawals` for blocks the crawl already
7
- * holds, from a second chain-sync stream. Only those two tables are written, keyed so a
8
- * repeat is idempotent; the cursor, the block and transaction rows stay untouched and the
9
- * live crawler keeps its own stream. A block the index does not know (rolled back since) is
10
- * skipped, so no row can point at a transaction that is not there.
11
- */
12
5
  export declare class CertificateBackfillError extends Error {
13
6
  constructor(message: string);
14
7
  }
@@ -36,11 +29,6 @@ export interface CertificateBackfillResult extends CertificateBackfillProgress {
36
29
  /** The chain point the stream started after. */
37
30
  intersection: ChainPoint | 'origin';
38
31
  }
39
- /**
40
- * Newest indexed block strictly before `slot` inside the crawled range; the crawler's own
41
- * start point when none is. Lazily indexed blocks below the crawl start are never picked:
42
- * they may lie far back or on a fork the node no longer knows.
43
- */
44
32
  export declare function intersectionBefore(db: CapTransaction, slot: number): Promise<ChainPoint | 'origin'>;
45
33
  /** One streamed block of a backfill, with what the collector took from it. */
46
34
  export interface StreamedBlock<T> {
@@ -57,11 +45,6 @@ export interface CrawledBlockStreamOptions {
57
45
  /** Error class the range and backend checks throw. */
58
46
  errorType?: new (message: string) => Error;
59
47
  }
60
- /**
61
- * Streams the crawled range `fromSlot..toSlot` over a second chain-sync connection and hands
62
- * batches of blocks the index holds to `writeBatch`, each in its own DB transaction. A block
63
- * the index does not know (rolled back since) is skipped. Returns the intersection used.
64
- */
65
48
  export declare function streamCrawledBlocks<T>(opts: CrawledBlockStreamOptions, collect: (block: BlockData, txs: Transaction[]) => T, writeBatch: (tx: CapTransaction, blocks: StreamedBlock<T>[]) => Promise<void>, afterBatch: (toSlot: number) => void): Promise<ChainPoint | 'origin'>;
66
49
  export declare function backfillCertificates(opts: CertificateBackfillOptions): Promise<CertificateBackfillResult>;
67
50
  //# sourceMappingURL=certificate-backfill.d.ts.map
@@ -13,13 +13,8 @@ const sync_state_1 = require("./sync-state");
13
13
  const cardano_1 = require("#cds-models/odatano/cardano");
14
14
  const { SELECT, UPSERT } = cds_1.default.ql;
15
15
  const logger = cds_1.default.log('CertificateBackfill');
16
- /**
17
- * Fills `TransactionCertificates` and `TransactionWithdrawals` for blocks the crawl already
18
- * holds, from a second chain-sync stream. Only those two tables are written, keyed so a
19
- * repeat is idempotent; the cursor, the block and transaction rows stay untouched and the
20
- * live crawler keeps its own stream. A block the index does not know (rolled back since) is
21
- * skipped, so no row can point at a transaction that is not there.
22
- */
16
+ // Fill certificates and withdrawals for already crawled blocks from a second chain-sync stream.
17
+ // Only those two tables are written, and a repeat run is idempotent. Unknown blocks are skipped.
23
18
  class CertificateBackfillError extends Error {
24
19
  constructor(message) {
25
20
  super(message);
@@ -27,11 +22,8 @@ class CertificateBackfillError extends Error {
27
22
  }
28
23
  }
29
24
  exports.CertificateBackfillError = CertificateBackfillError;
30
- /**
31
- * Newest indexed block strictly before `slot` inside the crawled range; the crawler's own
32
- * start point when none is. Lazily indexed blocks below the crawl start are never picked:
33
- * they may lie far back or on a fork the node no longer knows.
34
- */
25
+ // Newest crawled block before `slot`, else the crawl start. Lazily indexed blocks below the start
26
+ // are never picked, since they may lie on a fork the node no longer knows.
35
27
  async function intersectionBefore(db, slot) {
36
28
  const cursor = await (0, sync_state_1.readCursor)(db);
37
29
  const floor = cursor?.startSlot ?? null;
@@ -43,11 +35,8 @@ async function intersectionBefore(db, slot) {
43
35
  return { slot: floor, hash: cursor.startBlockHash };
44
36
  return 'origin';
45
37
  }
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
- */
38
+ // Stream `fromSlot..toSlot` over a second chain-sync connection and pass stored blocks to
39
+ // `writeBatch`, one DB transaction per batch. Returns the intersection used.
51
40
  async function streamCrawledBlocks(opts, collect, writeBatch, afterBatch) {
52
41
  const { client, fromSlot, toSlot } = opts;
53
42
  const Err = opts.errorType ?? CertificateBackfillError;
@@ -61,10 +50,7 @@ async function streamCrawledBlocks(opts, collect, writeBatch, afterBatch) {
61
50
  const intersection = await cds_1.default.tx((tx) => intersectionBefore(tx, fromSlot));
62
51
  const points = intersection === 'origin' ? 'origin' : [intersection];
63
52
  let pending = [];
64
- /**
65
- * Writes a batch: the index's blocks of the batch's slot range are read once (a sequential
66
- * index range, not one random lookup per block) and only blocks the index holds are passed on.
67
- */
53
+ // Read the stored blocks of the batch's slot range in one range query, not one lookup per block.
68
54
  const flush = async () => {
69
55
  if (!pending.length)
70
56
  return;
@@ -77,7 +63,7 @@ async function streamCrawledBlocks(opts, collect, writeBatch, afterBatch) {
77
63
  const held = batch.filter((b) => {
78
64
  if (known.has(b.hash))
79
65
  return true;
80
- logger.warn(`Block ${b.hash} at slot ${b.slot} is not in the index — skipped`);
66
+ logger.warn(`Block ${b.hash} at slot ${b.slot} is not in the index, skipped`);
81
67
  return false;
82
68
  });
83
69
  await writeBatch(tx, held);
@@ -18,38 +18,21 @@ export interface CrawlerConfig {
18
18
  confirmationDepth: number;
19
19
  /** Poll cadence when caught up / on transient errors (pagination path). */
20
20
  pollIntervalMs: number;
21
- /** Write mint/burn rows into AssetHistory. Free — no provider call. */
21
+ /** Write mint and burn rows into AssetHistory. Needs no provider call. */
22
22
  assetHistory: boolean;
23
- /**
24
- * `off` — nothing; `bare` — one Assets row per unit from block data alone (free);
25
- * `enrich` — additionally resolve supply/registry data in the background, rate limited.
26
- */
23
+ /** `bare` writes one Assets row per unit from block data. `enrich` also fetches registry data, rate limited. */
27
24
  assetCatalogue: 'off' | 'bare' | 'enrich';
28
25
  /** Units per second the background enrichment resolves (`assetCatalogue: 'enrich'` only). */
29
26
  assetEnrichRate: number;
30
27
  /** Snapshot every pool, DRep and the ada pots at each epoch boundary (Ogmios, or Koios at the tip). */
31
28
  epochSnapshots: boolean;
32
- /**
33
- * Write TransactionCertificates + TransactionWithdrawals per block (ledger-state
34
- * coverage). Free on Ogmios chain-sync and Koios; Blockfrost does not report them.
35
- */
29
+ /** Write certificates and withdrawals per block. Ogmios and Koios report them, Blockfrost does not. */
36
30
  certificates: boolean;
37
- /**
38
- * Maintain the crawler-fed UTxO set (`LedgerUTxOs` / `LedgerAddresses` / `LedgerAccounts`).
39
- * Needs a one-off snapshot import (`importUtxoSet`) to become active.
40
- */
31
+ /** Maintain the Ledger* UTxO tables. Inactive until `importUtxoSet` has run once. */
41
32
  utxoSet: boolean;
42
- /**
43
- * Treat the crawled chain as complete: a block, transaction, metadata or asset the database
44
- * does not hold is answered 404 instead of asking a provider (crawl from Shelley, synced).
45
- */
33
+ /** Answer 404 for chain data the database lacks instead of asking a provider. Needs a full synced crawl. */
46
34
  authoritative?: boolean;
47
35
  }
48
- /**
49
- * Pre-sync engine: streams the chain forward from a start block and bulk-indexes it. Sources:
50
- * Ogmios chain-sync (primary, native rollBackward) or Blockfrost/Koios pagination (fallback).
51
- * Per-block writes are atomic; stop() awaits the detached pipeline; no implicit genesis crawl.
52
- */
53
36
  export declare class CardanoCrawler {
54
37
  private readonly client;
55
38
  private readonly indexer;
@@ -63,10 +46,7 @@ export declare class CardanoCrawler {
63
46
  private static readonly POISON_BLOCK_THRESHOLD;
64
47
  /** Process-wide, survives instance restarts: the block currently failing and how often. */
65
48
  private static poison;
66
- /**
67
- * Errors deterministic for the block's data — only these count towards the poison latch.
68
- * Outages, statement timeouts and exhausted pools are fixed by a restart and must not latch.
69
- */
49
+ /** Errors caused by the block's data. Only these count towards the poison latch, outages never do. */
70
50
  private static readonly DATA_REJECTION_PATTERNS;
71
51
  /** Timeout for direct backend calls (the crawler bypasses the client's resilience layer). */
72
52
  private static readonly CALL_TIMEOUT_MS;
@@ -85,7 +65,7 @@ export declare class CardanoCrawler {
85
65
  private chainSyncProbeTimer;
86
66
  private chainSyncProbe;
87
67
  private chainSyncRecovered;
88
- /** The detached ingest pipeline — awaited by stop() so teardown never races it. */
68
+ /** The detached ingest pipeline. stop() awaits it so teardown never races it. */
89
69
  private pipeline;
90
70
  /** Resolver that cancels a pending poll sleep (set while sleeping). */
91
71
  private wake;
@@ -103,7 +83,7 @@ export declare class CardanoCrawler {
103
83
  /** Resolves the ingest loop's wait for the current chain-sync stream to end. */
104
84
  private streamEnded;
105
85
  private finalStatus;
106
- /** Set only by an unrecoverable halt — clears desiredRunning so restarts stay down. */
86
+ /** Set only by an unrecoverable halt. It clears desiredRunning so restarts stay down. */
107
87
  private latchOnHalt;
108
88
  /** Distance to k at which a block no longer counts as acquirable (the tip moves on while we query). */
109
89
  private static readonly SNAPSHOT_WINDOW_MARGIN;
@@ -126,98 +106,41 @@ export declare class CardanoCrawler {
126
106
  haltedWithError(): boolean;
127
107
  /** Source ingested from right now, or null while not running (a crawl degraded to pagination still advances the cursor). */
128
108
  getActiveSource(): CrawlSource | null;
129
- /**
130
- * Start crawling. Does NOT await the ingest pipeline (fire-and-forget).
131
- * Refuses to start without a resume point: an explicit configured start block or an
132
- * existing cursor — never an implicit full-chain sync from genesis.
133
- */
109
+ /** Start crawling without awaiting the pipeline. Refuses without a start block or cursor, never syncs from genesis. */
134
110
  start(): Promise<void>;
135
- /**
136
- * Stop crawling and await the pipeline's in-flight step, so callers can tear down
137
- * backends/DB afterwards.
138
- */
111
+ /** Stop crawling and await the in-flight step, so callers can tear down backends and the DB. */
139
112
  stop(finalStatus?: CrawlSyncStatusValue): Promise<void>;
140
- /**
141
- * Halt without awaiting the pipeline — safe to call from inside it.
142
- * @param latch clears `desiredRunning` so no restart brings the crawler back; only for failures
143
- * a restart cannot fix (misconfiguration, missing resume point), never for runtime outages.
144
- */
145
113
  private halt;
146
114
  /** Start teardown without awaiting it, so tracked callbacks can halt from inside themselves. */
147
115
  private beginHalt;
148
116
  private runIngestPipeline;
149
- /**
150
- * Retry the init of a chain-sync backend on its own timer (a poll sleep can be an hour long),
151
- * one probe at a time. On success `chainSyncRecovered` is set and a pending sleep is cut short;
152
- * the pagination loop leaves at its next check and the ingest loop reopens chain-sync.
153
- */
154
117
  private startChainSyncProbing;
155
118
  private scheduleChainSyncProbe;
156
119
  private stopChainSyncProbing;
157
- /** Bound a direct backend call — these bypass the client's timeout/breaker layer. */
120
+ /** Bound a direct backend call. These calls bypass the client's timeout and circuit breaker. */
158
121
  private withTimeout;
159
122
  private runChainSync;
160
123
  /** Read and clear the pending frame failure, so each stream starts from a clean slate. */
161
124
  private takeFrameFailure;
162
- /**
163
- * Whether an unparseable frame can be worked around over HTTP: needs a height, a paginating
164
- * backend, and a source not pinned to 'ogmios' (chain-sync only).
165
- */
166
125
  private canDegradeToPagination;
167
- /**
168
- * End the chain-sync stream and hand back to the ingest loop, which continues on pagination
169
- * past the offending block. The error is recorded first so `lastError` names the block.
170
- */
126
+ /** End the stream so the ingest loop passes the bad block on pagination. Records first, so `lastError` names it. */
171
127
  private degradeToPagination;
172
128
  /** Close the current chain-sync stream and hand the decision in `mark` to the ingest loop. */
173
129
  private endStream;
174
- /**
175
- * Candidate intersection points, newest first: the cursor, a ladder of already-crawled
176
- * ancestors, then the configured start block. If the cursor's block was orphaned while the
177
- * crawler was down, the node intersects at the last common ancestor and reports a rollBackward.
178
- */
179
130
  private buildIntersectionPoints;
180
131
  /** Track streamed callbacks because closing a socket does not imply DB callbacks finished. */
181
132
  private trackCallback;
182
- /**
183
- * @param untilHeight return once the cursor reaches it — walks past a block chain-sync
184
- * cannot deliver, then hands back.
185
- * @param untilChainSync retry a chain-sync backend in the background; return once one is usable.
186
- */
133
+ /** `untilHeight` returns once the cursor reaches it. `untilChainSync` returns once chain-sync is usable again. */
187
134
  private runPagination;
188
135
  private paginate;
189
- /**
190
- * Poll pause between pagination rounds; skipped when a chain-sync handover is already due,
191
- * since the probe's wake-up only reaches a sleep that has begun.
192
- */
136
+ /** Skipped when a chain-sync handover is due, since the probe's wake-up only reaches a running sleep. */
193
137
  private pollPause;
194
- /**
195
- * Pagination reorg recovery: walk back by height comparing the on-chain block hash with
196
- * our stored one until they agree — that height is the fork point. If the last-indexed
197
- * block still matches on-chain, there is no reorg (returns false → treat as transient).
198
- */
199
138
  private tryReorgRecovery;
200
- /**
201
- * Persist one block atomically and advance the cursor. Transient failures are retried; the
202
- * cursor is not advanced on failure, so a resume re-syncs from it. Marks 'synced' at the tip.
203
- * @returns true when the block was persisted, false when the crawler was stopped
204
- */
139
+ /** Persist one block atomically and advance the cursor. Returns false when the crawler stopped. */
205
140
  private persistBlock;
206
141
  /** Epoch a slot belongs to, from the network's Shelley anchor (same math as the Ogmios mapper). */
207
142
  private epochOfSlot;
208
- /**
209
- * Pool/DRep snapshot once per epoch, detached from the triggering block. With Ogmios the ledger
210
- * state is read AT the block, which works while the block is inside the node's volatile window
211
- * (k blocks behind the tip). Koios reports current state only, so there the crawl must be in the
212
- * tip's epoch. Epochs passed outside those bounds are skipped. Authority is the marker row in
213
- * `EpochLedgerSnapshots` (or a pool row written before the marker existed).
214
- */
215
143
  private maybeSnapshotEpoch;
216
- /**
217
- * Chain rollback in one transaction: delete blocks with slot > fork (absolute-slot axis, never
218
- * height), their transactions resolved via blockHash (lazily indexed txs of other blocks are
219
- * untouched), reset the cursor to the fork and write a CardanoReorgLog row.
220
- */
221
144
  private handleReorg;
222
145
  /** Renew the lease while no block commits; block writes renew it transactionally. */
223
146
  private startLeaseHeartbeat;
@@ -230,7 +153,7 @@ export declare class CardanoCrawler {
230
153
  /** Record state only while this instance still owns the lease. */
231
154
  private recordCrawlerError;
232
155
  private leaseSleep;
233
- /** Cancellable, unref'd delay — halt() wakes it so shutdown never waits out a poll. */
156
+ /** Cancellable delay. halt() wakes it so shutdown never waits out a poll. */
234
157
  private sleep;
235
158
  }
236
159
  //# sourceMappingURL=crawler.d.ts.map