@odatano/core 2.0.0-rc.3 → 2.0.0-rc.30

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 (162) 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 +294 -7
  8. package/@cds-models/CardanoODataService/index.js +33 -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 +52 -19
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +18 -0
  14. package/@cds-models/index.js +3 -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 +677 -13
  19. package/db/types.cds +27 -0
  20. package/package.json +182 -173
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +11 -10
  24. package/src/index.js +28 -14
  25. package/src/plugin.js +39 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +49 -160
  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 +356 -217
  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 +548 -197
  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 +78 -205
  39. package/srv/blockchain/cardano-client.js +186 -242
  40. package/srv/blockchain/cardano-indexer.d.ts +302 -242
  41. package/srv/blockchain/cardano-indexer.js +1191 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +43 -81
  43. package/srv/blockchain/cardano-tx-builder.js +177 -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 +8 -44
  68. package/srv/blockchain/signing/signature-verifier.js +13 -54
  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 +108 -160
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +620 -285
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +17 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +50 -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 +48 -24
  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 +56 -1
  102. package/srv/cardano-service.js +52 -113
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +55 -173
  105. package/srv/cardano-tx-service.cds +439 -364
  106. package/srv/cardano-tx-service.js +305 -209
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/parse.js +13 -1
  110. package/srv/server.d.ts +28 -86
  111. package/srv/server.js +127 -135
  112. package/srv/utils/agent-grants-config.d.ts +37 -0
  113. package/srv/utils/agent-grants-config.js +138 -0
  114. package/srv/utils/agent-grants.d.ts +262 -0
  115. package/srv/utils/agent-grants.js +922 -0
  116. package/srv/utils/agent-token-auth.d.ts +16 -0
  117. package/srv/utils/agent-token-auth.js +78 -0
  118. package/srv/utils/backend-request-handler.d.ts +2 -16
  119. package/srv/utils/backend-request-handler.js +3 -18
  120. package/srv/utils/collections.d.ts +4 -8
  121. package/srv/utils/collections.js +4 -8
  122. package/srv/utils/const.d.ts +30 -67
  123. package/srv/utils/const.js +32 -72
  124. package/srv/utils/crypto.d.ts +3 -12
  125. package/srv/utils/crypto.js +5 -18
  126. package/srv/utils/db-indexes.d.ts +25 -0
  127. package/srv/utils/db-indexes.js +94 -0
  128. package/srv/utils/db-sanitize.d.ts +27 -0
  129. package/srv/utils/db-sanitize.js +85 -0
  130. package/srv/utils/epoch-slots.d.ts +13 -0
  131. package/srv/utils/epoch-slots.js +25 -0
  132. package/srv/utils/error-codes.d.ts +20 -73
  133. package/srv/utils/error-codes.js +19 -70
  134. package/srv/utils/errors.d.ts +50 -177
  135. package/srv/utils/errors.js +94 -218
  136. package/srv/utils/liveness.d.ts +16 -0
  137. package/srv/utils/liveness.js +40 -0
  138. package/srv/utils/mappers.d.ts +128 -214
  139. package/srv/utils/mappers.js +354 -299
  140. package/srv/utils/network-context.js +2 -11
  141. package/srv/utils/pg-inline-json.d.ts +8 -0
  142. package/srv/utils/pg-inline-json.js +62 -0
  143. package/srv/utils/pg-order-nulls.d.ts +14 -0
  144. package/srv/utils/pg-order-nulls.js +56 -0
  145. package/srv/utils/plutus-placeholders.d.ts +23 -16
  146. package/srv/utils/plutus-placeholders.js +63 -27
  147. package/srv/utils/rate-limiter.d.ts +46 -0
  148. package/srv/utils/rate-limiter.js +116 -0
  149. package/srv/utils/service-events.d.ts +2 -22
  150. package/srv/utils/service-events.js +3 -23
  151. package/srv/utils/signing-helper.d.ts +3 -18
  152. package/srv/utils/signing-helper.js +10 -32
  153. package/srv/utils/tx-build-helper.d.ts +26 -92
  154. package/srv/utils/tx-build-helper.js +68 -123
  155. package/srv/utils/tx-request-parsers.d.ts +107 -21
  156. package/srv/utils/tx-request-parsers.js +433 -34
  157. package/srv/utils/tx-utils.d.ts +4 -23
  158. package/srv/utils/tx-utils.js +12 -41
  159. package/srv/utils/types.d.ts +238 -169
  160. package/srv/utils/types.js +2 -6
  161. package/srv/utils/validators.d.ts +24 -90
  162. package/srv/utils/validators.js +50 -147
@@ -0,0 +1,432 @@
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.buildLedgerUtxoRows = buildLedgerUtxoRows;
7
+ exports.readLedgerOutputs = readLedgerOutputs;
8
+ exports.ledgerRowAmount = ledgerRowAmount;
9
+ exports.applyBlockToLedger = applyBlockToLedger;
10
+ exports.undoLedgerForTransactions = undoLedgerForTransactions;
11
+ exports.recountLedgerAddresses = recountLedgerAddresses;
12
+ exports.recountLedgerAccounts = recountLedgerAccounts;
13
+ exports.backfillPaymentCredentials = backfillPaymentCredentials;
14
+ const cds_1 = __importDefault(require("@sap/cds"));
15
+ const cardano_1 = require("#cds-models/odatano/cardano");
16
+ const mappers_1 = require("../utils/mappers");
17
+ const collections_1 = require("../utils/collections");
18
+ const { SELECT, UPSERT, UPDATE, DELETE } = cds_1.default.ql;
19
+ const logger = cds_1.default.log('LedgerState');
20
+ const outpoint = (txHash, outputIndex) => `${txHash}#${outputIndex}`;
21
+ const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
22
+ const nativeAssets = (amount) => (amount ?? []).filter(a => a.unit !== 'lovelace' && a.quantity !== '0');
23
+ const big = (v) => (v == null || v === '' ? 0n : BigInt(String(v)));
24
+ const num = (v) => Number(v ?? 0);
25
+ function decodeAssetName(hex) {
26
+ if (!hex)
27
+ return null;
28
+ try {
29
+ const text = Buffer.from(hex, 'hex').toString('utf8');
30
+ // printable only — a binary asset name has no useful decoded form
31
+ return /^[\x20-\x7e]*$/.test(text) ? text : null;
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ /** Build the `LedgerUTxOs` row (+ asset rows) for one output. */
38
+ function buildLedgerUtxoRows(o, createdSlot) {
39
+ const decoded = (0, mappers_1.decodeShelleyAddress)(o.address);
40
+ const assets = nativeAssets(o.amount).map((a) => ({
41
+ utxo_txHash: o.txHash,
42
+ utxo_outputIndex: o.outputIndex,
43
+ unit: a.unit,
44
+ asset_quantity: String(a.quantity),
45
+ asset_policyId: a.unit.length >= 56 ? a.unit.slice(0, 56) : null,
46
+ asset_assetNameHex: a.unit.length > 56 ? a.unit.slice(56) : '',
47
+ asset_assetName: a.unit.length > 56 ? decodeAssetName(a.unit.slice(56)) : null,
48
+ }));
49
+ return {
50
+ row: {
51
+ txHash: o.txHash,
52
+ outputIndex: o.outputIndex,
53
+ address: o.address,
54
+ stakeAddress: decoded.stakeAddress,
55
+ addressType: decoded.type,
56
+ isScript: decoded.isScript,
57
+ lovelace: lovelaceOf(o.amount).toString(),
58
+ createdSlot,
59
+ spentTxHash: null,
60
+ spentSlot: null,
61
+ utxo_dataHash: o.dataHash || null,
62
+ utxo_inlineDatum: o.inlineDatum || null,
63
+ utxo_referenceScriptHash: o.referenceScriptHash || null,
64
+ hasAssets: assets.length > 0,
65
+ },
66
+ assets,
67
+ };
68
+ }
69
+ /** Outputs the ledger actually produced: collateral return on a phase-2 failure, else the regular ones. */
70
+ function producedOutputs(t) {
71
+ return (t.outputs ?? []).filter(o => (t.spendsCollaterals ? o.isCollateral : !o.isCollateral));
72
+ }
73
+ /** Inputs the ledger actually consumed: collateral on a phase-2 failure, else the regular (non-reference) ones. */
74
+ function consumedInputs(t) {
75
+ return (t.inputs ?? [])
76
+ .filter(i => (t.spendsCollaterals ? i.isCollateral : !i.isReference && !i.isCollateral))
77
+ .map(i => ({ txHash: i.txHash, outputIndex: i.outputIndex }));
78
+ }
79
+ function deltaFor(map, row) {
80
+ let d = map.get(row.address);
81
+ if (!d) {
82
+ d = { lovelace: 0n, utxos: 0, assets: new Map(), stakeAddress: row.stakeAddress, addressType: row.addressType, isScript: row.isScript };
83
+ map.set(row.address, d);
84
+ }
85
+ return d;
86
+ }
87
+ function applyDelta(d, row, assets, sign) {
88
+ d.lovelace += sign * BigInt(row.lovelace);
89
+ d.utxos += Number(sign);
90
+ for (const a of assets ?? []) {
91
+ const unit = 'unit' in a ? a.unit : '';
92
+ const qty = 'asset_quantity' in a ? a.asset_quantity : a.quantity;
93
+ if (!unit)
94
+ continue;
95
+ d.assets.set(unit, (d.assets.get(unit) ?? 0n) + sign * BigInt(qty));
96
+ }
97
+ }
98
+ /**
99
+ * Read the ledger rows of the given source transactions. Asset rows are read only for
100
+ * transactions with at least one row carrying assets, so an ada-only block costs one SELECT.
101
+ */
102
+ async function readLedgerOutputs(tx, txHashes, into) {
103
+ const lookup = into ?? { hashes: new Set(), rows: new Map(), assets: new Map() };
104
+ const todo = [...new Set(txHashes)].filter(h => !lookup.hashes.has(h));
105
+ for (const hashChunk of (0, collections_1.chunk)(todo, collections_1.IN_CHUNK)) {
106
+ const rows = await tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ txHash: { in: hashChunk } }));
107
+ for (const r of rows ?? [])
108
+ lookup.rows.set(outpoint(r.txHash, num(r.outputIndex)), r);
109
+ const withAssets = [...new Set((rows ?? []).filter(r => r.hasAssets).map(r => r.txHash))];
110
+ if (withAssets.length) {
111
+ const assets = await tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: withAssets } }));
112
+ for (const a of assets ?? []) {
113
+ const k = outpoint(a.utxo_txHash, num(a.utxo_outputIndex));
114
+ const list = lookup.assets.get(k) ?? [];
115
+ list.push(a);
116
+ lookup.assets.set(k, list);
117
+ }
118
+ }
119
+ for (const h of hashChunk)
120
+ lookup.hashes.add(h);
121
+ }
122
+ return lookup;
123
+ }
124
+ /** Amount list (lovelace + native assets) of a ledger row, the shape a resolved input carries. */
125
+ function ledgerRowAmount(row, assets) {
126
+ return [
127
+ { unit: 'lovelace', quantity: String(row.lovelace ?? '0') },
128
+ ...(assets ?? []).map(a => ({ unit: a.unit, quantity: String(a.asset_quantity) })),
129
+ ];
130
+ }
131
+ /**
132
+ * Apply one block to the ledger tables. Caller guarantees `block.slot > anchor.slot`.
133
+ * `lookup` may carry rows the caller already read for this block (input resolution).
134
+ * Never throws for a missing outpoint (it is counted and logged); DB errors propagate so the
135
+ * block transaction rolls back as a whole.
136
+ */
137
+ async function applyBlockToLedger(tx, block, txs, lookup) {
138
+ const slot = block.slot ?? 0;
139
+ // 1) everything this block produces
140
+ const created = new Map();
141
+ for (const t of txs) {
142
+ for (const o of producedOutputs(t)) {
143
+ const built = buildLedgerUtxoRows({ ...o, txHash: t.hash }, slot);
144
+ created.set(outpoint(t.hash, o.outputIndex), built);
145
+ }
146
+ }
147
+ // 2) everything this block consumes — same-block outputs first, the rest from the DB
148
+ const lookups = [];
149
+ const spentInBlock = new Set();
150
+ for (const t of txs) {
151
+ for (const i of consumedInputs(t)) {
152
+ const key = outpoint(i.txHash, i.outputIndex);
153
+ const own = created.get(key);
154
+ if (own) {
155
+ own.row.spentTxHash = t.hash;
156
+ own.row.spentSlot = slot;
157
+ spentInBlock.add(key);
158
+ }
159
+ else {
160
+ lookups.push({ key, txHash: i.txHash, outputIndex: i.outputIndex, spender: t.hash });
161
+ }
162
+ }
163
+ }
164
+ const { rows: dbRows, assets: dbAssets } = await readLedgerOutputs(tx, lookups.map(l => l.txHash), lookup);
165
+ const spentRows = [];
166
+ let missing = 0;
167
+ for (const l of lookups) {
168
+ const row = dbRows.get(l.key);
169
+ if (!row || row.spentTxHash) {
170
+ missing++;
171
+ if (missing <= 3) {
172
+ logger.warn(`ledger: ${l.spender} consumes ${l.key} which has no open row (${row ? 'already spent' : 'unknown'}) — snapshot gap?`);
173
+ }
174
+ continue;
175
+ }
176
+ spentRows.push({
177
+ ...row,
178
+ outputIndex: num(row.outputIndex),
179
+ lovelace: String(row.lovelace),
180
+ createdSlot: row.createdSlot == null ? null : num(row.createdSlot),
181
+ isScript: Boolean(row.isScript),
182
+ hasAssets: Boolean(row.hasAssets),
183
+ spentTxHash: l.spender,
184
+ spentSlot: slot,
185
+ });
186
+ }
187
+ // 3) per-address deltas
188
+ const deltas = new Map();
189
+ for (const [key, { row, assets }] of created) {
190
+ const d = deltaFor(deltas, row);
191
+ applyDelta(d, row, assets, 1n);
192
+ if (spentInBlock.has(key))
193
+ applyDelta(d, row, assets, -1n);
194
+ }
195
+ for (const row of spentRows) {
196
+ applyDelta(deltaFor(deltas, row), row, dbAssets.get(outpoint(row.txHash, row.outputIndex)), -1n);
197
+ }
198
+ // 4) UTxO rows
199
+ const createdRows = [...created.values()];
200
+ for (const rows of (0, collections_1.chunk)(createdRows.map(c => c.row), collections_1.IN_CHUNK)) {
201
+ await tx.run(UPSERT.into(cardano_1.LedgerUTxOs).entries(rows));
202
+ }
203
+ for (const rows of (0, collections_1.chunk)(createdRows.flatMap(c => c.assets), collections_1.IN_CHUNK)) {
204
+ await tx.run(UPSERT.into(cardano_1.LedgerUTxOAssets).entries(rows));
205
+ }
206
+ for (const rows of (0, collections_1.chunk)(spentRows, collections_1.IN_CHUNK)) {
207
+ await tx.run(UPSERT.into(cardano_1.LedgerUTxOs).entries(rows));
208
+ }
209
+ // 5) addresses, address assets, accounts
210
+ const touched = [...deltas.keys()];
211
+ const stakeDeltas = new Map();
212
+ for (const addrChunk of (0, collections_1.chunk)(touched, collections_1.IN_CHUNK)) {
213
+ const [existing, existingAssets] = await Promise.all([
214
+ tx.run(SELECT.from(cardano_1.LedgerAddresses).where({ address: { in: addrChunk } })),
215
+ tx.run(SELECT.from(cardano_1.LedgerAddressAssets).where({ address_address: { in: addrChunk } })),
216
+ ]);
217
+ const byAddress = new Map((existing ?? []).map(e => [String(e.address), e]));
218
+ const assetQty = new Map();
219
+ for (const a of existingAssets ?? [])
220
+ assetQty.set(`${a.address_address}|${a.unit}`, big(a.asset_quantity));
221
+ const addressRows = [];
222
+ const assetRows = [];
223
+ const assetDeletes = [];
224
+ for (const address of addrChunk) {
225
+ const d = deltas.get(address);
226
+ const prev = byAddress.get(address);
227
+ const total = big(prev?.totalLovelace) + d.lovelace;
228
+ const count = num(prev?.utxoCount) + d.utxos;
229
+ addressRows.push({
230
+ address,
231
+ stakeAddress: prev?.stakeAddress ?? d.stakeAddress,
232
+ paymentCredential: (0, mappers_1.decodeShelleyAddress)(address).paymentCredential,
233
+ addressType: prev?.addressType ?? d.addressType,
234
+ isScript: prev ? Boolean(prev.isScript) : d.isScript,
235
+ totalLovelace: total.toString(),
236
+ utxoCount: count,
237
+ // null stays null: an address that came with the snapshot has no known first slot
238
+ firstSeenSlot: prev ? (prev.firstSeenSlot == null ? null : num(prev.firstSeenSlot)) : slot,
239
+ lastActiveSlot: slot,
240
+ });
241
+ for (const [unit, delta] of d.assets) {
242
+ if (delta === 0n)
243
+ continue;
244
+ const k = `${address}|${unit}`;
245
+ const next = (assetQty.get(k) ?? 0n) + delta;
246
+ if (next === 0n) {
247
+ if (assetQty.has(k))
248
+ assetDeletes.push({ address_address: address, unit });
249
+ }
250
+ else {
251
+ assetRows.push({
252
+ address_address: address,
253
+ unit,
254
+ asset_quantity: next.toString(),
255
+ asset_policyId: unit.length >= 56 ? unit.slice(0, 56) : null,
256
+ asset_assetNameHex: unit.length > 56 ? unit.slice(56) : '',
257
+ asset_assetName: unit.length > 56 ? decodeAssetName(unit.slice(56)) : null,
258
+ });
259
+ }
260
+ }
261
+ const stake = prev?.stakeAddress ?? d.stakeAddress;
262
+ if (stake) {
263
+ const s = stakeDeltas.get(stake) ?? { lovelace: 0n, utxos: 0, newAddresses: 0 };
264
+ s.lovelace += d.lovelace;
265
+ s.utxos += d.utxos;
266
+ if (!prev)
267
+ s.newAddresses++;
268
+ stakeDeltas.set(stake, s);
269
+ }
270
+ }
271
+ for (const rows of (0, collections_1.chunk)(addressRows, collections_1.IN_CHUNK))
272
+ await tx.run(UPSERT.into(cardano_1.LedgerAddresses).entries(rows));
273
+ for (const rows of (0, collections_1.chunk)(assetRows, collections_1.IN_CHUNK))
274
+ await tx.run(UPSERT.into(cardano_1.LedgerAddressAssets).entries(rows));
275
+ for (const del of assetDeletes)
276
+ await tx.run(DELETE.from(cardano_1.LedgerAddressAssets).where(del));
277
+ }
278
+ const stakes = [...stakeDeltas.keys()];
279
+ for (const stakeChunk of (0, collections_1.chunk)(stakes, collections_1.IN_CHUNK)) {
280
+ const existing = await tx.run(SELECT.from(cardano_1.LedgerAccounts).where({ stakeAddress: { in: stakeChunk } }));
281
+ const byStake = new Map((existing ?? []).map(e => [String(e.stakeAddress), e]));
282
+ const rows = stakeChunk.map((stakeAddress) => {
283
+ const d = stakeDeltas.get(stakeAddress);
284
+ const prev = byStake.get(stakeAddress);
285
+ return {
286
+ stakeAddress,
287
+ controlledAmount: (big(prev?.controlledAmount) + d.lovelace).toString(),
288
+ addressCount: num(prev?.addressCount) + d.newAddresses,
289
+ utxoCount: num(prev?.utxoCount) + d.utxos,
290
+ lastActiveSlot: slot,
291
+ };
292
+ });
293
+ await tx.run(UPSERT.into(cardano_1.LedgerAccounts).entries(rows));
294
+ }
295
+ return { created: created.size, spent: spentInBlock.size + spentRows.length, missing, addresses: touched.length };
296
+ }
297
+ /**
298
+ * Reorg undo for a set of rolled-back transactions: drop what they created, reopen what
299
+ * they spent, then recount every address either side touched from the open rows.
300
+ * @returns the recounted addresses
301
+ */
302
+ async function undoLedgerForTransactions(tx, txHashes) {
303
+ if (!txHashes.length)
304
+ return [];
305
+ const touched = new Set();
306
+ for (const hashChunk of (0, collections_1.chunk)(txHashes, collections_1.IN_CHUNK)) {
307
+ const [createdRows, spentRows] = await Promise.all([
308
+ tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('address').where({ txHash: { in: hashChunk } })),
309
+ tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('address').where({ spentTxHash: { in: hashChunk } })),
310
+ ]);
311
+ for (const r of [...(createdRows ?? []), ...(spentRows ?? [])])
312
+ touched.add(r.address);
313
+ await tx.run(DELETE.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: hashChunk } }));
314
+ await tx.run(DELETE.from(cardano_1.LedgerUTxOs).where({ txHash: { in: hashChunk } }));
315
+ await tx.run(UPDATE.entity(cardano_1.LedgerUTxOs).set({ spentTxHash: null, spentSlot: null }).where({ spentTxHash: { in: hashChunk } }));
316
+ }
317
+ const addresses = [...touched];
318
+ await recountLedgerAddresses(tx, addresses);
319
+ return addresses;
320
+ }
321
+ /**
322
+ * Recount running sums for the given addresses from their open UTxO rows, then the
323
+ * stake keys those addresses belong to. Also the repair path for a drifted sum.
324
+ */
325
+ async function recountLedgerAddresses(tx, addresses) {
326
+ const stakes = new Set();
327
+ for (const address of addresses) {
328
+ const open = await tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('txHash', 'outputIndex', 'lovelace', 'hasAssets', 'stakeAddress')
329
+ .where({ address, spentTxHash: null }));
330
+ const openKeys = new Set((open ?? []).map(r => outpoint(r.txHash, num(r.outputIndex))));
331
+ let total = 0n;
332
+ for (const r of open ?? [])
333
+ total += big(r.lovelace);
334
+ const assetSums = new Map();
335
+ const withAssets = [...new Set((open ?? []).filter(r => Boolean(r.hasAssets)).map(r => r.txHash))];
336
+ for (const hashChunk of (0, collections_1.chunk)(withAssets, collections_1.IN_CHUNK)) {
337
+ const rows = await tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: hashChunk } }));
338
+ for (const a of rows ?? []) {
339
+ if (!openKeys.has(outpoint(a.utxo_txHash, num(a.utxo_outputIndex))))
340
+ continue;
341
+ assetSums.set(a.unit, (assetSums.get(a.unit) ?? 0n) + big(a.asset_quantity));
342
+ }
343
+ }
344
+ const prev = await tx.run(SELECT.one.from(cardano_1.LedgerAddresses).where({ address }));
345
+ const decoded = (0, mappers_1.decodeShelleyAddress)(address);
346
+ const stakeAddress = prev?.stakeAddress ?? open?.[0]?.stakeAddress ?? decoded.stakeAddress;
347
+ await tx.run(UPSERT.into(cardano_1.LedgerAddresses).entries({
348
+ address,
349
+ stakeAddress,
350
+ paymentCredential: decoded.paymentCredential,
351
+ addressType: prev?.addressType ?? decoded.type,
352
+ isScript: prev ? Boolean(prev.isScript) : decoded.isScript,
353
+ totalLovelace: total.toString(),
354
+ utxoCount: (open ?? []).length,
355
+ firstSeenSlot: prev?.firstSeenSlot == null ? null : num(prev.firstSeenSlot),
356
+ lastActiveSlot: prev?.lastActiveSlot == null ? null : num(prev.lastActiveSlot),
357
+ }));
358
+ await tx.run(DELETE.from(cardano_1.LedgerAddressAssets).where({ address_address: address }));
359
+ const assetRows = [...assetSums].filter(([, q]) => q !== 0n).map(([unit, q]) => ({
360
+ address_address: address,
361
+ unit,
362
+ asset_quantity: q.toString(),
363
+ asset_policyId: unit.length >= 56 ? unit.slice(0, 56) : null,
364
+ asset_assetNameHex: unit.length > 56 ? unit.slice(56) : '',
365
+ asset_assetName: unit.length > 56 ? decodeAssetName(unit.slice(56)) : null,
366
+ }));
367
+ for (const rows of (0, collections_1.chunk)(assetRows, collections_1.IN_CHUNK))
368
+ await tx.run(UPSERT.into(cardano_1.LedgerAddressAssets).entries(rows));
369
+ if (stakeAddress)
370
+ stakes.add(stakeAddress);
371
+ }
372
+ await recountLedgerAccounts(tx, [...stakes]);
373
+ }
374
+ /** Recount `LedgerAccounts` for the given stake keys from `LedgerAddresses`. */
375
+ async function recountLedgerAccounts(tx, stakeAddresses) {
376
+ for (const stakeChunk of (0, collections_1.chunk)(stakeAddresses, collections_1.IN_CHUNK)) {
377
+ const [addrRows, existing] = await Promise.all([
378
+ tx.run(SELECT.from(cardano_1.LedgerAddresses).columns('stakeAddress', 'totalLovelace', 'utxoCount')
379
+ .where({ stakeAddress: { in: stakeChunk } })),
380
+ tx.run(SELECT.from(cardano_1.LedgerAccounts).where({ stakeAddress: { in: stakeChunk } })),
381
+ ]);
382
+ const sums = new Map();
383
+ for (const r of addrRows ?? []) {
384
+ const k = String(r.stakeAddress);
385
+ const s = sums.get(k) ?? { lovelace: 0n, addresses: 0, utxos: 0 };
386
+ s.lovelace += big(r.totalLovelace);
387
+ s.addresses += 1;
388
+ s.utxos += num(r.utxoCount);
389
+ sums.set(k, s);
390
+ }
391
+ const byStake = new Map((existing ?? []).map(e => [String(e.stakeAddress), e]));
392
+ const rows = stakeChunk.map((stakeAddress) => {
393
+ const s = sums.get(stakeAddress) ?? { lovelace: 0n, addresses: 0, utxos: 0 };
394
+ const prev = byStake.get(stakeAddress);
395
+ return {
396
+ stakeAddress,
397
+ controlledAmount: s.lovelace.toString(),
398
+ addressCount: s.addresses,
399
+ utxoCount: s.utxos,
400
+ lastActiveSlot: prev?.lastActiveSlot == null ? null : num(prev.lastActiveSlot),
401
+ };
402
+ });
403
+ await tx.run(UPSERT.into(cardano_1.LedgerAccounts).entries(rows));
404
+ }
405
+ }
406
+ /** Address types that carry a payment credential. */
407
+ const CREDENTIAL_ADDRESS_TYPES = ['base', 'pointer', 'enterprise'];
408
+ /**
409
+ * Fill `LedgerAddresses.paymentCredential` where it is missing (rows from the import's SQL
410
+ * aggregation, or written before the column existed). One transaction per chunk, idempotent.
411
+ * @returns rows updated
412
+ */
413
+ async function backfillPaymentCredentials(chunkSize = 1000) {
414
+ let updated = 0;
415
+ for (;;) {
416
+ const n = await cds_1.default.tx(async (tx) => {
417
+ const rows = await tx.run(SELECT.from(cardano_1.LedgerAddresses).columns('address')
418
+ .where({ paymentCredential: null, addressType: { in: CREDENTIAL_ADDRESS_TYPES } })
419
+ .limit(chunkSize));
420
+ for (const { address } of rows ?? []) {
421
+ // '' marks an address that decodes without a credential, so it is not picked again
422
+ const credential = (0, mappers_1.decodeShelleyAddress)(address).paymentCredential ?? '';
423
+ await tx.run(UPDATE.entity(cardano_1.LedgerAddresses).set({ paymentCredential: credential }).where({ address }));
424
+ }
425
+ return (rows ?? []).length;
426
+ });
427
+ updated += n;
428
+ if (n < chunkSize)
429
+ return updated;
430
+ }
431
+ }
432
+ //# sourceMappingURL=ledger-state.js.map
@@ -0,0 +1,28 @@
1
+ import type { UTxO } from '../utils/types';
2
+ /** How long a submitted transaction counts as pending when no crawled block confirms it earlier. */
3
+ export declare const PENDING_TX_TTL_MS: number;
4
+ /**
5
+ * Transactions this process submitted that the ledger view does not show yet. The node's ledger
6
+ * state and the crawled UTxO set both still list their inputs as unspent while they wait in the
7
+ * mempool, so a second build would spend the same outputs. Builders skip those inputs and may
8
+ * spend the pending outputs (change) instead. Process-local; an entry ends when a crawled block
9
+ * holds the transaction or after PENDING_TX_TTL_MS.
10
+ */
11
+ export declare class PendingSpends {
12
+ private readonly now;
13
+ private readonly txs;
14
+ constructor(now?: () => number);
15
+ /** Remember a submitted transaction; unparseable CBOR is ignored (the submit already succeeded). */
16
+ record(signedTxCbor: string): void;
17
+ /** The pending transaction that spends this output, if any. */
18
+ spentBy(txHash: string, outputIndex: number): string | undefined;
19
+ /**
20
+ * The UTxOs of an address as they are after the pending transactions: inputs they spend are
21
+ * removed, their outputs to the address are added. A pending transaction whose outputs already
22
+ * appear in `utxos` has been crawled and is forgotten.
23
+ */
24
+ apply(address: string, utxos: UTxO[]): UTxO[];
25
+ get size(): number;
26
+ private prune;
27
+ }
28
+ //# sourceMappingURL=pending-spends.d.ts.map
@@ -0,0 +1,89 @@
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.PendingSpends = exports.PENDING_TX_TTL_MS = void 0;
7
+ const cds_1 = __importDefault(require("@sap/cds"));
8
+ const parse_1 = require("../cbor/parse");
9
+ const logger = cds_1.default.log('PendingSpends');
10
+ /** How long a submitted transaction counts as pending when no crawled block confirms it earlier. */
11
+ exports.PENDING_TX_TTL_MS = 10 * 60_000;
12
+ const refKey = (txHash, outputIndex) => `${txHash.toLowerCase()}#${outputIndex}`;
13
+ /**
14
+ * Transactions this process submitted that the ledger view does not show yet. The node's ledger
15
+ * state and the crawled UTxO set both still list their inputs as unspent while they wait in the
16
+ * mempool, so a second build would spend the same outputs. Builders skip those inputs and may
17
+ * spend the pending outputs (change) instead. Process-local; an entry ends when a crawled block
18
+ * holds the transaction or after PENDING_TX_TTL_MS.
19
+ */
20
+ class PendingSpends {
21
+ now;
22
+ txs = new Map();
23
+ constructor(now = Date.now) {
24
+ this.now = now;
25
+ }
26
+ /** Remember a submitted transaction; unparseable CBOR is ignored (the submit already succeeded). */
27
+ record(signedTxCbor) {
28
+ try {
29
+ const parsed = (0, parse_1.parseTransaction)(signedTxCbor);
30
+ this.txs.set(parsed.txHash, {
31
+ inputs: parsed.inputs.map((i) => refKey(i.txHash, i.outputIndex)),
32
+ outputs: parsed.outputs.map((o, outputIndex) => ({
33
+ txHash: parsed.txHash,
34
+ outputIndex,
35
+ address: o.address,
36
+ amount: [{ unit: 'lovelace', quantity: o.lovelace }, ...o.assets],
37
+ datumHash: o.datumHash,
38
+ inlineDatum: o.inlineDatumHex,
39
+ scriptRefCbor: o.referenceScriptHex,
40
+ })),
41
+ expiresAt: this.now() + exports.PENDING_TX_TTL_MS,
42
+ });
43
+ }
44
+ catch (err) {
45
+ logger.warn(`submitted transaction not tracked as pending: ${err instanceof Error ? err.message : String(err)}`);
46
+ }
47
+ }
48
+ /** The pending transaction that spends this output, if any. */
49
+ spentBy(txHash, outputIndex) {
50
+ this.prune();
51
+ const key = refKey(txHash, outputIndex);
52
+ for (const [hash, tx] of this.txs)
53
+ if (tx.inputs.includes(key))
54
+ return hash;
55
+ return undefined;
56
+ }
57
+ /**
58
+ * The UTxOs of an address as they are after the pending transactions: inputs they spend are
59
+ * removed, their outputs to the address are added. A pending transaction whose outputs already
60
+ * appear in `utxos` has been crawled and is forgotten.
61
+ */
62
+ apply(address, utxos) {
63
+ this.prune();
64
+ if (this.txs.size === 0)
65
+ return utxos;
66
+ const listed = new Set(utxos.map((u) => u.txHash.toLowerCase()));
67
+ for (const hash of [...this.txs.keys()])
68
+ if (listed.has(hash))
69
+ this.txs.delete(hash);
70
+ const spent = new Set([...this.txs.values()].flatMap((t) => t.inputs));
71
+ const keep = utxos.filter((u) => !spent.has(refKey(u.txHash, u.outputIndex)));
72
+ const pendingOut = [...this.txs.values()]
73
+ .flatMap((t) => t.outputs)
74
+ .filter((o) => o.address === address && !spent.has(refKey(o.txHash, o.outputIndex)));
75
+ return [...keep, ...pendingOut];
76
+ }
77
+ get size() {
78
+ this.prune();
79
+ return this.txs.size;
80
+ }
81
+ prune() {
82
+ const now = this.now();
83
+ for (const [hash, tx] of this.txs)
84
+ if (tx.expiresAt <= now)
85
+ this.txs.delete(hash);
86
+ }
87
+ }
88
+ exports.PendingSpends = PendingSpends;
89
+ //# sourceMappingURL=pending-spends.js.map
@@ -1,7 +1,6 @@
1
1
  /**
2
- * Input to {@link verifyDataSignature}. Mirrors the CIP-30 `signData` result:
3
- * `coseSignature` is the hex `signature` field (COSE_Sign1), `coseKey` is the
4
- * hex `key` field (COSE_Key).
2
+ * Input to {@link verifyDataSignature}, mirroring the CIP-30 `signData` result:
3
+ * `coseSignature` = hex `signature` field (COSE_Sign1), `coseKey` = hex `key` field (COSE_Key).
5
4
  */
6
5
  export interface CoseVerifyInput {
7
6
  address: string;
@@ -20,15 +19,9 @@ export interface CoseVerifyResult {
20
19
  signerVkh: string;
21
20
  }
22
21
  /**
23
- * Verify a CIP-30 `signData` (COSE_Sign1) message signature against a bech32
24
- * address. Stateless crypto only & no nonce/replay/session handling.
25
- * Never throws: all failures are returned as `{ valid: false, reason }`.
26
- *
27
- * Checks, in order:
28
- * 1. COSE_Sign1 + COSE_Key parse
29
- * 2. signer key hash (blake2b-224) == the address payment credential (key, not script)
30
- * 3. (optional) signed payload == expectedPayload
31
- * 4. Ed25519 signature over the COSE Sig_structure
22
+ * Verify a CIP-30 `signData` (COSE_Sign1) signature against a bech32 address: signer key hash
23
+ * (blake2b-224) must equal the address payment key credential, optional payload check, then
24
+ * Ed25519 over the Sig_structure. Stateless, no nonce/replay handling; never throws (`{ valid: false, reason }`).
32
25
  */
33
26
  export declare function verifyDataSignature(input: CoseVerifyInput): CoseVerifyResult;
34
27
  //# sourceMappingURL=cose-verifier.d.ts.map
@@ -71,15 +71,9 @@ function buildSigStructure(protectedBytes, payload) {
71
71
  return cbor_1.Cbor.encode(sigStruct);
72
72
  }
73
73
  /**
74
- * Verify a CIP-30 `signData` (COSE_Sign1) message signature against a bech32
75
- * address. Stateless crypto only & no nonce/replay/session handling.
76
- * Never throws: all failures are returned as `{ valid: false, reason }`.
77
- *
78
- * Checks, in order:
79
- * 1. COSE_Sign1 + COSE_Key parse
80
- * 2. signer key hash (blake2b-224) == the address payment credential (key, not script)
81
- * 3. (optional) signed payload == expectedPayload
82
- * 4. Ed25519 signature over the COSE Sig_structure
74
+ * Verify a CIP-30 `signData` (COSE_Sign1) signature against a bech32 address: signer key hash
75
+ * (blake2b-224) must equal the address payment key credential, optional payload check, then
76
+ * Ed25519 over the Sig_structure. Stateless, no nonce/replay handling; never throws (`{ valid: false, reason }`).
83
77
  */
84
78
  function verifyDataSignature(input) {
85
79
  const result = { valid: false, reason: '', signedPayload: '', signerVkh: '' };
@@ -88,7 +82,7 @@ function verifyDataSignature(input) {
88
82
  const pubKey = parseCoseKey(input.coseKey);
89
83
  result.signedPayload = Buffer.from(payload).toString('utf8');
90
84
  result.signerVkh = (0, uint8array_utils_1.toHex)((0, crypto_1.blake2b_224)(pubKey));
91
- // 2. signer key hash must equal the address payment credential (key hash, not script)
85
+ // signer key hash must equal the address payment credential (key hash, not script)
92
86
  const cred = (0, validators_1.extractPaymentCredential)(input.address);
93
87
  if (!cred) {
94
88
  result.reason = 'Address could not be decoded or has no payment credential (base/enterprise key-hash address required)';
@@ -102,14 +96,14 @@ function verifyDataSignature(input) {
102
96
  result.reason = `Signer key hash ${result.signerVkh} does not match address payment credential ${cred.hash}`;
103
97
  return result;
104
98
  }
105
- // 3. optional anti-replay payload check
99
+ // optional anti-replay payload check
106
100
  if (input.expectedPayload !== undefined && input.expectedPayload !== null) {
107
101
  if (result.signedPayload !== input.expectedPayload) {
108
102
  result.reason = 'Signed payload does not match the expected payload';
109
103
  return result;
110
104
  }
111
105
  }
112
- // 4. Ed25519 signature over the rebuilt Sig_structure
106
+ // Ed25519 signature over the rebuilt Sig_structure
113
107
  const sigStructure = buildSigStructure(protectedBytes, payload);
114
108
  if (!(0, crypto_1.verifyEd25519Signature_sync)(signature, sigStructure, pubKey)) {
115
109
  result.reason = 'Ed25519 signature does not verify against the signed message';