@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,399 @@
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.parseCliUtxoEntry = parseCliUtxoEntry;
8
+ exports.readUtxoSetFile = readUtxoSetFile;
9
+ exports.aggregateStatements = aggregateStatements;
10
+ exports.importUtxoSet = importUtxoSet;
11
+ exports.rebuildUtxoSetAggregates = rebuildUtxoSetAggregates;
12
+ exports.refreshUtxoSetReferenceScripts = refreshUtxoSetReferenceScripts;
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 reference_script_1 = require("../../utils/reference-script");
18
+ const deep_json_1 = require("../../utils/deep-json");
19
+ const ledger_state_1 = require("../ledger-state");
20
+ const sync_state_1 = require("./sync-state");
21
+ const cardano_1 = require("#cds-models/odatano/cardano");
22
+ const collections_1 = require("../../utils/collections");
23
+ const { UPSERT, DELETE, SELECT, UPDATE } = cds_1.default.ql;
24
+ const logger = cds_1.default.log('LedgerState');
25
+ // One-off import of the UTxO set that `crawler.utxoSet` builds on, from Ogmios or a cardano-cli dump.
26
+ // A `.json` dump is parsed whole. Other files are streamed with one entry or `{key,value}` per line.
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
+ /** Parse one `"txHash#index": {…}` entry of a cardano-cli dump; null when malformed. */
43
+ function parseCliUtxoEntry(key, value) {
44
+ const m = /^([0-9a-fA-F]{64})#(\d+)$/.exec(key ?? '');
45
+ if (!m || !value || typeof value.address !== 'string')
46
+ return null;
47
+ const amount = [];
48
+ const v = value.value ?? {};
49
+ for (const [k, q] of Object.entries(v)) {
50
+ if (k === 'lovelace') {
51
+ amount.push({ unit: 'lovelace', quantity: String(q) });
52
+ }
53
+ else if (q && typeof q === 'object') {
54
+ for (const [nameHex, qty] of Object.entries(q)) {
55
+ amount.push({ unit: `${k}${nameHex}`, quantity: String(qty) });
56
+ }
57
+ }
58
+ }
59
+ if (!amount.some(a => a.unit === 'lovelace'))
60
+ amount.unshift({ unit: 'lovelace', quantity: '0' });
61
+ const ref = (0, reference_script_1.cliReferenceScript)(value.referenceScript);
62
+ return {
63
+ txHash: m[1].toLowerCase(),
64
+ outputIndex: Number(m[2]),
65
+ address: value.address,
66
+ amount,
67
+ dataHash: value.datumhash ?? value.datumHash ?? null,
68
+ inlineDatum: typeof value.inlineDatumRaw === 'string' ? value.inlineDatumRaw : null,
69
+ referenceScriptHash: ref?.hash ?? null,
70
+ referenceScriptSize: ref?.size ?? null,
71
+ referenceScriptType: ref?.type ?? null,
72
+ };
73
+ }
74
+ /** Stream a cardano-cli dump. See the module doc for the accepted layouts. */
75
+ async function* readUtxoSetFile(filePath) {
76
+ if (/\.json$/i.test(filePath)) {
77
+ const parsed = (0, deep_json_1.parseJson)(await (0, promises_1.readFile)(filePath, 'utf8'));
78
+ for (const [key, value] of Object.entries(parsed)) {
79
+ const entry = parseCliUtxoEntry(key, value);
80
+ if (entry)
81
+ yield entry;
82
+ }
83
+ return;
84
+ }
85
+ const rl = (0, node_readline_1.createInterface)({ input: (0, node_fs_1.createReadStream)(filePath, 'utf8'), crlfDelay: Infinity });
86
+ for await (const line of rl) {
87
+ const trimmed = line.trim();
88
+ if (!trimmed)
89
+ continue;
90
+ const obj = (0, deep_json_1.parseJson)(trimmed);
91
+ if (typeof obj.key === 'string' && obj.value && typeof obj.value === 'object') {
92
+ const entry = parseCliUtxoEntry(obj.key, obj.value);
93
+ if (entry)
94
+ yield entry;
95
+ continue;
96
+ }
97
+ for (const [key, value] of Object.entries(obj)) {
98
+ const entry = parseCliUtxoEntry(key, value);
99
+ if (entry)
100
+ yield entry;
101
+ }
102
+ }
103
+ }
104
+ async function* readFromOgmios(client, anchor) {
105
+ const backend = client.getLedgerStateBackend();
106
+ if (!backend) {
107
+ throw new UtxoSetImportError('No Ogmios backend available for source "ogmios". Configure one or import a cardano-cli file.');
108
+ }
109
+ const utxos = await backend.queryUtxoSetAt({ slot: anchor.slot, hash: anchor.hash });
110
+ for (const u of utxos) {
111
+ yield {
112
+ txHash: u.txHash,
113
+ outputIndex: u.outputIndex,
114
+ address: u.address,
115
+ amount: u.amount,
116
+ dataHash: u.datumHash ?? null,
117
+ inlineDatum: u.inlineDatum ?? null,
118
+ referenceScriptHash: u.scriptRef ?? null,
119
+ referenceScriptSize: u.scriptRefSize ?? null,
120
+ referenceScriptType: u.scriptRefType ?? null,
121
+ };
122
+ }
123
+ }
124
+ /** Table names as CAP creates them (dots → underscores), for the aggregate statements. */
125
+ const T = {
126
+ utxos: 'odatano_cardano_LedgerUTxOs',
127
+ utxoAssets: 'odatano_cardano_LedgerUTxOAssets',
128
+ addresses: 'odatano_cardano_LedgerAddresses',
129
+ addressAssets: 'odatano_cardano_LedgerAddressAssets',
130
+ accounts: 'odatano_cardano_LedgerAccounts',
131
+ };
132
+ // Derive the running sums from the imported rows. Plain SQL, because millions of addresses
133
+ // do not fit in memory and per-row UPSERTs take hours. Portable across SQLite, PostgreSQL and HANA.
134
+ function aggregateStatements() {
135
+ return [
136
+ `INSERT INTO ${T.addresses} (address, stakeAddress, addressType, isScript, totalLovelace, utxoCount, firstSeenSlot, lastActiveSlot) ` +
137
+ `SELECT address, MIN(stakeAddress), MIN(addressType), ` +
138
+ `CASE WHEN MAX(CASE WHEN isScript THEN 1 ELSE 0 END) = 1 THEN TRUE ELSE FALSE END, ` +
139
+ `SUM(lovelace), COUNT(*), NULL, NULL FROM ${T.utxos} WHERE spentTxHash IS NULL GROUP BY address`,
140
+ `INSERT INTO ${T.addressAssets} (address_address, unit, asset_quantity, asset_policyId, asset_assetNameHex, asset_assetName) ` +
141
+ `SELECT u.address, a.unit, SUM(a.asset_quantity), MIN(a.asset_policyId), MIN(a.asset_assetNameHex), MIN(a.asset_assetName) ` +
142
+ `FROM ${T.utxoAssets} a JOIN ${T.utxos} u ON a.utxo_txHash = u.txHash AND a.utxo_outputIndex = u.outputIndex ` +
143
+ `WHERE u.spentTxHash IS NULL GROUP BY u.address, a.unit`,
144
+ `INSERT INTO ${T.accounts} (stakeAddress, controlledAmount, addressCount, utxoCount, lastActiveSlot) ` +
145
+ `SELECT stakeAddress, SUM(totalLovelace), COUNT(*), SUM(utxoCount), NULL FROM ${T.addresses} ` +
146
+ `WHERE stakeAddress IS NOT NULL GROUP BY stakeAddress`,
147
+ ];
148
+ }
149
+ // Precondition failures throw before any write. A failure mid-way marks the set `invalid`.
150
+ async function importUtxoSet(opts) {
151
+ const { anchor, source } = opts;
152
+ const batchSize = opts.batchSize ?? 2000;
153
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
154
+ if (!cursor)
155
+ throw new UtxoSetImportError('No crawler cursor yet. Start the crawler once before importing.');
156
+ if ((0, sync_state_1.isCrawlerLeaseActive)(cursor))
157
+ throw new UtxoSetImportError('Crawler is running. Pause it first (pauseCrawler).');
158
+ if (cursor.lastSlot > anchor.slot) {
159
+ throw new UtxoSetImportError(`Crawler cursor (slot ${cursor.lastSlot}) is past the anchor (slot ${anchor.slot}). Blocks after the anchor were ` +
160
+ 'already crawled without a set to apply them to. Dump the set at or after the cursor.');
161
+ }
162
+ if (source === 'file' && !opts.filePath)
163
+ throw new UtxoSetImportError('source "file" needs filePath.');
164
+ return withImportLease(async (lease) => {
165
+ const { writeTx } = lease;
166
+ opts.indexer.setUtxoAnchor(null);
167
+ await writeTx(async (tx) => {
168
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'importing', anchorSlot: anchor.slot, anchorHash: anchor.hash, error: null, importedAt: null, appliedSlot: null });
169
+ await tx.run(DELETE.from(cardano_1.LedgerUTxOAssets));
170
+ await tx.run(DELETE.from(cardano_1.LedgerUTxOs));
171
+ await tx.run(DELETE.from(cardano_1.LedgerAddressAssets));
172
+ await tx.run(DELETE.from(cardano_1.LedgerAddresses));
173
+ await tx.run(DELETE.from(cardano_1.LedgerAccounts));
174
+ });
175
+ let imported = 0;
176
+ try {
177
+ const entries = source === 'ogmios' ? readFromOgmios(opts.client, anchor) : readUtxoSetFile(opts.filePath);
178
+ let rows = [];
179
+ let assets = [];
180
+ const flush = async () => {
181
+ if (!rows.length)
182
+ return;
183
+ const r = rows;
184
+ const a = assets;
185
+ rows = [];
186
+ assets = [];
187
+ await writeTx(async (tx) => {
188
+ for (const c of (0, collections_1.chunk)(r, collections_1.IN_CHUNK))
189
+ await tx.run(UPSERT.into(cardano_1.LedgerUTxOs).entries(c));
190
+ for (const c of (0, collections_1.chunk)(a, collections_1.IN_CHUNK))
191
+ await tx.run(UPSERT.into(cardano_1.LedgerUTxOAssets).entries(c));
192
+ });
193
+ imported += r.length;
194
+ opts.onProgress?.(imported);
195
+ };
196
+ for await (const e of entries) {
197
+ const built = (0, ledger_state_1.buildLedgerUtxoRows)(e, null);
198
+ rows.push(built.row);
199
+ assets.push(...built.assets);
200
+ if (rows.length >= batchSize)
201
+ await flush();
202
+ }
203
+ await flush();
204
+ await activateWithAggregates(lease, opts.indexer, anchor);
205
+ logger.info(`UTxO set imported: ${imported} entries at anchor ${anchor.slot}/${anchor.hash} (source=${source})`);
206
+ return { utxos: imported, anchor };
207
+ }
208
+ catch (err) {
209
+ const message = err instanceof Error ? err.message : String(err);
210
+ logger.error(`UTxO set import failed after ${imported} entries: ${message}`);
211
+ // Only the lease holder may write the failure state; after a takeover the row is the
212
+ // successor's and the truncated tables are its problem to fill.
213
+ if (!(err instanceof UtxoSetLeaseLostError))
214
+ await lease.markInvalid(message);
215
+ throw err;
216
+ }
217
+ });
218
+ }
219
+ /** Hold the cursor lease for the whole run, so no crawler and no second import can start. */
220
+ async function withImportLease(run) {
221
+ const leaseOwner = `import:${process.pid}:${Date.now().toString(36)}`;
222
+ const acquired = await cds_1.default.tx((tx) => (0, sync_state_1.tryAcquireImportLease)(tx, leaseOwner));
223
+ if (!acquired)
224
+ throw new UtxoSetImportError('Could not take the cursor lease: a crawler or another import holds it.');
225
+ let leaseLost = false;
226
+ let renewing = false;
227
+ const heartbeat = setInterval(() => {
228
+ // A renewal still waiting keeps its connection; a second one would only take another from the pool
229
+ if (renewing)
230
+ return;
231
+ renewing = true;
232
+ cds_1.default.tx(async (tx) => { if (!(await (0, sync_state_1.renewImportLease)(tx, leaseOwner)))
233
+ leaseLost = true; })
234
+ .catch(() => { leaseLost = true; })
235
+ .finally(() => { renewing = false; });
236
+ }, Math.max(1000, Math.floor(sync_state_1.CRAWLER_LEASE_TTL_MS / 3)));
237
+ heartbeat.unref();
238
+ const lease = {
239
+ writeTx: (fn) => cds_1.default.tx(async (tx) => {
240
+ if (leaseLost || !(await (0, sync_state_1.renewImportLease)(tx, leaseOwner)))
241
+ throw new UtxoSetLeaseLostError();
242
+ return fn(tx);
243
+ }),
244
+ writeTxLeaseLast: (fn) => cds_1.default.tx(async (tx) => {
245
+ const result = await fn(tx);
246
+ if (!(await (0, sync_state_1.renewImportLease)(tx, leaseOwner)))
247
+ throw new UtxoSetLeaseLostError();
248
+ return result;
249
+ }),
250
+ markInvalid: (message) => cds_1.default.tx(async (tx) => {
251
+ if (await (0, sync_state_1.renewImportLease)(tx, leaseOwner))
252
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: message.slice(0, 500) });
253
+ }).then(() => undefined, () => undefined),
254
+ };
255
+ try {
256
+ return await run(lease);
257
+ }
258
+ finally {
259
+ clearInterval(heartbeat);
260
+ await cds_1.default.tx((tx) => (0, sync_state_1.releaseImportLease)(tx, leaseOwner)).catch(() => undefined);
261
+ }
262
+ }
263
+ /** A bigger sort/hash budget for the GROUP BY over millions of rows (PostgreSQL only). */
264
+ const AGGREGATE_WORK_MEM = '256MB';
265
+ // Aggregates and activation share one transaction, so `active` never shows truncated sums.
266
+ // The lease check runs last, so the cursor row is not locked during the aggregation.
267
+ async function activateWithAggregates(lease, indexer, anchor, hooks = {}) {
268
+ const importedAt = new Date().toISOString();
269
+ await lease.writeTxLeaseLast(async (tx) => {
270
+ const raw = tx;
271
+ if (cds_1.default.db?.kind === 'postgres') {
272
+ await raw.run(`SET LOCAL work_mem = '${AGGREGATE_WORK_MEM}'`);
273
+ // The planner overestimates the join and walks the address index row by row; hash join + hash aggregate read each table once.
274
+ await raw.run('SET LOCAL enable_nestloop = off');
275
+ }
276
+ await hooks.prepare?.(tx);
277
+ for (const sql of aggregateStatements())
278
+ await raw.run(sql);
279
+ await hooks.finish?.(tx);
280
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'active', anchorSlot: anchor.slot, anchorHash: anchor.hash, importedAt, error: null });
281
+ });
282
+ indexer.setUtxoAnchor(anchor);
283
+ // The aggregation leaves paymentCredential empty; filled in the background.
284
+ indexer.resetPaymentCredentials();
285
+ void indexer.paymentCredentialsReady();
286
+ }
287
+ // Rebuild only the sums from rows an earlier import left, e.g. after the aggregate step failed.
288
+ // A cursor past the snapshot slot is set back, so the blocks after it are crawled again.
289
+ async function rebuildUtxoSetAggregates(opts) {
290
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
291
+ if (!cursor)
292
+ throw new UtxoSetImportError('No crawler cursor yet.');
293
+ if ((0, sync_state_1.isCrawlerLeaseActive)(cursor))
294
+ throw new UtxoSetImportError('Crawler is running. Pause it first (pauseCrawler).');
295
+ const { anchorSlot, anchorHash, appliedSlot, status } = cursor.utxoSet;
296
+ if (anchorSlot == null || !anchorHash)
297
+ throw new UtxoSetImportError('No imported UTxO set to rebuild the sums from: run importUtxoSet first.');
298
+ if (status === 'importing')
299
+ throw new UtxoSetImportError('The import is still loading rows (status "importing").');
300
+ if (appliedSlot != null) {
301
+ throw new UtxoSetImportError(`Blocks up to slot ${appliedSlot} were already applied to the set. Its rows are past the anchor; import again.`);
302
+ }
303
+ const anchor = { slot: anchorSlot, hash: anchorHash };
304
+ const rows = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.LedgerUTxOs).columns('count(*) as n')));
305
+ const utxos = Number(rows?.n ?? 0);
306
+ if (utxos === 0)
307
+ throw new UtxoSetImportError('LedgerUTxOs is empty: run importUtxoSet first.');
308
+ let rewindTo = null;
309
+ if (cursor.lastSlot > anchor.slot) {
310
+ const block = await cds_1.default.tx((tx) => tx.run(SELECT.one.from(cardano_1.Blocks).columns('height').where({ hash: anchor.hash })));
311
+ if (!block)
312
+ throw new UtxoSetImportError(`Cursor is past the anchor and the anchor block ${anchor.hash} is not stored, cannot set the cursor back.`);
313
+ rewindTo = { slot: anchor.slot, hash: anchor.hash, height: Number(block.height ?? 0) };
314
+ }
315
+ return withImportLease(async (lease) => {
316
+ opts.indexer.setUtxoAnchor(null);
317
+ // The previous failure no longer describes the set; a new one replaces it below
318
+ await lease.writeTx((tx) => (0, sync_state_1.setUtxoSetState)(tx, { error: null }));
319
+ try {
320
+ await activateWithAggregates(lease, opts.indexer, anchor, {
321
+ prepare: async (tx) => {
322
+ await tx.run(DELETE.from(cardano_1.LedgerAddressAssets));
323
+ await tx.run(DELETE.from(cardano_1.LedgerAddresses));
324
+ await tx.run(DELETE.from(cardano_1.LedgerAccounts));
325
+ },
326
+ finish: rewindTo ? (tx) => (0, sync_state_1.resetCursorTo)(tx, rewindTo) : undefined,
327
+ });
328
+ }
329
+ catch (err) {
330
+ const message = err instanceof Error ? err.message : String(err);
331
+ logger.error(`UTxO set aggregate rebuild failed: ${message}`);
332
+ if (!(err instanceof UtxoSetLeaseLostError))
333
+ await lease.markInvalid(message);
334
+ throw err;
335
+ }
336
+ logger.info(`UTxO set sums rebuilt from ${utxos} rows at anchor ${anchor.slot}/${anchor.hash}` +
337
+ (rewindTo ? ` (cursor set back from slot ${cursor.lastSlot})` : ''));
338
+ return { utxos, anchor };
339
+ });
340
+ }
341
+ // Fill reference-script columns an earlier import left empty, from the dump or from the node.
342
+ // Takes the cursor lease, so the crawler must be paused. The set stays `active`.
343
+ async function refreshUtxoSetReferenceScripts(opts) {
344
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
345
+ if (!cursor)
346
+ throw new UtxoSetImportError('No crawler cursor yet.');
347
+ if ((0, sync_state_1.isCrawlerLeaseActive)(cursor))
348
+ throw new UtxoSetImportError('Crawler is running. Pause it first (pauseCrawler).');
349
+ if (cursor.utxoSet.anchorSlot == null)
350
+ throw new UtxoSetImportError('No imported UTxO set: run importUtxoSet first.');
351
+ const batchSize = opts.batchSize ?? 2000;
352
+ return withImportLease(async (lease) => {
353
+ let candidates = 0;
354
+ let updated = 0;
355
+ const write = async (fills) => {
356
+ if (!fills.length)
357
+ return;
358
+ await lease.writeTx(async (tx) => {
359
+ for (const f of fills) {
360
+ const n = await tx.run(UPDATE.entity(cardano_1.LedgerUTxOs)
361
+ .set({ utxo_referenceScriptHash: f.hash, utxo_referenceScriptSize: f.size, utxo_referenceScriptType: f.type })
362
+ .where({ txHash: f.txHash, outputIndex: f.outputIndex }));
363
+ updated += Number(n) || 0;
364
+ }
365
+ });
366
+ };
367
+ if (opts.filePath) {
368
+ let fills = [];
369
+ for await (const e of readUtxoSetFile(opts.filePath)) {
370
+ if (!e.referenceScriptHash || e.referenceScriptSize == null || !e.referenceScriptType)
371
+ continue;
372
+ candidates++;
373
+ fills.push({ txHash: e.txHash, outputIndex: e.outputIndex, hash: e.referenceScriptHash, size: e.referenceScriptSize, type: e.referenceScriptType });
374
+ if (fills.length >= batchSize) {
375
+ await write(fills);
376
+ fills = [];
377
+ }
378
+ }
379
+ await write(fills);
380
+ }
381
+ else {
382
+ const backend = opts.client.getLedgerStateBackend();
383
+ if (!backend)
384
+ throw new UtxoSetImportError('No Ogmios backend available. Pass the cardano-cli dump as filePath instead.');
385
+ const rows = await cds_1.default.tx((tx) => tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('txHash', 'outputIndex')
386
+ .where({ spentTxHash: null, utxo_referenceScriptHash: { '!=': null }, utxo_referenceScriptSize: null })));
387
+ candidates = rows?.length ?? 0;
388
+ for (const refs of (0, collections_1.chunk)(rows ?? [], collections_1.IN_CHUNK)) {
389
+ const live = await backend.getUnspentOutputs(refs.map(r => ({ txHash: r.txHash, outputIndex: Number(r.outputIndex) })));
390
+ await write(live.flatMap(u => (u.scriptRef && u.scriptRefSize != null && u.scriptRefType
391
+ ? [{ txHash: u.txHash, outputIndex: u.outputIndex, hash: u.scriptRef, size: u.scriptRefSize, type: u.scriptRefType }]
392
+ : [])));
393
+ }
394
+ }
395
+ logger.info(`UTxO set reference scripts refreshed: ${updated} of ${candidates} rows (${opts.filePath ? 'dump' : 'node'})`);
396
+ return { updated, candidates };
397
+ });
398
+ }
399
+ //# sourceMappingURL=utxo-set-import.js.map
@@ -0,0 +1,62 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import { type LedgerUTxO, type LedgerUTxOAsset } from '#cds-models/odatano/cardano';
3
+ import type { Amount, BlockData, Transaction as ProviderTransaction, ReferenceScriptType } from '../utils/types';
4
+ /** The point the imported UTxO set describes; blocks with slot > anchor.slot are applied. */
5
+ export interface LedgerAnchor {
6
+ slot: number;
7
+ hash: string;
8
+ }
9
+ export interface LedgerApplyResult {
10
+ created: number;
11
+ spent: number;
12
+ /** Consumed outputs with no open row. Means a gap between snapshot and crawl, never expected. */
13
+ missing: number;
14
+ addresses: number;
15
+ }
16
+ /** A `LedgerUTxOs` row as the block path writes it: every column set, lovelace as an exact string. */
17
+ export type LedgerUtxoRow = Required<Omit<LedgerUTxO, 'assets' | 'lovelace' | 'utxo_referenceScriptType' | 'address' | 'addressType' | 'isScript' | 'hasAssets'>> & {
18
+ address: string;
19
+ addressType: string;
20
+ isScript: boolean;
21
+ hasAssets: boolean;
22
+ lovelace: string;
23
+ utxo_referenceScriptType: ReferenceScriptType | null;
24
+ };
25
+ /** A `LedgerUTxOAssets` row as the block path writes it. */
26
+ export type LedgerUtxoAssetRow = Required<Omit<LedgerUTxOAsset, 'utxo' | 'asset_fingerprint' | 'asset_quantity'>> & {
27
+ asset_quantity: string;
28
+ };
29
+ /** Minimal output shape the row builder needs, shared by the block path and the import. */
30
+ export interface LedgerOutputLike {
31
+ txHash: string;
32
+ outputIndex: number;
33
+ address: string;
34
+ amount: Amount[];
35
+ dataHash?: string | null;
36
+ inlineDatum?: string | null;
37
+ referenceScriptHash?: string | null;
38
+ referenceScriptSize?: number | null;
39
+ referenceScriptType?: ReferenceScriptType | null;
40
+ }
41
+ /** Build the `LedgerUTxOs` row (+ asset rows) for one output. */
42
+ export declare function buildLedgerUtxoRows(o: LedgerOutputLike, createdSlot: number | null): {
43
+ row: LedgerUtxoRow;
44
+ assets: LedgerUtxoAssetRow[];
45
+ };
46
+ /** `LedgerUTxOs` rows (+ asset rows) of a set of source transactions, keyed `txHash#outputIndex`. */
47
+ export interface LedgerLookup {
48
+ /** Source transaction hashes this lookup covers (found or not). */
49
+ hashes: Set<string>;
50
+ rows: Map<string, LedgerUtxoRow>;
51
+ assets: Map<string, LedgerUtxoAssetRow[]>;
52
+ }
53
+ export declare function readLedgerOutputs(tx: CapTransaction, txHashes: Iterable<string>, into?: LedgerLookup): Promise<LedgerLookup>;
54
+ /** Amount list (lovelace + native assets) of a ledger row, the shape a resolved input carries. */
55
+ export declare function ledgerRowAmount(row: LedgerUtxoRow, assets: LedgerUtxoAssetRow[] | undefined): Amount[];
56
+ export declare function applyBlockToLedger(tx: CapTransaction, block: BlockData, txs: ProviderTransaction[], lookup?: LedgerLookup): Promise<LedgerApplyResult>;
57
+ export declare function undoLedgerForTransactions(tx: CapTransaction, txHashes: string[]): Promise<string[]>;
58
+ export declare function recountLedgerAddresses(tx: CapTransaction, addresses: string[]): Promise<void>;
59
+ /** Recount `LedgerAccounts` for the given stake keys from `LedgerAddresses`. */
60
+ export declare function recountLedgerAccounts(tx: CapTransaction, stakeAddresses: string[]): Promise<void>;
61
+ export declare function backfillPaymentCredentials(chunkSize?: number): Promise<number>;
62
+ //# sourceMappingURL=ledger-state.d.ts.map