@ocap/indexdb 1.32.0 → 1.32.2
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/esm/main.d.mts +2 -2
- package/esm/main.mjs +2 -2
- package/esm/rebuild.d.mts +17 -4
- package/esm/rebuild.mjs +229 -142
- package/lib/main.cjs +2 -0
- package/lib/main.d.cts +2 -2
- package/lib/rebuild.cjs +230 -141
- package/lib/rebuild.d.cts +17 -4
- package/package.json +4 -4
package/esm/main.d.mts
CHANGED
|
@@ -3,5 +3,5 @@ import BaseIndexDB from "./db.mjs";
|
|
|
3
3
|
import BaseIndex from "./index.mjs";
|
|
4
4
|
import { SearchResultFormatOptions, formatSearchResult } from "./search-result.mjs";
|
|
5
5
|
import { BridgeReleaseEvidenceInput, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, getTxBridgeReleaseEvidenceKey, isDefaultTokenChanged, parseDateTime } from "./util.mjs";
|
|
6
|
-
import { clearIndexDB, rebuildIndexFromState, scanStateTable } from "./rebuild.mjs";
|
|
7
|
-
export { BaseIndex, BaseIndexDB, BridgeReleaseEvidenceInput, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, ILedgerEntrySnapshot, ISqliteDatabaseLike, ISqliteStatementLike, ITxIndexBackfillInsert, ITxIndexBackfillPlan, ITxIndexBackfillUpdate, ITxIndexRowSnapshot, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, type SearchResultFormatOptions, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, applyTxIndexBackfill, buildTxIndexBackfillPlan, clearIndexDB, computeBackfillPlanDigest, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, getTxBridgeReleaseEvidenceKey, isDefaultTokenChanged, parseDateTime, planTxIndexBackfill, rebuildIndexFromState, scanStateTable };
|
|
6
|
+
import { REBUILD_BATCH_SIZE, clearIndexDB, iterateStateTable, rebuildIndexFromState, scanStateTable } from "./rebuild.mjs";
|
|
7
|
+
export { BaseIndex, BaseIndexDB, BridgeReleaseEvidenceInput, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, ILedgerEntrySnapshot, ISqliteDatabaseLike, ISqliteStatementLike, ITxIndexBackfillInsert, ITxIndexBackfillPlan, ITxIndexBackfillUpdate, ITxIndexRowSnapshot, IndexDBForTx, PagingInput, REBUILD_BATCH_SIZE, RollupBlockContext, RollupContext, type SearchResultFormatOptions, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, applyTxIndexBackfill, buildTxIndexBackfillPlan, clearIndexDB, computeBackfillPlanDigest, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, getTxBridgeReleaseEvidenceKey, isDefaultTokenChanged, iterateStateTable, parseDateTime, planTxIndexBackfill, rebuildIndexFromState, scanStateTable };
|
package/esm/main.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, getTxBridgeReleaseEvidenceKey, isDefaultTokenChanged, parseDateTime } from "./util.mjs";
|
|
2
2
|
import { applyTxIndexBackfill, buildTxIndexBackfillPlan, computeBackfillPlanDigest, planTxIndexBackfill } from "./backfill.mjs";
|
|
3
|
-
import { clearIndexDB, rebuildIndexFromState, scanStateTable } from "./rebuild.mjs";
|
|
3
|
+
import { REBUILD_BATCH_SIZE, clearIndexDB, iterateStateTable, rebuildIndexFromState, scanStateTable } from "./rebuild.mjs";
|
|
4
4
|
import db_default from "./db.mjs";
|
|
5
5
|
import src_default from "./index.mjs";
|
|
6
6
|
import { formatSearchResult } from "./search-result.mjs";
|
|
7
7
|
|
|
8
|
-
export { src_default as BaseIndex, db_default as BaseIndexDB, applyTxIndexBackfill, buildTxIndexBackfillPlan, clearIndexDB, computeBackfillPlanDigest, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, getTxBridgeReleaseEvidenceKey, isDefaultTokenChanged, parseDateTime, planTxIndexBackfill, rebuildIndexFromState, scanStateTable };
|
|
8
|
+
export { src_default as BaseIndex, db_default as BaseIndexDB, REBUILD_BATCH_SIZE, applyTxIndexBackfill, buildTxIndexBackfillPlan, clearIndexDB, computeBackfillPlanDigest, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, getTxBridgeReleaseEvidenceKey, isDefaultTokenChanged, iterateStateTable, parseDateTime, planTxIndexBackfill, rebuildIndexFromState, scanStateTable };
|
package/esm/rebuild.d.mts
CHANGED
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
import { IIndexDB, IRebuildOptions, IRebuildResult, IStateDB } from "@ocap/types";
|
|
2
2
|
|
|
3
3
|
//#region src/rebuild.d.ts
|
|
4
|
-
|
|
4
|
+
/** Rows per StateDB read during a rebuild: memory stays bounded by this, not by the table size. */
|
|
5
|
+
declare const REBUILD_BATCH_SIZE = 500;
|
|
6
|
+
/**
|
|
7
|
+
* Pages of a StateDB table, `batchSize` records each. SQLite tables are read page by page (keyset on rowid), so the
|
|
8
|
+
* memory of a rebuild does not grow with the table; other adapters (in-memory LokiJS, `listAll`, Dolt) are scanned
|
|
9
|
+
* whole as before and handed out in pages.
|
|
10
|
+
*/
|
|
11
|
+
declare function iterateStateTable<T = Record<string, unknown>>(statedb: IStateDB | Record<string, unknown>, tableName: string, batchSize?: number): AsyncGenerator<T[]>;
|
|
5
12
|
/**
|
|
6
13
|
* Scan all records from a StateDB table across Memory, SQLite, and Dolt adapters.
|
|
7
14
|
*/
|
|
@@ -13,8 +20,14 @@ declare function clearIndexDB(indexdb: IIndexDB, options?: {
|
|
|
13
20
|
preserveTx?: boolean;
|
|
14
21
|
}): Promise<void>;
|
|
15
22
|
/**
|
|
16
|
-
* Deterministically rebuild IndexDB from StateDB (`vledger index rebuild
|
|
23
|
+
* Deterministically rebuild IndexDB from StateDB (`vledger index rebuild`, follower initial index build).
|
|
24
|
+
*
|
|
25
|
+
* Memory is bounded by `options.batchSize` (default `REBUILD_BATCH_SIZE`) on SQLite: every table is read page by
|
|
26
|
+
* page and the records a transaction references are read by primary key, never held as whole-table arrays or maps.
|
|
27
|
+
* Only the token metadata and the rollup states (small tables every other step needs) stay in memory.
|
|
17
28
|
*/
|
|
18
|
-
declare function rebuildIndexFromState(indexdb: IIndexDB, statedb: IStateDB, options?: IRebuildOptions
|
|
29
|
+
declare function rebuildIndexFromState(indexdb: IIndexDB, statedb: IStateDB, options?: IRebuildOptions & {
|
|
30
|
+
batchSize?: number;
|
|
31
|
+
}): Promise<IRebuildResult>;
|
|
19
32
|
//#endregion
|
|
20
|
-
export { clearIndexDB, rebuildIndexFromState, scanStateTable };
|
|
33
|
+
export { REBUILD_BATCH_SIZE, clearIndexDB, iterateStateTable, rebuildIndexFromState, scanStateTable };
|
package/esm/rebuild.mjs
CHANGED
|
@@ -17,6 +17,119 @@ const INDEX_TABLES_STATE_ONLY = [
|
|
|
17
17
|
"indexFailure",
|
|
18
18
|
"balance"
|
|
19
19
|
];
|
|
20
|
+
/** Rows per StateDB read during a rebuild: memory stays bounded by this, not by the table size. */
|
|
21
|
+
const REBUILD_BATCH_SIZE = 500;
|
|
22
|
+
const ROWID_ALIAS = "__ocap_rebuild_rowid";
|
|
23
|
+
function getStateTable(statedb, tableName) {
|
|
24
|
+
return statedb?.[tableName];
|
|
25
|
+
}
|
|
26
|
+
/** The SQLite (Kysely) table adapter, unless the table has a `listAll` or LokiJS collection (those win in a scan). */
|
|
27
|
+
function asKyselyTable(table) {
|
|
28
|
+
if (!table || typeof table.listAll === "function") return null;
|
|
29
|
+
const collection = table.collection;
|
|
30
|
+
if (collection && typeof collection.find === "function") return null;
|
|
31
|
+
const db = table.db;
|
|
32
|
+
if (db && typeof db.selectFrom === "function" && typeof table.name === "string") return table;
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
/** A raw SQLite row as the state object a scan returns: deserialized, with the balance table merged in. */
|
|
36
|
+
async function toKyselyStateItem(table, row) {
|
|
37
|
+
const item = typeof table.deserializeFromDb === "function" ? table.deserializeFromDb(row) : { ...row };
|
|
38
|
+
const balanceTable = table.balanceTable;
|
|
39
|
+
if (Boolean(table.syncBalance) && balanceTable && typeof balanceTable.getBalance === "function" && typeof item.address === "string") {
|
|
40
|
+
const balances = await balanceTable.getBalance(item.address);
|
|
41
|
+
item.tokens = {
|
|
42
|
+
...item.tokens || {},
|
|
43
|
+
...balances
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
return item;
|
|
47
|
+
}
|
|
48
|
+
/** Keyset pages of `table` in rowid order (the order of a full scan), `batchSize` rows per query. */
|
|
49
|
+
async function* iterateKyselyRows(table, batchSize, columns) {
|
|
50
|
+
let after = 0;
|
|
51
|
+
for (;;) {
|
|
52
|
+
let qb = table.db.selectFrom(table.name).select(`rowid as ${ROWID_ALIAS}`);
|
|
53
|
+
qb = columns ? qb.select(columns) : qb.selectAll();
|
|
54
|
+
const rows = await qb.where("rowid", ">", after).orderBy("rowid").limit(batchSize).execute();
|
|
55
|
+
if (!rows.length) return;
|
|
56
|
+
const page = rows.map((r) => {
|
|
57
|
+
const row = { ...r };
|
|
58
|
+
const rowid = Number(row[ROWID_ALIAS]);
|
|
59
|
+
delete row[ROWID_ALIAS];
|
|
60
|
+
return {
|
|
61
|
+
rowid,
|
|
62
|
+
row
|
|
63
|
+
};
|
|
64
|
+
});
|
|
65
|
+
after = page[page.length - 1].rowid;
|
|
66
|
+
yield page;
|
|
67
|
+
if (rows.length < batchSize) return;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Pages of a StateDB table, `batchSize` records each. SQLite tables are read page by page (keyset on rowid), so the
|
|
72
|
+
* memory of a rebuild does not grow with the table; other adapters (in-memory LokiJS, `listAll`, Dolt) are scanned
|
|
73
|
+
* whole as before and handed out in pages.
|
|
74
|
+
*/
|
|
75
|
+
async function* iterateStateTable(statedb, tableName, batchSize = REBUILD_BATCH_SIZE) {
|
|
76
|
+
const kyselyTable = asKyselyTable(getStateTable(statedb, tableName));
|
|
77
|
+
if (kyselyTable) {
|
|
78
|
+
for await (const page of iterateKyselyRows(kyselyTable, batchSize)) {
|
|
79
|
+
const items = [];
|
|
80
|
+
for (const { row } of page) items.push(await toKyselyStateItem(kyselyTable, row));
|
|
81
|
+
yield items;
|
|
82
|
+
}
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const all = await scanStateTable(statedb, tableName);
|
|
86
|
+
for (let i = 0; i < all.length; i += batchSize) yield all.slice(i, i + batchSize);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Point reads by `address` with the semantics of a `Map` built from a full scan (`map.get(address)`): the raw row,
|
|
90
|
+
* no migration following, `undefined` when absent. SQLite reads the row by primary key; other adapters build that
|
|
91
|
+
* map from one scan on first use.
|
|
92
|
+
*/
|
|
93
|
+
function createStateLookup(statedb) {
|
|
94
|
+
const scannedMaps = /* @__PURE__ */ new Map();
|
|
95
|
+
return async (tableName, address) => {
|
|
96
|
+
if (typeof address !== "string" || !address) return void 0;
|
|
97
|
+
const kyselyTable = asKyselyTable(getStateTable(statedb, tableName));
|
|
98
|
+
if (kyselyTable) {
|
|
99
|
+
const rows = await kyselyTable.db.selectFrom(kyselyTable.name).selectAll().where("address", "=", address).limit(1).execute();
|
|
100
|
+
if (!rows.length) return void 0;
|
|
101
|
+
const item = await toKyselyStateItem(kyselyTable, rows[0]);
|
|
102
|
+
return item.address === address ? item : void 0;
|
|
103
|
+
}
|
|
104
|
+
let map = scannedMaps.get(tableName);
|
|
105
|
+
if (!map) {
|
|
106
|
+
map = /* @__PURE__ */ new Map();
|
|
107
|
+
for (const item of await scanStateTable(statedb, tableName)) if (item?.address) map.set(item.address, item);
|
|
108
|
+
scannedMaps.set(tableName, map);
|
|
109
|
+
}
|
|
110
|
+
return map.get(address);
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/** `rollupBlock` records sorted by height (stable: ties keep scan order), reading one block at a time on SQLite. */
|
|
114
|
+
async function* iterateRollupBlocksByHeight(statedb, batchSize) {
|
|
115
|
+
const kyselyTable = asKyselyTable(getStateTable(statedb, "rollupBlock"));
|
|
116
|
+
if (!kyselyTable) {
|
|
117
|
+
const blocks = await scanStateTable(statedb, "rollupBlock");
|
|
118
|
+
blocks.sort((a, b) => Number(a.height || 0) - Number(b.height || 0));
|
|
119
|
+
yield* blocks;
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const order = [];
|
|
123
|
+
for await (const page of iterateKyselyRows(kyselyTable, batchSize, ["height"])) for (const { rowid, row } of page) order.push({
|
|
124
|
+
rowid,
|
|
125
|
+
height: Number(row.height || 0)
|
|
126
|
+
});
|
|
127
|
+
order.sort((a, b) => a.height - b.height);
|
|
128
|
+
for (const { rowid } of order) {
|
|
129
|
+
const rows = await kyselyTable.db.selectFrom(kyselyTable.name).selectAll().where("rowid", "=", rowid).limit(1).execute();
|
|
130
|
+
if (rows.length) yield await toKyselyStateItem(kyselyTable, rows[0]);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
20
133
|
/**
|
|
21
134
|
* Scan all records from a StateDB table across Memory, SQLite, and Dolt adapters.
|
|
22
135
|
*/
|
|
@@ -47,23 +160,11 @@ async function scanStateTable(statedb, tableName) {
|
|
|
47
160
|
}
|
|
48
161
|
return results;
|
|
49
162
|
}
|
|
50
|
-
const
|
|
51
|
-
if (
|
|
52
|
-
const rawRows = await db.selectFrom(
|
|
163
|
+
const kyselyTable = asKyselyTable(table);
|
|
164
|
+
if (kyselyTable) {
|
|
165
|
+
const rawRows = await kyselyTable.db.selectFrom(kyselyTable.name).selectAll().execute();
|
|
53
166
|
const results = [];
|
|
54
|
-
const
|
|
55
|
-
const balanceTable = table.balanceTable;
|
|
56
|
-
for (const row of rawRows) {
|
|
57
|
-
const item = typeof table.deserializeFromDb === "function" ? table.deserializeFromDb(row) : { ...row };
|
|
58
|
-
if (syncBalance && balanceTable && typeof balanceTable.getBalance === "function" && typeof item.address === "string") {
|
|
59
|
-
const balances = await balanceTable.getBalance(item.address);
|
|
60
|
-
item.tokens = {
|
|
61
|
-
...item.tokens || {},
|
|
62
|
-
...balances
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
results.push(item);
|
|
66
|
-
}
|
|
167
|
+
for (const row of rawRows) results.push(await toKyselyStateItem(kyselyTable, row));
|
|
67
168
|
return results;
|
|
68
169
|
}
|
|
69
170
|
if (typeof table.driver === "function" && typeof table.name === "string") {
|
|
@@ -98,11 +199,17 @@ async function upsertIndexRecord(table, key, doc) {
|
|
|
98
199
|
else await table.insert(doc);
|
|
99
200
|
}
|
|
100
201
|
/**
|
|
101
|
-
* Deterministically rebuild IndexDB from StateDB (`vledger index rebuild
|
|
202
|
+
* Deterministically rebuild IndexDB from StateDB (`vledger index rebuild`, follower initial index build).
|
|
203
|
+
*
|
|
204
|
+
* Memory is bounded by `options.batchSize` (default `REBUILD_BATCH_SIZE`) on SQLite: every table is read page by
|
|
205
|
+
* page and the records a transaction references are read by primary key, never held as whole-table arrays or maps.
|
|
206
|
+
* Only the token metadata and the rollup states (small tables every other step needs) stay in memory.
|
|
102
207
|
*/
|
|
103
208
|
async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
104
209
|
const startTime = Date.now();
|
|
105
210
|
const preserveTx = Boolean(options?.preserveTx);
|
|
211
|
+
const batchSize = Number.isInteger(options?.batchSize) && Number(options?.batchSize) > 0 ? Number(options?.batchSize) : REBUILD_BATCH_SIZE;
|
|
212
|
+
const lookup = createStateLookup(statedb);
|
|
106
213
|
await clearIndexDB(indexdb, { preserveTx });
|
|
107
214
|
const counts = {
|
|
108
215
|
token: 0,
|
|
@@ -121,7 +228,6 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
121
228
|
let chainState = null;
|
|
122
229
|
if (options?.chainAddress) chainState = await statedb.chain.get(options.chainAddress);
|
|
123
230
|
if (!chainState) chainState = (await scanStateTable(statedb, "chain"))[0] || null;
|
|
124
|
-
const tokenStates = await scanStateTable(statedb, "token");
|
|
125
231
|
const tokenInfoMap = /* @__PURE__ */ new Map();
|
|
126
232
|
if (chainState?.token?.address) tokenInfoMap.set(chainState.token.address, {
|
|
127
233
|
address: chainState.token.address,
|
|
@@ -131,7 +237,7 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
131
237
|
icon: chainState.token.icon,
|
|
132
238
|
foreignToken: chainState.token.foreignToken
|
|
133
239
|
});
|
|
134
|
-
for (const tokenState of tokenStates) {
|
|
240
|
+
for await (const tokenStates of iterateStateTable(statedb, "token", batchSize)) for (const tokenState of tokenStates) {
|
|
135
241
|
if (!tokenState?.address) continue;
|
|
136
242
|
tokenInfoMap.set(tokenState.address, {
|
|
137
243
|
address: tokenState.address,
|
|
@@ -151,38 +257,52 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
151
257
|
if (cached) return cached;
|
|
152
258
|
return await indexdb.token.get(address) || null;
|
|
153
259
|
};
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
|
|
260
|
+
const vaultAddresses = {
|
|
261
|
+
gas: chainState?.vaults?.gas?.address || "",
|
|
262
|
+
fee: chainState?.vaults?.fee?.address || "",
|
|
263
|
+
slashed: chainState?.vaults?.slash?.address || "",
|
|
264
|
+
moderator: chainState?.moderator?.address || ""
|
|
265
|
+
};
|
|
266
|
+
const zero = new BN(0);
|
|
267
|
+
const sums = new Map(allTokenInfos.filter((t) => t.address).map((t) => [t.address, {
|
|
268
|
+
account: new BN(0),
|
|
269
|
+
gas: new BN(0),
|
|
270
|
+
fee: new BN(0),
|
|
271
|
+
slashed: new BN(0),
|
|
272
|
+
stake: new BN(0),
|
|
273
|
+
revokedStake: new BN(0),
|
|
274
|
+
gasStake: new BN(0)
|
|
275
|
+
}]));
|
|
276
|
+
for await (const assetStates of iterateStateTable(statedb, "asset", batchSize)) for (const assetState of assetStates) {
|
|
157
277
|
if (!assetState?.address) continue;
|
|
158
|
-
assetMap.set(assetState.address, assetState);
|
|
159
278
|
const indexedAsset = createIndexedAsset(assetState);
|
|
160
279
|
await upsertIndexRecord(indexdb.asset, assetState.address, indexedAsset);
|
|
161
280
|
counts.asset += 1;
|
|
162
281
|
}
|
|
163
|
-
const accountStates
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
282
|
+
for await (const accountStates of iterateStateTable(statedb, "account", batchSize)) for (const acc of accountStates) {
|
|
283
|
+
for (const [tokenAddr, sum] of sums) {
|
|
284
|
+
const balStr = acc?.tokens?.[tokenAddr];
|
|
285
|
+
if (!balStr) continue;
|
|
286
|
+
const bal = new BN(balStr);
|
|
287
|
+
if (bal.lte(zero)) continue;
|
|
288
|
+
if (acc.address === vaultAddresses.gas) sum.gas = sum.gas.add(bal);
|
|
289
|
+
else if (acc.address === vaultAddresses.fee) sum.fee = sum.fee.add(bal);
|
|
290
|
+
else if (acc.address === vaultAddresses.slashed) sum.slashed = sum.slashed.add(bal);
|
|
291
|
+
else sum.account = sum.account.add(bal);
|
|
292
|
+
}
|
|
293
|
+
if (!acc?.address) continue;
|
|
294
|
+
const indexedAccount = await createIndexedAccount(acc, getTokenFn);
|
|
295
|
+
await upsertIndexRecord(indexdb.account, acc.address, indexedAccount);
|
|
170
296
|
counts.account += 1;
|
|
171
297
|
}
|
|
172
|
-
const delegationStates
|
|
173
|
-
const delegationMap = /* @__PURE__ */ new Map();
|
|
174
|
-
for (const delegationState of delegationStates) {
|
|
298
|
+
for await (const delegationStates of iterateStateTable(statedb, "delegation", batchSize)) for (const delegationState of delegationStates) {
|
|
175
299
|
if (!delegationState?.address) continue;
|
|
176
|
-
delegationMap.set(delegationState.address, delegationState);
|
|
177
300
|
const indexedDelegation = createIndexedDelegation(delegationState, {});
|
|
178
301
|
await upsertIndexRecord(indexdb.delegation, delegationState.address, indexedDelegation);
|
|
179
302
|
counts.delegation += 1;
|
|
180
303
|
}
|
|
181
|
-
const factoryStates
|
|
182
|
-
const factoryMap = /* @__PURE__ */ new Map();
|
|
183
|
-
for (const factoryState of factoryStates) {
|
|
304
|
+
for await (const factoryStates of iterateStateTable(statedb, "factory", batchSize)) for (const factoryState of factoryStates) {
|
|
184
305
|
if (!factoryState?.address) continue;
|
|
185
|
-
factoryMap.set(factoryState.address, factoryState);
|
|
186
306
|
const indexedFactory = createIndexedFactory(factoryState, {
|
|
187
307
|
factoryTokens: factoryState.input?.tokens,
|
|
188
308
|
tokenStates: allTokenInfos
|
|
@@ -190,11 +310,8 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
190
310
|
await upsertIndexRecord(indexdb.factory, factoryState.address, indexedFactory);
|
|
191
311
|
counts.factory += 1;
|
|
192
312
|
}
|
|
193
|
-
const tokenFactoryStates
|
|
194
|
-
const tokenFactoryMap = /* @__PURE__ */ new Map();
|
|
195
|
-
for (const tfState of tokenFactoryStates) {
|
|
313
|
+
for await (const tokenFactoryStates of iterateStateTable(statedb, "tokenFactory", batchSize)) for (const tfState of tokenFactoryStates) {
|
|
196
314
|
if (!tfState?.address) continue;
|
|
197
|
-
tokenFactoryMap.set(tfState.address, tfState);
|
|
198
315
|
const tokenInfo = tokenInfoMap.get(tfState.tokenAddress);
|
|
199
316
|
const reserveInfo = tokenInfoMap.get(tfState.reserveAddress) || chainState?.token;
|
|
200
317
|
const indexedTokenFactory = createIndexedTokenFactory(tfState, {
|
|
@@ -204,20 +321,33 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
204
321
|
await upsertIndexRecord(indexdb.tokenFactory, tfState.address, indexedTokenFactory);
|
|
205
322
|
counts.tokenFactory += 1;
|
|
206
323
|
}
|
|
207
|
-
const
|
|
208
|
-
const
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
324
|
+
const rollupMap = /* @__PURE__ */ new Map();
|
|
325
|
+
for await (const rollupStates of iterateStateTable(statedb, "rollup", batchSize)) for (const rollupState of rollupStates) if (rollupState?.address) rollupMap.set(rollupState.address, rollupState);
|
|
326
|
+
const validatorPairKey = (sender, receiver) => `${String(sender)}\u0000${String(receiver)}`;
|
|
327
|
+
const validatorStakes = /* @__PURE__ */ new Map();
|
|
328
|
+
for (const rollupState of rollupMap.values()) for (const v of [...rollupState.seedValidators || [], ...rollupState.validators || []]) if (v?.address) validatorStakes.set(validatorPairKey(v.address, rollupState.address), null);
|
|
329
|
+
for await (const stakeStates of iterateStateTable(statedb, "stake", batchSize)) for (const stake of stakeStates) {
|
|
330
|
+
for (const [tokenAddr, sum] of sums) {
|
|
331
|
+
const activeStr = stake?.tokens?.[tokenAddr];
|
|
332
|
+
if (activeStr) {
|
|
333
|
+
const val = new BN(activeStr);
|
|
334
|
+
if (val.gt(zero)) if (stake.receiver === vaultAddresses.moderator) sum.gasStake = sum.gasStake.add(val);
|
|
335
|
+
else sum.stake = sum.stake.add(val);
|
|
336
|
+
}
|
|
337
|
+
const revokedStr = stake?.revokedTokens?.[tokenAddr];
|
|
338
|
+
if (revokedStr) {
|
|
339
|
+
const val = new BN(revokedStr);
|
|
340
|
+
if (val.gt(zero)) sum.revokedStake = sum.revokedStake.add(val);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
if (!stake?.address) continue;
|
|
344
|
+
const pairKey = validatorPairKey(stake.sender, stake.receiver);
|
|
345
|
+
if (validatorStakes.get(pairKey) === null) validatorStakes.set(pairKey, stake);
|
|
346
|
+
const indexedStake = await createIndexedStake(stake, { tokenStates: allTokenInfos }, indexdb);
|
|
347
|
+
await upsertIndexRecord(indexdb.stake, stake.address, indexedStake);
|
|
214
348
|
counts.stake += 1;
|
|
215
349
|
}
|
|
216
|
-
const
|
|
217
|
-
const rollupMap = /* @__PURE__ */ new Map();
|
|
218
|
-
for (const rollupState of rollupStates) {
|
|
219
|
-
if (!rollupState?.address) continue;
|
|
220
|
-
rollupMap.set(rollupState.address, rollupState);
|
|
350
|
+
for (const rollupState of rollupMap.values()) {
|
|
221
351
|
const indexedRollup = createIndexedRollup(rollupState, { tokenStates: allTokenInfos });
|
|
222
352
|
await upsertIndexRecord(indexdb.rollup, rollupState.address, indexedRollup);
|
|
223
353
|
counts.rollup += 1;
|
|
@@ -228,8 +358,8 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
228
358
|
...v
|
|
229
359
|
});
|
|
230
360
|
for (const v of validatorMap.values()) {
|
|
231
|
-
const matchingStake =
|
|
232
|
-
const account =
|
|
361
|
+
const matchingStake = validatorStakes.get(validatorPairKey(v.address, rollupState.address)) || void 0;
|
|
362
|
+
const account = await lookup("account", v.address);
|
|
233
363
|
const totalStake = matchingStake?.tokens?.[rollupState.tokenAddress] || "0";
|
|
234
364
|
const revokedStake = matchingStake?.revokedTokens?.[rollupState.tokenAddress] || "0";
|
|
235
365
|
const validatorDoc = {
|
|
@@ -255,9 +385,7 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
255
385
|
counts.rollupValidator += 1;
|
|
256
386
|
}
|
|
257
387
|
}
|
|
258
|
-
const
|
|
259
|
-
rollupBlockStates.sort((a, b) => Number(a.height || 0) - Number(b.height || 0));
|
|
260
|
-
for (const blockState of rollupBlockStates) {
|
|
388
|
+
for await (const blockState of iterateRollupBlocksByHeight(statedb, batchSize)) {
|
|
261
389
|
if (!blockState?.hash) continue;
|
|
262
390
|
const indexedBlock = createIndexedRollupBlock(blockState, {
|
|
263
391
|
rollupState: rollupMap.get(blockState.rollup),
|
|
@@ -279,76 +407,32 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
279
407
|
}
|
|
280
408
|
}
|
|
281
409
|
}
|
|
282
|
-
if (!preserveTx) {
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
factoryMap,
|
|
293
|
-
stakeMap,
|
|
294
|
-
rollupMap,
|
|
295
|
-
delegationMap,
|
|
296
|
-
tokenFactoryMap
|
|
297
|
-
}), indexdb);
|
|
298
|
-
await upsertIndexRecord(indexdb.tx, txState.hash, indexedTx);
|
|
299
|
-
counts.tx += 1;
|
|
300
|
-
}
|
|
410
|
+
if (!preserveTx) for await (const txStates of iterateStateTable(statedb, "tx", batchSize)) for (const txState of txStates) {
|
|
411
|
+
if (!txState?.hash) continue;
|
|
412
|
+
const txClone = JSON.parse(JSON.stringify(txState));
|
|
413
|
+
const indexedTx = await createIndexedTransaction(txClone, await buildSyntheticTxContext(txClone, {
|
|
414
|
+
lookup,
|
|
415
|
+
tokenInfoMap,
|
|
416
|
+
rollupMap
|
|
417
|
+
}), indexdb);
|
|
418
|
+
await upsertIndexRecord(indexdb.tx, txState.hash, indexedTx);
|
|
419
|
+
counts.tx += 1;
|
|
301
420
|
}
|
|
302
|
-
const vaultAddresses = {
|
|
303
|
-
gas: chainState?.vaults?.gas?.address || "",
|
|
304
|
-
fee: chainState?.vaults?.fee?.address || "",
|
|
305
|
-
slashed: chainState?.vaults?.slash?.address || "",
|
|
306
|
-
moderator: chainState?.moderator?.address || ""
|
|
307
|
-
};
|
|
308
421
|
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
309
422
|
for (const tokenInfo of allTokenInfos) {
|
|
310
423
|
const tokenAddr = tokenInfo.address;
|
|
311
424
|
if (!tokenAddr) continue;
|
|
312
|
-
|
|
313
|
-
let gasSum = new BN(0);
|
|
314
|
-
let feeSum = new BN(0);
|
|
315
|
-
let slashedSum = new BN(0);
|
|
316
|
-
let stakeSum = new BN(0);
|
|
317
|
-
let revokedStakeSum = new BN(0);
|
|
318
|
-
let gasStakeSum = new BN(0);
|
|
319
|
-
for (const acc of accountStates) {
|
|
320
|
-
const balStr = acc.tokens?.[tokenAddr];
|
|
321
|
-
if (!balStr) continue;
|
|
322
|
-
const bal = new BN(balStr);
|
|
323
|
-
if (bal.lte(new BN(0))) continue;
|
|
324
|
-
if (acc.address === vaultAddresses.gas) gasSum = gasSum.add(bal);
|
|
325
|
-
else if (acc.address === vaultAddresses.fee) feeSum = feeSum.add(bal);
|
|
326
|
-
else if (acc.address === vaultAddresses.slashed) slashedSum = slashedSum.add(bal);
|
|
327
|
-
else accountSum = accountSum.add(bal);
|
|
328
|
-
}
|
|
329
|
-
for (const stake of stakeStates) {
|
|
330
|
-
const activeStr = stake.tokens?.[tokenAddr];
|
|
331
|
-
if (activeStr) {
|
|
332
|
-
const val = new BN(activeStr);
|
|
333
|
-
if (val.gt(new BN(0))) if (stake.receiver === vaultAddresses.moderator) gasStakeSum = gasStakeSum.add(val);
|
|
334
|
-
else stakeSum = stakeSum.add(val);
|
|
335
|
-
}
|
|
336
|
-
const revokedStr = stake.revokedTokens?.[tokenAddr];
|
|
337
|
-
if (revokedStr) {
|
|
338
|
-
const val = new BN(revokedStr);
|
|
339
|
-
if (val.gt(new BN(0))) revokedStakeSum = revokedStakeSum.add(val);
|
|
340
|
-
}
|
|
341
|
-
}
|
|
425
|
+
const sum = sums.get(tokenAddr);
|
|
342
426
|
const distDoc = createIndexedTokenDistribution({
|
|
343
427
|
tokenAddress: tokenAddr,
|
|
344
428
|
txTime: nowIso,
|
|
345
|
-
account:
|
|
346
|
-
gas:
|
|
347
|
-
fee:
|
|
348
|
-
slashedVault:
|
|
349
|
-
stake:
|
|
350
|
-
revokedStake:
|
|
351
|
-
gasStake:
|
|
429
|
+
account: sum.account,
|
|
430
|
+
gas: sum.gas,
|
|
431
|
+
fee: sum.fee,
|
|
432
|
+
slashedVault: sum.slashed,
|
|
433
|
+
stake: sum.stake,
|
|
434
|
+
revokedStake: sum.revokedStake,
|
|
435
|
+
gasStake: sum.gasStake
|
|
352
436
|
});
|
|
353
437
|
await upsertIndexRecord(indexdb.tokenDistribution, tokenAddr, distDoc);
|
|
354
438
|
counts.tokenDistribution += 1;
|
|
@@ -360,11 +444,12 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
360
444
|
};
|
|
361
445
|
}
|
|
362
446
|
/**
|
|
363
|
-
* Reconstruct a FinalizedContext from a persisted ITransactionState and StateDB
|
|
447
|
+
* Reconstruct a FinalizedContext from a persisted ITransactionState and the StateDB records it references
|
|
364
448
|
* so `createIndexedTransaction` can populate entity references (`accounts`, `assets`,
|
|
365
449
|
* `tokens`, `factories`, `stakes`, `rollups`, `delegations`, `tokenFactories`, `tokenSymbols`).
|
|
366
450
|
*/
|
|
367
|
-
function buildSyntheticTxContext(txState,
|
|
451
|
+
async function buildSyntheticTxContext(txState, refs) {
|
|
452
|
+
const { lookup } = refs;
|
|
368
453
|
const itx = txState.tx?.itxJson || {};
|
|
369
454
|
const txType = itx.type_url || (txState.type ? `fg:t:${txState.type}` : "");
|
|
370
455
|
const updatedAccounts = [];
|
|
@@ -373,22 +458,24 @@ function buildSyntheticTxContext(txState, maps) {
|
|
|
373
458
|
const stakeStates = [];
|
|
374
459
|
const addTokenByAddr = (addr) => {
|
|
375
460
|
if (typeof addr !== "string" || !addr) return;
|
|
376
|
-
const info =
|
|
461
|
+
const info = refs.tokenInfoMap.get(addr);
|
|
377
462
|
if (info && !tokenStates.some((t) => t.address === addr)) tokenStates.push(info);
|
|
378
463
|
};
|
|
379
|
-
const addAssetByAddr = (addr) => {
|
|
464
|
+
const addAssetByAddr = async (addr) => {
|
|
380
465
|
if (typeof addr !== "string" || !addr) return;
|
|
381
|
-
const asset =
|
|
466
|
+
const asset = await lookup("asset", addr);
|
|
382
467
|
if (asset && !assetStates.some((a) => a.address === addr)) assetStates.push(asset);
|
|
383
468
|
};
|
|
384
469
|
for (const receipt of txState.receipts || []) {
|
|
385
|
-
if (typeof receipt.address === "string" && receipt.address)
|
|
386
|
-
const s =
|
|
387
|
-
if (
|
|
388
|
-
|
|
470
|
+
if (typeof receipt.address === "string" && receipt.address) {
|
|
471
|
+
const s = await lookup("stake", receipt.address);
|
|
472
|
+
if (s) {
|
|
473
|
+
if (!stakeStates.some((x) => x.address === s.address)) stakeStates.push(s);
|
|
474
|
+
} else updatedAccounts.push({ address: receipt.address });
|
|
475
|
+
}
|
|
389
476
|
for (const change of receipt.changes || []) if (typeof change.target === "string" && change.target) {
|
|
390
477
|
addTokenByAddr(change.target);
|
|
391
|
-
addAssetByAddr(change.target);
|
|
478
|
+
await addAssetByAddr(change.target);
|
|
392
479
|
}
|
|
393
480
|
}
|
|
394
481
|
const itxAddress = typeof itx.address === "string" ? itx.address : "";
|
|
@@ -398,19 +485,19 @@ function buildSyntheticTxContext(txState, maps) {
|
|
|
398
485
|
const itxTokenAddress = typeof itx.tokenAddress === "string" ? itx.tokenAddress : "";
|
|
399
486
|
addTokenByAddr(itxToken);
|
|
400
487
|
addTokenByAddr(itxTokenAddress);
|
|
401
|
-
addAssetByAddr(itxAddress);
|
|
488
|
+
await addAssetByAddr(itxAddress);
|
|
402
489
|
if (Array.isArray(itx.tokens)) for (const t of itx.tokens) addTokenByAddr(t?.address);
|
|
403
|
-
if (Array.isArray(itx.assets)) for (const a of itx.assets) addAssetByAddr(a);
|
|
404
|
-
const factoryState =
|
|
405
|
-
const rollupState =
|
|
406
|
-
const delegationState =
|
|
407
|
-
const tokenFactoryState =
|
|
408
|
-
const stakeState =
|
|
409
|
-
const assetState =
|
|
490
|
+
if (Array.isArray(itx.assets)) for (const a of itx.assets) await addAssetByAddr(a);
|
|
491
|
+
const factoryState = await lookup("factory", itxFactory || itxAddress);
|
|
492
|
+
const rollupState = refs.rollupMap.get(itxRollup || itxAddress);
|
|
493
|
+
const delegationState = await lookup("delegation", itxAddress);
|
|
494
|
+
const tokenFactoryState = await lookup("tokenFactory", itxAddress || itx.factoryAddress || "");
|
|
495
|
+
const stakeState = await lookup("stake", itxAddress);
|
|
496
|
+
const assetState = await lookup("asset", itxAddress);
|
|
410
497
|
return {
|
|
411
498
|
txType,
|
|
412
|
-
senderState: txState.sender ?
|
|
413
|
-
receiverState: txState.receiver ?
|
|
499
|
+
senderState: txState.sender ? await lookup("account", txState.sender) || { address: txState.sender } : void 0,
|
|
500
|
+
receiverState: txState.receiver ? await lookup("account", txState.receiver) || { address: txState.receiver } : void 0,
|
|
414
501
|
updatedAccounts,
|
|
415
502
|
assetState,
|
|
416
503
|
assetStates: assetStates.length > 0 ? assetStates : void 0,
|
|
@@ -426,4 +513,4 @@ function buildSyntheticTxContext(txState, maps) {
|
|
|
426
513
|
}
|
|
427
514
|
|
|
428
515
|
//#endregion
|
|
429
|
-
export { clearIndexDB, rebuildIndexFromState, scanStateTable };
|
|
516
|
+
export { REBUILD_BATCH_SIZE, clearIndexDB, iterateStateTable, rebuildIndexFromState, scanStateTable };
|
package/lib/main.cjs
CHANGED
|
@@ -7,6 +7,7 @@ const require_search_result = require('./search-result.cjs');
|
|
|
7
7
|
|
|
8
8
|
exports.BaseIndex = require_index.default;
|
|
9
9
|
exports.BaseIndexDB = require_db.default;
|
|
10
|
+
exports.REBUILD_BATCH_SIZE = require_rebuild.REBUILD_BATCH_SIZE;
|
|
10
11
|
exports.applyTxIndexBackfill = require_backfill.applyTxIndexBackfill;
|
|
11
12
|
exports.buildTxIndexBackfillPlan = require_backfill.buildTxIndexBackfillPlan;
|
|
12
13
|
exports.clearIndexDB = require_rebuild.clearIndexDB;
|
|
@@ -34,6 +35,7 @@ exports.formatTxBeforeInsert = require_util.formatTxBeforeInsert;
|
|
|
34
35
|
exports.getBridgeReleaseEvidenceKey = require_util.getBridgeReleaseEvidenceKey;
|
|
35
36
|
exports.getTxBridgeReleaseEvidenceKey = require_util.getTxBridgeReleaseEvidenceKey;
|
|
36
37
|
exports.isDefaultTokenChanged = require_util.isDefaultTokenChanged;
|
|
38
|
+
exports.iterateStateTable = require_rebuild.iterateStateTable;
|
|
37
39
|
exports.parseDateTime = require_util.parseDateTime;
|
|
38
40
|
exports.planTxIndexBackfill = require_backfill.planTxIndexBackfill;
|
|
39
41
|
exports.rebuildIndexFromState = require_rebuild.rebuildIndexFromState;
|
package/lib/main.d.cts
CHANGED
|
@@ -3,5 +3,5 @@ import BaseIndexDB from "./db.cjs";
|
|
|
3
3
|
import BaseIndex from "./index.cjs";
|
|
4
4
|
import { SearchResultFormatOptions, formatSearchResult } from "./search-result.cjs";
|
|
5
5
|
import { BridgeReleaseEvidenceInput, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, getTxBridgeReleaseEvidenceKey, isDefaultTokenChanged, parseDateTime } from "./util.cjs";
|
|
6
|
-
import { clearIndexDB, rebuildIndexFromState, scanStateTable } from "./rebuild.cjs";
|
|
7
|
-
export { BaseIndex, BaseIndexDB, BridgeReleaseEvidenceInput, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, ILedgerEntrySnapshot, ISqliteDatabaseLike, ISqliteStatementLike, ITxIndexBackfillInsert, ITxIndexBackfillPlan, ITxIndexBackfillUpdate, ITxIndexRowSnapshot, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, type SearchResultFormatOptions, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, applyTxIndexBackfill, buildTxIndexBackfillPlan, clearIndexDB, computeBackfillPlanDigest, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, getTxBridgeReleaseEvidenceKey, isDefaultTokenChanged, parseDateTime, planTxIndexBackfill, rebuildIndexFromState, scanStateTable };
|
|
6
|
+
import { REBUILD_BATCH_SIZE, clearIndexDB, iterateStateTable, rebuildIndexFromState, scanStateTable } from "./rebuild.cjs";
|
|
7
|
+
export { BaseIndex, BaseIndexDB, BridgeReleaseEvidenceInput, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, ILedgerEntrySnapshot, ISqliteDatabaseLike, ISqliteStatementLike, ITxIndexBackfillInsert, ITxIndexBackfillPlan, ITxIndexBackfillUpdate, ITxIndexRowSnapshot, IndexDBForTx, PagingInput, REBUILD_BATCH_SIZE, RollupBlockContext, RollupContext, type SearchResultFormatOptions, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, applyTxIndexBackfill, buildTxIndexBackfillPlan, clearIndexDB, computeBackfillPlanDigest, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, getBridgeReleaseEvidenceKey, getTxBridgeReleaseEvidenceKey, isDefaultTokenChanged, iterateStateTable, parseDateTime, planTxIndexBackfill, rebuildIndexFromState, scanStateTable };
|
package/lib/rebuild.cjs
CHANGED
|
@@ -18,6 +18,119 @@ const INDEX_TABLES_STATE_ONLY = [
|
|
|
18
18
|
"indexFailure",
|
|
19
19
|
"balance"
|
|
20
20
|
];
|
|
21
|
+
/** Rows per StateDB read during a rebuild: memory stays bounded by this, not by the table size. */
|
|
22
|
+
const REBUILD_BATCH_SIZE = 500;
|
|
23
|
+
const ROWID_ALIAS = "__ocap_rebuild_rowid";
|
|
24
|
+
function getStateTable(statedb, tableName) {
|
|
25
|
+
return statedb?.[tableName];
|
|
26
|
+
}
|
|
27
|
+
/** The SQLite (Kysely) table adapter, unless the table has a `listAll` or LokiJS collection (those win in a scan). */
|
|
28
|
+
function asKyselyTable(table) {
|
|
29
|
+
if (!table || typeof table.listAll === "function") return null;
|
|
30
|
+
const collection = table.collection;
|
|
31
|
+
if (collection && typeof collection.find === "function") return null;
|
|
32
|
+
const db = table.db;
|
|
33
|
+
if (db && typeof db.selectFrom === "function" && typeof table.name === "string") return table;
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
/** A raw SQLite row as the state object a scan returns: deserialized, with the balance table merged in. */
|
|
37
|
+
async function toKyselyStateItem(table, row) {
|
|
38
|
+
const item = typeof table.deserializeFromDb === "function" ? table.deserializeFromDb(row) : { ...row };
|
|
39
|
+
const balanceTable = table.balanceTable;
|
|
40
|
+
if (Boolean(table.syncBalance) && balanceTable && typeof balanceTable.getBalance === "function" && typeof item.address === "string") {
|
|
41
|
+
const balances = await balanceTable.getBalance(item.address);
|
|
42
|
+
item.tokens = {
|
|
43
|
+
...item.tokens || {},
|
|
44
|
+
...balances
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
return item;
|
|
48
|
+
}
|
|
49
|
+
/** Keyset pages of `table` in rowid order (the order of a full scan), `batchSize` rows per query. */
|
|
50
|
+
async function* iterateKyselyRows(table, batchSize, columns) {
|
|
51
|
+
let after = 0;
|
|
52
|
+
for (;;) {
|
|
53
|
+
let qb = table.db.selectFrom(table.name).select(`rowid as ${ROWID_ALIAS}`);
|
|
54
|
+
qb = columns ? qb.select(columns) : qb.selectAll();
|
|
55
|
+
const rows = await qb.where("rowid", ">", after).orderBy("rowid").limit(batchSize).execute();
|
|
56
|
+
if (!rows.length) return;
|
|
57
|
+
const page = rows.map((r) => {
|
|
58
|
+
const row = { ...r };
|
|
59
|
+
const rowid = Number(row[ROWID_ALIAS]);
|
|
60
|
+
delete row[ROWID_ALIAS];
|
|
61
|
+
return {
|
|
62
|
+
rowid,
|
|
63
|
+
row
|
|
64
|
+
};
|
|
65
|
+
});
|
|
66
|
+
after = page[page.length - 1].rowid;
|
|
67
|
+
yield page;
|
|
68
|
+
if (rows.length < batchSize) return;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Pages of a StateDB table, `batchSize` records each. SQLite tables are read page by page (keyset on rowid), so the
|
|
73
|
+
* memory of a rebuild does not grow with the table; other adapters (in-memory LokiJS, `listAll`, Dolt) are scanned
|
|
74
|
+
* whole as before and handed out in pages.
|
|
75
|
+
*/
|
|
76
|
+
async function* iterateStateTable(statedb, tableName, batchSize = REBUILD_BATCH_SIZE) {
|
|
77
|
+
const kyselyTable = asKyselyTable(getStateTable(statedb, tableName));
|
|
78
|
+
if (kyselyTable) {
|
|
79
|
+
for await (const page of iterateKyselyRows(kyselyTable, batchSize)) {
|
|
80
|
+
const items = [];
|
|
81
|
+
for (const { row } of page) items.push(await toKyselyStateItem(kyselyTable, row));
|
|
82
|
+
yield items;
|
|
83
|
+
}
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const all = await scanStateTable(statedb, tableName);
|
|
87
|
+
for (let i = 0; i < all.length; i += batchSize) yield all.slice(i, i + batchSize);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Point reads by `address` with the semantics of a `Map` built from a full scan (`map.get(address)`): the raw row,
|
|
91
|
+
* no migration following, `undefined` when absent. SQLite reads the row by primary key; other adapters build that
|
|
92
|
+
* map from one scan on first use.
|
|
93
|
+
*/
|
|
94
|
+
function createStateLookup(statedb) {
|
|
95
|
+
const scannedMaps = /* @__PURE__ */ new Map();
|
|
96
|
+
return async (tableName, address) => {
|
|
97
|
+
if (typeof address !== "string" || !address) return void 0;
|
|
98
|
+
const kyselyTable = asKyselyTable(getStateTable(statedb, tableName));
|
|
99
|
+
if (kyselyTable) {
|
|
100
|
+
const rows = await kyselyTable.db.selectFrom(kyselyTable.name).selectAll().where("address", "=", address).limit(1).execute();
|
|
101
|
+
if (!rows.length) return void 0;
|
|
102
|
+
const item = await toKyselyStateItem(kyselyTable, rows[0]);
|
|
103
|
+
return item.address === address ? item : void 0;
|
|
104
|
+
}
|
|
105
|
+
let map = scannedMaps.get(tableName);
|
|
106
|
+
if (!map) {
|
|
107
|
+
map = /* @__PURE__ */ new Map();
|
|
108
|
+
for (const item of await scanStateTable(statedb, tableName)) if (item?.address) map.set(item.address, item);
|
|
109
|
+
scannedMaps.set(tableName, map);
|
|
110
|
+
}
|
|
111
|
+
return map.get(address);
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** `rollupBlock` records sorted by height (stable: ties keep scan order), reading one block at a time on SQLite. */
|
|
115
|
+
async function* iterateRollupBlocksByHeight(statedb, batchSize) {
|
|
116
|
+
const kyselyTable = asKyselyTable(getStateTable(statedb, "rollupBlock"));
|
|
117
|
+
if (!kyselyTable) {
|
|
118
|
+
const blocks = await scanStateTable(statedb, "rollupBlock");
|
|
119
|
+
blocks.sort((a, b) => Number(a.height || 0) - Number(b.height || 0));
|
|
120
|
+
yield* blocks;
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
const order = [];
|
|
124
|
+
for await (const page of iterateKyselyRows(kyselyTable, batchSize, ["height"])) for (const { rowid, row } of page) order.push({
|
|
125
|
+
rowid,
|
|
126
|
+
height: Number(row.height || 0)
|
|
127
|
+
});
|
|
128
|
+
order.sort((a, b) => a.height - b.height);
|
|
129
|
+
for (const { rowid } of order) {
|
|
130
|
+
const rows = await kyselyTable.db.selectFrom(kyselyTable.name).selectAll().where("rowid", "=", rowid).limit(1).execute();
|
|
131
|
+
if (rows.length) yield await toKyselyStateItem(kyselyTable, rows[0]);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
21
134
|
/**
|
|
22
135
|
* Scan all records from a StateDB table across Memory, SQLite, and Dolt adapters.
|
|
23
136
|
*/
|
|
@@ -48,23 +161,11 @@ async function scanStateTable(statedb, tableName) {
|
|
|
48
161
|
}
|
|
49
162
|
return results;
|
|
50
163
|
}
|
|
51
|
-
const
|
|
52
|
-
if (
|
|
53
|
-
const rawRows = await db.selectFrom(
|
|
164
|
+
const kyselyTable = asKyselyTable(table);
|
|
165
|
+
if (kyselyTable) {
|
|
166
|
+
const rawRows = await kyselyTable.db.selectFrom(kyselyTable.name).selectAll().execute();
|
|
54
167
|
const results = [];
|
|
55
|
-
const
|
|
56
|
-
const balanceTable = table.balanceTable;
|
|
57
|
-
for (const row of rawRows) {
|
|
58
|
-
const item = typeof table.deserializeFromDb === "function" ? table.deserializeFromDb(row) : { ...row };
|
|
59
|
-
if (syncBalance && balanceTable && typeof balanceTable.getBalance === "function" && typeof item.address === "string") {
|
|
60
|
-
const balances = await balanceTable.getBalance(item.address);
|
|
61
|
-
item.tokens = {
|
|
62
|
-
...item.tokens || {},
|
|
63
|
-
...balances
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
results.push(item);
|
|
67
|
-
}
|
|
168
|
+
for (const row of rawRows) results.push(await toKyselyStateItem(kyselyTable, row));
|
|
68
169
|
return results;
|
|
69
170
|
}
|
|
70
171
|
if (typeof table.driver === "function" && typeof table.name === "string") {
|
|
@@ -99,11 +200,17 @@ async function upsertIndexRecord(table, key, doc) {
|
|
|
99
200
|
else await table.insert(doc);
|
|
100
201
|
}
|
|
101
202
|
/**
|
|
102
|
-
* Deterministically rebuild IndexDB from StateDB (`vledger index rebuild
|
|
203
|
+
* Deterministically rebuild IndexDB from StateDB (`vledger index rebuild`, follower initial index build).
|
|
204
|
+
*
|
|
205
|
+
* Memory is bounded by `options.batchSize` (default `REBUILD_BATCH_SIZE`) on SQLite: every table is read page by
|
|
206
|
+
* page and the records a transaction references are read by primary key, never held as whole-table arrays or maps.
|
|
207
|
+
* Only the token metadata and the rollup states (small tables every other step needs) stay in memory.
|
|
103
208
|
*/
|
|
104
209
|
async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
105
210
|
const startTime = Date.now();
|
|
106
211
|
const preserveTx = Boolean(options?.preserveTx);
|
|
212
|
+
const batchSize = Number.isInteger(options?.batchSize) && Number(options?.batchSize) > 0 ? Number(options?.batchSize) : REBUILD_BATCH_SIZE;
|
|
213
|
+
const lookup = createStateLookup(statedb);
|
|
107
214
|
await clearIndexDB(indexdb, { preserveTx });
|
|
108
215
|
const counts = {
|
|
109
216
|
token: 0,
|
|
@@ -122,7 +229,6 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
122
229
|
let chainState = null;
|
|
123
230
|
if (options?.chainAddress) chainState = await statedb.chain.get(options.chainAddress);
|
|
124
231
|
if (!chainState) chainState = (await scanStateTable(statedb, "chain"))[0] || null;
|
|
125
|
-
const tokenStates = await scanStateTable(statedb, "token");
|
|
126
232
|
const tokenInfoMap = /* @__PURE__ */ new Map();
|
|
127
233
|
if (chainState?.token?.address) tokenInfoMap.set(chainState.token.address, {
|
|
128
234
|
address: chainState.token.address,
|
|
@@ -132,7 +238,7 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
132
238
|
icon: chainState.token.icon,
|
|
133
239
|
foreignToken: chainState.token.foreignToken
|
|
134
240
|
});
|
|
135
|
-
for (const tokenState of tokenStates) {
|
|
241
|
+
for await (const tokenStates of iterateStateTable(statedb, "token", batchSize)) for (const tokenState of tokenStates) {
|
|
136
242
|
if (!tokenState?.address) continue;
|
|
137
243
|
tokenInfoMap.set(tokenState.address, {
|
|
138
244
|
address: tokenState.address,
|
|
@@ -152,38 +258,52 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
152
258
|
if (cached) return cached;
|
|
153
259
|
return await indexdb.token.get(address) || null;
|
|
154
260
|
};
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
|
|
261
|
+
const vaultAddresses = {
|
|
262
|
+
gas: chainState?.vaults?.gas?.address || "",
|
|
263
|
+
fee: chainState?.vaults?.fee?.address || "",
|
|
264
|
+
slashed: chainState?.vaults?.slash?.address || "",
|
|
265
|
+
moderator: chainState?.moderator?.address || ""
|
|
266
|
+
};
|
|
267
|
+
const zero = new _ocap_util.BN(0);
|
|
268
|
+
const sums = new Map(allTokenInfos.filter((t) => t.address).map((t) => [t.address, {
|
|
269
|
+
account: new _ocap_util.BN(0),
|
|
270
|
+
gas: new _ocap_util.BN(0),
|
|
271
|
+
fee: new _ocap_util.BN(0),
|
|
272
|
+
slashed: new _ocap_util.BN(0),
|
|
273
|
+
stake: new _ocap_util.BN(0),
|
|
274
|
+
revokedStake: new _ocap_util.BN(0),
|
|
275
|
+
gasStake: new _ocap_util.BN(0)
|
|
276
|
+
}]));
|
|
277
|
+
for await (const assetStates of iterateStateTable(statedb, "asset", batchSize)) for (const assetState of assetStates) {
|
|
158
278
|
if (!assetState?.address) continue;
|
|
159
|
-
assetMap.set(assetState.address, assetState);
|
|
160
279
|
const indexedAsset = require_util.createIndexedAsset(assetState);
|
|
161
280
|
await upsertIndexRecord(indexdb.asset, assetState.address, indexedAsset);
|
|
162
281
|
counts.asset += 1;
|
|
163
282
|
}
|
|
164
|
-
const accountStates
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
283
|
+
for await (const accountStates of iterateStateTable(statedb, "account", batchSize)) for (const acc of accountStates) {
|
|
284
|
+
for (const [tokenAddr, sum] of sums) {
|
|
285
|
+
const balStr = acc?.tokens?.[tokenAddr];
|
|
286
|
+
if (!balStr) continue;
|
|
287
|
+
const bal = new _ocap_util.BN(balStr);
|
|
288
|
+
if (bal.lte(zero)) continue;
|
|
289
|
+
if (acc.address === vaultAddresses.gas) sum.gas = sum.gas.add(bal);
|
|
290
|
+
else if (acc.address === vaultAddresses.fee) sum.fee = sum.fee.add(bal);
|
|
291
|
+
else if (acc.address === vaultAddresses.slashed) sum.slashed = sum.slashed.add(bal);
|
|
292
|
+
else sum.account = sum.account.add(bal);
|
|
293
|
+
}
|
|
294
|
+
if (!acc?.address) continue;
|
|
295
|
+
const indexedAccount = await require_util.createIndexedAccount(acc, getTokenFn);
|
|
296
|
+
await upsertIndexRecord(indexdb.account, acc.address, indexedAccount);
|
|
171
297
|
counts.account += 1;
|
|
172
298
|
}
|
|
173
|
-
const delegationStates
|
|
174
|
-
const delegationMap = /* @__PURE__ */ new Map();
|
|
175
|
-
for (const delegationState of delegationStates) {
|
|
299
|
+
for await (const delegationStates of iterateStateTable(statedb, "delegation", batchSize)) for (const delegationState of delegationStates) {
|
|
176
300
|
if (!delegationState?.address) continue;
|
|
177
|
-
delegationMap.set(delegationState.address, delegationState);
|
|
178
301
|
const indexedDelegation = require_util.createIndexedDelegation(delegationState, {});
|
|
179
302
|
await upsertIndexRecord(indexdb.delegation, delegationState.address, indexedDelegation);
|
|
180
303
|
counts.delegation += 1;
|
|
181
304
|
}
|
|
182
|
-
const factoryStates
|
|
183
|
-
const factoryMap = /* @__PURE__ */ new Map();
|
|
184
|
-
for (const factoryState of factoryStates) {
|
|
305
|
+
for await (const factoryStates of iterateStateTable(statedb, "factory", batchSize)) for (const factoryState of factoryStates) {
|
|
185
306
|
if (!factoryState?.address) continue;
|
|
186
|
-
factoryMap.set(factoryState.address, factoryState);
|
|
187
307
|
const indexedFactory = require_util.createIndexedFactory(factoryState, {
|
|
188
308
|
factoryTokens: factoryState.input?.tokens,
|
|
189
309
|
tokenStates: allTokenInfos
|
|
@@ -191,11 +311,8 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
191
311
|
await upsertIndexRecord(indexdb.factory, factoryState.address, indexedFactory);
|
|
192
312
|
counts.factory += 1;
|
|
193
313
|
}
|
|
194
|
-
const tokenFactoryStates
|
|
195
|
-
const tokenFactoryMap = /* @__PURE__ */ new Map();
|
|
196
|
-
for (const tfState of tokenFactoryStates) {
|
|
314
|
+
for await (const tokenFactoryStates of iterateStateTable(statedb, "tokenFactory", batchSize)) for (const tfState of tokenFactoryStates) {
|
|
197
315
|
if (!tfState?.address) continue;
|
|
198
|
-
tokenFactoryMap.set(tfState.address, tfState);
|
|
199
316
|
const tokenInfo = tokenInfoMap.get(tfState.tokenAddress);
|
|
200
317
|
const reserveInfo = tokenInfoMap.get(tfState.reserveAddress) || chainState?.token;
|
|
201
318
|
const indexedTokenFactory = require_util.createIndexedTokenFactory(tfState, {
|
|
@@ -205,20 +322,33 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
205
322
|
await upsertIndexRecord(indexdb.tokenFactory, tfState.address, indexedTokenFactory);
|
|
206
323
|
counts.tokenFactory += 1;
|
|
207
324
|
}
|
|
208
|
-
const
|
|
209
|
-
const
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
325
|
+
const rollupMap = /* @__PURE__ */ new Map();
|
|
326
|
+
for await (const rollupStates of iterateStateTable(statedb, "rollup", batchSize)) for (const rollupState of rollupStates) if (rollupState?.address) rollupMap.set(rollupState.address, rollupState);
|
|
327
|
+
const validatorPairKey = (sender, receiver) => `${String(sender)}\u0000${String(receiver)}`;
|
|
328
|
+
const validatorStakes = /* @__PURE__ */ new Map();
|
|
329
|
+
for (const rollupState of rollupMap.values()) for (const v of [...rollupState.seedValidators || [], ...rollupState.validators || []]) if (v?.address) validatorStakes.set(validatorPairKey(v.address, rollupState.address), null);
|
|
330
|
+
for await (const stakeStates of iterateStateTable(statedb, "stake", batchSize)) for (const stake of stakeStates) {
|
|
331
|
+
for (const [tokenAddr, sum] of sums) {
|
|
332
|
+
const activeStr = stake?.tokens?.[tokenAddr];
|
|
333
|
+
if (activeStr) {
|
|
334
|
+
const val = new _ocap_util.BN(activeStr);
|
|
335
|
+
if (val.gt(zero)) if (stake.receiver === vaultAddresses.moderator) sum.gasStake = sum.gasStake.add(val);
|
|
336
|
+
else sum.stake = sum.stake.add(val);
|
|
337
|
+
}
|
|
338
|
+
const revokedStr = stake?.revokedTokens?.[tokenAddr];
|
|
339
|
+
if (revokedStr) {
|
|
340
|
+
const val = new _ocap_util.BN(revokedStr);
|
|
341
|
+
if (val.gt(zero)) sum.revokedStake = sum.revokedStake.add(val);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
if (!stake?.address) continue;
|
|
345
|
+
const pairKey = validatorPairKey(stake.sender, stake.receiver);
|
|
346
|
+
if (validatorStakes.get(pairKey) === null) validatorStakes.set(pairKey, stake);
|
|
347
|
+
const indexedStake = await require_util.createIndexedStake(stake, { tokenStates: allTokenInfos }, indexdb);
|
|
348
|
+
await upsertIndexRecord(indexdb.stake, stake.address, indexedStake);
|
|
215
349
|
counts.stake += 1;
|
|
216
350
|
}
|
|
217
|
-
const
|
|
218
|
-
const rollupMap = /* @__PURE__ */ new Map();
|
|
219
|
-
for (const rollupState of rollupStates) {
|
|
220
|
-
if (!rollupState?.address) continue;
|
|
221
|
-
rollupMap.set(rollupState.address, rollupState);
|
|
351
|
+
for (const rollupState of rollupMap.values()) {
|
|
222
352
|
const indexedRollup = require_util.createIndexedRollup(rollupState, { tokenStates: allTokenInfos });
|
|
223
353
|
await upsertIndexRecord(indexdb.rollup, rollupState.address, indexedRollup);
|
|
224
354
|
counts.rollup += 1;
|
|
@@ -229,8 +359,8 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
229
359
|
...v
|
|
230
360
|
});
|
|
231
361
|
for (const v of validatorMap.values()) {
|
|
232
|
-
const matchingStake =
|
|
233
|
-
const account =
|
|
362
|
+
const matchingStake = validatorStakes.get(validatorPairKey(v.address, rollupState.address)) || void 0;
|
|
363
|
+
const account = await lookup("account", v.address);
|
|
234
364
|
const totalStake = matchingStake?.tokens?.[rollupState.tokenAddress] || "0";
|
|
235
365
|
const revokedStake = matchingStake?.revokedTokens?.[rollupState.tokenAddress] || "0";
|
|
236
366
|
const validatorDoc = {
|
|
@@ -256,9 +386,7 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
256
386
|
counts.rollupValidator += 1;
|
|
257
387
|
}
|
|
258
388
|
}
|
|
259
|
-
const
|
|
260
|
-
rollupBlockStates.sort((a, b) => Number(a.height || 0) - Number(b.height || 0));
|
|
261
|
-
for (const blockState of rollupBlockStates) {
|
|
389
|
+
for await (const blockState of iterateRollupBlocksByHeight(statedb, batchSize)) {
|
|
262
390
|
if (!blockState?.hash) continue;
|
|
263
391
|
const indexedBlock = require_util.createIndexedRollupBlock(blockState, {
|
|
264
392
|
rollupState: rollupMap.get(blockState.rollup),
|
|
@@ -280,76 +408,32 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
280
408
|
}
|
|
281
409
|
}
|
|
282
410
|
}
|
|
283
|
-
if (!preserveTx) {
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
factoryMap,
|
|
294
|
-
stakeMap,
|
|
295
|
-
rollupMap,
|
|
296
|
-
delegationMap,
|
|
297
|
-
tokenFactoryMap
|
|
298
|
-
}), indexdb);
|
|
299
|
-
await upsertIndexRecord(indexdb.tx, txState.hash, indexedTx);
|
|
300
|
-
counts.tx += 1;
|
|
301
|
-
}
|
|
411
|
+
if (!preserveTx) for await (const txStates of iterateStateTable(statedb, "tx", batchSize)) for (const txState of txStates) {
|
|
412
|
+
if (!txState?.hash) continue;
|
|
413
|
+
const txClone = JSON.parse(JSON.stringify(txState));
|
|
414
|
+
const indexedTx = await require_util.createIndexedTransaction(txClone, await buildSyntheticTxContext(txClone, {
|
|
415
|
+
lookup,
|
|
416
|
+
tokenInfoMap,
|
|
417
|
+
rollupMap
|
|
418
|
+
}), indexdb);
|
|
419
|
+
await upsertIndexRecord(indexdb.tx, txState.hash, indexedTx);
|
|
420
|
+
counts.tx += 1;
|
|
302
421
|
}
|
|
303
|
-
const vaultAddresses = {
|
|
304
|
-
gas: chainState?.vaults?.gas?.address || "",
|
|
305
|
-
fee: chainState?.vaults?.fee?.address || "",
|
|
306
|
-
slashed: chainState?.vaults?.slash?.address || "",
|
|
307
|
-
moderator: chainState?.moderator?.address || ""
|
|
308
|
-
};
|
|
309
422
|
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
310
423
|
for (const tokenInfo of allTokenInfos) {
|
|
311
424
|
const tokenAddr = tokenInfo.address;
|
|
312
425
|
if (!tokenAddr) continue;
|
|
313
|
-
|
|
314
|
-
let gasSum = new _ocap_util.BN(0);
|
|
315
|
-
let feeSum = new _ocap_util.BN(0);
|
|
316
|
-
let slashedSum = new _ocap_util.BN(0);
|
|
317
|
-
let stakeSum = new _ocap_util.BN(0);
|
|
318
|
-
let revokedStakeSum = new _ocap_util.BN(0);
|
|
319
|
-
let gasStakeSum = new _ocap_util.BN(0);
|
|
320
|
-
for (const acc of accountStates) {
|
|
321
|
-
const balStr = acc.tokens?.[tokenAddr];
|
|
322
|
-
if (!balStr) continue;
|
|
323
|
-
const bal = new _ocap_util.BN(balStr);
|
|
324
|
-
if (bal.lte(new _ocap_util.BN(0))) continue;
|
|
325
|
-
if (acc.address === vaultAddresses.gas) gasSum = gasSum.add(bal);
|
|
326
|
-
else if (acc.address === vaultAddresses.fee) feeSum = feeSum.add(bal);
|
|
327
|
-
else if (acc.address === vaultAddresses.slashed) slashedSum = slashedSum.add(bal);
|
|
328
|
-
else accountSum = accountSum.add(bal);
|
|
329
|
-
}
|
|
330
|
-
for (const stake of stakeStates) {
|
|
331
|
-
const activeStr = stake.tokens?.[tokenAddr];
|
|
332
|
-
if (activeStr) {
|
|
333
|
-
const val = new _ocap_util.BN(activeStr);
|
|
334
|
-
if (val.gt(new _ocap_util.BN(0))) if (stake.receiver === vaultAddresses.moderator) gasStakeSum = gasStakeSum.add(val);
|
|
335
|
-
else stakeSum = stakeSum.add(val);
|
|
336
|
-
}
|
|
337
|
-
const revokedStr = stake.revokedTokens?.[tokenAddr];
|
|
338
|
-
if (revokedStr) {
|
|
339
|
-
const val = new _ocap_util.BN(revokedStr);
|
|
340
|
-
if (val.gt(new _ocap_util.BN(0))) revokedStakeSum = revokedStakeSum.add(val);
|
|
341
|
-
}
|
|
342
|
-
}
|
|
426
|
+
const sum = sums.get(tokenAddr);
|
|
343
427
|
const distDoc = require_util.createIndexedTokenDistribution({
|
|
344
428
|
tokenAddress: tokenAddr,
|
|
345
429
|
txTime: nowIso,
|
|
346
|
-
account:
|
|
347
|
-
gas:
|
|
348
|
-
fee:
|
|
349
|
-
slashedVault:
|
|
350
|
-
stake:
|
|
351
|
-
revokedStake:
|
|
352
|
-
gasStake:
|
|
430
|
+
account: sum.account,
|
|
431
|
+
gas: sum.gas,
|
|
432
|
+
fee: sum.fee,
|
|
433
|
+
slashedVault: sum.slashed,
|
|
434
|
+
stake: sum.stake,
|
|
435
|
+
revokedStake: sum.revokedStake,
|
|
436
|
+
gasStake: sum.gasStake
|
|
353
437
|
});
|
|
354
438
|
await upsertIndexRecord(indexdb.tokenDistribution, tokenAddr, distDoc);
|
|
355
439
|
counts.tokenDistribution += 1;
|
|
@@ -361,11 +445,12 @@ async function rebuildIndexFromState(indexdb, statedb, options) {
|
|
|
361
445
|
};
|
|
362
446
|
}
|
|
363
447
|
/**
|
|
364
|
-
* Reconstruct a FinalizedContext from a persisted ITransactionState and StateDB
|
|
448
|
+
* Reconstruct a FinalizedContext from a persisted ITransactionState and the StateDB records it references
|
|
365
449
|
* so `createIndexedTransaction` can populate entity references (`accounts`, `assets`,
|
|
366
450
|
* `tokens`, `factories`, `stakes`, `rollups`, `delegations`, `tokenFactories`, `tokenSymbols`).
|
|
367
451
|
*/
|
|
368
|
-
function buildSyntheticTxContext(txState,
|
|
452
|
+
async function buildSyntheticTxContext(txState, refs) {
|
|
453
|
+
const { lookup } = refs;
|
|
369
454
|
const itx = txState.tx?.itxJson || {};
|
|
370
455
|
const txType = itx.type_url || (txState.type ? `fg:t:${txState.type}` : "");
|
|
371
456
|
const updatedAccounts = [];
|
|
@@ -374,22 +459,24 @@ function buildSyntheticTxContext(txState, maps) {
|
|
|
374
459
|
const stakeStates = [];
|
|
375
460
|
const addTokenByAddr = (addr) => {
|
|
376
461
|
if (typeof addr !== "string" || !addr) return;
|
|
377
|
-
const info =
|
|
462
|
+
const info = refs.tokenInfoMap.get(addr);
|
|
378
463
|
if (info && !tokenStates.some((t) => t.address === addr)) tokenStates.push(info);
|
|
379
464
|
};
|
|
380
|
-
const addAssetByAddr = (addr) => {
|
|
465
|
+
const addAssetByAddr = async (addr) => {
|
|
381
466
|
if (typeof addr !== "string" || !addr) return;
|
|
382
|
-
const asset =
|
|
467
|
+
const asset = await lookup("asset", addr);
|
|
383
468
|
if (asset && !assetStates.some((a) => a.address === addr)) assetStates.push(asset);
|
|
384
469
|
};
|
|
385
470
|
for (const receipt of txState.receipts || []) {
|
|
386
|
-
if (typeof receipt.address === "string" && receipt.address)
|
|
387
|
-
const s =
|
|
388
|
-
if (
|
|
389
|
-
|
|
471
|
+
if (typeof receipt.address === "string" && receipt.address) {
|
|
472
|
+
const s = await lookup("stake", receipt.address);
|
|
473
|
+
if (s) {
|
|
474
|
+
if (!stakeStates.some((x) => x.address === s.address)) stakeStates.push(s);
|
|
475
|
+
} else updatedAccounts.push({ address: receipt.address });
|
|
476
|
+
}
|
|
390
477
|
for (const change of receipt.changes || []) if (typeof change.target === "string" && change.target) {
|
|
391
478
|
addTokenByAddr(change.target);
|
|
392
|
-
addAssetByAddr(change.target);
|
|
479
|
+
await addAssetByAddr(change.target);
|
|
393
480
|
}
|
|
394
481
|
}
|
|
395
482
|
const itxAddress = typeof itx.address === "string" ? itx.address : "";
|
|
@@ -399,19 +486,19 @@ function buildSyntheticTxContext(txState, maps) {
|
|
|
399
486
|
const itxTokenAddress = typeof itx.tokenAddress === "string" ? itx.tokenAddress : "";
|
|
400
487
|
addTokenByAddr(itxToken);
|
|
401
488
|
addTokenByAddr(itxTokenAddress);
|
|
402
|
-
addAssetByAddr(itxAddress);
|
|
489
|
+
await addAssetByAddr(itxAddress);
|
|
403
490
|
if (Array.isArray(itx.tokens)) for (const t of itx.tokens) addTokenByAddr(t?.address);
|
|
404
|
-
if (Array.isArray(itx.assets)) for (const a of itx.assets) addAssetByAddr(a);
|
|
405
|
-
const factoryState =
|
|
406
|
-
const rollupState =
|
|
407
|
-
const delegationState =
|
|
408
|
-
const tokenFactoryState =
|
|
409
|
-
const stakeState =
|
|
410
|
-
const assetState =
|
|
491
|
+
if (Array.isArray(itx.assets)) for (const a of itx.assets) await addAssetByAddr(a);
|
|
492
|
+
const factoryState = await lookup("factory", itxFactory || itxAddress);
|
|
493
|
+
const rollupState = refs.rollupMap.get(itxRollup || itxAddress);
|
|
494
|
+
const delegationState = await lookup("delegation", itxAddress);
|
|
495
|
+
const tokenFactoryState = await lookup("tokenFactory", itxAddress || itx.factoryAddress || "");
|
|
496
|
+
const stakeState = await lookup("stake", itxAddress);
|
|
497
|
+
const assetState = await lookup("asset", itxAddress);
|
|
411
498
|
return {
|
|
412
499
|
txType,
|
|
413
|
-
senderState: txState.sender ?
|
|
414
|
-
receiverState: txState.receiver ?
|
|
500
|
+
senderState: txState.sender ? await lookup("account", txState.sender) || { address: txState.sender } : void 0,
|
|
501
|
+
receiverState: txState.receiver ? await lookup("account", txState.receiver) || { address: txState.receiver } : void 0,
|
|
415
502
|
updatedAccounts,
|
|
416
503
|
assetState,
|
|
417
504
|
assetStates: assetStates.length > 0 ? assetStates : void 0,
|
|
@@ -427,6 +514,8 @@ function buildSyntheticTxContext(txState, maps) {
|
|
|
427
514
|
}
|
|
428
515
|
|
|
429
516
|
//#endregion
|
|
517
|
+
exports.REBUILD_BATCH_SIZE = REBUILD_BATCH_SIZE;
|
|
430
518
|
exports.clearIndexDB = clearIndexDB;
|
|
519
|
+
exports.iterateStateTable = iterateStateTable;
|
|
431
520
|
exports.rebuildIndexFromState = rebuildIndexFromState;
|
|
432
521
|
exports.scanStateTable = scanStateTable;
|
package/lib/rebuild.d.cts
CHANGED
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
import { IIndexDB, IRebuildOptions, IRebuildResult, IStateDB } from "@ocap/types";
|
|
2
2
|
|
|
3
3
|
//#region src/rebuild.d.ts
|
|
4
|
-
|
|
4
|
+
/** Rows per StateDB read during a rebuild: memory stays bounded by this, not by the table size. */
|
|
5
|
+
declare const REBUILD_BATCH_SIZE = 500;
|
|
6
|
+
/**
|
|
7
|
+
* Pages of a StateDB table, `batchSize` records each. SQLite tables are read page by page (keyset on rowid), so the
|
|
8
|
+
* memory of a rebuild does not grow with the table; other adapters (in-memory LokiJS, `listAll`, Dolt) are scanned
|
|
9
|
+
* whole as before and handed out in pages.
|
|
10
|
+
*/
|
|
11
|
+
declare function iterateStateTable<T = Record<string, unknown>>(statedb: IStateDB | Record<string, unknown>, tableName: string, batchSize?: number): AsyncGenerator<T[]>;
|
|
5
12
|
/**
|
|
6
13
|
* Scan all records from a StateDB table across Memory, SQLite, and Dolt adapters.
|
|
7
14
|
*/
|
|
@@ -13,8 +20,14 @@ declare function clearIndexDB(indexdb: IIndexDB, options?: {
|
|
|
13
20
|
preserveTx?: boolean;
|
|
14
21
|
}): Promise<void>;
|
|
15
22
|
/**
|
|
16
|
-
* Deterministically rebuild IndexDB from StateDB (`vledger index rebuild
|
|
23
|
+
* Deterministically rebuild IndexDB from StateDB (`vledger index rebuild`, follower initial index build).
|
|
24
|
+
*
|
|
25
|
+
* Memory is bounded by `options.batchSize` (default `REBUILD_BATCH_SIZE`) on SQLite: every table is read page by
|
|
26
|
+
* page and the records a transaction references are read by primary key, never held as whole-table arrays or maps.
|
|
27
|
+
* Only the token metadata and the rollup states (small tables every other step needs) stay in memory.
|
|
17
28
|
*/
|
|
18
|
-
declare function rebuildIndexFromState(indexdb: IIndexDB, statedb: IStateDB, options?: IRebuildOptions
|
|
29
|
+
declare function rebuildIndexFromState(indexdb: IIndexDB, statedb: IStateDB, options?: IRebuildOptions & {
|
|
30
|
+
batchSize?: number;
|
|
31
|
+
}): Promise<IRebuildResult>;
|
|
19
32
|
//#endregion
|
|
20
|
-
export { clearIndexDB, rebuildIndexFromState, scanStateTable };
|
|
33
|
+
export { REBUILD_BATCH_SIZE, clearIndexDB, iterateStateTable, rebuildIndexFromState, scanStateTable };
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"publishConfig": {
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
|
-
"version": "1.32.
|
|
6
|
+
"version": "1.32.2",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"description": "Defines the basic interface for OCAP IndexDB",
|
|
9
9
|
"main": "./lib/main.cjs",
|
|
@@ -52,9 +52,9 @@
|
|
|
52
52
|
"tsdown": "^0.18.4"
|
|
53
53
|
},
|
|
54
54
|
"dependencies": {
|
|
55
|
-
"@ocap/state": "1.32.
|
|
56
|
-
"@ocap/types": "1.32.
|
|
57
|
-
"@ocap/util": "1.32.
|
|
55
|
+
"@ocap/state": "1.32.2",
|
|
56
|
+
"@ocap/types": "1.32.2",
|
|
57
|
+
"@ocap/util": "1.32.2",
|
|
58
58
|
"kareem": "^2.4.1",
|
|
59
59
|
"lodash": "^4.17.23"
|
|
60
60
|
}
|