@odatano/core 2.0.0-rc.2 → 2.0.0-rc.20

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 (132) 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/CardanoIndexerService/index.d.ts +139 -2
  4. package/@cds-models/CardanoIndexerService/index.js +18 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +224 -0
  6. package/@cds-models/CardanoODataService/index.js +27 -0
  7. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  8. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  9. package/@cds-models/odatano/cardano/index.d.ts +316 -0
  10. package/@cds-models/odatano/cardano/index.js +33 -0
  11. package/README.md +195 -136
  12. package/db/schema.cds +2121 -1633
  13. package/package.json +179 -173
  14. package/src/index.d.ts +10 -10
  15. package/src/index.js +24 -14
  16. package/src/plugin.js +39 -52
  17. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  18. package/srv/blockchain/backends/blockfrost-backend.js +45 -158
  19. package/srv/blockchain/backends/cardano-backend.d.ts +78 -158
  20. package/srv/blockchain/backends/cardano-backend.js +14 -5
  21. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  22. package/srv/blockchain/backends/koios-backend.js +292 -202
  23. package/srv/blockchain/backends/ogmios-backend.d.ts +59 -96
  24. package/srv/blockchain/backends/ogmios-backend.js +241 -153
  25. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  26. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  27. package/srv/blockchain/cardano-client.d.ts +50 -205
  28. package/srv/blockchain/cardano-client.js +80 -224
  29. package/srv/blockchain/cardano-indexer.d.ts +146 -244
  30. package/srv/blockchain/cardano-indexer.js +442 -285
  31. package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
  32. package/srv/blockchain/cardano-tx-builder.js +21 -107
  33. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  34. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  35. package/srv/blockchain/crawler/crawler.d.ts +121 -53
  36. package/srv/blockchain/crawler/crawler.js +402 -82
  37. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  38. package/srv/blockchain/crawler/index.d.ts +5 -0
  39. package/srv/blockchain/crawler/index.js +35 -7
  40. package/srv/blockchain/crawler/sync-state.d.ts +44 -28
  41. package/srv/blockchain/crawler/sync-state.js +115 -43
  42. package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
  43. package/srv/blockchain/crawler/utxo-set-import.js +269 -0
  44. package/srv/blockchain/ledger-state.d.ts +80 -0
  45. package/srv/blockchain/ledger-state.js +383 -0
  46. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  47. package/srv/blockchain/signing/cose-verifier.js +6 -12
  48. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  49. package/srv/blockchain/signing/external-signer.js +19 -122
  50. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  51. package/srv/blockchain/signing/hsm-signer.js +23 -63
  52. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  53. package/srv/blockchain/signing/signature-verifier.js +13 -54
  54. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  55. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  56. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
  57. package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
  58. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  59. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  60. package/srv/blockchain/wallet-worker/build-request.js +39 -23
  61. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  62. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  63. package/srv/blockchain/wallet-worker/index.js +2 -8
  64. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  65. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  66. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  67. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  68. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  69. package/srv/blockchain/wallet-worker/signers.js +3 -8
  70. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  71. package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
  72. package/srv/cardano-agent-service.cds +146 -0
  73. package/srv/cardano-agent-service.d.ts +2 -0
  74. package/srv/cardano-agent-service.js +12 -0
  75. package/srv/cardano-indexer-service.cds +164 -73
  76. package/srv/cardano-indexer-service.js +156 -11
  77. package/srv/cardano-service.cds +45 -0
  78. package/srv/cardano-service.js +38 -96
  79. package/srv/cardano-sign-service.cds +200 -180
  80. package/srv/cardano-sign-service.js +55 -173
  81. package/srv/cardano-tx-service.cds +32 -26
  82. package/srv/cardano-tx-service.js +133 -195
  83. package/srv/cardano-worker-service.js +7 -15
  84. package/srv/server.d.ts +28 -86
  85. package/srv/server.js +95 -128
  86. package/srv/utils/agent-grants-config.d.ts +37 -0
  87. package/srv/utils/agent-grants-config.js +138 -0
  88. package/srv/utils/agent-grants.d.ts +262 -0
  89. package/srv/utils/agent-grants.js +914 -0
  90. package/srv/utils/agent-token-auth.d.ts +16 -0
  91. package/srv/utils/agent-token-auth.js +78 -0
  92. package/srv/utils/backend-request-handler.d.ts +2 -16
  93. package/srv/utils/backend-request-handler.js +3 -18
  94. package/srv/utils/collections.d.ts +4 -8
  95. package/srv/utils/collections.js +4 -8
  96. package/srv/utils/const.d.ts +19 -68
  97. package/srv/utils/const.js +20 -69
  98. package/srv/utils/crypto.d.ts +3 -12
  99. package/srv/utils/crypto.js +5 -18
  100. package/srv/utils/db-indexes.d.ts +25 -0
  101. package/srv/utils/db-indexes.js +89 -0
  102. package/srv/utils/db-sanitize.d.ts +27 -0
  103. package/srv/utils/db-sanitize.js +85 -0
  104. package/srv/utils/error-codes.d.ts +18 -73
  105. package/srv/utils/error-codes.js +17 -70
  106. package/srv/utils/errors.d.ts +34 -178
  107. package/srv/utils/errors.js +55 -217
  108. package/srv/utils/liveness.d.ts +16 -0
  109. package/srv/utils/liveness.js +41 -0
  110. package/srv/utils/mappers.d.ts +82 -210
  111. package/srv/utils/mappers.js +272 -293
  112. package/srv/utils/network-context.js +2 -11
  113. package/srv/utils/pg-order-nulls.d.ts +14 -0
  114. package/srv/utils/pg-order-nulls.js +57 -0
  115. package/srv/utils/plutus-placeholders.d.ts +6 -18
  116. package/srv/utils/plutus-placeholders.js +6 -20
  117. package/srv/utils/rate-limiter.d.ts +46 -0
  118. package/srv/utils/rate-limiter.js +116 -0
  119. package/srv/utils/service-events.d.ts +2 -22
  120. package/srv/utils/service-events.js +3 -23
  121. package/srv/utils/signing-helper.d.ts +3 -18
  122. package/srv/utils/signing-helper.js +10 -32
  123. package/srv/utils/tx-build-helper.d.ts +18 -92
  124. package/srv/utils/tx-build-helper.js +32 -123
  125. package/srv/utils/tx-request-parsers.d.ts +14 -20
  126. package/srv/utils/tx-request-parsers.js +33 -20
  127. package/srv/utils/tx-utils.d.ts +4 -23
  128. package/srv/utils/tx-utils.js +12 -41
  129. package/srv/utils/types.d.ts +112 -169
  130. package/srv/utils/types.js +2 -6
  131. package/srv/utils/validators.d.ts +19 -89
  132. package/srv/utils/validators.js +31 -138
@@ -0,0 +1,269 @@
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
+ const cds_1 = __importDefault(require("@sap/cds"));
13
+ const node_fs_1 = require("node:fs");
14
+ const promises_1 = require("node:fs/promises");
15
+ const node_readline_1 = require("node:readline");
16
+ const ledger_state_1 = require("../ledger-state");
17
+ const sync_state_1 = require("./sync-state");
18
+ const cardano_1 = require("#cds-models/odatano/cardano");
19
+ const collections_1 = require("../../utils/collections");
20
+ const { UPSERT, DELETE } = cds_1.default.ql;
21
+ const logger = cds_1.default.log('LedgerState');
22
+ /**
23
+ * One-off import of the UTxO set at the anchor `crawler.utxoSet` builds on: from Ogmios
24
+ * (`queryLedgerState/utxo` at the cursor point) or a `cardano-cli query utxo --whole-utxo`
25
+ * dump (`.json` parsed whole; `.ndjson`/`.jsonl` streamed, one entry or `{key,value}` per line).
26
+ */
27
+ class UtxoSetImportError extends Error {
28
+ constructor(message) {
29
+ super(message);
30
+ this.name = 'UtxoSetImportError';
31
+ }
32
+ }
33
+ exports.UtxoSetImportError = UtxoSetImportError;
34
+ /** The cursor lease went to someone else: nothing more may be written, not even `invalid`. */
35
+ class UtxoSetLeaseLostError extends UtxoSetImportError {
36
+ constructor(message = 'Lost the cursor lease during the import — aborted without further writes.') {
37
+ super(message);
38
+ this.name = 'UtxoSetLeaseLostError';
39
+ }
40
+ }
41
+ exports.UtxoSetLeaseLostError = UtxoSetLeaseLostError;
42
+ /**
43
+ * `JSON.parse` for a cardano-cli dump that keeps every integer exact: integer literals outside
44
+ * strings are quoted before parsing, so a quantity above 2^53 is never rounded.
45
+ */
46
+ function parseJsonLossless(text) {
47
+ // string literals pass through untouched; floats keep their JSON meaning
48
+ const rewritten = text.replace(/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g, (m) => (m[0] === '"' || !/^-?\d+$/.test(m) ? m : `"${m}"`));
49
+ return JSON.parse(rewritten);
50
+ }
51
+ /** Parse one `"txHash#index": {…}` entry of a cardano-cli dump; null when malformed. */
52
+ function parseCliUtxoEntry(key, value) {
53
+ const m = /^([0-9a-fA-F]{64})#(\d+)$/.exec(key ?? '');
54
+ if (!m || !value || typeof value.address !== 'string')
55
+ return null;
56
+ const amount = [];
57
+ const v = value.value ?? {};
58
+ for (const [k, q] of Object.entries(v)) {
59
+ if (k === 'lovelace') {
60
+ amount.push({ unit: 'lovelace', quantity: String(q) });
61
+ }
62
+ else if (q && typeof q === 'object') {
63
+ for (const [nameHex, qty] of Object.entries(q)) {
64
+ amount.push({ unit: `${k}${nameHex}`, quantity: String(qty) });
65
+ }
66
+ }
67
+ }
68
+ if (!amount.some(a => a.unit === 'lovelace'))
69
+ amount.unshift({ unit: 'lovelace', quantity: '0' });
70
+ return {
71
+ txHash: m[1].toLowerCase(),
72
+ outputIndex: Number(m[2]),
73
+ address: value.address,
74
+ amount,
75
+ dataHash: value.datumhash ?? value.datumHash ?? null,
76
+ inlineDatum: typeof value.inlineDatumRaw === 'string' ? value.inlineDatumRaw : null,
77
+ // the cli prints the script itself, not its hash — resolved lazily, like every other path
78
+ referenceScriptHash: null,
79
+ };
80
+ }
81
+ /** Stream a cardano-cli dump. See the module doc for the accepted layouts. */
82
+ async function* readUtxoSetFile(filePath) {
83
+ if (/\.json$/i.test(filePath)) {
84
+ const parsed = parseJsonLossless(await (0, promises_1.readFile)(filePath, 'utf8'));
85
+ for (const [key, value] of Object.entries(parsed)) {
86
+ const entry = parseCliUtxoEntry(key, value);
87
+ if (entry)
88
+ yield entry;
89
+ }
90
+ return;
91
+ }
92
+ const rl = (0, node_readline_1.createInterface)({ input: (0, node_fs_1.createReadStream)(filePath, 'utf8'), crlfDelay: Infinity });
93
+ for await (const line of rl) {
94
+ const trimmed = line.trim();
95
+ if (!trimmed)
96
+ continue;
97
+ const obj = parseJsonLossless(trimmed);
98
+ if (typeof obj.key === 'string' && obj.value && typeof obj.value === 'object') {
99
+ const entry = parseCliUtxoEntry(obj.key, obj.value);
100
+ if (entry)
101
+ yield entry;
102
+ continue;
103
+ }
104
+ for (const [key, value] of Object.entries(obj)) {
105
+ const entry = parseCliUtxoEntry(key, value);
106
+ if (entry)
107
+ yield entry;
108
+ }
109
+ }
110
+ }
111
+ async function* readFromOgmios(client, anchor) {
112
+ const backend = client.getLedgerStateBackend();
113
+ if (!backend) {
114
+ throw new UtxoSetImportError('No Ogmios backend available for source "ogmios" — configure one or import a cardano-cli file.');
115
+ }
116
+ const utxos = await backend.queryUtxoSetAt({ slot: anchor.slot, hash: anchor.hash });
117
+ for (const u of utxos) {
118
+ yield {
119
+ txHash: u.txHash,
120
+ outputIndex: u.outputIndex,
121
+ address: u.address,
122
+ amount: u.amount,
123
+ dataHash: u.datumHash ?? null,
124
+ inlineDatum: u.inlineDatum ?? null,
125
+ referenceScriptHash: u.scriptRef ?? null,
126
+ };
127
+ }
128
+ }
129
+ /** Table names as CAP creates them (dots → underscores), for the aggregate statements. */
130
+ const T = {
131
+ utxos: 'odatano_cardano_LedgerUTxOs',
132
+ utxoAssets: 'odatano_cardano_LedgerUTxOAssets',
133
+ addresses: 'odatano_cardano_LedgerAddresses',
134
+ addressAssets: 'odatano_cardano_LedgerAddressAssets',
135
+ accounts: 'odatano_cardano_LedgerAccounts',
136
+ };
137
+ /**
138
+ * The three aggregate statements that derive the running sums from the imported rows.
139
+ * Plain SQL because millions of addresses do not fit an in-memory map and a per-row
140
+ * UPSERT would take hours; the syntax is the portable subset (sqlite, PostgreSQL, HANA).
141
+ */
142
+ function aggregateStatements() {
143
+ return [
144
+ `INSERT INTO ${T.addresses} (address, stakeAddress, addressType, isScript, totalLovelace, utxoCount, firstSeenSlot, lastActiveSlot) ` +
145
+ `SELECT address, MIN(stakeAddress), MIN(addressType), ` +
146
+ `CASE WHEN MAX(CASE WHEN isScript THEN 1 ELSE 0 END) = 1 THEN TRUE ELSE FALSE END, ` +
147
+ `SUM(lovelace), COUNT(*), NULL, NULL FROM ${T.utxos} GROUP BY address`,
148
+ `INSERT INTO ${T.addressAssets} (address_address, unit, asset_quantity, asset_policyId, asset_assetNameHex, asset_assetName) ` +
149
+ `SELECT u.address, a.unit, SUM(a.asset_quantity), MIN(a.asset_policyId), MIN(a.asset_assetNameHex), MIN(a.asset_assetName) ` +
150
+ `FROM ${T.utxoAssets} a JOIN ${T.utxos} u ON a.utxo_txHash = u.txHash AND a.utxo_outputIndex = u.outputIndex ` +
151
+ `GROUP BY u.address, a.unit`,
152
+ `INSERT INTO ${T.accounts} (stakeAddress, controlledAmount, addressCount, utxoCount, lastActiveSlot) ` +
153
+ `SELECT stakeAddress, SUM(totalLovelace), COUNT(*), SUM(utxoCount), NULL FROM ${T.addresses} ` +
154
+ `WHERE stakeAddress IS NOT NULL GROUP BY stakeAddress`,
155
+ ];
156
+ }
157
+ /**
158
+ * Run the import. Throws `UtxoSetImportError` on a precondition failure before anything is
159
+ * written; a failure mid-way leaves the set marked `invalid` (never half-`active`).
160
+ */
161
+ async function importUtxoSet(opts) {
162
+ const { anchor, source } = opts;
163
+ const batchSize = opts.batchSize ?? 2000;
164
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
165
+ if (!cursor)
166
+ throw new UtxoSetImportError('No crawler cursor yet — start the crawler once before importing.');
167
+ if ((0, sync_state_1.isCrawlerLeaseActive)(cursor))
168
+ throw new UtxoSetImportError('Crawler is running — pause it first (pauseCrawler).');
169
+ if (cursor.lastSlot > anchor.slot) {
170
+ throw new UtxoSetImportError(`Crawler cursor (slot ${cursor.lastSlot}) is past the anchor (slot ${anchor.slot}) — blocks after the anchor were ` +
171
+ 'already crawled without a set to apply them to. Dump the set at or after the cursor.');
172
+ }
173
+ if (source === 'file' && !opts.filePath)
174
+ throw new UtxoSetImportError('source "file" needs filePath.');
175
+ // Cluster-wide exclusion: hold the cursor lease for the whole import. A crawler start on
176
+ // any instance (resumeCrawler, standby) and a second import are refused while it is held;
177
+ // renewed on a heartbeat, released in `finally`.
178
+ const leaseOwner = `import:${process.pid}:${Date.now().toString(36)}`;
179
+ const acquired = await cds_1.default.tx((tx) => (0, sync_state_1.tryAcquireImportLease)(tx, leaseOwner));
180
+ if (!acquired)
181
+ throw new UtxoSetImportError('Could not take the cursor lease — a crawler or another import holds it.');
182
+ let leaseLost = false;
183
+ const heartbeat = setInterval(() => {
184
+ cds_1.default.tx((tx) => (0, sync_state_1.renewImportLease)(tx, leaseOwner))
185
+ .then((ok) => { if (!ok)
186
+ leaseLost = true; })
187
+ .catch(() => { leaseLost = true; });
188
+ }, Math.max(1000, Math.floor(sync_state_1.CRAWLER_LEASE_TTL_MS / 3)));
189
+ heartbeat.unref();
190
+ /**
191
+ * Every write re-takes the lease INSIDE its transaction (conditional UPDATE + read-back), so
192
+ * a successor that took the lease between two batches fails this transaction before commit.
193
+ */
194
+ const writeTx = (fn) => cds_1.default.tx(async (tx) => {
195
+ if (leaseLost || !(await (0, sync_state_1.renewImportLease)(tx, leaseOwner)))
196
+ throw new UtxoSetLeaseLostError();
197
+ return fn(tx);
198
+ });
199
+ opts.indexer.setUtxoAnchor(null);
200
+ try {
201
+ await writeTx(async (tx) => {
202
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'importing', anchorSlot: anchor.slot, anchorHash: anchor.hash, error: null, importedAt: null, appliedSlot: null });
203
+ await tx.run(DELETE.from(cardano_1.LedgerUTxOAssets));
204
+ await tx.run(DELETE.from(cardano_1.LedgerUTxOs));
205
+ await tx.run(DELETE.from(cardano_1.LedgerAddressAssets));
206
+ await tx.run(DELETE.from(cardano_1.LedgerAddresses));
207
+ await tx.run(DELETE.from(cardano_1.LedgerAccounts));
208
+ });
209
+ let imported = 0;
210
+ try {
211
+ const entries = source === 'ogmios' ? readFromOgmios(opts.client, anchor) : readUtxoSetFile(opts.filePath);
212
+ let rows = [];
213
+ let assets = [];
214
+ const flush = async () => {
215
+ if (!rows.length)
216
+ return;
217
+ const r = rows;
218
+ const a = assets;
219
+ rows = [];
220
+ assets = [];
221
+ await writeTx(async (tx) => {
222
+ for (const c of (0, collections_1.chunk)(r, collections_1.IN_CHUNK))
223
+ await tx.run(UPSERT.into(cardano_1.LedgerUTxOs).entries(c));
224
+ for (const c of (0, collections_1.chunk)(a, collections_1.IN_CHUNK))
225
+ await tx.run(UPSERT.into(cardano_1.LedgerUTxOAssets).entries(c));
226
+ });
227
+ imported += r.length;
228
+ opts.onProgress?.(imported);
229
+ };
230
+ for await (const e of entries) {
231
+ const built = (0, ledger_state_1.buildLedgerUtxoRows)(e, null);
232
+ rows.push(built.row);
233
+ assets.push(...built.assets);
234
+ if (rows.length >= batchSize)
235
+ await flush();
236
+ }
237
+ await flush();
238
+ // Aggregates + activation in ONE lease-checked transaction: the set can never be
239
+ // `active` with sums a successor's import has meanwhile truncated.
240
+ const importedAt = new Date().toISOString();
241
+ await writeTx(async (tx) => {
242
+ for (const sql of aggregateStatements())
243
+ await tx.run(sql);
244
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'active', anchorSlot: anchor.slot, anchorHash: anchor.hash, importedAt, error: null });
245
+ });
246
+ opts.indexer.setUtxoAnchor(anchor);
247
+ logger.info(`UTxO set imported: ${imported} entries at anchor ${anchor.slot}/${anchor.hash} (source=${source})`);
248
+ return { utxos: imported, anchor };
249
+ }
250
+ catch (err) {
251
+ const message = err instanceof Error ? err.message : String(err);
252
+ logger.error(`UTxO set import failed after ${imported} entries: ${message}`);
253
+ // Only the lease holder may write the failure state; after a takeover the row is the
254
+ // successor's and the truncated tables are its problem to fill.
255
+ if (!(err instanceof UtxoSetLeaseLostError)) {
256
+ await cds_1.default.tx(async (tx) => {
257
+ if (await (0, sync_state_1.renewImportLease)(tx, leaseOwner))
258
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: message.slice(0, 500) });
259
+ }).catch(() => undefined);
260
+ }
261
+ throw err;
262
+ }
263
+ }
264
+ finally {
265
+ clearInterval(heartbeat);
266
+ await cds_1.default.tx((tx) => (0, sync_state_1.releaseImportLease)(tx, leaseOwner)).catch(() => undefined);
267
+ }
268
+ }
269
+ //# sourceMappingURL=utxo-set-import.js.map
@@ -0,0 +1,80 @@
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
+ /**
62
+ * Apply one block to the ledger tables. Caller guarantees `block.slot > anchor.slot`.
63
+ * Never throws for a missing outpoint (it is counted and logged); DB errors propagate so the
64
+ * block transaction rolls back as a whole.
65
+ */
66
+ export declare function applyBlockToLedger(tx: CapTransaction, block: BlockData, txs: ProviderTransaction[]): Promise<LedgerApplyResult>;
67
+ /**
68
+ * Reorg undo for a set of rolled-back transactions: drop what they created, reopen what
69
+ * they spent, then recount every address either side touched from the open rows.
70
+ * @returns the recounted addresses
71
+ */
72
+ export declare function undoLedgerForTransactions(tx: CapTransaction, txHashes: string[]): Promise<string[]>;
73
+ /**
74
+ * Recount running sums for the given addresses from their open UTxO rows, then the
75
+ * stake keys those addresses belong to. Also the repair path for a drifted sum.
76
+ */
77
+ export declare function recountLedgerAddresses(tx: CapTransaction, addresses: string[]): Promise<void>;
78
+ /** Recount `LedgerAccounts` for the given stake keys from `LedgerAddresses`. */
79
+ export declare function recountLedgerAccounts(tx: CapTransaction, stakeAddresses: string[]): Promise<void>;
80
+ //# sourceMappingURL=ledger-state.d.ts.map