@ocap/tx-pipeline 1.30.26 → 1.31.1

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 (149) hide show
  1. package/esm/appchain-sovereign-hub.d.mts +160 -0
  2. package/esm/appchain-sovereign-hub.mjs +348 -0
  3. package/esm/arcvault-external-adapter.d.mts +166 -0
  4. package/esm/arcvault-external-adapter.mjs +376 -0
  5. package/esm/encrypted-nft-envelope.d.mts +172 -0
  6. package/esm/encrypted-nft-envelope.mjs +458 -0
  7. package/esm/evm-simplified-bridge.d.mts +1370 -0
  8. package/esm/evm-simplified-bridge.mjs +3875 -0
  9. package/esm/give-to-mint-karma.d.mts +472 -0
  10. package/esm/give-to-mint-karma.mjs +1057 -0
  11. package/esm/helpers/replay-guard.d.mts +15 -0
  12. package/esm/helpers/replay-guard.mjs +23 -0
  13. package/esm/index.d.mts +10 -5
  14. package/esm/index.mjs +14 -10
  15. package/esm/legacy-protocol-sunset.d.mts +251 -0
  16. package/esm/legacy-protocol-sunset.mjs +1519 -0
  17. package/esm/library.d.mts +16 -0
  18. package/esm/library.mjs +17 -0
  19. package/esm/native-abt-exchange.d.mts +2055 -0
  20. package/esm/native-abt-exchange.mjs +7250 -0
  21. package/esm/ofac-screening.d.mts +17 -0
  22. package/esm/ofac-screening.mjs +39 -0
  23. package/esm/pipes/anti-land-attack.mjs +1 -1
  24. package/esm/pipes/decode-itx.mjs +46 -4
  25. package/esm/pipes/decode-tx.d.mts +2 -3
  26. package/esm/pipes/decode-tx.mjs +56 -115
  27. package/esm/pipes/extract-signer.mjs +2 -2
  28. package/esm/pipes/extract-state.mjs +14 -3
  29. package/esm/pipes/post-execution-invariant-gate.d.mts +61 -0
  30. package/esm/pipes/post-execution-invariant-gate.mjs +789 -0
  31. package/esm/pipes/pre-flight-waf.d.mts +73 -0
  32. package/esm/pipes/pre-flight-waf.mjs +756 -0
  33. package/esm/pipes/take-state-snapshot.mjs +3 -2
  34. package/esm/pipes/update-owner.mjs +39 -4
  35. package/esm/pipes/verify-account-migration.mjs +14 -4
  36. package/esm/pipes/verify-blocked.mjs +1 -1
  37. package/esm/pipes/verify-delegation.d.mts +22 -3
  38. package/esm/pipes/verify-delegation.mjs +259 -36
  39. package/esm/pipes/verify-list-size.mjs +1 -1
  40. package/esm/pipes/verify-multisig-v2.mjs +15 -7
  41. package/esm/pipes/verify-multisig.mjs +15 -7
  42. package/esm/pipes/verify-sender.mjs +1 -1
  43. package/esm/pipes/verify-signature.mjs +35 -6
  44. package/esm/pipes/verify-signer.mjs +2 -2
  45. package/esm/pipes/verify-state-diff.mjs +3 -3
  46. package/esm/pipes/verify-token-access.mjs +1 -1
  47. package/esm/pipes/verify-token-balance.mjs +13 -5
  48. package/esm/pipes/verify-transferrable.d.mts +8 -1
  49. package/esm/pipes/verify-transferrable.mjs +3 -3
  50. package/esm/pipes/verify-tx-input.mjs +2 -2
  51. package/esm/pipes/verify-tx-size.mjs +46 -2
  52. package/esm/pipes/verify-tx.mjs +5 -7
  53. package/esm/pipes/verify-updater.mjs +1 -1
  54. package/esm/social-economy-factories.d.mts +346 -0
  55. package/esm/social-economy-factories.mjs +845 -0
  56. package/esm/super-suites-foundation.d.mts +513 -0
  57. package/esm/super-suites-foundation.mjs +1241 -0
  58. package/esm/transaction-block.d.mts +471 -0
  59. package/esm/transaction-block.mjs +1906 -0
  60. package/esm/uniswap-erc7683-solver.d.mts +201 -0
  61. package/esm/uniswap-erc7683-solver.mjs +321 -0
  62. package/esm/uniswap-lp-copilot.d.mts +113 -0
  63. package/esm/uniswap-lp-copilot.mjs +320 -0
  64. package/esm/uniswap-router.d.mts +335 -0
  65. package/esm/uniswap-router.mjs +578 -0
  66. package/esm/uniswap-token-factory-graduation.d.mts +187 -0
  67. package/esm/uniswap-token-factory-graduation.mjs +426 -0
  68. package/esm/uniswap-v4-hook.d.mts +173 -0
  69. package/esm/uniswap-v4-hook.mjs +517 -0
  70. package/lib/appchain-sovereign-hub.cjs +352 -0
  71. package/lib/appchain-sovereign-hub.d.cts +160 -0
  72. package/lib/arcvault-external-adapter.cjs +383 -0
  73. package/lib/arcvault-external-adapter.d.cts +166 -0
  74. package/lib/encrypted-nft-envelope.cjs +477 -0
  75. package/lib/encrypted-nft-envelope.d.cts +172 -0
  76. package/lib/evm-simplified-bridge.cjs +3943 -0
  77. package/lib/evm-simplified-bridge.d.cts +1370 -0
  78. package/lib/give-to-mint-karma.cjs +1084 -0
  79. package/lib/give-to-mint-karma.d.cts +472 -0
  80. package/lib/helpers/replay-guard.cjs +27 -0
  81. package/lib/helpers/replay-guard.d.cts +15 -0
  82. package/lib/index.cjs +49 -16
  83. package/lib/index.d.cts +10 -5
  84. package/lib/legacy-protocol-sunset.cjs +1543 -0
  85. package/lib/legacy-protocol-sunset.d.cts +251 -0
  86. package/lib/library.cjs +303 -0
  87. package/lib/library.d.cts +16 -0
  88. package/lib/native-abt-exchange.cjs +7322 -0
  89. package/lib/native-abt-exchange.d.cts +2055 -0
  90. package/lib/ofac-screening.cjs +42 -0
  91. package/lib/ofac-screening.d.cts +17 -0
  92. package/lib/pipes/anti-land-attack.cjs +2 -2
  93. package/lib/pipes/decode-itx.cjs +46 -4
  94. package/lib/pipes/decode-itx.d.cts +1 -1
  95. package/lib/pipes/decode-tx.cjs +55 -116
  96. package/lib/pipes/decode-tx.d.cts +3 -4
  97. package/lib/pipes/extract-signer.cjs +2 -2
  98. package/lib/pipes/extract-state.cjs +14 -3
  99. package/lib/pipes/post-execution-invariant-gate.cjs +800 -0
  100. package/lib/pipes/post-execution-invariant-gate.d.cts +61 -0
  101. package/lib/pipes/pre-flight-waf.cjs +772 -0
  102. package/lib/pipes/pre-flight-waf.d.cts +73 -0
  103. package/lib/pipes/take-state-snapshot.cjs +3 -2
  104. package/lib/pipes/update-owner.cjs +40 -5
  105. package/lib/pipes/update-owner.d.cts +1 -1
  106. package/lib/pipes/verify-account-migration.cjs +14 -4
  107. package/lib/pipes/verify-blocked.cjs +1 -1
  108. package/lib/pipes/verify-delegation.cjs +259 -36
  109. package/lib/pipes/verify-delegation.d.cts +22 -3
  110. package/lib/pipes/verify-list-size.cjs +1 -1
  111. package/lib/pipes/verify-multisig-v2.cjs +15 -7
  112. package/lib/pipes/verify-multisig.cjs +15 -7
  113. package/lib/pipes/verify-sender.cjs +1 -1
  114. package/lib/pipes/verify-service-fee.d.cts +1 -1
  115. package/lib/pipes/verify-signature.cjs +35 -6
  116. package/lib/pipes/verify-signature.d.cts +1 -1
  117. package/lib/pipes/verify-signer.cjs +2 -2
  118. package/lib/pipes/verify-state-diff.cjs +4 -4
  119. package/lib/pipes/verify-token-access.cjs +2 -2
  120. package/lib/pipes/verify-token-balance.cjs +13 -5
  121. package/lib/pipes/verify-transferrable.cjs +3 -3
  122. package/lib/pipes/verify-transferrable.d.cts +8 -1
  123. package/lib/pipes/verify-tx-input.cjs +3 -3
  124. package/lib/pipes/verify-tx-size.cjs +46 -2
  125. package/lib/pipes/verify-tx-size.d.cts +1 -1
  126. package/lib/pipes/verify-tx.cjs +6 -8
  127. package/lib/pipes/verify-tx.d.cts +1 -1
  128. package/lib/pipes/verify-updater.cjs +1 -1
  129. package/lib/social-economy-factories.cjs +852 -0
  130. package/lib/social-economy-factories.d.cts +346 -0
  131. package/lib/super-suites-foundation.cjs +1257 -0
  132. package/lib/super-suites-foundation.d.cts +513 -0
  133. package/lib/transaction-block.cjs +1941 -0
  134. package/lib/transaction-block.d.cts +471 -0
  135. package/lib/uniswap-erc7683-solver.cjs +327 -0
  136. package/lib/uniswap-erc7683-solver.d.cts +201 -0
  137. package/lib/uniswap-lp-copilot.cjs +328 -0
  138. package/lib/uniswap-lp-copilot.d.cts +113 -0
  139. package/lib/uniswap-router.cjs +593 -0
  140. package/lib/uniswap-router.d.cts +335 -0
  141. package/lib/uniswap-token-factory-graduation.cjs +431 -0
  142. package/lib/uniswap-token-factory-graduation.d.cts +187 -0
  143. package/lib/uniswap-v4-hook.cjs +527 -0
  144. package/lib/uniswap-v4-hook.d.cts +173 -0
  145. package/package.json +11 -10
  146. package/esm/helpers/dedup-height.d.mts +0 -16
  147. package/esm/helpers/dedup-height.mjs +0 -61
  148. package/lib/helpers/dedup-height.cjs +0 -72
  149. package/lib/helpers/dedup-height.d.cts +0 -16
@@ -0,0 +1,1906 @@
1
+ import { assertNotOfacSanctioned } from "./ofac-screening.mjs";
2
+ import "./uniswap-router.mjs";
3
+ import { Hasher } from "@ocap/mcrypto";
4
+ import { BN, toAddress } from "@ocap/util";
5
+ import { CustomError } from "@ocap/util/lib/error";
6
+ import cloneDeep from "lodash/cloneDeep.js";
7
+ import { isValid } from "@arcblock/did";
8
+ import isEqual from "lodash/isEqual.js";
9
+ import { toStakeAddress, toTokenCharterAssetAddress } from "@arcblock/did-util";
10
+ import { isEthereumDid, toChecksumAddress } from "@arcblock/did/lib/type";
11
+
12
+ //#region src/transaction-block.ts
13
+ const FORBIDDEN_PATH_SEGMENTS = new Set([
14
+ "__proto__",
15
+ "constructor",
16
+ "prototype"
17
+ ]);
18
+ const SAFE_SEGMENT_REGEX = /^[a-zA-Z0-9_$]+$/;
19
+ const CANONICAL_NON_NEGATIVE_INT_REGEX = /^\d+$/;
20
+ const CANONICAL_SIGNED_INT_REGEX = /^-?\d+$/;
21
+ const RESERVED_OVERLAY_MEMBERS = new Set([
22
+ "base",
23
+ "writes",
24
+ "reads",
25
+ "savepoints",
26
+ "runtimeIoBudget",
27
+ "getTableWrites",
28
+ "getTableReads",
29
+ "readBase",
30
+ "getBaseSnapshot",
31
+ "hasTableWrite",
32
+ "setRuntimeIoBudget",
33
+ "assertLiveReadBudget",
34
+ "assertLiveWriteBudget",
35
+ "getTouchedTableReadKeys",
36
+ "getTouchedTableWriteKeys",
37
+ "createTableProxy",
38
+ "createSavepoint",
39
+ "rollbackToSavepoint",
40
+ "releaseSavepoint",
41
+ "discard",
42
+ "getStateDiff",
43
+ "getReadKeys",
44
+ "getWriteKeys",
45
+ "verifyZeroSumConservation",
46
+ "verifyBaseUnchanged",
47
+ "commit"
48
+ ]);
49
+ const DEFAULT_TABLES = [
50
+ "account",
51
+ "asset",
52
+ "token",
53
+ "factory",
54
+ "tokenFactory",
55
+ "stake",
56
+ "delegation",
57
+ "rollup",
58
+ "rollupBlock",
59
+ "evidence",
60
+ "tx",
61
+ "chain"
62
+ ];
63
+ const MAX_TX_BLOCK_BYTES = 16384;
64
+ const MAX_TX_BLOCK_TOP_LEVEL_STATEMENTS = 16;
65
+ const HARD_MAX_TX_BLOCK_STATEMENTS = 64;
66
+ const MAX_TX_BLOCK_TOTAL_EXPANDED_STATEMENTS = 32;
67
+ const MAX_TX_BLOCK_READ_KEYS = 64;
68
+ const MAX_TX_BLOCK_WRITE_KEYS = 32;
69
+ const MAX_TX_BLOCK_STATE_DIFF_ENTRIES = 48;
70
+ const MAX_EXECUTE_ASSET_DEPTH = 1;
71
+ const MAX_EXECUTE_ASSET_CALLS_PER_BLOCK = 4;
72
+ function assertSafeKey(key, label = "key") {
73
+ if (!key || typeof key !== "string" || FORBIDDEN_PATH_SEGMENTS.has(key)) throw new CustomError("INVALID_TX", `Unsafe or empty ${label}: ${String(key)}`);
74
+ }
75
+ function parseSafePath(pathStr) {
76
+ assertSafeKey(pathStr, "path");
77
+ const parts = pathStr.split(".");
78
+ for (const part of parts) if (!part || !SAFE_SEGMENT_REGEX.test(part) || FORBIDDEN_PATH_SEGMENTS.has(part)) throw new CustomError("INVALID_TX", `Forbidden or unsafe path segment in ${pathStr}`);
79
+ return parts;
80
+ }
81
+ function getSafePath(target, pathStr) {
82
+ const parts = parseSafePath(pathStr);
83
+ let cur = target;
84
+ for (const part of parts) {
85
+ if (cur === null || cur === void 0 || typeof cur !== "object") return;
86
+ if (!Object.prototype.hasOwnProperty.call(cur, part)) return;
87
+ cur = cur[part];
88
+ }
89
+ return cur;
90
+ }
91
+ function parseNonNegativeBn(raw) {
92
+ if (raw === void 0 || raw === null) return {
93
+ ok: true,
94
+ value: new BN(0)
95
+ };
96
+ if (typeof raw !== "string" || !CANONICAL_NON_NEGATIVE_INT_REGEX.test(raw)) return {
97
+ ok: false,
98
+ value: new BN(0)
99
+ };
100
+ return {
101
+ ok: true,
102
+ value: new BN(raw, 10)
103
+ };
104
+ }
105
+ function canonicalizeStateKey(rawKey) {
106
+ const trimmed = rawKey.trim();
107
+ const stripped = isValid(toAddress(trimmed)) || trimmed.startsWith("did:abt:") ? toAddress(trimmed) : trimmed;
108
+ return isEthereumDid(stripped) ? toChecksumAddress(stripped) : stripped;
109
+ }
110
+ function normalizeDidOrKey(addr) {
111
+ if (typeof addr !== "string") return null;
112
+ const trimmed = addr.trim();
113
+ if (!trimmed || FORBIDDEN_PATH_SEGMENTS.has(trimmed)) return null;
114
+ const canon = canonicalizeStateKey(trimmed);
115
+ if (!canon || FORBIDDEN_PATH_SEGMENTS.has(canon)) return null;
116
+ return canon;
117
+ }
118
+ /**
119
+ * 1. Solana-Style Static & Explicit Read/Write State Footprint Extractor (`extractStateFootprint`)
120
+ * Derives `{ readSet, writeSet }` from any single OCAP transaction, statement, or multi-statement
121
+ * `TransactionBlock` without executing business logic.
122
+ */
123
+ function extractStateFootprint(input) {
124
+ const reads = /* @__PURE__ */ new Set();
125
+ const writes = /* @__PURE__ */ new Set();
126
+ const addRead = (v) => {
127
+ const k = normalizeDidOrKey(v);
128
+ if (k) reads.add(k);
129
+ };
130
+ const addWrite = (v) => {
131
+ const k = normalizeDidOrKey(v);
132
+ if (k) {
133
+ reads.add(k);
134
+ writes.add(k);
135
+ }
136
+ };
137
+ if (Array.isArray(input.readSet)) for (const r of input.readSet) addRead(r);
138
+ if (Array.isArray(input.writeSet)) for (const w of input.writeSet) addWrite(w);
139
+ if ("statements" in input && Array.isArray(input.statements)) {
140
+ addWrite(input.from);
141
+ if (input.delegator) addWrite(input.delegator);
142
+ for (const stmt of input.statements) {
143
+ const sub = extractStateFootprint(stmt);
144
+ for (const r of sub.readSet) reads.add(r);
145
+ for (const w of sub.writeSet) {
146
+ reads.add(w);
147
+ writes.add(w);
148
+ }
149
+ }
150
+ return {
151
+ readSet: Array.from(reads).sort(),
152
+ writeSet: Array.from(writes).sort()
153
+ };
154
+ }
155
+ addWrite(input.from);
156
+ if (input.delegator) addWrite(input.delegator);
157
+ const sigs = ("signatures" in input && Array.isArray(input.signatures) ? input.signatures : null) || ("signaturesList" in input && Array.isArray(input.signaturesList) ? input.signaturesList : []);
158
+ for (const s of sigs) {
159
+ if (s?.signer) addWrite(s.signer);
160
+ if (s?.delegator) addWrite(s.delegator);
161
+ }
162
+ const itx = input.itx || {};
163
+ if (itx.address) addWrite(itx.address);
164
+ if (itx.positionId) addWrite(itx.positionId);
165
+ if (itx.contractNft) addRead(itx.contractNft);
166
+ if (itx.to) addWrite(itx.to);
167
+ if (itx.receiver) addWrite(itx.receiver);
168
+ if (itx.issuer) addRead(itx.issuer);
169
+ if (itx.parent) addRead(itx.parent);
170
+ if (itx.factory) addWrite(itx.factory);
171
+ if (itx.tokenAddress) {
172
+ addWrite(itx.tokenAddress);
173
+ try {
174
+ addWrite(toTokenCharterAssetAddress(itx.tokenAddress));
175
+ } catch {}
176
+ }
177
+ if (itx.reserveAddress) addRead(itx.reserveAddress);
178
+ if (itx.rollup) {
179
+ addWrite(itx.rollup);
180
+ try {
181
+ addWrite(toStakeAddress(itx.rollup, itx.rollup));
182
+ } catch {}
183
+ if (itx.proposer) {
184
+ addWrite(itx.proposer);
185
+ try {
186
+ addWrite(toStakeAddress(itx.proposer, itx.rollup));
187
+ } catch {}
188
+ }
189
+ if (input.from) try {
190
+ addWrite(toStakeAddress(input.from, itx.rollup));
191
+ } catch {}
192
+ }
193
+ if (itx.evidence?.hash) addWrite(itx.evidence.hash);
194
+ if (itx.token?.address) {
195
+ addWrite(itx.token.address);
196
+ try {
197
+ addWrite(toTokenCharterAssetAddress(itx.token.address));
198
+ } catch {}
199
+ }
200
+ for (const listKey of ["assets", "assetsList"]) if (Array.isArray(itx[listKey])) for (const a of itx[listKey]) addWrite(typeof a === "string" ? a : a?.address);
201
+ for (const listKey of ["tokens", "tokensList"]) if (Array.isArray(itx[listKey])) for (const t of itx[listKey]) addRead(typeof t === "string" ? t : t?.address);
202
+ for (const ioKey of [
203
+ "inputs",
204
+ "inputsList",
205
+ "outputs",
206
+ "outputsList"
207
+ ]) if (Array.isArray(itx[ioKey])) for (const item of itx[ioKey]) {
208
+ if (item?.owner) addWrite(item.owner);
209
+ for (const a of item?.assets || item?.assetsList || []) addWrite(a);
210
+ for (const t of item?.tokens || item?.tokensList || []) addRead(t?.address || t);
211
+ }
212
+ return {
213
+ readSet: Array.from(reads).sort(),
214
+ writeSet: Array.from(writes).sort()
215
+ };
216
+ }
217
+ /**
218
+ * Determine whether two transactions or `TransactionBlock`s have a Read/Write or Write/Write conflict:
219
+ * $(W_A \cap (R_B \cup W_B)) \neq \emptyset \lor (W_B \cap (R_A \cup W_A)) \neq \emptyset$.
220
+ */
221
+ function hasStateConflict(fpA, fpB) {
222
+ const readA = new Set(fpA.readSet);
223
+ const writeA = new Set(fpA.writeSet);
224
+ const readB = new Set(fpB.readSet);
225
+ const writeB = new Set(fpB.writeSet);
226
+ for (const w of writeA) if (readB.has(w) || writeB.has(w)) return true;
227
+ for (const w of writeB) if (readA.has(w) || writeA.has(w)) return true;
228
+ return false;
229
+ }
230
+ const DEFAULT_MAX_STATEMENTS_PER_HOT_KEY_PER_BLOCK = 32;
231
+ /**
232
+ * Partition a batch of transactions or `TransactionBlock`s into deterministic, conflict-free
233
+ * parallel waves (Solana Sealevel / deterministic wave scheduler).
234
+ *
235
+ * When `options.maxStatementsPerHotKeyPerBlock` is provided, any item whose `writeSet` touches
236
+ * a hot state key that has already reached the per-block write quota is deferred into
237
+ * `deferredByHotKeyQuota`, preventing sniper storms on a single hot `TokenFactory` from
238
+ * creating hundreds of sequential waves and starving unrelated transactions.
239
+ */
240
+ function scheduleParallelBatches(items, getFootprint = (item) => extractStateFootprint(item), options) {
241
+ const maxPerHotKey = options?.maxStatementsPerHotKeyPerBlock;
242
+ if (maxPerHotKey !== void 0 && (typeof maxPerHotKey !== "number" || !Number.isSafeInteger(maxPerHotKey) || maxPerHotKey <= 0)) throw new CustomError("INVALID_HOT_KEY_QUOTA", "maxStatementsPerHotKeyPerBlock must be a positive safe integer");
243
+ const waves = [];
244
+ const waveFootprints = [];
245
+ const footprints = [];
246
+ const deferredByHotKeyQuota = [];
247
+ const writeKeyCounts = /* @__PURE__ */ new Map();
248
+ for (const item of items) {
249
+ const rawFp = getFootprint(item);
250
+ const uniqueReads = Array.from(new Set(rawFp.readSet));
251
+ const uniqueWrites = Array.from(new Set(rawFp.writeSet));
252
+ const fp = {
253
+ readSet: uniqueReads,
254
+ writeSet: uniqueWrites
255
+ };
256
+ footprints.push(fp);
257
+ if (maxPerHotKey !== void 0) {
258
+ if (uniqueWrites.some((w) => (writeKeyCounts.get(w) || 0) >= maxPerHotKey) || uniqueReads.some((r) => (writeKeyCounts.get(r) || 0) >= maxPerHotKey)) {
259
+ deferredByHotKeyQuota.push(item);
260
+ continue;
261
+ }
262
+ for (const w of uniqueWrites) writeKeyCounts.set(w, (writeKeyCounts.get(w) || 0) + 1);
263
+ }
264
+ let placedWaveIndex = -1;
265
+ for (let i = 0; i < waves.length; i++) {
266
+ const wf = waveFootprints[i];
267
+ if (!(fp.writeSet.some((w) => wf.reads.has(w) || wf.writes.has(w)) || fp.readSet.some((r) => wf.writes.has(r)))) {
268
+ placedWaveIndex = i;
269
+ break;
270
+ }
271
+ }
272
+ if (placedWaveIndex === -1) {
273
+ waves.push([item]);
274
+ waveFootprints.push({
275
+ reads: new Set(fp.readSet),
276
+ writes: new Set(fp.writeSet)
277
+ });
278
+ } else {
279
+ waves[placedWaveIndex].push(item);
280
+ const wf = waveFootprints[placedWaveIndex];
281
+ for (const r of fp.readSet) wf.reads.add(r);
282
+ for (const w of fp.writeSet) {
283
+ wf.reads.add(w);
284
+ wf.writes.add(w);
285
+ }
286
+ }
287
+ }
288
+ return {
289
+ waves,
290
+ footprints,
291
+ deferredByHotKeyQuota
292
+ };
293
+ }
294
+ var OverlayStateDB = class {
295
+ constructor(baseStateDB, tables = DEFAULT_TABLES) {
296
+ this.writes = /* @__PURE__ */ new Map();
297
+ this.reads = /* @__PURE__ */ new Map();
298
+ this.runtimeIoBudget = null;
299
+ this.savepoints = [];
300
+ this.base = baseStateDB;
301
+ const allTables = new Set([...tables, ...Object.keys(baseStateDB || {}).filter((k) => !FORBIDDEN_PATH_SEGMENTS.has(k) && !RESERVED_OVERLAY_MEMBERS.has(k))]);
302
+ for (const tableName of allTables) {
303
+ if (RESERVED_OVERLAY_MEMBERS.has(tableName) || tableName in this) continue;
304
+ this[tableName] = this.createTableProxy(tableName);
305
+ }
306
+ }
307
+ setRuntimeIoBudget(budget) {
308
+ this.runtimeIoBudget = budget;
309
+ }
310
+ getTableWrites(table) {
311
+ assertSafeKey(table, "table");
312
+ let map = this.writes.get(table);
313
+ if (!map) {
314
+ map = /* @__PURE__ */ new Map();
315
+ this.writes.set(table, map);
316
+ }
317
+ return map;
318
+ }
319
+ getTableReads(table) {
320
+ assertSafeKey(table, "table");
321
+ let map = this.reads.get(table);
322
+ if (!map) {
323
+ map = /* @__PURE__ */ new Map();
324
+ this.reads.set(table, map);
325
+ }
326
+ return map;
327
+ }
328
+ assertLiveReadBudget(table, key) {
329
+ if (!this.runtimeIoBudget) return;
330
+ if (this.reads.get(table)?.has(key)) return;
331
+ const currentTouched = new Set([
332
+ ...this.runtimeIoBudget.staticReadSet || [],
333
+ ...this.getReadKeys(),
334
+ ...this.getTouchedTableReadKeys(),
335
+ key,
336
+ `${table}:${key}`
337
+ ]);
338
+ const tableCount = this.getTouchedTableReadKeys().length + 1;
339
+ const bareCount = new Set([
340
+ ...this.runtimeIoBudget.staticReadSet || [],
341
+ ...this.getReadKeys(),
342
+ key
343
+ ]).size;
344
+ const effectiveCount = Math.max(tableCount, bareCount);
345
+ if (effectiveCount > this.runtimeIoBudget.maxReadKeys && currentTouched.size > this.runtimeIoBudget.maxReadKeys) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock runtime read key count (${effectiveCount}) exceeds maxReadKeys (${this.runtimeIoBudget.maxReadKeys})`);
346
+ }
347
+ assertLiveWriteBudget(table, key) {
348
+ if (!this.runtimeIoBudget) return;
349
+ if (this.writes.get(table)?.has(key)) return;
350
+ const tableCount = this.getTouchedTableWriteKeys().length + 1;
351
+ const bareCount = new Set([
352
+ ...this.runtimeIoBudget.staticWriteSet || [],
353
+ ...this.getWriteKeys(),
354
+ key
355
+ ]).size;
356
+ const effectiveCount = Math.max(tableCount, bareCount);
357
+ if (effectiveCount > this.runtimeIoBudget.maxWriteKeys) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock runtime write key count (${effectiveCount}) exceeds maxWriteKeys (${this.runtimeIoBudget.maxWriteKeys})`);
358
+ }
359
+ async readBase(table, rawKey, ctx) {
360
+ assertSafeKey(rawKey, "key");
361
+ const key = canonicalizeStateKey(rawKey);
362
+ assertSafeKey(key, "key");
363
+ const readsMap = this.getTableReads(table);
364
+ if (readsMap.has(key)) return cloneDeep(readsMap.get(key));
365
+ this.assertLiveReadBudget(table, key);
366
+ 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);
369
+ readsMap.set(key, cloneDeep(val ?? null));
370
+ return cloneDeep(val ?? null);
371
+ }
372
+ async getBaseSnapshot(table, rawKey, ctx) {
373
+ assertSafeKey(table, "table");
374
+ assertSafeKey(rawKey, "key");
375
+ return this.readBase(table, rawKey, ctx);
376
+ }
377
+ hasTableWrite(table, rawKey) {
378
+ assertSafeKey(table, "table");
379
+ assertSafeKey(rawKey, "key");
380
+ const key = canonicalizeStateKey(rawKey);
381
+ assertSafeKey(key, "key");
382
+ const tableWrites = this.writes.get(table);
383
+ if (!tableWrites?.has(key)) return false;
384
+ const entry = tableWrites.get(key);
385
+ return !isEqual(entry.before, entry.after);
386
+ }
387
+ createTableProxy(table) {
388
+ return {
389
+ get: async (rawKey, ctx) => {
390
+ assertSafeKey(rawKey, "key");
391
+ const key = canonicalizeStateKey(rawKey);
392
+ assertSafeKey(key, "key");
393
+ const tableWrites = this.writes.get(table);
394
+ if (tableWrites?.has(key)) {
395
+ const entry = tableWrites.get(key);
396
+ return entry.op === "delete" ? null : cloneDeep(entry.after);
397
+ }
398
+ return this.readBase(table, rawKey, ctx);
399
+ },
400
+ create: async (rawKey, state, ctx) => {
401
+ assertSafeKey(rawKey, "key");
402
+ const key = canonicalizeStateKey(rawKey);
403
+ assertSafeKey(key, "key");
404
+ this.assertLiveWriteBudget(table, key);
405
+ const tableWrites = this.getTableWrites(table);
406
+ const existingWrite = tableWrites.get(key);
407
+ const before = existingWrite ? existingWrite.before : await this.readBase(table, rawKey, ctx);
408
+ const cloned = cloneDeep(state);
409
+ tableWrites.set(key, {
410
+ op: before ? "update" : "create",
411
+ before,
412
+ after: cloned
413
+ });
414
+ return cloneDeep(cloned);
415
+ },
416
+ update: async (rawKey, updates, ctx) => {
417
+ assertSafeKey(rawKey, "key");
418
+ const key = canonicalizeStateKey(rawKey);
419
+ assertSafeKey(key, "key");
420
+ this.assertLiveWriteBudget(table, key);
421
+ const tableWrites = this.getTableWrites(table);
422
+ const existingWrite = tableWrites.get(key);
423
+ const before = existingWrite ? existingWrite.before : await this.readBase(table, rawKey, ctx);
424
+ const current = existingWrite ? existingWrite.after : before;
425
+ const merged = current && typeof current === "object" && updates && typeof updates === "object" ? cloneDeep({
426
+ ...current,
427
+ ...updates
428
+ }) : cloneDeep(updates);
429
+ tableWrites.set(key, {
430
+ op: before ? "update" : "create",
431
+ before,
432
+ after: merged
433
+ });
434
+ return cloneDeep(merged);
435
+ },
436
+ 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);
443
+ },
444
+ delete: async (rawKey, ctx) => {
445
+ assertSafeKey(rawKey, "key");
446
+ const key = canonicalizeStateKey(rawKey);
447
+ assertSafeKey(key, "key");
448
+ this.assertLiveWriteBudget(table, key);
449
+ const tableWrites = this.getTableWrites(table);
450
+ const existingWrite = tableWrites.get(key);
451
+ const before = existingWrite ? existingWrite.before : await this.readBase(table, rawKey, ctx);
452
+ tableWrites.set(key, {
453
+ op: "delete",
454
+ before,
455
+ after: null
456
+ });
457
+ }
458
+ };
459
+ }
460
+ createSavepoint() {
461
+ const clonedWrites = /* @__PURE__ */ new Map();
462
+ for (const [table, map] of this.writes.entries()) {
463
+ const inner = /* @__PURE__ */ new Map();
464
+ for (const [k, v] of map.entries()) inner.set(k, cloneDeep(v));
465
+ clonedWrites.set(table, inner);
466
+ }
467
+ const clonedReads = /* @__PURE__ */ new Map();
468
+ for (const [table, map] of this.reads.entries()) {
469
+ const inner = /* @__PURE__ */ new Map();
470
+ for (const [k, v] of map.entries()) inner.set(k, cloneDeep(v));
471
+ clonedReads.set(table, inner);
472
+ }
473
+ this.savepoints.push({
474
+ writes: clonedWrites,
475
+ reads: clonedReads
476
+ });
477
+ return this.savepoints.length - 1;
478
+ }
479
+ rollbackToSavepoint(savepointId) {
480
+ if (savepointId < 0 || savepointId >= this.savepoints.length) throw new CustomError("INVALID_SAVEPOINT", `Invalid savepoint id ${savepointId}`);
481
+ const restored = this.savepoints[savepointId];
482
+ this.savepoints.length = savepointId;
483
+ this.writes = restored.writes;
484
+ this.reads = restored.reads;
485
+ }
486
+ releaseSavepoint(savepointId) {
487
+ if (savepointId < 0 || savepointId >= this.savepoints.length) throw new CustomError("INVALID_SAVEPOINT", `Invalid savepoint id ${savepointId}`);
488
+ this.savepoints.length = savepointId;
489
+ }
490
+ discard() {
491
+ this.writes.clear();
492
+ this.reads.clear();
493
+ this.savepoints.length = 0;
494
+ }
495
+ getTouchedTableReadKeys() {
496
+ const keys = /* @__PURE__ */ new Set();
497
+ for (const [table, map] of this.reads.entries()) for (const k of map.keys()) keys.add(`${table}:${k}`);
498
+ for (const [table, map] of this.writes.entries()) for (const k of map.keys()) keys.add(`${table}:${k}`);
499
+ return Array.from(keys).sort();
500
+ }
501
+ getTouchedTableWriteKeys() {
502
+ const keys = /* @__PURE__ */ new Set();
503
+ for (const [table, map] of this.writes.entries()) for (const k of map.keys()) keys.add(`${table}:${k}`);
504
+ return Array.from(keys).sort();
505
+ }
506
+ getReadKeys() {
507
+ const keys = /* @__PURE__ */ new Set();
508
+ for (const map of this.reads.values()) for (const k of map.keys()) keys.add(k);
509
+ for (const map of this.writes.values()) for (const k of map.keys()) keys.add(k);
510
+ return Array.from(keys).sort();
511
+ }
512
+ getWriteKeys() {
513
+ const keys = /* @__PURE__ */ new Set();
514
+ for (const map of this.writes.values()) for (const k of map.keys()) keys.add(k);
515
+ return Array.from(keys).sort();
516
+ }
517
+ getStateDiff() {
518
+ const diffs = [];
519
+ for (const [table, map] of this.writes.entries()) for (const [key, entry] of map.entries()) {
520
+ if (isEqual(entry.before, entry.after)) continue;
521
+ diffs.push({
522
+ table,
523
+ key,
524
+ op: entry.op,
525
+ before: cloneDeep(entry.before),
526
+ after: cloneDeep(entry.after)
527
+ });
528
+ }
529
+ return diffs;
530
+ }
531
+ /**
532
+ * Compute net token balance changes across all modified `account` and `stake` rows,
533
+ * subtracting authorized supply mints/burns in `token` / `tokenFactory`, to verify strict zero-sum conservation
534
+ * and guarantee no post-state balance or supply is negative or malformed.
535
+ */
536
+ verifyZeroSumConservation() {
537
+ const balanceDeltas = /* @__PURE__ */ new Map();
538
+ const tokenSupplyDeltas = /* @__PURE__ */ new Map();
539
+ const factorySupplyDeltas = /* @__PURE__ */ new Map();
540
+ const netUnbackedDeltas = {};
541
+ let valid = true;
542
+ const addDelta = (map, tokenAddr, delta) => {
543
+ const cur = map.get(tokenAddr) || new BN(0);
544
+ map.set(tokenAddr, cur.add(delta));
545
+ };
546
+ for (const diff of this.getStateDiff()) if (diff.table === "account" || diff.table === "stake") {
547
+ const beforeTokens = diff.before?.tokens || {};
548
+ const afterTokens = diff.after?.tokens || {};
549
+ const beforePending = diff.before?.pendingTokens || {};
550
+ const afterPending = diff.after?.pendingTokens || {};
551
+ const beforeRevoked = diff.before?.revokedTokens || {};
552
+ const afterRevoked = diff.after?.revokedTokens || {};
553
+ const allKeys = new Set([
554
+ ...Object.keys(beforeTokens),
555
+ ...Object.keys(afterTokens),
556
+ ...Object.keys(beforePending),
557
+ ...Object.keys(afterPending),
558
+ ...Object.keys(beforeRevoked),
559
+ ...Object.keys(afterRevoked)
560
+ ]);
561
+ for (const tAddr of allKeys) {
562
+ if (FORBIDDEN_PATH_SEGMENTS.has(tAddr)) continue;
563
+ const bTok = parseNonNegativeBn(beforeTokens[tAddr]);
564
+ const aTok = parseNonNegativeBn(afterTokens[tAddr]);
565
+ const bPend = parseNonNegativeBn(beforePending[tAddr]);
566
+ const aPend = parseNonNegativeBn(afterPending[tAddr]);
567
+ const bRev = parseNonNegativeBn(beforeRevoked[tAddr]);
568
+ const aRev = parseNonNegativeBn(afterRevoked[tAddr]);
569
+ if (!bTok.ok || !aTok.ok || !bPend.ok || !aPend.ok || !bRev.ok || !aRev.ok) {
570
+ valid = false;
571
+ netUnbackedDeltas[tAddr] = "INVALID_NEGATIVE_OR_MALFORMED_BALANCE";
572
+ continue;
573
+ }
574
+ const bTotal = bTok.value.add(bPend.value).add(bRev.value);
575
+ addDelta(balanceDeltas, tAddr, aTok.value.add(aPend.value).add(aRev.value).sub(bTotal));
576
+ }
577
+ } else if (diff.table === "tokenFactory") {
578
+ const beforeReserveAddr = diff.before?.reserveAddress;
579
+ const afterReserveAddr = diff.after?.reserveAddress;
580
+ if (beforeReserveAddr) {
581
+ const bRes = parseNonNegativeBn(diff.before?.reserveBalance);
582
+ if (!bRes.ok) {
583
+ valid = false;
584
+ netUnbackedDeltas[beforeReserveAddr] = "INVALID_RESERVE_BALANCE";
585
+ } else addDelta(balanceDeltas, beforeReserveAddr, bRes.value.neg());
586
+ }
587
+ if (afterReserveAddr) {
588
+ const aRes = parseNonNegativeBn(diff.after?.reserveBalance);
589
+ if (!aRes.ok) {
590
+ valid = false;
591
+ netUnbackedDeltas[afterReserveAddr] = "INVALID_RESERVE_BALANCE";
592
+ } else addDelta(balanceDeltas, afterReserveAddr, aRes.value);
593
+ }
594
+ const beforeTokenAddr = diff.before?.tokenAddress;
595
+ const afterTokenAddr = diff.after?.tokenAddress;
596
+ if (beforeTokenAddr) {
597
+ const bSup = parseNonNegativeBn(diff.before?.currentSupply);
598
+ if (!bSup.ok) {
599
+ valid = false;
600
+ netUnbackedDeltas[beforeTokenAddr] = "INVALID_FACTORY_SUPPLY";
601
+ } else addDelta(factorySupplyDeltas, beforeTokenAddr, bSup.value.neg());
602
+ }
603
+ if (afterTokenAddr) {
604
+ const aSup = parseNonNegativeBn(diff.after?.currentSupply);
605
+ if (!aSup.ok) {
606
+ valid = false;
607
+ netUnbackedDeltas[afterTokenAddr] = "INVALID_FACTORY_SUPPLY";
608
+ } else addDelta(factorySupplyDeltas, afterTokenAddr, aSup.value);
609
+ }
610
+ } else if (diff.table === "token") {
611
+ const tokenAddr = diff.key;
612
+ const bSup = parseNonNegativeBn(diff.before?.totalSupply);
613
+ const aSup = parseNonNegativeBn(diff.after?.totalSupply);
614
+ if (!bSup.ok || !aSup.ok) {
615
+ valid = false;
616
+ netUnbackedDeltas[tokenAddr] = "INVALID_TOKEN_SUPPLY";
617
+ } else addDelta(tokenSupplyDeltas, tokenAddr, aSup.value.sub(bSup.value));
618
+ }
619
+ const allTokens = new Set([
620
+ ...balanceDeltas.keys(),
621
+ ...tokenSupplyDeltas.keys(),
622
+ ...factorySupplyDeltas.keys()
623
+ ]);
624
+ for (const tAddr of allTokens) {
625
+ if (netUnbackedDeltas[tAddr]) continue;
626
+ const balDelta = balanceDeltas.get(tAddr) || new BN(0);
627
+ const hasTokSup = tokenSupplyDeltas.has(tAddr);
628
+ const hasFacSup = factorySupplyDeltas.has(tAddr);
629
+ let supDelta = new BN(0);
630
+ if (hasTokSup && hasFacSup) {
631
+ const tokSup = tokenSupplyDeltas.get(tAddr);
632
+ const facSup = factorySupplyDeltas.get(tAddr);
633
+ if (!tokSup.eq(facSup)) {
634
+ valid = false;
635
+ netUnbackedDeltas[tAddr] = `SUPPLY_MISMATCH:${tokSup.toString(10)}!=${facSup.toString(10)}`;
636
+ continue;
637
+ }
638
+ supDelta = tokSup;
639
+ } else if (hasTokSup) supDelta = tokenSupplyDeltas.get(tAddr);
640
+ else if (hasFacSup) supDelta = factorySupplyDeltas.get(tAddr);
641
+ const unbacked = balDelta.sub(supDelta);
642
+ if (!unbacked.isZero()) {
643
+ valid = false;
644
+ netUnbackedDeltas[tAddr] = unbacked.toString(10);
645
+ }
646
+ }
647
+ return {
648
+ valid,
649
+ netUnbackedDeltas
650
+ };
651
+ }
652
+ /**
653
+ * Verify that the underlying `baseStateDB` has not changed since the overlay read snapshot was taken
654
+ * (Optimistic Concurrency Control check for 2PC Commit).
655
+ */
656
+ async verifyBaseUnchanged(ctx) {
657
+ for (const [table, readsMap] of this.reads.entries()) {
658
+ const baseTable = this.base?.[table];
659
+ if (typeof baseTable?.get !== "function") continue;
660
+ 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);
664
+ if (!isEqual(currentVal ?? null, expectedVal ?? null)) return false;
665
+ }
666
+ }
667
+ return true;
668
+ }
669
+ async commit(ctx) {
670
+ const diffs = this.getStateDiff();
671
+ const applyDiffs = async (commitCtx) => {
672
+ for (const diff of diffs) {
673
+ const baseTable = this.base?.[diff.table];
674
+ if (!baseTable) continue;
675
+ if (diff.op === "delete") if (typeof baseTable.delete === "function") await baseTable.delete(diff.key, commitCtx);
676
+ else throw new CustomError("UNSUPPORTED_STATE_OPERATION", `Table "${diff.table}" does not support delete operation for key "${diff.key}"`);
677
+ else if (diff.op === "create") {
678
+ if (typeof baseTable.create === "function") await baseTable.create(diff.key, cloneDeep(diff.after), commitCtx);
679
+ else if (typeof baseTable.updateOrCreate === "function") await baseTable.updateOrCreate(null, cloneDeep(diff.after), commitCtx);
680
+ } else if (diff.op === "update") {
681
+ if (typeof baseTable.update === "function") await baseTable.update(diff.key, cloneDeep(diff.after), commitCtx);
682
+ else if (typeof baseTable.updateOrCreate === "function") await baseTable.updateOrCreate(cloneDeep(diff.before), cloneDeep(diff.after), commitCtx);
683
+ }
684
+ }
685
+ };
686
+ if (!Boolean(ctx?.txn) && typeof this.base?.runAsLambda === "function") await this.base.runAsLambda(async (txn) => {
687
+ await applyDiffs(ctx && typeof ctx === "object" ? {
688
+ ...ctx,
689
+ txn
690
+ } : { txn });
691
+ });
692
+ else await applyDiffs(ctx);
693
+ this.writes.clear();
694
+ this.savepoints.length = 0;
695
+ return diffs;
696
+ }
697
+ };
698
+ function createOverlayStateDB(baseStateDB) {
699
+ return new OverlayStateDB(baseStateDB);
700
+ }
701
+ /**
702
+ * Resolve `$steps[i].<path>` references inside a statement's `itx` so output values from
703
+ * earlier statements in a `TransactionBlock` can be piped into subsequent statements (Sui PTB style).
704
+ */
705
+ function resolveStatementReferences(value, stepOutputs, currentStepIndex, depth = 0) {
706
+ if (depth > 16) throw new CustomError("INVALID_TX", "Maximum statement reference nesting depth exceeded");
707
+ if (typeof value === "string") {
708
+ const match = /^\$steps\[(\d+)\]\.(.+)$/.exec(value.trim());
709
+ if (match) {
710
+ const refIndex = Number(match[1]);
711
+ const refPath = match[2];
712
+ if (!Number.isInteger(refIndex) || refIndex < 0 || refIndex >= currentStepIndex) throw new CustomError("INVALID_TX", `Statement at index ${currentStepIndex} cannot reference step ${refIndex}`);
713
+ const resolved = getSafePath(stepOutputs[refIndex], refPath);
714
+ if (resolved === void 0) throw new CustomError("INVALID_TX", `Unresolved reference ${value}`);
715
+ return cloneDeep(resolved);
716
+ }
717
+ return value;
718
+ }
719
+ if (Array.isArray(value)) return value.map((item) => resolveStatementReferences(item, stepOutputs, currentStepIndex, depth + 1));
720
+ if (value && typeof value === "object") {
721
+ const out = {};
722
+ for (const [k, v] of Object.entries(value)) {
723
+ assertSafeKey(k, "property");
724
+ out[k] = resolveStatementReferences(v, stepOutputs, currentStepIndex, depth + 1);
725
+ }
726
+ return out;
727
+ }
728
+ return value;
729
+ }
730
+ function normalizeSingleProtocolTag(rawInput) {
731
+ const raw = typeof rawInput === "string" ? rawInput.trim() : "";
732
+ if (!raw) return "";
733
+ const segments = raw.replace(/^fg:t:/i, "").split(/[:/.]/).filter(Boolean);
734
+ const lastSegment = segments[segments.length - 1] ?? "";
735
+ if (!lastSegment) return "";
736
+ return lastSegment.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[-\s]+/g, "_").toLowerCase().replace(/_+/g, "_").replace(/^_+|_+$/g, "").replace(/(?:_?tx)+$/i, "").replace(/_?v_?\d+$/i, "").replace(/^_+|_+$/g, "");
737
+ }
738
+ function normalizeStatementProtocolTag(stmt) {
739
+ const tagUrl = normalizeSingleProtocolTag(stmt?.typeUrl);
740
+ const tagType = normalizeSingleProtocolTag(stmt?.type);
741
+ if (tagUrl && tagType && tagUrl !== tagType) throw new CustomError("INVALID_TX", `Conflicting statement protocol tags: typeUrl="${String(stmt.typeUrl)}" vs type="${String(stmt.type)}"`);
742
+ return tagUrl || tagType;
743
+ }
744
+ function isExecuteAssetStatement(stmt) {
745
+ const tag = normalizeStatementProtocolTag(stmt);
746
+ return tag === "execute_asset" || tag === "contract_nft" || tag === "executeasset" || tag === "contractnft";
747
+ }
748
+ function isRecursiveBlockStatement(stmt) {
749
+ const tag = normalizeStatementProtocolTag(stmt);
750
+ return tag === "transaction_block" || tag === "transactionblock" || tag === "cross_chain_purchase" || tag === "crosschainpurchase";
751
+ }
752
+ function extractInlineStatementTemplates(stmt) {
753
+ const itx = stmt?.itx && typeof stmt.itx === "object" ? stmt.itx : null;
754
+ if (!itx) return [];
755
+ const collected = [];
756
+ if (Array.isArray(itx.statementTemplates)) collected.push(...itx.statementTemplates);
757
+ if (Array.isArray(itx.statements)) collected.push(...itx.statements);
758
+ if (Array.isArray(itx.purchaseStatements)) collected.push(...itx.purchaseStatements);
759
+ if (Array.isArray(itx.data?.value?.statementTemplates)) collected.push(...itx.data.value.statementTemplates);
760
+ if (Array.isArray(itx.contractAsset?.data?.value?.statementTemplates)) collected.push(...itx.contractAsset.data.value.statementTemplates);
761
+ return collected;
762
+ }
763
+ function resolveAndValidateExecuteAssetTarget(stmt, allowStepRef) {
764
+ const itx = stmt?.itx && typeof stmt.itx === "object" ? stmt.itx : {};
765
+ const candidates = [];
766
+ for (const raw of [
767
+ itx.address,
768
+ itx.contractAsset?.address,
769
+ itx.contractNft
770
+ ]) if (typeof raw === "string" && raw.trim()) {
771
+ const trimmed = raw.trim();
772
+ if (trimmed.startsWith("$steps[")) {
773
+ if (!allowStepRef) throw new CustomError("INVALID_TX", `Unresolved $steps reference in execute_asset target: ${trimmed}`);
774
+ candidates.push(trimmed);
775
+ } else {
776
+ const norm = normalizeDidOrKey(trimmed);
777
+ if (!norm) throw new CustomError("INVALID_TX", `Invalid execute_asset target address: ${trimmed}`);
778
+ candidates.push(norm);
779
+ }
780
+ }
781
+ if (candidates.length === 0) throw new CustomError("INVALID_TX", "execute_asset statement requires a valid target asset address");
782
+ const canonical = candidates[0];
783
+ for (let i = 1; i < candidates.length; i++) if (candidates[i] !== canonical) throw new CustomError("INVALID_TX", `Conflicting execute_asset target addresses in statement: ${canonical} vs ${candidates[i]}`);
784
+ return canonical;
785
+ }
786
+ /**
787
+ * Enforces `MAX_EXECUTE_ASSET_DEPTH = 1`:
788
+ * Any statement inside `statementTemplates` (Depth 1) MUST be a leaf atomic primitive and CANNOT
789
+ * recursively invoke `execute_asset`, `contract_nft`, `transaction_block`, or carry nested `statementTemplates`.
790
+ */
791
+ function assertLeafStatementTemplateOnly(templateStmt, label = "statementTemplate") {
792
+ if (!templateStmt || typeof templateStmt !== "object" || Array.isArray(templateStmt)) throw new CustomError("INVALID_CONTRACT_NFT", `${label} must be a valid statement object`);
793
+ if (isExecuteAssetStatement(templateStmt) || isRecursiveBlockStatement(templateStmt)) throw new CustomError("RECURSIVE_EXECUTE_ASSET_FORBIDDEN", `${label} cannot recursively invoke ${String(templateStmt.typeUrl || templateStmt.type)} (MAX_EXECUTE_ASSET_DEPTH = ${MAX_EXECUTE_ASSET_DEPTH})`);
794
+ if (extractInlineStatementTemplates(templateStmt).length > 0) throw new CustomError("RECURSIVE_EXECUTE_ASSET_FORBIDDEN", `${label} cannot contain nested statementTemplates (MAX_EXECUTE_ASSET_DEPTH = ${MAX_EXECUTE_ASSET_DEPTH})`);
795
+ }
796
+ function resolveEffectiveResourceBudget(block, nodeBudget) {
797
+ const clamp = (userVal, nodeVal, defaultCeiling, hardCeiling, label) => {
798
+ const rawNode = nodeVal ?? defaultCeiling;
799
+ if (!Number.isSafeInteger(rawNode) || rawNode < 1 || rawNode > hardCeiling) throw new CustomError("INVALID_TX", `Invalid node resourceBudget.${label}: ${String(rawNode)}`);
800
+ if (userVal === void 0) return rawNode;
801
+ if (!Number.isSafeInteger(userVal) || userVal < 1) throw new CustomError("INVALID_TX", `Invalid block resourceBudget.${label}: ${String(userVal)}`);
802
+ if (userVal > rawNode) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock requested resourceBudget.${label} (${userVal}) exceeding node ceiling (${rawNode})`);
803
+ return userVal;
804
+ };
805
+ const userBudget = block?.resourceBudget;
806
+ return Object.freeze({
807
+ maxBytes: clamp(userBudget?.maxBytes, nodeBudget?.maxBytes, MAX_TX_BLOCK_BYTES, 262144, "maxBytes"),
808
+ maxTopLevelStatements: clamp(userBudget?.maxTopLevelStatements, nodeBudget?.maxTopLevelStatements, MAX_TX_BLOCK_TOP_LEVEL_STATEMENTS, HARD_MAX_TX_BLOCK_STATEMENTS, "maxTopLevelStatements"),
809
+ maxTotalExpandedStatements: clamp(userBudget?.maxTotalExpandedStatements, nodeBudget?.maxTotalExpandedStatements, MAX_TX_BLOCK_TOTAL_EXPANDED_STATEMENTS, 128, "maxTotalExpandedStatements"),
810
+ maxReadKeys: clamp(userBudget?.maxReadKeys, nodeBudget?.maxReadKeys, MAX_TX_BLOCK_READ_KEYS, 256, "maxReadKeys"),
811
+ maxWriteKeys: clamp(userBudget?.maxWriteKeys, nodeBudget?.maxWriteKeys, MAX_TX_BLOCK_WRITE_KEYS, 128, "maxWriteKeys"),
812
+ maxStateDiffEntries: clamp(userBudget?.maxStateDiffEntries, nodeBudget?.maxStateDiffEntries, MAX_TX_BLOCK_STATE_DIFF_ENTRIES, 128, "maxStateDiffEntries"),
813
+ maxExecuteAssetCallsPerBlock: clamp(userBudget?.maxExecuteAssetCallsPerBlock, nodeBudget?.maxExecuteAssetCallsPerBlock, MAX_EXECUTE_ASSET_CALLS_PER_BLOCK, 16, "maxExecuteAssetCallsPerBlock")
814
+ });
815
+ }
816
+ /**
817
+ * Issue #1253 Guardrail #1 & #3:
818
+ * Statically validates the 4D resource budget (byte size, top-level & expanded statement counts,
819
+ * static read/write I/O footprint keys, and single-layer `execute_asset` depth/call limits)
820
+ * BEFORE touching `OverlayStateDB`.
821
+ */
822
+ function assertTransactionBlockResourceBudget(block, nodeBudget) {
823
+ if (!block || typeof block !== "object" || !Array.isArray(block.statements) || block.statements.length === 0) throw new CustomError("INVALID_TX", "TransactionBlock must contain at least one statement");
824
+ const budget = resolveEffectiveResourceBudget(block, nodeBudget);
825
+ if (block.statements.length > budget.maxTopLevelStatements) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock top-level statements (${block.statements.length}) exceeds maxTopLevelStatements (${budget.maxTopLevelStatements})`);
826
+ let serialized;
827
+ try {
828
+ serialized = JSON.stringify(block);
829
+ } catch {
830
+ throw new CustomError("INVALID_TX", "TransactionBlock must be valid JSON-serializable data");
831
+ }
832
+ const byteSize = Buffer.byteLength(serialized, "utf8");
833
+ if (byteSize > budget.maxBytes) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock byte size (${byteSize}) exceeds maxBytes (${budget.maxBytes})`);
834
+ let staticExpandedStatements = 0;
835
+ let executeAssetCalls = 0;
836
+ const seenExecuteAssets = /* @__PURE__ */ new Set();
837
+ for (let i = 0; i < block.statements.length; i++) {
838
+ const stmt = block.statements[i];
839
+ if (!stmt || typeof stmt !== "object") throw new CustomError("INVALID_TX", `statements[${i}] must be an object`);
840
+ if (isRecursiveBlockStatement(stmt)) throw new CustomError("RECURSIVE_TX_BLOCK_FORBIDDEN", `statements[${i}] cannot recursively nest transaction_block`);
841
+ const inlineTemplates = extractInlineStatementTemplates(stmt);
842
+ for (let tIdx = 0; tIdx < inlineTemplates.length; tIdx++) assertLeafStatementTemplateOnly(inlineTemplates[tIdx], `statements[${i}].statementTemplates[${tIdx}]`);
843
+ if (isExecuteAssetStatement(stmt)) {
844
+ executeAssetCalls += 1;
845
+ if (executeAssetCalls > budget.maxExecuteAssetCallsPerBlock) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock execute_asset calls (${executeAssetCalls}) exceeds maxExecuteAssetCallsPerBlock (${budget.maxExecuteAssetCallsPerBlock})`);
846
+ const targetAddr = resolveAndValidateExecuteAssetTarget(stmt, true);
847
+ if (targetAddr && !targetAddr.startsWith("$steps[")) {
848
+ if (seenExecuteAssets.has(targetAddr)) throw new CustomError("REENTRANT_EXECUTE_ASSET_FORBIDDEN", `execute_asset target ${targetAddr} cannot be invoked multiple times in the same TransactionBlock`);
849
+ seenExecuteAssets.add(targetAddr);
850
+ }
851
+ staticExpandedStatements += Math.max(1, inlineTemplates.length);
852
+ } else staticExpandedStatements += 1;
853
+ }
854
+ if (staticExpandedStatements > budget.maxTotalExpandedStatements) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock total expanded statements (${staticExpandedStatements}) exceeds maxTotalExpandedStatements (${budget.maxTotalExpandedStatements})`);
855
+ const staticFootprint = extractStateFootprint(block);
856
+ if (staticFootprint.readSet.length > budget.maxReadKeys) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock static readSet (${staticFootprint.readSet.length}) exceeds maxReadKeys (${budget.maxReadKeys})`);
857
+ if (staticFootprint.writeSet.length > budget.maxWriteKeys) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock static writeSet (${staticFootprint.writeSet.length}) exceeds maxWriteKeys (${budget.maxWriteKeys})`);
858
+ return {
859
+ budget,
860
+ byteSize,
861
+ staticExpandedStatements,
862
+ executeAssetTargets: Array.from(seenExecuteAssets),
863
+ staticFootprint
864
+ };
865
+ }
866
+ /**
867
+ * Computes net per-account liquid spendable token deltas and asset ownership changes from `StateDiffEntry[]`.
868
+ * - RT-1253-3: Strictly attributes account token deltas to `diff.key` on `diff.table === 'account'` (never `diff.after.owner` or `stake`).
869
+ * - RT-1253-4: Uses `min(liquidDelta, totalDelta)` so locking liquid tokens into `pendingTokens` is caught as outflow, while fake `pendingTokens` credits cannot spoof `minTokenInflow`.
870
+ * - RT-1253-5: Rejects malformed/negative token balances immediately with `ACCOUNTING_INVARIANT_VIOLATION`.
871
+ * - RT-1253-9: Checks `!diff.before?.consumedTime` symmetrically on `beforeOwner`.
872
+ */
873
+ function computeAccountAndAssetNetEffects(stateDiff) {
874
+ const accountTokenNetDeltas = /* @__PURE__ */ new Map();
875
+ const outgoingAssetsByOwner = /* @__PURE__ */ new Map();
876
+ const incomingAssetsByOwner = /* @__PURE__ */ new Map();
877
+ const addAccountTokenDelta = (accountDid, tokenAddr, delta) => {
878
+ let tokenMap = accountTokenNetDeltas.get(accountDid);
879
+ if (!tokenMap) {
880
+ tokenMap = /* @__PURE__ */ new Map();
881
+ accountTokenNetDeltas.set(accountDid, tokenMap);
882
+ }
883
+ const cur = tokenMap.get(tokenAddr) || new BN(0);
884
+ tokenMap.set(tokenAddr, cur.add(delta));
885
+ };
886
+ for (const diff of stateDiff) if (diff.table === "account") {
887
+ const beforeTokens = diff.before?.tokens || {};
888
+ const afterTokens = diff.after?.tokens || {};
889
+ const beforePending = diff.before?.pendingTokens || {};
890
+ const afterPending = diff.after?.pendingTokens || {};
891
+ const allToks = new Set([
892
+ ...Object.keys(beforeTokens),
893
+ ...Object.keys(afterTokens),
894
+ ...Object.keys(beforePending),
895
+ ...Object.keys(afterPending)
896
+ ]);
897
+ for (const tAddr of allToks) {
898
+ if (FORBIDDEN_PATH_SEGMENTS.has(tAddr)) continue;
899
+ const bTok = parseNonNegativeBn(beforeTokens[tAddr]);
900
+ const aTok = parseNonNegativeBn(afterTokens[tAddr]);
901
+ const bPend = parseNonNegativeBn(beforePending[tAddr]);
902
+ const aPend = parseNonNegativeBn(afterPending[tAddr]);
903
+ 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
+ const liquidDelta = aTok.value.sub(bTok.value);
905
+ const totalDelta = aTok.value.add(aPend.value).sub(bTok.value.add(bPend.value));
906
+ const effectiveDelta = liquidDelta.lt(totalDelta) ? liquidDelta : totalDelta;
907
+ if (!effectiveDelta.isZero()) addAccountTokenDelta(diff.key, tAddr, effectiveDelta);
908
+ }
909
+ } else if (diff.table === "asset") {
910
+ const beforeOwner = typeof diff.before?.owner === "string" && !diff.before?.consumedTime ? diff.before.owner : null;
911
+ const afterOwner = diff.op !== "delete" && typeof diff.after?.owner === "string" && !diff.after?.consumedTime ? diff.after.owner : null;
912
+ if (beforeOwner && beforeOwner !== afterOwner) {
913
+ const set = outgoingAssetsByOwner.get(beforeOwner) || /* @__PURE__ */ new Set();
914
+ set.add(diff.key);
915
+ outgoingAssetsByOwner.set(beforeOwner, set);
916
+ }
917
+ if (afterOwner && afterOwner !== beforeOwner) {
918
+ const set = incomingAssetsByOwner.get(afterOwner) || /* @__PURE__ */ new Set();
919
+ set.add(diff.key);
920
+ incomingAssetsByOwner.set(afterOwner, set);
921
+ }
922
+ }
923
+ return {
924
+ accountTokenNetDeltas,
925
+ outgoingAssetsByOwner,
926
+ incomingAssetsByOwner
927
+ };
928
+ }
929
+ /**
930
+ * Issue #1253 Guardrail #2:
931
+ * Enforces user-signed `TransactionBlockPostConditions` against the actual `OverlayStateDB` diff
932
+ * prior to committing. Any excess token outflow, missing minimum inflow, or unauthorized asset transfer
933
+ * triggers an immediate `POST_CONDITION_VIOLATION` rollback.
934
+ */
935
+ async function verifyTransactionBlockPostConditions(block, stateDiff, overlay) {
936
+ const pc = block.postConditions;
937
+ if (!pc) return;
938
+ if (typeof pc !== "object" || Array.isArray(pc)) throw new CustomError("INVALID_TX", "TransactionBlock postConditions must be an object");
939
+ const strictZeroUnlisted = pc.strictZeroUnlistedOutflow !== false;
940
+ const { accountTokenNetDeltas, outgoingAssetsByOwner } = computeAccountAndAssetNetEffects(stateDiff);
941
+ if (pc.allowedOutgoingAssets !== void 0) {
942
+ if (typeof pc.allowedOutgoingAssets !== "object" || pc.allowedOutgoingAssets === null || Array.isArray(pc.allowedOutgoingAssets)) throw new CustomError("INVALID_TX", "postConditions.allowedOutgoingAssets must be an object");
943
+ for (const [accountDid, allowedList] of Object.entries(pc.allowedOutgoingAssets)) {
944
+ assertSafeKey(accountDid, "postConditions.allowedOutgoingAssets.account");
945
+ if (!Array.isArray(allowedList)) throw new CustomError("INVALID_TX", `postConditions.allowedOutgoingAssets[${accountDid}] must be an array`);
946
+ for (const assetDid of allowedList) assertSafeKey(assetDid, "postConditions.allowedOutgoingAssets.asset");
947
+ }
948
+ }
949
+ if (pc.maxTokenOutflow !== void 0) {
950
+ if (typeof pc.maxTokenOutflow !== "object" || pc.maxTokenOutflow === null || Array.isArray(pc.maxTokenOutflow)) throw new CustomError("INVALID_TX", "postConditions.maxTokenOutflow must be an object");
951
+ for (const [accountDid, tokenLimits] of Object.entries(pc.maxTokenOutflow)) {
952
+ assertSafeKey(accountDid, "postConditions.maxTokenOutflow.account");
953
+ if (!tokenLimits || typeof tokenLimits !== "object" || Array.isArray(tokenLimits)) throw new CustomError("INVALID_TX", `postConditions.maxTokenOutflow[${accountDid}] must be an object`);
954
+ for (const [tokenAddr, maxOutStr] of Object.entries(tokenLimits)) {
955
+ assertSafeKey(tokenAddr, "postConditions.maxTokenOutflow.token");
956
+ const parsedMax = parseNonNegativeBn(maxOutStr);
957
+ if (!parsedMax.ok) throw new CustomError("INVALID_TX", `Invalid postConditions.maxTokenOutflow[${accountDid}][${tokenAddr}]: ${String(maxOutStr)}`);
958
+ const netDelta = accountTokenNetDeltas.get(accountDid)?.get(tokenAddr) || new BN(0);
959
+ if (netDelta.isNeg()) {
960
+ const actualOutflow = netDelta.neg();
961
+ if (actualOutflow.gt(parsedMax.value)) throw new CustomError("POST_CONDITION_VIOLATION", `Account ${accountDid} net outflow of token ${tokenAddr} (${actualOutflow.toString(10)}) exceeds signed maxTokenOutflow (${parsedMax.value.toString(10)})`);
962
+ }
963
+ }
964
+ }
965
+ }
966
+ if (strictZeroUnlisted) {
967
+ const protectedAccounts = new Set([
968
+ block.from,
969
+ ...block.delegator ? [block.delegator] : [],
970
+ ...Object.keys(pc.maxTokenOutflow || {}),
971
+ ...Object.keys(pc.allowedOutgoingAssets || {}),
972
+ ...Object.keys(pc.minTokenInflow || {}),
973
+ ...Object.keys(pc.mustOwnAssetsAfter || {})
974
+ ]);
975
+ for (const accountDid of protectedAccounts) {
976
+ const tokenMap = accountTokenNetDeltas.get(accountDid);
977
+ if (tokenMap) {
978
+ const accountOutflowCaps = pc.maxTokenOutflow && Object.prototype.hasOwnProperty.call(pc.maxTokenOutflow, accountDid) ? pc.maxTokenOutflow[accountDid] : void 0;
979
+ for (const [tokenAddr, netDelta] of tokenMap.entries()) if (netDelta.isNeg()) {
980
+ if ((accountOutflowCaps && Object.prototype.hasOwnProperty.call(accountOutflowCaps, tokenAddr) ? accountOutflowCaps[tokenAddr] : void 0) === void 0) throw new CustomError("POST_CONDITION_VIOLATION", `Account ${accountDid} suffered unlisted net token outflow of ${netDelta.neg().toString(10)} on token ${tokenAddr} (strictZeroUnlistedOutflow=true)`);
981
+ }
982
+ }
983
+ const outgoingAssets = outgoingAssetsByOwner.get(accountDid);
984
+ if (outgoingAssets && outgoingAssets.size > 0) {
985
+ const allowedSet = new Set(pc.allowedOutgoingAssets?.[accountDid] || []);
986
+ for (const assetDid of outgoingAssets) if (!allowedSet.has(assetDid)) throw new CustomError("POST_CONDITION_VIOLATION", `Account ${accountDid} lost ownership of unlisted asset ${assetDid} (not in postConditions.allowedOutgoingAssets)`);
987
+ }
988
+ }
989
+ } else if (pc.allowedOutgoingAssets) for (const [accountDid, allowedList] of Object.entries(pc.allowedOutgoingAssets)) {
990
+ const allowedSet = new Set(allowedList);
991
+ const outgoingAssets = outgoingAssetsByOwner.get(accountDid);
992
+ if (outgoingAssets) {
993
+ for (const assetDid of outgoingAssets) if (!allowedSet.has(assetDid)) throw new CustomError("POST_CONDITION_VIOLATION", `Account ${accountDid} lost ownership of asset ${assetDid} not in allowedOutgoingAssets`);
994
+ }
995
+ }
996
+ if (pc.minTokenInflow !== void 0) {
997
+ if (typeof pc.minTokenInflow !== "object" || pc.minTokenInflow === null || Array.isArray(pc.minTokenInflow)) throw new CustomError("INVALID_TX", "postConditions.minTokenInflow must be an object");
998
+ for (const [accountDid, tokenMinimums] of Object.entries(pc.minTokenInflow)) {
999
+ assertSafeKey(accountDid, "postConditions.minTokenInflow.account");
1000
+ if (!tokenMinimums || typeof tokenMinimums !== "object" || Array.isArray(tokenMinimums)) throw new CustomError("INVALID_TX", `postConditions.minTokenInflow[${accountDid}] must be an object`);
1001
+ for (const [tokenAddr, minInStr] of Object.entries(tokenMinimums)) {
1002
+ assertSafeKey(tokenAddr, "postConditions.minTokenInflow.token");
1003
+ const parsedMin = parseNonNegativeBn(minInStr);
1004
+ if (!parsedMin.ok) throw new CustomError("INVALID_TX", `Invalid postConditions.minTokenInflow[${accountDid}][${tokenAddr}]: ${String(minInStr)}`);
1005
+ const netDelta = accountTokenNetDeltas.get(accountDid)?.get(tokenAddr) || new BN(0);
1006
+ if (netDelta.lt(parsedMin.value)) throw new CustomError("POST_CONDITION_VIOLATION", `Account ${accountDid} net inflow of token ${tokenAddr} (${netDelta.toString(10)}) is below signed minTokenInflow (${parsedMin.value.toString(10)})`);
1007
+ }
1008
+ }
1009
+ }
1010
+ if (pc.mustOwnAssetsAfter !== void 0) {
1011
+ if (typeof pc.mustOwnAssetsAfter !== "object" || pc.mustOwnAssetsAfter === null || Array.isArray(pc.mustOwnAssetsAfter)) throw new CustomError("INVALID_TX", "postConditions.mustOwnAssetsAfter must be an object");
1012
+ for (const [accountDid, requiredAssets] of Object.entries(pc.mustOwnAssetsAfter)) {
1013
+ assertSafeKey(accountDid, "postConditions.mustOwnAssetsAfter.account");
1014
+ if (!Array.isArray(requiredAssets)) throw new CustomError("INVALID_TX", `postConditions.mustOwnAssetsAfter[${accountDid}] must be an array`);
1015
+ for (const assetDid of requiredAssets) {
1016
+ assertSafeKey(assetDid, "postConditions.mustOwnAssetsAfter.asset");
1017
+ const assetRecord = typeof overlay.asset?.get === "function" ? await overlay.asset.get(assetDid) : null;
1018
+ if (!assetRecord || assetRecord.owner !== accountDid || Boolean(assetRecord.consumedTime)) throw new CustomError("POST_CONDITION_VIOLATION", `Account ${accountDid} does not own unconsumed asset ${assetDid} after TransactionBlock execution`);
1019
+ }
1020
+ }
1021
+ }
1022
+ }
1023
+ /**
1024
+ * 3. SQL-Style Multi-Statement `TransactionBlock` Execution + Zero-Side-Effect `Dry-Run`
1025
+ * + Issue #1253 Hard Guardrails (4D Size/I/O Budget, Enforced PostConditions, Single-Layer execute_asset Sandbox)
1026
+ */
1027
+ async function executeTransactionBlock(block, options) {
1028
+ if (!block || !Array.isArray(block.statements) || block.statements.length === 0) throw new CustomError("INVALID_TX", "TransactionBlock must contain at least one statement");
1029
+ if (block.statements.length > HARD_MAX_TX_BLOCK_STATEMENTS) throw new CustomError("INVALID_TX", `TransactionBlock exceeds maximum of ${HARD_MAX_TX_BLOCK_STATEMENTS} statements`);
1030
+ assertSafeKey(block.from, "block.from");
1031
+ if (block.delegator !== void 0) assertSafeKey(block.delegator, "block.delegator");
1032
+ const { budget, staticFootprint } = assertTransactionBlockResourceBudget(block, options.resourceBudget);
1033
+ const blockId = block.id || Hasher.SHA3.hash256(Uint8Array.from(Buffer.from(JSON.stringify({
1034
+ from: block.from,
1035
+ statements: block.statements
1036
+ }))));
1037
+ const dryRun = Boolean(options.dryRun);
1038
+ const enforceZeroSum = block.enforceZeroSum !== false;
1039
+ const overlay = options.statedb instanceof OverlayStateDB ? options.statedb : createOverlayStateDB(options.statedb);
1040
+ const topSavepoint = overlay.createSavepoint();
1041
+ overlay.setRuntimeIoBudget({
1042
+ maxReadKeys: budget.maxReadKeys,
1043
+ maxWriteKeys: budget.maxWriteKeys,
1044
+ staticReadSet: staticFootprint.readSet,
1045
+ staticWriteSet: staticFootprint.writeSet
1046
+ });
1047
+ const stepOutputs = [];
1048
+ let totalExpandedStatements = 0;
1049
+ let runtimeExecuteAssetCalls = 0;
1050
+ const runtimeInvokedExecuteAssets = /* @__PURE__ */ new Set();
1051
+ const protectedExecuteAssetSnapshots = /* @__PURE__ */ new Map();
1052
+ const assertRuntimeIoBudgetAndAssetImmutability = async () => {
1053
+ const liveReadCount = Math.max(new Set([...staticFootprint.readSet, ...overlay.getReadKeys()]).size, overlay.getTouchedTableReadKeys().length);
1054
+ if (liveReadCount > budget.maxReadKeys) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock runtime read key count (${liveReadCount}) exceeds maxReadKeys (${budget.maxReadKeys})`);
1055
+ const liveWriteCount = Math.max(new Set([...staticFootprint.writeSet, ...overlay.getWriteKeys()]).size, overlay.getTouchedTableWriteKeys().length);
1056
+ if (liveWriteCount > budget.maxWriteKeys) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock runtime write key count (${liveWriteCount}) exceeds maxWriteKeys (${budget.maxWriteKeys})`);
1057
+ const currentDiffCount = overlay.getStateDiff().length;
1058
+ if (currentDiffCount > budget.maxStateDiffEntries) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock runtime stateDiff entry count (${currentDiffCount}) exceeds maxStateDiffEntries (${budget.maxStateDiffEntries})`);
1059
+ for (const [assetAddr, initialSnapshot] of protectedExecuteAssetSnapshots.entries()) {
1060
+ if (overlay.hasTableWrite("asset", assetAddr)) throw new CustomError("IMMUTABLE_ACTIVE_EXECUTE_ASSET", `Active execute_asset ${assetAddr} cannot be created, deleted, consumed, transferred, or mutated during TransactionBlock execution`);
1061
+ if (initialSnapshot && typeof overlay.asset?.get === "function") {
1062
+ const currentAsset = await overlay.asset.get(assetAddr);
1063
+ if (!currentAsset || Boolean(currentAsset.consumedTime) || currentAsset.owner !== initialSnapshot.owner || !isEqual(currentAsset.data, initialSnapshot.data)) throw new CustomError("IMMUTABLE_ACTIVE_EXECUTE_ASSET", `Active execute_asset ${assetAddr} cannot be deleted, consumed, transferred, or have its contract payload mutated during TransactionBlock execution`);
1064
+ }
1065
+ }
1066
+ };
1067
+ try {
1068
+ for (let i = 0; i < block.statements.length; i++) {
1069
+ const rawStmt = block.statements[i];
1070
+ if (rawStmt.from !== void 0) assertSafeKey(rawStmt.from, `statements[${i}].from`);
1071
+ if (rawStmt.delegator !== void 0) assertSafeKey(rawStmt.delegator, `statements[${i}].delegator`);
1072
+ if (isExecuteAssetStatement(rawStmt) && rawStmt.itx?.args !== void 0) assertNoStepRefInValue(rawStmt.itx.args);
1073
+ const resolvedItx = resolveStatementReferences(rawStmt.itx, stepOutputs, i);
1074
+ const resolvedItxBytes = Buffer.byteLength(JSON.stringify(resolvedItx ?? {}), "utf8");
1075
+ if (resolvedItxBytes > budget.maxBytes) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock resolved statement[${i}] byte size (${resolvedItxBytes}) exceeds maxBytes (${budget.maxBytes})`);
1076
+ const resolvedStmt = {
1077
+ ...rawStmt,
1078
+ from: rawStmt.from || block.from,
1079
+ delegator: rawStmt.delegator ?? block.delegator,
1080
+ itx: resolvedItx
1081
+ };
1082
+ if (isExecuteAssetStatement(resolvedStmt)) {
1083
+ runtimeExecuteAssetCalls += 1;
1084
+ if (runtimeExecuteAssetCalls > budget.maxExecuteAssetCallsPerBlock) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock execute_asset calls (${runtimeExecuteAssetCalls}) exceeds maxExecuteAssetCallsPerBlock (${budget.maxExecuteAssetCallsPerBlock})`);
1085
+ const targetAddr = resolveAndValidateExecuteAssetTarget(resolvedStmt, false);
1086
+ if (runtimeInvokedExecuteAssets.has(targetAddr)) throw new CustomError("REENTRANT_EXECUTE_ASSET_FORBIDDEN", `execute_asset target ${targetAddr} cannot be invoked multiple times or recursively in the same TransactionBlock`);
1087
+ runtimeInvokedExecuteAssets.add(targetAddr);
1088
+ const baseSnap = await overlay.getBaseSnapshot("asset", targetAddr);
1089
+ if (!protectedExecuteAssetSnapshots.has(targetAddr)) protectedExecuteAssetSnapshots.set(targetAddr, baseSnap ? cloneDeep(baseSnap) : null);
1090
+ await assertRuntimeIoBudgetAndAssetImmutability();
1091
+ const inlineAsset = resolvedStmt.itx?.contractAsset || null;
1092
+ if (baseSnap && inlineAsset && !isEqual(inlineAsset, baseSnap)) throw new CustomError("IMMUTABLE_ACTIVE_EXECUTE_ASSET", `Inline itx.contractAsset for ${targetAddr} conflicts with authoritative on-chain ContractNFT state`);
1093
+ const contractCandidate = baseSnap || inlineAsset || null;
1094
+ const isAuthoritativeOnChainAsset = Boolean(baseSnap);
1095
+ if (options.inlineExpandExecuteAsset !== false && contractCandidate && contractCandidate.data?.type === "json" && contractCandidate.data?.value?.kind === CONTRACT_NFT_KIND) {
1096
+ if (contractCandidate.consumedTime) throw new CustomError("CONSUMED_ASSET", "Cannot execute a consumed Contract Asset");
1097
+ const payload = contractCandidate.data.value;
1098
+ if (!Array.isArray(payload.statementTemplates) || payload.statementTemplates.length === 0) throw new CustomError("INVALID_CONTRACT_NFT", "execute_asset must contain at least one statementTemplate");
1099
+ if (payload.statementTemplates.length > MAX_CONTRACT_NFT_STATEMENTS) throw new CustomError("CONTRACT_BUDGET_EXCEEDED", `execute_asset statementTemplates count (${payload.statementTemplates.length}) exceeds MAX_CONTRACT_NFT_STATEMENTS (${MAX_CONTRACT_NFT_STATEMENTS})`);
1100
+ for (let tIdx = 0; tIdx < payload.statementTemplates.length; tIdx++) assertLeafStatementTemplateOnly(payload.statementTemplates[tIdx], `statements[${i}].execute_asset.statementTemplates[${tIdx}]`);
1101
+ const callerDid = resolvedStmt.from || block.from;
1102
+ if (callerDid !== block.from && (!block.delegator || callerDid !== block.delegator)) throw new CustomError("FORBIDDEN", `execute_asset caller (${callerDid}) must match authenticated TransactionBlock signer (${block.from}${block.delegator ? ` or delegator ${block.delegator}` : ""})`);
1103
+ const callArgs = resolvedStmt.itx?.args && typeof resolvedStmt.itx.args === "object" ? resolvedStmt.itx.args : {};
1104
+ assertNoStepRefInValue(callArgs);
1105
+ if (payload.allowedCallers !== void 0 && !Array.isArray(payload.allowedCallers)) throw new CustomError("INVALID_CONTRACT_NFT", "execute_asset allowedCallers must be an array of DIDs");
1106
+ if (Array.isArray(payload.allowedCallers) && payload.allowedCallers.length > 0 && !payload.allowedCallers.includes(callerDid)) throw new CustomError("FORBIDDEN", `Caller ${callerDid} is not authorized by execute_asset allowlist`);
1107
+ const canonicalContractAddr = normalizeDidOrKey(contractCandidate.address) || targetAddr;
1108
+ const bindings = {
1109
+ caller: callerDid,
1110
+ args: callArgs,
1111
+ contract: {
1112
+ address: canonicalContractAddr,
1113
+ owner: contractCandidate.owner,
1114
+ name: payload.name
1115
+ }
1116
+ };
1117
+ for (const guard of payload.guards || []) if (!evaluateGuardPredicate(guard, bindings)) throw new CustomError("CONTRACT_GUARD_FAILED", `execute_asset guard failed: ${guard.field} ${guard.op} ${JSON.stringify(guard.value)}`);
1118
+ const permittedSenders = new Set(isAuthoritativeOnChainAsset ? [
1119
+ callerDid,
1120
+ canonicalContractAddr,
1121
+ contractCandidate.address,
1122
+ contractCandidate.owner
1123
+ ] : [
1124
+ callerDid,
1125
+ canonicalContractAddr,
1126
+ contractCandidate.address
1127
+ ]);
1128
+ const instantiatedTemplates = payload.statementTemplates.map((tpl) => {
1129
+ const resolvedFrom = tpl.from ? interpolateContractTemplate(tpl.from, bindings) : canonicalContractAddr;
1130
+ if (!permittedSenders.has(resolvedFrom)) throw new CustomError("FORBIDDEN", `execute_asset statement cannot impersonate unauthorized sender ${String(resolvedFrom)}`);
1131
+ return {
1132
+ ...tpl,
1133
+ from: resolvedFrom,
1134
+ delegator: canonicalContractAddr,
1135
+ itx: interpolateContractTemplate(tpl.itx, bindings)
1136
+ };
1137
+ });
1138
+ const expandedBytes = Buffer.byteLength(JSON.stringify(instantiatedTemplates), "utf8");
1139
+ if (expandedBytes > budget.maxBytes) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock expanded execute_asset byte size (${expandedBytes}) exceeds maxBytes (${budget.maxBytes})`);
1140
+ if (totalExpandedStatements + instantiatedTemplates.length > budget.maxTotalExpandedStatements) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock expanded statements (${totalExpandedStatements + instantiatedTemplates.length}) exceeds maxTotalExpandedStatements (${budget.maxTotalExpandedStatements})`);
1141
+ const templateOutputs = [];
1142
+ for (let tIdx = 0; tIdx < instantiatedTemplates.length; tIdx++) {
1143
+ const tplStmt = instantiatedTemplates[tIdx];
1144
+ totalExpandedStatements += 1;
1145
+ const tplOut = await options.executeStatement(tplStmt, overlay, {
1146
+ stepIndex: i,
1147
+ stepOutputs,
1148
+ block
1149
+ }) || {};
1150
+ templateOutputs.push(cloneDeep(tplOut));
1151
+ await assertRuntimeIoBudgetAndAssetImmutability();
1152
+ }
1153
+ const lastTplOut = templateOutputs.length > 0 ? templateOutputs[templateOutputs.length - 1] : {};
1154
+ stepOutputs.push(cloneDeep({
1155
+ ...lastTplOut,
1156
+ executedAsset: canonicalContractAddr,
1157
+ templateOutputs
1158
+ }));
1159
+ continue;
1160
+ }
1161
+ const inlineTemplates = extractInlineStatementTemplates(resolvedStmt);
1162
+ for (let tIdx = 0; tIdx < inlineTemplates.length; tIdx++) assertLeafStatementTemplateOnly(inlineTemplates[tIdx], `statements[${i}].statementTemplates[${tIdx}]`);
1163
+ totalExpandedStatements += Math.max(1, inlineTemplates.length);
1164
+ } else totalExpandedStatements += 1;
1165
+ if (totalExpandedStatements > budget.maxTotalExpandedStatements) throw new CustomError("TX_BLOCK_BUDGET_EXCEEDED", `TransactionBlock expanded statements (${totalExpandedStatements}) exceeds maxTotalExpandedStatements (${budget.maxTotalExpandedStatements})`);
1166
+ const output = await options.executeStatement(resolvedStmt, overlay, {
1167
+ stepIndex: i,
1168
+ stepOutputs,
1169
+ block
1170
+ }) || {};
1171
+ stepOutputs.push(cloneDeep(output));
1172
+ await assertRuntimeIoBudgetAndAssetImmutability();
1173
+ }
1174
+ const conservation = overlay.verifyZeroSumConservation();
1175
+ if (enforceZeroSum && !conservation.valid) throw new CustomError("ACCOUNTING_INVARIANT_VIOLATION", `TransactionBlock violates zero-sum token conservation: ${JSON.stringify(conservation.netUnbackedDeltas)}`);
1176
+ const stateDiff = overlay.getStateDiff();
1177
+ await verifyTransactionBlockPostConditions(block, stateDiff, overlay);
1178
+ const footprint = extractStateFootprint(block);
1179
+ const readKeySet = new Set(footprint.readSet);
1180
+ const writeKeySet = new Set(footprint.writeSet);
1181
+ for (const rk of overlay.getReadKeys()) readKeySet.add(rk);
1182
+ for (const wk of overlay.getWriteKeys()) {
1183
+ readKeySet.add(wk);
1184
+ writeKeySet.add(wk);
1185
+ }
1186
+ footprint.readSet = Array.from(readKeySet).sort();
1187
+ footprint.writeSet = Array.from(writeKeySet).sort();
1188
+ if (dryRun) {
1189
+ overlay.setRuntimeIoBudget(null);
1190
+ overlay.rollbackToSavepoint(topSavepoint);
1191
+ return {
1192
+ ok: true,
1193
+ blockId,
1194
+ dryRun: true,
1195
+ committed: false,
1196
+ footprint,
1197
+ stateDiff,
1198
+ tokenDeltas: conservation.netUnbackedDeltas,
1199
+ stepOutputs,
1200
+ totalExpandedStatements,
1201
+ invokedExecuteAssets: Array.from(runtimeInvokedExecuteAssets)
1202
+ };
1203
+ }
1204
+ overlay.setRuntimeIoBudget(null);
1205
+ if (!(options.statedb instanceof OverlayStateDB)) await overlay.commit(options.operationContext);
1206
+ else overlay.releaseSavepoint(topSavepoint);
1207
+ return {
1208
+ ok: true,
1209
+ blockId,
1210
+ dryRun: false,
1211
+ committed: true,
1212
+ footprint,
1213
+ stateDiff,
1214
+ tokenDeltas: conservation.netUnbackedDeltas,
1215
+ stepOutputs,
1216
+ totalExpandedStatements,
1217
+ invokedExecuteAssets: Array.from(runtimeInvokedExecuteAssets)
1218
+ };
1219
+ } catch (err) {
1220
+ overlay.setRuntimeIoBudget(null);
1221
+ overlay.rollbackToSavepoint(topSavepoint);
1222
+ const customErr = err instanceof CustomError ? err : new CustomError("TX_BLOCK_FAILED", err?.message || "TransactionBlock failed");
1223
+ return {
1224
+ ok: false,
1225
+ blockId,
1226
+ dryRun,
1227
+ committed: false,
1228
+ footprint: extractStateFootprint(block),
1229
+ stateDiff: [],
1230
+ tokenDeltas: {},
1231
+ stepOutputs,
1232
+ totalExpandedStatements,
1233
+ invokedExecuteAssets: Array.from(runtimeInvokedExecuteAssets),
1234
+ error: customErr
1235
+ };
1236
+ }
1237
+ }
1238
+ function isPostConditionsTightForSigner(pc, signerDid, signerTokenOutflows, signerAssetsSent) {
1239
+ if (!pc || pc.strictZeroUnlistedOutflow === false) return false;
1240
+ const signedTokenCaps = pc.maxTokenOutflow && Object.prototype.hasOwnProperty.call(pc.maxTokenOutflow, signerDid) ? pc.maxTokenOutflow[signerDid] : void 0;
1241
+ if (signerTokenOutflows.length > 0 && (!signedTokenCaps || typeof signedTokenCaps !== "object")) return false;
1242
+ if (signedTokenCaps && Object.keys(signedTokenCaps).length !== signerTokenOutflows.length) return false;
1243
+ for (const out of signerTokenOutflows) {
1244
+ const parsedCap = parseNonNegativeBn(signedTokenCaps && Object.prototype.hasOwnProperty.call(signedTokenCaps, out.tokenAddress) ? signedTokenCaps[out.tokenAddress] : void 0);
1245
+ if (!parsedCap.ok || parsedCap.value.gt(new BN(out.amount, 10))) return false;
1246
+ }
1247
+ const rawAllowedAssets = pc.allowedOutgoingAssets && Object.prototype.hasOwnProperty.call(pc.allowedOutgoingAssets, signerDid) ? pc.allowedOutgoingAssets[signerDid] : void 0;
1248
+ const allowedAssets = new Set(rawAllowedAssets || []);
1249
+ if (allowedAssets.size !== signerAssetsSent.length) return false;
1250
+ if (signerAssetsSent.length > 0) {
1251
+ for (const assetDid of signerAssetsSent) if (!allowedAssets.has(assetDid)) return false;
1252
+ }
1253
+ return true;
1254
+ }
1255
+ /**
1256
+ * Issue #1253 Guardrail #2:
1257
+ * Generates a human-comprehensible Wallet Clear-Signing Preview (`WalletClearSigningPreview`)
1258
+ * by simulating the `TransactionBlock` in zero-side-effect `dryRun: true` mode on `OverlayStateDB`.
1259
+ * Summarizes net token outflows, net token inflows, asset transfers, invoked `execute_asset` contracts,
1260
+ * tight suggested `postConditions`, and deterministic `riskLevel` (`LOW` | `MEDIUM` | `HIGH`).
1261
+ */
1262
+ async function buildWalletClearSigningPreview(block, options) {
1263
+ const signerDid = options.signerDid || block.from;
1264
+ assertSafeKey(signerDid, "signerDid");
1265
+ const preflight = assertTransactionBlockResourceBudget(block, options.resourceBudget);
1266
+ const simResult = await executeTransactionBlock(block, {
1267
+ statedb: options.statedb,
1268
+ executeStatement: options.executeStatement,
1269
+ dryRun: true,
1270
+ resourceBudget: options.resourceBudget
1271
+ });
1272
+ if (!simResult.ok) throw simResult.error || new CustomError("SIMULATION_FAILED", "TransactionBlock dry-run simulation failed");
1273
+ const { accountTokenNetDeltas, outgoingAssetsByOwner, incomingAssetsByOwner } = computeAccountAndAssetNetEffects(simResult.stateDiff);
1274
+ const signerTokenMap = accountTokenNetDeltas.get(signerDid) || /* @__PURE__ */ new Map();
1275
+ const signerTokenOutflows = [];
1276
+ const signerTokenInflows = [];
1277
+ for (const [tokenAddress, delta] of signerTokenMap.entries()) if (delta.isNeg()) signerTokenOutflows.push({
1278
+ tokenAddress,
1279
+ amount: delta.neg().toString(10)
1280
+ });
1281
+ else if (delta.gt(new BN(0))) signerTokenInflows.push({
1282
+ tokenAddress,
1283
+ amount: delta.toString(10)
1284
+ });
1285
+ const signerAssetsSent = Array.from(outgoingAssetsByOwner.get(signerDid) || []);
1286
+ const signerAssetsReceived = Array.from(incomingAssetsByOwner.get(signerDid) || []);
1287
+ const invokedExecuteAssets = simResult.invokedExecuteAssets || [];
1288
+ const totalExpandedStatements = simResult.totalExpandedStatements ?? block.statements.length;
1289
+ const suggestedMaxOutflow = {};
1290
+ for (const out of signerTokenOutflows) suggestedMaxOutflow[out.tokenAddress] = out.amount;
1291
+ const suggestedMinInflow = {};
1292
+ for (const inp of signerTokenInflows) suggestedMinInflow[inp.tokenAddress] = inp.amount;
1293
+ const suggestedPostConditions = {
1294
+ maxTokenOutflow: { [signerDid]: suggestedMaxOutflow },
1295
+ ...signerTokenInflows.length > 0 ? { minTokenInflow: { [signerDid]: suggestedMinInflow } } : {},
1296
+ ...signerAssetsSent.length > 0 ? { allowedOutgoingAssets: { [signerDid]: signerAssetsSent } } : {},
1297
+ ...signerAssetsReceived.length > 0 ? { mustOwnAssetsAfter: { [signerDid]: signerAssetsReceived } } : {},
1298
+ strictZeroUnlistedOutflow: true
1299
+ };
1300
+ const payParts = [];
1301
+ for (const o of signerTokenOutflows) payParts.push(`${o.amount} [${o.tokenAddress}]`);
1302
+ for (const a of signerAssetsSent) payParts.push(`Asset(${a})`);
1303
+ const youPaySummary = payParts.length > 0 ? `You spend at most: ${payParts.join(", ")}` : "You spend: 0 tokens / 0 assets";
1304
+ const recvParts = [];
1305
+ for (const i of signerTokenInflows) recvParts.push(`${i.amount} [${i.tokenAddress}]`);
1306
+ for (const a of signerAssetsReceived) recvParts.push(`Asset(${a})`);
1307
+ const youReceiveSummary = recvParts.length > 0 ? `You receive at least: ${recvParts.join(", ")}` : "You receive: 0 tokens / 0 assets";
1308
+ const actionTags = block.statements.map((s) => normalizeStatementProtocolTag(s) || "statement");
1309
+ const actionsSummary = `Executes ${block.statements.length} top-level statement(s) (${totalExpandedStatements} total atomic step(s)): ${actionTags.join(" -> ")}`;
1310
+ const riskReasons = [];
1311
+ let riskLevel = "LOW";
1312
+ if (!isPostConditionsTightForSigner(block.postConditions, signerDid, signerTokenOutflows, signerAssetsSent) && (totalExpandedStatements > 3 || invokedExecuteAssets.length > 0)) {
1313
+ riskLevel = "HIGH";
1314
+ riskReasons.push("Complex or programmable TransactionBlock is missing tight signed postConditions protection");
1315
+ }
1316
+ if (invokedExecuteAssets.length > 0) {
1317
+ if (riskLevel === "LOW") riskLevel = "MEDIUM";
1318
+ riskReasons.push(`Invokes ${invokedExecuteAssets.length} programmable execute_asset contract(s): ${invokedExecuteAssets.join(", ")}`);
1319
+ }
1320
+ if (totalExpandedStatements > 6) {
1321
+ if (riskLevel === "LOW") riskLevel = "MEDIUM";
1322
+ riskReasons.push(`High step count (${totalExpandedStatements} expanded atomic statements)`);
1323
+ }
1324
+ const distinctSenders = new Set(block.statements.map((s) => s.from || block.from));
1325
+ if (distinctSenders.size > 2) {
1326
+ if (riskLevel === "LOW") riskLevel = "MEDIUM";
1327
+ riskReasons.push(`Multi-party composition involving ${distinctSenders.size} distinct statement senders`);
1328
+ }
1329
+ return Object.freeze({
1330
+ signerDid,
1331
+ blockId: simResult.blockId,
1332
+ totalTopLevelStatements: block.statements.length,
1333
+ totalExpandedStatements,
1334
+ byteSize: preflight.byteSize,
1335
+ footprint: simResult.footprint,
1336
+ signerTokenOutflows,
1337
+ signerTokenInflows,
1338
+ signerAssetsSent,
1339
+ signerAssetsReceived,
1340
+ invokedExecuteAssets,
1341
+ humanReadableLines: Object.freeze({
1342
+ youPaySummary,
1343
+ actionsSummary,
1344
+ youReceiveSummary
1345
+ }),
1346
+ suggestedPostConditions,
1347
+ riskLevel,
1348
+ riskReasons
1349
+ });
1350
+ }
1351
+ var TwoPhaseCommitCoordinator = class {
1352
+ constructor() {
1353
+ this.preparedBlocks = /* @__PURE__ */ new Map();
1354
+ }
1355
+ evictExpired(currentHeight) {
1356
+ for (const [id, entry] of this.preparedBlocks.entries()) if (entry.status === "PREPARED" && currentHeight > entry.timeoutHeight) {
1357
+ entry.status = "ABORTED";
1358
+ entry.overlay.discard();
1359
+ this.preparedBlocks.delete(id);
1360
+ }
1361
+ }
1362
+ async prepare(block, options) {
1363
+ if (options.timeoutHeight <= options.currentHeight) throw new CustomError("INVALID_2PC_TIMEOUT", "timeoutHeight must be greater than currentHeight");
1364
+ this.evictExpired(options.currentHeight);
1365
+ if (block.id && this.preparedBlocks.has(block.id)) throw new CustomError("DUPLICATE_2PC_ID", `Prepared block ${block.id} already exists`);
1366
+ const candidateFootprint = extractStateFootprint(block);
1367
+ for (const active of this.preparedBlocks.values()) if (active.status === "PREPARED" && hasStateConflict(candidateFootprint, active.footprint)) throw new CustomError("LOCK_CONFLICT", `2PC prepare conflict with active prepared block ${active.preparedId}`);
1368
+ const overlay = createOverlayStateDB(options.statedb);
1369
+ const execResult = await executeTransactionBlock(block, {
1370
+ statedb: overlay,
1371
+ executeStatement: options.executeStatement,
1372
+ dryRun: false
1373
+ });
1374
+ if (!execResult.ok) throw execResult.error || new CustomError("PREPARE_FAILED", "Failed to prepare TransactionBlock");
1375
+ if (this.preparedBlocks.has(execResult.blockId)) {
1376
+ overlay.discard();
1377
+ throw new CustomError("DUPLICATE_2PC_ID", `Prepared block ${execResult.blockId} already exists`);
1378
+ }
1379
+ for (const active of this.preparedBlocks.values()) if (active.status === "PREPARED" && hasStateConflict(execResult.footprint, active.footprint)) {
1380
+ overlay.discard();
1381
+ throw new CustomError("LOCK_CONFLICT", `2PC runtime write-set conflict with active prepared block ${active.preparedId}`);
1382
+ }
1383
+ const prepared = {
1384
+ preparedId: execResult.blockId,
1385
+ block,
1386
+ footprint: execResult.footprint,
1387
+ stateDiff: execResult.stateDiff,
1388
+ stepOutputs: execResult.stepOutputs,
1389
+ timeoutHeight: options.timeoutHeight,
1390
+ status: "PREPARED",
1391
+ overlay
1392
+ };
1393
+ this.preparedBlocks.set(prepared.preparedId, prepared);
1394
+ return prepared;
1395
+ }
1396
+ async commit(preparedId, options) {
1397
+ const prepared = this.preparedBlocks.get(preparedId);
1398
+ if (!prepared) throw new CustomError("NOT_FOUND", `Prepared block ${preparedId} not found`);
1399
+ if (prepared.status !== "PREPARED") throw new CustomError("INVALID_2PC_STATE", `Prepared block ${preparedId} is already ${prepared.status}`);
1400
+ if (options.currentHeight > prepared.timeoutHeight) {
1401
+ prepared.status = "ABORTED";
1402
+ prepared.overlay.discard();
1403
+ throw new CustomError("EXPIRED_2PC", `Prepared block ${preparedId} expired at height ${prepared.timeoutHeight}`);
1404
+ }
1405
+ if (!await prepared.overlay.verifyBaseUnchanged(options.operationContext)) {
1406
+ prepared.status = "ABORTED";
1407
+ prepared.overlay.discard();
1408
+ throw new CustomError("STALE_2PC_READ_SET", `Underlying state mutated concurrently before committing ${preparedId}`);
1409
+ }
1410
+ const committedDiff = await prepared.overlay.commit(options.operationContext);
1411
+ prepared.status = "COMMITTED";
1412
+ return committedDiff;
1413
+ }
1414
+ abort(preparedId) {
1415
+ const prepared = this.preparedBlocks.get(preparedId);
1416
+ if (!prepared) throw new CustomError("NOT_FOUND", `Prepared block ${preparedId} not found`);
1417
+ if (prepared.status !== "PREPARED") throw new CustomError("INVALID_2PC_STATE", `Prepared block ${preparedId} is already ${prepared.status}`);
1418
+ prepared.status = "ABORTED";
1419
+ prepared.overlay.discard();
1420
+ return prepared;
1421
+ }
1422
+ getPrepared(preparedId) {
1423
+ return this.preparedBlocks.get(preparedId);
1424
+ }
1425
+ };
1426
+ var TwoPhaseTransferLedger = class {
1427
+ constructor() {
1428
+ this.transfers = /* @__PURE__ */ new Map();
1429
+ }
1430
+ async createPendingTransfer(params, statedb) {
1431
+ assertSafeKey(params.id, "transfer.id");
1432
+ assertSafeKey(params.debitAddress, "debitAddress");
1433
+ assertSafeKey(params.creditAddress, "creditAddress");
1434
+ assertSafeKey(params.tokenAddress, "tokenAddress");
1435
+ if (params.debitAddress === params.creditAddress) throw new CustomError("INVALID_SELF_TRANSFER", "Pending transfer debitAddress and creditAddress must be distinct");
1436
+ if (this.transfers.has(params.id)) throw new CustomError("DUPLICATE_PENDING_TRANSFER", `Pending transfer ${params.id} already exists`);
1437
+ if (params.timeoutHeight <= params.currentHeight) throw new CustomError("INVALID_TIMEOUT", "timeoutHeight must be greater than currentHeight");
1438
+ 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");
1439
+ const amt = new BN(params.amount, 10);
1440
+ if (amt.lte(new BN(0))) throw new CustomError("INVALID_AMOUNT", "Pending transfer amount must be greater than 0");
1441
+ const debitAccount = await statedb.account.get(params.debitAddress);
1442
+ if (!debitAccount) throw new CustomError("INVALID_SENDER_STATE", `Debit account ${params.debitAddress} not found`);
1443
+ const available = new BN(debitAccount.tokens?.[params.tokenAddress] || "0");
1444
+ if (available.lt(amt)) throw new CustomError("INSUFFICIENT_BALANCE", `Insufficient available balance for ${params.tokenAddress}`);
1445
+ const nextAvailable = available.sub(amt).toString(10);
1446
+ const nextPending = new BN(debitAccount.pendingTokens?.[params.tokenAddress] || "0").add(amt).toString(10);
1447
+ await statedb.account.update(params.debitAddress, {
1448
+ ...debitAccount,
1449
+ tokens: {
1450
+ ...debitAccount.tokens || {},
1451
+ [params.tokenAddress]: nextAvailable
1452
+ },
1453
+ pendingTokens: {
1454
+ ...debitAccount.pendingTokens || {},
1455
+ [params.tokenAddress]: nextPending
1456
+ }
1457
+ });
1458
+ const record = {
1459
+ id: params.id,
1460
+ debitAddress: params.debitAddress,
1461
+ creditAddress: params.creditAddress,
1462
+ tokenAddress: params.tokenAddress,
1463
+ amount: amt.toString(10),
1464
+ timeoutHeight: params.timeoutHeight,
1465
+ status: "PENDING"
1466
+ };
1467
+ this.transfers.set(params.id, record);
1468
+ return cloneDeep(record);
1469
+ }
1470
+ async postPendingTransfer(params, statedb) {
1471
+ const record = this.transfers.get(params.id);
1472
+ if (!record) throw new CustomError("NOT_FOUND", `Pending transfer ${params.id} not found`);
1473
+ if (record.status !== "PENDING") throw new CustomError("INVALID_STATE", `Pending transfer ${params.id} is already ${record.status}`);
1474
+ if (params.currentHeight > record.timeoutHeight) throw new CustomError("EXPIRED_PENDING_TRANSFER", `Pending transfer ${params.id} has expired`);
1475
+ const amt = new BN(record.amount);
1476
+ const debitAccount = await statedb.account.get(record.debitAddress);
1477
+ const curPending = new BN(debitAccount?.pendingTokens?.[record.tokenAddress] || "0");
1478
+ if (curPending.lt(amt)) throw new CustomError("INSUFFICIENT_PENDING", "Locked pending balance corrupted");
1479
+ await statedb.account.update(record.debitAddress, {
1480
+ ...debitAccount,
1481
+ pendingTokens: {
1482
+ ...debitAccount.pendingTokens || {},
1483
+ [record.tokenAddress]: curPending.sub(amt).toString(10)
1484
+ }
1485
+ });
1486
+ const existingCredit = await statedb.account.get(record.creditAddress);
1487
+ const creditAccount = existingCredit || {
1488
+ address: record.creditAddress,
1489
+ tokens: {},
1490
+ pendingTokens: {}
1491
+ };
1492
+ const curCredit = new BN(creditAccount.tokens?.[record.tokenAddress] || "0");
1493
+ await statedb.account.updateOrCreate(existingCredit, {
1494
+ ...creditAccount,
1495
+ address: record.creditAddress,
1496
+ tokens: {
1497
+ ...creditAccount.tokens || {},
1498
+ [record.tokenAddress]: curCredit.add(amt).toString(10)
1499
+ }
1500
+ });
1501
+ record.status = "POSTED";
1502
+ return cloneDeep(record);
1503
+ }
1504
+ async voidPendingTransfer(params, statedb) {
1505
+ const record = this.transfers.get(params.id);
1506
+ if (!record) throw new CustomError("NOT_FOUND", `Pending transfer ${params.id} not found`);
1507
+ if (record.status !== "PENDING") throw new CustomError("INVALID_STATE", `Pending transfer ${params.id} is already ${record.status}`);
1508
+ const amt = new BN(record.amount, 10);
1509
+ const debitAccount = await statedb.account.get(record.debitAddress);
1510
+ if (!debitAccount) throw new CustomError("INVALID_SENDER_STATE", `Debit account ${record.debitAddress} not found`);
1511
+ const curPending = new BN(debitAccount?.pendingTokens?.[record.tokenAddress] || "0", 10);
1512
+ if (curPending.lt(amt)) throw new CustomError("INSUFFICIENT_PENDING", "Locked pending balance corrupted");
1513
+ const curAvailable = new BN(debitAccount?.tokens?.[record.tokenAddress] || "0", 10);
1514
+ await statedb.account.update(record.debitAddress, {
1515
+ ...debitAccount,
1516
+ tokens: {
1517
+ ...debitAccount.tokens || {},
1518
+ [record.tokenAddress]: curAvailable.add(amt).toString(10)
1519
+ },
1520
+ pendingTokens: {
1521
+ ...debitAccount.pendingTokens || {},
1522
+ [record.tokenAddress]: curPending.sub(amt).toString(10)
1523
+ }
1524
+ });
1525
+ record.status = "VOIDED";
1526
+ return cloneDeep(record);
1527
+ }
1528
+ };
1529
+ /**
1530
+ * 5. NFT-as-a-Smart-Contract (`ContractNFT`: `@ocap/contract` Declarative Guard + Parameterized `TransactionBlock` Stored Procedure)
1531
+ */
1532
+ const CONTRACT_NFT_KIND = "ContractNFT";
1533
+ const MAX_CONTRACT_NFT_STATEMENTS = 16;
1534
+ const MAX_CONTRACT_ARGS_BYTES = 16384;
1535
+ const MAX_CONTRACT_FOOTPRINT_KEYS = 64;
1536
+ function parseStrictComparableBn(val) {
1537
+ if (typeof val === "number") {
1538
+ if (!Number.isFinite(val) || !Number.isInteger(val)) return null;
1539
+ return new BN(String(val), 10);
1540
+ }
1541
+ if (typeof val === "bigint") return new BN(val.toString(10), 10);
1542
+ if (typeof val === "string" && CANONICAL_SIGNED_INT_REGEX.test(val)) return new BN(val, 10);
1543
+ return null;
1544
+ }
1545
+ function evaluateGuardPredicate(pred, contextObj) {
1546
+ const actual = getSafePath(contextObj, pred.field);
1547
+ switch (pred.op) {
1548
+ case "eq": return actual === pred.value;
1549
+ case "neq": return actual !== pred.value;
1550
+ case "gt":
1551
+ case "gte":
1552
+ case "lt":
1553
+ case "lte": {
1554
+ const aBn = parseStrictComparableBn(actual);
1555
+ const bBn = parseStrictComparableBn(pred.value);
1556
+ if (!aBn || !bBn) return false;
1557
+ if (pred.op === "gt") return aBn.gt(bBn);
1558
+ if (pred.op === "gte") return aBn.gte(bBn);
1559
+ if (pred.op === "lt") return aBn.lt(bBn);
1560
+ return aBn.lte(bBn);
1561
+ }
1562
+ case "in": return Array.isArray(pred.value) && pred.value.includes(actual);
1563
+ default: return false;
1564
+ }
1565
+ }
1566
+ function assertNoStepRefInValue(val, depth = 0) {
1567
+ if (depth > 16) throw new CustomError("INVALID_CONTRACT_NFT", "ContractNFT argument nesting depth exceeded");
1568
+ if (typeof val === "string") {
1569
+ if (val.trim().startsWith("$steps[") || /\$steps\[\d+\]/.test(val)) throw new CustomError("INVALID_CONTRACT_NFT", "ContractNFT arguments cannot inject $steps[i] cross-statement pipeline references");
1570
+ return;
1571
+ }
1572
+ if (Array.isArray(val)) {
1573
+ for (const item of val) assertNoStepRefInValue(item, depth + 1);
1574
+ return;
1575
+ }
1576
+ if (val && typeof val === "object") for (const [k, v] of Object.entries(val)) {
1577
+ assertSafeKey(k, "argKey");
1578
+ assertNoStepRefInValue(v, depth + 1);
1579
+ }
1580
+ }
1581
+ function interpolateContractTemplate(template, bindings, depth = 0) {
1582
+ if (depth > 16) throw new CustomError("INVALID_CONTRACT_NFT", "Template interpolation depth exceeded");
1583
+ if (typeof template === "string") {
1584
+ if (template === "$caller" || template.startsWith("$args.") || template.startsWith("$contract.")) {
1585
+ const val = getSafePath(bindings, template.slice(1));
1586
+ if (val === void 0) throw new CustomError("INVALID_CONTRACT_NFT", `Missing contract template binding for ${template}`);
1587
+ assertNoStepRefInValue(val);
1588
+ return cloneDeep(val);
1589
+ }
1590
+ return template;
1591
+ }
1592
+ if (Array.isArray(template)) return template.map((item) => interpolateContractTemplate(item, bindings, depth + 1));
1593
+ if (template && typeof template === "object") {
1594
+ const out = {};
1595
+ for (const [k, v] of Object.entries(template)) {
1596
+ assertSafeKey(k, "templateKey");
1597
+ out[k] = interpolateContractTemplate(v, bindings, depth + 1);
1598
+ }
1599
+ return out;
1600
+ }
1601
+ return template;
1602
+ }
1603
+ async function executeContractNft(params) {
1604
+ const { contractAsset, caller, args, statedb, executeStatement, dryRun } = params;
1605
+ if (!contractAsset || contractAsset.consumedTime) throw new CustomError("CONSUMED_ASSET", "Cannot execute a consumed Contract NFT");
1606
+ const payload = contractAsset.data?.value;
1607
+ if (!payload || contractAsset.data?.type !== "json" || payload.kind !== CONTRACT_NFT_KIND) throw new CustomError("INVALID_CONTRACT_NFT", "Asset is not a valid ContractNFT");
1608
+ if (!Array.isArray(payload.statementTemplates) || payload.statementTemplates.length === 0) throw new CustomError("INVALID_CONTRACT_NFT", "ContractNFT must contain at least one statementTemplate");
1609
+ if (payload.statementTemplates.length > MAX_CONTRACT_NFT_STATEMENTS) throw new CustomError("CONTRACT_BUDGET_EXCEEDED", `ContractNFT statementTemplates count (${payload.statementTemplates.length}) exceeds MAX_CONTRACT_NFT_STATEMENTS (${MAX_CONTRACT_NFT_STATEMENTS})`);
1610
+ for (let tIdx = 0; tIdx < payload.statementTemplates.length; tIdx++) assertLeafStatementTemplateOnly(payload.statementTemplates[tIdx], `statementTemplates[${tIdx}]`);
1611
+ let serializedArgs;
1612
+ try {
1613
+ serializedArgs = JSON.stringify(args || {});
1614
+ } catch {
1615
+ throw new CustomError("INVALID_CONTRACT_NFT", "ContractNFT args must be valid JSON-serializable data");
1616
+ }
1617
+ const serializedArgsBytes = Buffer.byteLength(serializedArgs, "utf8");
1618
+ if (serializedArgsBytes > MAX_CONTRACT_ARGS_BYTES) throw new CustomError("CONTRACT_BUDGET_EXCEEDED", `ContractNFT args byte size (${serializedArgsBytes}) exceeds MAX_CONTRACT_ARGS_BYTES (${MAX_CONTRACT_ARGS_BYTES})`);
1619
+ assertNoStepRefInValue(args || {});
1620
+ if (Array.isArray(payload.allowedCallers) && payload.allowedCallers.length > 0 && !payload.allowedCallers.includes(caller)) throw new CustomError("FORBIDDEN", `Caller ${caller} is not authorized by ContractNFT allowlist`);
1621
+ const bindings = {
1622
+ caller,
1623
+ args: args || {},
1624
+ contract: {
1625
+ address: contractAsset.address,
1626
+ owner: contractAsset.owner,
1627
+ name: payload.name
1628
+ }
1629
+ };
1630
+ for (const guard of payload.guards || []) if (!evaluateGuardPredicate(guard, bindings)) throw new CustomError("CONTRACT_GUARD_FAILED", `ContractNFT guard failed: ${guard.field} ${guard.op} ${JSON.stringify(guard.value)}`);
1631
+ const permittedSenders = new Set([
1632
+ caller,
1633
+ contractAsset.address,
1634
+ contractAsset.owner
1635
+ ]);
1636
+ const instantiatedStatements = payload.statementTemplates.map((tpl) => {
1637
+ const resolvedFrom = tpl.from ? interpolateContractTemplate(tpl.from, bindings) : contractAsset.address;
1638
+ if (!permittedSenders.has(resolvedFrom)) throw new CustomError("FORBIDDEN", `ContractNFT statement cannot impersonate unauthorized sender ${String(resolvedFrom)}`);
1639
+ return {
1640
+ ...tpl,
1641
+ from: resolvedFrom,
1642
+ itx: interpolateContractTemplate(tpl.itx, bindings)
1643
+ };
1644
+ });
1645
+ const footprint = extractStateFootprint({
1646
+ from: caller,
1647
+ delegator: contractAsset.address,
1648
+ statements: instantiatedStatements
1649
+ });
1650
+ const uniqueFootprintKeys = new Set([...footprint.readSet, ...footprint.writeSet]);
1651
+ if (uniqueFootprintKeys.size > MAX_CONTRACT_FOOTPRINT_KEYS) throw new CustomError("CONTRACT_BUDGET_EXCEEDED", `ContractNFT state footprint key count (${uniqueFootprintKeys.size}) exceeds MAX_CONTRACT_FOOTPRINT_KEYS (${MAX_CONTRACT_FOOTPRINT_KEYS})`);
1652
+ const boundedExecutor = async (stmt, overlay, stepIdx) => {
1653
+ const res = await executeStatement(stmt, overlay, stepIdx);
1654
+ const dynamicFootprint = new Set([
1655
+ ...uniqueFootprintKeys,
1656
+ ...overlay.getReadKeys(),
1657
+ ...overlay.getWriteKeys()
1658
+ ]);
1659
+ if (dynamicFootprint.size > MAX_CONTRACT_FOOTPRINT_KEYS) throw new CustomError("CONTRACT_BUDGET_EXCEEDED", `ContractNFT runtime state footprint key count (${dynamicFootprint.size}) exceeds MAX_CONTRACT_FOOTPRINT_KEYS (${MAX_CONTRACT_FOOTPRINT_KEYS})`);
1660
+ return res;
1661
+ };
1662
+ return executeTransactionBlock({
1663
+ from: caller,
1664
+ delegator: contractAsset.address,
1665
+ statements: instantiatedStatements,
1666
+ enforceZeroSum: true
1667
+ }, {
1668
+ statedb,
1669
+ executeStatement: boundedExecutor,
1670
+ dryRun
1671
+ });
1672
+ }
1673
+ var StagedSyncPipeline = class {
1674
+ constructor() {
1675
+ this.stages = [];
1676
+ this.checkpoints = /* @__PURE__ */ new Map();
1677
+ }
1678
+ registerStage(stage) {
1679
+ assertSafeKey(stage.id, "stage.id");
1680
+ if (this.stages.some((s) => s.id === stage.id)) throw new CustomError("DUPLICATE_STAGE", `Sync stage ${stage.id} already registered`);
1681
+ this.stages.push(stage);
1682
+ this.checkpoints.set(stage.id, 0);
1683
+ return this;
1684
+ }
1685
+ getStageCheckpoint(stageId) {
1686
+ return this.checkpoints.get(stageId) ?? 0;
1687
+ }
1688
+ async runTo(targetHeight, statedb, ctx) {
1689
+ if (!Number.isInteger(targetHeight) || targetHeight < 0) throw new CustomError("INVALID_HEIGHT", `Invalid targetHeight ${targetHeight}`);
1690
+ const overlay = statedb instanceof OverlayStateDB ? statedb : createOverlayStateDB(statedb);
1691
+ const sp = overlay.createSavepoint();
1692
+ const checkpointSnapshot = new Map(this.checkpoints);
1693
+ try {
1694
+ for (const stage of this.stages) {
1695
+ const current = this.checkpoints.get(stage.id) ?? 0;
1696
+ if (current < targetHeight) {
1697
+ await stage.execute({
1698
+ fromHeight: current + 1,
1699
+ toHeight: targetHeight
1700
+ }, overlay, ctx);
1701
+ this.checkpoints.set(stage.id, targetHeight);
1702
+ }
1703
+ }
1704
+ const stateDiff = overlay.getStateDiff();
1705
+ if (!(statedb instanceof OverlayStateDB)) await overlay.commit();
1706
+ else overlay.releaseSavepoint(sp);
1707
+ return {
1708
+ checkpoints: Object.fromEntries(this.checkpoints.entries()),
1709
+ stateDiff
1710
+ };
1711
+ } catch (err) {
1712
+ this.checkpoints.clear();
1713
+ for (const [k, v] of checkpointSnapshot.entries()) this.checkpoints.set(k, v);
1714
+ overlay.rollbackToSavepoint(sp);
1715
+ throw err;
1716
+ }
1717
+ }
1718
+ async unwindTo(targetHeight, statedb, ctx) {
1719
+ if (!Number.isInteger(targetHeight) || targetHeight < 0) throw new CustomError("INVALID_HEIGHT", `Invalid unwind targetHeight ${targetHeight}`);
1720
+ const maxCheckpoint = this.checkpoints.size > 0 ? Math.max(...Array.from(this.checkpoints.values())) : 0;
1721
+ if (targetHeight > maxCheckpoint) throw new CustomError("INVALID_HEIGHT", `Cannot unwind to targetHeight ${targetHeight} above current tip ${maxCheckpoint}`);
1722
+ const overlay = statedb instanceof OverlayStateDB ? statedb : createOverlayStateDB(statedb);
1723
+ const sp = overlay.createSavepoint();
1724
+ const checkpointSnapshot = new Map(this.checkpoints);
1725
+ try {
1726
+ for (let i = this.stages.length - 1; i >= 0; i--) {
1727
+ const stage = this.stages[i];
1728
+ const current = this.checkpoints.get(stage.id) ?? 0;
1729
+ if (current > targetHeight) {
1730
+ await stage.unwind({
1731
+ fromHeight: current,
1732
+ toHeight: targetHeight
1733
+ }, overlay, ctx);
1734
+ this.checkpoints.set(stage.id, targetHeight);
1735
+ }
1736
+ }
1737
+ const stateDiff = overlay.getStateDiff();
1738
+ if (!(statedb instanceof OverlayStateDB)) await overlay.commit();
1739
+ else overlay.releaseSavepoint(sp);
1740
+ return {
1741
+ checkpoints: Object.fromEntries(this.checkpoints.entries()),
1742
+ stateDiff
1743
+ };
1744
+ } catch (err) {
1745
+ this.checkpoints.clear();
1746
+ for (const [k, v] of checkpointSnapshot.entries()) this.checkpoints.set(k, v);
1747
+ overlay.rollbackToSavepoint(sp);
1748
+ throw err;
1749
+ }
1750
+ }
1751
+ };
1752
+ async function executeCrossChainPurchaseBlock(input, options) {
1753
+ if (!input || typeof input !== "object") throw new CustomError("INVALID_CROSS_CHAIN_PURCHASE", "Missing cross-chain purchase input");
1754
+ assertSafeKey(input.relayer, "input.relayer");
1755
+ assertSafeKey(input.buyer, "input.buyer");
1756
+ const { deposit, purchaseStatements } = input;
1757
+ if (!deposit || typeof deposit !== "object") throw new CustomError("INVALID_CROSS_CHAIN_PURCHASE", "Missing deposit specification");
1758
+ assertSafeKey(deposit.rollup, "deposit.rollup");
1759
+ assertSafeKey(deposit.token?.address, "deposit.token.address");
1760
+ assertSafeKey(deposit.evidence?.hash, "deposit.evidence.hash");
1761
+ const depositValueParsed = parseNonNegativeBn(deposit.token?.value);
1762
+ if (!depositValueParsed.ok || depositValueParsed.value.lte(new BN(0))) throw new CustomError("INVALID_CROSS_CHAIN_PURCHASE", "Deposit token value must be a positive integer string");
1763
+ const actualFeeParsed = parseNonNegativeBn(deposit.actualFee ?? "0");
1764
+ if (!actualFeeParsed.ok || actualFeeParsed.value.lt(new BN(0))) throw new CustomError("INVALID_CROSS_CHAIN_PURCHASE", "Deposit actualFee must be a non-negative integer string");
1765
+ const depositValue = depositValueParsed.value;
1766
+ const actualFee = actualFeeParsed.value;
1767
+ const effectiveMinDeposit = options.minDepositValue ?? input.minDepositValue;
1768
+ if (effectiveMinDeposit !== void 0) {
1769
+ const minDepositParsed = parseNonNegativeBn(effectiveMinDeposit);
1770
+ if (!minDepositParsed.ok || minDepositParsed.value.lte(new BN(0))) throw new CustomError("INVALID_CROSS_CHAIN_PURCHASE", "minDepositValue must be a positive integer string");
1771
+ if (depositValue.lt(minDepositParsed.value)) throw new CustomError("DUST_DEPOSIT_REJECTED", `Cross-chain deposit value ${depositValue.toString(10)} is below minDepositValue ${minDepositParsed.value.toString(10)}`);
1772
+ }
1773
+ const effectiveMinRelayerFee = options.minRelayerFee ?? input.minRelayerFee;
1774
+ if (effectiveMinRelayerFee !== void 0) {
1775
+ const minFeeParsed = parseNonNegativeBn(effectiveMinRelayerFee);
1776
+ if (!minFeeParsed.ok) throw new CustomError("INVALID_CROSS_CHAIN_PURCHASE", "minRelayerFee must be a non-negative integer string");
1777
+ if (actualFee.lt(minFeeParsed.value)) throw new CustomError("INSUFFICIENT_RELAYER_FEE", `Cross-chain deposit actualFee ${actualFee.toString(10)} is below minRelayerFee ${minFeeParsed.value.toString(10)}`);
1778
+ }
1779
+ if (!Array.isArray(purchaseStatements) || purchaseStatements.length === 0) throw new CustomError("INVALID_CROSS_CHAIN_PURCHASE", "purchaseStatements must contain at least one statement");
1780
+ if (input.enforceZeroSum === false) throw new CustomError("INVALID_CROSS_CHAIN_PURCHASE", "Zero-sum conservation cannot be disabled in cross-chain purchase blocks");
1781
+ const proposer = deposit.proposer || input.relayer;
1782
+ assertSafeKey(proposer, "deposit.proposer");
1783
+ const combinedOfacList = /* @__PURE__ */ new Set();
1784
+ if (Array.isArray(input.ofacBlocklist)) for (const addr of input.ofacBlocklist) combinedOfacList.add(addr);
1785
+ if (options.ofacBlocklist) for (const addr of options.ofacBlocklist) combinedOfacList.add(addr);
1786
+ const depositStatement = {
1787
+ type: "deposit_token_v2",
1788
+ typeUrl: "fg:t:deposit_token_v2",
1789
+ from: input.relayer,
1790
+ itx: {
1791
+ rollup: deposit.rollup,
1792
+ to: input.buyer,
1793
+ proposer,
1794
+ token: {
1795
+ address: deposit.token.address,
1796
+ value: depositValue.toString(10)
1797
+ },
1798
+ actualFee: actualFee.toString(10),
1799
+ evidence: {
1800
+ hash: deposit.evidence.hash,
1801
+ ...deposit.evidence.targetType ? { targetType: deposit.evidence.targetType } : {},
1802
+ ...deposit.evidence.targetChainId ? { targetChainId: deposit.evidence.targetChainId } : {}
1803
+ }
1804
+ }
1805
+ };
1806
+ const normalizedPurchaseStatements = purchaseStatements.map((stmt, idx) => {
1807
+ if (!stmt || typeof stmt !== "object") throw new CustomError("INVALID_CROSS_CHAIN_PURCHASE", `Invalid purchase statement at index ${idx}`);
1808
+ const stmtType = stmt.typeUrl || stmt.type || "";
1809
+ if (stmtType === "deposit_token_v2" || stmtType === "fg:t:deposit_token_v2") throw new CustomError("FORBIDDEN", `Purchase statement at index ${idx} cannot spoof privileged deposit_token_v2 protocol`);
1810
+ if (stmt.from && stmt.from !== input.buyer) throw new CustomError("FORBIDDEN", `Purchase statement at index ${idx} cannot impersonate sender ${stmt.from}; expected buyer ${input.buyer}`);
1811
+ if (stmt.delegator !== void 0) {
1812
+ assertSafeKey(stmt.delegator, `purchaseStatements[${idx}].delegator`);
1813
+ if (stmt.delegator !== input.buyer) throw new CustomError("FORBIDDEN", `Purchase statement at index ${idx} cannot specify unauthorized delegator ${stmt.delegator}`);
1814
+ }
1815
+ return {
1816
+ ...stmt,
1817
+ from: input.buyer
1818
+ };
1819
+ });
1820
+ if (combinedOfacList.size > 0) {
1821
+ const staticFootprint = extractStateFootprint({
1822
+ from: input.relayer,
1823
+ statements: [depositStatement, ...normalizedPurchaseStatements]
1824
+ });
1825
+ const extraTargets = [
1826
+ input.relayer,
1827
+ input.buyer,
1828
+ proposer,
1829
+ deposit.rollup,
1830
+ deposit.token.address,
1831
+ ...staticFootprint.readSet,
1832
+ ...staticFootprint.writeSet
1833
+ ];
1834
+ for (const stmt of normalizedPurchaseStatements) if (stmt?.itx && typeof stmt.itx.tokenFactory === "string") extraTargets.push(stmt.itx.tokenFactory);
1835
+ assertNotOfacSanctioned(extraTargets, combinedOfacList);
1836
+ }
1837
+ let depositStepCompleted = false;
1838
+ const wrappedExecutor = async (stmt, overlay, meta) => {
1839
+ if (combinedOfacList.size > 0) {
1840
+ const resolvedFootprint = extractStateFootprint(stmt);
1841
+ const stepTargets = [
1842
+ stmt.from,
1843
+ stmt.delegator,
1844
+ ...resolvedFootprint.readSet,
1845
+ ...resolvedFootprint.writeSet
1846
+ ];
1847
+ if (stmt?.itx && typeof stmt.itx.tokenFactory === "string") stepTargets.push(stmt.itx.tokenFactory);
1848
+ assertNotOfacSanctioned(stepTargets, combinedOfacList);
1849
+ }
1850
+ const out = await options.executeStatement(stmt, overlay, meta) || {};
1851
+ if (combinedOfacList.size > 0) assertNotOfacSanctioned([...overlay.getReadKeys(), ...overlay.getWriteKeys()], combinedOfacList);
1852
+ if (meta.stepIndex === 0) {
1853
+ const step0Conservation = overlay.verifyZeroSumConservation();
1854
+ if (!step0Conservation.valid) throw new CustomError("ACCOUNTING_INVARIANT_VIOLATION", `Step 0 deposit_token_v2 violates zero-sum token conservation: ${JSON.stringify(step0Conservation.netUnbackedDeltas)}`);
1855
+ depositStepCompleted = true;
1856
+ return {
1857
+ ...out,
1858
+ depositedAmount: depositValue.toString(10),
1859
+ actualFee: actualFee.toString(10),
1860
+ tokenAddress: deposit.token.address,
1861
+ buyer: input.buyer,
1862
+ relayer: input.relayer,
1863
+ rollup: deposit.rollup,
1864
+ evidenceHash: deposit.evidence.hash
1865
+ };
1866
+ }
1867
+ return out;
1868
+ };
1869
+ const enableFallbackDeposit = options.fallbackToDepositOnPurchaseFailure ?? input.fallbackToDepositOnPurchaseFailure ?? false;
1870
+ const fullResult = await executeTransactionBlock({
1871
+ id: input.id,
1872
+ from: input.relayer,
1873
+ statements: [depositStatement, ...normalizedPurchaseStatements],
1874
+ enforceZeroSum: true
1875
+ }, {
1876
+ statedb: options.statedb,
1877
+ executeStatement: wrappedExecutor,
1878
+ dryRun: options.dryRun
1879
+ });
1880
+ if (fullResult.ok) return {
1881
+ ...fullResult,
1882
+ degradedToDepositOnly: false
1883
+ };
1884
+ if (enableFallbackDeposit && depositStepCompleted) {
1885
+ const fallbackResult = await executeTransactionBlock({
1886
+ id: input.id ? `${input.id}:deposit-fallback` : void 0,
1887
+ from: input.relayer,
1888
+ statements: [depositStatement],
1889
+ enforceZeroSum: true
1890
+ }, {
1891
+ statedb: options.statedb,
1892
+ executeStatement: wrappedExecutor,
1893
+ dryRun: options.dryRun
1894
+ });
1895
+ if (fallbackResult.ok) return {
1896
+ ...fallbackResult,
1897
+ degradedToDepositOnly: true,
1898
+ purchaseError: fullResult.error?.message || "Downstream purchase statement failed"
1899
+ };
1900
+ return fallbackResult;
1901
+ }
1902
+ return fullResult;
1903
+ }
1904
+
1905
+ //#endregion
1906
+ export { CONTRACT_NFT_KIND, DEFAULT_MAX_STATEMENTS_PER_HOT_KEY_PER_BLOCK, HARD_MAX_TX_BLOCK_STATEMENTS, MAX_CONTRACT_ARGS_BYTES, MAX_CONTRACT_FOOTPRINT_KEYS, MAX_CONTRACT_NFT_STATEMENTS, MAX_EXECUTE_ASSET_CALLS_PER_BLOCK, MAX_EXECUTE_ASSET_DEPTH, MAX_TX_BLOCK_BYTES, MAX_TX_BLOCK_READ_KEYS, MAX_TX_BLOCK_STATE_DIFF_ENTRIES, MAX_TX_BLOCK_TOP_LEVEL_STATEMENTS, MAX_TX_BLOCK_TOTAL_EXPANDED_STATEMENTS, MAX_TX_BLOCK_WRITE_KEYS, OverlayStateDB, StagedSyncPipeline, TwoPhaseCommitCoordinator, TwoPhaseTransferLedger, assertLeafStatementTemplateOnly, assertTransactionBlockResourceBudget, buildWalletClearSigningPreview, computeAccountAndAssetNetEffects, createOverlayStateDB, executeContractNft, executeCrossChainPurchaseBlock, executeTransactionBlock, extractStateFootprint, hasStateConflict, isExecuteAssetStatement, resolveEffectiveResourceBudget, resolveStatementReferences, scheduleParallelBatches, verifyTransactionBlockPostConditions };