@odatano/core 2.0.0-rc.17 → 2.0.0-rc.19
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/CardanoIndexerService/index.d.ts +52 -0
- package/@cds-models/CardanoIndexerService/index.js +7 -0
- package/@cds-models/CardanoODataService/index.d.ts +170 -0
- package/@cds-models/CardanoODataService/index.js +21 -0
- package/@cds-models/odatano/cardano/index.d.ts +176 -0
- package/@cds-models/odatano/cardano/index.js +21 -0
- package/README.md +3 -3
- package/db/schema.cds +277 -0
- package/package.json +179 -179
- package/srv/blockchain/backends/cardano-backend.d.ts +16 -0
- package/srv/blockchain/backends/cardano-backend.js +4 -0
- package/srv/blockchain/backends/koios-backend.d.ts +80 -1
- package/srv/blockchain/backends/koios-backend.js +128 -48
- package/srv/blockchain/backends/ogmios-backend.d.ts +21 -2
- package/srv/blockchain/backends/ogmios-backend.js +120 -16
- package/srv/blockchain/cardano-client.d.ts +3 -1
- package/srv/blockchain/cardano-client.js +9 -0
- package/srv/blockchain/cardano-indexer.d.ts +56 -3
- package/srv/blockchain/cardano-indexer.js +124 -3
- package/srv/blockchain/crawler/crawler.d.ts +11 -1
- package/srv/blockchain/crawler/crawler.js +70 -1
- package/srv/blockchain/crawler/sync-state.d.ts +27 -1
- package/srv/blockchain/crawler/sync-state.js +83 -1
- package/srv/blockchain/crawler/utxo-set-import.d.ts +86 -0
- package/srv/blockchain/crawler/utxo-set-import.js +289 -0
- package/srv/blockchain/ledger-state.d.ts +89 -0
- package/srv/blockchain/ledger-state.js +383 -0
- package/srv/cardano-indexer-service.cds +26 -0
- package/srv/cardano-indexer-service.js +71 -0
- package/srv/cardano-service.cds +35 -0
- package/srv/server.js +20 -12
- package/srv/utils/db-indexes.js +12 -0
- package/srv/utils/mappers.d.ts +43 -3
- package/srv/utils/mappers.js +115 -1
- package/srv/utils/types.d.ts +38 -0
|
@@ -0,0 +1,383 @@
|
|
|
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.applyBlockToLedger = applyBlockToLedger;
|
|
8
|
+
exports.undoLedgerForTransactions = undoLedgerForTransactions;
|
|
9
|
+
exports.recountLedgerAddresses = recountLedgerAddresses;
|
|
10
|
+
exports.recountLedgerAccounts = recountLedgerAccounts;
|
|
11
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
12
|
+
const cardano_1 = require("#cds-models/odatano/cardano");
|
|
13
|
+
const mappers_1 = require("../utils/mappers");
|
|
14
|
+
const collections_1 = require("../utils/collections");
|
|
15
|
+
const { SELECT, UPSERT, UPDATE, DELETE } = cds_1.default.ql;
|
|
16
|
+
const logger = cds_1.default.log('LedgerState');
|
|
17
|
+
const outpoint = (txHash, outputIndex) => `${txHash}#${outputIndex}`;
|
|
18
|
+
const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
|
|
19
|
+
const nativeAssets = (amount) => (amount ?? []).filter(a => a.unit !== 'lovelace' && a.quantity !== '0');
|
|
20
|
+
const big = (v) => (v == null || v === '' ? 0n : BigInt(String(v)));
|
|
21
|
+
const num = (v) => Number(v ?? 0);
|
|
22
|
+
function decodeAssetName(hex) {
|
|
23
|
+
if (!hex)
|
|
24
|
+
return null;
|
|
25
|
+
try {
|
|
26
|
+
const text = Buffer.from(hex, 'hex').toString('utf8');
|
|
27
|
+
// printable only — a binary asset name has no useful decoded form
|
|
28
|
+
return /^[\x20-\x7e]*$/.test(text) ? text : null;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Build the `LedgerUTxOs` row (+ asset rows) for one output. */
|
|
35
|
+
function buildLedgerUtxoRows(o, createdSlot) {
|
|
36
|
+
const decoded = (0, mappers_1.decodeShelleyAddress)(o.address);
|
|
37
|
+
const assets = nativeAssets(o.amount).map((a) => ({
|
|
38
|
+
utxo_txHash: o.txHash,
|
|
39
|
+
utxo_outputIndex: o.outputIndex,
|
|
40
|
+
unit: a.unit,
|
|
41
|
+
asset_quantity: String(a.quantity),
|
|
42
|
+
asset_policyId: a.unit.length >= 56 ? a.unit.slice(0, 56) : null,
|
|
43
|
+
asset_assetNameHex: a.unit.length > 56 ? a.unit.slice(56) : '',
|
|
44
|
+
asset_assetName: a.unit.length > 56 ? decodeAssetName(a.unit.slice(56)) : null,
|
|
45
|
+
}));
|
|
46
|
+
return {
|
|
47
|
+
row: {
|
|
48
|
+
txHash: o.txHash,
|
|
49
|
+
outputIndex: o.outputIndex,
|
|
50
|
+
address: o.address,
|
|
51
|
+
stakeAddress: decoded.stakeAddress,
|
|
52
|
+
addressType: decoded.type,
|
|
53
|
+
isScript: decoded.isScript,
|
|
54
|
+
lovelace: lovelaceOf(o.amount).toString(),
|
|
55
|
+
createdSlot,
|
|
56
|
+
spentTxHash: null,
|
|
57
|
+
spentSlot: null,
|
|
58
|
+
utxo_dataHash: o.dataHash || null,
|
|
59
|
+
utxo_inlineDatum: o.inlineDatum || null,
|
|
60
|
+
utxo_referenceScriptHash: o.referenceScriptHash || null,
|
|
61
|
+
hasAssets: assets.length > 0,
|
|
62
|
+
},
|
|
63
|
+
assets,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/** Outputs the ledger actually produced: collateral return on a phase-2 failure, else the regular ones. */
|
|
67
|
+
function producedOutputs(t) {
|
|
68
|
+
return (t.outputs ?? []).filter(o => (t.spendsCollaterals ? o.isCollateral : !o.isCollateral));
|
|
69
|
+
}
|
|
70
|
+
/** Inputs the ledger actually consumed: collateral on a phase-2 failure, else the regular (non-reference) ones. */
|
|
71
|
+
function consumedInputs(t) {
|
|
72
|
+
return (t.inputs ?? [])
|
|
73
|
+
.filter(i => (t.spendsCollaterals ? i.isCollateral : !i.isReference && !i.isCollateral))
|
|
74
|
+
.map(i => ({ txHash: i.txHash, outputIndex: i.outputIndex }));
|
|
75
|
+
}
|
|
76
|
+
function deltaFor(map, row) {
|
|
77
|
+
let d = map.get(row.address);
|
|
78
|
+
if (!d) {
|
|
79
|
+
d = { lovelace: 0n, utxos: 0, assets: new Map(), stakeAddress: row.stakeAddress, addressType: row.addressType, isScript: row.isScript };
|
|
80
|
+
map.set(row.address, d);
|
|
81
|
+
}
|
|
82
|
+
return d;
|
|
83
|
+
}
|
|
84
|
+
function applyDelta(d, row, assets, sign) {
|
|
85
|
+
d.lovelace += sign * BigInt(row.lovelace);
|
|
86
|
+
d.utxos += Number(sign);
|
|
87
|
+
for (const a of assets ?? []) {
|
|
88
|
+
const unit = 'unit' in a ? a.unit : '';
|
|
89
|
+
const qty = 'asset_quantity' in a ? a.asset_quantity : a.quantity;
|
|
90
|
+
if (!unit)
|
|
91
|
+
continue;
|
|
92
|
+
d.assets.set(unit, (d.assets.get(unit) ?? 0n) + sign * BigInt(qty));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Apply one block to the ledger tables. Caller guarantees `block.slot > anchor.slot`.
|
|
97
|
+
* Never throws for a missing outpoint (it is counted and logged); DB errors propagate so the
|
|
98
|
+
* block transaction rolls back as a whole.
|
|
99
|
+
*/
|
|
100
|
+
async function applyBlockToLedger(tx, block, txs) {
|
|
101
|
+
const slot = block.slot ?? 0;
|
|
102
|
+
// 1) everything this block produces
|
|
103
|
+
const created = new Map();
|
|
104
|
+
for (const t of txs) {
|
|
105
|
+
for (const o of producedOutputs(t)) {
|
|
106
|
+
const built = buildLedgerUtxoRows({ ...o, txHash: t.hash }, slot);
|
|
107
|
+
created.set(outpoint(t.hash, o.outputIndex), built);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
// 2) everything this block consumes — same-block outputs first, the rest from the DB
|
|
111
|
+
const lookups = [];
|
|
112
|
+
const spentInBlock = new Set();
|
|
113
|
+
for (const t of txs) {
|
|
114
|
+
for (const i of consumedInputs(t)) {
|
|
115
|
+
const key = outpoint(i.txHash, i.outputIndex);
|
|
116
|
+
const own = created.get(key);
|
|
117
|
+
if (own) {
|
|
118
|
+
own.row.spentTxHash = t.hash;
|
|
119
|
+
own.row.spentSlot = slot;
|
|
120
|
+
spentInBlock.add(key);
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
lookups.push({ key, txHash: i.txHash, outputIndex: i.outputIndex, spender: t.hash });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const dbRows = new Map();
|
|
128
|
+
const dbAssets = new Map();
|
|
129
|
+
const sourceHashes = [...new Set(lookups.map(l => l.txHash))];
|
|
130
|
+
for (const hashChunk of (0, collections_1.chunk)(sourceHashes, collections_1.IN_CHUNK)) {
|
|
131
|
+
const [rows, assets] = await Promise.all([
|
|
132
|
+
tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ txHash: { in: hashChunk } })),
|
|
133
|
+
tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: hashChunk } })),
|
|
134
|
+
]);
|
|
135
|
+
for (const r of rows ?? [])
|
|
136
|
+
dbRows.set(outpoint(r.txHash, num(r.outputIndex)), r);
|
|
137
|
+
for (const a of assets ?? []) {
|
|
138
|
+
const k = outpoint(a.utxo_txHash, num(a.utxo_outputIndex));
|
|
139
|
+
const list = dbAssets.get(k) ?? [];
|
|
140
|
+
list.push(a);
|
|
141
|
+
dbAssets.set(k, list);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const spentRows = [];
|
|
145
|
+
let missing = 0;
|
|
146
|
+
for (const l of lookups) {
|
|
147
|
+
const row = dbRows.get(l.key);
|
|
148
|
+
if (!row || row.spentTxHash) {
|
|
149
|
+
missing++;
|
|
150
|
+
if (missing <= 3) {
|
|
151
|
+
logger.warn(`ledger: ${l.spender} consumes ${l.key} which has no open row (${row ? 'already spent' : 'unknown'}) — snapshot gap?`);
|
|
152
|
+
}
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
spentRows.push({
|
|
156
|
+
...row,
|
|
157
|
+
outputIndex: num(row.outputIndex),
|
|
158
|
+
lovelace: String(row.lovelace),
|
|
159
|
+
createdSlot: row.createdSlot == null ? null : num(row.createdSlot),
|
|
160
|
+
isScript: Boolean(row.isScript),
|
|
161
|
+
hasAssets: Boolean(row.hasAssets),
|
|
162
|
+
spentTxHash: l.spender,
|
|
163
|
+
spentSlot: slot,
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
// 3) per-address deltas
|
|
167
|
+
const deltas = new Map();
|
|
168
|
+
for (const [key, { row, assets }] of created) {
|
|
169
|
+
const d = deltaFor(deltas, row);
|
|
170
|
+
applyDelta(d, row, assets, 1n);
|
|
171
|
+
if (spentInBlock.has(key))
|
|
172
|
+
applyDelta(d, row, assets, -1n);
|
|
173
|
+
}
|
|
174
|
+
for (const row of spentRows) {
|
|
175
|
+
applyDelta(deltaFor(deltas, row), row, dbAssets.get(outpoint(row.txHash, row.outputIndex)), -1n);
|
|
176
|
+
}
|
|
177
|
+
// 4) UTxO rows
|
|
178
|
+
const createdRows = [...created.values()];
|
|
179
|
+
for (const rows of (0, collections_1.chunk)(createdRows.map(c => c.row), collections_1.IN_CHUNK)) {
|
|
180
|
+
await tx.run(UPSERT.into(cardano_1.LedgerUTxOs).entries(rows));
|
|
181
|
+
}
|
|
182
|
+
for (const rows of (0, collections_1.chunk)(createdRows.flatMap(c => c.assets), collections_1.IN_CHUNK)) {
|
|
183
|
+
await tx.run(UPSERT.into(cardano_1.LedgerUTxOAssets).entries(rows));
|
|
184
|
+
}
|
|
185
|
+
for (const rows of (0, collections_1.chunk)(spentRows, collections_1.IN_CHUNK)) {
|
|
186
|
+
await tx.run(UPSERT.into(cardano_1.LedgerUTxOs).entries(rows));
|
|
187
|
+
}
|
|
188
|
+
// 5) addresses, address assets, accounts
|
|
189
|
+
const touched = [...deltas.keys()];
|
|
190
|
+
const stakeDeltas = new Map();
|
|
191
|
+
for (const addrChunk of (0, collections_1.chunk)(touched, collections_1.IN_CHUNK)) {
|
|
192
|
+
const [existing, existingAssets] = await Promise.all([
|
|
193
|
+
tx.run(SELECT.from(cardano_1.LedgerAddresses).where({ address: { in: addrChunk } })),
|
|
194
|
+
tx.run(SELECT.from(cardano_1.LedgerAddressAssets).where({ address_address: { in: addrChunk } })),
|
|
195
|
+
]);
|
|
196
|
+
const byAddress = new Map((existing ?? []).map(e => [String(e.address), e]));
|
|
197
|
+
const assetQty = new Map();
|
|
198
|
+
for (const a of existingAssets ?? [])
|
|
199
|
+
assetQty.set(`${a.address_address}|${a.unit}`, big(a.asset_quantity));
|
|
200
|
+
const addressRows = [];
|
|
201
|
+
const assetRows = [];
|
|
202
|
+
const assetDeletes = [];
|
|
203
|
+
for (const address of addrChunk) {
|
|
204
|
+
const d = deltas.get(address);
|
|
205
|
+
const prev = byAddress.get(address);
|
|
206
|
+
const total = big(prev?.totalLovelace) + d.lovelace;
|
|
207
|
+
const count = num(prev?.utxoCount) + d.utxos;
|
|
208
|
+
addressRows.push({
|
|
209
|
+
address,
|
|
210
|
+
stakeAddress: prev?.stakeAddress ?? d.stakeAddress,
|
|
211
|
+
addressType: prev?.addressType ?? d.addressType,
|
|
212
|
+
isScript: prev ? Boolean(prev.isScript) : d.isScript,
|
|
213
|
+
totalLovelace: total.toString(),
|
|
214
|
+
utxoCount: count,
|
|
215
|
+
// null stays null: an address that came with the snapshot has no known first slot
|
|
216
|
+
firstSeenSlot: prev ? (prev.firstSeenSlot == null ? null : num(prev.firstSeenSlot)) : slot,
|
|
217
|
+
lastActiveSlot: slot,
|
|
218
|
+
});
|
|
219
|
+
for (const [unit, delta] of d.assets) {
|
|
220
|
+
if (delta === 0n)
|
|
221
|
+
continue;
|
|
222
|
+
const k = `${address}|${unit}`;
|
|
223
|
+
const next = (assetQty.get(k) ?? 0n) + delta;
|
|
224
|
+
if (next === 0n) {
|
|
225
|
+
if (assetQty.has(k))
|
|
226
|
+
assetDeletes.push({ address_address: address, unit });
|
|
227
|
+
}
|
|
228
|
+
else {
|
|
229
|
+
assetRows.push({
|
|
230
|
+
address_address: address,
|
|
231
|
+
unit,
|
|
232
|
+
asset_quantity: next.toString(),
|
|
233
|
+
asset_policyId: unit.length >= 56 ? unit.slice(0, 56) : null,
|
|
234
|
+
asset_assetNameHex: unit.length > 56 ? unit.slice(56) : '',
|
|
235
|
+
asset_assetName: unit.length > 56 ? decodeAssetName(unit.slice(56)) : null,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
const stake = prev?.stakeAddress ?? d.stakeAddress;
|
|
240
|
+
if (stake) {
|
|
241
|
+
const s = stakeDeltas.get(stake) ?? { lovelace: 0n, utxos: 0, newAddresses: 0 };
|
|
242
|
+
s.lovelace += d.lovelace;
|
|
243
|
+
s.utxos += d.utxos;
|
|
244
|
+
if (!prev)
|
|
245
|
+
s.newAddresses++;
|
|
246
|
+
stakeDeltas.set(stake, s);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
for (const rows of (0, collections_1.chunk)(addressRows, collections_1.IN_CHUNK))
|
|
250
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAddresses).entries(rows));
|
|
251
|
+
for (const rows of (0, collections_1.chunk)(assetRows, collections_1.IN_CHUNK))
|
|
252
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAddressAssets).entries(rows));
|
|
253
|
+
for (const del of assetDeletes)
|
|
254
|
+
await tx.run(DELETE.from(cardano_1.LedgerAddressAssets).where(del));
|
|
255
|
+
}
|
|
256
|
+
const stakes = [...stakeDeltas.keys()];
|
|
257
|
+
for (const stakeChunk of (0, collections_1.chunk)(stakes, collections_1.IN_CHUNK)) {
|
|
258
|
+
const existing = await tx.run(SELECT.from(cardano_1.LedgerAccounts).where({ stakeAddress: { in: stakeChunk } }));
|
|
259
|
+
const byStake = new Map((existing ?? []).map(e => [String(e.stakeAddress), e]));
|
|
260
|
+
const rows = stakeChunk.map((stakeAddress) => {
|
|
261
|
+
const d = stakeDeltas.get(stakeAddress);
|
|
262
|
+
const prev = byStake.get(stakeAddress);
|
|
263
|
+
return {
|
|
264
|
+
stakeAddress,
|
|
265
|
+
controlledAmount: (big(prev?.controlledAmount) + d.lovelace).toString(),
|
|
266
|
+
addressCount: num(prev?.addressCount) + d.newAddresses,
|
|
267
|
+
utxoCount: num(prev?.utxoCount) + d.utxos,
|
|
268
|
+
lastActiveSlot: slot,
|
|
269
|
+
};
|
|
270
|
+
});
|
|
271
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAccounts).entries(rows));
|
|
272
|
+
}
|
|
273
|
+
return { created: created.size, spent: spentInBlock.size + spentRows.length, missing, addresses: touched.length };
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Reorg undo for a set of rolled-back transactions: drop what they created, reopen what
|
|
277
|
+
* they spent, then recount every address either side touched from the open rows.
|
|
278
|
+
* @returns the recounted addresses
|
|
279
|
+
*/
|
|
280
|
+
async function undoLedgerForTransactions(tx, txHashes) {
|
|
281
|
+
if (!txHashes.length)
|
|
282
|
+
return [];
|
|
283
|
+
const touched = new Set();
|
|
284
|
+
for (const hashChunk of (0, collections_1.chunk)(txHashes, collections_1.IN_CHUNK)) {
|
|
285
|
+
const [createdRows, spentRows] = await Promise.all([
|
|
286
|
+
tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('address').where({ txHash: { in: hashChunk } })),
|
|
287
|
+
tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('address').where({ spentTxHash: { in: hashChunk } })),
|
|
288
|
+
]);
|
|
289
|
+
for (const r of [...(createdRows ?? []), ...(spentRows ?? [])])
|
|
290
|
+
touched.add(r.address);
|
|
291
|
+
await tx.run(DELETE.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: hashChunk } }));
|
|
292
|
+
await tx.run(DELETE.from(cardano_1.LedgerUTxOs).where({ txHash: { in: hashChunk } }));
|
|
293
|
+
await tx.run(UPDATE.entity(cardano_1.LedgerUTxOs).set({ spentTxHash: null, spentSlot: null }).where({ spentTxHash: { in: hashChunk } }));
|
|
294
|
+
}
|
|
295
|
+
const addresses = [...touched];
|
|
296
|
+
await recountLedgerAddresses(tx, addresses);
|
|
297
|
+
return addresses;
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Recount running sums for the given addresses from their open UTxO rows, then the
|
|
301
|
+
* stake keys those addresses belong to. Also the repair path for a drifted sum.
|
|
302
|
+
*/
|
|
303
|
+
async function recountLedgerAddresses(tx, addresses) {
|
|
304
|
+
const stakes = new Set();
|
|
305
|
+
for (const address of addresses) {
|
|
306
|
+
const open = await tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('txHash', 'outputIndex', 'lovelace', 'hasAssets', 'stakeAddress')
|
|
307
|
+
.where({ address, spentTxHash: null }));
|
|
308
|
+
const openKeys = new Set((open ?? []).map(r => outpoint(r.txHash, num(r.outputIndex))));
|
|
309
|
+
let total = 0n;
|
|
310
|
+
for (const r of open ?? [])
|
|
311
|
+
total += big(r.lovelace);
|
|
312
|
+
const assetSums = new Map();
|
|
313
|
+
const withAssets = [...new Set((open ?? []).filter(r => Boolean(r.hasAssets)).map(r => r.txHash))];
|
|
314
|
+
for (const hashChunk of (0, collections_1.chunk)(withAssets, collections_1.IN_CHUNK)) {
|
|
315
|
+
const rows = await tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: hashChunk } }));
|
|
316
|
+
for (const a of rows ?? []) {
|
|
317
|
+
if (!openKeys.has(outpoint(a.utxo_txHash, num(a.utxo_outputIndex))))
|
|
318
|
+
continue;
|
|
319
|
+
assetSums.set(a.unit, (assetSums.get(a.unit) ?? 0n) + big(a.asset_quantity));
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
const prev = await tx.run(SELECT.one.from(cardano_1.LedgerAddresses).where({ address }));
|
|
323
|
+
const decoded = (0, mappers_1.decodeShelleyAddress)(address);
|
|
324
|
+
const stakeAddress = prev?.stakeAddress ?? open?.[0]?.stakeAddress ?? decoded.stakeAddress;
|
|
325
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAddresses).entries({
|
|
326
|
+
address,
|
|
327
|
+
stakeAddress,
|
|
328
|
+
addressType: prev?.addressType ?? decoded.type,
|
|
329
|
+
isScript: prev ? Boolean(prev.isScript) : decoded.isScript,
|
|
330
|
+
totalLovelace: total.toString(),
|
|
331
|
+
utxoCount: (open ?? []).length,
|
|
332
|
+
firstSeenSlot: prev?.firstSeenSlot == null ? null : num(prev.firstSeenSlot),
|
|
333
|
+
lastActiveSlot: prev?.lastActiveSlot == null ? null : num(prev.lastActiveSlot),
|
|
334
|
+
}));
|
|
335
|
+
await tx.run(DELETE.from(cardano_1.LedgerAddressAssets).where({ address_address: address }));
|
|
336
|
+
const assetRows = [...assetSums].filter(([, q]) => q !== 0n).map(([unit, q]) => ({
|
|
337
|
+
address_address: address,
|
|
338
|
+
unit,
|
|
339
|
+
asset_quantity: q.toString(),
|
|
340
|
+
asset_policyId: unit.length >= 56 ? unit.slice(0, 56) : null,
|
|
341
|
+
asset_assetNameHex: unit.length > 56 ? unit.slice(56) : '',
|
|
342
|
+
asset_assetName: unit.length > 56 ? decodeAssetName(unit.slice(56)) : null,
|
|
343
|
+
}));
|
|
344
|
+
for (const rows of (0, collections_1.chunk)(assetRows, collections_1.IN_CHUNK))
|
|
345
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAddressAssets).entries(rows));
|
|
346
|
+
if (stakeAddress)
|
|
347
|
+
stakes.add(stakeAddress);
|
|
348
|
+
}
|
|
349
|
+
await recountLedgerAccounts(tx, [...stakes]);
|
|
350
|
+
}
|
|
351
|
+
/** Recount `LedgerAccounts` for the given stake keys from `LedgerAddresses`. */
|
|
352
|
+
async function recountLedgerAccounts(tx, stakeAddresses) {
|
|
353
|
+
for (const stakeChunk of (0, collections_1.chunk)(stakeAddresses, collections_1.IN_CHUNK)) {
|
|
354
|
+
const [addrRows, existing] = await Promise.all([
|
|
355
|
+
tx.run(SELECT.from(cardano_1.LedgerAddresses).columns('stakeAddress', 'totalLovelace', 'utxoCount')
|
|
356
|
+
.where({ stakeAddress: { in: stakeChunk } })),
|
|
357
|
+
tx.run(SELECT.from(cardano_1.LedgerAccounts).where({ stakeAddress: { in: stakeChunk } })),
|
|
358
|
+
]);
|
|
359
|
+
const sums = new Map();
|
|
360
|
+
for (const r of addrRows ?? []) {
|
|
361
|
+
const k = String(r.stakeAddress);
|
|
362
|
+
const s = sums.get(k) ?? { lovelace: 0n, addresses: 0, utxos: 0 };
|
|
363
|
+
s.lovelace += big(r.totalLovelace);
|
|
364
|
+
s.addresses += 1;
|
|
365
|
+
s.utxos += num(r.utxoCount);
|
|
366
|
+
sums.set(k, s);
|
|
367
|
+
}
|
|
368
|
+
const byStake = new Map((existing ?? []).map(e => [String(e.stakeAddress), e]));
|
|
369
|
+
const rows = stakeChunk.map((stakeAddress) => {
|
|
370
|
+
const s = sums.get(stakeAddress) ?? { lovelace: 0n, addresses: 0, utxos: 0 };
|
|
371
|
+
const prev = byStake.get(stakeAddress);
|
|
372
|
+
return {
|
|
373
|
+
stakeAddress,
|
|
374
|
+
controlledAmount: s.lovelace.toString(),
|
|
375
|
+
addressCount: s.addresses,
|
|
376
|
+
utxoCount: s.utxos,
|
|
377
|
+
lastActiveSlot: prev?.lastActiveSlot == null ? null : num(prev.lastActiveSlot),
|
|
378
|
+
};
|
|
379
|
+
});
|
|
380
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAccounts).entries(rows));
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
//# sourceMappingURL=ledger-state.js.map
|
|
@@ -51,6 +51,27 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
|
|
|
51
51
|
tipHeight : String;
|
|
52
52
|
syncProgress : String;
|
|
53
53
|
consecutiveErrors : Integer;
|
|
54
|
+
// crawler-fed ledger state (crawler.utxoSet): snapshot anchor + validity
|
|
55
|
+
utxoSet : UtxoSetStatus;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
@title : 'UTxO Set Status'
|
|
59
|
+
@description: 'State of the crawler-maintained UTxO set (crawler.utxoSet)'
|
|
60
|
+
type UtxoSetStatus {
|
|
61
|
+
enabled : Boolean; // crawler.utxoSet configured
|
|
62
|
+
status : String; // none | importing | active | invalid
|
|
63
|
+
anchorSlot : String; // null until imported
|
|
64
|
+
anchorHash : String;
|
|
65
|
+
importedAt : Timestamp;
|
|
66
|
+
error : String; // why invalid
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
@title : 'UTxO Set Import Result'
|
|
70
|
+
type UtxoSetImportResult {
|
|
71
|
+
accepted : Boolean;
|
|
72
|
+
anchorSlot : String;
|
|
73
|
+
anchorHash : String;
|
|
74
|
+
message : String;
|
|
54
75
|
}
|
|
55
76
|
|
|
56
77
|
@title : 'Get Crawler Status'
|
|
@@ -107,4 +128,9 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
|
|
|
107
128
|
@description: 'Start/restart the crawler from the persisted cursor using the configured source.'
|
|
108
129
|
@requires : 'Admin'
|
|
109
130
|
action resumeCrawler() returns Boolean;
|
|
131
|
+
|
|
132
|
+
@title : 'Import UTxO Set'
|
|
133
|
+
@description: 'One-off import of the UTxO set that anchors crawler.utxoSet. Pause the crawler first. source=ogmios acquires the set at the crawler cursor (crawl must be at the tip); source=file loads a cardano-cli query utxo --whole-utxo dump (.json, or .ndjson from jq -c to_entries[]) taken at anchorSlot/anchorHash. Runs in the background; progress via getStatus().utxoSet.'
|
|
134
|
+
@requires : 'Admin'
|
|
135
|
+
action importUtxoSet(source: String, filePath: String, anchorSlot: Integer64, anchorHash: String) returns UtxoSetImportResult;
|
|
110
136
|
}
|
|
@@ -8,9 +8,21 @@ const backend_request_handler_1 = require("./utils/backend-request-handler");
|
|
|
8
8
|
const errors_1 = require("./utils/errors");
|
|
9
9
|
const crawler_1 = require("./blockchain/crawler");
|
|
10
10
|
const sync_state_1 = require("./blockchain/crawler/sync-state");
|
|
11
|
+
const utxo_set_import_1 = require("./blockchain/crawler/utxo-set-import");
|
|
12
|
+
const validators_1 = require("./utils/validators");
|
|
11
13
|
const server_1 = require("./server");
|
|
12
14
|
const liveness_1 = require("./utils/liveness");
|
|
13
15
|
const logger = cds_1.default.log('CardanoIndexerService');
|
|
16
|
+
/** One import at a time per process; the promise is only used as the busy flag. */
|
|
17
|
+
let utxoSetImportInFlight = null;
|
|
18
|
+
function utxoSetConfigured() {
|
|
19
|
+
try {
|
|
20
|
+
return Boolean((0, server_1.loadCrawlerConfigFromEnv)()?.utxoSet);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
14
26
|
/**
|
|
15
27
|
* CardanoIndexerService handlers — thin control/observability surface over the crawler
|
|
16
28
|
* singleton (srv/blockchain/crawler). Engine logic lives there; this only reads the
|
|
@@ -37,6 +49,65 @@ module.exports = (srv) => {
|
|
|
37
49
|
tipHeight: String(tipHeight),
|
|
38
50
|
syncProgress: progress.toFixed(2),
|
|
39
51
|
consecutiveErrors: cursor?.consecutiveErrors ?? 0,
|
|
52
|
+
utxoSet: {
|
|
53
|
+
enabled: utxoSetConfigured(),
|
|
54
|
+
status: utxoSetImportInFlight ? 'importing' : (cursor?.utxoSet?.status ?? 'none'),
|
|
55
|
+
anchorSlot: cursor?.utxoSet?.anchorSlot == null ? null : String(cursor.utxoSet.anchorSlot),
|
|
56
|
+
anchorHash: cursor?.utxoSet?.anchorHash ?? null,
|
|
57
|
+
importedAt: cursor?.utxoSet?.importedAt ?? null,
|
|
58
|
+
error: cursor?.utxoSet?.error ?? null,
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
// importUtxoSet — one-off snapshot import that anchors crawler.utxoSet. Validation first,
|
|
64
|
+
// then the import runs detached (mainnet takes a while); progress via getStatus().utxoSet.
|
|
65
|
+
srv.on('importUtxoSet', async (req) => {
|
|
66
|
+
const data = (req.data ?? {});
|
|
67
|
+
const source = data.source === 'file' || data.source === 'ogmios' ? data.source : null;
|
|
68
|
+
if (!source)
|
|
69
|
+
return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'source must be "ogmios" or "file"', 'source');
|
|
70
|
+
if (source === 'file' && !data.filePath)
|
|
71
|
+
return (0, errors_1.rejectMissing)(req, 'importUtxoSet', 'filePath');
|
|
72
|
+
const anchorGiven = data.anchorSlot != null || !!data.anchorHash;
|
|
73
|
+
if (source === 'file' && !anchorGiven) {
|
|
74
|
+
return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'source "file" needs anchorSlot + anchorHash: the tip at dump time', 'anchorSlot');
|
|
75
|
+
}
|
|
76
|
+
if (anchorGiven && (data.anchorSlot == null || !Number.isInteger(Number(data.anchorSlot)) || !(0, validators_1.isBlockHash)(data.anchorHash))) {
|
|
77
|
+
return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'anchorSlot must be an integer and anchorHash a 64-hex block hash', 'anchorHash');
|
|
78
|
+
}
|
|
79
|
+
if ((0, crawler_1.isCrawlerRunning)())
|
|
80
|
+
return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'Crawler is running in this process — pauseCrawler first');
|
|
81
|
+
if (utxoSetImportInFlight)
|
|
82
|
+
return (0, errors_1.rejectInvalid)(req, 'importUtxoSet', 'A UTxO set import is already running');
|
|
83
|
+
return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
|
|
84
|
+
const cursor = await (0, sync_state_1.readCursor)(db);
|
|
85
|
+
if (!cursor)
|
|
86
|
+
throw new errors_1.TransactionValidationError('No crawler cursor yet — start the crawler once before importing.');
|
|
87
|
+
if ((0, sync_state_1.isCrawlerLeaseActive)(cursor))
|
|
88
|
+
throw new errors_1.TransactionValidationError('Crawler is running (active lease) — pauseCrawler first.');
|
|
89
|
+
const anchor = anchorGiven
|
|
90
|
+
? { slot: Number(data.anchorSlot), hash: String(data.anchorHash).toLowerCase() }
|
|
91
|
+
: { slot: cursor.lastSlot, hash: cursor.lastBlockHash ?? '' };
|
|
92
|
+
if (!anchor.hash)
|
|
93
|
+
throw new errors_1.TransactionValidationError('Cursor has no block hash yet — pass anchorSlot + anchorHash.');
|
|
94
|
+
if (cursor.lastSlot > anchor.slot) {
|
|
95
|
+
throw new errors_1.TransactionValidationError(`Crawler cursor (slot ${cursor.lastSlot}) is past the anchor (slot ${anchor.slot}) — dump the set at or after the cursor.`);
|
|
96
|
+
}
|
|
97
|
+
utxoSetImportInFlight = (0, utxo_set_import_1.importUtxoSet)({
|
|
98
|
+
source, filePath: data.filePath, anchor,
|
|
99
|
+
client: (0, server_1.getCardanoClient)(), indexer: (0, server_1.getCardanoIndexer)(),
|
|
100
|
+
onProgress: (n) => { if (n % 100_000 === 0)
|
|
101
|
+
logger.info(`UTxO set import: ${n} entries`); },
|
|
102
|
+
})
|
|
103
|
+
.then((r) => logger.info(`UTxO set import done: ${r.utxos} entries at ${r.anchor.slot}/${r.anchor.hash}`))
|
|
104
|
+
.catch((err) => logger.error(`UTxO set import failed: ${err instanceof Error ? err.message : String(err)}`))
|
|
105
|
+
.finally(() => { utxoSetImportInFlight = null; });
|
|
106
|
+
return {
|
|
107
|
+
accepted: true,
|
|
108
|
+
anchorSlot: String(anchor.slot),
|
|
109
|
+
anchorHash: anchor.hash,
|
|
110
|
+
message: `UTxO set import started (source=${source}); poll getStatus().utxoSet, then resumeCrawler.`,
|
|
40
111
|
};
|
|
41
112
|
});
|
|
42
113
|
});
|
package/srv/cardano-service.cds
CHANGED
|
@@ -107,6 +107,41 @@ service CardanoODataService @(impl: './cardano-service') {
|
|
|
107
107
|
@description: 'Projection for Transaction Output Assets'
|
|
108
108
|
entity TransactionOutputAssets as projection on db.TransactionOutputAssets;
|
|
109
109
|
|
|
110
|
+
@readonly
|
|
111
|
+
@title : 'Transaction Certificates'
|
|
112
|
+
@description: 'Projection for Transaction Certificates (crawler-fed, crawler.certificates)'
|
|
113
|
+
entity TransactionCertificates as projection on db.TransactionCertificates;
|
|
114
|
+
|
|
115
|
+
@readonly
|
|
116
|
+
@title : 'Transaction Withdrawals'
|
|
117
|
+
@description: 'Projection for Transaction Withdrawals (crawler-fed, crawler.certificates)'
|
|
118
|
+
entity TransactionWithdrawals as projection on db.TransactionWithdrawals;
|
|
119
|
+
|
|
120
|
+
@readonly
|
|
121
|
+
@title : 'Ledger UTxOs'
|
|
122
|
+
@description: 'Crawler-maintained UTxO set (crawler.utxoSet); unspent while spentTxHash is null'
|
|
123
|
+
entity LedgerUTxOs as projection on db.LedgerUTxOs;
|
|
124
|
+
|
|
125
|
+
@readonly
|
|
126
|
+
@title : 'Ledger UTxO Assets'
|
|
127
|
+
@description: 'Native assets of a LedgerUTxOs row'
|
|
128
|
+
entity LedgerUTxOAssets as projection on db.LedgerUTxOAssets;
|
|
129
|
+
|
|
130
|
+
@readonly
|
|
131
|
+
@title : 'Ledger Addresses'
|
|
132
|
+
@description: 'Per-address balances from the crawler-maintained UTxO set (crawler.utxoSet)'
|
|
133
|
+
entity LedgerAddresses as projection on db.LedgerAddresses;
|
|
134
|
+
|
|
135
|
+
@readonly
|
|
136
|
+
@title : 'Ledger Address Assets'
|
|
137
|
+
@description: 'Native-asset balances per address (crawler.utxoSet)'
|
|
138
|
+
entity LedgerAddressAssets as projection on db.LedgerAddressAssets;
|
|
139
|
+
|
|
140
|
+
@readonly
|
|
141
|
+
@title : 'Ledger Accounts'
|
|
142
|
+
@description: 'Per-stake-key balances from the crawler-maintained UTxO set (crawler.utxoSet)'
|
|
143
|
+
entity LedgerAccounts as projection on db.LedgerAccounts;
|
|
144
|
+
|
|
110
145
|
@readonly
|
|
111
146
|
@title : 'Accounts'
|
|
112
147
|
@description: 'Projection for Accounts'
|
package/srv/server.js
CHANGED
|
@@ -78,6 +78,20 @@ let bootstrapError = null;
|
|
|
78
78
|
*/
|
|
79
79
|
async function initializeAppContext(config, protocolParams, hsmConfig) {
|
|
80
80
|
logger.debug('Initializing blockchain components...');
|
|
81
|
+
// Database first, on every start path: the standalone served hook and the
|
|
82
|
+
// plugin's initializeFromConfig both come through here (rc.17 had these in
|
|
83
|
+
// initializeFromConfig only, so the standalone image never ran them).
|
|
84
|
+
// ORDER BY on Postgres without a NULLS clause for key / NOT NULL columns, so
|
|
85
|
+
// the indexes serve `$top` and `$orderby` reads (srv/utils/pg-order-nulls.ts).
|
|
86
|
+
(0, pg_order_nulls_1.installPostgresOrderNulls)();
|
|
87
|
+
// The secondary indexes the model cannot declare (srv/utils/db-indexes.ts):
|
|
88
|
+
// idempotent, never fatal, before anything reads.
|
|
89
|
+
try {
|
|
90
|
+
await (0, db_indexes_1.ensureDbIndexes)();
|
|
91
|
+
}
|
|
92
|
+
catch (err) {
|
|
93
|
+
logger.warn('secondary indexes not ensured (non-fatal):', err);
|
|
94
|
+
}
|
|
81
95
|
// Create CardanoClient from configuration
|
|
82
96
|
const cardanoClient = new cardano_client_1.CardanoClient(config);
|
|
83
97
|
// Publish the active network for leaf utilities (e.g. network-aware validators)
|
|
@@ -182,17 +196,6 @@ async function initializeFromConfig(config, protocolParams, hsmConfig) {
|
|
|
182
196
|
return;
|
|
183
197
|
}
|
|
184
198
|
hsmConfigInstance = hsmConfig;
|
|
185
|
-
// ORDER BY on Postgres without a NULLS clause for key / NOT NULL columns, so
|
|
186
|
-
// the indexes below serve `$top` and `$orderby` reads (srv/utils/pg-order-nulls.ts).
|
|
187
|
-
(0, pg_order_nulls_1.installPostgresOrderNulls)();
|
|
188
|
-
// The secondary indexes the model cannot declare (srv/utils/db-indexes.ts):
|
|
189
|
-
// idempotent, never fatal, before anything reads.
|
|
190
|
-
try {
|
|
191
|
-
await (0, db_indexes_1.ensureDbIndexes)();
|
|
192
|
-
}
|
|
193
|
-
catch (err) {
|
|
194
|
-
logger.warn('secondary indexes not ensured (non-fatal):', err);
|
|
195
|
-
}
|
|
196
199
|
try {
|
|
197
200
|
appContext = await initializeAppContext(config, protocolParams, hsmConfig);
|
|
198
201
|
bootstrapError = null;
|
|
@@ -441,9 +444,14 @@ function loadCrawlerConfigFromEnv() {
|
|
|
441
444
|
}
|
|
442
445
|
const assetEnrichRate = crawlerInteger(c.assetEnrichRate ?? process_1.env.CRAWLER_ASSET_ENRICH_RATE, 'CRAWLER_ASSET_ENRICH_RATE', CRAWLER_LIMITS.assetEnrichRate.min, CRAWLER_LIMITS.assetEnrichRate.max, 2);
|
|
443
446
|
const epochSnapshots = crawlerBoolean(c.epochSnapshots ?? process_1.env.CRAWLER_EPOCH_SNAPSHOTS, 'CRAWLER_EPOCH_SNAPSHOTS', false);
|
|
447
|
+
// Certificates + withdrawals: block content on Ogmios chain-sync and Koios, no extra request;
|
|
448
|
+
// opt-in like the other coverage knobs so an existing deployment's write volume does not change.
|
|
449
|
+
const certificates = crawlerBoolean(c.certificates ?? process_1.env.CRAWLER_CERTIFICATES, 'CRAWLER_CERTIFICATES', false);
|
|
450
|
+
// UTxO set: opt-in, and inert until a snapshot has been imported (importUtxoSet).
|
|
451
|
+
const utxoSet = crawlerBoolean(c.utxoSet ?? process_1.env.CRAWLER_UTXO_SET, 'CRAWLER_UTXO_SET', false);
|
|
444
452
|
return {
|
|
445
453
|
enabled, startSlot, startBlockHash, startHeight, source, batchSize, confirmationDepth, pollIntervalMs,
|
|
446
|
-
assetHistory, assetCatalogue, assetEnrichRate, epochSnapshots,
|
|
454
|
+
assetHistory, assetCatalogue, assetEnrichRate, epochSnapshots, certificates, utxoSet,
|
|
447
455
|
};
|
|
448
456
|
}
|
|
449
457
|
/**
|
package/srv/utils/db-indexes.js
CHANGED
|
@@ -63,6 +63,18 @@ exports.DB_INDEXES = Object.freeze([
|
|
|
63
63
|
{ name: 'odatano_cardano_dreps_drepid', table: 'odatano_cardano_Dreps', columns: 'drepId' },
|
|
64
64
|
// agent token lane: one lookup by token hash per request
|
|
65
65
|
{ name: 'odatano_cardano_cardanoagentgrants_token', table: 'odatano_cardano_CardanoAgentGrants', columns: 'tokenHash' },
|
|
66
|
+
// crawler-fed ledger state: "who spent this output" and delegation per stake key / pool / DRep
|
|
67
|
+
{ name: 'odatano_cardano_transactioninputs_spent', table: 'odatano_cardano_TransactionInputs', columns: 'spentTxHash, spentOutputIndex' },
|
|
68
|
+
{ name: 'odatano_cardano_transactioncertificates_stake', table: 'odatano_cardano_TransactionCertificates', columns: 'stakeAddress' },
|
|
69
|
+
{ name: 'odatano_cardano_transactioncertificates_pool', table: 'odatano_cardano_TransactionCertificates', columns: 'poolId' },
|
|
70
|
+
{ name: 'odatano_cardano_transactioncertificates_drep', table: 'odatano_cardano_TransactionCertificates', columns: 'drepId' },
|
|
71
|
+
{ name: 'odatano_cardano_transactionwithdrawals_stake', table: 'odatano_cardano_TransactionWithdrawals', columns: 'stakeAddress' },
|
|
72
|
+
// crawler-fed UTxO set: open rows per address, "who spent", stake-key rollups, asset holders
|
|
73
|
+
{ name: 'odatano_cardano_ledgerutxos_address', table: 'odatano_cardano_LedgerUTxOs', columns: 'address, spentTxHash' },
|
|
74
|
+
{ name: 'odatano_cardano_ledgerutxos_spent', table: 'odatano_cardano_LedgerUTxOs', columns: 'spentTxHash' },
|
|
75
|
+
{ name: 'odatano_cardano_ledgeraddresses_stake', table: 'odatano_cardano_LedgerAddresses', columns: 'stakeAddress' },
|
|
76
|
+
{ name: 'odatano_cardano_ledgerutxoassets_unit', table: 'odatano_cardano_LedgerUTxOAssets', columns: 'unit' },
|
|
77
|
+
{ name: 'odatano_cardano_ledgeraddressassets_unit', table: 'odatano_cardano_LedgerAddressAssets', columns: 'unit' },
|
|
66
78
|
]);
|
|
67
79
|
/** The statement for one entry; exported so tests pin the shape. */
|
|
68
80
|
function indexStatement(spec, kind = 'sqlite') {
|