@odatano/core 2.0.0-rc.5 → 2.0.0-rc.51
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.
- package/@cds-models/CardanoAgentService/index.d.ts +99 -51
- package/@cds-models/CardanoAgentService/index.js +15 -0
- package/@cds-models/CardanoBackendService/index.d.ts +358 -0
- package/@cds-models/CardanoBackendService/index.js +41 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
- package/@cds-models/CardanoIndexerService/index.js +74 -0
- package/@cds-models/CardanoODataService/index.d.ts +417 -57
- package/@cds-models/CardanoODataService/index.js +42 -0
- package/@cds-models/CardanoSignService/index.d.ts +45 -19
- package/@cds-models/CardanoSignService/index.js +4 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
- package/@cds-models/CardanoTransactionService/index.js +5 -0
- package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
- package/@cds-models/CardanoWorkerService/index.js +2 -0
- package/@cds-models/index.d.ts +114 -4
- package/@cds-models/index.js +20 -4
- package/@cds-models/odatano/cardano/index.d.ts +451 -32
- package/@cds-models/odatano/cardano/index.js +48 -0
- package/README.md +103 -167
- package/db/schema.cds +2455 -1705
- package/db/types.cds +456 -295
- package/package.json +41 -53
- package/scripts/deploy-schema.mjs +113 -0
- package/scripts/migrate-schema.mjs +528 -0
- package/scripts/migrate-slot-leader.mjs +96 -0
- package/src/index.d.ts +20 -21
- package/src/index.js +45 -31
- package/src/plugin.js +17 -35
- package/srv/blockchain/asset-decimals.d.ts +7 -0
- package/srv/blockchain/asset-decimals.js +91 -0
- package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
- package/srv/blockchain/backends/blockfrost-backend.js +125 -215
- package/srv/blockchain/backends/call-signal.d.ts +7 -0
- package/srv/blockchain/backends/call-signal.js +22 -0
- package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
- package/srv/blockchain/backends/cardano-backend.js +29 -5
- package/srv/blockchain/backends/koios-backend.d.ts +108 -170
- package/srv/blockchain/backends/koios-backend.js +488 -482
- package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
- package/srv/blockchain/backends/odatano-backend.js +211 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
- package/srv/blockchain/backends/ogmios-backend.js +683 -327
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
- package/srv/blockchain/cardano-client.d.ts +71 -241
- package/srv/blockchain/cardano-client.js +354 -322
- package/srv/blockchain/cardano-indexer.d.ts +295 -283
- package/srv/blockchain/cardano-indexer.js +1690 -502
- package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
- package/srv/blockchain/cardano-tx-builder.js +164 -140
- package/srv/blockchain/circuit-breaker.d.ts +2 -13
- package/srv/blockchain/circuit-breaker.js +11 -15
- package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
- package/srv/blockchain/crawler/account-snapshots.js +173 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
- package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
- package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
- package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
- package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
- package/srv/blockchain/crawler/certificate-backfill.js +174 -0
- package/srv/blockchain/crawler/crawler.d.ts +125 -81
- package/srv/blockchain/crawler/crawler.js +738 -167
- package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
- package/srv/blockchain/crawler/credential-backfill.js +101 -0
- package/srv/blockchain/crawler/hooks.d.ts +2 -17
- package/srv/blockchain/crawler/index.d.ts +1 -8
- package/srv/blockchain/crawler/index.js +31 -17
- package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
- package/srv/blockchain/crawler/input-asset-copies.js +161 -0
- package/srv/blockchain/crawler/key-pages.d.ts +12 -0
- package/srv/blockchain/crawler/key-pages.js +48 -0
- package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
- package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
- package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
- package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
- package/srv/blockchain/crawler/sync-state.d.ts +31 -47
- package/srv/blockchain/crawler/sync-state.js +135 -128
- package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
- package/srv/blockchain/crawler/transaction-backfill.js +271 -0
- package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
- package/srv/blockchain/crawler/utxo-set-import.js +399 -0
- package/srv/blockchain/crawler/window-plan.d.ts +31 -0
- package/srv/blockchain/crawler/window-plan.js +59 -0
- package/srv/blockchain/ledger-state.d.ts +62 -0
- package/srv/blockchain/ledger-state.js +521 -0
- package/srv/blockchain/pending-spends.d.ts +16 -0
- package/srv/blockchain/pending-spends.js +81 -0
- package/srv/blockchain/pool-metadata.d.ts +15 -0
- package/srv/blockchain/pool-metadata.js +132 -0
- package/srv/blockchain/request-coalescer.d.ts +2 -16
- package/srv/blockchain/request-coalescer.js +2 -16
- package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
- package/srv/blockchain/signing/cose-verifier.js +146 -70
- package/srv/blockchain/signing/external-signer.d.ts +15 -115
- package/srv/blockchain/signing/external-signer.js +22 -131
- package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
- package/srv/blockchain/signing/failed-recheck.js +135 -0
- package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
- package/srv/blockchain/signing/hsm-signer.js +28 -79
- package/srv/blockchain/signing/landing-proof.d.ts +60 -0
- package/srv/blockchain/signing/landing-proof.js +224 -0
- package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
- package/srv/blockchain/signing/signature-verifier.js +71 -87
- package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
- package/srv/blockchain/signing/submission-finalizer.js +280 -86
- package/srv/blockchain/stored-chain.d.ts +19 -0
- package/srv/blockchain/stored-chain.js +258 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
- package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
- package/srv/blockchain/transaction-presence.d.ts +12 -0
- package/srv/blockchain/transaction-presence.js +29 -0
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +44 -0
- package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
- package/srv/blockchain/wallet-worker/build-request.js +40 -353
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
- package/srv/blockchain/wallet-worker/index.d.ts +1 -1
- package/srv/blockchain/wallet-worker/index.js +3 -11
- package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
- package/srv/blockchain/wallet-worker/invalidation.js +128 -0
- package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
- package/srv/blockchain/wallet-worker/job-store.js +200 -273
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
- package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
- package/srv/blockchain/wallet-worker/signers.js +4 -12
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
- package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
- package/srv/cardano-agent-service.cds +122 -84
- package/srv/cardano-agent-service.js +12 -9
- package/srv/cardano-backend-service.cds +81 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +259 -0
- package/srv/cardano-indexer-service.cds +393 -18
- package/srv/cardano-indexer-service.d.ts +5 -1
- package/srv/cardano-indexer-service.js +477 -16
- package/srv/cardano-service.cds +426 -269
- package/srv/cardano-service.js +640 -217
- package/srv/cardano-sign-service.cds +211 -180
- package/srv/cardano-sign-service.js +210 -287
- package/srv/cardano-tx-service.cds +462 -370
- package/srv/cardano-tx-service.js +283 -800
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.cds +141 -125
- package/srv/cardano-worker-service.js +104 -61
- package/srv/cbor/cip68.d.ts +13 -0
- package/srv/cbor/cip68.js +56 -0
- package/srv/cbor/index.d.ts +3 -1
- package/srv/cbor/index.js +9 -1
- package/srv/cbor/parse.d.ts +30 -18
- package/srv/cbor/parse.js +44 -9
- package/srv/cbor/plutus-data-json.d.ts +20 -0
- package/srv/cbor/plutus-data-json.js +32 -0
- package/srv/config.d.ts +117 -0
- package/srv/config.js +419 -0
- package/srv/server.d.ts +15 -110
- package/srv/server.js +83 -405
- package/srv/utils/agent-access.d.ts +11 -0
- package/srv/utils/agent-access.js +86 -0
- package/srv/utils/agent-grants-config.d.ts +0 -46
- package/srv/utils/agent-grants-config.js +17 -85
- package/srv/utils/agent-grants.d.ts +106 -122
- package/srv/utils/agent-grants.js +538 -237
- package/srv/utils/agent-token-auth.d.ts +4 -99
- package/srv/utils/agent-token-auth.js +62 -186
- package/srv/utils/backend-request-handler.d.ts +3 -17
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/build-request.d.ts +52 -0
- package/srv/utils/build-request.js +487 -0
- package/srv/utils/collections.d.ts +4 -10
- package/srv/utils/collections.js +14 -10
- package/srv/utils/const.d.ts +32 -75
- package/srv/utils/const.js +40 -80
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +11 -25
- package/srv/utils/db-indexes.d.ts +31 -0
- package/srv/utils/db-indexes.js +185 -0
- package/srv/utils/db-kind.d.ts +23 -0
- package/srv/utils/db-kind.js +42 -0
- package/srv/utils/db-sanitize.d.ts +20 -0
- package/srv/utils/db-sanitize.js +80 -0
- package/srv/utils/deep-json.d.ts +6 -0
- package/srv/utils/deep-json.js +240 -0
- package/srv/utils/detached-run.d.ts +41 -0
- package/srv/utils/detached-run.js +101 -0
- package/srv/utils/epoch-slots.d.ts +14 -0
- package/srv/utils/epoch-slots.js +45 -0
- package/srv/utils/error-codes.d.ts +26 -75
- package/srv/utils/error-codes.js +27 -72
- package/srv/utils/errors.d.ts +55 -187
- package/srv/utils/errors.js +161 -235
- package/srv/utils/lease.d.ts +20 -0
- package/srv/utils/lease.js +62 -0
- package/srv/utils/liveness.d.ts +12 -0
- package/srv/utils/liveness.js +35 -0
- package/srv/utils/mappers.d.ts +111 -223
- package/srv/utils/mappers.js +432 -371
- package/srv/utils/navigation.d.ts +17 -0
- package/srv/utils/navigation.js +52 -0
- package/srv/utils/network-context.d.ts +0 -1
- package/srv/utils/network-context.js +9 -15
- package/srv/utils/paging.d.ts +31 -0
- package/srv/utils/paging.js +43 -0
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +58 -0
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +54 -0
- package/srv/utils/plutus-placeholders.d.ts +16 -22
- package/srv/utils/plutus-placeholders.js +62 -33
- package/srv/utils/rate-limiter.d.ts +2 -21
- package/srv/utils/rate-limiter.js +5 -17
- package/srv/utils/readiness.d.ts +12 -0
- package/srv/utils/readiness.js +29 -0
- package/srv/utils/reference-script.d.ts +19 -0
- package/srv/utils/reference-script.js +84 -0
- package/srv/utils/resolution.d.ts +13 -0
- package/srv/utils/resolution.js +47 -0
- package/srv/utils/result-numbers.d.ts +15 -0
- package/srv/utils/result-numbers.js +61 -0
- package/srv/utils/row-values.d.ts +7 -0
- package/srv/utils/row-values.js +27 -0
- package/srv/utils/service-events.d.ts +0 -24
- package/srv/utils/service-events.js +3 -25
- package/srv/utils/signing-helper.d.ts +3 -20
- package/srv/utils/signing-helper.js +35 -64
- package/srv/utils/tx-build-helper.d.ts +25 -105
- package/srv/utils/tx-build-helper.js +108 -156
- package/srv/utils/tx-request-parsers.d.ts +82 -33
- package/srv/utils/tx-request-parsers.js +401 -49
- package/srv/utils/tx-utils.d.ts +3 -27
- package/srv/utils/tx-utils.js +32 -50
- package/srv/utils/types.d.ts +294 -232
- package/srv/utils/types.js +2 -22
- package/srv/utils/validators.d.ts +22 -92
- package/srv/utils/validators.js +60 -170
|
@@ -0,0 +1,521 @@
|
|
|
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
|
+
/** Build the `LedgerUTxOs` row (+ asset rows) for one output. */
|
|
26
|
+
function buildLedgerUtxoRows(o, createdSlot) {
|
|
27
|
+
const decoded = (0, mappers_1.decodeShelleyAddress)(o.address);
|
|
28
|
+
const assets = nativeAssets(o.amount).map((a) => ({
|
|
29
|
+
utxo_txHash: o.txHash,
|
|
30
|
+
utxo_outputIndex: o.outputIndex,
|
|
31
|
+
unit: a.unit,
|
|
32
|
+
...(0, mappers_1.assetSlice)(a.unit, a.quantity),
|
|
33
|
+
}));
|
|
34
|
+
return {
|
|
35
|
+
row: {
|
|
36
|
+
txHash: o.txHash,
|
|
37
|
+
outputIndex: o.outputIndex,
|
|
38
|
+
address: o.address,
|
|
39
|
+
stakeAddress: decoded.stakeAddress,
|
|
40
|
+
addressType: decoded.type,
|
|
41
|
+
isScript: decoded.isScript,
|
|
42
|
+
lovelace: lovelaceOf(o.amount).toString(),
|
|
43
|
+
createdSlot,
|
|
44
|
+
spentTxHash: null,
|
|
45
|
+
spentSlot: null,
|
|
46
|
+
utxo_dataHash: o.dataHash || null,
|
|
47
|
+
utxo_inlineDatum: o.inlineDatum || null,
|
|
48
|
+
utxo_referenceScriptHash: o.referenceScriptHash || null,
|
|
49
|
+
utxo_referenceScriptSize: o.referenceScriptSize ?? null,
|
|
50
|
+
utxo_referenceScriptType: o.referenceScriptType ?? null,
|
|
51
|
+
utxo_paymentCredential: decoded.paymentCredential,
|
|
52
|
+
hasAssets: assets.length > 0,
|
|
53
|
+
},
|
|
54
|
+
assets,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** Outputs the ledger actually produced: collateral return on a phase-2 failure, else the regular ones. */
|
|
58
|
+
function producedOutputs(t) {
|
|
59
|
+
return (t.outputs ?? []).filter(o => (t.spendsCollaterals ? o.isCollateral : !o.isCollateral));
|
|
60
|
+
}
|
|
61
|
+
/** Inputs the ledger actually consumed: collateral on a phase-2 failure, else the regular (non-reference) ones. */
|
|
62
|
+
function consumedInputs(t) {
|
|
63
|
+
return (t.inputs ?? [])
|
|
64
|
+
.filter(i => (t.spendsCollaterals ? i.isCollateral : !i.isReference && !i.isCollateral))
|
|
65
|
+
.map(i => ({ txHash: i.txHash, outputIndex: i.outputIndex }));
|
|
66
|
+
}
|
|
67
|
+
function deltaFor(map, row) {
|
|
68
|
+
let d = map.get(row.address);
|
|
69
|
+
if (!d) {
|
|
70
|
+
d = { lovelace: 0n, utxos: 0, assets: new Map(), stakeAddress: row.stakeAddress, addressType: row.addressType, isScript: row.isScript };
|
|
71
|
+
map.set(row.address, d);
|
|
72
|
+
}
|
|
73
|
+
return d;
|
|
74
|
+
}
|
|
75
|
+
function applyDelta(d, row, assets, sign) {
|
|
76
|
+
d.lovelace += sign * BigInt(row.lovelace);
|
|
77
|
+
d.utxos += Number(sign);
|
|
78
|
+
for (const a of assets ?? []) {
|
|
79
|
+
const unit = 'unit' in a ? a.unit : '';
|
|
80
|
+
const qty = 'asset_quantity' in a ? a.asset_quantity : a.quantity;
|
|
81
|
+
if (!unit)
|
|
82
|
+
continue;
|
|
83
|
+
d.assets.set(unit, (d.assets.get(unit) ?? 0n) + sign * BigInt(qty));
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// Read the ledger rows of the given source transactions. Asset rows are read only where a row
|
|
87
|
+
// has assets, so an ada-only block costs one SELECT.
|
|
88
|
+
async function readLedgerOutputs(tx, txHashes, into) {
|
|
89
|
+
const lookup = into ?? { hashes: new Set(), rows: new Map(), assets: new Map() };
|
|
90
|
+
const todo = [...new Set(txHashes)].filter(h => !lookup.hashes.has(h));
|
|
91
|
+
for (const hashChunk of (0, collections_1.chunk)(todo, collections_1.IN_CHUNK)) {
|
|
92
|
+
const rows = await tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ txHash: { in: hashChunk } }));
|
|
93
|
+
for (const r of rows ?? [])
|
|
94
|
+
lookup.rows.set(outpoint(r.txHash, num(r.outputIndex)), r);
|
|
95
|
+
const withAssets = [...new Set((rows ?? []).filter(r => r.hasAssets).map(r => r.txHash))];
|
|
96
|
+
if (withAssets.length) {
|
|
97
|
+
const assets = await tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: withAssets } }));
|
|
98
|
+
for (const a of assets ?? []) {
|
|
99
|
+
const k = outpoint(a.utxo_txHash, num(a.utxo_outputIndex));
|
|
100
|
+
const list = lookup.assets.get(k) ?? [];
|
|
101
|
+
list.push(a);
|
|
102
|
+
lookup.assets.set(k, list);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
for (const h of hashChunk)
|
|
106
|
+
lookup.hashes.add(h);
|
|
107
|
+
}
|
|
108
|
+
return lookup;
|
|
109
|
+
}
|
|
110
|
+
/** Amount list (lovelace + native assets) of a ledger row, the shape a resolved input carries. */
|
|
111
|
+
function ledgerRowAmount(row, assets) {
|
|
112
|
+
return [
|
|
113
|
+
{ unit: 'lovelace', quantity: String(row.lovelace ?? '0') },
|
|
114
|
+
...(assets ?? []).map(a => ({ unit: a.unit, quantity: String(a.asset_quantity) })),
|
|
115
|
+
];
|
|
116
|
+
}
|
|
117
|
+
// Apply one block after the anchor. `lookup` may carry rows the caller already read.
|
|
118
|
+
// A missing output is counted, not thrown. DB errors propagate so the block transaction rolls back.
|
|
119
|
+
async function applyBlockToLedger(tx, block, txs, lookup) {
|
|
120
|
+
const slot = block.slot ?? 0;
|
|
121
|
+
// 1) everything this block produces
|
|
122
|
+
const created = new Map();
|
|
123
|
+
for (const t of txs) {
|
|
124
|
+
for (const o of producedOutputs(t)) {
|
|
125
|
+
const built = buildLedgerUtxoRows({ ...o, txHash: t.hash }, slot);
|
|
126
|
+
created.set(outpoint(t.hash, o.outputIndex), built);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
// 2) everything this block consumes, same-block outputs first, the rest from the DB
|
|
130
|
+
const lookups = [];
|
|
131
|
+
const spentInBlock = new Set();
|
|
132
|
+
for (const t of txs) {
|
|
133
|
+
for (const i of consumedInputs(t)) {
|
|
134
|
+
const key = outpoint(i.txHash, i.outputIndex);
|
|
135
|
+
const own = created.get(key);
|
|
136
|
+
if (own) {
|
|
137
|
+
own.row.spentTxHash = t.hash;
|
|
138
|
+
own.row.spentSlot = slot;
|
|
139
|
+
spentInBlock.add(key);
|
|
140
|
+
}
|
|
141
|
+
else {
|
|
142
|
+
lookups.push({ key, txHash: i.txHash, outputIndex: i.outputIndex, spender: t.hash });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const { rows: dbRows, assets: dbAssets } = await readLedgerOutputs(tx, lookups.map(l => l.txHash), lookup);
|
|
147
|
+
const spentRows = [];
|
|
148
|
+
let missing = 0;
|
|
149
|
+
for (const l of lookups) {
|
|
150
|
+
const row = dbRows.get(l.key);
|
|
151
|
+
if (!row || row.spentTxHash) {
|
|
152
|
+
missing++;
|
|
153
|
+
if (missing <= 3) {
|
|
154
|
+
logger.warn(`ledger: ${l.spender} consumes ${l.key} which has no open row (${row ? 'already spent' : 'unknown'}), snapshot gap?`);
|
|
155
|
+
}
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
spentRows.push({
|
|
159
|
+
...row,
|
|
160
|
+
outputIndex: num(row.outputIndex),
|
|
161
|
+
lovelace: String(row.lovelace),
|
|
162
|
+
createdSlot: row.createdSlot == null ? null : num(row.createdSlot),
|
|
163
|
+
isScript: Boolean(row.isScript),
|
|
164
|
+
hasAssets: Boolean(row.hasAssets),
|
|
165
|
+
spentTxHash: l.spender,
|
|
166
|
+
spentSlot: slot,
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
// 3) per-address deltas
|
|
170
|
+
const deltas = new Map();
|
|
171
|
+
for (const [key, { row, assets }] of created) {
|
|
172
|
+
const d = deltaFor(deltas, row);
|
|
173
|
+
applyDelta(d, row, assets, 1n);
|
|
174
|
+
if (spentInBlock.has(key))
|
|
175
|
+
applyDelta(d, row, assets, -1n);
|
|
176
|
+
}
|
|
177
|
+
for (const row of spentRows) {
|
|
178
|
+
applyDelta(deltaFor(deltas, row), row, dbAssets.get(outpoint(row.txHash, row.outputIndex)), -1n);
|
|
179
|
+
}
|
|
180
|
+
// 4) UTxO rows
|
|
181
|
+
const createdRows = [...created.values()];
|
|
182
|
+
for (const rows of (0, collections_1.chunk)(createdRows.map(c => c.row), collections_1.IN_CHUNK)) {
|
|
183
|
+
await tx.run(UPSERT.into(cardano_1.LedgerUTxOs).entries(rows));
|
|
184
|
+
}
|
|
185
|
+
for (const rows of (0, collections_1.chunk)(createdRows.flatMap(c => c.assets), collections_1.IN_CHUNK)) {
|
|
186
|
+
await tx.run(UPSERT.into(cardano_1.LedgerUTxOAssets).entries(rows));
|
|
187
|
+
}
|
|
188
|
+
for (const rows of (0, collections_1.chunk)(spentRows, collections_1.IN_CHUNK)) {
|
|
189
|
+
await tx.run(UPSERT.into(cardano_1.LedgerUTxOs).entries(rows));
|
|
190
|
+
}
|
|
191
|
+
// 5) addresses, address assets, accounts
|
|
192
|
+
const touched = [...deltas.keys()];
|
|
193
|
+
const stakeDeltas = new Map();
|
|
194
|
+
for (const addrChunk of (0, collections_1.chunk)(touched, collections_1.IN_CHUNK)) {
|
|
195
|
+
const [existing, existingAssets] = await Promise.all([
|
|
196
|
+
tx.run(SELECT.from(cardano_1.LedgerAddresses).where({ address: { in: addrChunk } })),
|
|
197
|
+
tx.run(SELECT.from(cardano_1.LedgerAddressAssets).where({ address_address: { in: addrChunk } })),
|
|
198
|
+
]);
|
|
199
|
+
const byAddress = new Map((existing ?? []).map(e => [String(e.address), e]));
|
|
200
|
+
const assetQty = new Map();
|
|
201
|
+
for (const a of existingAssets ?? [])
|
|
202
|
+
assetQty.set(`${a.address_address}|${a.unit}`, big(a.asset_quantity));
|
|
203
|
+
const addressRows = [];
|
|
204
|
+
const assetRows = [];
|
|
205
|
+
const assetDeletes = [];
|
|
206
|
+
for (const address of addrChunk) {
|
|
207
|
+
const d = deltas.get(address);
|
|
208
|
+
const prev = byAddress.get(address);
|
|
209
|
+
const total = big(prev?.totalLovelace) + d.lovelace;
|
|
210
|
+
const count = num(prev?.utxoCount) + d.utxos;
|
|
211
|
+
addressRows.push({
|
|
212
|
+
address,
|
|
213
|
+
stakeAddress: prev?.stakeAddress ?? d.stakeAddress,
|
|
214
|
+
paymentCredential: (0, mappers_1.decodeShelleyAddress)(address).paymentCredential,
|
|
215
|
+
addressType: prev?.addressType ?? d.addressType,
|
|
216
|
+
isScript: prev ? Boolean(prev.isScript) : d.isScript,
|
|
217
|
+
totalLovelace: total.toString(),
|
|
218
|
+
utxoCount: count,
|
|
219
|
+
// null stays null: an address that came with the snapshot has no known first slot
|
|
220
|
+
firstSeenSlot: prev ? (prev.firstSeenSlot == null ? null : num(prev.firstSeenSlot)) : slot,
|
|
221
|
+
lastActiveSlot: slot,
|
|
222
|
+
});
|
|
223
|
+
for (const [unit, delta] of d.assets) {
|
|
224
|
+
if (delta === 0n)
|
|
225
|
+
continue;
|
|
226
|
+
const k = `${address}|${unit}`;
|
|
227
|
+
const next = (assetQty.get(k) ?? 0n) + delta;
|
|
228
|
+
if (next === 0n) {
|
|
229
|
+
if (assetQty.has(k))
|
|
230
|
+
assetDeletes.push({ address_address: address, unit });
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
assetRows.push({
|
|
234
|
+
address_address: address,
|
|
235
|
+
unit,
|
|
236
|
+
...(0, mappers_1.assetSlice)(unit, next),
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
const stake = prev?.stakeAddress ?? d.stakeAddress;
|
|
241
|
+
if (stake) {
|
|
242
|
+
const s = stakeDeltas.get(stake) ?? { lovelace: 0n, utxos: 0, newAddresses: 0 };
|
|
243
|
+
s.lovelace += d.lovelace;
|
|
244
|
+
s.utxos += d.utxos;
|
|
245
|
+
if (!prev)
|
|
246
|
+
s.newAddresses++;
|
|
247
|
+
stakeDeltas.set(stake, s);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
for (const rows of (0, collections_1.chunk)(addressRows, collections_1.IN_CHUNK))
|
|
251
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAddresses).entries(rows));
|
|
252
|
+
for (const rows of (0, collections_1.chunk)(assetRows, collections_1.IN_CHUNK))
|
|
253
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAddressAssets).entries(rows));
|
|
254
|
+
for (const del of assetDeletes)
|
|
255
|
+
await tx.run(DELETE.from(cardano_1.LedgerAddressAssets).where(del));
|
|
256
|
+
}
|
|
257
|
+
const stakes = [...stakeDeltas.keys()];
|
|
258
|
+
for (const stakeChunk of (0, collections_1.chunk)(stakes, collections_1.IN_CHUNK)) {
|
|
259
|
+
const existing = await tx.run(SELECT.from(cardano_1.LedgerAccounts).where({ stakeAddress: { in: stakeChunk } }));
|
|
260
|
+
const byStake = new Map((existing ?? []).map(e => [String(e.stakeAddress), e]));
|
|
261
|
+
const rows = stakeChunk.map((stakeAddress) => {
|
|
262
|
+
const d = stakeDeltas.get(stakeAddress);
|
|
263
|
+
const prev = byStake.get(stakeAddress);
|
|
264
|
+
return {
|
|
265
|
+
stakeAddress,
|
|
266
|
+
controlledAmount: (big(prev?.controlledAmount) + d.lovelace).toString(),
|
|
267
|
+
addressCount: num(prev?.addressCount) + d.newAddresses,
|
|
268
|
+
utxoCount: num(prev?.utxoCount) + d.utxos,
|
|
269
|
+
lastActiveSlot: slot,
|
|
270
|
+
};
|
|
271
|
+
});
|
|
272
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAccounts).entries(rows));
|
|
273
|
+
}
|
|
274
|
+
return { created: created.size, spent: spentInBlock.size + spentRows.length, missing, addresses: touched.length };
|
|
275
|
+
}
|
|
276
|
+
/** Asset rows of the given ledger rows, keyed `txHash#outputIndex`. Reads only rows that have assets. */
|
|
277
|
+
async function assetsOfRows(tx, rows) {
|
|
278
|
+
const byKey = new Map();
|
|
279
|
+
const wanted = new Set(rows.filter(r => Boolean(r.hasAssets)).map(r => outpoint(r.txHash, num(r.outputIndex))));
|
|
280
|
+
const hashes = [...new Set(rows.filter(r => Boolean(r.hasAssets)).map(r => r.txHash))];
|
|
281
|
+
for (const hashChunk of (0, collections_1.chunk)(hashes, collections_1.IN_CHUNK)) {
|
|
282
|
+
const assets = await tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: hashChunk } }));
|
|
283
|
+
for (const a of assets ?? []) {
|
|
284
|
+
const k = outpoint(a.utxo_txHash, num(a.utxo_outputIndex));
|
|
285
|
+
if (!wanted.has(k))
|
|
286
|
+
continue;
|
|
287
|
+
byKey.set(k, [...(byKey.get(k) ?? []), a]);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return byKey;
|
|
291
|
+
}
|
|
292
|
+
/** Latest slot at or before `forkSlot` at which a row of `address` was created or spent. */
|
|
293
|
+
async function lastActiveSlotUpTo(tx, address, forkSlot) {
|
|
294
|
+
const [created, spent] = await Promise.all([
|
|
295
|
+
tx.run(SELECT.one.from(cardano_1.LedgerUTxOs).columns('max(createdSlot) as slot').where({ address, createdSlot: { '<=': forkSlot } })),
|
|
296
|
+
tx.run(SELECT.one.from(cardano_1.LedgerUTxOs).columns('max(spentSlot) as slot').where({ address, spentSlot: { '<=': forkSlot } })),
|
|
297
|
+
]);
|
|
298
|
+
const slots = [created?.slot, spent?.slot].filter(s => s != null).map(num);
|
|
299
|
+
return slots.length ? Math.max(...slots) : null;
|
|
300
|
+
}
|
|
301
|
+
// Undo rolled-back transactions: drop what they created, reopen what they spent, and take the
|
|
302
|
+
// same amounts off the address and account sums that the apply added. `forkSlot` is the slot the
|
|
303
|
+
// chain rolled back to. Returns the touched addresses.
|
|
304
|
+
async function undoLedgerForTransactions(tx, txHashes, forkSlot) {
|
|
305
|
+
if (!txHashes.length)
|
|
306
|
+
return [];
|
|
307
|
+
const rolledBack = new Set(txHashes);
|
|
308
|
+
const deltas = new Map();
|
|
309
|
+
const hashChunks = (0, collections_1.chunk)(txHashes, collections_1.IN_CHUNK);
|
|
310
|
+
// Every chunk is read before the first write: a reopen in one chunk would otherwise change
|
|
311
|
+
// what a later chunk reads about the outputs its transactions created.
|
|
312
|
+
for (const hashChunk of hashChunks) {
|
|
313
|
+
const [created, spent] = await Promise.all([
|
|
314
|
+
tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ txHash: { in: hashChunk } })),
|
|
315
|
+
tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ spentTxHash: { in: hashChunk } })),
|
|
316
|
+
]);
|
|
317
|
+
// A row a rolled-back transaction created and another one spent added nothing to the sums.
|
|
318
|
+
const openCreated = (created ?? []).filter(r => r.spentTxHash == null);
|
|
319
|
+
const reopened = (spent ?? []).filter(r => !rolledBack.has(r.txHash));
|
|
320
|
+
const assets = await assetsOfRows(tx, [...openCreated, ...reopened]);
|
|
321
|
+
for (const r of openCreated)
|
|
322
|
+
applyDelta(deltaFor(deltas, r), r, assets.get(outpoint(r.txHash, num(r.outputIndex))), -1n);
|
|
323
|
+
for (const r of reopened)
|
|
324
|
+
applyDelta(deltaFor(deltas, r), r, assets.get(outpoint(r.txHash, num(r.outputIndex))), 1n);
|
|
325
|
+
}
|
|
326
|
+
for (const hashChunk of hashChunks) {
|
|
327
|
+
await tx.run(DELETE.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: hashChunk } }));
|
|
328
|
+
await tx.run(DELETE.from(cardano_1.LedgerUTxOs).where({ txHash: { in: hashChunk } }));
|
|
329
|
+
}
|
|
330
|
+
for (const hashChunk of hashChunks) {
|
|
331
|
+
await tx.run(UPDATE.entity(cardano_1.LedgerUTxOs).set({ spentTxHash: null, spentSlot: null }).where({ spentTxHash: { in: hashChunk } }));
|
|
332
|
+
}
|
|
333
|
+
const touched = [...deltas.keys()];
|
|
334
|
+
const stakeDeltas = new Map();
|
|
335
|
+
for (const addrChunk of (0, collections_1.chunk)(touched, collections_1.IN_CHUNK)) {
|
|
336
|
+
const [existing, existingAssets] = await Promise.all([
|
|
337
|
+
tx.run(SELECT.from(cardano_1.LedgerAddresses).where({ address: { in: addrChunk } })),
|
|
338
|
+
tx.run(SELECT.from(cardano_1.LedgerAddressAssets).where({ address_address: { in: addrChunk } })),
|
|
339
|
+
]);
|
|
340
|
+
const byAddress = new Map((existing ?? []).map(e => [String(e.address), e]));
|
|
341
|
+
const assetQty = new Map();
|
|
342
|
+
for (const a of existingAssets ?? [])
|
|
343
|
+
assetQty.set(`${a.address_address}|${a.unit}`, big(a.asset_quantity));
|
|
344
|
+
for (const address of addrChunk) {
|
|
345
|
+
const d = deltas.get(address);
|
|
346
|
+
const prev = byAddress.get(address);
|
|
347
|
+
if (!prev)
|
|
348
|
+
continue;
|
|
349
|
+
const count = num(prev.utxoCount) + d.utxos;
|
|
350
|
+
const stake = prev.stakeAddress ?? d.stakeAddress;
|
|
351
|
+
// An address the rolled-back blocks brought in did not exist at the fork.
|
|
352
|
+
const firstSeen = prev.firstSeenSlot == null ? null : num(prev.firstSeenSlot);
|
|
353
|
+
const bornAfterFork = firstSeen != null && firstSeen > forkSlot && count <= 0;
|
|
354
|
+
if (bornAfterFork) {
|
|
355
|
+
await tx.run(DELETE.from(cardano_1.LedgerAddressAssets).where({ address_address: address }));
|
|
356
|
+
await tx.run(DELETE.from(cardano_1.LedgerAddresses).where({ address }));
|
|
357
|
+
}
|
|
358
|
+
else {
|
|
359
|
+
const lastActive = prev.lastActiveSlot == null ? null : num(prev.lastActiveSlot);
|
|
360
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAddresses).entries({
|
|
361
|
+
...prev,
|
|
362
|
+
totalLovelace: (big(prev.totalLovelace) + d.lovelace).toString(),
|
|
363
|
+
utxoCount: count,
|
|
364
|
+
lastActiveSlot: lastActive != null && lastActive > forkSlot ? await lastActiveSlotUpTo(tx, address, forkSlot) : lastActive,
|
|
365
|
+
}));
|
|
366
|
+
for (const [unit, delta] of d.assets) {
|
|
367
|
+
if (delta === 0n)
|
|
368
|
+
continue;
|
|
369
|
+
const k = `${address}|${unit}`;
|
|
370
|
+
const next = (assetQty.get(k) ?? 0n) + delta;
|
|
371
|
+
if (next === 0n) {
|
|
372
|
+
await tx.run(DELETE.from(cardano_1.LedgerAddressAssets).where({ address_address: address, unit }));
|
|
373
|
+
}
|
|
374
|
+
else {
|
|
375
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAddressAssets).entries({
|
|
376
|
+
address_address: address,
|
|
377
|
+
unit,
|
|
378
|
+
...(0, mappers_1.assetSlice)(unit, next),
|
|
379
|
+
}));
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (stake) {
|
|
384
|
+
const s = stakeDeltas.get(stake) ?? { lovelace: 0n, utxos: 0, removedAddresses: 0 };
|
|
385
|
+
s.lovelace += d.lovelace;
|
|
386
|
+
s.utxos += d.utxos;
|
|
387
|
+
if (bornAfterFork)
|
|
388
|
+
s.removedAddresses++;
|
|
389
|
+
stakeDeltas.set(stake, s);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
for (const stakeChunk of (0, collections_1.chunk)([...stakeDeltas.keys()], collections_1.IN_CHUNK)) {
|
|
394
|
+
const existing = await tx.run(SELECT.from(cardano_1.LedgerAccounts).where({ stakeAddress: { in: stakeChunk } }));
|
|
395
|
+
for (const prev of existing ?? []) {
|
|
396
|
+
const stakeAddress = String(prev.stakeAddress);
|
|
397
|
+
const d = stakeDeltas.get(stakeAddress);
|
|
398
|
+
const addressCount = num(prev.addressCount) - d.removedAddresses;
|
|
399
|
+
if (addressCount <= 0) {
|
|
400
|
+
await tx.run(DELETE.from(cardano_1.LedgerAccounts).where({ stakeAddress }));
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
const lastActive = prev.lastActiveSlot == null ? null : num(prev.lastActiveSlot);
|
|
404
|
+
let lastActiveSlot = lastActive;
|
|
405
|
+
if (lastActive != null && lastActive > forkSlot) {
|
|
406
|
+
const latest = await tx.run(SELECT.one.from(cardano_1.LedgerAddresses).columns('max(lastActiveSlot) as slot').where({ stakeAddress, lastActiveSlot: { '<=': forkSlot } }));
|
|
407
|
+
lastActiveSlot = latest?.slot == null ? null : num(latest.slot);
|
|
408
|
+
}
|
|
409
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAccounts).entries({
|
|
410
|
+
stakeAddress,
|
|
411
|
+
controlledAmount: (big(prev.controlledAmount) + d.lovelace).toString(),
|
|
412
|
+
addressCount,
|
|
413
|
+
utxoCount: num(prev.utxoCount) + d.utxos,
|
|
414
|
+
lastActiveSlot,
|
|
415
|
+
}));
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
return touched;
|
|
419
|
+
}
|
|
420
|
+
// Recount the sums of these addresses and their stake keys from open rows. Also repairs a drifted sum.
|
|
421
|
+
async function recountLedgerAddresses(tx, addresses) {
|
|
422
|
+
const stakes = new Set();
|
|
423
|
+
for (const address of addresses) {
|
|
424
|
+
const open = await tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('txHash', 'outputIndex', 'lovelace', 'hasAssets', 'stakeAddress')
|
|
425
|
+
.where({ address, spentTxHash: null }));
|
|
426
|
+
const openKeys = new Set((open ?? []).map(r => outpoint(r.txHash, num(r.outputIndex))));
|
|
427
|
+
let total = 0n;
|
|
428
|
+
for (const r of open ?? [])
|
|
429
|
+
total += big(r.lovelace);
|
|
430
|
+
const assetSums = new Map();
|
|
431
|
+
const withAssets = [...new Set((open ?? []).filter(r => Boolean(r.hasAssets)).map(r => r.txHash))];
|
|
432
|
+
for (const hashChunk of (0, collections_1.chunk)(withAssets, collections_1.IN_CHUNK)) {
|
|
433
|
+
const rows = await tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: hashChunk } }));
|
|
434
|
+
for (const a of rows ?? []) {
|
|
435
|
+
if (!openKeys.has(outpoint(a.utxo_txHash, num(a.utxo_outputIndex))))
|
|
436
|
+
continue;
|
|
437
|
+
assetSums.set(a.unit, (assetSums.get(a.unit) ?? 0n) + big(a.asset_quantity));
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
const prev = await tx.run(SELECT.one.from(cardano_1.LedgerAddresses).where({ address }));
|
|
441
|
+
const decoded = (0, mappers_1.decodeShelleyAddress)(address);
|
|
442
|
+
const stakeAddress = prev?.stakeAddress ?? open?.[0]?.stakeAddress ?? decoded.stakeAddress;
|
|
443
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAddresses).entries({
|
|
444
|
+
address,
|
|
445
|
+
stakeAddress,
|
|
446
|
+
paymentCredential: decoded.paymentCredential,
|
|
447
|
+
addressType: prev?.addressType ?? decoded.type,
|
|
448
|
+
isScript: prev ? Boolean(prev.isScript) : decoded.isScript,
|
|
449
|
+
totalLovelace: total.toString(),
|
|
450
|
+
utxoCount: (open ?? []).length,
|
|
451
|
+
firstSeenSlot: prev?.firstSeenSlot == null ? null : num(prev.firstSeenSlot),
|
|
452
|
+
lastActiveSlot: prev?.lastActiveSlot == null ? null : num(prev.lastActiveSlot),
|
|
453
|
+
}));
|
|
454
|
+
await tx.run(DELETE.from(cardano_1.LedgerAddressAssets).where({ address_address: address }));
|
|
455
|
+
const assetRows = [...assetSums].filter(([, q]) => q !== 0n).map(([unit, q]) => ({
|
|
456
|
+
address_address: address,
|
|
457
|
+
unit,
|
|
458
|
+
...(0, mappers_1.assetSlice)(unit, q),
|
|
459
|
+
}));
|
|
460
|
+
for (const rows of (0, collections_1.chunk)(assetRows, collections_1.IN_CHUNK))
|
|
461
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAddressAssets).entries(rows));
|
|
462
|
+
if (stakeAddress)
|
|
463
|
+
stakes.add(stakeAddress);
|
|
464
|
+
}
|
|
465
|
+
await recountLedgerAccounts(tx, [...stakes]);
|
|
466
|
+
}
|
|
467
|
+
/** Recount `LedgerAccounts` for the given stake keys from `LedgerAddresses`. */
|
|
468
|
+
async function recountLedgerAccounts(tx, stakeAddresses) {
|
|
469
|
+
for (const stakeChunk of (0, collections_1.chunk)(stakeAddresses, collections_1.IN_CHUNK)) {
|
|
470
|
+
const [addrRows, existing] = await Promise.all([
|
|
471
|
+
tx.run(SELECT.from(cardano_1.LedgerAddresses).columns('stakeAddress', 'totalLovelace', 'utxoCount')
|
|
472
|
+
.where({ stakeAddress: { in: stakeChunk } })),
|
|
473
|
+
tx.run(SELECT.from(cardano_1.LedgerAccounts).where({ stakeAddress: { in: stakeChunk } })),
|
|
474
|
+
]);
|
|
475
|
+
const sums = new Map();
|
|
476
|
+
for (const r of addrRows ?? []) {
|
|
477
|
+
const k = String(r.stakeAddress);
|
|
478
|
+
const s = sums.get(k) ?? { lovelace: 0n, addresses: 0, utxos: 0 };
|
|
479
|
+
s.lovelace += big(r.totalLovelace);
|
|
480
|
+
s.addresses += 1;
|
|
481
|
+
s.utxos += num(r.utxoCount);
|
|
482
|
+
sums.set(k, s);
|
|
483
|
+
}
|
|
484
|
+
const byStake = new Map((existing ?? []).map(e => [String(e.stakeAddress), e]));
|
|
485
|
+
const rows = stakeChunk.map((stakeAddress) => {
|
|
486
|
+
const s = sums.get(stakeAddress) ?? { lovelace: 0n, addresses: 0, utxos: 0 };
|
|
487
|
+
const prev = byStake.get(stakeAddress);
|
|
488
|
+
return {
|
|
489
|
+
stakeAddress,
|
|
490
|
+
controlledAmount: s.lovelace.toString(),
|
|
491
|
+
addressCount: s.addresses,
|
|
492
|
+
utxoCount: s.utxos,
|
|
493
|
+
lastActiveSlot: prev?.lastActiveSlot == null ? null : num(prev.lastActiveSlot),
|
|
494
|
+
};
|
|
495
|
+
});
|
|
496
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAccounts).entries(rows));
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
/** Address types that carry a payment credential. */
|
|
500
|
+
const CREDENTIAL_ADDRESS_TYPES = ['base', 'pointer', 'enterprise'];
|
|
501
|
+
// Fill a missing `LedgerAddresses.paymentCredential`, one transaction per chunk. Returns rows updated.
|
|
502
|
+
async function backfillPaymentCredentials(chunkSize = 1000) {
|
|
503
|
+
let updated = 0;
|
|
504
|
+
for (;;) {
|
|
505
|
+
const n = await cds_1.default.tx(async (tx) => {
|
|
506
|
+
const rows = await tx.run(SELECT.from(cardano_1.LedgerAddresses).columns('address')
|
|
507
|
+
.where({ paymentCredential: null, addressType: { in: CREDENTIAL_ADDRESS_TYPES } })
|
|
508
|
+
.limit(chunkSize));
|
|
509
|
+
for (const { address } of rows ?? []) {
|
|
510
|
+
// '' marks an address that decodes without a credential, so it is not picked again
|
|
511
|
+
const credential = (0, mappers_1.decodeShelleyAddress)(address).paymentCredential ?? '';
|
|
512
|
+
await tx.run(UPDATE.entity(cardano_1.LedgerAddresses).set({ paymentCredential: credential }).where({ address }));
|
|
513
|
+
}
|
|
514
|
+
return (rows ?? []).length;
|
|
515
|
+
});
|
|
516
|
+
updated += n;
|
|
517
|
+
if (n < chunkSize)
|
|
518
|
+
return updated;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
//# sourceMappingURL=ledger-state.js.map
|
|
@@ -0,0 +1,16 @@
|
|
|
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
|
+
export declare class PendingSpends {
|
|
5
|
+
private readonly now;
|
|
6
|
+
private readonly txs;
|
|
7
|
+
constructor(now?: () => number);
|
|
8
|
+
/** Remember a submitted transaction; unparseable CBOR is ignored (the submit already succeeded). */
|
|
9
|
+
record(signedTxCbor: string): void;
|
|
10
|
+
/** The pending transaction that spends this output, if any. */
|
|
11
|
+
spentBy(txHash: string, outputIndex: number): string | undefined;
|
|
12
|
+
apply(address: string, utxos: UTxO[]): UTxO[];
|
|
13
|
+
get size(): number;
|
|
14
|
+
private prune;
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=pending-spends.d.ts.map
|
|
@@ -0,0 +1,81 @@
|
|
|
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
|
+
// Submitted transactions still in the mempool, whose inputs still look unspent. Builders skip
|
|
14
|
+
// those inputs and may spend the pending change. Entries end when crawled or after PENDING_TX_TTL_MS.
|
|
15
|
+
class PendingSpends {
|
|
16
|
+
now;
|
|
17
|
+
txs = new Map();
|
|
18
|
+
constructor(now = Date.now) {
|
|
19
|
+
this.now = now;
|
|
20
|
+
}
|
|
21
|
+
/** Remember a submitted transaction; unparseable CBOR is ignored (the submit already succeeded). */
|
|
22
|
+
record(signedTxCbor) {
|
|
23
|
+
try {
|
|
24
|
+
const parsed = (0, parse_1.parseTransaction)(signedTxCbor);
|
|
25
|
+
this.txs.set(parsed.txHash, {
|
|
26
|
+
inputs: parsed.inputs.map((i) => refKey(i.txHash, i.outputIndex)),
|
|
27
|
+
outputs: parsed.outputs.map((o, outputIndex) => ({
|
|
28
|
+
txHash: parsed.txHash,
|
|
29
|
+
outputIndex,
|
|
30
|
+
address: o.address,
|
|
31
|
+
amount: [{ unit: 'lovelace', quantity: o.lovelace }, ...o.assets],
|
|
32
|
+
datumHash: o.datumHash,
|
|
33
|
+
inlineDatum: o.inlineDatumHex,
|
|
34
|
+
scriptRefCbor: o.referenceScriptHex,
|
|
35
|
+
})),
|
|
36
|
+
expiresAt: this.now() + exports.PENDING_TX_TTL_MS,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
catch (err) {
|
|
40
|
+
logger.warn(`submitted transaction not tracked as pending: ${err instanceof Error ? err.message : String(err)}`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** The pending transaction that spends this output, if any. */
|
|
44
|
+
spentBy(txHash, outputIndex) {
|
|
45
|
+
this.prune();
|
|
46
|
+
const key = refKey(txHash, outputIndex);
|
|
47
|
+
for (const [hash, tx] of this.txs)
|
|
48
|
+
if (tx.inputs.includes(key))
|
|
49
|
+
return hash;
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
// The address's UTxOs after the pending transactions. One whose outputs already appear in `utxos`
|
|
53
|
+
// has been crawled and is forgotten.
|
|
54
|
+
apply(address, utxos) {
|
|
55
|
+
this.prune();
|
|
56
|
+
if (this.txs.size === 0)
|
|
57
|
+
return utxos;
|
|
58
|
+
const listed = new Set(utxos.map((u) => u.txHash.toLowerCase()));
|
|
59
|
+
for (const hash of [...this.txs.keys()])
|
|
60
|
+
if (listed.has(hash))
|
|
61
|
+
this.txs.delete(hash);
|
|
62
|
+
const spent = new Set([...this.txs.values()].flatMap((t) => t.inputs));
|
|
63
|
+
const keep = utxos.filter((u) => !spent.has(refKey(u.txHash, u.outputIndex)));
|
|
64
|
+
const pendingOut = [...this.txs.values()]
|
|
65
|
+
.flatMap((t) => t.outputs)
|
|
66
|
+
.filter((o) => o.address === address && !spent.has(refKey(o.txHash, o.outputIndex)));
|
|
67
|
+
return [...keep, ...pendingOut];
|
|
68
|
+
}
|
|
69
|
+
get size() {
|
|
70
|
+
this.prune();
|
|
71
|
+
return this.txs.size;
|
|
72
|
+
}
|
|
73
|
+
prune() {
|
|
74
|
+
const now = this.now();
|
|
75
|
+
for (const [hash, tx] of this.txs)
|
|
76
|
+
if (tx.expiresAt <= now)
|
|
77
|
+
this.txs.delete(hash);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
exports.PendingSpends = PendingSpends;
|
|
81
|
+
//# sourceMappingURL=pending-spends.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import net from 'node:net';
|
|
2
|
+
/** A stake pool's metadata file is at most this many bytes. */
|
|
3
|
+
export declare const POOL_METADATA_MAX_BYTES = 512;
|
|
4
|
+
/** The four fields of a stake pool's metadata file. */
|
|
5
|
+
export interface PoolMetadata {
|
|
6
|
+
name: string;
|
|
7
|
+
ticker: string;
|
|
8
|
+
homepage: string;
|
|
9
|
+
description: string;
|
|
10
|
+
}
|
|
11
|
+
export declare function validPoolMetadata(value: unknown): PoolMetadata | null;
|
|
12
|
+
export declare function isPublicAddress(address: string): boolean;
|
|
13
|
+
export declare const publicLookup: net.LookupFunction;
|
|
14
|
+
export declare function fetchPoolMetadata(url: string, hash: string): Promise<PoolMetadata | null>;
|
|
15
|
+
//# sourceMappingURL=pool-metadata.d.ts.map
|