@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,86 @@
|
|
|
1
|
+
import type { CardanoClient } from '../cardano-client';
|
|
2
|
+
import type { CardanoIndexer } from '../cardano-indexer';
|
|
3
|
+
import type { Amount } from '../../utils/types';
|
|
4
|
+
import { type LedgerAnchor } from '../ledger-state';
|
|
5
|
+
/**
|
|
6
|
+
* One-off import of the UTxO set at the anchor point that `crawler.utxoSet` builds on.
|
|
7
|
+
* Two sources:
|
|
8
|
+
*
|
|
9
|
+
* - `ogmios`: `queryLedgerState/utxo` for the whole set, acquired at the crawler's
|
|
10
|
+
* cursor point (which must lie inside the node's volatile window, i.e. the crawl is at
|
|
11
|
+
* the tip). Fine on preview/preprod; on mainnet the whole-set query is memory-heavy on
|
|
12
|
+
* the node, use a file.
|
|
13
|
+
* - `file`: a `cardano-cli query utxo --whole-utxo --out-file` dump. `.json` is parsed
|
|
14
|
+
* whole (small networks); `.ndjson` / `.jsonl` is streamed line by line, one entry per
|
|
15
|
+
* line as `jq -c 'to_entries[]'` emits it (`{"key":"tx#ix","value":{…}}`) or as a
|
|
16
|
+
* one-key object. The anchor is the tip at dump time (`cardano-cli query tip` before
|
|
17
|
+
* and after; same hash = valid anchor).
|
|
18
|
+
*
|
|
19
|
+
* Preconditions: the crawler is paused (no active lease) and its cursor is not past the
|
|
20
|
+
* anchor — blocks between cursor and anchor are crawled but not applied, blocks after it
|
|
21
|
+
* are. The tables are truncated first, so a re-import is always a full one.
|
|
22
|
+
*/
|
|
23
|
+
export declare class UtxoSetImportError extends Error {
|
|
24
|
+
constructor(message: string);
|
|
25
|
+
}
|
|
26
|
+
/** The cursor lease went to someone else: nothing more may be written, not even `invalid`. */
|
|
27
|
+
export declare class UtxoSetLeaseLostError extends UtxoSetImportError {
|
|
28
|
+
constructor(message?: string);
|
|
29
|
+
}
|
|
30
|
+
export interface UtxoSetEntry {
|
|
31
|
+
txHash: string;
|
|
32
|
+
outputIndex: number;
|
|
33
|
+
address: string;
|
|
34
|
+
amount: Amount[];
|
|
35
|
+
dataHash?: string | null;
|
|
36
|
+
inlineDatum?: string | null;
|
|
37
|
+
referenceScriptHash?: string | null;
|
|
38
|
+
}
|
|
39
|
+
export interface UtxoSetImportOptions {
|
|
40
|
+
source: 'ogmios' | 'file';
|
|
41
|
+
filePath?: string;
|
|
42
|
+
anchor: LedgerAnchor;
|
|
43
|
+
client: CardanoClient;
|
|
44
|
+
indexer: CardanoIndexer;
|
|
45
|
+
/** Rows per write transaction. */
|
|
46
|
+
batchSize?: number;
|
|
47
|
+
onProgress?: (imported: number) => void;
|
|
48
|
+
}
|
|
49
|
+
export interface UtxoSetImportResult {
|
|
50
|
+
utxos: number;
|
|
51
|
+
anchor: LedgerAnchor;
|
|
52
|
+
}
|
|
53
|
+
/** `cardano-cli query utxo` value: `{ lovelace: n, [policyId]: { [assetNameHex]: qty } }`. */
|
|
54
|
+
export interface CliUtxoValue {
|
|
55
|
+
address: string;
|
|
56
|
+
value: Record<string, number | string | Record<string, number | string>>;
|
|
57
|
+
datumhash?: string | null;
|
|
58
|
+
datumHash?: string | null;
|
|
59
|
+
inlineDatumRaw?: string | null;
|
|
60
|
+
referenceScript?: unknown;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* `JSON.parse` for a cardano-cli dump that keeps every integer exact. The cli prints
|
|
64
|
+
* quantities as JSON numbers; a token supply above 2^53 would otherwise be rounded before
|
|
65
|
+
* it ever reaches `String()`. A small scanner quotes every integer literal that sits
|
|
66
|
+
* OUTSIDE a string (string contents, escapes included, pass through untouched), so the
|
|
67
|
+
* value arrives as a string — the entry parser stringifies anyway. Floats keep their JSON
|
|
68
|
+
* meaning; a cli dump has none in value position.
|
|
69
|
+
*/
|
|
70
|
+
export declare function parseJsonLossless<T = unknown>(text: string): T;
|
|
71
|
+
/** Parse one `"txHash#index": {…}` entry of a cardano-cli dump; null when malformed. */
|
|
72
|
+
export declare function parseCliUtxoEntry(key: string, value: CliUtxoValue | null | undefined): UtxoSetEntry | null;
|
|
73
|
+
/** Stream a cardano-cli dump. See the module doc for the accepted layouts. */
|
|
74
|
+
export declare function readUtxoSetFile(filePath: string): AsyncGenerator<UtxoSetEntry>;
|
|
75
|
+
/**
|
|
76
|
+
* The three aggregate statements that derive the running sums from the imported rows.
|
|
77
|
+
* Plain SQL because millions of addresses do not fit an in-memory map and a per-row
|
|
78
|
+
* UPSERT would take hours; the syntax is the portable subset (sqlite, PostgreSQL, HANA).
|
|
79
|
+
*/
|
|
80
|
+
export declare function aggregateStatements(): string[];
|
|
81
|
+
/**
|
|
82
|
+
* Run the import. Throws `UtxoSetImportError` on a precondition failure before anything is
|
|
83
|
+
* written; a failure mid-way leaves the set marked `invalid` (never half-`active`).
|
|
84
|
+
*/
|
|
85
|
+
export declare function importUtxoSet(opts: UtxoSetImportOptions): Promise<UtxoSetImportResult>;
|
|
86
|
+
//# sourceMappingURL=utxo-set-import.d.ts.map
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.UtxoSetLeaseLostError = exports.UtxoSetImportError = void 0;
|
|
7
|
+
exports.parseJsonLossless = parseJsonLossless;
|
|
8
|
+
exports.parseCliUtxoEntry = parseCliUtxoEntry;
|
|
9
|
+
exports.readUtxoSetFile = readUtxoSetFile;
|
|
10
|
+
exports.aggregateStatements = aggregateStatements;
|
|
11
|
+
exports.importUtxoSet = importUtxoSet;
|
|
12
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
13
|
+
const node_fs_1 = require("node:fs");
|
|
14
|
+
const promises_1 = require("node:fs/promises");
|
|
15
|
+
const node_readline_1 = require("node:readline");
|
|
16
|
+
const ledger_state_1 = require("../ledger-state");
|
|
17
|
+
const sync_state_1 = require("./sync-state");
|
|
18
|
+
const cardano_1 = require("#cds-models/odatano/cardano");
|
|
19
|
+
const collections_1 = require("../../utils/collections");
|
|
20
|
+
const { UPSERT, DELETE } = cds_1.default.ql;
|
|
21
|
+
const logger = cds_1.default.log('LedgerState');
|
|
22
|
+
/**
|
|
23
|
+
* One-off import of the UTxO set at the anchor point that `crawler.utxoSet` builds on.
|
|
24
|
+
* Two sources:
|
|
25
|
+
*
|
|
26
|
+
* - `ogmios`: `queryLedgerState/utxo` for the whole set, acquired at the crawler's
|
|
27
|
+
* cursor point (which must lie inside the node's volatile window, i.e. the crawl is at
|
|
28
|
+
* the tip). Fine on preview/preprod; on mainnet the whole-set query is memory-heavy on
|
|
29
|
+
* the node, use a file.
|
|
30
|
+
* - `file`: a `cardano-cli query utxo --whole-utxo --out-file` dump. `.json` is parsed
|
|
31
|
+
* whole (small networks); `.ndjson` / `.jsonl` is streamed line by line, one entry per
|
|
32
|
+
* line as `jq -c 'to_entries[]'` emits it (`{"key":"tx#ix","value":{…}}`) or as a
|
|
33
|
+
* one-key object. The anchor is the tip at dump time (`cardano-cli query tip` before
|
|
34
|
+
* and after; same hash = valid anchor).
|
|
35
|
+
*
|
|
36
|
+
* Preconditions: the crawler is paused (no active lease) and its cursor is not past the
|
|
37
|
+
* anchor — blocks between cursor and anchor are crawled but not applied, blocks after it
|
|
38
|
+
* are. The tables are truncated first, so a re-import is always a full one.
|
|
39
|
+
*/
|
|
40
|
+
class UtxoSetImportError extends Error {
|
|
41
|
+
constructor(message) {
|
|
42
|
+
super(message);
|
|
43
|
+
this.name = 'UtxoSetImportError';
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
exports.UtxoSetImportError = UtxoSetImportError;
|
|
47
|
+
/** The cursor lease went to someone else: nothing more may be written, not even `invalid`. */
|
|
48
|
+
class UtxoSetLeaseLostError extends UtxoSetImportError {
|
|
49
|
+
constructor(message = 'Lost the cursor lease during the import — aborted without further writes.') {
|
|
50
|
+
super(message);
|
|
51
|
+
this.name = 'UtxoSetLeaseLostError';
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
exports.UtxoSetLeaseLostError = UtxoSetLeaseLostError;
|
|
55
|
+
/**
|
|
56
|
+
* `JSON.parse` for a cardano-cli dump that keeps every integer exact. The cli prints
|
|
57
|
+
* quantities as JSON numbers; a token supply above 2^53 would otherwise be rounded before
|
|
58
|
+
* it ever reaches `String()`. A small scanner quotes every integer literal that sits
|
|
59
|
+
* OUTSIDE a string (string contents, escapes included, pass through untouched), so the
|
|
60
|
+
* value arrives as a string — the entry parser stringifies anyway. Floats keep their JSON
|
|
61
|
+
* meaning; a cli dump has none in value position.
|
|
62
|
+
*/
|
|
63
|
+
function parseJsonLossless(text) {
|
|
64
|
+
// One native pass: a string literal is copied as is, an integer literal outside a string is
|
|
65
|
+
// quoted, floats keep their JSON meaning (a cli dump has none in value position).
|
|
66
|
+
const rewritten = text.replace(/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g, (m) => (m[0] === '"' || !/^-?\d+$/.test(m) ? m : `"${m}"`));
|
|
67
|
+
return JSON.parse(rewritten);
|
|
68
|
+
}
|
|
69
|
+
/** Parse one `"txHash#index": {…}` entry of a cardano-cli dump; null when malformed. */
|
|
70
|
+
function parseCliUtxoEntry(key, value) {
|
|
71
|
+
const m = /^([0-9a-fA-F]{64})#(\d+)$/.exec(key ?? '');
|
|
72
|
+
if (!m || !value || typeof value.address !== 'string')
|
|
73
|
+
return null;
|
|
74
|
+
const amount = [];
|
|
75
|
+
const v = value.value ?? {};
|
|
76
|
+
for (const [k, q] of Object.entries(v)) {
|
|
77
|
+
if (k === 'lovelace') {
|
|
78
|
+
amount.push({ unit: 'lovelace', quantity: String(q) });
|
|
79
|
+
}
|
|
80
|
+
else if (q && typeof q === 'object') {
|
|
81
|
+
for (const [nameHex, qty] of Object.entries(q)) {
|
|
82
|
+
amount.push({ unit: `${k}${nameHex}`, quantity: String(qty) });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (!amount.some(a => a.unit === 'lovelace'))
|
|
87
|
+
amount.unshift({ unit: 'lovelace', quantity: '0' });
|
|
88
|
+
return {
|
|
89
|
+
txHash: m[1].toLowerCase(),
|
|
90
|
+
outputIndex: Number(m[2]),
|
|
91
|
+
address: value.address,
|
|
92
|
+
amount,
|
|
93
|
+
dataHash: value.datumhash ?? value.datumHash ?? null,
|
|
94
|
+
inlineDatum: typeof value.inlineDatumRaw === 'string' ? value.inlineDatumRaw : null,
|
|
95
|
+
// the cli prints the script itself, not its hash — resolved lazily, like every other path
|
|
96
|
+
referenceScriptHash: null,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/** Stream a cardano-cli dump. See the module doc for the accepted layouts. */
|
|
100
|
+
async function* readUtxoSetFile(filePath) {
|
|
101
|
+
if (/\.json$/i.test(filePath)) {
|
|
102
|
+
const parsed = parseJsonLossless(await (0, promises_1.readFile)(filePath, 'utf8'));
|
|
103
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
104
|
+
const entry = parseCliUtxoEntry(key, value);
|
|
105
|
+
if (entry)
|
|
106
|
+
yield entry;
|
|
107
|
+
}
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const rl = (0, node_readline_1.createInterface)({ input: (0, node_fs_1.createReadStream)(filePath, 'utf8'), crlfDelay: Infinity });
|
|
111
|
+
for await (const line of rl) {
|
|
112
|
+
const trimmed = line.trim();
|
|
113
|
+
if (!trimmed)
|
|
114
|
+
continue;
|
|
115
|
+
const obj = parseJsonLossless(trimmed);
|
|
116
|
+
if (typeof obj.key === 'string' && obj.value && typeof obj.value === 'object') {
|
|
117
|
+
const entry = parseCliUtxoEntry(obj.key, obj.value);
|
|
118
|
+
if (entry)
|
|
119
|
+
yield entry;
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
123
|
+
const entry = parseCliUtxoEntry(key, value);
|
|
124
|
+
if (entry)
|
|
125
|
+
yield entry;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async function* readFromOgmios(client, anchor) {
|
|
130
|
+
const backend = client.getLedgerStateBackend();
|
|
131
|
+
if (!backend) {
|
|
132
|
+
throw new UtxoSetImportError('No Ogmios backend available for source "ogmios" — configure one or import a cardano-cli file.');
|
|
133
|
+
}
|
|
134
|
+
const utxos = await backend.queryUtxoSetAt({ slot: anchor.slot, hash: anchor.hash });
|
|
135
|
+
for (const u of utxos) {
|
|
136
|
+
yield {
|
|
137
|
+
txHash: u.txHash,
|
|
138
|
+
outputIndex: u.outputIndex,
|
|
139
|
+
address: u.address,
|
|
140
|
+
amount: u.amount,
|
|
141
|
+
dataHash: u.datumHash ?? null,
|
|
142
|
+
inlineDatum: u.inlineDatum ?? null,
|
|
143
|
+
referenceScriptHash: u.scriptRef ?? null,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/** Table names as CAP creates them (dots → underscores), for the aggregate statements. */
|
|
148
|
+
const T = {
|
|
149
|
+
utxos: 'odatano_cardano_LedgerUTxOs',
|
|
150
|
+
utxoAssets: 'odatano_cardano_LedgerUTxOAssets',
|
|
151
|
+
addresses: 'odatano_cardano_LedgerAddresses',
|
|
152
|
+
addressAssets: 'odatano_cardano_LedgerAddressAssets',
|
|
153
|
+
accounts: 'odatano_cardano_LedgerAccounts',
|
|
154
|
+
};
|
|
155
|
+
/**
|
|
156
|
+
* The three aggregate statements that derive the running sums from the imported rows.
|
|
157
|
+
* Plain SQL because millions of addresses do not fit an in-memory map and a per-row
|
|
158
|
+
* UPSERT would take hours; the syntax is the portable subset (sqlite, PostgreSQL, HANA).
|
|
159
|
+
*/
|
|
160
|
+
function aggregateStatements() {
|
|
161
|
+
return [
|
|
162
|
+
`INSERT INTO ${T.addresses} (address, stakeAddress, addressType, isScript, totalLovelace, utxoCount, firstSeenSlot, lastActiveSlot) ` +
|
|
163
|
+
`SELECT address, MIN(stakeAddress), MIN(addressType), ` +
|
|
164
|
+
`CASE WHEN MAX(CASE WHEN isScript THEN 1 ELSE 0 END) = 1 THEN TRUE ELSE FALSE END, ` +
|
|
165
|
+
`SUM(lovelace), COUNT(*), NULL, NULL FROM ${T.utxos} GROUP BY address`,
|
|
166
|
+
`INSERT INTO ${T.addressAssets} (address_address, unit, asset_quantity, asset_policyId, asset_assetNameHex, asset_assetName) ` +
|
|
167
|
+
`SELECT u.address, a.unit, SUM(a.asset_quantity), MIN(a.asset_policyId), MIN(a.asset_assetNameHex), MIN(a.asset_assetName) ` +
|
|
168
|
+
`FROM ${T.utxoAssets} a JOIN ${T.utxos} u ON a.utxo_txHash = u.txHash AND a.utxo_outputIndex = u.outputIndex ` +
|
|
169
|
+
`GROUP BY u.address, a.unit`,
|
|
170
|
+
`INSERT INTO ${T.accounts} (stakeAddress, controlledAmount, addressCount, utxoCount, lastActiveSlot) ` +
|
|
171
|
+
`SELECT stakeAddress, SUM(totalLovelace), COUNT(*), SUM(utxoCount), NULL FROM ${T.addresses} ` +
|
|
172
|
+
`WHERE stakeAddress IS NOT NULL GROUP BY stakeAddress`,
|
|
173
|
+
];
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Run the import. Throws `UtxoSetImportError` on a precondition failure before anything is
|
|
177
|
+
* written; a failure mid-way leaves the set marked `invalid` (never half-`active`).
|
|
178
|
+
*/
|
|
179
|
+
async function importUtxoSet(opts) {
|
|
180
|
+
const { anchor, source } = opts;
|
|
181
|
+
const batchSize = opts.batchSize ?? 2000;
|
|
182
|
+
const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
|
|
183
|
+
if (!cursor)
|
|
184
|
+
throw new UtxoSetImportError('No crawler cursor yet — start the crawler once before importing.');
|
|
185
|
+
if ((0, sync_state_1.isCrawlerLeaseActive)(cursor))
|
|
186
|
+
throw new UtxoSetImportError('Crawler is running — pause it first (pauseCrawler).');
|
|
187
|
+
if (cursor.lastSlot > anchor.slot) {
|
|
188
|
+
throw new UtxoSetImportError(`Crawler cursor (slot ${cursor.lastSlot}) is past the anchor (slot ${anchor.slot}) — blocks after the anchor were ` +
|
|
189
|
+
'already crawled without a set to apply them to. Dump the set at or after the cursor.');
|
|
190
|
+
}
|
|
191
|
+
if (source === 'file' && !opts.filePath)
|
|
192
|
+
throw new UtxoSetImportError('source "file" needs filePath.');
|
|
193
|
+
// Cluster-wide exclusion: hold the cursor lease for the whole import. A crawler start on
|
|
194
|
+
// any instance (resumeCrawler, standby) and a second import are refused while it is held;
|
|
195
|
+
// renewed on a heartbeat, released in `finally`.
|
|
196
|
+
const leaseOwner = `import:${process.pid}:${Date.now().toString(36)}`;
|
|
197
|
+
const acquired = await cds_1.default.tx((tx) => (0, sync_state_1.tryAcquireImportLease)(tx, leaseOwner));
|
|
198
|
+
if (!acquired)
|
|
199
|
+
throw new UtxoSetImportError('Could not take the cursor lease — a crawler or another import holds it.');
|
|
200
|
+
let leaseLost = false;
|
|
201
|
+
const heartbeat = setInterval(() => {
|
|
202
|
+
cds_1.default.tx((tx) => (0, sync_state_1.renewImportLease)(tx, leaseOwner))
|
|
203
|
+
.then((ok) => { if (!ok)
|
|
204
|
+
leaseLost = true; })
|
|
205
|
+
.catch(() => { leaseLost = true; });
|
|
206
|
+
}, Math.max(1000, Math.floor(sync_state_1.CRAWLER_LEASE_TTL_MS / 3)));
|
|
207
|
+
heartbeat.unref();
|
|
208
|
+
/**
|
|
209
|
+
* Every write runs through here: the lease is re-taken INSIDE the transaction (an UPDATE
|
|
210
|
+
* conditioned on `leaseOwner = us`, verified by read-back), so a successor that took the
|
|
211
|
+
* lease between two batches makes this transaction fail before its writes commit. The
|
|
212
|
+
* heartbeat flag alone only knows what was true at the last tick.
|
|
213
|
+
*/
|
|
214
|
+
const writeTx = (fn) => cds_1.default.tx(async (tx) => {
|
|
215
|
+
if (leaseLost || !(await (0, sync_state_1.renewImportLease)(tx, leaseOwner)))
|
|
216
|
+
throw new UtxoSetLeaseLostError();
|
|
217
|
+
return fn(tx);
|
|
218
|
+
});
|
|
219
|
+
opts.indexer.setUtxoAnchor(null);
|
|
220
|
+
try {
|
|
221
|
+
await writeTx(async (tx) => {
|
|
222
|
+
await (0, sync_state_1.setUtxoSetState)(tx, { status: 'importing', anchorSlot: anchor.slot, anchorHash: anchor.hash, error: null, importedAt: null, appliedSlot: null });
|
|
223
|
+
await tx.run(DELETE.from(cardano_1.LedgerUTxOAssets));
|
|
224
|
+
await tx.run(DELETE.from(cardano_1.LedgerUTxOs));
|
|
225
|
+
await tx.run(DELETE.from(cardano_1.LedgerAddressAssets));
|
|
226
|
+
await tx.run(DELETE.from(cardano_1.LedgerAddresses));
|
|
227
|
+
await tx.run(DELETE.from(cardano_1.LedgerAccounts));
|
|
228
|
+
});
|
|
229
|
+
let imported = 0;
|
|
230
|
+
try {
|
|
231
|
+
const entries = source === 'ogmios' ? readFromOgmios(opts.client, anchor) : readUtxoSetFile(opts.filePath);
|
|
232
|
+
let rows = [];
|
|
233
|
+
let assets = [];
|
|
234
|
+
const flush = async () => {
|
|
235
|
+
if (!rows.length)
|
|
236
|
+
return;
|
|
237
|
+
const r = rows;
|
|
238
|
+
const a = assets;
|
|
239
|
+
rows = [];
|
|
240
|
+
assets = [];
|
|
241
|
+
await writeTx(async (tx) => {
|
|
242
|
+
for (const c of (0, collections_1.chunk)(r, collections_1.IN_CHUNK))
|
|
243
|
+
await tx.run(UPSERT.into(cardano_1.LedgerUTxOs).entries(c));
|
|
244
|
+
for (const c of (0, collections_1.chunk)(a, collections_1.IN_CHUNK))
|
|
245
|
+
await tx.run(UPSERT.into(cardano_1.LedgerUTxOAssets).entries(c));
|
|
246
|
+
});
|
|
247
|
+
imported += r.length;
|
|
248
|
+
opts.onProgress?.(imported);
|
|
249
|
+
};
|
|
250
|
+
for await (const e of entries) {
|
|
251
|
+
const built = (0, ledger_state_1.buildLedgerUtxoRows)(e, null);
|
|
252
|
+
rows.push(built.row);
|
|
253
|
+
assets.push(...built.assets);
|
|
254
|
+
if (rows.length >= batchSize)
|
|
255
|
+
await flush();
|
|
256
|
+
}
|
|
257
|
+
await flush();
|
|
258
|
+
// Aggregates + activation in ONE lease-checked transaction: the set can never be
|
|
259
|
+
// `active` with sums a successor's import has meanwhile truncated.
|
|
260
|
+
const importedAt = new Date().toISOString();
|
|
261
|
+
await writeTx(async (tx) => {
|
|
262
|
+
for (const sql of aggregateStatements())
|
|
263
|
+
await tx.run(sql);
|
|
264
|
+
await (0, sync_state_1.setUtxoSetState)(tx, { status: 'active', anchorSlot: anchor.slot, anchorHash: anchor.hash, importedAt, error: null });
|
|
265
|
+
});
|
|
266
|
+
opts.indexer.setUtxoAnchor(anchor);
|
|
267
|
+
logger.info(`UTxO set imported: ${imported} entries at anchor ${anchor.slot}/${anchor.hash} (source=${source})`);
|
|
268
|
+
return { utxos: imported, anchor };
|
|
269
|
+
}
|
|
270
|
+
catch (err) {
|
|
271
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
272
|
+
logger.error(`UTxO set import failed after ${imported} entries: ${message}`);
|
|
273
|
+
// Only the lease holder may write the failure state; after a takeover the row is the
|
|
274
|
+
// successor's and the truncated tables are its problem to fill.
|
|
275
|
+
if (!(err instanceof UtxoSetLeaseLostError)) {
|
|
276
|
+
await cds_1.default.tx(async (tx) => {
|
|
277
|
+
if (await (0, sync_state_1.renewImportLease)(tx, leaseOwner))
|
|
278
|
+
await (0, sync_state_1.setUtxoSetState)(tx, { status: 'invalid', error: message.slice(0, 500) });
|
|
279
|
+
}).catch(() => undefined);
|
|
280
|
+
}
|
|
281
|
+
throw err;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
finally {
|
|
285
|
+
clearInterval(heartbeat);
|
|
286
|
+
await cds_1.default.tx((tx) => (0, sync_state_1.releaseImportLease)(tx, leaseOwner)).catch(() => undefined);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
//# sourceMappingURL=utxo-set-import.js.map
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { Transaction as CapTransaction } from '@sap/cds';
|
|
2
|
+
import type { Amount, BlockData, Transaction as ProviderTransaction } from '../utils/types';
|
|
3
|
+
/**
|
|
4
|
+
* Crawler-fed ledger state (`crawler.utxoSet`): a UTxO set with
|
|
5
|
+
* per-address and per-stake-key running sums, maintained from the blocks the crawler
|
|
6
|
+
* already holds. Separate, non-temporal tables (`LedgerUTxOs`, `LedgerAddresses`,
|
|
7
|
+
* `LedgerAccounts`) so the lazy, provider-fed `Addresses` / `AddressUTxOs` path and its
|
|
8
|
+
* TTL semantics stay untouched.
|
|
9
|
+
*
|
|
10
|
+
* Correctness rests on an anchor: the set is imported once at a recent point
|
|
11
|
+
* (`utxo-set-import.ts`) and only blocks AFTER that point are applied here. A reorg past
|
|
12
|
+
* the anchor invalidates the set; a reorg after it is undone by `undoLedgerForTransactions`
|
|
13
|
+
* (reopen what the rolled-back blocks spent, drop what they created, recount the touched
|
|
14
|
+
* addresses from the open rows — the recount, not a mirror of the forward logic, is the
|
|
15
|
+
* undo). Everything runs inside the caller's block transaction.
|
|
16
|
+
*/
|
|
17
|
+
/** The point the imported UTxO set describes; blocks with slot > anchor.slot are applied. */
|
|
18
|
+
export interface LedgerAnchor {
|
|
19
|
+
slot: number;
|
|
20
|
+
hash: string;
|
|
21
|
+
}
|
|
22
|
+
export interface LedgerApplyResult {
|
|
23
|
+
created: number;
|
|
24
|
+
spent: number;
|
|
25
|
+
/** Consumed outpoints with no open row — a gap between snapshot and crawl, never expected. */
|
|
26
|
+
missing: number;
|
|
27
|
+
addresses: number;
|
|
28
|
+
}
|
|
29
|
+
/** DB row of `LedgerUTxOs` (flattened struct columns as CAP names them). */
|
|
30
|
+
export interface LedgerUtxoRow {
|
|
31
|
+
txHash: string;
|
|
32
|
+
outputIndex: number;
|
|
33
|
+
address: string;
|
|
34
|
+
stakeAddress: string | null;
|
|
35
|
+
addressType: string;
|
|
36
|
+
isScript: boolean;
|
|
37
|
+
lovelace: string;
|
|
38
|
+
createdSlot: number | null;
|
|
39
|
+
spentTxHash: string | null;
|
|
40
|
+
spentSlot: number | null;
|
|
41
|
+
utxo_dataHash: string | null;
|
|
42
|
+
utxo_inlineDatum: string | null;
|
|
43
|
+
utxo_referenceScriptHash: string | null;
|
|
44
|
+
hasAssets: boolean;
|
|
45
|
+
}
|
|
46
|
+
export interface LedgerUtxoAssetRow {
|
|
47
|
+
utxo_txHash: string;
|
|
48
|
+
utxo_outputIndex: number;
|
|
49
|
+
unit: string;
|
|
50
|
+
asset_quantity: string;
|
|
51
|
+
asset_policyId: string | null;
|
|
52
|
+
asset_assetNameHex: string | null;
|
|
53
|
+
asset_assetName: string | null;
|
|
54
|
+
}
|
|
55
|
+
/** Minimal output shape the row builder needs — shared by the block path and the import. */
|
|
56
|
+
export interface LedgerOutputLike {
|
|
57
|
+
txHash: string;
|
|
58
|
+
outputIndex: number;
|
|
59
|
+
address: string;
|
|
60
|
+
amount: Amount[];
|
|
61
|
+
dataHash?: string | null;
|
|
62
|
+
inlineDatum?: string | null;
|
|
63
|
+
referenceScriptHash?: string | null;
|
|
64
|
+
}
|
|
65
|
+
/** Build the `LedgerUTxOs` row (+ asset rows) for one output. */
|
|
66
|
+
export declare function buildLedgerUtxoRows(o: LedgerOutputLike, createdSlot: number | null): {
|
|
67
|
+
row: LedgerUtxoRow;
|
|
68
|
+
assets: LedgerUtxoAssetRow[];
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* Apply one block to the ledger tables. Caller guarantees `block.slot > anchor.slot`.
|
|
72
|
+
* Never throws for a missing outpoint (it is counted and logged); DB errors propagate so the
|
|
73
|
+
* block transaction rolls back as a whole.
|
|
74
|
+
*/
|
|
75
|
+
export declare function applyBlockToLedger(tx: CapTransaction, block: BlockData, txs: ProviderTransaction[]): Promise<LedgerApplyResult>;
|
|
76
|
+
/**
|
|
77
|
+
* Reorg undo for a set of rolled-back transactions: drop what they created, reopen what
|
|
78
|
+
* they spent, then recount every address either side touched from the open rows.
|
|
79
|
+
* @returns the recounted addresses
|
|
80
|
+
*/
|
|
81
|
+
export declare function undoLedgerForTransactions(tx: CapTransaction, txHashes: string[]): Promise<string[]>;
|
|
82
|
+
/**
|
|
83
|
+
* Recount running sums for the given addresses from their open UTxO rows, then the
|
|
84
|
+
* stake keys those addresses belong to. Also the repair path for a drifted sum.
|
|
85
|
+
*/
|
|
86
|
+
export declare function recountLedgerAddresses(tx: CapTransaction, addresses: string[]): Promise<void>;
|
|
87
|
+
/** Recount `LedgerAccounts` for the given stake keys from `LedgerAddresses`. */
|
|
88
|
+
export declare function recountLedgerAccounts(tx: CapTransaction, stakeAddresses: string[]): Promise<void>;
|
|
89
|
+
//# sourceMappingURL=ledger-state.d.ts.map
|