@odatano/core 2.0.0-rc.5 → 2.0.0-rc.50

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 (208) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +347 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
  6. package/@cds-models/CardanoIndexerService/index.js +64 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +414 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +32 -19
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
  14. package/@cds-models/index.d.ts +101 -1
  15. package/@cds-models/index.js +16 -1
  16. package/@cds-models/odatano/cardano/index.d.ts +437 -32
  17. package/@cds-models/odatano/cardano/index.js +48 -0
  18. package/README.md +207 -167
  19. package/db/schema.cds +2402 -1705
  20. package/db/types.cds +446 -295
  21. package/package.json +41 -16
  22. package/scripts/migrate-schema.mjs +334 -0
  23. package/scripts/migrate-slot-leader.mjs +96 -0
  24. package/src/index.d.ts +20 -21
  25. package/src/index.js +45 -31
  26. package/src/plugin.js +17 -35
  27. package/srv/blockchain/asset-decimals.d.ts +7 -0
  28. package/srv/blockchain/asset-decimals.js +91 -0
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
  30. package/srv/blockchain/backends/blockfrost-backend.js +66 -172
  31. package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
  32. package/srv/blockchain/backends/cardano-backend.js +29 -5
  33. package/srv/blockchain/backends/koios-backend.d.ts +103 -168
  34. package/srv/blockchain/backends/koios-backend.js +428 -360
  35. package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
  36. package/srv/blockchain/backends/odatano-backend.js +169 -0
  37. package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
  38. package/srv/blockchain/backends/ogmios-backend.js +637 -315
  39. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  40. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  41. package/srv/blockchain/cardano-client.d.ts +61 -241
  42. package/srv/blockchain/cardano-client.js +253 -293
  43. package/srv/blockchain/cardano-indexer.d.ts +282 -281
  44. package/srv/blockchain/cardano-indexer.js +1551 -484
  45. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  46. package/srv/blockchain/cardano-tx-builder.js +164 -140
  47. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  48. package/srv/blockchain/circuit-breaker.js +5 -15
  49. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  50. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  51. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  52. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  53. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
  54. package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
  55. package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
  56. package/srv/blockchain/crawler/certificate-backfill.js +162 -0
  57. package/srv/blockchain/crawler/crawler.d.ts +104 -81
  58. package/srv/blockchain/crawler/crawler.js +532 -160
  59. package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
  60. package/srv/blockchain/crawler/credential-backfill.js +124 -0
  61. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  62. package/srv/blockchain/crawler/index.d.ts +1 -8
  63. package/srv/blockchain/crawler/index.js +31 -17
  64. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  65. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  66. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  67. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  68. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  69. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  70. package/srv/blockchain/crawler/sync-state.d.ts +27 -47
  71. package/srv/blockchain/crawler/sync-state.js +113 -63
  72. package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
  73. package/srv/blockchain/crawler/transaction-backfill.js +278 -0
  74. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  75. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  76. package/srv/blockchain/ledger-state.d.ts +62 -0
  77. package/srv/blockchain/ledger-state.js +419 -0
  78. package/srv/blockchain/pending-spends.d.ts +16 -0
  79. package/srv/blockchain/pending-spends.js +81 -0
  80. package/srv/blockchain/pool-metadata.d.ts +15 -0
  81. package/srv/blockchain/pool-metadata.js +132 -0
  82. package/srv/blockchain/request-coalescer.d.ts +2 -16
  83. package/srv/blockchain/request-coalescer.js +2 -16
  84. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  85. package/srv/blockchain/signing/cose-verifier.js +146 -70
  86. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  87. package/srv/blockchain/signing/external-signer.js +17 -126
  88. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  89. package/srv/blockchain/signing/hsm-signer.js +28 -79
  90. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  91. package/srv/blockchain/signing/signature-verifier.js +70 -83
  92. package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
  93. package/srv/blockchain/signing/submission-finalizer.js +219 -86
  94. package/srv/blockchain/stored-chain.d.ts +20 -0
  95. package/srv/blockchain/stored-chain.js +237 -0
  96. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  97. package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
  98. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  99. package/srv/blockchain/transaction-presence.d.ts +5 -0
  100. package/srv/blockchain/transaction-presence.js +29 -0
  101. package/srv/blockchain/transaction-rows.d.ts +12 -0
  102. package/srv/blockchain/transaction-rows.js +44 -0
  103. package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
  104. package/srv/blockchain/wallet-worker/build-request.js +47 -30
  105. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
  106. package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
  107. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  108. package/srv/blockchain/wallet-worker/index.js +3 -11
  109. package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
  110. package/srv/blockchain/wallet-worker/job-store.js +101 -201
  111. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  112. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  113. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  114. package/srv/blockchain/wallet-worker/signers.js +4 -12
  115. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
  116. package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
  117. package/srv/cardano-agent-service.cds +122 -84
  118. package/srv/cardano-agent-service.js +4 -9
  119. package/srv/cardano-backend-service.cds +78 -0
  120. package/srv/cardano-backend-service.d.ts +2 -0
  121. package/srv/cardano-backend-service.js +242 -0
  122. package/srv/cardano-indexer-service.cds +387 -73
  123. package/srv/cardano-indexer-service.d.ts +5 -1
  124. package/srv/cardano-indexer-service.js +532 -16
  125. package/srv/cardano-service.cds +424 -269
  126. package/srv/cardano-service.js +289 -201
  127. package/srv/cardano-sign-service.cds +201 -180
  128. package/srv/cardano-sign-service.js +71 -201
  129. package/srv/cardano-tx-service.cds +451 -370
  130. package/srv/cardano-tx-service.js +271 -289
  131. package/srv/cardano-ui.cds +16 -16
  132. package/srv/cardano-worker-service.cds +118 -125
  133. package/srv/cardano-worker-service.js +52 -61
  134. package/srv/cbor/cip68.d.ts +13 -0
  135. package/srv/cbor/cip68.js +56 -0
  136. package/srv/cbor/index.d.ts +3 -1
  137. package/srv/cbor/index.js +9 -1
  138. package/srv/cbor/parse.d.ts +30 -18
  139. package/srv/cbor/parse.js +44 -9
  140. package/srv/cbor/plutus-data-json.d.ts +20 -0
  141. package/srv/cbor/plutus-data-json.js +32 -0
  142. package/srv/config.d.ts +113 -0
  143. package/srv/config.js +409 -0
  144. package/srv/server.d.ts +15 -110
  145. package/srv/server.js +84 -404
  146. package/srv/utils/agent-access.d.ts +9 -0
  147. package/srv/utils/agent-access.js +67 -0
  148. package/srv/utils/agent-grants-config.d.ts +0 -46
  149. package/srv/utils/agent-grants-config.js +17 -85
  150. package/srv/utils/agent-grants.d.ts +106 -122
  151. package/srv/utils/agent-grants.js +538 -236
  152. package/srv/utils/agent-token-auth.d.ts +4 -99
  153. package/srv/utils/agent-token-auth.js +18 -182
  154. package/srv/utils/backend-request-handler.d.ts +3 -17
  155. package/srv/utils/backend-request-handler.js +3 -18
  156. package/srv/utils/collections.d.ts +3 -10
  157. package/srv/utils/collections.js +3 -10
  158. package/srv/utils/const.d.ts +23 -74
  159. package/srv/utils/const.js +32 -79
  160. package/srv/utils/crypto.d.ts +3 -12
  161. package/srv/utils/crypto.js +6 -21
  162. package/srv/utils/db-indexes.d.ts +27 -0
  163. package/srv/utils/db-indexes.js +120 -0
  164. package/srv/utils/db-sanitize.d.ts +20 -0
  165. package/srv/utils/db-sanitize.js +80 -0
  166. package/srv/utils/deep-json.d.ts +6 -0
  167. package/srv/utils/deep-json.js +240 -0
  168. package/srv/utils/epoch-slots.d.ts +13 -0
  169. package/srv/utils/epoch-slots.js +38 -0
  170. package/srv/utils/error-codes.d.ts +22 -75
  171. package/srv/utils/error-codes.js +23 -72
  172. package/srv/utils/errors.d.ts +46 -187
  173. package/srv/utils/errors.js +114 -230
  174. package/srv/utils/liveness.d.ts +12 -0
  175. package/srv/utils/liveness.js +35 -0
  176. package/srv/utils/mappers.d.ts +102 -223
  177. package/srv/utils/mappers.js +387 -316
  178. package/srv/utils/network-context.js +2 -13
  179. package/srv/utils/paging.d.ts +31 -0
  180. package/srv/utils/paging.js +43 -0
  181. package/srv/utils/pg-inline-json.d.ts +8 -0
  182. package/srv/utils/pg-inline-json.js +58 -0
  183. package/srv/utils/pg-order-nulls.d.ts +14 -0
  184. package/srv/utils/pg-order-nulls.js +54 -0
  185. package/srv/utils/plutus-placeholders.d.ts +16 -22
  186. package/srv/utils/plutus-placeholders.js +62 -33
  187. package/srv/utils/rate-limiter.d.ts +2 -21
  188. package/srv/utils/rate-limiter.js +5 -17
  189. package/srv/utils/readiness.d.ts +12 -0
  190. package/srv/utils/readiness.js +29 -0
  191. package/srv/utils/reference-script.d.ts +19 -0
  192. package/srv/utils/reference-script.js +84 -0
  193. package/srv/utils/result-numbers.d.ts +15 -0
  194. package/srv/utils/result-numbers.js +61 -0
  195. package/srv/utils/service-events.d.ts +0 -24
  196. package/srv/utils/service-events.js +3 -25
  197. package/srv/utils/signing-helper.d.ts +3 -20
  198. package/srv/utils/signing-helper.js +35 -64
  199. package/srv/utils/tx-build-helper.d.ts +10 -105
  200. package/srv/utils/tx-build-helper.js +81 -144
  201. package/srv/utils/tx-request-parsers.d.ts +82 -33
  202. package/srv/utils/tx-request-parsers.js +401 -49
  203. package/srv/utils/tx-utils.d.ts +3 -27
  204. package/srv/utils/tx-utils.js +32 -50
  205. package/srv/utils/types.d.ts +261 -191
  206. package/srv/utils/types.js +2 -6
  207. package/srv/utils/validators.d.ts +22 -92
  208. package/srv/utils/validators.js +50 -149
@@ -0,0 +1,110 @@
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.OutputDatumBackfillError = void 0;
7
+ exports.fillOutputFields = fillOutputFields;
8
+ exports.backfillOutputDatums = backfillOutputDatums;
9
+ const cds_1 = __importDefault(require("@sap/cds"));
10
+ const collections_1 = require("../../utils/collections");
11
+ const cardano_1 = require("#cds-models/odatano/cardano");
12
+ const { SELECT, UPDATE } = cds_1.default.ql;
13
+ const logger = cds_1.default.log('OutputDatumBackfill');
14
+ // Datum and reference-script fields of stored outputs that an earlier read left empty. The same
15
+ // values go to the input rows that spent the output and to its row in the crawler-fed UTxO set.
16
+ const FIELDS = ['dataHash', 'inlineDatum', 'referenceScriptHash', 'referenceScriptSize', 'referenceScriptType'];
17
+ const OUTPUT_COLUMNS = ['txSeq', 'outputIndex', ...FIELDS.map((f) => `utxo_${f}`)];
18
+ /** Fields the stored output lacks and the fresh one carries. */
19
+ function missingFields(row, fresh) {
20
+ return FIELDS.flatMap((f) => {
21
+ const value = fresh[f];
22
+ return row[`utxo_${f}`] == null && value != null && value !== '' ? [[f, value]] : [];
23
+ });
24
+ }
25
+ // Fills the empty datum and reference-script fields of the stored outputs of these transactions,
26
+ // of the inputs that spent them and of their UTxO set rows. Only empty fields change.
27
+ async function fillOutputFields(tx, sources) {
28
+ const counts = { outputs: 0, inputs: 0, ledgerUtxos: 0 };
29
+ const bySeq = new Map(sources.map((s) => [s.txSeq, s]));
30
+ for (const seqs of (0, collections_1.chunk)([...bySeq.keys()], collections_1.IN_CHUNK)) {
31
+ const rows = (await tx.run(SELECT.from(cardano_1.TransactionOutputs).columns(...OUTPUT_COLUMNS).where({ txSeq: { in: seqs } }))) ?? [];
32
+ for (const row of rows) {
33
+ const source = bySeq.get(Number(row.txSeq));
34
+ const outputIndex = Number(row.outputIndex);
35
+ const fresh = source?.outputs.find((o) => o.outputIndex === outputIndex);
36
+ const missing = fresh ? missingFields(row, fresh) : [];
37
+ if (!source || !missing.length)
38
+ continue;
39
+ const set = Object.fromEntries(missing.map(([f, v]) => [`utxo_${f}`, v]));
40
+ await tx.run(UPDATE.entity(cardano_1.TransactionOutputs).set(set).where({ txSeq: row.txSeq, outputIndex }));
41
+ counts.outputs++;
42
+ let inputs = 0;
43
+ let ledgerUtxos = 0;
44
+ for (const [f, v] of missing) {
45
+ const spent = { spentTxHash: source.hash, spentOutputIndex: outputIndex, [`utxoData_${f}`]: null };
46
+ inputs = Math.max(inputs, Number(await tx.run(UPDATE.entity(cardano_1.TransactionInputs).set({ [`utxoData_${f}`]: v }).where(spent))) || 0);
47
+ const unspent = { txHash: source.hash, outputIndex, [`utxo_${f}`]: null };
48
+ ledgerUtxos = Math.max(ledgerUtxos, Number(await tx.run(UPDATE.entity(cardano_1.LedgerUTxOs).set({ [`utxo_${f}`]: v }).where(unspent))) || 0);
49
+ }
50
+ counts.inputs += inputs;
51
+ counts.ledgerUtxos += ledgerUtxos;
52
+ }
53
+ }
54
+ return counts;
55
+ }
56
+ class OutputDatumBackfillError extends Error {
57
+ constructor(message) {
58
+ super(message);
59
+ this.name = 'OutputDatumBackfillError';
60
+ }
61
+ }
62
+ exports.OutputDatumBackfillError = OutputDatumBackfillError;
63
+ // Reads every transaction again that holds an output with a datum hash and no inline datum, and
64
+ // fills what the backend returns. Pages by primary key only. Backend reads run outside any DB tx.
65
+ async function backfillOutputDatums(opts) {
66
+ if (!opts.client.supports('getTransaction')) {
67
+ throw new OutputDatumBackfillError('No configured backend serves transactions. With Ogmios only, run backfillTransactions over the crawled range.');
68
+ }
69
+ const chunkSize = opts.chunkSize ?? 5000;
70
+ const batchSize = Math.min(opts.batchSize ?? 100, collections_1.IN_CHUNK);
71
+ const progress = { scanned: 0, candidates: 0, transactions: 0, missing: 0, outputs: 0, inputs: 0, ledgerUtxos: 0 };
72
+ let cursor = null;
73
+ for (;;) {
74
+ const after = cursor;
75
+ const rows = (await cds_1.default.tx((tx) => tx.run(SELECT.from(cardano_1.TransactionOutputs).columns('txSeq', 'outputIndex', 'utxo_dataHash', 'utxo_inlineDatum')
76
+ .where(after == null ? {} : { txSeq: { '>': after } }).orderBy('txSeq', 'outputIndex').limit(chunkSize)))) ?? [];
77
+ if (!rows.length)
78
+ break;
79
+ const full = rows.length === chunkSize;
80
+ const lastSeq = Number(rows[rows.length - 1].txSeq);
81
+ // The last transaction of a full page may continue on the next one, so its rows wait there.
82
+ const whole = rows.filter((r) => Number(r.txSeq) !== lastSeq);
83
+ const complete = full && whole.length ? whole : rows;
84
+ const candidates = complete.filter((r) => r.utxo_dataHash != null && r.utxo_inlineDatum == null);
85
+ progress.scanned += complete.length;
86
+ progress.candidates += candidates.length;
87
+ for (const seqs of (0, collections_1.chunk)([...new Set(candidates.map((r) => Number(r.txSeq)))], batchSize)) {
88
+ const stored = (await cds_1.default.tx((tx) => tx.run(SELECT.from(cardano_1.Transactions).columns('hash', 'txSeq').where({ txSeq: { in: seqs } })))) ?? [];
89
+ const fresh = stored.length ? await opts.client.getTransactionsBatch(stored.map((t) => t.hash)) : new Map();
90
+ const sources = stored.flatMap((t) => {
91
+ const read = fresh.get(t.hash);
92
+ return read ? [{ hash: t.hash, txSeq: Number(t.txSeq), outputs: read.outputs ?? [] }] : [];
93
+ });
94
+ progress.transactions += sources.length;
95
+ progress.missing += seqs.length - sources.length;
96
+ const counts = await cds_1.default.tx((tx) => fillOutputFields(tx, sources));
97
+ progress.outputs += counts.outputs;
98
+ progress.inputs += counts.inputs;
99
+ progress.ledgerUtxos += counts.ledgerUtxos;
100
+ }
101
+ cursor = Number(complete[complete.length - 1].txSeq);
102
+ opts.onProgress?.({ ...progress });
103
+ if (!full)
104
+ break;
105
+ }
106
+ logger.info(`output datums: ${progress.outputs} outputs, ${progress.inputs} inputs and ${progress.ledgerUtxos} UTxO set rows filled; ` +
107
+ `${progress.candidates} candidates in ${progress.scanned} outputs, ${progress.transactions} transactions read, ${progress.missing} not returned`);
108
+ return progress;
109
+ }
110
+ //# sourceMappingURL=output-datum-backfill.js.map
@@ -1,15 +1,4 @@
1
1
  import type { Transaction as CapTransaction } from '@sap/cds';
2
- /**
3
- * Chain crawler cursor helpers (v2.0 pre-sync).
4
- *
5
- * `CardanoSyncState` is a singleton row (key = SINGLETON_ID) that records how far
6
- * the crawler has indexed the chain, so a restart resumes instead of re-crawling.
7
- *
8
- * NOTE (CAP 10): Integer64 / Decimal columns are read back from SQLite/HANA as
9
- * STRINGS, not JS numbers — the same change that makes them strings over OData.
10
- * Every read here therefore coerces numeric fields with `num()`; callers get a
11
- * clean numeric `SyncCursor` and never have to think about it.
12
- */
13
2
  export declare const SINGLETON_ID = "SINGLETON";
14
3
  /** Circuit-breaker threshold: pause crawling after this many back-to-back failures. */
15
4
  export declare const MAX_CONSECUTIVE_ERRORS = 10;
@@ -22,6 +11,17 @@ export interface CrawlPoint {
22
11
  hash: string;
23
12
  height?: number;
24
13
  }
14
+ export type UtxoSetStatusValue = 'none' | 'importing' | 'active' | 'invalid';
15
+ /** Crawler-fed ledger state (crawler.utxoSet): the anchor the imported UTxO set describes. */
16
+ export interface UtxoSetState {
17
+ status: UtxoSetStatusValue;
18
+ anchorSlot: number | null;
19
+ anchorHash: string | null;
20
+ importedAt: string | null;
21
+ /** Slot of the last block applied to the ledger tables (null = nothing applied since the import). */
22
+ appliedSlot: number | null;
23
+ error: string | null;
24
+ }
25
25
  /** Normalized, number-typed view of the cursor row (numeric fields already coerced). */
26
26
  export interface SyncCursor {
27
27
  network: string | null;
@@ -34,61 +34,41 @@ export interface SyncCursor {
34
34
  tipHeight: number | null;
35
35
  syncStatus: CrawlSyncStatusValue;
36
36
  consecutiveErrors: number;
37
+ lastIndexedAt: string | null;
37
38
  desiredRunning: boolean;
38
39
  leaseOwner: string | null;
39
40
  leaseUntil: string | null;
41
+ utxoSet: UtxoSetState;
40
42
  }
41
- /**
42
- * Idempotently ensure the singleton cursor row exists and return it.
43
- * On first call (fresh DB) the row is created with the configured start point
44
- * (if given) and status 'stopped'. Subsequent calls just return the current row.
45
- * Safe to call from both the crawler and the control service.
46
- */
43
+ /** Ensure the cursor row exists and return it. A fresh DB gets the configured start point. */
47
44
  export declare function ensureSyncStateSingleton(db: CapTransaction, network: string, start?: CrawlPoint): Promise<SyncCursor>;
48
45
  /** Read the current cursor, or null if it has not been initialized yet. */
49
46
  export declare function readCursor(db: CapTransaction): Promise<SyncCursor | null>;
50
47
  /** Whether the shared lease currently represents a live cluster-wide crawler. */
51
48
  export declare function isCrawlerLeaseActive(cursor: SyncCursor | null, now?: Date): boolean;
52
- /**
53
- * Atomically acquire an expired/unowned lease with compare-and-swap semantics.
54
- * The post-update read is intentional: CAP adapters consistently return the row
55
- * for SELECT, whereas affected-row return shapes differ between SQLite and HANA.
56
- */
49
+ /** Take a free or expired lease. Verified by reading back, since affected-row results differ per database. */
57
50
  export declare function tryAcquireCrawlerLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
58
- /**
59
- * Renew/fence a lease. Call this inside the same transaction as every crawler write:
60
- * the conditional UPDATE serializes a former leader against a newly elected one.
61
- */
51
+ /** Renew the lease inside every crawler write transaction, so a former leader cannot write after a takeover. */
62
52
  export declare function renewCrawlerLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
63
- /**
64
- * Release only the caller's lease; a stale process can never clear a successor.
65
- *
66
- * `pauseCluster` clears `desiredRunning`, which no restart undoes — every instance
67
- * then refuses to start until an operator calls resumeCrawler. Reserve it for
68
- * failures a restart genuinely cannot fix (misconfiguration, no resume point). A
69
- * crashed stream, a provider outage or a node restart must NOT latch: those are
70
- * exactly the cases where coming back up should resume the pre-sync by itself.
71
- */
72
53
  export declare function releaseCrawlerLease(db: CapTransaction, owner: string, status: CrawlSyncStatusValue, pauseCluster?: boolean): Promise<void>;
73
- /** Persist the pause/resume intent shared by every app instance. */
54
+ /** Store the pause intent for all instances. Resuming clears the error streak, so the backoff restarts. */
74
55
  export declare function setCrawlerDesiredRunning(db: CapTransaction, desiredRunning: boolean): Promise<void>;
75
- /**
76
- * Advance the cursor to a freshly-indexed block. Sets the status (default 'syncing';
77
- * pass 'synced' when the block is at the tip), clears the error streak, and refreshes
78
- * lastIndexedAt. Optionally records the latest known tip (for progress).
79
- */
56
+ export declare function latchPoisonBlock(db: CapTransaction, message: string): Promise<void>;
80
57
  export declare function advanceCursor(db: CapTransaction, block: CrawlPoint, tip?: {
81
58
  slot: number;
82
59
  height?: number;
83
- }, status?: CrawlSyncStatusValue): Promise<void>;
60
+ }, status?: CrawlSyncStatusValue,
61
+ /** Extra cursor columns written in the same statement (e.g. the ledger's `utxoAppliedSlot`). */
62
+ extra?: Record<string, unknown>, leaseOwner?: string, now?: Date, ttlMs?: number): Promise<boolean>;
63
+ export declare function tryAcquireImportLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
64
+ export declare function renewImportLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
65
+ export declare function releaseImportLease(db: CapTransaction, owner: string): Promise<void>;
66
+ /** Persist the crawler-fed ledger state's anchor / validity (crawler.utxoSet). */
67
+ export declare function setUtxoSetState(db: CapTransaction, state: Partial<UtxoSetState>): Promise<void>;
84
68
  /** Reset the cursor to a rollback point (used by reorg handling). */
85
69
  export declare function resetCursorTo(db: CapTransaction, point: CrawlPoint): Promise<void>;
86
70
  /** Set the crawler status (e.g. 'synced' when caught up, 'stopped' on shutdown). */
87
71
  export declare function setSyncStatus(db: CapTransaction, status: CrawlSyncStatusValue, pauseCluster?: boolean): Promise<void>;
88
- /**
89
- * Record a crawler error. Increments the consecutive-error counter and flips status
90
- * to 'error' once the circuit-breaker threshold is reached. Returns the new streak
91
- * length so the caller can decide whether to back off / stop.
92
- */
72
+ /** Record a crawler error and return the new streak. Sets status 'error' at the threshold. -1 means the lease is lost. */
93
73
  export declare function recordError(db: CapTransaction, err: unknown, leaseOwner?: string): Promise<number>;
94
74
  //# sourceMappingURL=sync-state.d.ts.map
@@ -11,7 +11,12 @@ exports.tryAcquireCrawlerLease = tryAcquireCrawlerLease;
11
11
  exports.renewCrawlerLease = renewCrawlerLease;
12
12
  exports.releaseCrawlerLease = releaseCrawlerLease;
13
13
  exports.setCrawlerDesiredRunning = setCrawlerDesiredRunning;
14
+ exports.latchPoisonBlock = latchPoisonBlock;
14
15
  exports.advanceCursor = advanceCursor;
16
+ exports.tryAcquireImportLease = tryAcquireImportLease;
17
+ exports.renewImportLease = renewImportLease;
18
+ exports.releaseImportLease = releaseImportLease;
19
+ exports.setUtxoSetState = setUtxoSetState;
15
20
  exports.resetCursorTo = resetCursorTo;
16
21
  exports.setSyncStatus = setSyncStatus;
17
22
  exports.recordError = recordError;
@@ -20,27 +25,13 @@ const cardano_1 = require("#cds-models/odatano/cardano");
20
25
  const errors_1 = require("../../utils/errors");
21
26
  const { SELECT, INSERT, UPDATE } = cds_1.default.ql;
22
27
  const logger = cds_1.default.log('CardanoCrawler');
23
- /**
24
- * Chain crawler cursor helpers (v2.0 pre-sync).
25
- *
26
- * `CardanoSyncState` is a singleton row (key = SINGLETON_ID) that records how far
27
- * the crawler has indexed the chain, so a restart resumes instead of re-crawling.
28
- *
29
- * NOTE (CAP 10): Integer64 / Decimal columns are read back from SQLite/HANA as
30
- * STRINGS, not JS numbers — the same change that makes them strings over OData.
31
- * Every read here therefore coerces numeric fields with `num()`; callers get a
32
- * clean numeric `SyncCursor` and never have to think about it.
33
- */
28
+ // Cursor helpers for the singleton `CardanoSyncState` row.
29
+ // Numeric columns come back from the DB as strings, so every read converts them to numbers.
34
30
  exports.SINGLETON_ID = 'SINGLETON';
35
31
  /** Circuit-breaker threshold: pause crawling after this many back-to-back failures. */
36
32
  exports.MAX_CONSECUTIVE_ERRORS = 10;
37
33
  /** A short, renewable DB lease prevents two app instances from advancing one cursor. */
38
34
  exports.CRAWLER_LEASE_TTL_MS = 15_000;
39
- /**
40
- * Coerce a CAP-10 numeric-as-string (or number/bigint/null) into a JS number.
41
- * Separate optional/required helpers avoid overload declarations (and the
42
- * no-redeclare lint false-positive they caused).
43
- */
44
35
  function optionalNum(v) {
45
36
  if (v === null || v === undefined || v === '')
46
37
  return null;
@@ -57,6 +48,13 @@ function timestamp(v) {
57
48
  return v.toISOString();
58
49
  return String(v);
59
50
  }
51
+ /** Unlike the crawler lease, this ignores `desiredRunning`, which is cleared while an import runs. */
52
+ function importLeaseHeld(cursor, owner, expectedMs) {
53
+ if (!cursor || cursor.leaseOwner !== owner || !cursor.leaseUntil)
54
+ return false;
55
+ const actualMs = Date.parse(cursor.leaseUntil);
56
+ return Number.isFinite(actualMs) && actualMs >= expectedMs - 1_000;
57
+ }
60
58
  function leaseDeadlineReached(cursor, owner, expectedMs) {
61
59
  if (cursor?.desiredRunning !== true || cursor.leaseOwner !== owner || !cursor.leaseUntil)
62
60
  return false;
@@ -65,7 +63,6 @@ function leaseDeadlineReached(cursor, owner, expectedMs) {
65
63
  // that representation change without accepting an old lease interval.
66
64
  return Number.isFinite(actualMs) && actualMs >= expectedMs - 1_000;
67
65
  }
68
- /** Map a raw DB row into the normalized numeric cursor. */
69
66
  function toCursor(row) {
70
67
  return {
71
68
  network: row.network ?? null,
@@ -78,17 +75,21 @@ function toCursor(row) {
78
75
  tipHeight: optionalNum(row.tipHeight),
79
76
  syncStatus: (row.syncStatus ?? 'stopped'),
80
77
  consecutiveErrors: requiredNum(row.consecutiveErrors),
78
+ lastIndexedAt: timestamp(row.lastIndexedAt),
81
79
  desiredRunning: row.desiredRunning !== false,
82
80
  leaseOwner: row.leaseOwner ?? null,
83
81
  leaseUntil: timestamp(row.leaseUntil),
82
+ utxoSet: {
83
+ status: (row.utxoSetStatus ?? 'none'),
84
+ anchorSlot: optionalNum(row.utxoAnchorSlot),
85
+ anchorHash: row.utxoAnchorHash ?? null,
86
+ importedAt: timestamp(row.utxoSetImportedAt),
87
+ appliedSlot: optionalNum(row.utxoAppliedSlot),
88
+ error: row.utxoSetError ?? null,
89
+ },
84
90
  };
85
91
  }
86
- /**
87
- * Idempotently ensure the singleton cursor row exists and return it.
88
- * On first call (fresh DB) the row is created with the configured start point
89
- * (if given) and status 'stopped'. Subsequent calls just return the current row.
90
- * Safe to call from both the crawler and the control service.
91
- */
92
+ /** Ensure the cursor row exists and return it. A fresh DB gets the configured start point. */
92
93
  async function ensureSyncStateSingleton(db, network, start) {
93
94
  const existing = await db.run(SELECT.one.from(cardano_1.CardanoSyncState).where({ ID: exports.SINGLETON_ID }));
94
95
  if (existing) {
@@ -113,6 +114,12 @@ async function ensureSyncStateSingleton(db, network, start) {
113
114
  desiredRunning: true,
114
115
  leaseOwner: null,
115
116
  leaseUntil: null,
117
+ utxoSetStatus: 'none',
118
+ utxoAnchorSlot: null,
119
+ utxoAnchorHash: null,
120
+ utxoSetImportedAt: null,
121
+ utxoAppliedSlot: null,
122
+ utxoSetError: null,
116
123
  };
117
124
  await db.run(INSERT.into(cardano_1.CardanoSyncState).entries(row));
118
125
  logger.info(`Sync cursor initialized (network=${network}, start=${start ? `${start.slot}/${start.hash}` : 'none'})`);
@@ -130,11 +137,7 @@ function isCrawlerLeaseActive(cursor, now = new Date()) {
130
137
  const deadline = Date.parse(cursor.leaseUntil);
131
138
  return Number.isFinite(deadline) && deadline > now.getTime();
132
139
  }
133
- /**
134
- * Atomically acquire an expired/unowned lease with compare-and-swap semantics.
135
- * The post-update read is intentional: CAP adapters consistently return the row
136
- * for SELECT, whereas affected-row return shapes differ between SQLite and HANA.
137
- */
140
+ /** Take a free or expired lease. Verified by reading back, since affected-row results differ per database. */
138
141
  async function tryAcquireCrawlerLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
139
142
  const raw = await db.run(SELECT.one.from(cardano_1.CardanoSyncState).where({ ID: exports.SINGLETON_ID }));
140
143
  if (!raw)
@@ -145,15 +148,8 @@ async function tryAcquireCrawlerLease(db, owner, now = new Date(), ttlMs = expor
145
148
  const deadline = current.leaseUntil ? Date.parse(current.leaseUntil) : Number.NEGATIVE_INFINITY;
146
149
  if (current.leaseOwner && current.leaseOwner !== owner && deadline > now.getTime())
147
150
  return false;
148
- // CAS on the observed OWNER only (a plain string that round-trips identically
149
- // on every adapter). If two instances race, the first writer changes leaseOwner
150
- // and the loser's UPDATE matches 0 rows → its read-back verification fails.
151
- // Deliberately NOT comparing leaseUntil: HANA/driver timestamp normalization can
152
- // make the read-back representation differ from what the WHERE serializes, so a
153
- // timestamp-equality CAS may NEVER match again after a leader crash — the lease
154
- // would be stuck until the row is cleared by hand. The residual race (the old
155
- // owner renewing concurrently) resolves via fencing: its next renew no longer
156
- // matches leaseOwner and it halts.
151
+ // Compare the owner only. Some adapters reformat timestamps, so a leaseUntil match could fail forever.
152
+ // An old owner that renews meanwhile is fenced by its next renewal.
157
153
  const where = {
158
154
  ID: exports.SINGLETON_ID,
159
155
  leaseOwner: raw.leaseOwner ?? null,
@@ -166,10 +162,7 @@ async function tryAcquireCrawlerLease(db, owner, now = new Date(), ttlMs = expor
166
162
  const verified = await readCursor(db);
167
163
  return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
168
164
  }
169
- /**
170
- * Renew/fence a lease. Call this inside the same transaction as every crawler write:
171
- * the conditional UPDATE serializes a former leader against a newly elected one.
172
- */
165
+ /** Renew the lease inside every crawler write transaction, so a former leader cannot write after a takeover. */
173
166
  async function renewCrawlerLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
174
167
  const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
175
168
  await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseUntil }).where({
@@ -180,15 +173,8 @@ async function renewCrawlerLease(db, owner, now = new Date(), ttlMs = exports.CR
180
173
  const verified = await readCursor(db);
181
174
  return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
182
175
  }
183
- /**
184
- * Release only the caller's lease; a stale process can never clear a successor.
185
- *
186
- * `pauseCluster` clears `desiredRunning`, which no restart undoes — every instance
187
- * then refuses to start until an operator calls resumeCrawler. Reserve it for
188
- * failures a restart genuinely cannot fix (misconfiguration, no resume point). A
189
- * crashed stream, a provider outage or a node restart must NOT latch: those are
190
- * exactly the cases where coming back up should resume the pre-sync by itself.
191
- */
176
+ // Release only the caller's lease. `pauseCluster` keeps the crawler down across restarts.
177
+ // Use it only for failures a restart cannot fix, such as misconfiguration.
192
178
  async function releaseCrawlerLease(db, owner, status, pauseCluster = false) {
193
179
  await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
194
180
  leaseOwner: null,
@@ -197,19 +183,30 @@ async function releaseCrawlerLease(db, owner, status, pauseCluster = false) {
197
183
  ...(pauseCluster ? { desiredRunning: false } : {}),
198
184
  }).where({ ID: exports.SINGLETON_ID, leaseOwner: owner }));
199
185
  }
200
- /** Persist the pause/resume intent shared by every app instance. */
186
+ /** Store the pause intent for all instances. Resuming clears the error streak, so the backoff restarts. */
201
187
  async function setCrawlerDesiredRunning(db, desiredRunning) {
202
188
  const set = { desiredRunning };
203
- if (!desiredRunning)
189
+ if (desiredRunning)
190
+ set.consecutiveErrors = 0;
191
+ else
204
192
  set.syncStatus = 'stopped';
205
193
  await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
206
194
  }
207
- /**
208
- * Advance the cursor to a freshly-indexed block. Sets the status (default 'syncing';
209
- * pass 'synced' when the block is at the tip), clears the error streak, and refreshes
210
- * lastIndexedAt. Optionally records the latest known tip (for progress).
211
- */
212
- async function advanceCursor(db, block, tip, status = 'syncing') {
195
+ // Latch the cluster off for a poison block. Not tied to the lease, since the fault is in the block.
196
+ // Only resumeCrawler brings the crawler back.
197
+ async function latchPoisonBlock(db, message) {
198
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
199
+ desiredRunning: false,
200
+ syncStatus: 'error',
201
+ lastError: message.slice(0, 500),
202
+ lastErrorAt: new Date().toISOString(),
203
+ }).where({ ID: exports.SINGLETON_ID }));
204
+ }
205
+ // Advance the cursor to an indexed block and clear the error streak. With `leaseOwner` the
206
+ // same UPDATE renews the lease. Returns false when the lease is lost, and the caller must roll back.
207
+ async function advanceCursor(db, block, tip, status = 'syncing',
208
+ /** Extra cursor columns written in the same statement (e.g. the ledger's `utxoAppliedSlot`). */
209
+ extra, leaseOwner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
213
210
  const set = {
214
211
  lastSlot: block.slot,
215
212
  lastBlockHash: block.hash,
@@ -218,12 +215,69 @@ async function advanceCursor(db, block, tip, status = 'syncing') {
218
215
  syncStatus: status,
219
216
  consecutiveErrors: 0,
220
217
  lastError: null,
218
+ ...(extra ?? {}),
221
219
  };
222
220
  if (tip) {
223
221
  set.tipSlot = tip.slot;
224
222
  if (tip.height !== undefined)
225
223
  set.tipHeight = tip.height;
226
224
  }
225
+ if (!leaseOwner) {
226
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
227
+ return true;
228
+ }
229
+ set.leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
230
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({
231
+ ID: exports.SINGLETON_ID,
232
+ leaseOwner,
233
+ desiredRunning: true,
234
+ }));
235
+ const verified = await readCursor(db);
236
+ return leaseDeadlineReached(verified, leaseOwner, now.getTime() + ttlMs);
237
+ }
238
+ // Lease for the UTxO set import on the crawler's lease columns. Blocks crawler starts and other imports.
239
+ async function tryAcquireImportLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
240
+ const raw = await db.run(SELECT.one.from(cardano_1.CardanoSyncState).where({ ID: exports.SINGLETON_ID }));
241
+ if (!raw)
242
+ return false;
243
+ const current = toCursor(raw);
244
+ const deadline = current.leaseUntil ? Date.parse(current.leaseUntil) : Number.NEGATIVE_INFINITY;
245
+ if (current.leaseOwner && current.leaseOwner !== owner && deadline > now.getTime())
246
+ return false;
247
+ const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
248
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseOwner: owner, leaseUntil }).where({
249
+ ID: exports.SINGLETON_ID,
250
+ leaseOwner: raw.leaseOwner ?? null,
251
+ }));
252
+ const verified = await readCursor(db);
253
+ return importLeaseHeld(verified, owner, now.getTime() + ttlMs);
254
+ }
255
+ async function renewImportLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
256
+ const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
257
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseUntil }).where({ ID: exports.SINGLETON_ID, leaseOwner: owner }));
258
+ const verified = await readCursor(db);
259
+ return importLeaseHeld(verified, owner, now.getTime() + ttlMs);
260
+ }
261
+ async function releaseImportLease(db, owner) {
262
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseOwner: null, leaseUntil: null }).where({ ID: exports.SINGLETON_ID, leaseOwner: owner }));
263
+ }
264
+ /** Persist the crawler-fed ledger state's anchor / validity (crawler.utxoSet). */
265
+ async function setUtxoSetState(db, state) {
266
+ const set = {};
267
+ if (state.status !== undefined)
268
+ set.utxoSetStatus = state.status;
269
+ if (state.anchorSlot !== undefined)
270
+ set.utxoAnchorSlot = state.anchorSlot;
271
+ if (state.anchorHash !== undefined)
272
+ set.utxoAnchorHash = state.anchorHash;
273
+ if (state.importedAt !== undefined)
274
+ set.utxoSetImportedAt = state.importedAt;
275
+ if (state.appliedSlot !== undefined)
276
+ set.utxoAppliedSlot = state.appliedSlot;
277
+ if (state.error !== undefined)
278
+ set.utxoSetError = state.error;
279
+ if (!Object.keys(set).length)
280
+ return;
227
281
  await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
228
282
  }
229
283
  /** Reset the cursor to a rollback point (used by reorg handling). */
@@ -243,11 +297,7 @@ async function setSyncStatus(db, status, pauseCluster = false) {
243
297
  ...(pauseCluster ? { desiredRunning: false } : {}),
244
298
  }).where({ ID: exports.SINGLETON_ID }));
245
299
  }
246
- /**
247
- * Record a crawler error. Increments the consecutive-error counter and flips status
248
- * to 'error' once the circuit-breaker threshold is reached. Returns the new streak
249
- * length so the caller can decide whether to back off / stop.
250
- */
300
+ /** Record a crawler error and return the new streak. Sets status 'error' at the threshold. -1 means the lease is lost. */
251
301
  async function recordError(db, err, leaseOwner) {
252
302
  if (leaseOwner && !(await renewCrawlerLease(db, leaseOwner)))
253
303
  return -1;
@@ -0,0 +1,44 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import type { CardanoClient } from '../cardano-client';
3
+ import type { ChainPoint } from '../backends/cardano-backend';
4
+ import type { Transaction } from '../../utils/types';
5
+ import type { LedgerLookup } from '../ledger-state';
6
+ export declare class TransactionBackfillError extends Error {
7
+ constructor(message: string);
8
+ }
9
+ export interface TransactionBackfillProgress {
10
+ /** Slot of the last block handled. */
11
+ atSlot: number;
12
+ blocks: number;
13
+ transactions: number;
14
+ /** Input rows that got at least one field. */
15
+ inputs: number;
16
+ /** Output rows that got a datum or reference-script field. */
17
+ outputs: number;
18
+ redeemers: number;
19
+ datums: number;
20
+ /** Transactions whose stored rows differed from the ledger view (order, inputs or outputs the ledger did not apply) and were rewritten. */
21
+ rewritten: number;
22
+ /** Transactions left as they are: stored inputs differ from the stream. */
23
+ skipped: number;
24
+ }
25
+ /** Resolves bare chain-sync inputs from the index (CardanoIndexer.resolveInputs). */
26
+ export interface InputResolver {
27
+ resolveInputs(tx: CapTransaction, txs: Transaction[], ledger?: LedgerLookup): Promise<void>;
28
+ }
29
+ export interface TransactionBackfillOptions {
30
+ client: CardanoClient;
31
+ indexer: InputResolver;
32
+ fromSlot: number;
33
+ toSlot: number;
34
+ batchBlocks?: number;
35
+ onProgress?: (p: TransactionBackfillProgress) => void;
36
+ }
37
+ export interface TransactionBackfillResult extends TransactionBackfillProgress {
38
+ fromSlot: number;
39
+ toSlot: number;
40
+ intersection: ChainPoint | 'origin';
41
+ }
42
+ export declare function inputFillStatement(kind: string): string | null;
43
+ export declare function backfillTransactions(opts: TransactionBackfillOptions): Promise<TransactionBackfillResult>;
44
+ //# sourceMappingURL=transaction-backfill.d.ts.map