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