@ocap/tx-pipeline 1.31.1 → 1.31.3

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.
Files changed (105) hide show
  1. package/esm/bridge-release-keys.d.mts +33 -0
  2. package/esm/bridge-release-keys.mjs +81 -0
  3. package/esm/bridge-reserves.d.mts +107 -0
  4. package/esm/bridge-reserves.mjs +242 -0
  5. package/esm/helpers/bridge-withdraw.d.mts +86 -0
  6. package/esm/helpers/bridge-withdraw.mjs +123 -0
  7. package/esm/helpers/replay-guard.d.mts +19 -1
  8. package/esm/helpers/replay-guard.mjs +39 -1
  9. package/esm/index.d.mts +3 -1
  10. package/esm/index.mjs +8 -6
  11. package/esm/legacy-protocol-sunset.d.mts +2 -2
  12. package/esm/legacy-protocol-sunset.mjs +5 -5
  13. package/esm/legacy-rollup-archive.d.mts +67 -0
  14. package/esm/legacy-rollup-archive.mjs +199 -0
  15. package/esm/library.d.mts +4 -4
  16. package/esm/library.mjs +3 -3
  17. package/esm/native-abt-exchange.d.mts +3 -0
  18. package/esm/native-abt-exchange.mjs +93 -46
  19. package/esm/pipes/bridge-release-gate.d.mts +30 -0
  20. package/esm/pipes/bridge-release-gate.mjs +143 -0
  21. package/esm/pipes/bridge-reserve-v2-gate.d.mts +53 -0
  22. package/esm/pipes/bridge-reserve-v2-gate.mjs +264 -0
  23. package/esm/pipes/decode-tx.mjs +29 -4
  24. package/esm/pipes/extract-signer.mjs +1 -1
  25. package/esm/pipes/extract-state.mjs +2 -2
  26. package/esm/pipes/post-execution-invariant-gate.d.mts +19 -2
  27. package/esm/pipes/post-execution-invariant-gate.mjs +121 -6
  28. package/esm/pipes/pre-flight-waf.d.mts +18 -1
  29. package/esm/pipes/pre-flight-waf.mjs +48 -13
  30. package/esm/pipes/update-owner.mjs +1 -1
  31. package/esm/pipes/verify-account-migration.mjs +1 -1
  32. package/esm/pipes/verify-delegation.mjs +49 -25
  33. package/esm/pipes/verify-multisig-v2.mjs +5 -4
  34. package/esm/pipes/verify-multisig.mjs +5 -4
  35. package/esm/pipes/verify-signature.d.mts +7 -1
  36. package/esm/pipes/verify-signature.mjs +119 -16
  37. package/esm/pipes/verify-signer.mjs +2 -2
  38. package/esm/pipes/verify-token-access.mjs +1 -1
  39. package/esm/pipes/verify-token-balance.mjs +1 -1
  40. package/esm/pipes/verify-tx-input.mjs +1 -1
  41. package/esm/pipes/verify-tx-size.mjs +1 -1
  42. package/esm/pipes/verify-tx.mjs +12 -5
  43. package/esm/super-suites-foundation.mjs +6 -6
  44. package/esm/transaction-block.d.mts +6 -2
  45. package/esm/transaction-block.mjs +282 -40
  46. package/esm/uniswap-router.d.mts +247 -1
  47. package/esm/uniswap-router.mjs +573 -2
  48. package/lib/bridge-release-keys.cjs +88 -0
  49. package/lib/bridge-release-keys.d.cts +33 -0
  50. package/lib/bridge-reserves.cjs +257 -0
  51. package/lib/bridge-reserves.d.cts +107 -0
  52. package/lib/helpers/bridge-withdraw.cjs +136 -0
  53. package/lib/helpers/bridge-withdraw.d.cts +86 -0
  54. package/lib/helpers/replay-guard.cjs +39 -0
  55. package/lib/helpers/replay-guard.d.cts +20 -2
  56. package/lib/index.cjs +25 -5
  57. package/lib/index.d.cts +3 -1
  58. package/lib/legacy-protocol-sunset.cjs +7 -7
  59. package/lib/legacy-protocol-sunset.d.cts +2 -2
  60. package/lib/legacy-rollup-archive.cjs +208 -0
  61. package/lib/legacy-rollup-archive.d.cts +67 -0
  62. package/lib/library.cjs +14 -68
  63. package/lib/library.d.cts +4 -4
  64. package/lib/native-abt-exchange.cjs +93 -46
  65. package/lib/native-abt-exchange.d.cts +3 -0
  66. package/lib/pipes/bridge-release-gate.cjs +145 -0
  67. package/lib/pipes/bridge-release-gate.d.cts +30 -0
  68. package/lib/pipes/bridge-reserve-v2-gate.cjs +273 -0
  69. package/lib/pipes/bridge-reserve-v2-gate.d.cts +53 -0
  70. package/lib/pipes/decode-itx.d.cts +1 -1
  71. package/lib/pipes/decode-tx.cjs +28 -3
  72. package/lib/pipes/decode-tx.d.cts +1 -1
  73. package/lib/pipes/extract-signer.cjs +1 -1
  74. package/lib/pipes/extract-state.cjs +3 -3
  75. package/lib/pipes/post-execution-invariant-gate.cjs +121 -4
  76. package/lib/pipes/post-execution-invariant-gate.d.cts +19 -2
  77. package/lib/pipes/pre-flight-waf.cjs +51 -13
  78. package/lib/pipes/pre-flight-waf.d.cts +19 -2
  79. package/lib/pipes/update-owner.cjs +1 -1
  80. package/lib/pipes/update-owner.d.cts +1 -1
  81. package/lib/pipes/verify-account-migration.cjs +1 -1
  82. package/lib/pipes/verify-delegation.cjs +50 -26
  83. package/lib/pipes/verify-multisig-v2.cjs +5 -4
  84. package/lib/pipes/verify-multisig.cjs +5 -4
  85. package/lib/pipes/verify-service-fee.d.cts +1 -1
  86. package/lib/pipes/verify-signature.cjs +118 -14
  87. package/lib/pipes/verify-signature.d.cts +8 -2
  88. package/lib/pipes/verify-signer.cjs +2 -2
  89. package/lib/pipes/verify-token-access.cjs +1 -1
  90. package/lib/pipes/verify-token-balance.cjs +1 -1
  91. package/lib/pipes/verify-tx-input.cjs +1 -1
  92. package/lib/pipes/verify-tx-size.cjs +1 -1
  93. package/lib/pipes/verify-tx-size.d.cts +1 -1
  94. package/lib/pipes/verify-tx.cjs +11 -5
  95. package/lib/pipes/verify-tx.d.cts +1 -1
  96. package/lib/super-suites-foundation.cjs +6 -6
  97. package/lib/transaction-block.cjs +282 -40
  98. package/lib/transaction-block.d.cts +6 -2
  99. package/lib/uniswap-router.cjs +576 -1
  100. package/lib/uniswap-router.d.cts +247 -1
  101. package/package.json +10 -10
  102. package/esm/evm-simplified-bridge.d.mts +0 -1370
  103. package/esm/evm-simplified-bridge.mjs +0 -3875
  104. package/lib/evm-simplified-bridge.cjs +0 -3943
  105. package/lib/evm-simplified-bridge.d.cts +0 -1370
@@ -4,12 +4,12 @@ require('./uniswap-router.cjs');
4
4
  let _ocap_mcrypto = require("@ocap/mcrypto");
5
5
  let _ocap_util = require("@ocap/util");
6
6
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
7
+ let _arcblock_did = require("@arcblock/did");
8
+ let _arcblock_did_util = require("@arcblock/did-util");
7
9
  let lodash_cloneDeep = require("lodash/cloneDeep");
8
10
  lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
9
- let _arcblock_did = require("@arcblock/did");
10
11
  let lodash_isEqual = require("lodash/isEqual");
11
12
  lodash_isEqual = require_rolldown_runtime.__toESM(lodash_isEqual);
12
- let _arcblock_did_util = require("@arcblock/did-util");
13
13
  let _arcblock_did_lib_type = require("@arcblock/did/lib/type");
14
14
 
15
15
  //#region src/transaction-block.ts
@@ -51,6 +51,7 @@ const RESERVED_OVERLAY_MEMBERS = new Set([
51
51
  ]);
52
52
  const DEFAULT_TABLES = [
53
53
  "account",
54
+ "balance",
54
55
  "asset",
55
56
  "token",
56
57
  "factory",
@@ -294,10 +295,53 @@ function scheduleParallelBatches(items, getFootprint = (item) => extractStateFoo
294
295
  deferredByHotKeyQuota
295
296
  };
296
297
  }
298
+ function extractValidatedBalanceDiffIdentity(diff) {
299
+ const rawBeforeAddr = diff.before && typeof diff.before.address === "string" ? diff.before.address : "";
300
+ const beforeAddr = rawBeforeAddr.trim() ? canonicalizeStateKey(rawBeforeAddr) : "";
301
+ const rawAfterAddr = diff.op !== "delete" && diff.after && typeof diff.after.address === "string" ? diff.after.address : "";
302
+ const afterAddr = rawAfterAddr.trim() ? canonicalizeStateKey(rawAfterAddr) : "";
303
+ const rawBeforeTok = diff.before && typeof diff.before.tokenAddress === "string" ? diff.before.tokenAddress : "";
304
+ const beforeTok = rawBeforeTok.trim() ? canonicalizeStateKey(rawBeforeTok) : "";
305
+ const rawAfterTok = diff.op !== "delete" && diff.after && typeof diff.after.tokenAddress === "string" ? diff.after.tokenAddress : "";
306
+ const afterTok = rawAfterTok.trim() ? canonicalizeStateKey(rawAfterTok) : "";
307
+ if (diff.before !== null && diff.before !== void 0 && (!beforeAddr || !beforeTok || rawBeforeAddr !== beforeAddr || rawBeforeTok !== beforeTok)) return {
308
+ ok: false,
309
+ reason: "INVALID_BALANCE_ROW_IDENTITY",
310
+ tokenKey: afterTok || beforeTok || diff.key
311
+ };
312
+ if (diff.op !== "delete" && (!afterAddr || !afterTok || rawAfterAddr !== afterAddr || rawAfterTok !== afterTok)) return {
313
+ ok: false,
314
+ reason: "INVALID_BALANCE_ROW_IDENTITY",
315
+ tokenKey: afterTok || beforeTok || diff.key
316
+ };
317
+ if (beforeAddr && afterAddr && beforeAddr !== afterAddr) return {
318
+ ok: false,
319
+ reason: "INVALID_BALANCE_ROW_IDENTITY",
320
+ tokenKey: afterTok || beforeTok || diff.key
321
+ };
322
+ if (beforeTok && afterTok && beforeTok !== afterTok) return {
323
+ ok: false,
324
+ reason: "INVALID_BALANCE_ROW_IDENTITY",
325
+ tokenKey: afterTok || beforeTok || diff.key
326
+ };
327
+ const address = afterAddr || beforeAddr;
328
+ const tokenAddress = afterTok || beforeTok;
329
+ if (!address || !tokenAddress || FORBIDDEN_PATH_SEGMENTS.has(address) || FORBIDDEN_PATH_SEGMENTS.has(tokenAddress) || diff.key !== `${address}-${tokenAddress}`) return {
330
+ ok: false,
331
+ reason: "INVALID_BALANCE_ROW_IDENTITY",
332
+ tokenKey: tokenAddress || diff.key
333
+ };
334
+ return {
335
+ ok: true,
336
+ address,
337
+ tokenAddress
338
+ };
339
+ }
297
340
  var OverlayStateDB = class {
298
341
  constructor(baseStateDB, tables = DEFAULT_TABLES) {
299
342
  this.writes = /* @__PURE__ */ new Map();
300
343
  this.reads = /* @__PURE__ */ new Map();
344
+ this.balanceReadsByAddress = /* @__PURE__ */ new Map();
301
345
  this.runtimeIoBudget = null;
302
346
  this.savepoints = [];
303
347
  this.base = baseStateDB;
@@ -331,6 +375,7 @@ var OverlayStateDB = class {
331
375
  assertLiveReadBudget(table, key) {
332
376
  if (!this.runtimeIoBudget) return;
333
377
  if (this.reads.get(table)?.has(key)) return;
378
+ if (table === "balance" && this.balanceReadsByAddress.has(key)) return;
334
379
  const currentTouched = new Set([
335
380
  ...this.runtimeIoBudget.staticReadSet || [],
336
381
  ...this.getReadKeys(),
@@ -359,40 +404,67 @@ var OverlayStateDB = class {
359
404
  const effectiveCount = Math.max(tableCount, bareCount);
360
405
  if (effectiveCount > this.runtimeIoBudget.maxWriteKeys) throw new _ocap_util_lib_error.CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock runtime write key count (${effectiveCount}) exceeds maxWriteKeys (${this.runtimeIoBudget.maxWriteKeys})`);
361
406
  }
362
- async readBase(table, rawKey, ctx) {
363
- assertSafeKey(rawKey, "key");
407
+ normalizeTableKey(table, rawKey, fieldName = "key") {
408
+ if (table === "balance" && rawKey && typeof rawKey === "object" && !Array.isArray(rawKey) && typeof rawKey.address === "string" && typeof rawKey.tokenAddress === "string") {
409
+ const rawAddr = rawKey.address;
410
+ const rawTok = rawKey.tokenAddress;
411
+ assertSafeKey(rawAddr, `${fieldName}.address`);
412
+ assertSafeKey(rawTok, `${fieldName}.tokenAddress`);
413
+ const address = canonicalizeStateKey(rawAddr);
414
+ const tokenAddress = canonicalizeStateKey(rawTok);
415
+ assertSafeKey(address, `${fieldName}.address`);
416
+ assertSafeKey(tokenAddress, `${fieldName}.tokenAddress`);
417
+ return {
418
+ key: `${address}-${tokenAddress}`,
419
+ baseQueryKey: {
420
+ address,
421
+ tokenAddress
422
+ }
423
+ };
424
+ }
425
+ assertSafeKey(rawKey, fieldName);
364
426
  const key = canonicalizeStateKey(rawKey);
365
- assertSafeKey(key, "key");
427
+ assertSafeKey(key, fieldName);
428
+ return {
429
+ key,
430
+ baseQueryKey: key
431
+ };
432
+ }
433
+ async readBase(table, rawKey, ctx) {
434
+ const { key, baseQueryKey } = this.normalizeTableKey(table, rawKey, "key");
366
435
  const readsMap = this.getTableReads(table);
367
436
  if (readsMap.has(key)) return (0, lodash_cloneDeep.default)(readsMap.get(key));
368
437
  this.assertLiveReadBudget(table, key);
369
438
  const baseTable = this.base?.[table];
370
- let val = typeof baseTable?.get === "function" ? await baseTable.get(key, ctx) : null;
371
- if ((val === null || val === void 0) && rawKey !== key && typeof baseTable?.get === "function") val = await baseTable.get(rawKey, ctx);
439
+ let val = null;
440
+ if (typeof baseTable?.get === "function") {
441
+ if (table === "balance" && baseQueryKey !== key) try {
442
+ val = await baseTable.get(baseQueryKey, ctx);
443
+ } catch {
444
+ val = await baseTable.get(key, ctx);
445
+ }
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);
448
+ }
372
449
  readsMap.set(key, (0, lodash_cloneDeep.default)(val ?? null));
373
450
  return (0, lodash_cloneDeep.default)(val ?? null);
374
451
  }
375
452
  async getBaseSnapshot(table, rawKey, ctx) {
376
453
  assertSafeKey(table, "table");
377
- assertSafeKey(rawKey, "key");
378
454
  return this.readBase(table, rawKey, ctx);
379
455
  }
380
456
  hasTableWrite(table, rawKey) {
381
457
  assertSafeKey(table, "table");
382
- assertSafeKey(rawKey, "key");
383
- const key = canonicalizeStateKey(rawKey);
384
- assertSafeKey(key, "key");
458
+ const { key } = this.normalizeTableKey(table, rawKey, "key");
385
459
  const tableWrites = this.writes.get(table);
386
460
  if (!tableWrites?.has(key)) return false;
387
461
  const entry = tableWrites.get(key);
388
462
  return !(0, lodash_isEqual.default)(entry.before, entry.after);
389
463
  }
390
464
  createTableProxy(table) {
391
- return {
465
+ const proxy = {
392
466
  get: async (rawKey, ctx) => {
393
- assertSafeKey(rawKey, "key");
394
- const key = canonicalizeStateKey(rawKey);
395
- assertSafeKey(key, "key");
467
+ const { key } = this.normalizeTableKey(table, rawKey, "key");
396
468
  const tableWrites = this.writes.get(table);
397
469
  if (tableWrites?.has(key)) {
398
470
  const entry = tableWrites.get(key);
@@ -401,14 +473,15 @@ var OverlayStateDB = class {
401
473
  return this.readBase(table, rawKey, ctx);
402
474
  },
403
475
  create: async (rawKey, state, ctx) => {
404
- assertSafeKey(rawKey, "key");
405
- const key = canonicalizeStateKey(rawKey);
406
- assertSafeKey(key, "key");
476
+ const { key, baseQueryKey } = this.normalizeTableKey(table, rawKey, "key");
407
477
  this.assertLiveWriteBudget(table, key);
408
478
  const tableWrites = this.getTableWrites(table);
409
479
  const existingWrite = tableWrites.get(key);
410
480
  const before = existingWrite ? existingWrite.before : await this.readBase(table, rawKey, ctx);
411
- const cloned = (0, lodash_cloneDeep.default)(state);
481
+ const cloned = typeof baseQueryKey === "object" && state && typeof state === "object" ? (0, lodash_cloneDeep.default)({
482
+ ...baseQueryKey,
483
+ ...state
484
+ }) : (0, lodash_cloneDeep.default)(state);
412
485
  tableWrites.set(key, {
413
486
  op: before ? "update" : "create",
414
487
  before,
@@ -417,17 +490,20 @@ var OverlayStateDB = class {
417
490
  return (0, lodash_cloneDeep.default)(cloned);
418
491
  },
419
492
  update: async (rawKey, updates, ctx) => {
420
- assertSafeKey(rawKey, "key");
421
- const key = canonicalizeStateKey(rawKey);
422
- assertSafeKey(key, "key");
493
+ const { key, baseQueryKey } = this.normalizeTableKey(table, rawKey, "key");
423
494
  this.assertLiveWriteBudget(table, key);
424
495
  const tableWrites = this.getTableWrites(table);
425
496
  const existingWrite = tableWrites.get(key);
426
497
  const before = existingWrite ? existingWrite.before : await this.readBase(table, rawKey, ctx);
427
498
  const current = existingWrite ? existingWrite.after : before;
499
+ const baseObj = typeof baseQueryKey === "object" ? baseQueryKey : {};
428
500
  const merged = current && typeof current === "object" && updates && typeof updates === "object" ? (0, lodash_cloneDeep.default)({
501
+ ...baseObj,
429
502
  ...current,
430
503
  ...updates
504
+ }) : updates && typeof updates === "object" ? (0, lodash_cloneDeep.default)({
505
+ ...baseObj,
506
+ ...updates
431
507
  }) : (0, lodash_cloneDeep.default)(updates);
432
508
  tableWrites.set(key, {
433
509
  op: before ? "update" : "create",
@@ -437,17 +513,16 @@ var OverlayStateDB = class {
437
513
  return (0, lodash_cloneDeep.default)(merged);
438
514
  },
439
515
  updateOrCreate: async (existing, updates, ctx) => {
440
- const rawKey = updates?.address || existing?.address;
441
- assertSafeKey(rawKey, "address");
442
- const key = canonicalizeStateKey(rawKey);
443
- assertSafeKey(key, "address");
444
- if (await this[table].get(key, ctx)) return this[table].update(key, updates, ctx);
445
- return this[table].create(key, 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,
518
+ tokenAddress: updates?.tokenAddress || existing?.tokenAddress
519
+ } : updates?.address || existing?.address;
520
+ const { baseQueryKey } = this.normalizeTableKey(table, rawKey, "address");
521
+ if (await this[table].get(baseQueryKey, ctx)) return this[table].update(baseQueryKey, updates, ctx);
522
+ return this[table].create(baseQueryKey, updates, ctx);
446
523
  },
447
524
  delete: async (rawKey, ctx) => {
448
- assertSafeKey(rawKey, "key");
449
- const key = canonicalizeStateKey(rawKey);
450
- assertSafeKey(key, "key");
525
+ const { key } = this.normalizeTableKey(table, rawKey, "key");
451
526
  this.assertLiveWriteBudget(table, key);
452
527
  const tableWrites = this.getTableWrites(table);
453
528
  const existingWrite = tableWrites.get(key);
@@ -459,6 +534,63 @@ var OverlayStateDB = class {
459
534
  });
460
535
  }
461
536
  };
537
+ if (table === "balance") {
538
+ proxy.getBalance = async (rawAddress, ctx) => {
539
+ assertSafeKey(rawAddress, "address");
540
+ const address = canonicalizeStateKey(rawAddress);
541
+ assertSafeKey(address, "address");
542
+ let baseBalances = {};
543
+ if (this.balanceReadsByAddress.has(address)) baseBalances = (0, lodash_cloneDeep.default)(this.balanceReadsByAddress.get(address)) || {};
544
+ else {
545
+ this.assertLiveReadBudget("balance", address);
546
+ const baseBalanceTable = this.base?.balance;
547
+ if (typeof baseBalanceTable?.getBalance === "function") baseBalances = await baseBalanceTable.getBalance(address, ctx) || {};
548
+ this.balanceReadsByAddress.set(address, (0, lodash_cloneDeep.default)(baseBalances));
549
+ }
550
+ const merged = { ...baseBalances };
551
+ const tableWrites = this.writes.get("balance");
552
+ if (tableWrites) {
553
+ const prefix = `${address}-`;
554
+ for (const [k, entry] of tableWrites.entries()) {
555
+ const entryAddr = entry.after?.address ?? entry.before?.address;
556
+ const entryTok = entry.after?.tokenAddress ?? entry.before?.tokenAddress ?? (k.startsWith(prefix) ? k.slice(prefix.length) : void 0);
557
+ if ((entryAddr === address || k.startsWith(prefix)) && typeof entryTok === "string" && entryTok) if (entry.op === "delete" || entry.after === null || entry.after?.balance === void 0) delete merged[entryTok];
558
+ else merged[entryTok] = String(entry.after.balance);
559
+ }
560
+ }
561
+ return merged;
562
+ };
563
+ proxy.updateBalance = async (params, ctx) => {
564
+ assertSafeKey(params?.address, "address");
565
+ const address = canonicalizeStateKey(params.address);
566
+ assertSafeKey(address, "address");
567
+ const nextTokens = params?.tokens && typeof params.tokens === "object" ? params.tokens : {};
568
+ const currentBalances = await proxy.getBalance(address, ctx);
569
+ const allTokens = new Set([...Object.keys(currentBalances), ...Object.keys(nextTokens)]);
570
+ for (const rawTok of allTokens) {
571
+ if (FORBIDDEN_PATH_SEGMENTS.has(rawTok)) continue;
572
+ assertSafeKey(rawTok, "tokenAddress");
573
+ const tokenAddress = canonicalizeStateKey(rawTok);
574
+ assertSafeKey(tokenAddress, "tokenAddress");
575
+ const hasNext = Object.prototype.hasOwnProperty.call(nextTokens, rawTok) || Object.prototype.hasOwnProperty.call(nextTokens, tokenAddress);
576
+ const nextVal = Object.prototype.hasOwnProperty.call(nextTokens, rawTok) ? nextTokens[rawTok] : nextTokens[tokenAddress];
577
+ const prevVal = currentBalances[tokenAddress] ?? currentBalances[rawTok];
578
+ const compKey = {
579
+ address,
580
+ tokenAddress
581
+ };
582
+ if (!hasNext && prevVal !== void 0) await proxy.delete(compKey, ctx);
583
+ else if (hasNext && String(nextVal) !== String(prevVal ?? "0")) await proxy.update(compKey, {
584
+ address,
585
+ tokenAddress,
586
+ balance: String(nextVal),
587
+ ...params.context !== void 0 ? { context: params.context } : {}
588
+ }, ctx);
589
+ }
590
+ return (0, lodash_cloneDeep.default)(nextTokens);
591
+ };
592
+ }
593
+ return proxy;
462
594
  }
463
595
  createSavepoint() {
464
596
  const clonedWrites = /* @__PURE__ */ new Map();
@@ -473,9 +605,12 @@ var OverlayStateDB = class {
473
605
  for (const [k, v] of map.entries()) inner.set(k, (0, lodash_cloneDeep.default)(v));
474
606
  clonedReads.set(table, inner);
475
607
  }
608
+ const clonedBalanceReads = /* @__PURE__ */ new Map();
609
+ for (const [k, v] of this.balanceReadsByAddress.entries()) clonedBalanceReads.set(k, (0, lodash_cloneDeep.default)(v));
476
610
  this.savepoints.push({
477
611
  writes: clonedWrites,
478
- reads: clonedReads
612
+ reads: clonedReads,
613
+ balanceReadsByAddress: clonedBalanceReads
479
614
  });
480
615
  return this.savepoints.length - 1;
481
616
  }
@@ -485,6 +620,7 @@ var OverlayStateDB = class {
485
620
  this.savepoints.length = savepointId;
486
621
  this.writes = restored.writes;
487
622
  this.reads = restored.reads;
623
+ this.balanceReadsByAddress = restored.balanceReadsByAddress;
488
624
  }
489
625
  releaseSavepoint(savepointId) {
490
626
  if (savepointId < 0 || savepointId >= this.savepoints.length) throw new _ocap_util_lib_error.CustomError("INVALID_SAVEPOINT", `Invalid savepoint id ${savepointId}`);
@@ -493,11 +629,13 @@ var OverlayStateDB = class {
493
629
  discard() {
494
630
  this.writes.clear();
495
631
  this.reads.clear();
632
+ this.balanceReadsByAddress.clear();
496
633
  this.savepoints.length = 0;
497
634
  }
498
635
  getTouchedTableReadKeys() {
499
636
  const keys = /* @__PURE__ */ new Set();
500
637
  for (const [table, map] of this.reads.entries()) for (const k of map.keys()) keys.add(`${table}:${k}`);
638
+ for (const addr of this.balanceReadsByAddress.keys()) keys.add(`balance:${addr}`);
501
639
  for (const [table, map] of this.writes.entries()) for (const k of map.keys()) keys.add(`${table}:${k}`);
502
640
  return Array.from(keys).sort();
503
641
  }
@@ -509,6 +647,7 @@ var OverlayStateDB = class {
509
647
  getReadKeys() {
510
648
  const keys = /* @__PURE__ */ new Set();
511
649
  for (const map of this.reads.values()) for (const k of map.keys()) keys.add(k);
650
+ for (const addr of this.balanceReadsByAddress.keys()) keys.add(addr);
512
651
  for (const map of this.writes.values()) for (const k of map.keys()) keys.add(k);
513
652
  return Array.from(keys).sort();
514
653
  }
@@ -546,7 +685,9 @@ var OverlayStateDB = class {
546
685
  const cur = map.get(tokenAddr) || new _ocap_util.BN(0);
547
686
  map.set(tokenAddr, cur.add(delta));
548
687
  };
549
- for (const diff of this.getStateDiff()) if (diff.table === "account" || diff.table === "stake") {
688
+ const stateDiffs = this.getStateDiff();
689
+ const accountTokenLiquidDeltas = /* @__PURE__ */ new Map();
690
+ for (const diff of stateDiffs) if (diff.table === "account" || diff.table === "stake") {
550
691
  const beforeTokens = diff.before?.tokens || {};
551
692
  const afterTokens = diff.after?.tokens || {};
552
693
  const beforePending = diff.before?.pendingTokens || {};
@@ -574,6 +715,7 @@ var OverlayStateDB = class {
574
715
  netUnbackedDeltas[tAddr] = "INVALID_NEGATIVE_OR_MALFORMED_BALANCE";
575
716
  continue;
576
717
  }
718
+ if (diff.table === "account" && (Object.prototype.hasOwnProperty.call(beforeTokens, tAddr) || Object.prototype.hasOwnProperty.call(afterTokens, tAddr))) accountTokenLiquidDeltas.set(`${diff.key}:${tAddr}`, aTok.value.sub(bTok.value));
577
719
  const bTotal = bTok.value.add(bPend.value).add(bRev.value);
578
720
  addDelta(balanceDeltas, tAddr, aTok.value.add(aPend.value).add(aRev.value).sub(bTotal));
579
721
  }
@@ -619,6 +761,35 @@ var OverlayStateDB = class {
619
761
  netUnbackedDeltas[tokenAddr] = "INVALID_TOKEN_SUPPLY";
620
762
  } else addDelta(tokenSupplyDeltas, tokenAddr, aSup.value.sub(bSup.value));
621
763
  }
764
+ for (const diff of stateDiffs) {
765
+ if (diff.table !== "balance") continue;
766
+ const identity = extractValidatedBalanceDiffIdentity(diff);
767
+ if (!identity.ok) {
768
+ valid = false;
769
+ netUnbackedDeltas[identity.tokenKey] = identity.reason;
770
+ continue;
771
+ }
772
+ const { address: addr, tokenAddress: tAddr } = identity;
773
+ const bBal = parseNonNegativeBn(diff.before?.balance);
774
+ const aBal = parseNonNegativeBn(diff.after?.balance);
775
+ if (!bBal.ok || !aBal.ok) {
776
+ valid = false;
777
+ netUnbackedDeltas[tAddr] = "INVALID_NEGATIVE_OR_MALFORMED_BALANCE";
778
+ continue;
779
+ }
780
+ const balDelta = aBal.value.sub(bBal.value);
781
+ const pairKey = `${addr}:${tAddr}`;
782
+ if (accountTokenLiquidDeltas.has(pairKey)) {
783
+ const acctDelta = accountTokenLiquidDeltas.get(pairKey);
784
+ if (!acctDelta.eq(balDelta)) {
785
+ valid = false;
786
+ netUnbackedDeltas[tAddr] = `ACCOUNT_BALANCE_MISMATCH:${acctDelta.toString(10)}!=${balDelta.toString(10)}`;
787
+ continue;
788
+ }
789
+ continue;
790
+ }
791
+ addDelta(balanceDeltas, tAddr, balDelta);
792
+ }
622
793
  const allTokens = new Set([
623
794
  ...balanceDeltas.keys(),
624
795
  ...tokenSupplyDeltas.keys(),
@@ -657,13 +828,34 @@ var OverlayStateDB = class {
657
828
  * (Optimistic Concurrency Control check for 2PC Commit).
658
829
  */
659
830
  async verifyBaseUnchanged(ctx) {
831
+ if (this.balanceReadsByAddress.size > 0) {
832
+ const baseBalanceTable = this.base?.balance;
833
+ if (typeof baseBalanceTable?.getBalance === "function") {
834
+ for (const [addr, expectedBalances] of this.balanceReadsByAddress.entries()) if (!(0, lodash_isEqual.default)(await baseBalanceTable.getBalance(addr, ctx) || {}, expectedBalances ?? {})) return false;
835
+ }
836
+ }
660
837
  for (const [table, readsMap] of this.reads.entries()) {
661
838
  const baseTable = this.base?.[table];
662
- if (typeof baseTable?.get !== "function") continue;
839
+ if (!baseTable) continue;
663
840
  for (const [key, expectedVal] of readsMap.entries()) {
664
- const canonKey = canonicalizeStateKey(key);
665
- let currentVal = await baseTable.get(canonKey, ctx);
666
- if ((currentVal === null || currentVal === void 0) && canonKey !== key) currentVal = await baseTable.get(key, ctx);
841
+ if (typeof baseTable.get !== "function") continue;
842
+ let currentVal = null;
843
+ if (table === "balance") {
844
+ const splitIdx = key.indexOf("-");
845
+ const compKey = splitIdx > 0 ? {
846
+ address: key.slice(0, splitIdx),
847
+ tokenAddress: key.slice(splitIdx + 1)
848
+ } : key;
849
+ try {
850
+ currentVal = await baseTable.get(compKey, ctx);
851
+ } catch {
852
+ currentVal = await baseTable.get(key, ctx);
853
+ }
854
+ } else {
855
+ 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);
858
+ }
667
859
  if (!(0, lodash_isEqual.default)(currentVal ?? null, expectedVal ?? null)) return false;
668
860
  }
669
861
  }
@@ -671,17 +863,46 @@ var OverlayStateDB = class {
671
863
  }
672
864
  async commit(ctx) {
673
865
  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}"`);
868
+ }
674
869
  const applyDiffs = async (commitCtx) => {
675
870
  for (const diff of diffs) {
676
871
  const baseTable = this.base?.[diff.table];
677
872
  if (!baseTable) continue;
678
- if (diff.op === "delete") if (typeof baseTable.delete === "function") await baseTable.delete(diff.key, commitCtx);
873
+ let isBalanceComposite = false;
874
+ let targetKey = diff.key;
875
+ if (diff.table === "balance") {
876
+ const identity = extractValidatedBalanceDiffIdentity(diff);
877
+ if (!identity.ok) throw new _ocap_util_lib_error.CustomError("ACCOUNTING_INVARIANT_VIOLATION", `Invalid or mutated balance row identity for key "${diff.key}"`);
878
+ isBalanceComposite = true;
879
+ targetKey = {
880
+ address: identity.address,
881
+ tokenAddress: identity.tokenAddress
882
+ };
883
+ }
884
+ if (diff.op === "delete") if (typeof baseTable.delete === "function") if (isBalanceComposite) try {
885
+ await baseTable.delete(targetKey, commitCtx);
886
+ } catch {
887
+ await baseTable.delete(diff.key, commitCtx);
888
+ }
889
+ else await baseTable.delete(diff.key, commitCtx);
679
890
  else throw new _ocap_util_lib_error.CustomError("UNSUPPORTED_STATE_OPERATION", `Table "${diff.table}" does not support delete operation for key "${diff.key}"`);
680
891
  else if (diff.op === "create") {
681
- if (typeof baseTable.create === "function") await baseTable.create(diff.key, (0, lodash_cloneDeep.default)(diff.after), commitCtx);
892
+ if (typeof baseTable.create === "function") if (isBalanceComposite) try {
893
+ await baseTable.create(targetKey, (0, lodash_cloneDeep.default)(diff.after), commitCtx);
894
+ } catch {
895
+ await baseTable.create(diff.key, (0, lodash_cloneDeep.default)(diff.after), commitCtx);
896
+ }
897
+ else await baseTable.create(diff.key, (0, lodash_cloneDeep.default)(diff.after), commitCtx);
682
898
  else if (typeof baseTable.updateOrCreate === "function") await baseTable.updateOrCreate(null, (0, lodash_cloneDeep.default)(diff.after), commitCtx);
683
899
  } else if (diff.op === "update") {
684
- if (typeof baseTable.update === "function") await baseTable.update(diff.key, (0, lodash_cloneDeep.default)(diff.after), commitCtx);
900
+ if (typeof baseTable.update === "function") if (isBalanceComposite) try {
901
+ await baseTable.update(targetKey, (0, lodash_cloneDeep.default)(diff.after), commitCtx);
902
+ } catch {
903
+ await baseTable.update(diff.key, (0, lodash_cloneDeep.default)(diff.after), commitCtx);
904
+ }
905
+ else await baseTable.update(diff.key, (0, lodash_cloneDeep.default)(diff.after), commitCtx);
685
906
  else if (typeof baseTable.updateOrCreate === "function") await baseTable.updateOrCreate((0, lodash_cloneDeep.default)(diff.before), (0, lodash_cloneDeep.default)(diff.after), commitCtx);
686
907
  }
687
908
  }
@@ -886,6 +1107,7 @@ function computeAccountAndAssetNetEffects(stateDiff) {
886
1107
  const cur = tokenMap.get(tokenAddr) || new _ocap_util.BN(0);
887
1108
  tokenMap.set(tokenAddr, cur.add(delta));
888
1109
  };
1110
+ const accountTokenLiquidDeltas = /* @__PURE__ */ new Map();
889
1111
  for (const diff of stateDiff) if (diff.table === "account") {
890
1112
  const beforeTokens = diff.before?.tokens || {};
891
1113
  const afterTokens = diff.after?.tokens || {};
@@ -905,6 +1127,7 @@ function computeAccountAndAssetNetEffects(stateDiff) {
905
1127
  const aPend = parseNonNegativeBn(afterPending[tAddr]);
906
1128
  if (!bTok.ok || !aTok.ok || !bPend.ok || !aPend.ok) throw new _ocap_util_lib_error.CustomError("ACCOUNTING_INVARIANT_VIOLATION", `Malformed or negative token balance in account[${diff.key}][${tAddr}]`);
907
1129
  const liquidDelta = aTok.value.sub(bTok.value);
1130
+ if (Object.prototype.hasOwnProperty.call(beforeTokens, tAddr) || Object.prototype.hasOwnProperty.call(afterTokens, tAddr)) accountTokenLiquidDeltas.set(`${diff.key}:${tAddr}`, liquidDelta);
908
1131
  const totalDelta = aTok.value.add(aPend.value).sub(bTok.value.add(bPend.value));
909
1132
  const effectiveDelta = liquidDelta.lt(totalDelta) ? liquidDelta : totalDelta;
910
1133
  if (!effectiveDelta.isZero()) addAccountTokenDelta(diff.key, tAddr, effectiveDelta);
@@ -923,6 +1146,23 @@ function computeAccountAndAssetNetEffects(stateDiff) {
923
1146
  incomingAssetsByOwner.set(afterOwner, set);
924
1147
  }
925
1148
  }
1149
+ for (const diff of stateDiff) {
1150
+ if (diff.table !== "balance") continue;
1151
+ const identity = extractValidatedBalanceDiffIdentity(diff);
1152
+ if (!identity.ok) throw new _ocap_util_lib_error.CustomError("ACCOUNTING_INVARIANT_VIOLATION", `Invalid or mutated balance row identity in balance[${diff.key}]`);
1153
+ const { address: addr, tokenAddress: tAddr } = identity;
1154
+ const bBal = parseNonNegativeBn(diff.before?.balance);
1155
+ const aBal = parseNonNegativeBn(diff.after?.balance);
1156
+ if (!bBal.ok || !aBal.ok) throw new _ocap_util_lib_error.CustomError("ACCOUNTING_INVARIANT_VIOLATION", `Malformed or negative token balance in balance[${addr}][${tAddr}]`);
1157
+ const delta = aBal.value.sub(bBal.value);
1158
+ const pairKey = `${addr}:${tAddr}`;
1159
+ if (accountTokenLiquidDeltas.has(pairKey)) {
1160
+ const acctDelta = accountTokenLiquidDeltas.get(pairKey);
1161
+ if (!acctDelta.eq(delta)) throw new _ocap_util_lib_error.CustomError("ACCOUNTING_INVARIANT_VIOLATION", `Account ${addr} token ${tAddr} delta mismatch between account (${acctDelta.toString(10)}) and balance (${delta.toString(10)}) tables`);
1162
+ continue;
1163
+ }
1164
+ if (!delta.isZero()) addAccountTokenDelta(addr, tAddr, delta);
1165
+ }
926
1166
  return {
927
1167
  accountTokenNetDeltas,
928
1168
  outgoingAssetsByOwner,
@@ -966,10 +1206,12 @@ async function verifyTransactionBlockPostConditions(block, stateDiff, overlay) {
966
1206
  }
967
1207
  }
968
1208
  }
1209
+ if (pc.signer !== void 0) assertSafeKey(pc.signer, "postConditions.signer");
969
1210
  if (strictZeroUnlisted) {
970
1211
  const protectedAccounts = new Set([
971
1212
  block.from,
972
1213
  ...block.delegator ? [block.delegator] : [],
1214
+ ...typeof pc.signer === "string" && pc.signer ? [pc.signer] : [],
973
1215
  ...Object.keys(pc.maxTokenOutflow || {}),
974
1216
  ...Object.keys(pc.allowedOutgoingAssets || {}),
975
1217
  ...Object.keys(pc.minTokenInflow || {}),
@@ -21,6 +21,8 @@ interface TransactionBlockResourceBudget {
21
21
  maxExecuteAssetCallsPerBlock?: number;
22
22
  }
23
23
  interface TransactionBlockPostConditions {
24
+ /** Optional signer/account DID associated with this PostCondition envelope */
25
+ signer?: string;
24
26
  /**
25
27
  * Maximum allowed net token outflow per account DID and token address:
26
28
  * `{ [accountDid]: { [tokenAddress]: "100" } }`
@@ -173,6 +175,7 @@ declare class OverlayStateDB {
173
175
  private readonly base;
174
176
  private writes;
175
177
  private reads;
178
+ private balanceReadsByAddress;
176
179
  private runtimeIoBudget;
177
180
  private savepoints;
178
181
  [key: string]: any;
@@ -187,9 +190,10 @@ declare class OverlayStateDB {
187
190
  private getTableReads;
188
191
  private assertLiveReadBudget;
189
192
  private assertLiveWriteBudget;
193
+ private normalizeTableKey;
190
194
  private readBase;
191
- getBaseSnapshot(table: string, rawKey: string, ctx?: unknown): Promise<any>;
192
- hasTableWrite(table: string, rawKey: string): boolean;
195
+ getBaseSnapshot(table: string, rawKey: unknown, ctx?: unknown): Promise<any>;
196
+ hasTableWrite(table: string, rawKey: unknown): boolean;
193
197
  private createTableProxy;
194
198
  createSavepoint(): number;
195
199
  rollbackToSavepoint(savepointId: number): void;