@ocap/statedb-sqlite 1.30.25 → 1.31.0

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.
@@ -0,0 +1,836 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let _ocap_statedb = require("@ocap/statedb");
3
+ let kysely = require("kysely");
4
+ let _ocap_util = require("@ocap/util");
5
+ let _ocap_state_lib_states_account = require("@ocap/state/lib/states/account");
6
+ let _arcblock_did_util = require("@arcblock/did-util");
7
+
8
+ //#region src/reconcile.ts
9
+ /**
10
+ * Verification and reconcile are SQLite-only (they query SQLite tables through kysely). Fail loudly when given
11
+ * any other backend (e.g. statedb-dolt, statedb-memory) instead of crashing midway or silently skipping.
12
+ */
13
+ function assertSqliteStateDb(db) {
14
+ const candidate = db;
15
+ if (!candidate || typeof candidate.getKysely !== "function") throw new Error("Chain state verify/reconcile only supports @ocap/statedb-sqlite. Dolt and other backends are not supported (read-only verification for Dolt is not implemented).");
16
+ }
17
+ const CANONICAL_UINT_REGEX = /^\d+$/;
18
+ function parseJsonColumn(raw, fallback) {
19
+ if (raw === null || raw === void 0) return fallback;
20
+ if (typeof raw === "object") return raw;
21
+ if (typeof raw === "string") {
22
+ const trimmed = raw.trim();
23
+ if (!trimmed) return fallback;
24
+ try {
25
+ return JSON.parse(trimmed);
26
+ } catch {
27
+ return fallback;
28
+ }
29
+ }
30
+ return fallback;
31
+ }
32
+ /**
33
+ * Verifies all chain state & ledger invariants across `SqliteStateDB` (and optional `ledger`).
34
+ */
35
+ async function verifyChainStateInvariants(db, options = {}) {
36
+ assertSqliteStateDb(db);
37
+ const kysely$1 = db.getKysely();
38
+ const violations = [];
39
+ const [accounts, assets, balances, tokens, tokenFactories, stakes] = await Promise.all([
40
+ kysely$1.selectFrom("account").selectAll().execute(),
41
+ kysely$1.selectFrom("asset").selectAll().execute(),
42
+ kysely$1.selectFrom("balance").selectAll().execute(),
43
+ kysely$1.selectFrom("token").selectAll().execute(),
44
+ kysely$1.selectFrom("tokenFactory").selectAll().execute(),
45
+ kysely$1.selectFrom("stake").selectAll().execute()
46
+ ]);
47
+ const factories = await kysely$1.selectFrom("factory").selectAll().execute();
48
+ const accountMap = /* @__PURE__ */ new Map();
49
+ for (const acc of accounts) accountMap.set(acc.address, acc);
50
+ const assetMap = /* @__PURE__ */ new Map();
51
+ for (const ast of assets) assetMap.set(ast.address, ast);
52
+ const tokenMap = /* @__PURE__ */ new Map();
53
+ for (const tok of tokens) tokenMap.set(tok.address, tok);
54
+ const stakeMap = /* @__PURE__ */ new Map();
55
+ for (const stk of stakes) stakeMap.set(stk.address, stk);
56
+ const factoryMap = /* @__PURE__ */ new Map();
57
+ for (const fac of factories) factoryMap.set(fac.address, fac);
58
+ const tokenActiveBalanceSums = /* @__PURE__ */ new Map();
59
+ for (const row of balances) {
60
+ const addr = String(row.address || "");
61
+ const tokAddr = String(row.tokenAddress || "");
62
+ const balStr = String(row.balance ?? "");
63
+ const compositeKey = `${addr}:${tokAddr}`;
64
+ const checksumAddr = (0, _ocap_state_lib_states_account.ensureChecksumAddress)(addr);
65
+ if (checksumAddr !== addr) violations.push({
66
+ code: "I-BAL-1",
67
+ severity: "HIGH",
68
+ table: "balance",
69
+ key: compositeKey,
70
+ message: `Non-canonical 0x address casing in balance table: "${addr}" (expected "${checksumAddr}")`,
71
+ details: {
72
+ address: addr,
73
+ expectedAddress: checksumAddr,
74
+ tokenAddress: tokAddr,
75
+ balance: balStr
76
+ },
77
+ reconcilable: true
78
+ });
79
+ if (!CANONICAL_UINT_REGEX.test(balStr)) {
80
+ violations.push({
81
+ code: "I-BAL-1",
82
+ severity: "CRITICAL",
83
+ table: "balance",
84
+ key: compositeKey,
85
+ message: `Malformed or negative balance "${balStr}" for (${addr}, ${tokAddr})`,
86
+ details: {
87
+ address: addr,
88
+ tokenAddress: tokAddr,
89
+ balance: balStr
90
+ },
91
+ reconcilable: false
92
+ });
93
+ continue;
94
+ }
95
+ const bnVal = new _ocap_util.BN(balStr, 10);
96
+ if (bnVal.isZero()) violations.push({
97
+ code: "I-BAL-3",
98
+ severity: "MEDIUM",
99
+ table: "balance",
100
+ key: compositeKey,
101
+ message: `Zero-balance row persisted in balance table for (${addr}, ${tokAddr})`,
102
+ details: {
103
+ address: addr,
104
+ tokenAddress: tokAddr,
105
+ balance: balStr
106
+ },
107
+ reconcilable: true
108
+ });
109
+ const holderAccount = accountMap.get(checksumAddr) || accountMap.get(addr);
110
+ const holderStake = stakeMap.get(checksumAddr) || stakeMap.get(addr);
111
+ const holderFactory = factoryMap.get(checksumAddr) || factoryMap.get(addr);
112
+ if (!holderAccount && !holderStake && !holderFactory && bnVal.gt(new _ocap_util.BN(0))) violations.push({
113
+ code: "I-BAL-1",
114
+ severity: "HIGH",
115
+ table: "balance",
116
+ key: compositeKey,
117
+ message: `Orphaned positive balance "${balStr}" for non-existent entity "${addr}"`,
118
+ details: {
119
+ address: addr,
120
+ tokenAddress: tokAddr,
121
+ balance: balStr
122
+ },
123
+ reconcilable: false
124
+ });
125
+ if (holderAccount) {
126
+ const migratedTo = parseJsonColumn(holderAccount.migratedTo, []);
127
+ if (migratedTo.length > 0 && bnVal.gt(new _ocap_util.BN(0))) violations.push({
128
+ code: "I-BAL-2",
129
+ severity: "CRITICAL",
130
+ table: "balance",
131
+ key: compositeKey,
132
+ message: `Migrated account "${addr}" (migratedTo=${JSON.stringify(migratedTo)}) still retains positive balance "${balStr}" for token "${tokAddr}"`,
133
+ details: {
134
+ address: addr,
135
+ tokenAddress: tokAddr,
136
+ balance: balStr,
137
+ migratedTo
138
+ },
139
+ reconcilable: true
140
+ });
141
+ }
142
+ const prevSum = tokenActiveBalanceSums.get(tokAddr) || new _ocap_util.BN(0);
143
+ tokenActiveBalanceSums.set(tokAddr, prevSum.add(bnVal));
144
+ }
145
+ const tokenRevokedSums = /* @__PURE__ */ new Map();
146
+ const globalStakedAssets = /* @__PURE__ */ new Map();
147
+ for (const stk of stakes) {
148
+ const revokedTokens = parseJsonColumn(stk.revokedTokens, {});
149
+ for (const [tokAddr, rawVal] of Object.entries(revokedTokens)) {
150
+ const valStr = String(rawVal ?? "0");
151
+ if (!CANONICAL_UINT_REGEX.test(valStr)) {
152
+ violations.push({
153
+ code: "I-STK-1",
154
+ severity: "CRITICAL",
155
+ table: "stake",
156
+ key: stk.address,
157
+ message: `Stake "${stk.address}" has malformed revokedTokens["${tokAddr}"] = "${valStr}"`,
158
+ details: {
159
+ stakeAddress: stk.address,
160
+ tokenAddress: tokAddr,
161
+ value: valStr
162
+ },
163
+ reconcilable: false
164
+ });
165
+ continue;
166
+ }
167
+ const prev = tokenRevokedSums.get(tokAddr) || new _ocap_util.BN(0);
168
+ tokenRevokedSums.set(tokAddr, prev.add(new _ocap_util.BN(valStr, 10)));
169
+ }
170
+ const activeAssets = parseJsonColumn(stk.assets, []);
171
+ const revokedAssets = parseJsonColumn(stk.revokedAssets, []);
172
+ const activeSet = new Set(activeAssets);
173
+ for (const revAsset of revokedAssets) if (activeSet.has(revAsset)) violations.push({
174
+ code: "I-STK-1",
175
+ severity: "HIGH",
176
+ table: "stake",
177
+ key: stk.address,
178
+ message: `Asset "${revAsset}" appears in both stake.assets and stake.revokedAssets on stake "${stk.address}"`,
179
+ details: {
180
+ stakeAddress: stk.address,
181
+ assetAddress: revAsset
182
+ },
183
+ reconcilable: true
184
+ });
185
+ for (const assetDid of [...activeAssets, ...revokedAssets]) {
186
+ const priorStake = globalStakedAssets.get(assetDid);
187
+ if (priorStake && priorStake !== stk.address) violations.push({
188
+ code: "I-STK-1",
189
+ severity: "CRITICAL",
190
+ table: "stake",
191
+ key: stk.address,
192
+ message: `Asset "${assetDid}" is listed in multiple stakes ("${priorStake}" and "${stk.address}")`,
193
+ details: {
194
+ assetAddress: assetDid,
195
+ stakes: [priorStake, stk.address]
196
+ },
197
+ reconcilable: false
198
+ });
199
+ globalStakedAssets.set(assetDid, stk.address);
200
+ const assetRow = assetMap.get(assetDid);
201
+ if (!assetRow) violations.push({
202
+ code: "I-STK-1",
203
+ severity: "HIGH",
204
+ table: "stake",
205
+ key: stk.address,
206
+ message: `Stake "${stk.address}" references non-existent asset "${assetDid}"`,
207
+ details: {
208
+ stakeAddress: stk.address,
209
+ assetAddress: assetDid
210
+ },
211
+ reconcilable: true
212
+ });
213
+ else if (assetRow.owner !== stk.address) violations.push({
214
+ code: "I-STK-1",
215
+ severity: "HIGH",
216
+ table: "stake",
217
+ key: stk.address,
218
+ message: `Stake "${stk.address}" lists asset "${assetDid}", but asset.owner is "${assetRow.owner}"`,
219
+ details: {
220
+ stakeAddress: stk.address,
221
+ assetAddress: assetDid,
222
+ actualOwner: assetRow.owner
223
+ },
224
+ reconcilable: true
225
+ });
226
+ }
227
+ }
228
+ for (const tok of tokens) {
229
+ const totalSupplyStr = String(tok.totalSupply ?? "0");
230
+ const maxSupplyStr = String(tok.maxTotalSupply ?? tok.maxSupply ?? "-1");
231
+ if (!CANONICAL_UINT_REGEX.test(totalSupplyStr)) {
232
+ violations.push({
233
+ code: "I-TOK-1",
234
+ severity: "CRITICAL",
235
+ table: "token",
236
+ key: tok.address,
237
+ message: `Token "${tok.address}" has non-canonical totalSupply "${totalSupplyStr}"`,
238
+ details: { totalSupply: totalSupplyStr },
239
+ reconcilable: true
240
+ });
241
+ continue;
242
+ }
243
+ const totalSupplyBn = new _ocap_util.BN(totalSupplyStr, 10);
244
+ const activeSum = tokenActiveBalanceSums.get(tok.address) || new _ocap_util.BN(0);
245
+ const revokedSum = tokenRevokedSums.get(tok.address) || new _ocap_util.BN(0);
246
+ const accountedSum = activeSum.add(revokedSum);
247
+ if (!totalSupplyBn.eq(accountedSum)) violations.push({
248
+ code: "I-TOK-1",
249
+ severity: "CRITICAL",
250
+ table: "token",
251
+ key: tok.address,
252
+ message: `Token "${tok.address}" totalSupply (${totalSupplyBn.toString(10)}) != accounted balances + revokedTokens (${accountedSum.toString(10)})`,
253
+ details: {
254
+ tokenAddress: tok.address,
255
+ totalSupply: totalSupplyBn.toString(10),
256
+ activeBalancesSum: activeSum.toString(10),
257
+ revokedTokensSum: revokedSum.toString(10),
258
+ accountedSum: accountedSum.toString(10)
259
+ },
260
+ reconcilable: true
261
+ });
262
+ if (maxSupplyStr !== "-1" && CANONICAL_UINT_REGEX.test(maxSupplyStr)) {
263
+ const maxSupplyBn = new _ocap_util.BN(maxSupplyStr, 10);
264
+ if (totalSupplyBn.gt(maxSupplyBn)) violations.push({
265
+ code: "I-TOK-2",
266
+ severity: "CRITICAL",
267
+ table: "token",
268
+ key: tok.address,
269
+ message: `Token "${tok.address}" totalSupply (${totalSupplyBn.toString(10)}) exceeds maxSupply (${maxSupplyBn.toString(10)})`,
270
+ details: {
271
+ totalSupply: totalSupplyBn.toString(10),
272
+ maxSupply: maxSupplyBn.toString(10)
273
+ },
274
+ reconcilable: false
275
+ });
276
+ }
277
+ try {
278
+ const charterAddress = (0, _arcblock_did_util.toTokenCharterAssetAddress)(tok.address);
279
+ const charterAsset = assetMap.get(charterAddress);
280
+ if (charterAsset) {
281
+ const charterData = parseJsonColumn(charterAsset.data, null);
282
+ if (charterData?.value?.kind !== "TokenCharter" || charterData?.value?.tokenAddress !== tok.address) violations.push({
283
+ code: "I-TOK-4",
284
+ severity: "HIGH",
285
+ table: "asset",
286
+ key: charterAddress,
287
+ message: `Token Charter Asset "${charterAddress}" for token "${tok.address}" has mismatched charter payload`,
288
+ details: {
289
+ tokenAddress: tok.address,
290
+ charterAddress,
291
+ data: charterData
292
+ },
293
+ reconcilable: true
294
+ });
295
+ }
296
+ } catch {}
297
+ }
298
+ for (const tf of tokenFactories) {
299
+ const tok = tokenMap.get(tf.tokenAddress);
300
+ if (!tok) {
301
+ violations.push({
302
+ code: "I-TOK-3",
303
+ severity: "CRITICAL",
304
+ table: "tokenFactory",
305
+ key: tf.address,
306
+ message: `TokenFactory "${tf.address}" references missing token "${tf.tokenAddress}"`,
307
+ details: {
308
+ factoryAddress: tf.address,
309
+ tokenAddress: tf.tokenAddress
310
+ },
311
+ reconcilable: false
312
+ });
313
+ continue;
314
+ }
315
+ const currentSupplyStr = String(tf.currentSupply ?? "0");
316
+ const reserveBalanceStr = String(tf.reserveBalance ?? "0");
317
+ const tokActiveSum = tokenActiveBalanceSums.get(tf.tokenAddress) || new _ocap_util.BN(0);
318
+ const tokRevokedSum = tokenRevokedSums.get(tf.tokenAddress) || new _ocap_util.BN(0);
319
+ const tokAccountedSum = tokActiveSum.add(tokRevokedSum).toString(10);
320
+ if (Number(tf.status || 0) === 0 && (currentSupplyStr !== String(tok.totalSupply ?? "0") || currentSupplyStr !== tokAccountedSum)) violations.push({
321
+ code: "I-TOK-3",
322
+ severity: "CRITICAL",
323
+ table: "tokenFactory",
324
+ key: tf.address,
325
+ message: `Active TokenFactory "${tf.address}" currentSupply (${currentSupplyStr}) != token.totalSupply (${tok.totalSupply}) / accounted supply (${tokAccountedSum})`,
326
+ details: {
327
+ factoryAddress: tf.address,
328
+ tokenAddress: tf.tokenAddress,
329
+ currentSupply: currentSupplyStr,
330
+ tokenTotalSupply: tok.totalSupply,
331
+ accountedSupply: tokAccountedSum
332
+ },
333
+ reconcilable: true
334
+ });
335
+ if (Number(tf.status || 0) === 0 && CANONICAL_UINT_REGEX.test(reserveBalanceStr)) {
336
+ const reserveBn = new _ocap_util.BN(reserveBalanceStr, 10);
337
+ if (reserveBn.gt(new _ocap_util.BN(0))) try {
338
+ const reserveStakeAddr = (0, _arcblock_did_util.toStakeAddress)(tf.address, tf.reserveAddress);
339
+ const actualStakeReserve = new _ocap_util.BN((await db.balance.getBalance(reserveStakeAddr))[tf.reserveAddress] || "0", 10);
340
+ if (actualStakeReserve.lt(reserveBn)) violations.push({
341
+ code: "I-TOK-3",
342
+ severity: "CRITICAL",
343
+ table: "tokenFactory",
344
+ key: tf.address,
345
+ message: `TokenFactory "${tf.address}" reserveBalance (${reserveBn.toString(10)}) exceeds reserve stake "${reserveStakeAddr}" balance (${actualStakeReserve.toString(10)})`,
346
+ details: {
347
+ factoryAddress: tf.address,
348
+ reserveStakeAddr,
349
+ expectedReserve: reserveBn.toString(10),
350
+ actualStakeReserve: actualStakeReserve.toString(10)
351
+ },
352
+ reconcilable: false
353
+ });
354
+ } catch {}
355
+ }
356
+ }
357
+ for (const ast of assets) {
358
+ const ownerAcc = accountMap.get(ast.owner);
359
+ if (ownerAcc) {
360
+ const migratedTo = parseJsonColumn(ownerAcc.migratedTo, []);
361
+ if (migratedTo.length > 0) violations.push({
362
+ code: "I-AST-1",
363
+ severity: "HIGH",
364
+ table: "asset",
365
+ key: ast.address,
366
+ message: `Asset "${ast.address}" is still owned by migrated account "${ast.owner}" (migratedTo=${JSON.stringify(migratedTo)})`,
367
+ details: {
368
+ assetAddress: ast.address,
369
+ owner: ast.owner,
370
+ migratedTo
371
+ },
372
+ reconcilable: true
373
+ });
374
+ }
375
+ }
376
+ for (const acc of accounts) {
377
+ const migratedTo = parseJsonColumn(acc.migratedTo, []);
378
+ if (migratedTo.length > 0) {
379
+ if (migratedTo.length > 1) violations.push({
380
+ code: "I-MIG-1",
381
+ severity: "HIGH",
382
+ table: "account",
383
+ key: acc.address,
384
+ message: `Account "${acc.address}" migratedTo contains multiple entries (${JSON.stringify(migratedTo)}); linear migration requires a single immediate successor`,
385
+ details: {
386
+ address: acc.address,
387
+ migratedTo
388
+ },
389
+ reconcilable: false
390
+ });
391
+ const nextHop = (0, _ocap_state_lib_states_account.ensureChecksumAddress)(migratedTo[0]);
392
+ const targetAcc = accountMap.get(nextHop);
393
+ if (!targetAcc) {
394
+ violations.push({
395
+ code: "I-MIG-1",
396
+ severity: "HIGH",
397
+ table: "account",
398
+ key: acc.address,
399
+ message: `Account "${acc.address}" migratedTo references non-existent account "${nextHop}"`,
400
+ details: {
401
+ address: acc.address,
402
+ nextHop
403
+ },
404
+ reconcilable: false
405
+ });
406
+ continue;
407
+ }
408
+ if (!await (0, _ocap_statedb.followMigrationChain)(acc.address, async (addr) => {
409
+ const row = accountMap.get(addr);
410
+ if (!row) return null;
411
+ return {
412
+ address: row.address,
413
+ migratedTo: parseJsonColumn(row.migratedTo, [])
414
+ };
415
+ }, _ocap_state_lib_states_account.ensureChecksumAddress)) violations.push({
416
+ code: "I-MIG-1",
417
+ severity: "CRITICAL",
418
+ table: "account",
419
+ key: acc.address,
420
+ message: `Account migration cycle or broken chain detected starting at "${acc.address}"`,
421
+ details: {
422
+ address: acc.address,
423
+ migratedTo
424
+ },
425
+ reconcilable: false
426
+ });
427
+ const targetMigratedFrom = parseJsonColumn(targetAcc.migratedFrom, []);
428
+ if (!targetMigratedFrom.includes(acc.address)) violations.push({
429
+ code: "I-MIG-1",
430
+ severity: "HIGH",
431
+ table: "account",
432
+ key: acc.address,
433
+ message: `Asymmetric migration link: "${acc.address}" -> "${nextHop}", but "${nextHop}".migratedFrom does not contain "${acc.address}"`,
434
+ details: {
435
+ from: acc.address,
436
+ to: nextHop,
437
+ targetMigratedFrom
438
+ },
439
+ reconcilable: true
440
+ });
441
+ }
442
+ }
443
+ try {
444
+ await db.verifyTrustedHash();
445
+ } catch (err) {
446
+ violations.push({
447
+ code: "I-LDG-1",
448
+ severity: "CRITICAL",
449
+ table: "_state_commit",
450
+ key: "1",
451
+ message: `StateDB trustedHash verification failed: ${err?.message || String(err)}`,
452
+ details: { code: err?.code },
453
+ reconcilable: false
454
+ });
455
+ }
456
+ if (options.ledger && typeof options.ledger.verifyChain === "function") {
457
+ const ledgerCheck = await options.ledger.verifyChain();
458
+ if (!ledgerCheck.valid) violations.push({
459
+ code: "I-LDG-2",
460
+ severity: "CRITICAL",
461
+ table: "ledger_entries",
462
+ key: "chain",
463
+ message: `Ledger hash-chain verification failed: ${ledgerCheck.error || "invalid chain"}`,
464
+ details: ledgerCheck,
465
+ reconcilable: false
466
+ });
467
+ }
468
+ const critical = violations.filter((v) => v.severity === "CRITICAL").length;
469
+ const high = violations.filter((v) => v.severity === "HIGH").length;
470
+ const medium = violations.filter((v) => v.severity === "MEDIUM").length;
471
+ return {
472
+ valid: violations.length === 0,
473
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
474
+ counts: {
475
+ accounts: accounts.length,
476
+ assets: assets.length,
477
+ balances: balances.length,
478
+ tokens: tokens.length,
479
+ tokenFactories: tokenFactories.length,
480
+ stakes: stakes.length,
481
+ violations: violations.length,
482
+ critical,
483
+ high,
484
+ medium
485
+ },
486
+ violations
487
+ };
488
+ }
489
+ /**
490
+ * Reconciles deterministically repairable state anomalies in `SqliteStateDB`.
491
+ * By default runs in `dryRun: true` preview mode; when `dryRun: false` is passed,
492
+ * executes all repairs atomically inside `db.runAsLambda()`.
493
+ */
494
+ async function reconcileChainState(db, options = {}) {
495
+ assertSqliteStateDb(db);
496
+ const dryRun = options.dryRun !== false;
497
+ if (!dryRun && options.allowProtocolBypass !== true) throw new Error("reconcileChainState({ dryRun: false }) writes directly to SQLite and bypasses protocol validation; pass allowProtocolBypass: true to confirm");
498
+ const beforeReport = await verifyChainStateInvariants(db, { ledger: options.ledger });
499
+ const actions = [];
500
+ if (beforeReport.valid) return {
501
+ dryRun,
502
+ reconciled: true,
503
+ beforeReport,
504
+ afterReport: beforeReport,
505
+ actions
506
+ };
507
+ const executeRepairs = async (executor) => {
508
+ const allBalances = await executor.selectFrom("balance").selectAll().execute();
509
+ for (const row of allBalances) {
510
+ const addr = String(row.address || "");
511
+ const tokAddr = String(row.tokenAddress || "");
512
+ const balStr = String(row.balance ?? "0");
513
+ const checksumAddr = (0, _ocap_state_lib_states_account.ensureChecksumAddress)(addr);
514
+ if (CANONICAL_UINT_REGEX.test(balStr) && new _ocap_util.BN(balStr, 10).isZero()) {
515
+ actions.push({
516
+ code: "I-BAL-3",
517
+ table: "balance",
518
+ key: `${addr}:${tokAddr}`,
519
+ action: "delete_zero_balance_row",
520
+ before: {
521
+ address: addr,
522
+ tokenAddress: tokAddr,
523
+ balance: balStr
524
+ },
525
+ after: null
526
+ });
527
+ if (!dryRun) await executor.deleteFrom("balance").where("address", "=", addr).where("tokenAddress", "=", tokAddr).execute();
528
+ continue;
529
+ }
530
+ if (checksumAddr !== addr && CANONICAL_UINT_REGEX.test(balStr)) {
531
+ const existingCanonical = await executor.selectFrom("balance").selectAll().where("address", "=", checksumAddr).where("tokenAddress", "=", tokAddr).executeTakeFirst();
532
+ const mergedBalance = existingCanonical && CANONICAL_UINT_REGEX.test(String(existingCanonical.balance)) ? new _ocap_util.BN(String(existingCanonical.balance), 10).add(new _ocap_util.BN(balStr, 10)).toString(10) : balStr;
533
+ actions.push({
534
+ code: "I-BAL-1",
535
+ table: "balance",
536
+ key: `${addr}:${tokAddr}`,
537
+ action: "normalize_checksum_balance_row",
538
+ before: {
539
+ address: addr,
540
+ tokenAddress: tokAddr,
541
+ balance: balStr
542
+ },
543
+ after: {
544
+ address: checksumAddr,
545
+ tokenAddress: tokAddr,
546
+ balance: mergedBalance
547
+ }
548
+ });
549
+ if (!dryRun) {
550
+ await executor.deleteFrom("balance").where("address", "=", addr).where("tokenAddress", "=", tokAddr).execute();
551
+ await executor.insertInto("balance").values({
552
+ address: checksumAddr,
553
+ tokenAddress: tokAddr,
554
+ balance: mergedBalance,
555
+ context: row.context || "{}"
556
+ }).onConflict((oc) => oc.columns(["address", "tokenAddress"]).doUpdateSet({ balance: mergedBalance })).execute();
557
+ }
558
+ }
559
+ }
560
+ const accounts = await executor.selectFrom("account").selectAll().execute();
561
+ const accountMap = new Map(accounts.map((a) => [a.address, a]));
562
+ const tokensForMigration = await executor.selectFrom("token").selectAll().execute();
563
+ const declaredSupplyMap = /* @__PURE__ */ new Map();
564
+ for (const t of tokensForMigration) if (CANONICAL_UINT_REGEX.test(String(t.totalSupply ?? ""))) declaredSupplyMap.set(t.address, new _ocap_util.BN(String(t.totalSupply), 10));
565
+ const preMigrationBalances = await executor.selectFrom("balance").selectAll().execute();
566
+ const preMigrationStakes = await executor.selectFrom("stake").selectAll().execute();
567
+ const runningAccountedSupply = /* @__PURE__ */ new Map();
568
+ const liveBalanceMap = /* @__PURE__ */ new Map();
569
+ for (const b of preMigrationBalances) if (CANONICAL_UINT_REGEX.test(String(b.balance ?? ""))) {
570
+ const bnVal = new _ocap_util.BN(String(b.balance), 10);
571
+ const prev = runningAccountedSupply.get(b.tokenAddress) || new _ocap_util.BN(0);
572
+ runningAccountedSupply.set(b.tokenAddress, prev.add(bnVal));
573
+ const balKey = `${(0, _ocap_state_lib_states_account.ensureChecksumAddress)(String(b.address || ""))}:${b.tokenAddress}`;
574
+ liveBalanceMap.set(balKey, (liveBalanceMap.get(balKey) || new _ocap_util.BN(0)).add(bnVal));
575
+ }
576
+ for (const s of preMigrationStakes) {
577
+ const rev = parseJsonColumn(s.revokedTokens, {});
578
+ for (const [tAddr, val] of Object.entries(rev)) if (CANONICAL_UINT_REGEX.test(String(val ?? ""))) {
579
+ const prev = runningAccountedSupply.get(tAddr) || new _ocap_util.BN(0);
580
+ runningAccountedSupply.set(tAddr, prev.add(new _ocap_util.BN(String(val), 10)));
581
+ }
582
+ }
583
+ for (const acc of accounts) {
584
+ const migratedTo = parseJsonColumn(acc.migratedTo, []);
585
+ if (migratedTo.length === 0) continue;
586
+ const terminal = await (0, _ocap_statedb.followMigrationChain)(acc.address, async (addr) => {
587
+ const row = accountMap.get(addr);
588
+ if (!row) return null;
589
+ return {
590
+ address: row.address,
591
+ migratedTo: parseJsonColumn(row.migratedTo, [])
592
+ };
593
+ }, _ocap_state_lib_states_account.ensureChecksumAddress);
594
+ if (!terminal || !terminal.address || terminal.address === acc.address) continue;
595
+ const terminalAddr = terminal.address;
596
+ if (!accountMap.get(terminalAddr)) continue;
597
+ const nextHop = (0, _ocap_state_lib_states_account.ensureChecksumAddress)(migratedTo[0]);
598
+ const nextAcc = accountMap.get(nextHop);
599
+ if (nextAcc) {
600
+ const nextMigratedFrom = parseJsonColumn(nextAcc.migratedFrom, []);
601
+ if (!nextMigratedFrom.includes(acc.address)) {
602
+ const updatedFrom = [...nextMigratedFrom, acc.address];
603
+ nextAcc.migratedFrom = JSON.stringify(updatedFrom);
604
+ actions.push({
605
+ code: "I-MIG-1",
606
+ table: "account",
607
+ key: nextHop,
608
+ action: "restore_symmetric_migratedFrom",
609
+ before: nextMigratedFrom,
610
+ after: updatedFrom
611
+ });
612
+ if (!dryRun) await executor.updateTable("account").set({ migratedFrom: JSON.stringify(updatedFrom) }).where("address", "=", nextHop).execute();
613
+ }
614
+ }
615
+ const zombieRows = await executor.selectFrom("balance").selectAll().where("address", "=", acc.address).execute();
616
+ for (const zRow of zombieRows) {
617
+ const tokAddr = String(zRow.tokenAddress || "");
618
+ const zBalStr = String(zRow.balance ?? "0");
619
+ if (!CANONICAL_UINT_REGEX.test(zBalStr)) continue;
620
+ const zBal = new _ocap_util.BN(zBalStr, 10);
621
+ if (zBal.isZero()) continue;
622
+ const termBalKey = `${(0, _ocap_state_lib_states_account.ensureChecksumAddress)(terminalAddr)}:${tokAddr}`;
623
+ const termBal = liveBalanceMap.get(termBalKey) || new _ocap_util.BN(0);
624
+ const declaredSupply = declaredSupplyMap.get(tokAddr) ?? null;
625
+ const accountedSupply = runningAccountedSupply.get(tokAddr) || new _ocap_util.BN(0);
626
+ const excessSupply = declaredSupply === null ? termBal.gte(zBal) ? zBal : new _ocap_util.BN(0) : accountedSupply.gt(declaredSupply) ? accountedSupply.sub(declaredSupply) : new _ocap_util.BN(0);
627
+ const zombiePortion = termBal.gte(zBal) ? _ocap_util.BN.min(zBal, excessSupply) : new _ocap_util.BN(0);
628
+ const forwardPortion = zBal.sub(zombiePortion);
629
+ if (zombiePortion.gt(new _ocap_util.BN(0))) runningAccountedSupply.set(tokAddr, accountedSupply.sub(zombiePortion));
630
+ if (forwardPortion.isZero()) {
631
+ actions.push({
632
+ code: "I-BAL-2",
633
+ table: "balance",
634
+ key: `${acc.address}:${tokAddr}`,
635
+ action: "delete_migrated_account_zombie_balance",
636
+ before: {
637
+ address: acc.address,
638
+ tokenAddress: tokAddr,
639
+ balance: zBalStr
640
+ },
641
+ after: null
642
+ });
643
+ if (!dryRun) await executor.deleteFrom("balance").where("address", "=", acc.address).where("tokenAddress", "=", tokAddr).execute();
644
+ } else {
645
+ const nextTermBalBn = termBal.add(forwardPortion);
646
+ const nextTermBal = nextTermBalBn.toString(10);
647
+ liveBalanceMap.set(termBalKey, nextTermBalBn);
648
+ actions.push({
649
+ code: "I-BAL-2",
650
+ table: "balance",
651
+ key: `${acc.address}:${tokAddr}`,
652
+ action: "forward_migrated_account_balance",
653
+ before: {
654
+ from: {
655
+ address: acc.address,
656
+ balance: zBalStr
657
+ },
658
+ to: {
659
+ address: terminalAddr,
660
+ balance: termBal.toString(10)
661
+ }
662
+ },
663
+ after: {
664
+ from: null,
665
+ to: {
666
+ address: terminalAddr,
667
+ balance: nextTermBal
668
+ },
669
+ deletedDuplicateZombiePortion: zombiePortion.toString(10)
670
+ }
671
+ });
672
+ if (!dryRun) {
673
+ await executor.deleteFrom("balance").where("address", "=", acc.address).where("tokenAddress", "=", tokAddr).execute();
674
+ await executor.insertInto("balance").values({
675
+ address: terminalAddr,
676
+ tokenAddress: tokAddr,
677
+ balance: nextTermBal,
678
+ context: zRow.context || "{}"
679
+ }).onConflict((oc) => oc.columns(["address", "tokenAddress"]).doUpdateSet({ balance: nextTermBal })).execute();
680
+ }
681
+ }
682
+ }
683
+ const orphanAssets = await executor.selectFrom("asset").selectAll().where("owner", "=", acc.address).execute();
684
+ for (const ast of orphanAssets) {
685
+ actions.push({
686
+ code: "I-AST-1",
687
+ table: "asset",
688
+ key: ast.address,
689
+ action: "forward_asset_to_migrated_terminal_owner",
690
+ before: { owner: acc.address },
691
+ after: { owner: terminalAddr }
692
+ });
693
+ if (!dryRun) await executor.updateTable("asset").set({ owner: terminalAddr }).where("address", "=", ast.address).execute();
694
+ }
695
+ }
696
+ const stakes = await executor.selectFrom("stake").selectAll().execute();
697
+ const assets = await executor.selectFrom("asset").selectAll().execute();
698
+ const assetMap = new Map(assets.map((a) => [a.address, a]));
699
+ for (const stk of stakes) {
700
+ const activeAssets = parseJsonColumn(stk.assets, []);
701
+ const revokedAssets = parseJsonColumn(stk.revokedAssets, []);
702
+ const validRevoked = revokedAssets.filter((id) => {
703
+ const a = assetMap.get(id);
704
+ return Boolean(a && a.owner === stk.address);
705
+ });
706
+ const revokedSet = new Set(validRevoked);
707
+ const validActive = activeAssets.filter((id) => {
708
+ if (revokedSet.has(id)) return false;
709
+ const a = assetMap.get(id);
710
+ return Boolean(a && a.owner === stk.address);
711
+ });
712
+ if (validActive.length !== activeAssets.length || validRevoked.length !== revokedAssets.length) {
713
+ actions.push({
714
+ code: "I-STK-1",
715
+ table: "stake",
716
+ key: stk.address,
717
+ action: "prune_dangling_or_duplicate_stake_assets",
718
+ before: {
719
+ assets: activeAssets,
720
+ revokedAssets
721
+ },
722
+ after: {
723
+ assets: validActive,
724
+ revokedAssets: validRevoked
725
+ }
726
+ });
727
+ if (!dryRun) await executor.updateTable("stake").set({
728
+ assets: JSON.stringify(validActive),
729
+ revokedAssets: JSON.stringify(validRevoked)
730
+ }).where("address", "=", stk.address).execute();
731
+ }
732
+ }
733
+ const tokens = await executor.selectFrom("token").selectAll().execute();
734
+ for (const tok of tokens) try {
735
+ const charterAddr = (0, _arcblock_did_util.toTokenCharterAssetAddress)(tok.address);
736
+ const charter = assetMap.get(charterAddr);
737
+ if (charter) {
738
+ const charterData = parseJsonColumn(charter.data, null);
739
+ if (charterData?.value?.kind !== "TokenCharter" || charterData?.value?.tokenAddress !== tok.address) {
740
+ const repairedData = {
741
+ type: "json",
742
+ value: {
743
+ ...charterData?.value || {},
744
+ kind: "TokenCharter",
745
+ tokenAddress: tok.address,
746
+ symbol: tok.symbol,
747
+ name: tok.name
748
+ }
749
+ };
750
+ actions.push({
751
+ code: "I-TOK-4",
752
+ table: "asset",
753
+ key: charterAddr,
754
+ action: "repair_token_charter_payload",
755
+ before: charterData,
756
+ after: repairedData
757
+ });
758
+ if (!dryRun) await executor.updateTable("asset").set({ data: JSON.stringify(repairedData) }).where("address", "=", charterAddr).execute();
759
+ }
760
+ }
761
+ } catch {}
762
+ if (options.reconcileTokenSupply) {
763
+ const freshBalances = await executor.selectFrom("balance").selectAll().execute();
764
+ const freshStakes = await executor.selectFrom("stake").selectAll().execute();
765
+ const sums = /* @__PURE__ */ new Map();
766
+ for (const b of freshBalances) if (CANONICAL_UINT_REGEX.test(String(b.balance ?? ""))) {
767
+ const prev = sums.get(b.tokenAddress) || new _ocap_util.BN(0);
768
+ sums.set(b.tokenAddress, prev.add(new _ocap_util.BN(String(b.balance), 10)));
769
+ }
770
+ for (const s of freshStakes) {
771
+ const rev = parseJsonColumn(s.revokedTokens, {});
772
+ for (const [tAddr, val] of Object.entries(rev)) if (CANONICAL_UINT_REGEX.test(String(val ?? ""))) {
773
+ const prev = sums.get(tAddr) || new _ocap_util.BN(0);
774
+ sums.set(tAddr, prev.add(new _ocap_util.BN(String(val), 10)));
775
+ }
776
+ }
777
+ for (const tok of tokens) {
778
+ const expected = (sums.get(tok.address) || new _ocap_util.BN(0)).toString(10);
779
+ if (String(tok.totalSupply ?? "0") !== expected) {
780
+ actions.push({
781
+ code: "I-TOK-1",
782
+ table: "token",
783
+ key: tok.address,
784
+ action: "reconcile_token_total_supply",
785
+ before: { totalSupply: tok.totalSupply },
786
+ after: { totalSupply: expected }
787
+ });
788
+ if (!dryRun) await executor.updateTable("token").set({ totalSupply: expected }).where("address", "=", tok.address).execute();
789
+ }
790
+ }
791
+ const tokenFactories = await executor.selectFrom("tokenFactory").selectAll().execute();
792
+ for (const tf of tokenFactories) {
793
+ if (Number(tf.status || 0) !== 0) continue;
794
+ const expected = (sums.get(tf.tokenAddress) || new _ocap_util.BN(0)).toString(10);
795
+ if (String(tf.currentSupply ?? "0") !== expected) {
796
+ actions.push({
797
+ code: "I-TOK-3",
798
+ table: "tokenFactory",
799
+ key: tf.address,
800
+ action: "reconcile_token_factory_current_supply",
801
+ before: { currentSupply: tf.currentSupply },
802
+ after: { currentSupply: expected }
803
+ });
804
+ if (!dryRun) await executor.updateTable("tokenFactory").set({ currentSupply: expected }).where("address", "=", tf.address).execute();
805
+ }
806
+ }
807
+ }
808
+ };
809
+ if (dryRun) {
810
+ await executeRepairs(db.getKysely());
811
+ return {
812
+ dryRun: true,
813
+ reconciled: false,
814
+ beforeReport,
815
+ afterReport: beforeReport,
816
+ actions
817
+ };
818
+ }
819
+ await db.runAsLambda(async (txn) => {
820
+ await executeRepairs(txn);
821
+ }, { commitMessage: "reconcile_chain_state" });
822
+ await kysely.sql`PRAGMA wal_checkpoint(PASSIVE)`.execute(db.getKysely()).catch(() => {});
823
+ const afterReport = await verifyChainStateInvariants(db, { ledger: options.ledger });
824
+ return {
825
+ dryRun: false,
826
+ reconciled: afterReport.valid,
827
+ beforeReport,
828
+ afterReport,
829
+ actions
830
+ };
831
+ }
832
+
833
+ //#endregion
834
+ exports.assertSqliteStateDb = assertSqliteStateDb;
835
+ exports.reconcileChainState = reconcileChainState;
836
+ exports.verifyChainStateInvariants = verifyChainStateInvariants;