@odatano/core 2.0.0-rc.53 → 2.0.0-rc.54

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "2.0.0-rc.53",
3
+ "version": "2.0.0-rc.54",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
@@ -0,0 +1,15 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import { AssetHistory, AssetSupply } from '#cds-models/odatano/cardano';
3
+ type HistoryRow = Pick<AssetHistory, 'unit' | 'action' | 'quantity' | 'blockHeight'>;
4
+ /** The stored sums of one unit; undefined for a unit without counted rows. */
5
+ export declare function readAssetSupply(tx: CapTransaction, unit: string): Promise<AssetSupply | undefined>;
6
+ /** Height up to which AssetSupply is counted; null until computed. */
7
+ export declare function assetSupplyHeight(tx: CapTransaction): Promise<number | null>;
8
+ export declare function applyBlockAssetSupply(tx: CapTransaction, rows: HistoryRow[], height: number): Promise<void>;
9
+ export declare function undoAssetSupply(tx: CapTransaction, txHashes: string[]): Promise<void>;
10
+ export declare function lowerAssetSupplyHeight(tx: CapTransaction, forkHeight: number | null): Promise<void>;
11
+ /** Statements that rebuild AssetSupply from the AssetHistory rows up to `height`. Portable SQL. */
12
+ export declare function assetSupplyStatements(height: number): string[];
13
+ export declare function computeAssetSupply(tx: CapTransaction, height: number): Promise<void>;
14
+ export {};
15
+ //# sourceMappingURL=asset-supply.d.ts.map
@@ -0,0 +1,109 @@
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.readAssetSupply = readAssetSupply;
7
+ exports.assetSupplyHeight = assetSupplyHeight;
8
+ exports.applyBlockAssetSupply = applyBlockAssetSupply;
9
+ exports.undoAssetSupply = undoAssetSupply;
10
+ exports.lowerAssetSupplyHeight = lowerAssetSupplyHeight;
11
+ exports.assetSupplyStatements = assetSupplyStatements;
12
+ exports.computeAssetSupply = computeAssetSupply;
13
+ const cds_1 = __importDefault(require("@sap/cds"));
14
+ const cardano_1 = require("#cds-models/odatano/cardano");
15
+ const collections_1 = require("../utils/collections");
16
+ const sync_state_1 = require("./crawler/sync-state");
17
+ const { SELECT, UPSERT, UPDATE, DELETE } = cds_1.default.ql;
18
+ const big = (v) => (v == null || v === '' ? 0n : BigInt(String(v).split('.')[0]));
19
+ const signed = (r) => (r.action === 'burn' ? -1n : 1n) * big(r.quantity);
20
+ /** The stored sums of one unit; undefined for a unit without counted rows. */
21
+ async function readAssetSupply(tx, unit) {
22
+ return await tx.run(SELECT.one.from(cardano_1.AssetSupply_).where({ unit }));
23
+ }
24
+ /** Height up to which AssetSupply is counted; null until computed. */
25
+ async function assetSupplyHeight(tx) {
26
+ const row = await tx.run(SELECT.one.from(cardano_1.CardanoSyncState).columns('assetSupplyHeight').where({ ID: sync_state_1.SINGLETON_ID }));
27
+ return row?.assetSupplyHeight == null ? null : Number(row.assetSupplyHeight);
28
+ }
29
+ async function addToSupply(tx, rows, sign) {
30
+ const deltas = new Map();
31
+ for (const r of rows) {
32
+ const d = deltas.get(String(r.unit)) ?? { supply: 0n, count: 0 };
33
+ d.supply += sign * signed(r);
34
+ d.count += Number(sign);
35
+ deltas.set(String(r.unit), d);
36
+ }
37
+ for (const units of (0, collections_1.chunk)([...deltas.keys()], collections_1.IN_CHUNK)) {
38
+ const existing = await tx.run(SELECT.from(cardano_1.AssetSupply_).where({ unit: { in: units } }));
39
+ const byUnit = new Map((existing ?? []).map(e => [String(e.unit), e]));
40
+ const upserts = [];
41
+ const deletes = [];
42
+ for (const unit of units) {
43
+ const d = deltas.get(unit);
44
+ const prev = byUnit.get(unit);
45
+ const count = Number(prev?.mintOrBurnCount ?? 0) + d.count;
46
+ if (count <= 0)
47
+ deletes.push(unit);
48
+ else
49
+ upserts.push({ unit, totalSupply: (big(prev?.totalSupply) + d.supply).toString(), mintOrBurnCount: count });
50
+ }
51
+ if (upserts.length)
52
+ await tx.run(UPSERT.into(cardano_1.AssetSupply_).entries(upserts));
53
+ if (deletes.length)
54
+ await tx.run(DELETE.from(cardano_1.AssetSupply_).where({ unit: { in: deletes } }));
55
+ }
56
+ }
57
+ // Counts the mint and burn rows of one crawled block. A block at or below the height is
58
+ // already counted (a crawl repeated after a cursor reset) and changes nothing.
59
+ async function applyBlockAssetSupply(tx, rows, height) {
60
+ if (!rows.length)
61
+ return;
62
+ const counted = await assetSupplyHeight(tx);
63
+ if (counted == null || height <= counted)
64
+ return;
65
+ await addToSupply(tx, rows, 1n);
66
+ await tx.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ assetSupplyHeight: height }).where({ ID: sync_state_1.SINGLETON_ID }));
67
+ }
68
+ // Takes the rows of rolled-back transactions off the sums. Runs before they are deleted and
69
+ // before lowerAssetSupplyHeight, which ends the rollback.
70
+ async function undoAssetSupply(tx, txHashes) {
71
+ const counted = await assetSupplyHeight(tx);
72
+ if (counted == null || !txHashes.length)
73
+ return;
74
+ const rows = [];
75
+ for (const hashes of (0, collections_1.chunk)(txHashes, collections_1.IN_CHUNK)) {
76
+ const found = await tx.run(SELECT.from(cardano_1.AssetHistory).columns('unit', 'action', 'quantity', 'blockHeight').where({ txHash: { in: hashes } }));
77
+ rows.push(...(found ?? []).filter(r => r.blockHeight != null && Number(r.blockHeight) <= counted));
78
+ }
79
+ await addToSupply(tx, rows, -1n);
80
+ }
81
+ // Lowers the counted height to the fork, so the blocks of the new chain are counted.
82
+ // An unknown fork height clears it, and the next crawler start computes the sums again.
83
+ async function lowerAssetSupplyHeight(tx, forkHeight) {
84
+ await tx.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ assetSupplyHeight: forkHeight })
85
+ .where(forkHeight == null ? { ID: sync_state_1.SINGLETON_ID } : { ID: sync_state_1.SINGLETON_ID, assetSupplyHeight: { '>': forkHeight } }));
86
+ }
87
+ const T = { supply: 'odatano_cardano_AssetSupply', history: 'odatano_cardano_AssetHistory' };
88
+ /** Statements that rebuild AssetSupply from the AssetHistory rows up to `height`. Portable SQL. */
89
+ function assetSupplyStatements(height) {
90
+ const h = Math.trunc(height);
91
+ return [
92
+ `DELETE FROM ${T.supply}`,
93
+ `INSERT INTO ${T.supply} (unit, totalSupply, mintOrBurnCount) ` +
94
+ `SELECT unit, SUM(CASE WHEN action = 'burn' THEN -CAST(quantity AS DECIMAL(38, 0)) ELSE CAST(quantity AS DECIMAL(38, 0)) END), COUNT(*) ` +
95
+ `FROM ${T.history} WHERE blockHeight <= ${h} GROUP BY unit`,
96
+ ];
97
+ }
98
+ // Builds AssetSupply once from the stored rows up to `height`, the crawler's cursor. Runs
99
+ // before the crawler writes blocks, so no block lands between the sum and the height.
100
+ async function computeAssetSupply(tx, height) {
101
+ const raw = tx;
102
+ // the GROUP BY reads every row once; a bigger hash budget keeps it in memory on PostgreSQL
103
+ if (cds_1.default.db?.kind === 'postgres')
104
+ await raw.run(`SET LOCAL work_mem = '256MB'`);
105
+ for (const sql of assetSupplyStatements(height))
106
+ await raw.run(sql);
107
+ await tx.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ assetSupplyHeight: Math.trunc(height) }).where({ ID: sync_state_1.SINGLETON_ID }));
108
+ }
109
+ //# sourceMappingURL=asset-supply.js.map
@@ -27,6 +27,7 @@ const cip68_1 = require("../cbor/cip68");
27
27
  const pool_metadata_1 = require("./pool-metadata");
28
28
  const epoch_slots_1 = require("../utils/epoch-slots");
29
29
  const const_1 = require("../utils/const");
30
+ const asset_supply_1 = require("./asset-supply");
30
31
  const { UPSERT, INSERT, UPDATE, SELECT, DELETE } = cds_1.default.ql;
31
32
  const logger = cds_1.default.log('CardanoIndexer');
32
33
  /** The address list of an account as stored: unique and sorted. */
@@ -148,7 +149,14 @@ class CardanoIndexer {
148
149
  const cursor = await (0, sync_state_1.readCursor)(tx);
149
150
  if (!cursor || cursor.syncStatus !== 'synced' || cursor.nodeBehindSince != null || cursor.startSlot == null || !(0, sync_state_1.isCrawlerLeaseActive)(cursor))
150
151
  return null;
151
- return { fromSlot: cursor.startSlot, lastSlot: cursor.lastSlot, tipHeight: cursor.tipHeight, ledger: cursor.utxoSet.status === 'active' };
152
+ const ledger = cursor.utxoSet.status === 'active';
153
+ return {
154
+ fromSlot: cursor.startSlot,
155
+ lastSlot: cursor.lastSlot,
156
+ tipHeight: cursor.tipHeight,
157
+ ledger,
158
+ ledgerLovelace: ledger ? cursor.utxoSet.lovelace : null,
159
+ };
152
160
  }
153
161
  // Block counts of a pool from crawled blocks. The epoch count needs the whole current epoch
154
162
  // crawled, the lifetime count the whole chain since Shelley.
@@ -185,21 +193,25 @@ class CardanoIndexer {
185
193
  if (coverage)
186
194
  throw new errors_1.NotFoundError(`${what} (not in the crawled chain up to slot ${coverage.lastSlot})`);
187
195
  }
188
- // Asset from crawled mint and burn rows. Registry fields stay null.
189
- // Null when the crawled chain does not answer.
196
+ // Asset from the crawled supply sums and its first and latest mint. Registry fields stay null.
197
+ // Null when the crawled chain does not answer or the sums are not computed yet.
190
198
  async localAssetInfo(tx, unit) {
191
199
  if (!this.crawlAssetHistory || !(await this.crawlAnswers(tx, 'getAssetInfo')))
192
200
  return null;
193
- const events = await tx.run(SELECT.from(CardanoODataService_1.AssetHistory).columns('txHash', 'action', 'quantity', 'blockTime', 'blockHeight').where({ unit }));
194
- if (!events?.length)
201
+ if ((await (0, asset_supply_1.assetSupplyHeight)(tx)) == null)
202
+ return null;
203
+ const sums = await (0, asset_supply_1.readAssetSupply)(tx, unit);
204
+ if (!sums)
195
205
  throw new errors_1.NotFoundError(`Asset ${unit} (never minted in the crawled chain)`);
196
- const ordered = [...events].sort((a, b) => Number(a.blockHeight ?? 0) - Number(b.blockHeight ?? 0));
197
- let supply = 0n;
198
- for (const e of ordered)
199
- supply += (e.action === 'burn' ? -1n : 1n) * BigInt(String(e.quantity ?? '0'));
200
- const mints = ordered.filter(e => e.action !== 'burn');
201
- const first = mints[0];
202
- const latest = mints[mints.length - 1];
206
+ const supply = BigInt(lovelaceSum(sums.totalSupply));
207
+ // the (unit, blockHeight) index serves both ends; a row without a height counts as the oldest
208
+ const mintAt = async (sort) => {
209
+ const q = SELECT.one.from(CardanoODataService_1.AssetHistory).columns('txHash', 'blockTime').where({ unit, action: 'mint' });
210
+ q.SELECT.orderBy = [{ ref: ['blockHeight'], sort, nulls: sort === 'asc' ? 'first' : 'last' }];
211
+ return await tx.run(q);
212
+ };
213
+ const first = await mintAt('asc');
214
+ const latest = await mintAt('desc');
203
215
  let onchainMetadata = null;
204
216
  if (latest) {
205
217
  const meta = await tx.run(SELECT.one.from(CardanoODataService_1.TransactionMetadata).columns('payload').where({ tx_hash: latest.txHash, label: '721' }));
@@ -218,7 +230,7 @@ class CardanoIndexer {
218
230
  assetName: slice.asset_assetName,
219
231
  fingerprint: slice.asset_fingerprint ?? (0, mappers_1.computeCip14Fingerprint)(unit.slice(0, 56), unit.slice(56)),
220
232
  totalSupply: supply.toString(),
221
- mintOrBurnCount: ordered.length,
233
+ mintOrBurnCount: Number(sums.mintOrBurnCount ?? 0),
222
234
  initialMintTxHash: first?.txHash ?? null,
223
235
  initialMintTime: first?.blockTime == null ? null : Number(first.blockTime),
224
236
  onchainMetadata,
@@ -1065,9 +1077,8 @@ class CardanoIndexer {
1065
1077
  /** Network information from the backend; circulating supply from the crawled UTxO set when current. */
1066
1078
  async resolveNetworkInformation(tx) {
1067
1079
  const netInfo = await this.client.getNetworkInformation();
1068
- const circulating = (await this.localCoverage(tx))?.ledger
1069
- ? lovelaceSum((await tx.run(SELECT.one.from(CardanoODataService_1.LedgerAddresses).columns('sum(totalLovelace) as total')))?.total)
1070
- : null;
1080
+ const total = (await this.localCoverage(tx))?.ledgerLovelace;
1081
+ const circulating = total == null ? null : lovelaceSum(total);
1071
1082
  return circulating === null ? netInfo : { ...netInfo, supply: { ...netInfo.supply, circulating } };
1072
1083
  }
1073
1084
  /** Index a block by hash, with best-effort epoch enrichment. */
@@ -1235,8 +1246,11 @@ class CardanoIndexer {
1235
1246
  }
1236
1247
  }
1237
1248
  }
1238
- if (assetHistoryRows.length)
1249
+ if (assetHistoryRows.length) {
1239
1250
  await tx.run(UPSERT.into(CardanoODataService_1.AssetHistory).entries(assetHistoryRows));
1251
+ if (blockData.height != null)
1252
+ await (0, asset_supply_1.applyBlockAssetSupply)(tx, assetHistoryRows, blockData.height);
1253
+ }
1240
1254
  // Catalogue last; collecting the units is skipped entirely when the catalogue is off.
1241
1255
  const newAssets = this.crawlAssetCatalogue === 'off'
1242
1256
  ? 0
@@ -134,6 +134,7 @@ export declare class CardanoCrawler {
134
134
  getActiveSource(): CrawlSource | null;
135
135
  /** Start crawling without awaiting the pipeline. Refuses without a start block or cursor, never syncs from genesis. */
136
136
  start(): Promise<void>;
137
+ private computeMissingSums;
137
138
  /** Stop crawling and await the in-flight step, so callers can tear down backends and the DB. */
138
139
  stop(finalStatus?: CrawlSyncStatusValue): Promise<void>;
139
140
  private halt;
@@ -11,6 +11,7 @@ const const_1 = require("../../utils/const");
11
11
  const epoch_slots_1 = require("../../utils/epoch-slots");
12
12
  const hooks_1 = require("./hooks");
13
13
  const ledger_state_1 = require("../ledger-state");
14
+ const asset_supply_1 = require("../asset-supply");
14
15
  const transaction_rows_1 = require("../transaction-rows");
15
16
  const cardano_1 = require("#cds-models/odatano/cardano");
16
17
  const account_snapshots_1 = require("./account-snapshots");
@@ -204,6 +205,15 @@ class CardanoCrawler {
204
205
  this.indexer.setUtxoAnchor(null);
205
206
  }
206
207
  this.startLeaseHeartbeat();
208
+ try {
209
+ await this.computeMissingSums(cursor);
210
+ }
211
+ catch (err) {
212
+ await this.halt(err instanceof CrawlerLeaseLostError ? 'stopped' : 'error');
213
+ if (!(err instanceof CrawlerLeaseLostError))
214
+ logger.error('Crawler start failed computing the stored sums:', err);
215
+ return;
216
+ }
207
217
  // A pipeline crash must show on the cursor, or the crawler looks healthy while idle.
208
218
  this.pipeline = this.runIngestPipeline().catch(async (err) => {
209
219
  if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError) {
@@ -215,6 +225,25 @@ class CardanoCrawler {
215
225
  await this.halt(streak < 0 ? 'stopped' : 'error');
216
226
  });
217
227
  }
228
+ // Sums the crawler keeps per block, computed once where they are missing. Runs before the
229
+ // first block and commits only while the lease is held.
230
+ async computeMissingSums(cursor) {
231
+ const underLease = (work) => cds_1.default.tx(async (tx) => {
232
+ await work(tx);
233
+ if (this.leaseOwner && !(await (0, sync_state_1.renewCrawlerLease)(tx, this.leaseOwner)))
234
+ throw new CrawlerLeaseLostError();
235
+ });
236
+ if (this.indexer.getUtxoAnchor() && cursor.utxoSet.lovelace == null) {
237
+ let total = '';
238
+ await underLease(async (tx) => { total = await (0, ledger_state_1.computeUtxoSetLovelace)(tx); });
239
+ logger.info(`UTxO set total computed: ${total} lovelace`);
240
+ }
241
+ if (this.config.assetHistory && (await cds_1.default.tx((tx) => (0, asset_supply_1.assetSupplyHeight)(tx))) == null) {
242
+ const started = Date.now();
243
+ await underLease((tx) => (0, asset_supply_1.computeAssetSupply)(tx, cursor.lastHeight));
244
+ logger.info(`Asset supply sums computed up to height ${cursor.lastHeight} in ${Date.now() - started} ms`);
245
+ }
246
+ }
218
247
  /** Stop crawling and await the in-flight step, so callers can tear down backends and the DB. */
219
248
  async stop(finalStatus = 'stopped') {
220
249
  this.beginHalt(finalStatus);
@@ -1080,7 +1109,7 @@ class CardanoCrawler {
1080
1109
  emittedForkHeight = forkHeight ?? null;
1081
1110
  // Blocks strictly after the fork, cut on the absolute-slot axis. Rows without a
1082
1111
  // slot (lazily indexed blocks from an older schema) are deliberately excluded.
1083
- const staleBlocks = await tx.run(SELECT.from(cardano_1.Blocks).columns('hash').where({ slot: { '>': forkSlot } }));
1112
+ const staleBlocks = await tx.run(SELECT.from(cardano_1.Blocks).columns('hash', 'height').where({ slot: { '>': forkSlot } }));
1084
1113
  const blockHashes = staleBlocks.map((b) => b.hash);
1085
1114
  blocksRolledBack = blockHashes.length;
1086
1115
  for (const blockChunk of (0, collections_1.chunk)(blockHashes, collections_1.IN_CHUNK)) {
@@ -1104,6 +1133,7 @@ class CardanoCrawler {
1104
1133
  for (const u of history ?? [])
1105
1134
  rolledBackUnits.add(u.unit);
1106
1135
  }
1136
+ await (0, asset_supply_1.undoAssetSupply)(tx, txHashes);
1107
1137
  for (const txChunk of (0, collections_1.chunk)(txHashes, collections_1.IN_CHUNK)) {
1108
1138
  // These tables have no cascading delete. Remove them first so no orphans leak via OData.
1109
1139
  await tx.run(DELETE.from(cardano_1.UTxOAssets).where({ utxo_hash: { in: txChunk } }));
@@ -1114,6 +1144,10 @@ class CardanoCrawler {
1114
1144
  await (0, transaction_rows_1.deleteTransactionRows)(tx, staleTxs);
1115
1145
  await tx.run(DELETE.from(cardano_1.Blocks).where({ hash: { in: blockChunk } }));
1116
1146
  }
1147
+ if (blocksRolledBack > 0) {
1148
+ const lowest = staleBlocks.reduce((m, b) => (b.height == null ? m : Math.min(m, Number(b.height))), Infinity);
1149
+ await (0, asset_supply_1.lowerAssetSupplyHeight)(tx, forkHeight ?? (Number.isFinite(lowest) ? lowest - 1 : null));
1150
+ }
1117
1151
  // Epoch snapshots read at a rolled-back block describe a chain that no longer exists.
1118
1152
  if (blocksRolledBack > 0) {
1119
1153
  await (0, account_snapshots_1.dropAccountSnapshotsAfter)(tx, forkSlot);
@@ -20,6 +20,8 @@ export interface UtxoSetState {
20
20
  importedAt: string | null;
21
21
  /** Slot of the last block applied to the ledger tables (null = nothing applied since the import). */
22
22
  appliedSlot: number | null;
23
+ /** Lovelace over the unspent rows, as text (null = not computed yet). */
24
+ lovelace: string | null;
23
25
  error: string | null;
24
26
  }
25
27
  /** Normalized, number-typed view of the cursor row (numeric fields already coerced). */
@@ -67,6 +69,7 @@ export declare function renewImportLease(db: CapTransaction, owner: string, now?
67
69
  export declare function releaseImportLease(db: CapTransaction, owner: string): Promise<void>;
68
70
  /** Persist the crawler-fed ledger state's anchor / validity (crawler.utxoSet). */
69
71
  export declare function setUtxoSetState(db: CapTransaction, state: Partial<UtxoSetState>): Promise<void>;
72
+ export declare function addUtxoSetLovelace(db: CapTransaction, delta: bigint): Promise<void>;
70
73
  /** Reset the cursor to a rollback point (used by reorg handling). */
71
74
  export declare function resetCursorTo(db: CapTransaction, point: CrawlPoint): Promise<void>;
72
75
  export declare function markNodeBehind(db: CapTransaction, reason: string, leaseOwner?: string): Promise<boolean>;
@@ -17,6 +17,7 @@ exports.tryAcquireImportLease = tryAcquireImportLease;
17
17
  exports.renewImportLease = renewImportLease;
18
18
  exports.releaseImportLease = releaseImportLease;
19
19
  exports.setUtxoSetState = setUtxoSetState;
20
+ exports.addUtxoSetLovelace = addUtxoSetLovelace;
20
21
  exports.resetCursorTo = resetCursorTo;
21
22
  exports.markNodeBehind = markNodeBehind;
22
23
  exports.recordRollbackRefusal = recordRollbackRefusal;
@@ -68,6 +69,7 @@ function toCursor(row) {
68
69
  anchorHash: row.utxoAnchorHash ?? null,
69
70
  importedAt: (0, row_values_1.timestamp)(row.utxoSetImportedAt),
70
71
  appliedSlot: (0, row_values_1.optionalNum)(row.utxoAppliedSlot),
72
+ lovelace: row.utxoSetLovelace == null ? null : String(row.utxoSetLovelace),
71
73
  error: row.utxoSetError ?? null,
72
74
  },
73
75
  };
@@ -102,6 +104,7 @@ async function ensureSyncStateSingleton(db, network, start) {
102
104
  utxoAnchorHash: null,
103
105
  utxoSetImportedAt: null,
104
106
  utxoAppliedSlot: null,
107
+ utxoSetLovelace: null,
105
108
  utxoSetError: null,
106
109
  };
107
110
  await db.run(INSERT.into(cardano_1.CardanoSyncState).entries(row));
@@ -201,12 +204,21 @@ async function setUtxoSetState(db, state) {
201
204
  set.utxoSetImportedAt = state.importedAt;
202
205
  if (state.appliedSlot !== undefined)
203
206
  set.utxoAppliedSlot = state.appliedSlot;
207
+ if (state.lovelace !== undefined)
208
+ set.utxoSetLovelace = state.lovelace;
204
209
  if (state.error !== undefined)
205
210
  set.utxoSetError = state.error;
206
211
  if (!Object.keys(set).length)
207
212
  return;
208
213
  await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
209
214
  }
215
+ // Adds a block's net lovelace change to the set total. A null total stays null until computed.
216
+ async function addUtxoSetLovelace(db, delta) {
217
+ if (delta === 0n)
218
+ return;
219
+ const by = Number.isSafeInteger(Number(delta)) ? Number(delta) : delta.toString();
220
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ utxoSetLovelace: { '+=': by } }).where({ ID: exports.SINGLETON_ID }));
221
+ }
210
222
  /** Reset the cursor to a rollback point (used by reorg handling). */
211
223
  async function resetCursorTo(db, point) {
212
224
  await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
@@ -128,6 +128,7 @@ const T = {
128
128
  addresses: 'odatano_cardano_LedgerAddresses',
129
129
  addressAssets: 'odatano_cardano_LedgerAddressAssets',
130
130
  accounts: 'odatano_cardano_LedgerAccounts',
131
+ syncState: 'odatano_cardano_CardanoSyncState',
131
132
  };
132
133
  // Derive the running sums from the imported rows. Plain SQL, because millions of addresses
133
134
  // do not fit in memory and per-row UPSERTs take hours. Portable across SQLite, PostgreSQL and HANA.
@@ -144,6 +145,8 @@ function aggregateStatements() {
144
145
  `INSERT INTO ${T.accounts} (stakeAddress, controlledAmount, addressCount, utxoCount, lastActiveSlot) ` +
145
146
  `SELECT stakeAddress, SUM(totalLovelace), COUNT(*), SUM(utxoCount), NULL FROM ${T.addresses} ` +
146
147
  `WHERE stakeAddress IS NOT NULL GROUP BY stakeAddress`,
148
+ `UPDATE ${T.syncState} SET utxoSetLovelace = (SELECT COALESCE(SUM(totalLovelace), 0) FROM ${T.addresses}) ` +
149
+ `WHERE ID = '${sync_state_1.SINGLETON_ID}'`,
147
150
  ];
148
151
  }
149
152
  // Precondition failures throw before any write. A failure mid-way marks the set `invalid`.
@@ -165,7 +168,7 @@ async function importUtxoSet(opts) {
165
168
  const { writeTx } = lease;
166
169
  opts.indexer.setUtxoAnchor(null);
167
170
  await writeTx(async (tx) => {
168
- await (0, sync_state_1.setUtxoSetState)(tx, { status: 'importing', anchorSlot: anchor.slot, anchorHash: anchor.hash, error: null, importedAt: null, appliedSlot: null });
171
+ await (0, sync_state_1.setUtxoSetState)(tx, { status: 'importing', anchorSlot: anchor.slot, anchorHash: anchor.hash, error: null, importedAt: null, appliedSlot: null, lovelace: null });
169
172
  await tx.run(DELETE.from(cardano_1.LedgerUTxOAssets));
170
173
  await tx.run(DELETE.from(cardano_1.LedgerUTxOs));
171
174
  await tx.run(DELETE.from(cardano_1.LedgerAddressAssets));
@@ -56,6 +56,7 @@ export declare function ledgerRowAmount(row: LedgerUtxoRow, assets: LedgerUtxoAs
56
56
  export declare function applyBlockToLedger(tx: CapTransaction, block: BlockData, txs: ProviderTransaction[], lookup?: LedgerLookup): Promise<LedgerApplyResult>;
57
57
  export declare function undoLedgerForTransactions(tx: CapTransaction, txHashes: string[], forkSlot: number): Promise<string[]>;
58
58
  export declare function recountLedgerAddresses(tx: CapTransaction, addresses: string[]): Promise<void>;
59
+ export declare function computeUtxoSetLovelace(tx: CapTransaction): Promise<string>;
59
60
  /** Recount `LedgerAccounts` for the given stake keys from `LedgerAddresses`. */
60
61
  export declare function recountLedgerAccounts(tx: CapTransaction, stakeAddresses: string[]): Promise<void>;
61
62
  export declare function backfillPaymentCredentials(chunkSize?: number): Promise<number>;
@@ -9,12 +9,14 @@ exports.ledgerRowAmount = ledgerRowAmount;
9
9
  exports.applyBlockToLedger = applyBlockToLedger;
10
10
  exports.undoLedgerForTransactions = undoLedgerForTransactions;
11
11
  exports.recountLedgerAddresses = recountLedgerAddresses;
12
+ exports.computeUtxoSetLovelace = computeUtxoSetLovelace;
12
13
  exports.recountLedgerAccounts = recountLedgerAccounts;
13
14
  exports.backfillPaymentCredentials = backfillPaymentCredentials;
14
15
  const cds_1 = __importDefault(require("@sap/cds"));
15
16
  const cardano_1 = require("#cds-models/odatano/cardano");
16
17
  const mappers_1 = require("../utils/mappers");
17
18
  const collections_1 = require("../utils/collections");
19
+ const sync_state_1 = require("./crawler/sync-state");
18
20
  const { SELECT, UPSERT, UPDATE, DELETE } = cds_1.default.ql;
19
21
  const logger = cds_1.default.log('LedgerState');
20
22
  const outpoint = (txHash, outputIndex) => `${txHash}#${outputIndex}`;
@@ -64,6 +66,12 @@ function consumedInputs(t) {
64
66
  .filter(i => (t.spendsCollaterals ? i.isCollateral : !i.isReference && !i.isCollateral))
65
67
  .map(i => ({ txHash: i.txHash, outputIndex: i.outputIndex }));
66
68
  }
69
+ function netLovelace(deltas) {
70
+ let net = 0n;
71
+ for (const d of deltas.values())
72
+ net += d.lovelace;
73
+ return net;
74
+ }
67
75
  function deltaFor(map, row) {
68
76
  let d = map.get(row.address);
69
77
  if (!d) {
@@ -177,6 +185,7 @@ async function applyBlockToLedger(tx, block, txs, lookup) {
177
185
  for (const row of spentRows) {
178
186
  applyDelta(deltaFor(deltas, row), row, dbAssets.get(outpoint(row.txHash, row.outputIndex)), -1n);
179
187
  }
188
+ await (0, sync_state_1.addUtxoSetLovelace)(tx, netLovelace(deltas));
180
189
  // 4) UTxO rows
181
190
  const createdRows = [...created.values()];
182
191
  for (const rows of (0, collections_1.chunk)(createdRows.map(c => c.row), collections_1.IN_CHUNK)) {
@@ -323,6 +332,7 @@ async function undoLedgerForTransactions(tx, txHashes, forkSlot) {
323
332
  for (const r of reopened)
324
333
  applyDelta(deltaFor(deltas, r), r, assets.get(outpoint(r.txHash, num(r.outputIndex))), 1n);
325
334
  }
335
+ await (0, sync_state_1.addUtxoSetLovelace)(tx, netLovelace(deltas));
326
336
  for (const hashChunk of hashChunks) {
327
337
  await tx.run(DELETE.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: hashChunk } }));
328
338
  await tx.run(DELETE.from(cardano_1.LedgerUTxOs).where({ txHash: { in: hashChunk } }));
@@ -438,6 +448,7 @@ async function recountLedgerAddresses(tx, addresses) {
438
448
  }
439
449
  }
440
450
  const prev = await tx.run(SELECT.one.from(cardano_1.LedgerAddresses).where({ address }));
451
+ await (0, sync_state_1.addUtxoSetLovelace)(tx, total - big(prev?.totalLovelace));
441
452
  const decoded = (0, mappers_1.decodeShelleyAddress)(address);
442
453
  const stakeAddress = prev?.stakeAddress ?? open?.[0]?.stakeAddress ?? decoded.stakeAddress;
443
454
  await tx.run(UPSERT.into(cardano_1.LedgerAddresses).entries({
@@ -464,6 +475,14 @@ async function recountLedgerAddresses(tx, addresses) {
464
475
  }
465
476
  await recountLedgerAccounts(tx, [...stakes]);
466
477
  }
478
+ // Computes the set total once for a set imported before the total was kept. One scan of
479
+ // LedgerAddresses; the caller runs it before the crawler applies blocks.
480
+ async function computeUtxoSetLovelace(tx) {
481
+ const row = await tx.run(SELECT.one.from(cardano_1.LedgerAddresses).columns('sum(totalLovelace) as total'));
482
+ const total = big(row?.total == null ? null : String(row.total).split('.')[0]).toString();
483
+ await tx.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ utxoSetLovelace: total }).where({ ID: sync_state_1.SINGLETON_ID, utxoSetLovelace: null }));
484
+ return total;
485
+ }
467
486
  /** Recount `LedgerAccounts` for the given stake keys from `LedgerAddresses`. */
468
487
  async function recountLedgerAccounts(tx, stakeAddresses) {
469
488
  for (const stakeChunk of (0, collections_1.chunk)(stakeAddresses, collections_1.IN_CHUNK)) {
@@ -21,8 +21,11 @@ exports.GUARDED_ENTITIES = Object.freeze([
21
21
  'Blocks', 'Transactions', 'TransactionInputs', 'TransactionOutputs', 'TransactionInputAssets',
22
22
  'TransactionOutputAssets', 'TransactionMetadata', 'TransactionCertificates', 'TransactionWithdrawals',
23
23
  'TransactionRedeemers', 'TransactionDatums', 'AssetHistory', 'Assets',
24
- 'LedgerUTxOs', 'LedgerUTxOAssets', 'LedgerAddresses', 'LedgerAddressAssets',
24
+ 'LedgerUTxOs', 'LedgerUTxOAssets', 'LedgerAddresses', 'LedgerAddressAssets', 'LedgerAccounts',
25
+ 'AccountEpochSnapshots', 'PoolEpochSnapshots', 'DrepEpochSnapshots',
25
26
  ]);
27
+ // One row per block: counting a slot or height range reads only the index, and stays fast.
28
+ const RANGE_COUNTS = new Set(['Blocks']);
26
29
  const DB_NAMESPACE = 'odatano.cardano';
27
30
  const lower = (s) => s.toLowerCase();
28
31
  /** Primary key columns in table order; a managed association key becomes its foreign key columns. */
@@ -131,7 +134,8 @@ function unindexedReason(entityName, select, entity) {
131
134
  return null;
132
135
  if (select.search)
133
136
  return '$search is not supported on this entity set';
134
- if (select.groupBy?.length || select.having)
137
+ const aggregated = select.columns?.some(c => c.func && c.func !== 'count') ?? false;
138
+ if (select.groupBy?.length || select.having || aggregated)
135
139
  return '$apply is not supported on this entity set';
136
140
  const lists = indexColumnLists(entityName, entity);
137
141
  const shape = whereShape(select.where);
@@ -144,6 +148,9 @@ function unindexedReason(entityName, select, entity) {
144
148
  const counted = select.count === true || (select.columns?.some(c => c.func === 'count') ?? false);
145
149
  if (counted && !select.where?.length)
146
150
  return '$count needs a $filter on an indexed field';
151
+ // a range on a large table counts every row in it
152
+ if (counted && shape.narrowing.size === 0 && !RANGE_COUNTS.has(entityName))
153
+ return '$count needs an eq $filter on an indexed field';
147
154
  const order = (select.orderBy ?? []).filter(o => !o.implicit);
148
155
  if (order.some(o => !columnOf(o.ref)))
149
156
  return '$orderby supports plain fields only';