@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
@@ -253,7 +253,7 @@ var OcapSuperSuitesFoundationEngine = class {
253
253
  }];
254
254
  const postConditions = {
255
255
  signer: pool.poolDid,
256
- maxTokenOutflow: { [pool.tokenAddress]: redeemAmountAbt.toString(10) },
256
+ maxTokenOutflow: { [pool.poolDid]: { [pool.tokenAddress]: redeemAmountAbt.toString(10) } },
257
257
  strictZeroUnlistedOutflow: true
258
258
  };
259
259
  return {
@@ -471,7 +471,7 @@ var OcapSuperSuitesFoundationEngine = class {
471
471
  pushSplitTransfer(org.creatorDid, creatorNetAbt, "CREATOR_NET_REVENUE");
472
472
  const postConditions = {
473
473
  signer: payerDid,
474
- maxTokenOutflow: { [org.tokenAddress]: ticketPriceAbt.toString(10) },
474
+ maxTokenOutflow: { [payerDid]: { [org.tokenAddress]: ticketPriceAbt.toString(10) } },
475
475
  strictZeroUnlistedOutflow: true
476
476
  };
477
477
  return {
@@ -668,7 +668,7 @@ var OcapSuperSuitesFoundationEngine = class {
668
668
  pushSplit(machineDid, poolCAddedAbt, "C_CONSERVATION_PRIZE_POOL");
669
669
  const postConditions = {
670
670
  signer: payerDid,
671
- maxTokenOutflow: { [machine.tokenAddress]: A.toString(10) },
671
+ maxTokenOutflow: { [payerDid]: { [machine.tokenAddress]: A.toString(10) } },
672
672
  strictZeroUnlistedOutflow: true
673
673
  };
674
674
  return {
@@ -773,7 +773,7 @@ var OcapSuperSuitesFoundationEngine = class {
773
773
  }));
774
774
  const postConditions = {
775
775
  signer: machineDid,
776
- maxTokenOutflow: { [machine.tokenAddress]: totalPayoutAbt.toString(10) },
776
+ maxTokenOutflow: { [machineDid]: { [machine.tokenAddress]: totalPayoutAbt.toString(10) } },
777
777
  strictZeroUnlistedOutflow: true
778
778
  };
779
779
  return {
@@ -944,7 +944,7 @@ var OcapSuperSuitesFoundationEngine = class {
944
944
  });
945
945
  const postConditions = {
946
946
  signer: offer.buyerDid,
947
- maxTokenOutflow: { [DEFAULT_ABT_TOKEN_ADDRESS]: grossOfferAbt.toString(10) },
947
+ maxTokenOutflow: { [offer.buyerDid]: { [DEFAULT_ABT_TOKEN_ADDRESS]: grossOfferAbt.toString(10) } },
948
948
  mustOwnAssetsAfter: { [offer.buyerDid]: [sticker.stickerDid] },
949
949
  strictZeroUnlistedOutflow: true
950
950
  };
@@ -1207,7 +1207,7 @@ var OcapSuperSuitesFoundationEngine = class {
1207
1207
  if (senderRefundAbt + recipientNetAbt + referrerAbt + protocolFeeAbt + spamSinkAbt !== stamp.stampAmountAbt) throw new CustomError(ErrorCode.ConservationViolation, "AttentionStamp resolution violated ABT conservation");
1208
1208
  const postConditions = {
1209
1209
  signer: stampId,
1210
- maxTokenOutflow: { [DEFAULT_ABT_TOKEN_ADDRESS]: stamp.stampAmountAbt.toString(10) },
1210
+ maxTokenOutflow: { [stampId]: { [DEFAULT_ABT_TOKEN_ADDRESS]: stamp.stampAmountAbt.toString(10) } },
1211
1211
  strictZeroUnlistedOutflow: true
1212
1212
  };
1213
1213
  return {
@@ -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;
@@ -3,10 +3,10 @@ import "./uniswap-router.mjs";
3
3
  import { Hasher } from "@ocap/mcrypto";
4
4
  import { BN, toAddress } from "@ocap/util";
5
5
  import { CustomError } from "@ocap/util/lib/error";
6
- import cloneDeep from "lodash/cloneDeep.js";
7
6
  import { isValid } from "@arcblock/did";
8
- import isEqual from "lodash/isEqual.js";
9
7
  import { toStakeAddress, toTokenCharterAssetAddress } from "@arcblock/did-util";
8
+ import cloneDeep from "lodash/cloneDeep.js";
9
+ import isEqual from "lodash/isEqual.js";
10
10
  import { isEthereumDid, toChecksumAddress } from "@arcblock/did/lib/type";
11
11
 
12
12
  //#region src/transaction-block.ts
@@ -48,6 +48,7 @@ const RESERVED_OVERLAY_MEMBERS = new Set([
48
48
  ]);
49
49
  const DEFAULT_TABLES = [
50
50
  "account",
51
+ "balance",
51
52
  "asset",
52
53
  "token",
53
54
  "factory",
@@ -291,10 +292,53 @@ function scheduleParallelBatches(items, getFootprint = (item) => extractStateFoo
291
292
  deferredByHotKeyQuota
292
293
  };
293
294
  }
295
+ function extractValidatedBalanceDiffIdentity(diff) {
296
+ const rawBeforeAddr = diff.before && typeof diff.before.address === "string" ? diff.before.address : "";
297
+ const beforeAddr = rawBeforeAddr.trim() ? canonicalizeStateKey(rawBeforeAddr) : "";
298
+ const rawAfterAddr = diff.op !== "delete" && diff.after && typeof diff.after.address === "string" ? diff.after.address : "";
299
+ const afterAddr = rawAfterAddr.trim() ? canonicalizeStateKey(rawAfterAddr) : "";
300
+ const rawBeforeTok = diff.before && typeof diff.before.tokenAddress === "string" ? diff.before.tokenAddress : "";
301
+ const beforeTok = rawBeforeTok.trim() ? canonicalizeStateKey(rawBeforeTok) : "";
302
+ const rawAfterTok = diff.op !== "delete" && diff.after && typeof diff.after.tokenAddress === "string" ? diff.after.tokenAddress : "";
303
+ const afterTok = rawAfterTok.trim() ? canonicalizeStateKey(rawAfterTok) : "";
304
+ if (diff.before !== null && diff.before !== void 0 && (!beforeAddr || !beforeTok || rawBeforeAddr !== beforeAddr || rawBeforeTok !== beforeTok)) return {
305
+ ok: false,
306
+ reason: "INVALID_BALANCE_ROW_IDENTITY",
307
+ tokenKey: afterTok || beforeTok || diff.key
308
+ };
309
+ if (diff.op !== "delete" && (!afterAddr || !afterTok || rawAfterAddr !== afterAddr || rawAfterTok !== afterTok)) return {
310
+ ok: false,
311
+ reason: "INVALID_BALANCE_ROW_IDENTITY",
312
+ tokenKey: afterTok || beforeTok || diff.key
313
+ };
314
+ if (beforeAddr && afterAddr && beforeAddr !== afterAddr) return {
315
+ ok: false,
316
+ reason: "INVALID_BALANCE_ROW_IDENTITY",
317
+ tokenKey: afterTok || beforeTok || diff.key
318
+ };
319
+ if (beforeTok && afterTok && beforeTok !== afterTok) return {
320
+ ok: false,
321
+ reason: "INVALID_BALANCE_ROW_IDENTITY",
322
+ tokenKey: afterTok || beforeTok || diff.key
323
+ };
324
+ const address = afterAddr || beforeAddr;
325
+ const tokenAddress = afterTok || beforeTok;
326
+ if (!address || !tokenAddress || FORBIDDEN_PATH_SEGMENTS.has(address) || FORBIDDEN_PATH_SEGMENTS.has(tokenAddress) || diff.key !== `${address}-${tokenAddress}`) return {
327
+ ok: false,
328
+ reason: "INVALID_BALANCE_ROW_IDENTITY",
329
+ tokenKey: tokenAddress || diff.key
330
+ };
331
+ return {
332
+ ok: true,
333
+ address,
334
+ tokenAddress
335
+ };
336
+ }
294
337
  var OverlayStateDB = class {
295
338
  constructor(baseStateDB, tables = DEFAULT_TABLES) {
296
339
  this.writes = /* @__PURE__ */ new Map();
297
340
  this.reads = /* @__PURE__ */ new Map();
341
+ this.balanceReadsByAddress = /* @__PURE__ */ new Map();
298
342
  this.runtimeIoBudget = null;
299
343
  this.savepoints = [];
300
344
  this.base = baseStateDB;
@@ -328,6 +372,7 @@ var OverlayStateDB = class {
328
372
  assertLiveReadBudget(table, key) {
329
373
  if (!this.runtimeIoBudget) return;
330
374
  if (this.reads.get(table)?.has(key)) return;
375
+ if (table === "balance" && this.balanceReadsByAddress.has(key)) return;
331
376
  const currentTouched = new Set([
332
377
  ...this.runtimeIoBudget.staticReadSet || [],
333
378
  ...this.getReadKeys(),
@@ -356,40 +401,67 @@ var OverlayStateDB = class {
356
401
  const effectiveCount = Math.max(tableCount, bareCount);
357
402
  if (effectiveCount > this.runtimeIoBudget.maxWriteKeys) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock runtime write key count (${effectiveCount}) exceeds maxWriteKeys (${this.runtimeIoBudget.maxWriteKeys})`);
358
403
  }
359
- async readBase(table, rawKey, ctx) {
360
- assertSafeKey(rawKey, "key");
404
+ normalizeTableKey(table, rawKey, fieldName = "key") {
405
+ if (table === "balance" && rawKey && typeof rawKey === "object" && !Array.isArray(rawKey) && typeof rawKey.address === "string" && typeof rawKey.tokenAddress === "string") {
406
+ const rawAddr = rawKey.address;
407
+ const rawTok = rawKey.tokenAddress;
408
+ assertSafeKey(rawAddr, `${fieldName}.address`);
409
+ assertSafeKey(rawTok, `${fieldName}.tokenAddress`);
410
+ const address = canonicalizeStateKey(rawAddr);
411
+ const tokenAddress = canonicalizeStateKey(rawTok);
412
+ assertSafeKey(address, `${fieldName}.address`);
413
+ assertSafeKey(tokenAddress, `${fieldName}.tokenAddress`);
414
+ return {
415
+ key: `${address}-${tokenAddress}`,
416
+ baseQueryKey: {
417
+ address,
418
+ tokenAddress
419
+ }
420
+ };
421
+ }
422
+ assertSafeKey(rawKey, fieldName);
361
423
  const key = canonicalizeStateKey(rawKey);
362
- assertSafeKey(key, "key");
424
+ assertSafeKey(key, fieldName);
425
+ return {
426
+ key,
427
+ baseQueryKey: key
428
+ };
429
+ }
430
+ async readBase(table, rawKey, ctx) {
431
+ const { key, baseQueryKey } = this.normalizeTableKey(table, rawKey, "key");
363
432
  const readsMap = this.getTableReads(table);
364
433
  if (readsMap.has(key)) return cloneDeep(readsMap.get(key));
365
434
  this.assertLiveReadBudget(table, key);
366
435
  const baseTable = this.base?.[table];
367
- let val = typeof baseTable?.get === "function" ? await baseTable.get(key, ctx) : null;
368
- if ((val === null || val === void 0) && rawKey !== key && typeof baseTable?.get === "function") val = await baseTable.get(rawKey, ctx);
436
+ let val = null;
437
+ if (typeof baseTable?.get === "function") {
438
+ if (table === "balance" && baseQueryKey !== key) try {
439
+ val = await baseTable.get(baseQueryKey, ctx);
440
+ } catch {
441
+ val = await baseTable.get(key, ctx);
442
+ }
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);
445
+ }
369
446
  readsMap.set(key, cloneDeep(val ?? null));
370
447
  return cloneDeep(val ?? null);
371
448
  }
372
449
  async getBaseSnapshot(table, rawKey, ctx) {
373
450
  assertSafeKey(table, "table");
374
- assertSafeKey(rawKey, "key");
375
451
  return this.readBase(table, rawKey, ctx);
376
452
  }
377
453
  hasTableWrite(table, rawKey) {
378
454
  assertSafeKey(table, "table");
379
- assertSafeKey(rawKey, "key");
380
- const key = canonicalizeStateKey(rawKey);
381
- assertSafeKey(key, "key");
455
+ const { key } = this.normalizeTableKey(table, rawKey, "key");
382
456
  const tableWrites = this.writes.get(table);
383
457
  if (!tableWrites?.has(key)) return false;
384
458
  const entry = tableWrites.get(key);
385
459
  return !isEqual(entry.before, entry.after);
386
460
  }
387
461
  createTableProxy(table) {
388
- return {
462
+ const proxy = {
389
463
  get: async (rawKey, ctx) => {
390
- assertSafeKey(rawKey, "key");
391
- const key = canonicalizeStateKey(rawKey);
392
- assertSafeKey(key, "key");
464
+ const { key } = this.normalizeTableKey(table, rawKey, "key");
393
465
  const tableWrites = this.writes.get(table);
394
466
  if (tableWrites?.has(key)) {
395
467
  const entry = tableWrites.get(key);
@@ -398,14 +470,15 @@ var OverlayStateDB = class {
398
470
  return this.readBase(table, rawKey, ctx);
399
471
  },
400
472
  create: async (rawKey, state, ctx) => {
401
- assertSafeKey(rawKey, "key");
402
- const key = canonicalizeStateKey(rawKey);
403
- assertSafeKey(key, "key");
473
+ const { key, baseQueryKey } = this.normalizeTableKey(table, rawKey, "key");
404
474
  this.assertLiveWriteBudget(table, key);
405
475
  const tableWrites = this.getTableWrites(table);
406
476
  const existingWrite = tableWrites.get(key);
407
477
  const before = existingWrite ? existingWrite.before : await this.readBase(table, rawKey, ctx);
408
- const cloned = cloneDeep(state);
478
+ const cloned = typeof baseQueryKey === "object" && state && typeof state === "object" ? cloneDeep({
479
+ ...baseQueryKey,
480
+ ...state
481
+ }) : cloneDeep(state);
409
482
  tableWrites.set(key, {
410
483
  op: before ? "update" : "create",
411
484
  before,
@@ -414,17 +487,20 @@ var OverlayStateDB = class {
414
487
  return cloneDeep(cloned);
415
488
  },
416
489
  update: async (rawKey, updates, ctx) => {
417
- assertSafeKey(rawKey, "key");
418
- const key = canonicalizeStateKey(rawKey);
419
- assertSafeKey(key, "key");
490
+ const { key, baseQueryKey } = this.normalizeTableKey(table, rawKey, "key");
420
491
  this.assertLiveWriteBudget(table, key);
421
492
  const tableWrites = this.getTableWrites(table);
422
493
  const existingWrite = tableWrites.get(key);
423
494
  const before = existingWrite ? existingWrite.before : await this.readBase(table, rawKey, ctx);
424
495
  const current = existingWrite ? existingWrite.after : before;
496
+ const baseObj = typeof baseQueryKey === "object" ? baseQueryKey : {};
425
497
  const merged = current && typeof current === "object" && updates && typeof updates === "object" ? cloneDeep({
498
+ ...baseObj,
426
499
  ...current,
427
500
  ...updates
501
+ }) : updates && typeof updates === "object" ? cloneDeep({
502
+ ...baseObj,
503
+ ...updates
428
504
  }) : cloneDeep(updates);
429
505
  tableWrites.set(key, {
430
506
  op: before ? "update" : "create",
@@ -434,17 +510,16 @@ var OverlayStateDB = class {
434
510
  return cloneDeep(merged);
435
511
  },
436
512
  updateOrCreate: async (existing, updates, ctx) => {
437
- const rawKey = updates?.address || existing?.address;
438
- assertSafeKey(rawKey, "address");
439
- const key = canonicalizeStateKey(rawKey);
440
- assertSafeKey(key, "address");
441
- if (await this[table].get(key, ctx)) return this[table].update(key, updates, ctx);
442
- return this[table].create(key, 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,
515
+ tokenAddress: updates?.tokenAddress || existing?.tokenAddress
516
+ } : updates?.address || existing?.address;
517
+ const { baseQueryKey } = this.normalizeTableKey(table, rawKey, "address");
518
+ if (await this[table].get(baseQueryKey, ctx)) return this[table].update(baseQueryKey, updates, ctx);
519
+ return this[table].create(baseQueryKey, updates, ctx);
443
520
  },
444
521
  delete: async (rawKey, ctx) => {
445
- assertSafeKey(rawKey, "key");
446
- const key = canonicalizeStateKey(rawKey);
447
- assertSafeKey(key, "key");
522
+ const { key } = this.normalizeTableKey(table, rawKey, "key");
448
523
  this.assertLiveWriteBudget(table, key);
449
524
  const tableWrites = this.getTableWrites(table);
450
525
  const existingWrite = tableWrites.get(key);
@@ -456,6 +531,63 @@ var OverlayStateDB = class {
456
531
  });
457
532
  }
458
533
  };
534
+ if (table === "balance") {
535
+ proxy.getBalance = async (rawAddress, ctx) => {
536
+ assertSafeKey(rawAddress, "address");
537
+ const address = canonicalizeStateKey(rawAddress);
538
+ assertSafeKey(address, "address");
539
+ let baseBalances = {};
540
+ if (this.balanceReadsByAddress.has(address)) baseBalances = cloneDeep(this.balanceReadsByAddress.get(address)) || {};
541
+ else {
542
+ this.assertLiveReadBudget("balance", address);
543
+ const baseBalanceTable = this.base?.balance;
544
+ if (typeof baseBalanceTable?.getBalance === "function") baseBalances = await baseBalanceTable.getBalance(address, ctx) || {};
545
+ this.balanceReadsByAddress.set(address, cloneDeep(baseBalances));
546
+ }
547
+ const merged = { ...baseBalances };
548
+ const tableWrites = this.writes.get("balance");
549
+ if (tableWrites) {
550
+ const prefix = `${address}-`;
551
+ for (const [k, entry] of tableWrites.entries()) {
552
+ const entryAddr = entry.after?.address ?? entry.before?.address;
553
+ const entryTok = entry.after?.tokenAddress ?? entry.before?.tokenAddress ?? (k.startsWith(prefix) ? k.slice(prefix.length) : void 0);
554
+ 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];
555
+ else merged[entryTok] = String(entry.after.balance);
556
+ }
557
+ }
558
+ return merged;
559
+ };
560
+ proxy.updateBalance = async (params, ctx) => {
561
+ assertSafeKey(params?.address, "address");
562
+ const address = canonicalizeStateKey(params.address);
563
+ assertSafeKey(address, "address");
564
+ const nextTokens = params?.tokens && typeof params.tokens === "object" ? params.tokens : {};
565
+ const currentBalances = await proxy.getBalance(address, ctx);
566
+ const allTokens = new Set([...Object.keys(currentBalances), ...Object.keys(nextTokens)]);
567
+ for (const rawTok of allTokens) {
568
+ if (FORBIDDEN_PATH_SEGMENTS.has(rawTok)) continue;
569
+ assertSafeKey(rawTok, "tokenAddress");
570
+ const tokenAddress = canonicalizeStateKey(rawTok);
571
+ assertSafeKey(tokenAddress, "tokenAddress");
572
+ const hasNext = Object.prototype.hasOwnProperty.call(nextTokens, rawTok) || Object.prototype.hasOwnProperty.call(nextTokens, tokenAddress);
573
+ const nextVal = Object.prototype.hasOwnProperty.call(nextTokens, rawTok) ? nextTokens[rawTok] : nextTokens[tokenAddress];
574
+ const prevVal = currentBalances[tokenAddress] ?? currentBalances[rawTok];
575
+ const compKey = {
576
+ address,
577
+ tokenAddress
578
+ };
579
+ if (!hasNext && prevVal !== void 0) await proxy.delete(compKey, ctx);
580
+ else if (hasNext && String(nextVal) !== String(prevVal ?? "0")) await proxy.update(compKey, {
581
+ address,
582
+ tokenAddress,
583
+ balance: String(nextVal),
584
+ ...params.context !== void 0 ? { context: params.context } : {}
585
+ }, ctx);
586
+ }
587
+ return cloneDeep(nextTokens);
588
+ };
589
+ }
590
+ return proxy;
459
591
  }
460
592
  createSavepoint() {
461
593
  const clonedWrites = /* @__PURE__ */ new Map();
@@ -470,9 +602,12 @@ var OverlayStateDB = class {
470
602
  for (const [k, v] of map.entries()) inner.set(k, cloneDeep(v));
471
603
  clonedReads.set(table, inner);
472
604
  }
605
+ const clonedBalanceReads = /* @__PURE__ */ new Map();
606
+ for (const [k, v] of this.balanceReadsByAddress.entries()) clonedBalanceReads.set(k, cloneDeep(v));
473
607
  this.savepoints.push({
474
608
  writes: clonedWrites,
475
- reads: clonedReads
609
+ reads: clonedReads,
610
+ balanceReadsByAddress: clonedBalanceReads
476
611
  });
477
612
  return this.savepoints.length - 1;
478
613
  }
@@ -482,6 +617,7 @@ var OverlayStateDB = class {
482
617
  this.savepoints.length = savepointId;
483
618
  this.writes = restored.writes;
484
619
  this.reads = restored.reads;
620
+ this.balanceReadsByAddress = restored.balanceReadsByAddress;
485
621
  }
486
622
  releaseSavepoint(savepointId) {
487
623
  if (savepointId < 0 || savepointId >= this.savepoints.length) throw new CustomError("INVALID_SAVEPOINT", `Invalid savepoint id ${savepointId}`);
@@ -490,11 +626,13 @@ var OverlayStateDB = class {
490
626
  discard() {
491
627
  this.writes.clear();
492
628
  this.reads.clear();
629
+ this.balanceReadsByAddress.clear();
493
630
  this.savepoints.length = 0;
494
631
  }
495
632
  getTouchedTableReadKeys() {
496
633
  const keys = /* @__PURE__ */ new Set();
497
634
  for (const [table, map] of this.reads.entries()) for (const k of map.keys()) keys.add(`${table}:${k}`);
635
+ for (const addr of this.balanceReadsByAddress.keys()) keys.add(`balance:${addr}`);
498
636
  for (const [table, map] of this.writes.entries()) for (const k of map.keys()) keys.add(`${table}:${k}`);
499
637
  return Array.from(keys).sort();
500
638
  }
@@ -506,6 +644,7 @@ var OverlayStateDB = class {
506
644
  getReadKeys() {
507
645
  const keys = /* @__PURE__ */ new Set();
508
646
  for (const map of this.reads.values()) for (const k of map.keys()) keys.add(k);
647
+ for (const addr of this.balanceReadsByAddress.keys()) keys.add(addr);
509
648
  for (const map of this.writes.values()) for (const k of map.keys()) keys.add(k);
510
649
  return Array.from(keys).sort();
511
650
  }
@@ -543,7 +682,9 @@ var OverlayStateDB = class {
543
682
  const cur = map.get(tokenAddr) || new BN(0);
544
683
  map.set(tokenAddr, cur.add(delta));
545
684
  };
546
- for (const diff of this.getStateDiff()) if (diff.table === "account" || diff.table === "stake") {
685
+ const stateDiffs = this.getStateDiff();
686
+ const accountTokenLiquidDeltas = /* @__PURE__ */ new Map();
687
+ for (const diff of stateDiffs) if (diff.table === "account" || diff.table === "stake") {
547
688
  const beforeTokens = diff.before?.tokens || {};
548
689
  const afterTokens = diff.after?.tokens || {};
549
690
  const beforePending = diff.before?.pendingTokens || {};
@@ -571,6 +712,7 @@ var OverlayStateDB = class {
571
712
  netUnbackedDeltas[tAddr] = "INVALID_NEGATIVE_OR_MALFORMED_BALANCE";
572
713
  continue;
573
714
  }
715
+ 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));
574
716
  const bTotal = bTok.value.add(bPend.value).add(bRev.value);
575
717
  addDelta(balanceDeltas, tAddr, aTok.value.add(aPend.value).add(aRev.value).sub(bTotal));
576
718
  }
@@ -616,6 +758,35 @@ var OverlayStateDB = class {
616
758
  netUnbackedDeltas[tokenAddr] = "INVALID_TOKEN_SUPPLY";
617
759
  } else addDelta(tokenSupplyDeltas, tokenAddr, aSup.value.sub(bSup.value));
618
760
  }
761
+ for (const diff of stateDiffs) {
762
+ if (diff.table !== "balance") continue;
763
+ const identity = extractValidatedBalanceDiffIdentity(diff);
764
+ if (!identity.ok) {
765
+ valid = false;
766
+ netUnbackedDeltas[identity.tokenKey] = identity.reason;
767
+ continue;
768
+ }
769
+ const { address: addr, tokenAddress: tAddr } = identity;
770
+ const bBal = parseNonNegativeBn(diff.before?.balance);
771
+ const aBal = parseNonNegativeBn(diff.after?.balance);
772
+ if (!bBal.ok || !aBal.ok) {
773
+ valid = false;
774
+ netUnbackedDeltas[tAddr] = "INVALID_NEGATIVE_OR_MALFORMED_BALANCE";
775
+ continue;
776
+ }
777
+ const balDelta = aBal.value.sub(bBal.value);
778
+ const pairKey = `${addr}:${tAddr}`;
779
+ if (accountTokenLiquidDeltas.has(pairKey)) {
780
+ const acctDelta = accountTokenLiquidDeltas.get(pairKey);
781
+ if (!acctDelta.eq(balDelta)) {
782
+ valid = false;
783
+ netUnbackedDeltas[tAddr] = `ACCOUNT_BALANCE_MISMATCH:${acctDelta.toString(10)}!=${balDelta.toString(10)}`;
784
+ continue;
785
+ }
786
+ continue;
787
+ }
788
+ addDelta(balanceDeltas, tAddr, balDelta);
789
+ }
619
790
  const allTokens = new Set([
620
791
  ...balanceDeltas.keys(),
621
792
  ...tokenSupplyDeltas.keys(),
@@ -654,13 +825,34 @@ var OverlayStateDB = class {
654
825
  * (Optimistic Concurrency Control check for 2PC Commit).
655
826
  */
656
827
  async verifyBaseUnchanged(ctx) {
828
+ if (this.balanceReadsByAddress.size > 0) {
829
+ const baseBalanceTable = this.base?.balance;
830
+ if (typeof baseBalanceTable?.getBalance === "function") {
831
+ for (const [addr, expectedBalances] of this.balanceReadsByAddress.entries()) if (!isEqual(await baseBalanceTable.getBalance(addr, ctx) || {}, expectedBalances ?? {})) return false;
832
+ }
833
+ }
657
834
  for (const [table, readsMap] of this.reads.entries()) {
658
835
  const baseTable = this.base?.[table];
659
- if (typeof baseTable?.get !== "function") continue;
836
+ if (!baseTable) continue;
660
837
  for (const [key, expectedVal] of readsMap.entries()) {
661
- const canonKey = canonicalizeStateKey(key);
662
- let currentVal = await baseTable.get(canonKey, ctx);
663
- if ((currentVal === null || currentVal === void 0) && canonKey !== key) currentVal = await baseTable.get(key, ctx);
838
+ if (typeof baseTable.get !== "function") continue;
839
+ let currentVal = null;
840
+ if (table === "balance") {
841
+ const splitIdx = key.indexOf("-");
842
+ const compKey = splitIdx > 0 ? {
843
+ address: key.slice(0, splitIdx),
844
+ tokenAddress: key.slice(splitIdx + 1)
845
+ } : key;
846
+ try {
847
+ currentVal = await baseTable.get(compKey, ctx);
848
+ } catch {
849
+ currentVal = await baseTable.get(key, ctx);
850
+ }
851
+ } else {
852
+ 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);
855
+ }
664
856
  if (!isEqual(currentVal ?? null, expectedVal ?? null)) return false;
665
857
  }
666
858
  }
@@ -668,17 +860,46 @@ var OverlayStateDB = class {
668
860
  }
669
861
  async commit(ctx) {
670
862
  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}"`);
865
+ }
671
866
  const applyDiffs = async (commitCtx) => {
672
867
  for (const diff of diffs) {
673
868
  const baseTable = this.base?.[diff.table];
674
869
  if (!baseTable) continue;
675
- if (diff.op === "delete") if (typeof baseTable.delete === "function") await baseTable.delete(diff.key, commitCtx);
870
+ let isBalanceComposite = false;
871
+ let targetKey = diff.key;
872
+ if (diff.table === "balance") {
873
+ const identity = extractValidatedBalanceDiffIdentity(diff);
874
+ if (!identity.ok) throw new CustomError("ACCOUNTING_INVARIANT_VIOLATION", `Invalid or mutated balance row identity for key "${diff.key}"`);
875
+ isBalanceComposite = true;
876
+ targetKey = {
877
+ address: identity.address,
878
+ tokenAddress: identity.tokenAddress
879
+ };
880
+ }
881
+ if (diff.op === "delete") if (typeof baseTable.delete === "function") if (isBalanceComposite) try {
882
+ await baseTable.delete(targetKey, commitCtx);
883
+ } catch {
884
+ await baseTable.delete(diff.key, commitCtx);
885
+ }
886
+ else await baseTable.delete(diff.key, commitCtx);
676
887
  else throw new CustomError("UNSUPPORTED_STATE_OPERATION", `Table "${diff.table}" does not support delete operation for key "${diff.key}"`);
677
888
  else if (diff.op === "create") {
678
- if (typeof baseTable.create === "function") await baseTable.create(diff.key, cloneDeep(diff.after), commitCtx);
889
+ if (typeof baseTable.create === "function") if (isBalanceComposite) try {
890
+ await baseTable.create(targetKey, cloneDeep(diff.after), commitCtx);
891
+ } catch {
892
+ await baseTable.create(diff.key, cloneDeep(diff.after), commitCtx);
893
+ }
894
+ else await baseTable.create(diff.key, cloneDeep(diff.after), commitCtx);
679
895
  else if (typeof baseTable.updateOrCreate === "function") await baseTable.updateOrCreate(null, cloneDeep(diff.after), commitCtx);
680
896
  } else if (diff.op === "update") {
681
- if (typeof baseTable.update === "function") await baseTable.update(diff.key, cloneDeep(diff.after), commitCtx);
897
+ if (typeof baseTable.update === "function") if (isBalanceComposite) try {
898
+ await baseTable.update(targetKey, cloneDeep(diff.after), commitCtx);
899
+ } catch {
900
+ await baseTable.update(diff.key, cloneDeep(diff.after), commitCtx);
901
+ }
902
+ else await baseTable.update(diff.key, cloneDeep(diff.after), commitCtx);
682
903
  else if (typeof baseTable.updateOrCreate === "function") await baseTable.updateOrCreate(cloneDeep(diff.before), cloneDeep(diff.after), commitCtx);
683
904
  }
684
905
  }
@@ -883,6 +1104,7 @@ function computeAccountAndAssetNetEffects(stateDiff) {
883
1104
  const cur = tokenMap.get(tokenAddr) || new BN(0);
884
1105
  tokenMap.set(tokenAddr, cur.add(delta));
885
1106
  };
1107
+ const accountTokenLiquidDeltas = /* @__PURE__ */ new Map();
886
1108
  for (const diff of stateDiff) if (diff.table === "account") {
887
1109
  const beforeTokens = diff.before?.tokens || {};
888
1110
  const afterTokens = diff.after?.tokens || {};
@@ -902,6 +1124,7 @@ function computeAccountAndAssetNetEffects(stateDiff) {
902
1124
  const aPend = parseNonNegativeBn(afterPending[tAddr]);
903
1125
  if (!bTok.ok || !aTok.ok || !bPend.ok || !aPend.ok) throw new CustomError("ACCOUNTING_INVARIANT_VIOLATION", `Malformed or negative token balance in account[${diff.key}][${tAddr}]`);
904
1126
  const liquidDelta = aTok.value.sub(bTok.value);
1127
+ if (Object.prototype.hasOwnProperty.call(beforeTokens, tAddr) || Object.prototype.hasOwnProperty.call(afterTokens, tAddr)) accountTokenLiquidDeltas.set(`${diff.key}:${tAddr}`, liquidDelta);
905
1128
  const totalDelta = aTok.value.add(aPend.value).sub(bTok.value.add(bPend.value));
906
1129
  const effectiveDelta = liquidDelta.lt(totalDelta) ? liquidDelta : totalDelta;
907
1130
  if (!effectiveDelta.isZero()) addAccountTokenDelta(diff.key, tAddr, effectiveDelta);
@@ -920,6 +1143,23 @@ function computeAccountAndAssetNetEffects(stateDiff) {
920
1143
  incomingAssetsByOwner.set(afterOwner, set);
921
1144
  }
922
1145
  }
1146
+ for (const diff of stateDiff) {
1147
+ if (diff.table !== "balance") continue;
1148
+ const identity = extractValidatedBalanceDiffIdentity(diff);
1149
+ if (!identity.ok) throw new CustomError("ACCOUNTING_INVARIANT_VIOLATION", `Invalid or mutated balance row identity in balance[${diff.key}]`);
1150
+ const { address: addr, tokenAddress: tAddr } = identity;
1151
+ const bBal = parseNonNegativeBn(diff.before?.balance);
1152
+ const aBal = parseNonNegativeBn(diff.after?.balance);
1153
+ if (!bBal.ok || !aBal.ok) throw new CustomError("ACCOUNTING_INVARIANT_VIOLATION", `Malformed or negative token balance in balance[${addr}][${tAddr}]`);
1154
+ const delta = aBal.value.sub(bBal.value);
1155
+ const pairKey = `${addr}:${tAddr}`;
1156
+ if (accountTokenLiquidDeltas.has(pairKey)) {
1157
+ const acctDelta = accountTokenLiquidDeltas.get(pairKey);
1158
+ if (!acctDelta.eq(delta)) throw new CustomError("ACCOUNTING_INVARIANT_VIOLATION", `Account ${addr} token ${tAddr} delta mismatch between account (${acctDelta.toString(10)}) and balance (${delta.toString(10)}) tables`);
1159
+ continue;
1160
+ }
1161
+ if (!delta.isZero()) addAccountTokenDelta(addr, tAddr, delta);
1162
+ }
923
1163
  return {
924
1164
  accountTokenNetDeltas,
925
1165
  outgoingAssetsByOwner,
@@ -963,10 +1203,12 @@ async function verifyTransactionBlockPostConditions(block, stateDiff, overlay) {
963
1203
  }
964
1204
  }
965
1205
  }
1206
+ if (pc.signer !== void 0) assertSafeKey(pc.signer, "postConditions.signer");
966
1207
  if (strictZeroUnlisted) {
967
1208
  const protectedAccounts = new Set([
968
1209
  block.from,
969
1210
  ...block.delegator ? [block.delegator] : [],
1211
+ ...typeof pc.signer === "string" && pc.signer ? [pc.signer] : [],
970
1212
  ...Object.keys(pc.maxTokenOutflow || {}),
971
1213
  ...Object.keys(pc.allowedOutgoingAssets || {}),
972
1214
  ...Object.keys(pc.minTokenInflow || {}),