@odatano/core 2.0.0-rc.18 → 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 +6 -1
- 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
|
@@ -444,9 +444,14 @@ function loadCrawlerConfigFromEnv() {
|
|
|
444
444
|
}
|
|
445
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);
|
|
446
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);
|
|
447
452
|
return {
|
|
448
453
|
enabled, startSlot, startBlockHash, startHeight, source, batchSize, confirmationDepth, pollIntervalMs,
|
|
449
|
-
assetHistory, assetCatalogue, assetEnrichRate, epochSnapshots,
|
|
454
|
+
assetHistory, assetCatalogue, assetEnrichRate, epochSnapshots, certificates, utxoSet,
|
|
450
455
|
};
|
|
451
456
|
}
|
|
452
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') {
|
package/srv/utils/mappers.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Transaction as TransactionProviderData, Address as AddressProviderData, UTxO as UtxosProviderData, TxInputLine as TxInputProviderData, TxOutputLine as TxOutputProviderData, Amount as AmountProviderData, NetworkInformation as NetworkInfoProviderData, BlockData as BlockProviderData, EpochData as EpochProviderData, MetadataLabelTx as MetadataLabelTxProviderData, PoolData as PoolProviderData, DrepData as DrepProviderData, AccountData as AccountProviderData, AssetInfo as AssetInfoProviderData, AssetHistoryEntry as AssetHistoryEntryProviderData, TxBuildResult as TransactionBuildResult, LedgerProtocolParameters as ProtocolParameters } from './types';
|
|
2
|
-
import { Address as AddressRow, AddressAsset as AddressAssetRow, AddressUTxO as AddressUTxORow, UTxOAsset as UTxOAssetRow, Transaction as TransactionRow, TransactionInput as TransactionInputRow, TransactionInputAsset as TransactionInputAssetRow, TransactionOutput as TransactionOutputRow, TransactionOutputAsset as TransactionOutputAssetRow, NetworkInformation as NetworkInfoRow, TransactionMetadata as TransactionMetadataRow, Block as BlockRow, Epoch as EpochRow, Pool as PoolRow, Drep as DrepRow, PoolEpochSnapshot as PoolEpochSnapshotRow, DrepEpochSnapshot as DrepEpochSnapshotRow, Asset as AssetRow, AssetHistory as AssetHistoryRow, Account as AccountRow, LedgerProtocolParameter as ProtocolParameterRow, AddressTransaction as AddressTransactionRow } from '#cds-models/CardanoODataService';
|
|
1
|
+
import { Transaction as TransactionProviderData, Address as AddressProviderData, UTxO as UtxosProviderData, TxInputLine as TxInputProviderData, TxOutputLine as TxOutputProviderData, TxCertificate as TxCertificateProviderData, TxWithdrawal as TxWithdrawalProviderData, Amount as AmountProviderData, NetworkInformation as NetworkInfoProviderData, BlockData as BlockProviderData, EpochData as EpochProviderData, MetadataLabelTx as MetadataLabelTxProviderData, PoolData as PoolProviderData, DrepData as DrepProviderData, AccountData as AccountProviderData, AssetInfo as AssetInfoProviderData, AssetHistoryEntry as AssetHistoryEntryProviderData, TxBuildResult as TransactionBuildResult, LedgerProtocolParameters as ProtocolParameters } from './types';
|
|
2
|
+
import { Address as AddressRow, AddressAsset as AddressAssetRow, AddressUTxO as AddressUTxORow, UTxOAsset as UTxOAssetRow, Transaction as TransactionRow, TransactionInput as TransactionInputRow, TransactionInputAsset as TransactionInputAssetRow, TransactionOutput as TransactionOutputRow, TransactionOutputAsset as TransactionOutputAssetRow, TransactionCertificate as TransactionCertificateRow, TransactionWithdrawal as TransactionWithdrawalRow, NetworkInformation as NetworkInfoRow, TransactionMetadata as TransactionMetadataRow, Block as BlockRow, Epoch as EpochRow, Pool as PoolRow, Drep as DrepRow, PoolEpochSnapshot as PoolEpochSnapshotRow, DrepEpochSnapshot as DrepEpochSnapshotRow, Asset as AssetRow, AssetHistory as AssetHistoryRow, Account as AccountRow, LedgerProtocolParameter as ProtocolParameterRow, AddressTransaction as AddressTransactionRow } from '#cds-models/CardanoODataService';
|
|
3
3
|
import type { TransactionBuild as TransactionBuildRow, TransactionBuildInput as TransactionBuildInputRow, TransactionBuildOutput as TransactionBuildOutputRow, TransactionSubmission as TransactionSubmissionRow, AddressTransactionBuild as AddressTransactionBuildRow } from '#cds-models/CardanoTransactionService';
|
|
4
4
|
import type { AddressSigningRequest as AddressSigningRequestRow } from '#cds-models/CardanoSignService';
|
|
5
5
|
import type { Request } from '@sap/cds';
|
|
@@ -29,6 +29,20 @@ export declare function mapTransactionInputs(txHash: string, txInputs: TxInputPr
|
|
|
29
29
|
* @returns {TransactionInputAssetRow[]} mapped transaction input asset rows
|
|
30
30
|
*/
|
|
31
31
|
export declare function mapTransactionInputAssets(txHash: string, inputs: TxInputProviderData[]): TransactionInputAssetRow[];
|
|
32
|
+
/**
|
|
33
|
+
* Map Transaction Certificates (crawler coverage, `crawler.certificates`).
|
|
34
|
+
* @param txHash transaction hash
|
|
35
|
+
* @param certificates normalized certificates from the source
|
|
36
|
+
* @returns {TransactionCertificateRow[]} one row per (certIndex, kind)
|
|
37
|
+
*/
|
|
38
|
+
export declare function mapTransactionCertificates(txHash: string, certificates: TxCertificateProviderData[]): TransactionCertificateRow[];
|
|
39
|
+
/**
|
|
40
|
+
* Map Transaction Withdrawals (crawler coverage, `crawler.certificates`).
|
|
41
|
+
* @param txHash transaction hash
|
|
42
|
+
* @param withdrawals normalized withdrawals from the source
|
|
43
|
+
* @returns {TransactionWithdrawalRow[]} one row per reward account
|
|
44
|
+
*/
|
|
45
|
+
export declare function mapTransactionWithdrawals(txHash: string, withdrawals: TxWithdrawalProviderData[]): TransactionWithdrawalRow[];
|
|
32
46
|
/**
|
|
33
47
|
* Map Transaction Outputs
|
|
34
48
|
* Converts provider transaction output data into TransactionOutputRow format
|
|
@@ -183,7 +197,7 @@ export declare const BARE_ASSET_STAMP = "1970-01-01T00:00:00.000Z";
|
|
|
183
197
|
* Map a bare asset row from an asset unit alone — everything derivable without a provider
|
|
184
198
|
* call: policyId, assetNameHex, the decoded name and the CIP-14 fingerprint. Used by the
|
|
185
199
|
* crawler to keep the `Assets` catalogue complete for units it meets in a block, at zero
|
|
186
|
-
* network cost (
|
|
200
|
+
* network cost (analytics coverage).
|
|
187
201
|
*
|
|
188
202
|
* The row is stamped as ALREADY EXPIRED (`validTo === validFrom`). That is deliberate: CAP's
|
|
189
203
|
* temporal filter hides it from OData reads, so the first keyed read still counts as a miss
|
|
@@ -337,4 +351,30 @@ export declare function computeCip14Fingerprint(policyIdHex: string, assetNameHe
|
|
|
337
351
|
* Header: 0x71 (mainnet, type 7 network 1) or 0x70 (testnet, type 7 network 0).
|
|
338
352
|
*/
|
|
339
353
|
export declare function scriptHashToEnterpriseAddress(scriptHashHex: string, network: 'mainnet' | 'preprod' | 'preview'): string;
|
|
354
|
+
/**
|
|
355
|
+
* Encode a stake credential as a bech32 reward account (stake address).
|
|
356
|
+
* Header: type nibble 0xe (key) / 0xf (script), network nibble 1 (mainnet) / 0 (testnets).
|
|
357
|
+
*/
|
|
358
|
+
export declare function credentialToStakeAddress(credentialHex: string, isScript: boolean, network: 'mainnet' | 'preprod' | 'preview'): string;
|
|
359
|
+
export interface DecodedAddress {
|
|
360
|
+
type: 'base' | 'pointer' | 'enterprise' | 'reward' | 'byron' | 'unknown';
|
|
361
|
+
/** Payment credential is a script hash. */
|
|
362
|
+
isScript: boolean;
|
|
363
|
+
/** Reward account (bech32) of a base address; null for every other type. */
|
|
364
|
+
stakeAddress: string | null;
|
|
365
|
+
/** Network nibble of the header (1 = mainnet, 0 = testnets); null when not a Shelley address. */
|
|
366
|
+
networkId: number | null;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Decode the Shelley address header (CIP-19) without a provider: type, script flag and,
|
|
370
|
+
* for base addresses, the embedded stake credential re-encoded as a reward account.
|
|
371
|
+
* Byron (base58) and anything unparseable come back as `byron` / `unknown` with no stake.
|
|
372
|
+
*/
|
|
373
|
+
export declare function decodeShelleyAddress(address: string): DecodedAddress;
|
|
374
|
+
/**
|
|
375
|
+
* Encode a DRep credential as a CIP-129 DRep ID (`drep1…`, 29 bytes).
|
|
376
|
+
* Header byte: high nibble 0x2 = DRep, low nibble 0x2 = key hash / 0x3 = script hash —
|
|
377
|
+
* the inverse of `decodeDrepId` in the Ogmios backend.
|
|
378
|
+
*/
|
|
379
|
+
export declare function credentialToDrepId(credentialHex: string, isScript: boolean): string;
|
|
340
380
|
//# sourceMappingURL=mappers.d.ts.map
|