@ocap/tx-pipeline 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.
@@ -191,7 +191,15 @@ declare class OverlayStateDB {
191
191
  private assertLiveReadBudget;
192
192
  private assertLiveWriteBudget;
193
193
  private normalizeTableKey;
194
+ private static withRawAccountContext;
195
+ private static isAccountMigrateContext;
196
+ private static equalTokenRecords;
197
+ private static isPureCreditAboveTerminal;
198
+ private resolveMigratedCreditTarget;
199
+ private static assertValidAccountWrite;
194
200
  private readBase;
201
+ private getRawAccount;
202
+ private getAccountWithMigration;
195
203
  getBaseSnapshot(table: string, rawKey: unknown, ctx?: unknown): Promise<any>;
196
204
  hasTableWrite(table: string, rawKey: unknown): boolean;
197
205
  private createTableProxy;
@@ -334,7 +334,7 @@ function extractValidatedBalanceDiffIdentity(diff) {
334
334
  tokenAddress
335
335
  };
336
336
  }
337
- var OverlayStateDB = class {
337
+ var OverlayStateDB = class OverlayStateDB {
338
338
  constructor(baseStateDB, tables = DEFAULT_TABLES) {
339
339
  this.writes = /* @__PURE__ */ new Map();
340
340
  this.reads = /* @__PURE__ */ new Map();
@@ -427,25 +427,135 @@ var OverlayStateDB = class {
427
427
  baseQueryKey: key
428
428
  };
429
429
  }
430
+ static withRawAccountContext(table, ctx) {
431
+ if (table !== "account") return ctx;
432
+ return ctx && typeof ctx === "object" ? {
433
+ ...ctx,
434
+ traceMigration: false
435
+ } : { traceMigration: false };
436
+ }
437
+ static isAccountMigrateContext(ctx) {
438
+ if (!ctx || typeof ctx !== "object") return false;
439
+ const c = ctx;
440
+ const txType = c.tx?.itx?.typeUrl || c.tx?.type || c.tx?.itxJson?.type || c.txType || "";
441
+ return txType === "fg:t:account_migrate" || txType === "account_migrate";
442
+ }
443
+ static equalTokenRecords(a, b) {
444
+ const recA = a && typeof a === "object" ? a : {};
445
+ const recB = b && typeof b === "object" ? b : {};
446
+ const keys = new Set([...Object.keys(recA), ...Object.keys(recB)]);
447
+ for (const k of keys) {
448
+ const pa = parseNonNegativeBn(recA[k] === void 0 ? "0" : String(recA[k]));
449
+ const pb = parseNonNegativeBn(recB[k] === void 0 ? "0" : String(recB[k]));
450
+ if (!pa.ok || !pb.ok || !pa.value.eq(pb.value)) return false;
451
+ }
452
+ return true;
453
+ }
454
+ static isPureCreditAboveTerminal(terminal, updates) {
455
+ if (!terminal || typeof terminal !== "object" || !updates || typeof updates !== "object") return false;
456
+ const updMig = updates.migratedTo;
457
+ const termMig = Array.isArray(terminal.migratedTo) ? terminal.migratedTo : [];
458
+ if (updMig !== void 0 && !isEqual(updMig, termMig)) return false;
459
+ if (updates.nonce !== void 0 && String(updates.nonce ?? 0) !== String(terminal.nonce ?? 0)) return false;
460
+ if (updates.pk !== void 0 && String(updates.pk ?? "") !== String(terminal.pk ?? "")) return false;
461
+ if (updates.pendingTokens !== void 0 && !OverlayStateDB.equalTokenRecords(terminal.pendingTokens, updates.pendingTokens)) return false;
462
+ if (updates.revokedTokens !== void 0 && !OverlayStateDB.equalTokenRecords(terminal.revokedTokens, updates.revokedTokens)) return false;
463
+ if (!updates.tokens || typeof updates.tokens !== "object") return false;
464
+ const termToks = terminal.tokens && typeof terminal.tokens === "object" ? terminal.tokens : {};
465
+ const updToks = updates.tokens;
466
+ const allKeys = new Set([...Object.keys(termToks), ...Object.keys(updToks)]);
467
+ let hasPositiveCredit = false;
468
+ for (const k of allKeys) {
469
+ const pt = parseNonNegativeBn(termToks[k] === void 0 ? "0" : String(termToks[k]));
470
+ const pu = parseNonNegativeBn(updToks[k] === void 0 ? "0" : String(updToks[k]));
471
+ if (!pt.ok || !pu.ok || pu.value.lt(pt.value)) return false;
472
+ if (pu.value.gt(pt.value)) hasPositiveCredit = true;
473
+ }
474
+ return hasPositiveCredit;
475
+ }
476
+ async resolveMigratedCreditTarget(key, priorRaw, updates, ctx) {
477
+ if ((Array.isArray(priorRaw?.migratedTo) ? priorRaw.migratedTo : []).length === 0 || OverlayStateDB.isAccountMigrateContext(ctx)) return null;
478
+ if (Boolean(ctx && typeof ctx === "object" && ctx.traceMigration === false)) return null;
479
+ const terminal = await this.getAccountWithMigration(key, void 0);
480
+ if (!terminal || typeof terminal.address !== "string" || !terminal.address) return null;
481
+ if (canonicalizeStateKey(terminal.address) === key || !OverlayStateDB.isPureCreditAboveTerminal(terminal, updates)) return null;
482
+ return {
483
+ targetAddr: terminal.address,
484
+ patchedUpdates: {
485
+ ...cloneDeep(updates),
486
+ address: terminal.address
487
+ }
488
+ };
489
+ }
490
+ static assertValidAccountWrite(key, beforeState, priorState, afterState, op, ctx) {
491
+ const beforeMig = Array.isArray(beforeState?.migratedTo) ? beforeState.migratedTo : [];
492
+ const effectiveTombstone = (Array.isArray(priorState?.migratedTo) ? priorState.migratedTo : []).length > 0 ? priorState : beforeMig.length > 0 ? beforeState : null;
493
+ if (op === "delete") {
494
+ if (effectiveTombstone) throw new CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Cannot delete migrated tombstone account "${key}"`);
495
+ return;
496
+ }
497
+ if (afterState && typeof afterState === "object" && typeof afterState.address === "string" && afterState.address) {
498
+ if (canonicalizeStateKey(afterState.address) !== key) throw new CustomError(effectiveTombstone ? "TOMBSTONE_ACCOUNT_VIOLATION" : "ACCOUNT_IDENTITY_MISMATCH", `Account write key "${key}" does not match state address "${afterState.address}"`);
499
+ }
500
+ const afterMig = Array.isArray(afterState?.migratedTo) ? afterState.migratedTo : [];
501
+ if (afterMig.length > 0) {
502
+ for (const target of afterMig) if (typeof target !== "string" || !target.trim() || canonicalizeStateKey(target) === key) throw new CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Invalid or self-referential migratedTo target on account "${key}"`);
503
+ }
504
+ if (effectiveTombstone) {
505
+ const tombMig = Array.isArray(effectiveTombstone.migratedTo) ? effectiveTombstone.migratedTo : [];
506
+ if (afterMig.length === 0) throw new CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Cannot clear migratedTo on migrated tombstone account "${key}"`);
507
+ if (!OverlayStateDB.equalTokenRecords(effectiveTombstone.tokens, afterState?.tokens) || !OverlayStateDB.equalTokenRecords(effectiveTombstone.pendingTokens, afterState?.pendingTokens) || !OverlayStateDB.equalTokenRecords(effectiveTombstone.revokedTokens, afterState?.revokedTokens)) throw new CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Cannot mutate token balances on migrated tombstone account "${key}"`);
508
+ if (String(effectiveTombstone.nonce ?? 0) !== String(afterState?.nonce ?? 0)) throw new CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Cannot mutate nonce on migrated tombstone account "${key}"`);
509
+ if (String(effectiveTombstone.pk ?? "") !== String(afterState?.pk ?? "")) throw new CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Cannot mutate pk on migrated tombstone account "${key}"`);
510
+ if (!isEqual(tombMig, afterMig) && !OverlayStateDB.isAccountMigrateContext(ctx)) throw new CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Cannot mutate migratedTo on tombstone account "${key}" outside account_migrate`);
511
+ }
512
+ }
430
513
  async readBase(table, rawKey, ctx) {
431
514
  const { key, baseQueryKey } = this.normalizeTableKey(table, rawKey, "key");
432
515
  const readsMap = this.getTableReads(table);
433
516
  if (readsMap.has(key)) return cloneDeep(readsMap.get(key));
434
517
  this.assertLiveReadBudget(table, key);
435
518
  const baseTable = this.base?.[table];
519
+ const baseCtx = OverlayStateDB.withRawAccountContext(table, ctx);
436
520
  let val = null;
437
521
  if (typeof baseTable?.get === "function") {
438
522
  if (table === "balance" && baseQueryKey !== key) try {
439
- val = await baseTable.get(baseQueryKey, ctx);
523
+ val = await baseTable.get(baseQueryKey, baseCtx);
440
524
  } catch {
441
- val = await baseTable.get(key, ctx);
525
+ val = await baseTable.get(key, baseCtx);
442
526
  }
443
- else val = await baseTable.get(baseQueryKey, ctx);
444
- if ((val === null || val === void 0) && typeof rawKey === "string" && rawKey !== key) val = await baseTable.get(rawKey, ctx);
527
+ else val = await baseTable.get(baseQueryKey, baseCtx);
528
+ if ((val === null || val === void 0) && typeof rawKey === "string" && rawKey !== key) val = await baseTable.get(rawKey, baseCtx);
445
529
  }
446
530
  readsMap.set(key, cloneDeep(val ?? null));
447
531
  return cloneDeep(val ?? null);
448
532
  }
533
+ async getRawAccount(rawKey, ctx) {
534
+ const { key } = this.normalizeTableKey("account", rawKey, "key");
535
+ const tableWrites = this.writes.get("account");
536
+ if (tableWrites?.has(key)) {
537
+ const entry = tableWrites.get(key);
538
+ return entry.op === "delete" ? null : cloneDeep(entry.after);
539
+ }
540
+ return this.readBase("account", rawKey, ctx);
541
+ }
542
+ async getAccountWithMigration(rawKey, ctx) {
543
+ if (!!(ctx && typeof ctx === "object" && ctx.traceMigration === false)) return this.getRawAccount(rawKey, ctx);
544
+ const visited = /* @__PURE__ */ new Set();
545
+ let currentKey = rawKey;
546
+ for (let hop = 0; hop <= 64; hop++) {
547
+ const { key } = this.normalizeTableKey("account", currentKey, "key");
548
+ if (visited.has(key)) return null;
549
+ visited.add(key);
550
+ const acct = await this.getRawAccount(currentKey, ctx);
551
+ if (!acct) return null;
552
+ const migratedTo = Array.isArray(acct.migratedTo) ? acct.migratedTo : [];
553
+ if (migratedTo.length === 0) return acct;
554
+ if (hop === 64 || typeof migratedTo[0] !== "string" || !migratedTo[0].trim()) return null;
555
+ currentKey = migratedTo[0];
556
+ }
557
+ return null;
558
+ }
449
559
  async getBaseSnapshot(table, rawKey, ctx) {
450
560
  assertSafeKey(table, "table");
451
561
  return this.readBase(table, rawKey, ctx);
@@ -461,6 +571,7 @@ var OverlayStateDB = class {
461
571
  createTableProxy(table) {
462
572
  const proxy = {
463
573
  get: async (rawKey, ctx) => {
574
+ if (table === "account") return this.getAccountWithMigration(rawKey, ctx);
464
575
  const { key } = this.normalizeTableKey(table, rawKey, "key");
465
576
  const tableWrites = this.writes.get(table);
466
577
  if (tableWrites?.has(key)) {
@@ -475,19 +586,29 @@ var OverlayStateDB = class {
475
586
  const tableWrites = this.getTableWrites(table);
476
587
  const existingWrite = tableWrites.get(key);
477
588
  const before = existingWrite ? existingWrite.before : await this.readBase(table, rawKey, ctx);
589
+ const prior = existingWrite ? existingWrite.after : before;
478
590
  const cloned = typeof baseQueryKey === "object" && state && typeof state === "object" ? cloneDeep({
479
591
  ...baseQueryKey,
480
592
  ...state
481
593
  }) : cloneDeep(state);
594
+ if (table === "account") OverlayStateDB.assertValidAccountWrite(key, before, prior, cloned, "create", ctx);
595
+ const isAcctMigrate = (table === "account" || table === "balance") && OverlayStateDB.isAccountMigrateContext(ctx) && (!existingWrite || existingWrite.authorizedAccountMigrate === true);
482
596
  tableWrites.set(key, {
483
597
  op: before ? "update" : "create",
484
598
  before,
485
- after: cloned
599
+ after: cloned,
600
+ ...isAcctMigrate ? { authorizedAccountMigrate: true } : {}
486
601
  });
487
602
  return cloneDeep(cloned);
488
603
  },
489
604
  update: async (rawKey, updates, ctx) => {
490
605
  const { key, baseQueryKey } = this.normalizeTableKey(table, rawKey, "key");
606
+ if (table === "account") {
607
+ const existingAccountWrite = this.writes.get("account")?.get(key);
608
+ const priorAccountRaw = existingAccountWrite ? existingAccountWrite.after : await this.readBase("account", rawKey, ctx);
609
+ const redirect = await this.resolveMigratedCreditTarget(key, priorAccountRaw, updates, ctx);
610
+ if (redirect) return proxy.update(redirect.targetAddr, redirect.patchedUpdates, ctx);
611
+ }
491
612
  this.assertLiveWriteBudget(table, key);
492
613
  const tableWrites = this.getTableWrites(table);
493
614
  const existingWrite = tableWrites.get(key);
@@ -502,20 +623,24 @@ var OverlayStateDB = class {
502
623
  ...baseObj,
503
624
  ...updates
504
625
  }) : cloneDeep(updates);
626
+ if (table === "account") OverlayStateDB.assertValidAccountWrite(key, before, current, merged, "update", ctx);
627
+ const isAcctMigrate = (table === "account" || table === "balance") && OverlayStateDB.isAccountMigrateContext(ctx) && (!existingWrite || existingWrite.authorizedAccountMigrate === true);
505
628
  tableWrites.set(key, {
506
629
  op: before ? "update" : "create",
507
630
  before,
508
- after: merged
631
+ after: merged,
632
+ ...isAcctMigrate ? { authorizedAccountMigrate: true } : {}
509
633
  });
510
634
  return cloneDeep(merged);
511
635
  },
512
636
  updateOrCreate: async (existing, updates, ctx) => {
513
- const rawKey = table === "balance" && typeof (updates?.address || existing?.address) === "string" && typeof (updates?.tokenAddress || existing?.tokenAddress) === "string" ? {
514
- address: updates?.address || existing?.address,
637
+ const existingAddr = typeof existing === "string" ? existing : existing?.address;
638
+ const rawKey = table === "balance" && typeof (updates?.address || existingAddr) === "string" && typeof (updates?.tokenAddress || existing?.tokenAddress) === "string" ? {
639
+ address: updates?.address || existingAddr,
515
640
  tokenAddress: updates?.tokenAddress || existing?.tokenAddress
516
- } : updates?.address || existing?.address;
641
+ } : updates?.address || existingAddr;
517
642
  const { baseQueryKey } = this.normalizeTableKey(table, rawKey, "address");
518
- if (await this[table].get(baseQueryKey, ctx)) return this[table].update(baseQueryKey, updates, ctx);
643
+ if (table === "account" ? await this.getRawAccount(baseQueryKey, ctx) : await this[table].get(baseQueryKey, ctx)) return this[table].update(baseQueryKey, updates, ctx);
519
644
  return this[table].create(baseQueryKey, updates, ctx);
520
645
  },
521
646
  delete: async (rawKey, ctx) => {
@@ -524,10 +649,14 @@ var OverlayStateDB = class {
524
649
  const tableWrites = this.getTableWrites(table);
525
650
  const existingWrite = tableWrites.get(key);
526
651
  const before = existingWrite ? existingWrite.before : await this.readBase(table, rawKey, ctx);
652
+ const prior = existingWrite ? existingWrite.after : before;
653
+ if (table === "account") OverlayStateDB.assertValidAccountWrite(key, before, prior, null, "delete", ctx);
654
+ const isAcctMigrate = table === "balance" && OverlayStateDB.isAccountMigrateContext(ctx) && (!existingWrite || existingWrite.authorizedAccountMigrate === true);
527
655
  tableWrites.set(key, {
528
656
  op: "delete",
529
657
  before,
530
- after: null
658
+ after: null,
659
+ ...isAcctMigrate ? { authorizedAccountMigrate: true } : {}
531
660
  });
532
661
  }
533
662
  };
@@ -849,9 +978,10 @@ var OverlayStateDB = class {
849
978
  currentVal = await baseTable.get(key, ctx);
850
979
  }
851
980
  } else {
981
+ const baseCtx = OverlayStateDB.withRawAccountContext(table, ctx);
852
982
  const canonKey = canonicalizeStateKey(key);
853
- currentVal = await baseTable.get(canonKey, ctx);
854
- if ((currentVal === null || currentVal === void 0) && canonKey !== key) currentVal = await baseTable.get(key, ctx);
983
+ currentVal = await baseTable.get(canonKey, baseCtx);
984
+ if ((currentVal === null || currentVal === void 0) && canonKey !== key) currentVal = await baseTable.get(key, baseCtx);
855
985
  }
856
986
  if (!isEqual(currentVal ?? null, expectedVal ?? null)) return false;
857
987
  }
@@ -860,8 +990,26 @@ var OverlayStateDB = class {
860
990
  }
861
991
  async commit(ctx) {
862
992
  const diffs = this.getStateDiff();
863
- for (const diff of diffs) if (diff.table === "balance") {
864
- if (!extractValidatedBalanceDiffIdentity(diff).ok) throw new CustomError("ACCOUNTING_INVARIANT_VIOLATION", `Invalid or mutated balance row identity for key "${diff.key}"`);
993
+ const accountWrites = this.writes.get("account");
994
+ const balanceWrites = this.writes.get("balance");
995
+ for (const diff of diffs) if (diff.table === "account") {
996
+ const effectiveCtx = (accountWrites?.get(diff.key))?.authorizedAccountMigrate ? { txType: "account_migrate" } : ctx;
997
+ OverlayStateDB.assertValidAccountWrite(diff.key, diff.before, diff.before, diff.after, diff.op, effectiveCtx);
998
+ } else if (diff.table === "balance") {
999
+ const identity = extractValidatedBalanceDiffIdentity(diff);
1000
+ if (!identity.ok) throw new CustomError("ACCOUNTING_INVARIANT_VIOLATION", `Invalid or mutated balance row identity for key "${diff.key}"`);
1001
+ const baseOwnerAcct = await this.readBase("account", identity.address, ctx);
1002
+ const curOwnerAcct = await this.getRawAccount(identity.address, ctx);
1003
+ const balanceEntry = balanceWrites?.get(diff.key);
1004
+ if (Array.isArray(baseOwnerAcct?.migratedTo) && baseOwnerAcct.migratedTo.length > 0) throw new CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Cannot mutate balance row "${diff.key}" of pre-existing migrated tombstone account "${identity.address}"`);
1005
+ if (Array.isArray(curOwnerAcct?.migratedTo) && curOwnerAcct.migratedTo.length > 0) {
1006
+ const afterBal = diff.op === "delete" ? {
1007
+ ok: true,
1008
+ value: new BN(0)
1009
+ } : parseNonNegativeBn(diff.after?.balance);
1010
+ const isZeroed = afterBal.ok && afterBal.value.isZero();
1011
+ if (!(OverlayStateDB.isAccountMigrateContext(ctx) || balanceEntry?.authorizedAccountMigrate === true) || !isZeroed) throw new CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Cannot leave non-zero or unauthorized balance row "${diff.key}" on migrated tombstone account "${identity.address}"`);
1012
+ }
865
1013
  }
866
1014
  const applyDiffs = async (commitCtx) => {
867
1015
  for (const diff of diffs) {
@@ -1680,8 +1828,9 @@ var TwoPhaseTransferLedger = class {
1680
1828
  if (typeof params.amount !== "string" || !CANONICAL_NON_NEGATIVE_INT_REGEX.test(params.amount)) throw new CustomError("INVALID_AMOUNT", "Pending transfer amount must be a positive base-10 integer string");
1681
1829
  const amt = new BN(params.amount, 10);
1682
1830
  if (amt.lte(new BN(0))) throw new CustomError("INVALID_AMOUNT", "Pending transfer amount must be greater than 0");
1683
- const debitAccount = await statedb.account.get(params.debitAddress);
1831
+ const debitAccount = await statedb.account.get(params.debitAddress, { traceMigration: false });
1684
1832
  if (!debitAccount) throw new CustomError("INVALID_SENDER_STATE", `Debit account ${params.debitAddress} not found`);
1833
+ if (Array.isArray(debitAccount.migratedTo) && debitAccount.migratedTo.length > 0 || typeof debitAccount.address === "string" && debitAccount.address && canonicalizeStateKey(debitAccount.address) !== canonicalizeStateKey(params.debitAddress)) throw new CustomError("ACCOUNT_MIGRATED", `Debit account ${params.debitAddress} has been migrated`);
1685
1834
  const available = new BN(debitAccount.tokens?.[params.tokenAddress] || "0");
1686
1835
  if (available.lt(amt)) throw new CustomError("INSUFFICIENT_BALANCE", `Insufficient available balance for ${params.tokenAddress}`);
1687
1836
  const nextAvailable = available.sub(amt).toString(10);
@@ -1715,7 +1864,8 @@ var TwoPhaseTransferLedger = class {
1715
1864
  if (record.status !== "PENDING") throw new CustomError("INVALID_STATE", `Pending transfer ${params.id} is already ${record.status}`);
1716
1865
  if (params.currentHeight > record.timeoutHeight) throw new CustomError("EXPIRED_PENDING_TRANSFER", `Pending transfer ${params.id} has expired`);
1717
1866
  const amt = new BN(record.amount);
1718
- const debitAccount = await statedb.account.get(record.debitAddress);
1867
+ const debitAccount = await statedb.account.get(record.debitAddress, { traceMigration: false });
1868
+ if (debitAccount && (Array.isArray(debitAccount.migratedTo) && debitAccount.migratedTo.length > 0 || typeof debitAccount.address === "string" && debitAccount.address && canonicalizeStateKey(debitAccount.address) !== canonicalizeStateKey(record.debitAddress))) throw new CustomError("ACCOUNT_MIGRATED", `Debit account ${record.debitAddress} has been migrated`);
1719
1869
  const curPending = new BN(debitAccount?.pendingTokens?.[record.tokenAddress] || "0");
1720
1870
  if (curPending.lt(amt)) throw new CustomError("INSUFFICIENT_PENDING", "Locked pending balance corrupted");
1721
1871
  await statedb.account.update(record.debitAddress, {
@@ -1726,15 +1876,16 @@ var TwoPhaseTransferLedger = class {
1726
1876
  }
1727
1877
  });
1728
1878
  const existingCredit = await statedb.account.get(record.creditAddress);
1879
+ const resolvedCreditAddr = existingCredit && typeof existingCredit.address === "string" && existingCredit.address ? existingCredit.address : record.creditAddress;
1729
1880
  const creditAccount = existingCredit || {
1730
- address: record.creditAddress,
1881
+ address: resolvedCreditAddr,
1731
1882
  tokens: {},
1732
1883
  pendingTokens: {}
1733
1884
  };
1734
1885
  const curCredit = new BN(creditAccount.tokens?.[record.tokenAddress] || "0");
1735
1886
  await statedb.account.updateOrCreate(existingCredit, {
1736
1887
  ...creditAccount,
1737
- address: record.creditAddress,
1888
+ address: resolvedCreditAddr,
1738
1889
  tokens: {
1739
1890
  ...creditAccount.tokens || {},
1740
1891
  [record.tokenAddress]: curCredit.add(amt).toString(10)
@@ -1748,8 +1899,9 @@ var TwoPhaseTransferLedger = class {
1748
1899
  if (!record) throw new CustomError("NOT_FOUND", `Pending transfer ${params.id} not found`);
1749
1900
  if (record.status !== "PENDING") throw new CustomError("INVALID_STATE", `Pending transfer ${params.id} is already ${record.status}`);
1750
1901
  const amt = new BN(record.amount, 10);
1751
- const debitAccount = await statedb.account.get(record.debitAddress);
1902
+ const debitAccount = await statedb.account.get(record.debitAddress, { traceMigration: false });
1752
1903
  if (!debitAccount) throw new CustomError("INVALID_SENDER_STATE", `Debit account ${record.debitAddress} not found`);
1904
+ if (Array.isArray(debitAccount.migratedTo) && debitAccount.migratedTo.length > 0 || typeof debitAccount.address === "string" && debitAccount.address && canonicalizeStateKey(debitAccount.address) !== canonicalizeStateKey(record.debitAddress)) throw new CustomError("ACCOUNT_MIGRATED", `Debit account ${record.debitAddress} has been migrated`);
1753
1905
  const curPending = new BN(debitAccount?.pendingTokens?.[record.tokenAddress] || "0", 10);
1754
1906
  if (curPending.lt(amt)) throw new CustomError("INSUFFICIENT_PENDING", "Locked pending balance corrupted");
1755
1907
  const curAvailable = new BN(debitAccount?.tokens?.[record.tokenAddress] || "0", 10);
@@ -337,7 +337,7 @@ function extractValidatedBalanceDiffIdentity(diff) {
337
337
  tokenAddress
338
338
  };
339
339
  }
340
- var OverlayStateDB = class {
340
+ var OverlayStateDB = class OverlayStateDB {
341
341
  constructor(baseStateDB, tables = DEFAULT_TABLES) {
342
342
  this.writes = /* @__PURE__ */ new Map();
343
343
  this.reads = /* @__PURE__ */ new Map();
@@ -430,25 +430,135 @@ var OverlayStateDB = class {
430
430
  baseQueryKey: key
431
431
  };
432
432
  }
433
+ static withRawAccountContext(table, ctx) {
434
+ if (table !== "account") return ctx;
435
+ return ctx && typeof ctx === "object" ? {
436
+ ...ctx,
437
+ traceMigration: false
438
+ } : { traceMigration: false };
439
+ }
440
+ static isAccountMigrateContext(ctx) {
441
+ if (!ctx || typeof ctx !== "object") return false;
442
+ const c = ctx;
443
+ const txType = c.tx?.itx?.typeUrl || c.tx?.type || c.tx?.itxJson?.type || c.txType || "";
444
+ return txType === "fg:t:account_migrate" || txType === "account_migrate";
445
+ }
446
+ static equalTokenRecords(a, b) {
447
+ const recA = a && typeof a === "object" ? a : {};
448
+ const recB = b && typeof b === "object" ? b : {};
449
+ const keys = new Set([...Object.keys(recA), ...Object.keys(recB)]);
450
+ for (const k of keys) {
451
+ const pa = parseNonNegativeBn(recA[k] === void 0 ? "0" : String(recA[k]));
452
+ const pb = parseNonNegativeBn(recB[k] === void 0 ? "0" : String(recB[k]));
453
+ if (!pa.ok || !pb.ok || !pa.value.eq(pb.value)) return false;
454
+ }
455
+ return true;
456
+ }
457
+ static isPureCreditAboveTerminal(terminal, updates) {
458
+ if (!terminal || typeof terminal !== "object" || !updates || typeof updates !== "object") return false;
459
+ const updMig = updates.migratedTo;
460
+ const termMig = Array.isArray(terminal.migratedTo) ? terminal.migratedTo : [];
461
+ if (updMig !== void 0 && !(0, lodash_isEqual.default)(updMig, termMig)) return false;
462
+ if (updates.nonce !== void 0 && String(updates.nonce ?? 0) !== String(terminal.nonce ?? 0)) return false;
463
+ if (updates.pk !== void 0 && String(updates.pk ?? "") !== String(terminal.pk ?? "")) return false;
464
+ if (updates.pendingTokens !== void 0 && !OverlayStateDB.equalTokenRecords(terminal.pendingTokens, updates.pendingTokens)) return false;
465
+ if (updates.revokedTokens !== void 0 && !OverlayStateDB.equalTokenRecords(terminal.revokedTokens, updates.revokedTokens)) return false;
466
+ if (!updates.tokens || typeof updates.tokens !== "object") return false;
467
+ const termToks = terminal.tokens && typeof terminal.tokens === "object" ? terminal.tokens : {};
468
+ const updToks = updates.tokens;
469
+ const allKeys = new Set([...Object.keys(termToks), ...Object.keys(updToks)]);
470
+ let hasPositiveCredit = false;
471
+ for (const k of allKeys) {
472
+ const pt = parseNonNegativeBn(termToks[k] === void 0 ? "0" : String(termToks[k]));
473
+ const pu = parseNonNegativeBn(updToks[k] === void 0 ? "0" : String(updToks[k]));
474
+ if (!pt.ok || !pu.ok || pu.value.lt(pt.value)) return false;
475
+ if (pu.value.gt(pt.value)) hasPositiveCredit = true;
476
+ }
477
+ return hasPositiveCredit;
478
+ }
479
+ async resolveMigratedCreditTarget(key, priorRaw, updates, ctx) {
480
+ if ((Array.isArray(priorRaw?.migratedTo) ? priorRaw.migratedTo : []).length === 0 || OverlayStateDB.isAccountMigrateContext(ctx)) return null;
481
+ if (Boolean(ctx && typeof ctx === "object" && ctx.traceMigration === false)) return null;
482
+ const terminal = await this.getAccountWithMigration(key, void 0);
483
+ if (!terminal || typeof terminal.address !== "string" || !terminal.address) return null;
484
+ if (canonicalizeStateKey(terminal.address) === key || !OverlayStateDB.isPureCreditAboveTerminal(terminal, updates)) return null;
485
+ return {
486
+ targetAddr: terminal.address,
487
+ patchedUpdates: {
488
+ ...(0, lodash_cloneDeep.default)(updates),
489
+ address: terminal.address
490
+ }
491
+ };
492
+ }
493
+ static assertValidAccountWrite(key, beforeState, priorState, afterState, op, ctx) {
494
+ const beforeMig = Array.isArray(beforeState?.migratedTo) ? beforeState.migratedTo : [];
495
+ const effectiveTombstone = (Array.isArray(priorState?.migratedTo) ? priorState.migratedTo : []).length > 0 ? priorState : beforeMig.length > 0 ? beforeState : null;
496
+ if (op === "delete") {
497
+ if (effectiveTombstone) throw new _ocap_util_lib_error.CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Cannot delete migrated tombstone account "${key}"`);
498
+ return;
499
+ }
500
+ if (afterState && typeof afterState === "object" && typeof afterState.address === "string" && afterState.address) {
501
+ if (canonicalizeStateKey(afterState.address) !== key) throw new _ocap_util_lib_error.CustomError(effectiveTombstone ? "TOMBSTONE_ACCOUNT_VIOLATION" : "ACCOUNT_IDENTITY_MISMATCH", `Account write key "${key}" does not match state address "${afterState.address}"`);
502
+ }
503
+ const afterMig = Array.isArray(afterState?.migratedTo) ? afterState.migratedTo : [];
504
+ if (afterMig.length > 0) {
505
+ for (const target of afterMig) if (typeof target !== "string" || !target.trim() || canonicalizeStateKey(target) === key) throw new _ocap_util_lib_error.CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Invalid or self-referential migratedTo target on account "${key}"`);
506
+ }
507
+ if (effectiveTombstone) {
508
+ const tombMig = Array.isArray(effectiveTombstone.migratedTo) ? effectiveTombstone.migratedTo : [];
509
+ if (afterMig.length === 0) throw new _ocap_util_lib_error.CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Cannot clear migratedTo on migrated tombstone account "${key}"`);
510
+ if (!OverlayStateDB.equalTokenRecords(effectiveTombstone.tokens, afterState?.tokens) || !OverlayStateDB.equalTokenRecords(effectiveTombstone.pendingTokens, afterState?.pendingTokens) || !OverlayStateDB.equalTokenRecords(effectiveTombstone.revokedTokens, afterState?.revokedTokens)) throw new _ocap_util_lib_error.CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Cannot mutate token balances on migrated tombstone account "${key}"`);
511
+ if (String(effectiveTombstone.nonce ?? 0) !== String(afterState?.nonce ?? 0)) throw new _ocap_util_lib_error.CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Cannot mutate nonce on migrated tombstone account "${key}"`);
512
+ if (String(effectiveTombstone.pk ?? "") !== String(afterState?.pk ?? "")) throw new _ocap_util_lib_error.CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Cannot mutate pk on migrated tombstone account "${key}"`);
513
+ if (!(0, lodash_isEqual.default)(tombMig, afterMig) && !OverlayStateDB.isAccountMigrateContext(ctx)) throw new _ocap_util_lib_error.CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Cannot mutate migratedTo on tombstone account "${key}" outside account_migrate`);
514
+ }
515
+ }
433
516
  async readBase(table, rawKey, ctx) {
434
517
  const { key, baseQueryKey } = this.normalizeTableKey(table, rawKey, "key");
435
518
  const readsMap = this.getTableReads(table);
436
519
  if (readsMap.has(key)) return (0, lodash_cloneDeep.default)(readsMap.get(key));
437
520
  this.assertLiveReadBudget(table, key);
438
521
  const baseTable = this.base?.[table];
522
+ const baseCtx = OverlayStateDB.withRawAccountContext(table, ctx);
439
523
  let val = null;
440
524
  if (typeof baseTable?.get === "function") {
441
525
  if (table === "balance" && baseQueryKey !== key) try {
442
- val = await baseTable.get(baseQueryKey, ctx);
526
+ val = await baseTable.get(baseQueryKey, baseCtx);
443
527
  } catch {
444
- val = await baseTable.get(key, ctx);
528
+ val = await baseTable.get(key, baseCtx);
445
529
  }
446
- else val = await baseTable.get(baseQueryKey, ctx);
447
- if ((val === null || val === void 0) && typeof rawKey === "string" && rawKey !== key) val = await baseTable.get(rawKey, ctx);
530
+ else val = await baseTable.get(baseQueryKey, baseCtx);
531
+ if ((val === null || val === void 0) && typeof rawKey === "string" && rawKey !== key) val = await baseTable.get(rawKey, baseCtx);
448
532
  }
449
533
  readsMap.set(key, (0, lodash_cloneDeep.default)(val ?? null));
450
534
  return (0, lodash_cloneDeep.default)(val ?? null);
451
535
  }
536
+ async getRawAccount(rawKey, ctx) {
537
+ const { key } = this.normalizeTableKey("account", rawKey, "key");
538
+ const tableWrites = this.writes.get("account");
539
+ if (tableWrites?.has(key)) {
540
+ const entry = tableWrites.get(key);
541
+ return entry.op === "delete" ? null : (0, lodash_cloneDeep.default)(entry.after);
542
+ }
543
+ return this.readBase("account", rawKey, ctx);
544
+ }
545
+ async getAccountWithMigration(rawKey, ctx) {
546
+ if (!!(ctx && typeof ctx === "object" && ctx.traceMigration === false)) return this.getRawAccount(rawKey, ctx);
547
+ const visited = /* @__PURE__ */ new Set();
548
+ let currentKey = rawKey;
549
+ for (let hop = 0; hop <= 64; hop++) {
550
+ const { key } = this.normalizeTableKey("account", currentKey, "key");
551
+ if (visited.has(key)) return null;
552
+ visited.add(key);
553
+ const acct = await this.getRawAccount(currentKey, ctx);
554
+ if (!acct) return null;
555
+ const migratedTo = Array.isArray(acct.migratedTo) ? acct.migratedTo : [];
556
+ if (migratedTo.length === 0) return acct;
557
+ if (hop === 64 || typeof migratedTo[0] !== "string" || !migratedTo[0].trim()) return null;
558
+ currentKey = migratedTo[0];
559
+ }
560
+ return null;
561
+ }
452
562
  async getBaseSnapshot(table, rawKey, ctx) {
453
563
  assertSafeKey(table, "table");
454
564
  return this.readBase(table, rawKey, ctx);
@@ -464,6 +574,7 @@ var OverlayStateDB = class {
464
574
  createTableProxy(table) {
465
575
  const proxy = {
466
576
  get: async (rawKey, ctx) => {
577
+ if (table === "account") return this.getAccountWithMigration(rawKey, ctx);
467
578
  const { key } = this.normalizeTableKey(table, rawKey, "key");
468
579
  const tableWrites = this.writes.get(table);
469
580
  if (tableWrites?.has(key)) {
@@ -478,19 +589,29 @@ var OverlayStateDB = class {
478
589
  const tableWrites = this.getTableWrites(table);
479
590
  const existingWrite = tableWrites.get(key);
480
591
  const before = existingWrite ? existingWrite.before : await this.readBase(table, rawKey, ctx);
592
+ const prior = existingWrite ? existingWrite.after : before;
481
593
  const cloned = typeof baseQueryKey === "object" && state && typeof state === "object" ? (0, lodash_cloneDeep.default)({
482
594
  ...baseQueryKey,
483
595
  ...state
484
596
  }) : (0, lodash_cloneDeep.default)(state);
597
+ if (table === "account") OverlayStateDB.assertValidAccountWrite(key, before, prior, cloned, "create", ctx);
598
+ const isAcctMigrate = (table === "account" || table === "balance") && OverlayStateDB.isAccountMigrateContext(ctx) && (!existingWrite || existingWrite.authorizedAccountMigrate === true);
485
599
  tableWrites.set(key, {
486
600
  op: before ? "update" : "create",
487
601
  before,
488
- after: cloned
602
+ after: cloned,
603
+ ...isAcctMigrate ? { authorizedAccountMigrate: true } : {}
489
604
  });
490
605
  return (0, lodash_cloneDeep.default)(cloned);
491
606
  },
492
607
  update: async (rawKey, updates, ctx) => {
493
608
  const { key, baseQueryKey } = this.normalizeTableKey(table, rawKey, "key");
609
+ if (table === "account") {
610
+ const existingAccountWrite = this.writes.get("account")?.get(key);
611
+ const priorAccountRaw = existingAccountWrite ? existingAccountWrite.after : await this.readBase("account", rawKey, ctx);
612
+ const redirect = await this.resolveMigratedCreditTarget(key, priorAccountRaw, updates, ctx);
613
+ if (redirect) return proxy.update(redirect.targetAddr, redirect.patchedUpdates, ctx);
614
+ }
494
615
  this.assertLiveWriteBudget(table, key);
495
616
  const tableWrites = this.getTableWrites(table);
496
617
  const existingWrite = tableWrites.get(key);
@@ -505,20 +626,24 @@ var OverlayStateDB = class {
505
626
  ...baseObj,
506
627
  ...updates
507
628
  }) : (0, lodash_cloneDeep.default)(updates);
629
+ if (table === "account") OverlayStateDB.assertValidAccountWrite(key, before, current, merged, "update", ctx);
630
+ const isAcctMigrate = (table === "account" || table === "balance") && OverlayStateDB.isAccountMigrateContext(ctx) && (!existingWrite || existingWrite.authorizedAccountMigrate === true);
508
631
  tableWrites.set(key, {
509
632
  op: before ? "update" : "create",
510
633
  before,
511
- after: merged
634
+ after: merged,
635
+ ...isAcctMigrate ? { authorizedAccountMigrate: true } : {}
512
636
  });
513
637
  return (0, lodash_cloneDeep.default)(merged);
514
638
  },
515
639
  updateOrCreate: async (existing, updates, ctx) => {
516
- const rawKey = table === "balance" && typeof (updates?.address || existing?.address) === "string" && typeof (updates?.tokenAddress || existing?.tokenAddress) === "string" ? {
517
- address: updates?.address || existing?.address,
640
+ const existingAddr = typeof existing === "string" ? existing : existing?.address;
641
+ const rawKey = table === "balance" && typeof (updates?.address || existingAddr) === "string" && typeof (updates?.tokenAddress || existing?.tokenAddress) === "string" ? {
642
+ address: updates?.address || existingAddr,
518
643
  tokenAddress: updates?.tokenAddress || existing?.tokenAddress
519
- } : updates?.address || existing?.address;
644
+ } : updates?.address || existingAddr;
520
645
  const { baseQueryKey } = this.normalizeTableKey(table, rawKey, "address");
521
- if (await this[table].get(baseQueryKey, ctx)) return this[table].update(baseQueryKey, updates, ctx);
646
+ if (table === "account" ? await this.getRawAccount(baseQueryKey, ctx) : await this[table].get(baseQueryKey, ctx)) return this[table].update(baseQueryKey, updates, ctx);
522
647
  return this[table].create(baseQueryKey, updates, ctx);
523
648
  },
524
649
  delete: async (rawKey, ctx) => {
@@ -527,10 +652,14 @@ var OverlayStateDB = class {
527
652
  const tableWrites = this.getTableWrites(table);
528
653
  const existingWrite = tableWrites.get(key);
529
654
  const before = existingWrite ? existingWrite.before : await this.readBase(table, rawKey, ctx);
655
+ const prior = existingWrite ? existingWrite.after : before;
656
+ if (table === "account") OverlayStateDB.assertValidAccountWrite(key, before, prior, null, "delete", ctx);
657
+ const isAcctMigrate = table === "balance" && OverlayStateDB.isAccountMigrateContext(ctx) && (!existingWrite || existingWrite.authorizedAccountMigrate === true);
530
658
  tableWrites.set(key, {
531
659
  op: "delete",
532
660
  before,
533
- after: null
661
+ after: null,
662
+ ...isAcctMigrate ? { authorizedAccountMigrate: true } : {}
534
663
  });
535
664
  }
536
665
  };
@@ -852,9 +981,10 @@ var OverlayStateDB = class {
852
981
  currentVal = await baseTable.get(key, ctx);
853
982
  }
854
983
  } else {
984
+ const baseCtx = OverlayStateDB.withRawAccountContext(table, ctx);
855
985
  const canonKey = canonicalizeStateKey(key);
856
- currentVal = await baseTable.get(canonKey, ctx);
857
- if ((currentVal === null || currentVal === void 0) && canonKey !== key) currentVal = await baseTable.get(key, ctx);
986
+ currentVal = await baseTable.get(canonKey, baseCtx);
987
+ if ((currentVal === null || currentVal === void 0) && canonKey !== key) currentVal = await baseTable.get(key, baseCtx);
858
988
  }
859
989
  if (!(0, lodash_isEqual.default)(currentVal ?? null, expectedVal ?? null)) return false;
860
990
  }
@@ -863,8 +993,26 @@ var OverlayStateDB = class {
863
993
  }
864
994
  async commit(ctx) {
865
995
  const diffs = this.getStateDiff();
866
- for (const diff of diffs) if (diff.table === "balance") {
867
- if (!extractValidatedBalanceDiffIdentity(diff).ok) throw new _ocap_util_lib_error.CustomError("ACCOUNTING_INVARIANT_VIOLATION", `Invalid or mutated balance row identity for key "${diff.key}"`);
996
+ const accountWrites = this.writes.get("account");
997
+ const balanceWrites = this.writes.get("balance");
998
+ for (const diff of diffs) if (diff.table === "account") {
999
+ const effectiveCtx = (accountWrites?.get(diff.key))?.authorizedAccountMigrate ? { txType: "account_migrate" } : ctx;
1000
+ OverlayStateDB.assertValidAccountWrite(diff.key, diff.before, diff.before, diff.after, diff.op, effectiveCtx);
1001
+ } else if (diff.table === "balance") {
1002
+ const identity = extractValidatedBalanceDiffIdentity(diff);
1003
+ if (!identity.ok) throw new _ocap_util_lib_error.CustomError("ACCOUNTING_INVARIANT_VIOLATION", `Invalid or mutated balance row identity for key "${diff.key}"`);
1004
+ const baseOwnerAcct = await this.readBase("account", identity.address, ctx);
1005
+ const curOwnerAcct = await this.getRawAccount(identity.address, ctx);
1006
+ const balanceEntry = balanceWrites?.get(diff.key);
1007
+ if (Array.isArray(baseOwnerAcct?.migratedTo) && baseOwnerAcct.migratedTo.length > 0) throw new _ocap_util_lib_error.CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Cannot mutate balance row "${diff.key}" of pre-existing migrated tombstone account "${identity.address}"`);
1008
+ if (Array.isArray(curOwnerAcct?.migratedTo) && curOwnerAcct.migratedTo.length > 0) {
1009
+ const afterBal = diff.op === "delete" ? {
1010
+ ok: true,
1011
+ value: new _ocap_util.BN(0)
1012
+ } : parseNonNegativeBn(diff.after?.balance);
1013
+ const isZeroed = afterBal.ok && afterBal.value.isZero();
1014
+ if (!(OverlayStateDB.isAccountMigrateContext(ctx) || balanceEntry?.authorizedAccountMigrate === true) || !isZeroed) throw new _ocap_util_lib_error.CustomError("TOMBSTONE_ACCOUNT_VIOLATION", `Cannot leave non-zero or unauthorized balance row "${diff.key}" on migrated tombstone account "${identity.address}"`);
1015
+ }
868
1016
  }
869
1017
  const applyDiffs = async (commitCtx) => {
870
1018
  for (const diff of diffs) {
@@ -1683,8 +1831,9 @@ var TwoPhaseTransferLedger = class {
1683
1831
  if (typeof params.amount !== "string" || !CANONICAL_NON_NEGATIVE_INT_REGEX.test(params.amount)) throw new _ocap_util_lib_error.CustomError("INVALID_AMOUNT", "Pending transfer amount must be a positive base-10 integer string");
1684
1832
  const amt = new _ocap_util.BN(params.amount, 10);
1685
1833
  if (amt.lte(new _ocap_util.BN(0))) throw new _ocap_util_lib_error.CustomError("INVALID_AMOUNT", "Pending transfer amount must be greater than 0");
1686
- const debitAccount = await statedb.account.get(params.debitAddress);
1834
+ const debitAccount = await statedb.account.get(params.debitAddress, { traceMigration: false });
1687
1835
  if (!debitAccount) throw new _ocap_util_lib_error.CustomError("INVALID_SENDER_STATE", `Debit account ${params.debitAddress} not found`);
1836
+ if (Array.isArray(debitAccount.migratedTo) && debitAccount.migratedTo.length > 0 || typeof debitAccount.address === "string" && debitAccount.address && canonicalizeStateKey(debitAccount.address) !== canonicalizeStateKey(params.debitAddress)) throw new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `Debit account ${params.debitAddress} has been migrated`);
1688
1837
  const available = new _ocap_util.BN(debitAccount.tokens?.[params.tokenAddress] || "0");
1689
1838
  if (available.lt(amt)) throw new _ocap_util_lib_error.CustomError("INSUFFICIENT_BALANCE", `Insufficient available balance for ${params.tokenAddress}`);
1690
1839
  const nextAvailable = available.sub(amt).toString(10);
@@ -1718,7 +1867,8 @@ var TwoPhaseTransferLedger = class {
1718
1867
  if (record.status !== "PENDING") throw new _ocap_util_lib_error.CustomError("INVALID_STATE", `Pending transfer ${params.id} is already ${record.status}`);
1719
1868
  if (params.currentHeight > record.timeoutHeight) throw new _ocap_util_lib_error.CustomError("EXPIRED_PENDING_TRANSFER", `Pending transfer ${params.id} has expired`);
1720
1869
  const amt = new _ocap_util.BN(record.amount);
1721
- const debitAccount = await statedb.account.get(record.debitAddress);
1870
+ const debitAccount = await statedb.account.get(record.debitAddress, { traceMigration: false });
1871
+ if (debitAccount && (Array.isArray(debitAccount.migratedTo) && debitAccount.migratedTo.length > 0 || typeof debitAccount.address === "string" && debitAccount.address && canonicalizeStateKey(debitAccount.address) !== canonicalizeStateKey(record.debitAddress))) throw new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `Debit account ${record.debitAddress} has been migrated`);
1722
1872
  const curPending = new _ocap_util.BN(debitAccount?.pendingTokens?.[record.tokenAddress] || "0");
1723
1873
  if (curPending.lt(amt)) throw new _ocap_util_lib_error.CustomError("INSUFFICIENT_PENDING", "Locked pending balance corrupted");
1724
1874
  await statedb.account.update(record.debitAddress, {
@@ -1729,15 +1879,16 @@ var TwoPhaseTransferLedger = class {
1729
1879
  }
1730
1880
  });
1731
1881
  const existingCredit = await statedb.account.get(record.creditAddress);
1882
+ const resolvedCreditAddr = existingCredit && typeof existingCredit.address === "string" && existingCredit.address ? existingCredit.address : record.creditAddress;
1732
1883
  const creditAccount = existingCredit || {
1733
- address: record.creditAddress,
1884
+ address: resolvedCreditAddr,
1734
1885
  tokens: {},
1735
1886
  pendingTokens: {}
1736
1887
  };
1737
1888
  const curCredit = new _ocap_util.BN(creditAccount.tokens?.[record.tokenAddress] || "0");
1738
1889
  await statedb.account.updateOrCreate(existingCredit, {
1739
1890
  ...creditAccount,
1740
- address: record.creditAddress,
1891
+ address: resolvedCreditAddr,
1741
1892
  tokens: {
1742
1893
  ...creditAccount.tokens || {},
1743
1894
  [record.tokenAddress]: curCredit.add(amt).toString(10)
@@ -1751,8 +1902,9 @@ var TwoPhaseTransferLedger = class {
1751
1902
  if (!record) throw new _ocap_util_lib_error.CustomError("NOT_FOUND", `Pending transfer ${params.id} not found`);
1752
1903
  if (record.status !== "PENDING") throw new _ocap_util_lib_error.CustomError("INVALID_STATE", `Pending transfer ${params.id} is already ${record.status}`);
1753
1904
  const amt = new _ocap_util.BN(record.amount, 10);
1754
- const debitAccount = await statedb.account.get(record.debitAddress);
1905
+ const debitAccount = await statedb.account.get(record.debitAddress, { traceMigration: false });
1755
1906
  if (!debitAccount) throw new _ocap_util_lib_error.CustomError("INVALID_SENDER_STATE", `Debit account ${record.debitAddress} not found`);
1907
+ if (Array.isArray(debitAccount.migratedTo) && debitAccount.migratedTo.length > 0 || typeof debitAccount.address === "string" && debitAccount.address && canonicalizeStateKey(debitAccount.address) !== canonicalizeStateKey(record.debitAddress)) throw new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `Debit account ${record.debitAddress} has been migrated`);
1756
1908
  const curPending = new _ocap_util.BN(debitAccount?.pendingTokens?.[record.tokenAddress] || "0", 10);
1757
1909
  if (curPending.lt(amt)) throw new _ocap_util_lib_error.CustomError("INSUFFICIENT_PENDING", "Locked pending balance corrupted");
1758
1910
  const curAvailable = new _ocap_util.BN(debitAccount?.tokens?.[record.tokenAddress] || "0", 10);
@@ -191,7 +191,15 @@ declare class OverlayStateDB {
191
191
  private assertLiveReadBudget;
192
192
  private assertLiveWriteBudget;
193
193
  private normalizeTableKey;
194
+ private static withRawAccountContext;
195
+ private static isAccountMigrateContext;
196
+ private static equalTokenRecords;
197
+ private static isPureCreditAboveTerminal;
198
+ private resolveMigratedCreditTarget;
199
+ private static assertValidAccountWrite;
194
200
  private readBase;
201
+ private getRawAccount;
202
+ private getAccountWithMigration;
195
203
  getBaseSnapshot(table: string, rawKey: unknown, ctx?: unknown): Promise<any>;
196
204
  hasTableWrite(table: string, rawKey: unknown): boolean;
197
205
  private createTableProxy;
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.32.0",
6
+ "version": "1.32.2",
7
7
  "description": "Pipeline runner and common pipelines to process transactions",
8
8
  "type": "module",
9
9
  "main": "./lib/index.cjs",
@@ -49,15 +49,15 @@
49
49
  "elliptic": "6.5.3"
50
50
  },
51
51
  "dependencies": {
52
- "@arcblock/did": "1.32.0",
53
- "@arcblock/did-util": "1.32.0",
54
- "@ocap/client": "1.32.0",
55
- "@ocap/mcrypto": "1.32.0",
56
- "@ocap/message": "1.32.0",
57
- "@ocap/state": "1.32.0",
58
- "@ocap/types": "1.32.0",
59
- "@ocap/util": "1.32.0",
60
- "@ocap/wallet": "1.32.0",
52
+ "@arcblock/did": "1.32.2",
53
+ "@arcblock/did-util": "1.32.2",
54
+ "@ocap/client": "1.32.2",
55
+ "@ocap/mcrypto": "1.32.2",
56
+ "@ocap/message": "1.32.2",
57
+ "@ocap/state": "1.32.2",
58
+ "@ocap/types": "1.32.2",
59
+ "@ocap/util": "1.32.2",
60
+ "@ocap/wallet": "1.32.2",
61
61
  "elliptic": "6.6.1",
62
62
  "debug": "^4.4.3",
63
63
  "lodash": "^4.17.23"