@ocap/indexdb 1.30.24 → 1.30.25

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/db.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Ready } from "@ocap/util/lib/ready";
2
- import { IIndexDB, IIndexTable, IListAccountsResult, IListAssetsResult, IListDelegationsResult, IListFactoriesResult, IListRollupBlocksResult, IListRollupValidatorsResult, IListRollupsResult, IListStakesResult, IListTokenFactoriesResult, IListTokensResult, IListTransactionsResult, IndexTableTypeMap, Promisable, TRequestListAssets, TRequestListDelegations, TRequestListFactories, TRequestListRollupBlocks, TRequestListRollupValidators, TRequestListRollups, TRequestListStakes, TRequestListTokenFactories, TRequestListTokens, TRequestListTopAccounts, TRequestListTransactions, TSearchResult } from "@ocap/types";
2
+ import { IIndexDB, IIndexTable, IListAccountsResult, IListAssetsResult, IListDelegationsResult, IListFactoriesResult, IListRollupBlocksResult, IListRollupValidatorsResult, IListRollupsResult, IListStakesResult, IListTokenFactoriesResult, IListTokensResult, IListTransactionsResult, IRebuildOptions, IRebuildResult, IStateDB, IndexTableTypeMap, Promisable, TRequestListAssets, TRequestListDelegations, TRequestListFactories, TRequestListRollupBlocks, TRequestListRollupValidators, TRequestListRollups, TRequestListStakes, TRequestListTokenFactories, TRequestListTokens, TRequestListTopAccounts, TRequestListTransactions, TSearchResult } from "@ocap/types";
3
3
 
4
4
  //#region src/db.d.ts
5
5
  declare class BaseIndexDB extends Ready implements IIndexDB {
@@ -37,6 +37,10 @@ declare class BaseIndexDB extends Ready implements IIndexDB {
37
37
  getRelatedAddresses(_address: string): Promisable<string[]>;
38
38
  listBlocks(): unknown[];
39
39
  close(): Promise<void>;
40
+ clear(options?: {
41
+ preserveTx?: boolean;
42
+ }): Promise<void>;
43
+ rebuild(statedb: IStateDB, options?: IRebuildOptions): Promise<IRebuildResult>;
40
44
  }
41
45
  //#endregion
42
46
  export { BaseIndexDB as default };
package/esm/db.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { clearIndexDB, rebuildIndexFromState } from "./rebuild.mjs";
1
2
  import { indexes } from "@ocap/state";
2
3
  import { Ready } from "@ocap/util/lib/ready";
3
4
 
@@ -59,6 +60,12 @@ var BaseIndexDB = class extends Ready {
59
60
  return [];
60
61
  }
61
62
  async close() {}
63
+ async clear(options) {
64
+ await clearIndexDB(this, options);
65
+ }
66
+ async rebuild(statedb, options) {
67
+ return rebuildIndexFromState(this, statedb, options);
68
+ }
62
69
  };
63
70
  var db_default = BaseIndexDB;
64
71
 
package/esm/main.d.mts CHANGED
@@ -2,4 +2,5 @@ import BaseIndexDB from "./db.mjs";
2
2
  import BaseIndex from "./index.mjs";
3
3
  import { SearchResultFormatOptions, formatSearchResult } from "./search-result.mjs";
4
4
  import { DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime } from "./util.mjs";
5
- export { BaseIndex, BaseIndexDB, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, type SearchResultFormatOptions, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime };
5
+ import { clearIndexDB, rebuildIndexFromState, scanStateTable } from "./rebuild.mjs";
6
+ export { BaseIndex, BaseIndexDB, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, type SearchResultFormatOptions, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, clearIndexDB, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime, rebuildIndexFromState, scanStateTable };
package/esm/main.mjs CHANGED
@@ -1,6 +1,7 @@
1
+ import { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime } from "./util.mjs";
2
+ import { clearIndexDB, rebuildIndexFromState, scanStateTable } from "./rebuild.mjs";
1
3
  import db_default from "./db.mjs";
2
4
  import src_default from "./index.mjs";
3
5
  import { formatSearchResult } from "./search-result.mjs";
4
- import { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime } from "./util.mjs";
5
6
 
6
- export { src_default as BaseIndex, db_default as BaseIndexDB, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime };
7
+ export { src_default as BaseIndex, db_default as BaseIndexDB, clearIndexDB, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime, rebuildIndexFromState, scanStateTable };
@@ -0,0 +1,20 @@
1
+ import { IIndexDB, IRebuildOptions, IRebuildResult, IStateDB } from "@ocap/types";
2
+
3
+ //#region src/rebuild.d.ts
4
+
5
+ /**
6
+ * Scan all records from a StateDB table across Memory, SQLite, and Dolt adapters.
7
+ */
8
+ declare function scanStateTable<T = Record<string, unknown>>(statedb: IStateDB | Record<string, unknown>, tableName: string): Promise<T[]>;
9
+ /**
10
+ * Clear all IndexDB tables (or state-only tables when `preserveTx` is true).
11
+ */
12
+ declare function clearIndexDB(indexdb: IIndexDB, options?: {
13
+ preserveTx?: boolean;
14
+ }): Promise<void>;
15
+ /**
16
+ * Deterministically rebuild IndexDB from StateDB (`vledger index rebuild`).
17
+ */
18
+ declare function rebuildIndexFromState(indexdb: IIndexDB, statedb: IStateDB, options?: IRebuildOptions): Promise<IRebuildResult>;
19
+ //#endregion
20
+ export { clearIndexDB, rebuildIndexFromState, scanStateTable };
@@ -0,0 +1,429 @@
1
+ import { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction } from "./util.mjs";
2
+ import { BN } from "@ocap/util";
3
+
4
+ //#region src/rebuild.ts
5
+ const INDEX_TABLES_STATE_ONLY = [
6
+ "account",
7
+ "asset",
8
+ "delegation",
9
+ "factory",
10
+ "token",
11
+ "stake",
12
+ "rollup",
13
+ "rollupBlock",
14
+ "rollupValidator",
15
+ "tokenDistribution",
16
+ "tokenFactory",
17
+ "indexFailure",
18
+ "balance"
19
+ ];
20
+ /**
21
+ * Scan all records from a StateDB table across Memory, SQLite, and Dolt adapters.
22
+ */
23
+ async function scanStateTable(statedb, tableName) {
24
+ const table = statedb?.[tableName];
25
+ if (!table) return [];
26
+ if (typeof table.listAll === "function") return await table.listAll() || [];
27
+ const collection = table.collection;
28
+ if (collection && typeof collection.find === "function") {
29
+ const rawRows = collection.find({});
30
+ const results = [];
31
+ const syncBalance = Boolean(table.syncBalance);
32
+ const balanceTable = table.balanceTable;
33
+ for (const row of rawRows) {
34
+ if (!row || typeof row !== "object") continue;
35
+ const cloned = { ...row };
36
+ delete cloned.$loki;
37
+ delete cloned.meta;
38
+ const item = typeof table._deserialize === "function" ? table._deserialize(cloned) ?? cloned : cloned;
39
+ if (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
+ results.push(item);
47
+ }
48
+ return results;
49
+ }
50
+ const db = table.db;
51
+ if (db && typeof db.selectFrom === "function" && typeof table.name === "string") {
52
+ const rawRows = await db.selectFrom(table.name).selectAll().execute();
53
+ const results = [];
54
+ const syncBalance = Boolean(table.syncBalance);
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
+ }
67
+ return results;
68
+ }
69
+ if (typeof table.driver === "function" && typeof table.name === "string") {
70
+ const rawRows = await table.driver(table.name).select("*");
71
+ const results = [];
72
+ for (const row of rawRows) {
73
+ const item = typeof table._formatAfterRetrieve === "function" ? await table._formatAfterRetrieve(row, {}) : row;
74
+ results.push(item);
75
+ }
76
+ return results;
77
+ }
78
+ return [];
79
+ }
80
+ /**
81
+ * Clear all IndexDB tables (or state-only tables when `preserveTx` is true).
82
+ */
83
+ async function clearIndexDB(indexdb, options) {
84
+ const dbRecord = indexdb;
85
+ const tableNames = [...INDEX_TABLES_STATE_ONLY];
86
+ if (!options?.preserveTx) tableNames.push("tx");
87
+ for (const name of tableNames) {
88
+ const table = dbRecord[name];
89
+ if (table && typeof table.reset === "function") await table.reset();
90
+ }
91
+ }
92
+ /**
93
+ * Insert or update a record in an IIndexTable (which provides `get`, `insert`, `update`).
94
+ */
95
+ async function upsertIndexRecord(table, key, doc) {
96
+ if (!table) return;
97
+ if (await table.get(key)) await table.update(key, doc);
98
+ else await table.insert(doc);
99
+ }
100
+ /**
101
+ * Deterministically rebuild IndexDB from StateDB (`vledger index rebuild`).
102
+ */
103
+ async function rebuildIndexFromState(indexdb, statedb, options) {
104
+ const startTime = Date.now();
105
+ const preserveTx = Boolean(options?.preserveTx);
106
+ await clearIndexDB(indexdb, { preserveTx });
107
+ const counts = {
108
+ token: 0,
109
+ asset: 0,
110
+ account: 0,
111
+ delegation: 0,
112
+ factory: 0,
113
+ tokenFactory: 0,
114
+ stake: 0,
115
+ rollup: 0,
116
+ rollupValidator: 0,
117
+ rollupBlock: 0,
118
+ tokenDistribution: 0
119
+ };
120
+ if (!preserveTx) counts.tx = 0;
121
+ let chainState = null;
122
+ if (options?.chainAddress) chainState = await statedb.chain.get(options.chainAddress);
123
+ if (!chainState) chainState = (await scanStateTable(statedb, "chain"))[0] || null;
124
+ const tokenStates = await scanStateTable(statedb, "token");
125
+ const tokenInfoMap = /* @__PURE__ */ new Map();
126
+ if (chainState?.token?.address) tokenInfoMap.set(chainState.token.address, {
127
+ address: chainState.token.address,
128
+ decimal: chainState.token.decimal,
129
+ unit: chainState.token.unit,
130
+ symbol: chainState.token.symbol,
131
+ icon: chainState.token.icon,
132
+ foreignToken: chainState.token.foreignToken
133
+ });
134
+ for (const tokenState of tokenStates) {
135
+ if (!tokenState?.address) continue;
136
+ tokenInfoMap.set(tokenState.address, {
137
+ address: tokenState.address,
138
+ decimal: tokenState.decimal,
139
+ unit: tokenState.unit,
140
+ symbol: tokenState.symbol,
141
+ icon: tokenState.icon,
142
+ foreignToken: tokenState.foreignToken
143
+ });
144
+ const indexedToken = createIndexedToken(tokenState);
145
+ await upsertIndexRecord(indexdb.token, tokenState.address, indexedToken);
146
+ counts.token += 1;
147
+ }
148
+ const allTokenInfos = Array.from(tokenInfoMap.values());
149
+ const getTokenFn = async (address) => {
150
+ const cached = tokenInfoMap.get(address);
151
+ if (cached) return cached;
152
+ return await indexdb.token.get(address) || null;
153
+ };
154
+ const assetStates = await scanStateTable(statedb, "asset");
155
+ const assetMap = /* @__PURE__ */ new Map();
156
+ for (const assetState of assetStates) {
157
+ if (!assetState?.address) continue;
158
+ assetMap.set(assetState.address, assetState);
159
+ const indexedAsset = createIndexedAsset(assetState);
160
+ await upsertIndexRecord(indexdb.asset, assetState.address, indexedAsset);
161
+ counts.asset += 1;
162
+ }
163
+ const accountStates = await scanStateTable(statedb, "account");
164
+ const accountMap = /* @__PURE__ */ new Map();
165
+ for (const accountState of accountStates) {
166
+ if (!accountState?.address) continue;
167
+ accountMap.set(accountState.address, accountState);
168
+ const indexedAccount = await createIndexedAccount(accountState, getTokenFn);
169
+ await upsertIndexRecord(indexdb.account, accountState.address, indexedAccount);
170
+ counts.account += 1;
171
+ }
172
+ const delegationStates = await scanStateTable(statedb, "delegation");
173
+ const delegationMap = /* @__PURE__ */ new Map();
174
+ for (const delegationState of delegationStates) {
175
+ if (!delegationState?.address) continue;
176
+ delegationMap.set(delegationState.address, delegationState);
177
+ const indexedDelegation = createIndexedDelegation(delegationState, {});
178
+ await upsertIndexRecord(indexdb.delegation, delegationState.address, indexedDelegation);
179
+ counts.delegation += 1;
180
+ }
181
+ const factoryStates = await scanStateTable(statedb, "factory");
182
+ const factoryMap = /* @__PURE__ */ new Map();
183
+ for (const factoryState of factoryStates) {
184
+ if (!factoryState?.address) continue;
185
+ factoryMap.set(factoryState.address, factoryState);
186
+ const indexedFactory = createIndexedFactory(factoryState, {
187
+ factoryTokens: factoryState.input?.tokens,
188
+ tokenStates: allTokenInfos
189
+ });
190
+ await upsertIndexRecord(indexdb.factory, factoryState.address, indexedFactory);
191
+ counts.factory += 1;
192
+ }
193
+ const tokenFactoryStates = await scanStateTable(statedb, "tokenFactory");
194
+ const tokenFactoryMap = /* @__PURE__ */ new Map();
195
+ for (const tfState of tokenFactoryStates) {
196
+ if (!tfState?.address) continue;
197
+ tokenFactoryMap.set(tfState.address, tfState);
198
+ const tokenInfo = tokenInfoMap.get(tfState.tokenAddress);
199
+ const reserveInfo = tokenInfoMap.get(tfState.reserveAddress) || chainState?.token;
200
+ const indexedTokenFactory = createIndexedTokenFactory(tfState, {
201
+ itx: { token: tokenInfo },
202
+ config: { token: reserveInfo }
203
+ });
204
+ await upsertIndexRecord(indexdb.tokenFactory, tfState.address, indexedTokenFactory);
205
+ counts.tokenFactory += 1;
206
+ }
207
+ const stakeStates = await scanStateTable(statedb, "stake");
208
+ const stakeMap = /* @__PURE__ */ new Map();
209
+ for (const stakeState of stakeStates) {
210
+ if (!stakeState?.address) continue;
211
+ stakeMap.set(stakeState.address, stakeState);
212
+ const indexedStake = await createIndexedStake(stakeState, { tokenStates: allTokenInfos }, indexdb);
213
+ await upsertIndexRecord(indexdb.stake, stakeState.address, indexedStake);
214
+ counts.stake += 1;
215
+ }
216
+ const rollupStates = await scanStateTable(statedb, "rollup");
217
+ const rollupMap = /* @__PURE__ */ new Map();
218
+ for (const rollupState of rollupStates) {
219
+ if (!rollupState?.address) continue;
220
+ rollupMap.set(rollupState.address, rollupState);
221
+ const indexedRollup = createIndexedRollup(rollupState, { tokenStates: allTokenInfos });
222
+ await upsertIndexRecord(indexdb.rollup, rollupState.address, indexedRollup);
223
+ counts.rollup += 1;
224
+ const validatorMap = /* @__PURE__ */ new Map();
225
+ for (const v of rollupState.seedValidators || []) if (v?.address) validatorMap.set(v.address, v);
226
+ for (const v of rollupState.validators || []) if (v?.address) validatorMap.set(v.address, {
227
+ ...validatorMap.get(v.address),
228
+ ...v
229
+ });
230
+ for (const v of validatorMap.values()) {
231
+ const matchingStake = Array.from(stakeMap.values()).find((s) => s.sender === v.address && s.receiver === rollupState.address);
232
+ const account = accountMap.get(v.address);
233
+ const totalStake = matchingStake?.tokens?.[rollupState.tokenAddress] || "0";
234
+ const revokedStake = matchingStake?.revokedTokens?.[rollupState.tokenAddress] || "0";
235
+ const validatorDoc = {
236
+ rollup: rollupState.address,
237
+ address: v.address,
238
+ pk: v.pk || "",
239
+ endpoint: v.endpoint || "",
240
+ moniker: v.moniker || account?.moniker || "",
241
+ joinTime: rollupState.context?.genesisTime || "",
242
+ leaveTime: "",
243
+ genesisTime: rollupState.context?.genesisTime || "",
244
+ renaissanceTime: rollupState.context?.renaissanceTime || "",
245
+ totalStake,
246
+ revokedStake,
247
+ availableStake: "0",
248
+ totalGain: "0",
249
+ proposedBlockCount: 0,
250
+ verifiedBlockCount: 0,
251
+ latestBlockHeight: 0,
252
+ latestBlockHash: ""
253
+ };
254
+ await upsertIndexRecord(indexdb.rollupValidator, v.address, validatorDoc);
255
+ counts.rollupValidator += 1;
256
+ }
257
+ }
258
+ const rollupBlockStates = await scanStateTable(statedb, "rollupBlock");
259
+ rollupBlockStates.sort((a, b) => Number(a.height || 0) - Number(b.height || 0));
260
+ for (const blockState of rollupBlockStates) {
261
+ if (!blockState?.hash) continue;
262
+ const indexedBlock = createIndexedRollupBlock(blockState, {
263
+ rollupState: rollupMap.get(blockState.rollup),
264
+ tokenStates: allTokenInfos
265
+ });
266
+ await upsertIndexRecord(indexdb.rollupBlock, blockState.hash, indexedBlock);
267
+ counts.rollupBlock += 1;
268
+ for (const signerAddr of indexedBlock.validators || []) {
269
+ const existingValidator = await indexdb.rollupValidator.get(signerAddr);
270
+ if (existingValidator) {
271
+ existingValidator.verifiedBlockCount = (existingValidator.verifiedBlockCount || 0) + 1;
272
+ existingValidator.renaissanceTime = blockState.context?.genesisTime || existingValidator.renaissanceTime;
273
+ if (signerAddr === blockState.proposer) {
274
+ existingValidator.proposedBlockCount = (existingValidator.proposedBlockCount || 0) + 1;
275
+ existingValidator.latestBlockHeight = Number(blockState.height || 0);
276
+ existingValidator.latestBlockHash = blockState.hash;
277
+ }
278
+ await indexdb.rollupValidator.update(signerAddr, existingValidator);
279
+ }
280
+ }
281
+ }
282
+ if (!preserveTx) {
283
+ const txStates = await scanStateTable(statedb, "tx");
284
+ txStates.sort((a, b) => String(a.time || "").localeCompare(String(b.time || "")));
285
+ for (const txState of txStates) {
286
+ if (!txState?.hash) continue;
287
+ const txClone = JSON.parse(JSON.stringify(txState));
288
+ const indexedTx = await createIndexedTransaction(txClone, buildSyntheticTxContext(txClone, {
289
+ accountMap,
290
+ assetMap,
291
+ tokenInfoMap,
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
+ }
301
+ }
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
+ const nowIso = (/* @__PURE__ */ new Date()).toISOString();
309
+ for (const tokenInfo of allTokenInfos) {
310
+ const tokenAddr = tokenInfo.address;
311
+ if (!tokenAddr) continue;
312
+ let accountSum = new BN(0);
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
+ }
342
+ const distDoc = createIndexedTokenDistribution({
343
+ tokenAddress: tokenAddr,
344
+ txTime: nowIso,
345
+ account: accountSum,
346
+ gas: gasSum,
347
+ fee: feeSum,
348
+ slashedVault: slashedSum,
349
+ stake: stakeSum,
350
+ revokedStake: revokedStakeSum,
351
+ gasStake: gasStakeSum
352
+ });
353
+ await upsertIndexRecord(indexdb.tokenDistribution, tokenAddr, distDoc);
354
+ counts.tokenDistribution += 1;
355
+ }
356
+ return {
357
+ tables: counts,
358
+ totalRecords: Object.values(counts).reduce((sum, n) => sum + n, 0),
359
+ durationMs: Date.now() - startTime
360
+ };
361
+ }
362
+ /**
363
+ * Reconstruct a FinalizedContext from a persisted ITransactionState and StateDB maps
364
+ * so `createIndexedTransaction` can populate entity references (`accounts`, `assets`,
365
+ * `tokens`, `factories`, `stakes`, `rollups`, `delegations`, `tokenFactories`, `tokenSymbols`).
366
+ */
367
+ function buildSyntheticTxContext(txState, maps) {
368
+ const itx = txState.tx?.itxJson || {};
369
+ const txType = itx.type_url || (txState.type ? `fg:t:${txState.type}` : "");
370
+ const updatedAccounts = [];
371
+ const assetStates = [];
372
+ const tokenStates = [];
373
+ const stakeStates = [];
374
+ const addTokenByAddr = (addr) => {
375
+ if (typeof addr !== "string" || !addr) return;
376
+ const info = maps.tokenInfoMap.get(addr);
377
+ if (info && !tokenStates.some((t) => t.address === addr)) tokenStates.push(info);
378
+ };
379
+ const addAssetByAddr = (addr) => {
380
+ if (typeof addr !== "string" || !addr) return;
381
+ const asset = maps.assetMap.get(addr);
382
+ if (asset && !assetStates.some((a) => a.address === addr)) assetStates.push(asset);
383
+ };
384
+ for (const receipt of txState.receipts || []) {
385
+ if (typeof receipt.address === "string" && receipt.address) if (maps.stakeMap.has(receipt.address)) {
386
+ const s = maps.stakeMap.get(receipt.address);
387
+ if (!stakeStates.some((x) => x.address === s.address)) stakeStates.push(s);
388
+ } else updatedAccounts.push({ address: receipt.address });
389
+ for (const change of receipt.changes || []) if (typeof change.target === "string" && change.target) {
390
+ addTokenByAddr(change.target);
391
+ addAssetByAddr(change.target);
392
+ }
393
+ }
394
+ const itxAddress = typeof itx.address === "string" ? itx.address : "";
395
+ const itxFactory = typeof itx.factory === "string" ? itx.factory : "";
396
+ const itxRollup = typeof itx.rollup === "string" ? itx.rollup : "";
397
+ const itxToken = typeof itx.token === "string" ? itx.token : "";
398
+ const itxTokenAddress = typeof itx.tokenAddress === "string" ? itx.tokenAddress : "";
399
+ addTokenByAddr(itxToken);
400
+ addTokenByAddr(itxTokenAddress);
401
+ addAssetByAddr(itxAddress);
402
+ 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 = maps.factoryMap.get(itxFactory || itxAddress);
405
+ const rollupState = maps.rollupMap.get(itxRollup || itxAddress);
406
+ const delegationState = maps.delegationMap.get(itxAddress);
407
+ const tokenFactoryState = maps.tokenFactoryMap.get(itxAddress || itx.factoryAddress || "");
408
+ const stakeState = maps.stakeMap.get(itxAddress);
409
+ const assetState = maps.assetMap.get(itxAddress);
410
+ return {
411
+ txType,
412
+ senderState: txState.sender ? maps.accountMap.get(txState.sender) || { address: txState.sender } : void 0,
413
+ receiverState: txState.receiver ? maps.accountMap.get(txState.receiver) || { address: txState.receiver } : void 0,
414
+ updatedAccounts,
415
+ assetState,
416
+ assetStates: assetStates.length > 0 ? assetStates : void 0,
417
+ tokenStates: tokenStates.length > 0 ? tokenStates : void 0,
418
+ factoryState,
419
+ stakeState,
420
+ stakeStates: stakeStates.length > 0 ? stakeStates : void 0,
421
+ rollupState,
422
+ delegationState,
423
+ tokenFactoryState,
424
+ ownerAddress: assetState?.owner || txState.receiver || txState.sender
425
+ };
426
+ }
427
+
428
+ //#endregion
429
+ export { clearIndexDB, rebuildIndexFromState, scanStateTable };
package/esm/util.mjs CHANGED
@@ -472,9 +472,12 @@ const PAGE_SIZE_MAX = 100;
472
472
  */
473
473
  const formatPagination = ({ paging, defaultSortField, supportedSortFields = [] }) => {
474
474
  if (!defaultSortField) throw new Error("argument defaultSortField is required");
475
+ const rawSize = Number(paging?.size ?? PAGE_SIZE_DEFAULT);
476
+ const safeSize = Number.isFinite(rawSize) && rawSize >= 0 ? Math.floor(rawSize) : PAGE_SIZE_DEFAULT;
477
+ const rawCursor = typeof paging?.cursor === "number" ? paging.cursor : Number(paging?.cursor) || 0;
475
478
  const pagination = {
476
- size: paging?.size ?? PAGE_SIZE_DEFAULT,
477
- cursor: typeof paging?.cursor === "number" ? paging.cursor : Number(paging?.cursor) || 0,
479
+ size: safeSize,
480
+ cursor: Number.isFinite(rawCursor) && rawCursor >= 0 ? Math.floor(rawCursor) : 0,
478
481
  order: {
479
482
  field: defaultSortField,
480
483
  type: "desc"
@@ -484,7 +487,10 @@ const formatPagination = ({ paging, defaultSortField, supportedSortFields = [] }
484
487
  if (Array.isArray(inputOrder)) inputOrder = inputOrder[0];
485
488
  if (inputOrder?.field) pagination.order.field = inputOrder.field;
486
489
  if (supportedSortFields.length > 0 && !supportedSortFields.includes(pagination.order.field)) pagination.order.field = defaultSortField;
487
- if (inputOrder?.type) pagination.order.type = inputOrder.type;
490
+ if (inputOrder?.type) {
491
+ const normalizedType = String(inputOrder.type).toLowerCase();
492
+ pagination.order.type = normalizedType === "asc" || normalizedType === "desc" ? normalizedType : "desc";
493
+ }
488
494
  pagination.size = Math.min(pagination.size, PAGE_SIZE_MAX);
489
495
  return pagination;
490
496
  };
package/lib/db.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
3
+ const require_rebuild = require('./rebuild.cjs');
3
4
  let _ocap_state = require("@ocap/state");
4
5
  let _ocap_util_lib_ready = require("@ocap/util/lib/ready");
5
6
 
@@ -61,6 +62,12 @@ var BaseIndexDB = class extends _ocap_util_lib_ready.Ready {
61
62
  return [];
62
63
  }
63
64
  async close() {}
65
+ async clear(options) {
66
+ await require_rebuild.clearIndexDB(this, options);
67
+ }
68
+ async rebuild(statedb, options) {
69
+ return require_rebuild.rebuildIndexFromState(this, statedb, options);
70
+ }
64
71
  };
65
72
  var db_default = BaseIndexDB;
66
73
 
package/lib/db.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { IIndexDB, IIndexTable, IListAccountsResult, IListAssetsResult, IListDelegationsResult, IListFactoriesResult, IListRollupBlocksResult, IListRollupValidatorsResult, IListRollupsResult, IListStakesResult, IListTokenFactoriesResult, IListTokensResult, IListTransactionsResult, IndexTableTypeMap, Promisable, TRequestListAssets, TRequestListDelegations, TRequestListFactories, TRequestListRollupBlocks, TRequestListRollupValidators, TRequestListRollups, TRequestListStakes, TRequestListTokenFactories, TRequestListTokens, TRequestListTopAccounts, TRequestListTransactions, TSearchResult } from "@ocap/types";
1
+ import { IIndexDB, IIndexTable, IListAccountsResult, IListAssetsResult, IListDelegationsResult, IListFactoriesResult, IListRollupBlocksResult, IListRollupValidatorsResult, IListRollupsResult, IListStakesResult, IListTokenFactoriesResult, IListTokensResult, IListTransactionsResult, IRebuildOptions, IRebuildResult, IStateDB, IndexTableTypeMap, Promisable, TRequestListAssets, TRequestListDelegations, TRequestListFactories, TRequestListRollupBlocks, TRequestListRollupValidators, TRequestListRollups, TRequestListStakes, TRequestListTokenFactories, TRequestListTokens, TRequestListTopAccounts, TRequestListTransactions, TSearchResult } from "@ocap/types";
2
2
  import { Ready } from "@ocap/util/lib/ready";
3
3
 
4
4
  //#region src/db.d.ts
@@ -37,6 +37,10 @@ declare class BaseIndexDB extends Ready implements IIndexDB {
37
37
  getRelatedAddresses(_address: string): Promisable<string[]>;
38
38
  listBlocks(): unknown[];
39
39
  close(): Promise<void>;
40
+ clear(options?: {
41
+ preserveTx?: boolean;
42
+ }): Promise<void>;
43
+ rebuild(statedb: IStateDB, options?: IRebuildOptions): Promise<IRebuildResult>;
40
44
  }
41
45
  //#endregion
42
46
  export { BaseIndexDB as default };
package/lib/main.cjs CHANGED
@@ -1,10 +1,12 @@
1
+ const require_util = require('./util.cjs');
2
+ const require_rebuild = require('./rebuild.cjs');
1
3
  const require_db = require('./db.cjs');
2
4
  const require_index = require('./index.cjs');
3
5
  const require_search_result = require('./search-result.cjs');
4
- const require_util = require('./util.cjs');
5
6
 
6
7
  exports.BaseIndex = require_index.default;
7
8
  exports.BaseIndexDB = require_db.default;
9
+ exports.clearIndexDB = require_rebuild.clearIndexDB;
8
10
  exports.createIndexedAccount = require_util.createIndexedAccount;
9
11
  exports.createIndexedAsset = require_util.createIndexedAsset;
10
12
  exports.createIndexedDelegation = require_util.createIndexedDelegation;
@@ -24,4 +26,6 @@ exports.formatTokenMeta = require_util.formatTokenMeta;
24
26
  exports.formatTxAfterRead = require_util.formatTxAfterRead;
25
27
  exports.formatTxBeforeInsert = require_util.formatTxBeforeInsert;
26
28
  exports.isDefaultTokenChanged = require_util.isDefaultTokenChanged;
27
- exports.parseDateTime = require_util.parseDateTime;
29
+ exports.parseDateTime = require_util.parseDateTime;
30
+ exports.rebuildIndexFromState = require_rebuild.rebuildIndexFromState;
31
+ exports.scanStateTable = require_rebuild.scanStateTable;
package/lib/main.d.cts CHANGED
@@ -2,4 +2,5 @@ import BaseIndexDB from "./db.cjs";
2
2
  import BaseIndex from "./index.cjs";
3
3
  import { SearchResultFormatOptions, formatSearchResult } from "./search-result.cjs";
4
4
  import { DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime } from "./util.cjs";
5
- export { BaseIndex, BaseIndexDB, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, type SearchResultFormatOptions, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime };
5
+ import { clearIndexDB, rebuildIndexFromState, scanStateTable } from "./rebuild.cjs";
6
+ export { BaseIndex, BaseIndexDB, DelegationContext, FactoryContext, FormatPaginationParams, FormattedPagination, IndexDBForTx, PagingInput, RollupBlockContext, RollupContext, type SearchResultFormatOptions, TokenFactoryContext, TokenStateInfo, TokenWithBalance, TxData, clearIndexDB, createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenDistribution, createIndexedTokenFactory, createIndexedTransaction, formatDelegationAfterRead, formatNextPagination, formatPagination, formatSearchResult, formatTokenMeta, formatTxAfterRead, formatTxBeforeInsert, isDefaultTokenChanged, parseDateTime, rebuildIndexFromState, scanStateTable };
@@ -0,0 +1,432 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ const require_util = require('./util.cjs');
3
+ let _ocap_util = require("@ocap/util");
4
+
5
+ //#region src/rebuild.ts
6
+ const INDEX_TABLES_STATE_ONLY = [
7
+ "account",
8
+ "asset",
9
+ "delegation",
10
+ "factory",
11
+ "token",
12
+ "stake",
13
+ "rollup",
14
+ "rollupBlock",
15
+ "rollupValidator",
16
+ "tokenDistribution",
17
+ "tokenFactory",
18
+ "indexFailure",
19
+ "balance"
20
+ ];
21
+ /**
22
+ * Scan all records from a StateDB table across Memory, SQLite, and Dolt adapters.
23
+ */
24
+ async function scanStateTable(statedb, tableName) {
25
+ const table = statedb?.[tableName];
26
+ if (!table) return [];
27
+ if (typeof table.listAll === "function") return await table.listAll() || [];
28
+ const collection = table.collection;
29
+ if (collection && typeof collection.find === "function") {
30
+ const rawRows = collection.find({});
31
+ const results = [];
32
+ const syncBalance = Boolean(table.syncBalance);
33
+ const balanceTable = table.balanceTable;
34
+ for (const row of rawRows) {
35
+ if (!row || typeof row !== "object") continue;
36
+ const cloned = { ...row };
37
+ delete cloned.$loki;
38
+ delete cloned.meta;
39
+ const item = typeof table._deserialize === "function" ? table._deserialize(cloned) ?? cloned : cloned;
40
+ if (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
+ results.push(item);
48
+ }
49
+ return results;
50
+ }
51
+ const db = table.db;
52
+ if (db && typeof db.selectFrom === "function" && typeof table.name === "string") {
53
+ const rawRows = await db.selectFrom(table.name).selectAll().execute();
54
+ const results = [];
55
+ const syncBalance = Boolean(table.syncBalance);
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
+ }
68
+ return results;
69
+ }
70
+ if (typeof table.driver === "function" && typeof table.name === "string") {
71
+ const rawRows = await table.driver(table.name).select("*");
72
+ const results = [];
73
+ for (const row of rawRows) {
74
+ const item = typeof table._formatAfterRetrieve === "function" ? await table._formatAfterRetrieve(row, {}) : row;
75
+ results.push(item);
76
+ }
77
+ return results;
78
+ }
79
+ return [];
80
+ }
81
+ /**
82
+ * Clear all IndexDB tables (or state-only tables when `preserveTx` is true).
83
+ */
84
+ async function clearIndexDB(indexdb, options) {
85
+ const dbRecord = indexdb;
86
+ const tableNames = [...INDEX_TABLES_STATE_ONLY];
87
+ if (!options?.preserveTx) tableNames.push("tx");
88
+ for (const name of tableNames) {
89
+ const table = dbRecord[name];
90
+ if (table && typeof table.reset === "function") await table.reset();
91
+ }
92
+ }
93
+ /**
94
+ * Insert or update a record in an IIndexTable (which provides `get`, `insert`, `update`).
95
+ */
96
+ async function upsertIndexRecord(table, key, doc) {
97
+ if (!table) return;
98
+ if (await table.get(key)) await table.update(key, doc);
99
+ else await table.insert(doc);
100
+ }
101
+ /**
102
+ * Deterministically rebuild IndexDB from StateDB (`vledger index rebuild`).
103
+ */
104
+ async function rebuildIndexFromState(indexdb, statedb, options) {
105
+ const startTime = Date.now();
106
+ const preserveTx = Boolean(options?.preserveTx);
107
+ await clearIndexDB(indexdb, { preserveTx });
108
+ const counts = {
109
+ token: 0,
110
+ asset: 0,
111
+ account: 0,
112
+ delegation: 0,
113
+ factory: 0,
114
+ tokenFactory: 0,
115
+ stake: 0,
116
+ rollup: 0,
117
+ rollupValidator: 0,
118
+ rollupBlock: 0,
119
+ tokenDistribution: 0
120
+ };
121
+ if (!preserveTx) counts.tx = 0;
122
+ let chainState = null;
123
+ if (options?.chainAddress) chainState = await statedb.chain.get(options.chainAddress);
124
+ if (!chainState) chainState = (await scanStateTable(statedb, "chain"))[0] || null;
125
+ const tokenStates = await scanStateTable(statedb, "token");
126
+ const tokenInfoMap = /* @__PURE__ */ new Map();
127
+ if (chainState?.token?.address) tokenInfoMap.set(chainState.token.address, {
128
+ address: chainState.token.address,
129
+ decimal: chainState.token.decimal,
130
+ unit: chainState.token.unit,
131
+ symbol: chainState.token.symbol,
132
+ icon: chainState.token.icon,
133
+ foreignToken: chainState.token.foreignToken
134
+ });
135
+ for (const tokenState of tokenStates) {
136
+ if (!tokenState?.address) continue;
137
+ tokenInfoMap.set(tokenState.address, {
138
+ address: tokenState.address,
139
+ decimal: tokenState.decimal,
140
+ unit: tokenState.unit,
141
+ symbol: tokenState.symbol,
142
+ icon: tokenState.icon,
143
+ foreignToken: tokenState.foreignToken
144
+ });
145
+ const indexedToken = require_util.createIndexedToken(tokenState);
146
+ await upsertIndexRecord(indexdb.token, tokenState.address, indexedToken);
147
+ counts.token += 1;
148
+ }
149
+ const allTokenInfos = Array.from(tokenInfoMap.values());
150
+ const getTokenFn = async (address) => {
151
+ const cached = tokenInfoMap.get(address);
152
+ if (cached) return cached;
153
+ return await indexdb.token.get(address) || null;
154
+ };
155
+ const assetStates = await scanStateTable(statedb, "asset");
156
+ const assetMap = /* @__PURE__ */ new Map();
157
+ for (const assetState of assetStates) {
158
+ if (!assetState?.address) continue;
159
+ assetMap.set(assetState.address, assetState);
160
+ const indexedAsset = require_util.createIndexedAsset(assetState);
161
+ await upsertIndexRecord(indexdb.asset, assetState.address, indexedAsset);
162
+ counts.asset += 1;
163
+ }
164
+ const accountStates = await scanStateTable(statedb, "account");
165
+ const accountMap = /* @__PURE__ */ new Map();
166
+ for (const accountState of accountStates) {
167
+ if (!accountState?.address) continue;
168
+ accountMap.set(accountState.address, accountState);
169
+ const indexedAccount = await require_util.createIndexedAccount(accountState, getTokenFn);
170
+ await upsertIndexRecord(indexdb.account, accountState.address, indexedAccount);
171
+ counts.account += 1;
172
+ }
173
+ const delegationStates = await scanStateTable(statedb, "delegation");
174
+ const delegationMap = /* @__PURE__ */ new Map();
175
+ for (const delegationState of delegationStates) {
176
+ if (!delegationState?.address) continue;
177
+ delegationMap.set(delegationState.address, delegationState);
178
+ const indexedDelegation = require_util.createIndexedDelegation(delegationState, {});
179
+ await upsertIndexRecord(indexdb.delegation, delegationState.address, indexedDelegation);
180
+ counts.delegation += 1;
181
+ }
182
+ const factoryStates = await scanStateTable(statedb, "factory");
183
+ const factoryMap = /* @__PURE__ */ new Map();
184
+ for (const factoryState of factoryStates) {
185
+ if (!factoryState?.address) continue;
186
+ factoryMap.set(factoryState.address, factoryState);
187
+ const indexedFactory = require_util.createIndexedFactory(factoryState, {
188
+ factoryTokens: factoryState.input?.tokens,
189
+ tokenStates: allTokenInfos
190
+ });
191
+ await upsertIndexRecord(indexdb.factory, factoryState.address, indexedFactory);
192
+ counts.factory += 1;
193
+ }
194
+ const tokenFactoryStates = await scanStateTable(statedb, "tokenFactory");
195
+ const tokenFactoryMap = /* @__PURE__ */ new Map();
196
+ for (const tfState of tokenFactoryStates) {
197
+ if (!tfState?.address) continue;
198
+ tokenFactoryMap.set(tfState.address, tfState);
199
+ const tokenInfo = tokenInfoMap.get(tfState.tokenAddress);
200
+ const reserveInfo = tokenInfoMap.get(tfState.reserveAddress) || chainState?.token;
201
+ const indexedTokenFactory = require_util.createIndexedTokenFactory(tfState, {
202
+ itx: { token: tokenInfo },
203
+ config: { token: reserveInfo }
204
+ });
205
+ await upsertIndexRecord(indexdb.tokenFactory, tfState.address, indexedTokenFactory);
206
+ counts.tokenFactory += 1;
207
+ }
208
+ const stakeStates = await scanStateTable(statedb, "stake");
209
+ const stakeMap = /* @__PURE__ */ new Map();
210
+ for (const stakeState of stakeStates) {
211
+ if (!stakeState?.address) continue;
212
+ stakeMap.set(stakeState.address, stakeState);
213
+ const indexedStake = await require_util.createIndexedStake(stakeState, { tokenStates: allTokenInfos }, indexdb);
214
+ await upsertIndexRecord(indexdb.stake, stakeState.address, indexedStake);
215
+ counts.stake += 1;
216
+ }
217
+ const rollupStates = await scanStateTable(statedb, "rollup");
218
+ const rollupMap = /* @__PURE__ */ new Map();
219
+ for (const rollupState of rollupStates) {
220
+ if (!rollupState?.address) continue;
221
+ rollupMap.set(rollupState.address, rollupState);
222
+ const indexedRollup = require_util.createIndexedRollup(rollupState, { tokenStates: allTokenInfos });
223
+ await upsertIndexRecord(indexdb.rollup, rollupState.address, indexedRollup);
224
+ counts.rollup += 1;
225
+ const validatorMap = /* @__PURE__ */ new Map();
226
+ for (const v of rollupState.seedValidators || []) if (v?.address) validatorMap.set(v.address, v);
227
+ for (const v of rollupState.validators || []) if (v?.address) validatorMap.set(v.address, {
228
+ ...validatorMap.get(v.address),
229
+ ...v
230
+ });
231
+ for (const v of validatorMap.values()) {
232
+ const matchingStake = Array.from(stakeMap.values()).find((s) => s.sender === v.address && s.receiver === rollupState.address);
233
+ const account = accountMap.get(v.address);
234
+ const totalStake = matchingStake?.tokens?.[rollupState.tokenAddress] || "0";
235
+ const revokedStake = matchingStake?.revokedTokens?.[rollupState.tokenAddress] || "0";
236
+ const validatorDoc = {
237
+ rollup: rollupState.address,
238
+ address: v.address,
239
+ pk: v.pk || "",
240
+ endpoint: v.endpoint || "",
241
+ moniker: v.moniker || account?.moniker || "",
242
+ joinTime: rollupState.context?.genesisTime || "",
243
+ leaveTime: "",
244
+ genesisTime: rollupState.context?.genesisTime || "",
245
+ renaissanceTime: rollupState.context?.renaissanceTime || "",
246
+ totalStake,
247
+ revokedStake,
248
+ availableStake: "0",
249
+ totalGain: "0",
250
+ proposedBlockCount: 0,
251
+ verifiedBlockCount: 0,
252
+ latestBlockHeight: 0,
253
+ latestBlockHash: ""
254
+ };
255
+ await upsertIndexRecord(indexdb.rollupValidator, v.address, validatorDoc);
256
+ counts.rollupValidator += 1;
257
+ }
258
+ }
259
+ const rollupBlockStates = await scanStateTable(statedb, "rollupBlock");
260
+ rollupBlockStates.sort((a, b) => Number(a.height || 0) - Number(b.height || 0));
261
+ for (const blockState of rollupBlockStates) {
262
+ if (!blockState?.hash) continue;
263
+ const indexedBlock = require_util.createIndexedRollupBlock(blockState, {
264
+ rollupState: rollupMap.get(blockState.rollup),
265
+ tokenStates: allTokenInfos
266
+ });
267
+ await upsertIndexRecord(indexdb.rollupBlock, blockState.hash, indexedBlock);
268
+ counts.rollupBlock += 1;
269
+ for (const signerAddr of indexedBlock.validators || []) {
270
+ const existingValidator = await indexdb.rollupValidator.get(signerAddr);
271
+ if (existingValidator) {
272
+ existingValidator.verifiedBlockCount = (existingValidator.verifiedBlockCount || 0) + 1;
273
+ existingValidator.renaissanceTime = blockState.context?.genesisTime || existingValidator.renaissanceTime;
274
+ if (signerAddr === blockState.proposer) {
275
+ existingValidator.proposedBlockCount = (existingValidator.proposedBlockCount || 0) + 1;
276
+ existingValidator.latestBlockHeight = Number(blockState.height || 0);
277
+ existingValidator.latestBlockHash = blockState.hash;
278
+ }
279
+ await indexdb.rollupValidator.update(signerAddr, existingValidator);
280
+ }
281
+ }
282
+ }
283
+ if (!preserveTx) {
284
+ const txStates = await scanStateTable(statedb, "tx");
285
+ txStates.sort((a, b) => String(a.time || "").localeCompare(String(b.time || "")));
286
+ for (const txState of txStates) {
287
+ if (!txState?.hash) continue;
288
+ const txClone = JSON.parse(JSON.stringify(txState));
289
+ const indexedTx = await require_util.createIndexedTransaction(txClone, buildSyntheticTxContext(txClone, {
290
+ accountMap,
291
+ assetMap,
292
+ tokenInfoMap,
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
+ }
302
+ }
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
+ const nowIso = (/* @__PURE__ */ new Date()).toISOString();
310
+ for (const tokenInfo of allTokenInfos) {
311
+ const tokenAddr = tokenInfo.address;
312
+ if (!tokenAddr) continue;
313
+ let accountSum = new _ocap_util.BN(0);
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
+ }
343
+ const distDoc = require_util.createIndexedTokenDistribution({
344
+ tokenAddress: tokenAddr,
345
+ txTime: nowIso,
346
+ account: accountSum,
347
+ gas: gasSum,
348
+ fee: feeSum,
349
+ slashedVault: slashedSum,
350
+ stake: stakeSum,
351
+ revokedStake: revokedStakeSum,
352
+ gasStake: gasStakeSum
353
+ });
354
+ await upsertIndexRecord(indexdb.tokenDistribution, tokenAddr, distDoc);
355
+ counts.tokenDistribution += 1;
356
+ }
357
+ return {
358
+ tables: counts,
359
+ totalRecords: Object.values(counts).reduce((sum, n) => sum + n, 0),
360
+ durationMs: Date.now() - startTime
361
+ };
362
+ }
363
+ /**
364
+ * Reconstruct a FinalizedContext from a persisted ITransactionState and StateDB maps
365
+ * so `createIndexedTransaction` can populate entity references (`accounts`, `assets`,
366
+ * `tokens`, `factories`, `stakes`, `rollups`, `delegations`, `tokenFactories`, `tokenSymbols`).
367
+ */
368
+ function buildSyntheticTxContext(txState, maps) {
369
+ const itx = txState.tx?.itxJson || {};
370
+ const txType = itx.type_url || (txState.type ? `fg:t:${txState.type}` : "");
371
+ const updatedAccounts = [];
372
+ const assetStates = [];
373
+ const tokenStates = [];
374
+ const stakeStates = [];
375
+ const addTokenByAddr = (addr) => {
376
+ if (typeof addr !== "string" || !addr) return;
377
+ const info = maps.tokenInfoMap.get(addr);
378
+ if (info && !tokenStates.some((t) => t.address === addr)) tokenStates.push(info);
379
+ };
380
+ const addAssetByAddr = (addr) => {
381
+ if (typeof addr !== "string" || !addr) return;
382
+ const asset = maps.assetMap.get(addr);
383
+ if (asset && !assetStates.some((a) => a.address === addr)) assetStates.push(asset);
384
+ };
385
+ for (const receipt of txState.receipts || []) {
386
+ if (typeof receipt.address === "string" && receipt.address) if (maps.stakeMap.has(receipt.address)) {
387
+ const s = maps.stakeMap.get(receipt.address);
388
+ if (!stakeStates.some((x) => x.address === s.address)) stakeStates.push(s);
389
+ } else updatedAccounts.push({ address: receipt.address });
390
+ for (const change of receipt.changes || []) if (typeof change.target === "string" && change.target) {
391
+ addTokenByAddr(change.target);
392
+ addAssetByAddr(change.target);
393
+ }
394
+ }
395
+ const itxAddress = typeof itx.address === "string" ? itx.address : "";
396
+ const itxFactory = typeof itx.factory === "string" ? itx.factory : "";
397
+ const itxRollup = typeof itx.rollup === "string" ? itx.rollup : "";
398
+ const itxToken = typeof itx.token === "string" ? itx.token : "";
399
+ const itxTokenAddress = typeof itx.tokenAddress === "string" ? itx.tokenAddress : "";
400
+ addTokenByAddr(itxToken);
401
+ addTokenByAddr(itxTokenAddress);
402
+ addAssetByAddr(itxAddress);
403
+ 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 = maps.factoryMap.get(itxFactory || itxAddress);
406
+ const rollupState = maps.rollupMap.get(itxRollup || itxAddress);
407
+ const delegationState = maps.delegationMap.get(itxAddress);
408
+ const tokenFactoryState = maps.tokenFactoryMap.get(itxAddress || itx.factoryAddress || "");
409
+ const stakeState = maps.stakeMap.get(itxAddress);
410
+ const assetState = maps.assetMap.get(itxAddress);
411
+ return {
412
+ txType,
413
+ senderState: txState.sender ? maps.accountMap.get(txState.sender) || { address: txState.sender } : void 0,
414
+ receiverState: txState.receiver ? maps.accountMap.get(txState.receiver) || { address: txState.receiver } : void 0,
415
+ updatedAccounts,
416
+ assetState,
417
+ assetStates: assetStates.length > 0 ? assetStates : void 0,
418
+ tokenStates: tokenStates.length > 0 ? tokenStates : void 0,
419
+ factoryState,
420
+ stakeState,
421
+ stakeStates: stakeStates.length > 0 ? stakeStates : void 0,
422
+ rollupState,
423
+ delegationState,
424
+ tokenFactoryState,
425
+ ownerAddress: assetState?.owner || txState.receiver || txState.sender
426
+ };
427
+ }
428
+
429
+ //#endregion
430
+ exports.clearIndexDB = clearIndexDB;
431
+ exports.rebuildIndexFromState = rebuildIndexFromState;
432
+ exports.scanStateTable = scanStateTable;
@@ -0,0 +1,20 @@
1
+ import { IIndexDB, IRebuildOptions, IRebuildResult, IStateDB } from "@ocap/types";
2
+
3
+ //#region src/rebuild.d.ts
4
+
5
+ /**
6
+ * Scan all records from a StateDB table across Memory, SQLite, and Dolt adapters.
7
+ */
8
+ declare function scanStateTable<T = Record<string, unknown>>(statedb: IStateDB | Record<string, unknown>, tableName: string): Promise<T[]>;
9
+ /**
10
+ * Clear all IndexDB tables (or state-only tables when `preserveTx` is true).
11
+ */
12
+ declare function clearIndexDB(indexdb: IIndexDB, options?: {
13
+ preserveTx?: boolean;
14
+ }): Promise<void>;
15
+ /**
16
+ * Deterministically rebuild IndexDB from StateDB (`vledger index rebuild`).
17
+ */
18
+ declare function rebuildIndexFromState(indexdb: IIndexDB, statedb: IStateDB, options?: IRebuildOptions): Promise<IRebuildResult>;
19
+ //#endregion
20
+ export { clearIndexDB, rebuildIndexFromState, scanStateTable };
package/lib/util.cjs CHANGED
@@ -477,9 +477,12 @@ const PAGE_SIZE_MAX = 100;
477
477
  */
478
478
  const formatPagination = ({ paging, defaultSortField, supportedSortFields = [] }) => {
479
479
  if (!defaultSortField) throw new Error("argument defaultSortField is required");
480
+ const rawSize = Number(paging?.size ?? PAGE_SIZE_DEFAULT);
481
+ const safeSize = Number.isFinite(rawSize) && rawSize >= 0 ? Math.floor(rawSize) : PAGE_SIZE_DEFAULT;
482
+ const rawCursor = typeof paging?.cursor === "number" ? paging.cursor : Number(paging?.cursor) || 0;
480
483
  const pagination = {
481
- size: paging?.size ?? PAGE_SIZE_DEFAULT,
482
- cursor: typeof paging?.cursor === "number" ? paging.cursor : Number(paging?.cursor) || 0,
484
+ size: safeSize,
485
+ cursor: Number.isFinite(rawCursor) && rawCursor >= 0 ? Math.floor(rawCursor) : 0,
483
486
  order: {
484
487
  field: defaultSortField,
485
488
  type: "desc"
@@ -489,7 +492,10 @@ const formatPagination = ({ paging, defaultSortField, supportedSortFields = [] }
489
492
  if (Array.isArray(inputOrder)) inputOrder = inputOrder[0];
490
493
  if (inputOrder?.field) pagination.order.field = inputOrder.field;
491
494
  if (supportedSortFields.length > 0 && !supportedSortFields.includes(pagination.order.field)) pagination.order.field = defaultSortField;
492
- if (inputOrder?.type) pagination.order.type = inputOrder.type;
495
+ if (inputOrder?.type) {
496
+ const normalizedType = String(inputOrder.type).toLowerCase();
497
+ pagination.order.type = normalizedType === "asc" || normalizedType === "desc" ? normalizedType : "desc";
498
+ }
493
499
  pagination.size = Math.min(pagination.size, PAGE_SIZE_MAX);
494
500
  return pagination;
495
501
  };
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.30.24",
6
+ "version": "1.30.25",
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.30.24",
56
- "@ocap/types": "1.30.24",
57
- "@ocap/util": "1.30.24",
55
+ "@ocap/state": "1.30.25",
56
+ "@ocap/types": "1.30.25",
57
+ "@ocap/util": "1.30.25",
58
58
  "kareem": "^2.4.1",
59
59
  "lodash": "^4.17.23"
60
60
  }