@odatano/core 2.0.0-rc.4 → 2.0.0-rc.41

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 (166) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +305 -7
  8. package/@cds-models/CardanoODataService/index.js +34 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +46 -13
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +72 -0
  14. package/@cds-models/index.js +12 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +2297 -1633
  19. package/db/types.cds +114 -0
  20. package/package.json +27 -6
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +18 -11
  24. package/src/index.js +44 -14
  25. package/src/plugin.js +42 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +53 -162
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +376 -235
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +556 -201
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +87 -202
  39. package/srv/blockchain/cardano-client.js +210 -240
  40. package/srv/blockchain/cardano-indexer.d.ts +311 -242
  41. package/srv/blockchain/cardano-indexer.js +1238 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +44 -81
  43. package/srv/blockchain/cardano-tx-builder.js +173 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +14 -45
  68. package/srv/blockchain/signing/signature-verifier.js +73 -76
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +111 -173
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +649 -326
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +18 -23
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +65 -2
  102. package/srv/cardano-service.js +170 -129
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +57 -184
  105. package/srv/cardano-tx-service.cds +439 -370
  106. package/srv/cardano-tx-service.js +231 -190
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/index.d.ts +1 -1
  110. package/srv/cbor/parse.d.ts +27 -0
  111. package/srv/cbor/parse.js +63 -2
  112. package/srv/server.d.ts +28 -86
  113. package/srv/server.js +132 -135
  114. package/srv/utils/agent-grants-config.d.ts +37 -0
  115. package/srv/utils/agent-grants-config.js +138 -0
  116. package/srv/utils/agent-grants.d.ts +262 -0
  117. package/srv/utils/agent-grants.js +922 -0
  118. package/srv/utils/agent-token-auth.d.ts +16 -0
  119. package/srv/utils/agent-token-auth.js +78 -0
  120. package/srv/utils/backend-request-handler.d.ts +2 -16
  121. package/srv/utils/backend-request-handler.js +3 -18
  122. package/srv/utils/collections.d.ts +4 -8
  123. package/srv/utils/collections.js +4 -8
  124. package/srv/utils/const.d.ts +30 -67
  125. package/srv/utils/const.js +32 -72
  126. package/srv/utils/crypto.d.ts +3 -12
  127. package/srv/utils/crypto.js +5 -18
  128. package/srv/utils/db-indexes.d.ts +25 -0
  129. package/srv/utils/db-indexes.js +94 -0
  130. package/srv/utils/db-sanitize.d.ts +27 -0
  131. package/srv/utils/db-sanitize.js +85 -0
  132. package/srv/utils/epoch-slots.d.ts +20 -0
  133. package/srv/utils/epoch-slots.js +43 -0
  134. package/srv/utils/error-codes.d.ts +20 -73
  135. package/srv/utils/error-codes.js +19 -70
  136. package/srv/utils/errors.d.ts +50 -177
  137. package/srv/utils/errors.js +94 -218
  138. package/srv/utils/legacy-service-paths.d.ts +11 -0
  139. package/srv/utils/legacy-service-paths.js +58 -0
  140. package/srv/utils/liveness.d.ts +16 -0
  141. package/srv/utils/liveness.js +40 -0
  142. package/srv/utils/mappers.d.ts +128 -214
  143. package/srv/utils/mappers.js +354 -299
  144. package/srv/utils/network-context.js +2 -11
  145. package/srv/utils/pg-inline-json.d.ts +8 -0
  146. package/srv/utils/pg-inline-json.js +62 -0
  147. package/srv/utils/pg-order-nulls.d.ts +14 -0
  148. package/srv/utils/pg-order-nulls.js +56 -0
  149. package/srv/utils/plutus-placeholders.d.ts +23 -16
  150. package/srv/utils/plutus-placeholders.js +63 -27
  151. package/srv/utils/rate-limiter.d.ts +46 -0
  152. package/srv/utils/rate-limiter.js +116 -0
  153. package/srv/utils/service-events.d.ts +2 -22
  154. package/srv/utils/service-events.js +3 -23
  155. package/srv/utils/signing-helper.d.ts +6 -16
  156. package/srv/utils/signing-helper.js +36 -60
  157. package/srv/utils/tx-build-helper.d.ts +28 -93
  158. package/srv/utils/tx-build-helper.js +75 -124
  159. package/srv/utils/tx-request-parsers.d.ts +101 -28
  160. package/srv/utils/tx-request-parsers.js +410 -43
  161. package/srv/utils/tx-utils.d.ts +4 -23
  162. package/srv/utils/tx-utils.js +12 -41
  163. package/srv/utils/types.d.ts +252 -179
  164. package/srv/utils/types.js +2 -6
  165. package/srv/utils/validators.d.ts +24 -90
  166. package/srv/utils/validators.js +50 -147
@@ -0,0 +1,363 @@
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.UtxoSetLeaseLostError = exports.UtxoSetImportError = void 0;
7
+ exports.parseJsonLossless = parseJsonLossless;
8
+ exports.parseCliUtxoEntry = parseCliUtxoEntry;
9
+ exports.readUtxoSetFile = readUtxoSetFile;
10
+ exports.aggregateStatements = aggregateStatements;
11
+ exports.importUtxoSet = importUtxoSet;
12
+ exports.rebuildUtxoSetAggregates = rebuildUtxoSetAggregates;
13
+ const cds_1 = __importDefault(require("@sap/cds"));
14
+ const node_fs_1 = require("node:fs");
15
+ const promises_1 = require("node:fs/promises");
16
+ const node_readline_1 = require("node:readline");
17
+ const ledger_state_1 = require("../ledger-state");
18
+ const sync_state_1 = require("./sync-state");
19
+ const cardano_1 = require("#cds-models/odatano/cardano");
20
+ const collections_1 = require("../../utils/collections");
21
+ const { UPSERT, DELETE, SELECT } = cds_1.default.ql;
22
+ const logger = cds_1.default.log('LedgerState');
23
+ /**
24
+ * One-off import of the UTxO set at the anchor `crawler.utxoSet` builds on: from Ogmios
25
+ * (`queryLedgerState/utxo` at the cursor point) or a `cardano-cli query utxo --whole-utxo`
26
+ * dump (`.json` parsed whole; `.ndjson`/`.jsonl` streamed, one entry or `{key,value}` per line).
27
+ */
28
+ class UtxoSetImportError extends Error {
29
+ constructor(message) {
30
+ super(message);
31
+ this.name = 'UtxoSetImportError';
32
+ }
33
+ }
34
+ exports.UtxoSetImportError = UtxoSetImportError;
35
+ /** The cursor lease went to someone else: nothing more may be written, not even `invalid`. */
36
+ class UtxoSetLeaseLostError extends UtxoSetImportError {
37
+ constructor(message = 'Lost the cursor lease during the import — aborted without further writes.') {
38
+ super(message);
39
+ this.name = 'UtxoSetLeaseLostError';
40
+ }
41
+ }
42
+ exports.UtxoSetLeaseLostError = UtxoSetLeaseLostError;
43
+ /**
44
+ * `JSON.parse` for a cardano-cli dump that keeps every integer exact: integer literals outside
45
+ * strings are quoted before parsing, so a quantity above 2^53 is never rounded.
46
+ */
47
+ function parseJsonLossless(text) {
48
+ // string literals pass through untouched; floats keep their JSON meaning
49
+ const rewritten = text.replace(/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g, (m) => (m[0] === '"' || !/^-?\d+$/.test(m) ? m : `"${m}"`));
50
+ return JSON.parse(rewritten);
51
+ }
52
+ /** Parse one `"txHash#index": {…}` entry of a cardano-cli dump; null when malformed. */
53
+ function parseCliUtxoEntry(key, value) {
54
+ const m = /^([0-9a-fA-F]{64})#(\d+)$/.exec(key ?? '');
55
+ if (!m || !value || typeof value.address !== 'string')
56
+ return null;
57
+ const amount = [];
58
+ const v = value.value ?? {};
59
+ for (const [k, q] of Object.entries(v)) {
60
+ if (k === 'lovelace') {
61
+ amount.push({ unit: 'lovelace', quantity: String(q) });
62
+ }
63
+ else if (q && typeof q === 'object') {
64
+ for (const [nameHex, qty] of Object.entries(q)) {
65
+ amount.push({ unit: `${k}${nameHex}`, quantity: String(qty) });
66
+ }
67
+ }
68
+ }
69
+ if (!amount.some(a => a.unit === 'lovelace'))
70
+ amount.unshift({ unit: 'lovelace', quantity: '0' });
71
+ return {
72
+ txHash: m[1].toLowerCase(),
73
+ outputIndex: Number(m[2]),
74
+ address: value.address,
75
+ amount,
76
+ dataHash: value.datumhash ?? value.datumHash ?? null,
77
+ inlineDatum: typeof value.inlineDatumRaw === 'string' ? value.inlineDatumRaw : null,
78
+ // the cli prints the script itself, not its hash — resolved lazily, like every other path
79
+ referenceScriptHash: null,
80
+ };
81
+ }
82
+ /** Stream a cardano-cli dump. See the module doc for the accepted layouts. */
83
+ async function* readUtxoSetFile(filePath) {
84
+ if (/\.json$/i.test(filePath)) {
85
+ const parsed = parseJsonLossless(await (0, promises_1.readFile)(filePath, 'utf8'));
86
+ for (const [key, value] of Object.entries(parsed)) {
87
+ const entry = parseCliUtxoEntry(key, value);
88
+ if (entry)
89
+ yield entry;
90
+ }
91
+ return;
92
+ }
93
+ const rl = (0, node_readline_1.createInterface)({ input: (0, node_fs_1.createReadStream)(filePath, 'utf8'), crlfDelay: Infinity });
94
+ for await (const line of rl) {
95
+ const trimmed = line.trim();
96
+ if (!trimmed)
97
+ continue;
98
+ const obj = parseJsonLossless(trimmed);
99
+ if (typeof obj.key === 'string' && obj.value && typeof obj.value === 'object') {
100
+ const entry = parseCliUtxoEntry(obj.key, obj.value);
101
+ if (entry)
102
+ yield entry;
103
+ continue;
104
+ }
105
+ for (const [key, value] of Object.entries(obj)) {
106
+ const entry = parseCliUtxoEntry(key, value);
107
+ if (entry)
108
+ yield entry;
109
+ }
110
+ }
111
+ }
112
+ async function* readFromOgmios(client, anchor) {
113
+ const backend = client.getLedgerStateBackend();
114
+ if (!backend) {
115
+ throw new UtxoSetImportError('No Ogmios backend available for source "ogmios" — configure one or import a cardano-cli file.');
116
+ }
117
+ const utxos = await backend.queryUtxoSetAt({ slot: anchor.slot, hash: anchor.hash });
118
+ for (const u of utxos) {
119
+ yield {
120
+ txHash: u.txHash,
121
+ outputIndex: u.outputIndex,
122
+ address: u.address,
123
+ amount: u.amount,
124
+ dataHash: u.datumHash ?? null,
125
+ inlineDatum: u.inlineDatum ?? null,
126
+ referenceScriptHash: u.scriptRef ?? null,
127
+ };
128
+ }
129
+ }
130
+ /** Table names as CAP creates them (dots → underscores), for the aggregate statements. */
131
+ const T = {
132
+ utxos: 'odatano_cardano_LedgerUTxOs',
133
+ utxoAssets: 'odatano_cardano_LedgerUTxOAssets',
134
+ addresses: 'odatano_cardano_LedgerAddresses',
135
+ addressAssets: 'odatano_cardano_LedgerAddressAssets',
136
+ accounts: 'odatano_cardano_LedgerAccounts',
137
+ };
138
+ /**
139
+ * The three aggregate statements that derive the running sums from the imported rows.
140
+ * Plain SQL because millions of addresses do not fit an in-memory map and a per-row
141
+ * UPSERT would take hours; the syntax is the portable subset (sqlite, PostgreSQL, HANA).
142
+ */
143
+ function aggregateStatements() {
144
+ return [
145
+ `INSERT INTO ${T.addresses} (address, stakeAddress, addressType, isScript, totalLovelace, utxoCount, firstSeenSlot, lastActiveSlot) ` +
146
+ `SELECT address, MIN(stakeAddress), MIN(addressType), ` +
147
+ `CASE WHEN MAX(CASE WHEN isScript THEN 1 ELSE 0 END) = 1 THEN TRUE ELSE FALSE END, ` +
148
+ `SUM(lovelace), COUNT(*), NULL, NULL FROM ${T.utxos} WHERE spentTxHash IS NULL GROUP BY address`,
149
+ `INSERT INTO ${T.addressAssets} (address_address, unit, asset_quantity, asset_policyId, asset_assetNameHex, asset_assetName) ` +
150
+ `SELECT u.address, a.unit, SUM(a.asset_quantity), MIN(a.asset_policyId), MIN(a.asset_assetNameHex), MIN(a.asset_assetName) ` +
151
+ `FROM ${T.utxoAssets} a JOIN ${T.utxos} u ON a.utxo_txHash = u.txHash AND a.utxo_outputIndex = u.outputIndex ` +
152
+ `WHERE u.spentTxHash IS NULL GROUP BY u.address, a.unit`,
153
+ `INSERT INTO ${T.accounts} (stakeAddress, controlledAmount, addressCount, utxoCount, lastActiveSlot) ` +
154
+ `SELECT stakeAddress, SUM(totalLovelace), COUNT(*), SUM(utxoCount), NULL FROM ${T.addresses} ` +
155
+ `WHERE stakeAddress IS NOT NULL GROUP BY stakeAddress`,
156
+ ];
157
+ }
158
+ /**
159
+ * Run the import. Throws `UtxoSetImportError` on a precondition failure before anything is
160
+ * written; a failure mid-way leaves the set marked `invalid` (never half-`active`).
161
+ */
162
+ async function importUtxoSet(opts) {
163
+ const { anchor, source } = opts;
164
+ const batchSize = opts.batchSize ?? 2000;
165
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
166
+ if (!cursor)
167
+ throw new UtxoSetImportError('No crawler cursor yet — start the crawler once before importing.');
168
+ if ((0, sync_state_1.isCrawlerLeaseActive)(cursor))
169
+ throw new UtxoSetImportError('Crawler is running — pause it first (pauseCrawler).');
170
+ if (cursor.lastSlot > anchor.slot) {
171
+ throw new UtxoSetImportError(`Crawler cursor (slot ${cursor.lastSlot}) is past the anchor (slot ${anchor.slot}) — blocks after the anchor were ` +
172
+ 'already crawled without a set to apply them to. Dump the set at or after the cursor.');
173
+ }
174
+ if (source === 'file' && !opts.filePath)
175
+ throw new UtxoSetImportError('source "file" needs filePath.');
176
+ return withImportLease(async (lease) => {
177
+ const { writeTx } = lease;
178
+ opts.indexer.setUtxoAnchor(null);
179
+ await writeTx(async (tx) => {
180
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'importing', anchorSlot: anchor.slot, anchorHash: anchor.hash, error: null, importedAt: null, appliedSlot: null });
181
+ await tx.run(DELETE.from(cardano_1.LedgerUTxOAssets));
182
+ await tx.run(DELETE.from(cardano_1.LedgerUTxOs));
183
+ await tx.run(DELETE.from(cardano_1.LedgerAddressAssets));
184
+ await tx.run(DELETE.from(cardano_1.LedgerAddresses));
185
+ await tx.run(DELETE.from(cardano_1.LedgerAccounts));
186
+ });
187
+ let imported = 0;
188
+ try {
189
+ const entries = source === 'ogmios' ? readFromOgmios(opts.client, anchor) : readUtxoSetFile(opts.filePath);
190
+ let rows = [];
191
+ let assets = [];
192
+ const flush = async () => {
193
+ if (!rows.length)
194
+ return;
195
+ const r = rows;
196
+ const a = assets;
197
+ rows = [];
198
+ assets = [];
199
+ await writeTx(async (tx) => {
200
+ for (const c of (0, collections_1.chunk)(r, collections_1.IN_CHUNK))
201
+ await tx.run(UPSERT.into(cardano_1.LedgerUTxOs).entries(c));
202
+ for (const c of (0, collections_1.chunk)(a, collections_1.IN_CHUNK))
203
+ await tx.run(UPSERT.into(cardano_1.LedgerUTxOAssets).entries(c));
204
+ });
205
+ imported += r.length;
206
+ opts.onProgress?.(imported);
207
+ };
208
+ for await (const e of entries) {
209
+ const built = (0, ledger_state_1.buildLedgerUtxoRows)(e, null);
210
+ rows.push(built.row);
211
+ assets.push(...built.assets);
212
+ if (rows.length >= batchSize)
213
+ await flush();
214
+ }
215
+ await flush();
216
+ await activateWithAggregates(lease, opts.indexer, anchor);
217
+ logger.info(`UTxO set imported: ${imported} entries at anchor ${anchor.slot}/${anchor.hash} (source=${source})`);
218
+ return { utxos: imported, anchor };
219
+ }
220
+ catch (err) {
221
+ const message = err instanceof Error ? err.message : String(err);
222
+ logger.error(`UTxO set import failed after ${imported} entries: ${message}`);
223
+ // Only the lease holder may write the failure state; after a takeover the row is the
224
+ // successor's and the truncated tables are its problem to fill.
225
+ if (!(err instanceof UtxoSetLeaseLostError))
226
+ await lease.markInvalid(message);
227
+ throw err;
228
+ }
229
+ });
230
+ }
231
+ /**
232
+ * Hold the cursor lease for the whole run: a crawler start on any instance and a second import
233
+ * are refused while it is held; renewed on a heartbeat (one at a time), released at the end.
234
+ */
235
+ async function withImportLease(run) {
236
+ const leaseOwner = `import:${process.pid}:${Date.now().toString(36)}`;
237
+ const acquired = await cds_1.default.tx((tx) => (0, sync_state_1.tryAcquireImportLease)(tx, leaseOwner));
238
+ if (!acquired)
239
+ throw new UtxoSetImportError('Could not take the cursor lease — a crawler or another import holds it.');
240
+ let leaseLost = false;
241
+ let renewing = false;
242
+ const heartbeat = setInterval(() => {
243
+ // A renewal still waiting keeps its connection; a second one would only take another from the pool
244
+ if (renewing)
245
+ return;
246
+ renewing = true;
247
+ cds_1.default.tx(async (tx) => { if (!(await (0, sync_state_1.renewImportLease)(tx, leaseOwner)))
248
+ leaseLost = true; })
249
+ .catch(() => { leaseLost = true; })
250
+ .finally(() => { renewing = false; });
251
+ }, Math.max(1000, Math.floor(sync_state_1.CRAWLER_LEASE_TTL_MS / 3)));
252
+ heartbeat.unref();
253
+ const lease = {
254
+ writeTx: (fn) => cds_1.default.tx(async (tx) => {
255
+ if (leaseLost || !(await (0, sync_state_1.renewImportLease)(tx, leaseOwner)))
256
+ throw new UtxoSetLeaseLostError();
257
+ return fn(tx);
258
+ }),
259
+ writeTxLeaseLast: (fn) => cds_1.default.tx(async (tx) => {
260
+ const result = await fn(tx);
261
+ if (!(await (0, sync_state_1.renewImportLease)(tx, leaseOwner)))
262
+ throw new UtxoSetLeaseLostError();
263
+ return result;
264
+ }),
265
+ markInvalid: (message) => cds_1.default.tx(async (tx) => {
266
+ if (await (0, sync_state_1.renewImportLease)(tx, leaseOwner))
267
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: message.slice(0, 500) });
268
+ }).then(() => undefined, () => undefined),
269
+ };
270
+ try {
271
+ return await run(lease);
272
+ }
273
+ finally {
274
+ clearInterval(heartbeat);
275
+ await cds_1.default.tx((tx) => (0, sync_state_1.releaseImportLease)(tx, leaseOwner)).catch(() => undefined);
276
+ }
277
+ }
278
+ /** A bigger sort/hash budget for the GROUP BY over millions of rows (PostgreSQL only). */
279
+ const AGGREGATE_WORK_MEM = '256MB';
280
+ /**
281
+ * Aggregates + activation in ONE transaction, so the set is never `active` with sums a successor's
282
+ * import has meanwhile truncated. `prepare` runs first; `finish` and the activation run last,
283
+ * together with the lease check, so the cursor row is not locked during the aggregation.
284
+ */
285
+ async function activateWithAggregates(lease, indexer, anchor, hooks = {}) {
286
+ const importedAt = new Date().toISOString();
287
+ await lease.writeTxLeaseLast(async (tx) => {
288
+ const raw = tx;
289
+ if (cds_1.default.db?.kind === 'postgres') {
290
+ await raw.run(`SET LOCAL work_mem = '${AGGREGATE_WORK_MEM}'`);
291
+ // The planner overestimates the join and walks the address index row by row; hash join + hash aggregate read each table once.
292
+ await raw.run('SET LOCAL enable_nestloop = off');
293
+ }
294
+ await hooks.prepare?.(tx);
295
+ for (const sql of aggregateStatements())
296
+ await raw.run(sql);
297
+ await hooks.finish?.(tx);
298
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'active', anchorSlot: anchor.slot, anchorHash: anchor.hash, importedAt, error: null });
299
+ });
300
+ indexer.setUtxoAnchor(anchor);
301
+ // The aggregation leaves paymentCredential empty; filled in the background.
302
+ indexer.resetPaymentCredentials();
303
+ void indexer.paymentCredentialsReady();
304
+ }
305
+ /**
306
+ * Rebuild only the sums (LedgerAddresses, LedgerAddressAssets, LedgerAccounts) from the rows an
307
+ * earlier import left at the stored anchor, e.g. after the aggregate phase failed. Nothing may have
308
+ * been applied since the anchor; a cursor past it is set back to the anchor, and the blocks after
309
+ * it are crawled again (idempotent writes) so the set follows them.
310
+ */
311
+ async function rebuildUtxoSetAggregates(opts) {
312
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
313
+ if (!cursor)
314
+ throw new UtxoSetImportError('No crawler cursor yet.');
315
+ if ((0, sync_state_1.isCrawlerLeaseActive)(cursor))
316
+ throw new UtxoSetImportError('Crawler is running — pause it first (pauseCrawler).');
317
+ const { anchorSlot, anchorHash, appliedSlot, status } = cursor.utxoSet;
318
+ if (anchorSlot == null || !anchorHash)
319
+ throw new UtxoSetImportError('No imported UTxO set to rebuild the sums from — run importUtxoSet first.');
320
+ if (status === 'importing')
321
+ throw new UtxoSetImportError('The import is still loading rows (status "importing").');
322
+ if (appliedSlot != null) {
323
+ throw new UtxoSetImportError(`Blocks up to slot ${appliedSlot} were already applied to the set — its rows are past the anchor; import again.`);
324
+ }
325
+ const anchor = { slot: anchorSlot, hash: anchorHash };
326
+ const rows = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.LedgerUTxOs).columns('count(*) as n')));
327
+ const utxos = Number(rows?.n ?? 0);
328
+ if (utxos === 0)
329
+ throw new UtxoSetImportError('LedgerUTxOs is empty — run importUtxoSet first.');
330
+ let rewindTo = null;
331
+ if (cursor.lastSlot > anchor.slot) {
332
+ const block = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.Blocks).columns('height').where({ hash: anchor.hash })));
333
+ if (!block)
334
+ throw new UtxoSetImportError(`Cursor is past the anchor and the anchor block ${anchor.hash} is not stored — cannot set the cursor back.`);
335
+ rewindTo = { slot: anchor.slot, hash: anchor.hash, height: Number(block.height ?? 0) };
336
+ }
337
+ return withImportLease(async (lease) => {
338
+ opts.indexer.setUtxoAnchor(null);
339
+ // The previous failure no longer describes the set; a new one replaces it below
340
+ await lease.writeTx((tx) => (0, sync_state_1.setUtxoSetState)(tx, { error: null }));
341
+ try {
342
+ await activateWithAggregates(lease, opts.indexer, anchor, {
343
+ prepare: async (tx) => {
344
+ await tx.run(DELETE.from(cardano_1.LedgerAddressAssets));
345
+ await tx.run(DELETE.from(cardano_1.LedgerAddresses));
346
+ await tx.run(DELETE.from(cardano_1.LedgerAccounts));
347
+ },
348
+ finish: rewindTo ? (tx) => (0, sync_state_1.resetCursorTo)(tx, rewindTo) : undefined,
349
+ });
350
+ }
351
+ catch (err) {
352
+ const message = err instanceof Error ? err.message : String(err);
353
+ logger.error(`UTxO set aggregate rebuild failed: ${message}`);
354
+ if (!(err instanceof UtxoSetLeaseLostError))
355
+ await lease.markInvalid(message);
356
+ throw err;
357
+ }
358
+ logger.info(`UTxO set sums rebuilt from ${utxos} rows at anchor ${anchor.slot}/${anchor.hash}` +
359
+ (rewindTo ? ` (cursor set back from slot ${cursor.lastSlot})` : ''));
360
+ return { utxos, anchor };
361
+ });
362
+ }
363
+ //# sourceMappingURL=utxo-set-import.js.map
@@ -0,0 +1,101 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import type { Amount, BlockData, Transaction as ProviderTransaction } 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
+ /** The point the imported UTxO set describes; blocks with slot > anchor.slot are applied. */
9
+ export interface LedgerAnchor {
10
+ slot: number;
11
+ hash: string;
12
+ }
13
+ export interface LedgerApplyResult {
14
+ created: number;
15
+ spent: number;
16
+ /** Consumed outpoints with no open row — a gap between snapshot and crawl, never expected. */
17
+ missing: number;
18
+ addresses: number;
19
+ }
20
+ /** DB row of `LedgerUTxOs` (flattened struct columns as CAP names them). */
21
+ export interface LedgerUtxoRow {
22
+ txHash: string;
23
+ outputIndex: number;
24
+ address: string;
25
+ stakeAddress: string | null;
26
+ addressType: string;
27
+ isScript: boolean;
28
+ 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
+ hasAssets: boolean;
36
+ }
37
+ export interface LedgerUtxoAssetRow {
38
+ utxo_txHash: string;
39
+ utxo_outputIndex: number;
40
+ unit: string;
41
+ asset_quantity: string;
42
+ asset_policyId: string | null;
43
+ asset_assetNameHex: string | null;
44
+ asset_assetName: string | null;
45
+ }
46
+ /** Minimal output shape the row builder needs — shared by the block path and the import. */
47
+ export interface LedgerOutputLike {
48
+ txHash: string;
49
+ outputIndex: number;
50
+ address: string;
51
+ amount: Amount[];
52
+ dataHash?: string | null;
53
+ inlineDatum?: string | null;
54
+ referenceScriptHash?: string | null;
55
+ }
56
+ /** Build the `LedgerUTxOs` row (+ asset rows) for one output. */
57
+ export declare function buildLedgerUtxoRows(o: LedgerOutputLike, createdSlot: number | null): {
58
+ row: LedgerUtxoRow;
59
+ assets: LedgerUtxoAssetRow[];
60
+ };
61
+ /** `LedgerUTxOs` rows (+ asset rows) of a set of source transactions, keyed `txHash#outputIndex`. */
62
+ export interface LedgerLookup {
63
+ /** Source transaction hashes this lookup covers (found or not). */
64
+ hashes: Set<string>;
65
+ rows: Map<string, LedgerUtxoRow>;
66
+ assets: Map<string, LedgerUtxoAssetRow[]>;
67
+ }
68
+ /**
69
+ * Read the ledger rows of the given source transactions. Asset rows are read only for
70
+ * transactions with at least one row carrying assets, so an ada-only block costs one SELECT.
71
+ */
72
+ export declare function readLedgerOutputs(tx: CapTransaction, txHashes: Iterable<string>, into?: LedgerLookup): Promise<LedgerLookup>;
73
+ /** Amount list (lovelace + native assets) of a ledger row, the shape a resolved input carries. */
74
+ export declare function ledgerRowAmount(row: LedgerUtxoRow, assets: LedgerUtxoAssetRow[] | undefined): Amount[];
75
+ /**
76
+ * Apply one block to the ledger tables. Caller guarantees `block.slot > anchor.slot`.
77
+ * `lookup` may carry rows the caller already read for this block (input resolution).
78
+ * Never throws for a missing outpoint (it is counted and logged); DB errors propagate so the
79
+ * block transaction rolls back as a whole.
80
+ */
81
+ export declare function applyBlockToLedger(tx: CapTransaction, block: BlockData, txs: ProviderTransaction[], lookup?: LedgerLookup): Promise<LedgerApplyResult>;
82
+ /**
83
+ * Reorg undo for a set of rolled-back transactions: drop what they created, reopen what
84
+ * they spent, then recount every address either side touched from the open rows.
85
+ * @returns the recounted addresses
86
+ */
87
+ export declare function undoLedgerForTransactions(tx: CapTransaction, txHashes: string[]): Promise<string[]>;
88
+ /**
89
+ * Recount running sums for the given addresses from their open UTxO rows, then the
90
+ * stake keys those addresses belong to. Also the repair path for a drifted sum.
91
+ */
92
+ export declare function recountLedgerAddresses(tx: CapTransaction, addresses: string[]): Promise<void>;
93
+ /** Recount `LedgerAccounts` for the given stake keys from `LedgerAddresses`. */
94
+ export declare function recountLedgerAccounts(tx: CapTransaction, stakeAddresses: string[]): Promise<void>;
95
+ /**
96
+ * Fill `LedgerAddresses.paymentCredential` where it is missing (rows from the import's SQL
97
+ * aggregation, or written before the column existed). One transaction per chunk, idempotent.
98
+ * @returns rows updated
99
+ */
100
+ export declare function backfillPaymentCredentials(chunkSize?: number): Promise<number>;
101
+ //# sourceMappingURL=ledger-state.d.ts.map