@ocap/tx-protocols 1.31.0 → 1.31.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/esm/bridge-release-crypto.d.mts +39 -0
  2. package/esm/bridge-release-crypto.mjs +88 -0
  3. package/esm/bridge-release-window.d.mts +47 -0
  4. package/esm/bridge-release-window.mjs +62 -0
  5. package/esm/bridge-reserve.d.mts +24 -0
  6. package/esm/bridge-reserve.mjs +41 -0
  7. package/esm/execute.d.mts +5 -3
  8. package/esm/execute.mjs +593 -21
  9. package/esm/gas-security-guard.d.mts +7 -2
  10. package/esm/gas-security-guard.mjs +25 -16
  11. package/esm/index.d.mts +38 -19
  12. package/esm/index.mjs +7 -3
  13. package/esm/pipes/ensure-cost.mjs +36 -10
  14. package/esm/pipes/write-ledger.d.mts +2 -2
  15. package/esm/pipes/write-ledger.mjs +6 -3
  16. package/esm/protocols/account/delegate.mjs +6 -4
  17. package/esm/protocols/account/migrate.mjs +5 -3
  18. package/esm/protocols/account/revoke-delegate.mjs +5 -3
  19. package/esm/protocols/asset/acquire-v2.mjs +3 -1
  20. package/esm/protocols/asset/acquire-v3.mjs +4 -2
  21. package/esm/protocols/asset/consume.mjs +3 -1
  22. package/esm/protocols/asset/create.mjs +4 -2
  23. package/esm/protocols/asset/mint.mjs +4 -2
  24. package/esm/protocols/asset/pipes/exec-mint-hook.mjs +1 -1
  25. package/esm/protocols/asset/pipes/verify-itx-address.mjs +1 -1
  26. package/esm/protocols/asset/pipes/verify-itx-assets.mjs +1 -1
  27. package/esm/protocols/asset/update.mjs +4 -2
  28. package/esm/protocols/bridge/release.d.mts +34 -0
  29. package/esm/protocols/bridge/release.mjs +385 -0
  30. package/esm/protocols/factory/create.mjs +4 -2
  31. package/esm/protocols/governance/claim-stake.mjs +35 -11
  32. package/esm/protocols/governance/return-stake.mjs +4 -2
  33. package/esm/protocols/governance/revoke-ledger.d.mts +34 -0
  34. package/esm/protocols/governance/revoke-ledger.mjs +179 -0
  35. package/esm/protocols/governance/revoke-stake.d.mts +7 -2
  36. package/esm/protocols/governance/revoke-stake.mjs +58 -29
  37. package/esm/protocols/governance/slash-stake.mjs +14 -4
  38. package/esm/protocols/governance/stake.mjs +6 -4
  39. package/esm/protocols/rollup/bridge-create.d.mts +13 -0
  40. package/esm/protocols/rollup/bridge-create.mjs +206 -0
  41. package/esm/protocols/rollup/bridge-membership.d.mts +10 -0
  42. package/esm/protocols/rollup/bridge-membership.mjs +154 -0
  43. package/esm/protocols/rollup/bridge-migrate.d.mts +10 -0
  44. package/esm/protocols/rollup/bridge-migrate.mjs +208 -0
  45. package/esm/protocols/rollup/bridge-v2.d.mts +113 -0
  46. package/esm/protocols/rollup/bridge-v2.mjs +219 -0
  47. package/esm/protocols/rollup/claim-reward.mjs +4 -2
  48. package/esm/protocols/rollup/close.d.mts +2 -1
  49. package/esm/protocols/rollup/close.mjs +59 -6
  50. package/esm/protocols/rollup/create-block.mjs +4 -2
  51. package/esm/protocols/rollup/create.d.mts +3 -0
  52. package/esm/protocols/rollup/create.mjs +45 -6
  53. package/esm/protocols/rollup/join.d.mts +2 -1
  54. package/esm/protocols/rollup/join.mjs +31 -23
  55. package/esm/protocols/rollup/leave.d.mts +2 -1
  56. package/esm/protocols/rollup/leave.mjs +32 -24
  57. package/esm/protocols/rollup/migrate.d.mts +2 -1
  58. package/esm/protocols/rollup/migrate.mjs +19 -10
  59. package/esm/protocols/rollup/pause.d.mts +4 -1
  60. package/esm/protocols/rollup/pause.mjs +50 -6
  61. package/esm/protocols/rollup/pipes/verify-evidence.mjs +2 -2
  62. package/esm/protocols/rollup/resume.d.mts +2 -1
  63. package/esm/protocols/rollup/resume.mjs +26 -6
  64. package/esm/protocols/rollup/update.d.mts +5 -1
  65. package/esm/protocols/rollup/update.mjs +56 -9
  66. package/esm/protocols/token/create.mjs +4 -2
  67. package/esm/protocols/token/deposit-v2.mjs +5 -3
  68. package/esm/protocols/token/withdraw-v2.mjs +5 -3
  69. package/esm/protocols/token-factory/burn.mjs +4 -2
  70. package/esm/protocols/token-factory/create.mjs +8 -4
  71. package/esm/protocols/token-factory/mint.mjs +4 -2
  72. package/esm/protocols/token-factory/update.mjs +20 -5
  73. package/esm/protocols/trade/exchange-v2.d.mts +5 -1
  74. package/esm/protocols/trade/exchange-v2.mjs +89 -4
  75. package/esm/protocols/trade/transfer-v2.mjs +15 -4
  76. package/esm/protocols/trade/transfer-v3.mjs +5 -3
  77. package/esm/stateless-prefix.d.mts +16 -0
  78. package/esm/stateless-prefix.mjs +82 -0
  79. package/esm/tx-timer.d.mts +1 -1
  80. package/esm/tx-timer.mjs +1 -1
  81. package/esm/util.mjs +2 -2
  82. package/lib/bridge-release-crypto.cjs +93 -0
  83. package/lib/bridge-release-crypto.d.cts +39 -0
  84. package/lib/bridge-release-window.cjs +69 -0
  85. package/lib/bridge-release-window.d.cts +47 -0
  86. package/lib/bridge-reserve.cjs +45 -0
  87. package/lib/bridge-reserve.d.cts +24 -0
  88. package/lib/execute.cjs +594 -19
  89. package/lib/execute.d.cts +4 -2
  90. package/lib/gas-security-guard.cjs +25 -16
  91. package/lib/gas-security-guard.d.cts +7 -2
  92. package/lib/index.cjs +10 -1
  93. package/lib/index.d.cts +37 -18
  94. package/lib/pipes/ensure-cost.cjs +37 -11
  95. package/lib/pipes/write-ledger.cjs +6 -3
  96. package/lib/pipes/write-ledger.d.cts +2 -2
  97. package/lib/protocols/account/delegate.cjs +6 -4
  98. package/lib/protocols/account/migrate.cjs +5 -3
  99. package/lib/protocols/account/revoke-delegate.cjs +5 -3
  100. package/lib/protocols/asset/acquire-v2.cjs +3 -1
  101. package/lib/protocols/asset/acquire-v3.cjs +4 -2
  102. package/lib/protocols/asset/consume.cjs +3 -1
  103. package/lib/protocols/asset/create.cjs +4 -2
  104. package/lib/protocols/asset/mint.cjs +4 -2
  105. package/lib/protocols/asset/pipes/exec-mint-hook.cjs +1 -1
  106. package/lib/protocols/asset/pipes/verify-itx-address.cjs +1 -1
  107. package/lib/protocols/asset/pipes/verify-itx-assets.cjs +1 -1
  108. package/lib/protocols/asset/update.cjs +4 -2
  109. package/lib/protocols/bridge/release.cjs +390 -0
  110. package/lib/protocols/bridge/release.d.cts +34 -0
  111. package/lib/protocols/factory/create.cjs +4 -2
  112. package/lib/protocols/governance/claim-stake.cjs +35 -11
  113. package/lib/protocols/governance/return-stake.cjs +4 -2
  114. package/lib/protocols/governance/revoke-ledger.cjs +184 -0
  115. package/lib/protocols/governance/revoke-ledger.d.cts +34 -0
  116. package/lib/protocols/governance/revoke-stake.cjs +58 -29
  117. package/lib/protocols/governance/revoke-stake.d.cts +7 -2
  118. package/lib/protocols/governance/slash-stake.cjs +14 -4
  119. package/lib/protocols/governance/stake.cjs +6 -4
  120. package/lib/protocols/rollup/bridge-create.cjs +209 -0
  121. package/lib/protocols/rollup/bridge-create.d.cts +13 -0
  122. package/lib/protocols/rollup/bridge-membership.cjs +157 -0
  123. package/lib/protocols/rollup/bridge-membership.d.cts +10 -0
  124. package/lib/protocols/rollup/bridge-migrate.cjs +212 -0
  125. package/lib/protocols/rollup/bridge-migrate.d.cts +10 -0
  126. package/lib/protocols/rollup/bridge-v2.cjs +244 -0
  127. package/lib/protocols/rollup/bridge-v2.d.cts +113 -0
  128. package/lib/protocols/rollup/claim-reward.cjs +4 -2
  129. package/lib/protocols/rollup/close.cjs +59 -6
  130. package/lib/protocols/rollup/close.d.cts +2 -1
  131. package/lib/protocols/rollup/create-block.cjs +4 -2
  132. package/lib/protocols/rollup/create.cjs +45 -6
  133. package/lib/protocols/rollup/create.d.cts +3 -0
  134. package/lib/protocols/rollup/join.cjs +31 -23
  135. package/lib/protocols/rollup/join.d.cts +2 -1
  136. package/lib/protocols/rollup/leave.cjs +32 -24
  137. package/lib/protocols/rollup/leave.d.cts +2 -1
  138. package/lib/protocols/rollup/migrate.cjs +19 -10
  139. package/lib/protocols/rollup/migrate.d.cts +2 -1
  140. package/lib/protocols/rollup/pause.cjs +50 -6
  141. package/lib/protocols/rollup/pause.d.cts +4 -1
  142. package/lib/protocols/rollup/pipes/verify-evidence.cjs +2 -2
  143. package/lib/protocols/rollup/resume.cjs +26 -6
  144. package/lib/protocols/rollup/resume.d.cts +2 -1
  145. package/lib/protocols/rollup/update.cjs +56 -9
  146. package/lib/protocols/rollup/update.d.cts +5 -1
  147. package/lib/protocols/token/create.cjs +4 -2
  148. package/lib/protocols/token/deposit-v2.cjs +5 -3
  149. package/lib/protocols/token/withdraw-v2.cjs +5 -3
  150. package/lib/protocols/token-factory/burn.cjs +4 -2
  151. package/lib/protocols/token-factory/create.cjs +8 -4
  152. package/lib/protocols/token-factory/mint.cjs +4 -2
  153. package/lib/protocols/token-factory/update.cjs +20 -5
  154. package/lib/protocols/trade/exchange-v2.cjs +90 -3
  155. package/lib/protocols/trade/exchange-v2.d.cts +5 -1
  156. package/lib/protocols/trade/transfer-v2.cjs +15 -4
  157. package/lib/protocols/trade/transfer-v3.cjs +5 -3
  158. package/lib/stateless-prefix.cjs +88 -0
  159. package/lib/stateless-prefix.d.cts +16 -0
  160. package/lib/tx-timer.cjs +1 -1
  161. package/lib/tx-timer.d.cts +1 -1
  162. package/lib/util.cjs +2 -2
  163. package/package.json +16 -16
  164. package/tools/fixtures.ts +9 -4
package/lib/execute.cjs CHANGED
@@ -1,18 +1,23 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
3
+ const require_bridge_reserve = require('./bridge-reserve.cjs');
3
4
  const require_gas_security_guard = require('./gas-security-guard.cjs');
5
+ const require_util = require('./util.cjs');
4
6
  const require_pipes_ensure_cost = require('./pipes/ensure-cost.cjs');
5
7
  const require_pipes_ensure_gas = require('./pipes/ensure-gas.cjs');
6
8
  const require_pipes_write_ledger = require('./pipes/write-ledger.cjs');
9
+ const require_stateless_prefix = require('./stateless-prefix.cjs');
7
10
  const require_tx_timer = require('./tx-timer.cjs');
8
- let _arcblock_did = require("@arcblock/did");
9
- let _arcblock_did_util = require("@arcblock/did-util");
10
11
  let _ocap_mcrypto = require("@ocap/mcrypto");
11
- let _ocap_state = require("@ocap/state");
12
12
  let _ocap_tx_pipeline = require("@ocap/tx-pipeline");
13
- let _ocap_util = require("@ocap/util");
14
13
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
15
14
  let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
15
+ let _arcblock_did = require("@arcblock/did");
16
+ let _arcblock_did_util = require("@arcblock/did-util");
17
+ let _arcblock_jwt = require("@arcblock/jwt");
18
+ _arcblock_jwt = require_rolldown_runtime.__toESM(_arcblock_jwt);
19
+ let _ocap_state = require("@ocap/state");
20
+ let _ocap_util = require("@ocap/util");
16
21
  let _ocap_util_lib_get_related_addr = require("@ocap/util/lib/get-related-addr");
17
22
  let lodash_camelCase = require("lodash/camelCase");
18
23
  lodash_camelCase = require_rolldown_runtime.__toESM(lodash_camelCase);
@@ -26,6 +31,20 @@ let lodash_pick = require("lodash/pick");
26
31
  lodash_pick = require_rolldown_runtime.__toESM(lodash_pick);
27
32
 
28
33
  //#region src/execute.ts
34
+ const ZERO = new _ocap_util.BN(0);
35
+ const PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL = _ocap_tx_pipeline.pipes.PreFlightWaf.SNAPSHOT_SYMBOL || Symbol.for("@ocap/tx-pipeline/preFlightVerifiedSnapshot");
36
+ const tryApplyPreFlightVerifiedSnapshot = (context) => {
37
+ const fn = _ocap_tx_pipeline.pipes.PreFlightWaf.tryApplyVerifiedSnapshot;
38
+ return typeof fn === "function" ? fn(context) : false;
39
+ };
40
+ function isMatchingAccountPublicKey(onChainPk, headerPk) {
41
+ if (onChainPk === headerPk) return true;
42
+ try {
43
+ const headerBuf = (0, _ocap_util.toBuffer)(headerPk);
44
+ if ((0, _ocap_util.toBase58)(headerBuf) === onChainPk || (0, _ocap_util.toBase64)(headerBuf) === onChainPk) return true;
45
+ } catch {}
46
+ return false;
47
+ }
29
48
  const ensureTxGas = require_pipes_ensure_gas.default(() => ({
30
49
  create: 0,
31
50
  update: 2
@@ -72,6 +91,29 @@ const MULTISIG_DELEGATION_TX_TYPES = new Set([
72
91
  "fg:t:exchange_v2",
73
92
  "fg:t:transfer_v3"
74
93
  ]);
94
+ /** Zero-stake onboarding transaction types permitted from a non-existent sender within free-gas size ceilings. */
95
+ const ONBOARDING_FREE_TX_TYPES = new Set([
96
+ "declare",
97
+ "poke",
98
+ "faucet"
99
+ ]);
100
+ /**
101
+ * Transaction types whose protocol pipeline uses `status: 'OK'` on `ExtractState({ from: 'tx.from', to: 'senderState' })`
102
+ * and can therefore execute when `tx.from` has no `statedb.account` row (and is not an existing `ROLE_ASSET`).
103
+ */
104
+ const NON_EXISTENT_SENDER_CAPABLE_TX_TYPES = new Set([
105
+ "declare",
106
+ "poke",
107
+ "faucet",
108
+ "delegate",
109
+ "account_migrate",
110
+ "acquire_asset_v3",
111
+ "stake",
112
+ "burn_token",
113
+ "mint_token",
114
+ "deposit_token_v2",
115
+ "transfer_v3"
116
+ ]);
75
117
  const shouldPersistTx = (err, context) => {
76
118
  if (!err) return true;
77
119
  if (!(0, lodash_get.default)(err, "props.persist")) return false;
@@ -128,6 +170,20 @@ const createExecute = ({ filter, runAsLambda }) => {
128
170
  resolve();
129
171
  })).catch(reject);
130
172
  });
173
+ /**
174
+ * Append the tx to the verifiable ledger at the point where its tx state is written (#1419).
175
+ *
176
+ * Invariant: a ledger row exists only for a tx that also gets a `statedb.tx` row, i.e. a successful tx or a
177
+ * failed tx that went through the failed-tx gas charge (`ensureGasFeePaid`). The append used to run in the
178
+ * pre-execute pipeline, ahead of the protocol runner, so every protocol-phase rejection that is not persisted
179
+ * (itx schema errors, `VerifyInfo` defaults, every `VerifyDelegation` rejection, multisig signature failures,
180
+ * a failed-tx gas charge nobody can pay) left an uncharged row in the append-only ledger.
181
+ *
182
+ * The append still precedes `statedb.tx.create` and the statedb commit, so the ledger stays write-ahead of the
183
+ * committed state, and `WriteLedger` is idempotent per context (`ledgerSequence`), so `runAsLambda` retries
184
+ * reuse the sequence allocated by the first attempt (#973).
185
+ */
186
+ const appendLedgerEntry = (context) => runSinglePipe(require_pipes_write_ledger.WriteLedger, context);
131
187
  const hasCommittedUnsignedTx = async (context) => {
132
188
  if (!context.unsignedTxHash || !hasEvidenceStore(context.statedb)) return false;
133
189
  const unsignedKey = toUnsignedEvidenceKey(context.unsignedTxHash);
@@ -163,16 +219,442 @@ const createExecute = ({ filter, runAsLambda }) => {
163
219
  * - Sender migrated (statedb resolves `tx.from` to its successor): reject like
164
220
  * VerifyAccountMigration, but before the ledger write.
165
221
  */
222
+ /**
223
+ * Pre-ledger admission check for non-existent senders (#1359).
224
+ *
225
+ * When `tx.from` has no account in `statedb.account`, it cannot pay direct gas or service fees
226
+ * from `senderState`. Rejecting unpaid or unexecutable transactions from non-existent senders before
227
+ * `WriteLedger` prevents unauthenticated actors from appending uncompensated entries to the immutable
228
+ * ledger for free.
229
+ */
230
+ const estimatePreLedgerGasOps = async (context, shortTxType, from, statedb, isExistingAssetSender) => {
231
+ const itx = context.itx || {};
232
+ const accountStore = statedb?.account;
233
+ const inputs = (0, _ocap_util_lib_get_list_field.getListField)(itx, "inputs") || [];
234
+ const uniqueInputOwners = Array.from(new Set(inputs.map((inp) => typeof inp?.owner === "string" ? inp.owner : "").filter(Boolean)));
235
+ const uniqueInputAssets = Array.from(new Set(inputs.flatMap((inp) => (0, _ocap_util_lib_get_list_field.getListField)(inp, "assets") || []).filter((a) => typeof a === "string" && a.length > 0)));
236
+ switch (shortTxType) {
237
+ case "declare": return {
238
+ create: 1,
239
+ update: 0,
240
+ isGasSelfStakeTx: false
241
+ };
242
+ case "poke": return {
243
+ create: 1,
244
+ update: 1,
245
+ isGasSelfStakeTx: false
246
+ };
247
+ case "faucet": return {
248
+ create: 0,
249
+ update: 1,
250
+ isGasSelfStakeTx: false
251
+ };
252
+ case "account_migrate": return {
253
+ create: 2,
254
+ update: 0,
255
+ isGasSelfStakeTx: false
256
+ };
257
+ case "delegate": {
258
+ const result = {
259
+ create: 0,
260
+ update: 1,
261
+ isGasSelfStakeTx: false
262
+ };
263
+ const toAddr = typeof itx.to === "string" ? itx.to : "";
264
+ if (Boolean(toAddr) && typeof accountStore?.get === "function" && Boolean(await accountStore.get(toAddr, context))) result.update += 1;
265
+ else result.create += 1;
266
+ const delAddr = typeof itx.address === "string" ? itx.address : "";
267
+ if (Boolean(delAddr) && typeof statedb?.delegation?.get === "function" && Boolean(await statedb.delegation.get(delAddr, context))) result.update += 1;
268
+ else result.create += 1;
269
+ return result;
270
+ }
271
+ case "deposit_token_v2": {
272
+ const result = {
273
+ create: 2,
274
+ update: 1,
275
+ isGasSelfStakeTx: false
276
+ };
277
+ const proposer = typeof itx.proposer === "string" ? itx.proposer : "";
278
+ const toAddr = typeof itx.to === "string" ? itx.to : "";
279
+ if (proposer === from && toAddr && toAddr !== from) if (typeof accountStore?.get === "function" && Boolean(await accountStore.get(toAddr, context))) result.update += 1;
280
+ else result.create += 1;
281
+ const rollupAddr = typeof itx.rollup === "string" ? itx.rollup : "";
282
+ if (Boolean(rollupAddr) && typeof statedb?.stake?.get === "function" && Boolean(await statedb.stake.get(require_util.getRewardLocker(rollupAddr), context))) result.update += 1;
283
+ else result.create += 1;
284
+ return result;
285
+ }
286
+ case "acquire_asset_v3": {
287
+ const result = {
288
+ create: 1,
289
+ update: 2 + uniqueInputOwners.length + uniqueInputAssets.length,
290
+ isGasSelfStakeTx: false
291
+ };
292
+ const ownerAddr = typeof itx.owner === "string" ? itx.owner : "";
293
+ if (!(Boolean(ownerAddr) && typeof accountStore?.get === "function" && Boolean(await accountStore.get(ownerAddr, context)))) result.create += 1;
294
+ return result;
295
+ }
296
+ case "transfer_v3": {
297
+ const result = {
298
+ create: 1,
299
+ update: uniqueInputOwners.length + uniqueInputAssets.length,
300
+ isGasSelfStakeTx: false
301
+ };
302
+ const outputs = (0, _ocap_util_lib_get_list_field.getListField)(itx, "outputs") || [];
303
+ const uniqueReceivers = Array.from(new Set(outputs.map((out) => typeof out?.owner === "string" ? out.owner : "").filter(Boolean)));
304
+ for (const r of uniqueReceivers) if (typeof accountStore?.get === "function" && Boolean(await accountStore.get(r, context))) result.update += 1;
305
+ else result.create += 1;
306
+ return result;
307
+ }
308
+ case "mint_token":
309
+ case "burn_token": {
310
+ const result = {
311
+ create: 1,
312
+ update: 2 + uniqueInputOwners.length,
313
+ isGasSelfStakeTx: false
314
+ };
315
+ const receiverAddr = typeof itx.receiver === "string" ? itx.receiver : "";
316
+ if (Boolean(receiverAddr) && typeof accountStore?.get === "function" && Boolean(await accountStore.get(receiverAddr, context))) result.update += 1;
317
+ else result.create += 1;
318
+ if (itx.reserveFee && /^\d+$/.test(String(itx.reserveFee)) && new _ocap_util.BN(String(itx.reserveFee)).gt(ZERO)) result.update += 1;
319
+ return result;
320
+ }
321
+ case "stake": {
322
+ const stakeAddr = typeof itx.address === "string" ? itx.address : "";
323
+ const normalizedInputs = inputs.map((inp) => ({
324
+ assetsList: (0, _ocap_util_lib_get_list_field.getListField)(inp, "assets") || [],
325
+ tokensList: (0, _ocap_util_lib_get_list_field.getListField)(inp, "tokens") || []
326
+ }));
327
+ const officialTok = context.config?.token?.address || "";
328
+ if (stakeAddr && officialTok && require_util.isGasStakeAddress(from, stakeAddr) && require_util.isGasStakeInput(normalizedInputs, officialTok)) return {
329
+ create: 0,
330
+ update: 0,
331
+ isGasSelfStakeTx: true
332
+ };
333
+ const result = {
334
+ create: 1,
335
+ update: uniqueInputOwners.length + uniqueInputAssets.length,
336
+ isGasSelfStakeTx: false
337
+ };
338
+ if (Boolean(stakeAddr) && typeof statedb?.stake?.get === "function" && Boolean(await statedb.stake.get(stakeAddr, context))) result.update += 1;
339
+ else result.create += 1;
340
+ return result;
341
+ }
342
+ default:
343
+ if (shortTxType === "create_asset" || shortTxType === "create_factory" || shortTxType === "create_token" || shortTxType === "create_token_factory" || shortTxType === "create_rollup") return {
344
+ create: 1,
345
+ update: 2,
346
+ isGasSelfStakeTx: false
347
+ };
348
+ if (shortTxType === "transfer_v2" || shortTxType === "transfer") {
349
+ const toAddr = typeof itx.to === "string" ? itx.to : "";
350
+ const hasReceiver = Boolean(toAddr) && typeof accountStore?.get === "function" && Boolean(await accountStore.get(toAddr, context));
351
+ const assetsList = (0, _ocap_util_lib_get_list_field.getListField)(itx, "assets") || [];
352
+ return {
353
+ create: hasReceiver ? 0 : 1,
354
+ update: (isExistingAssetSender ? 1 : 0) + (hasReceiver ? 1 : 0) + assetsList.length,
355
+ isGasSelfStakeTx: false
356
+ };
357
+ }
358
+ return {
359
+ create: 0,
360
+ update: 2,
361
+ isGasSelfStakeTx: false
362
+ };
363
+ }
364
+ };
365
+ const assertNonExistentSenderAdmissible = async (context) => {
366
+ const from = context.tx?.from;
367
+ const statedb = context.statedb;
368
+ const accountStore = statedb?.account;
369
+ if (!from || !context.ledger || typeof accountStore?.get !== "function") return;
370
+ if (context.tx?.delegator) {
371
+ if (!await accountStore.get(context.tx.delegator, context)) throw new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "No delegation found between sender and delegator", { persist: false });
372
+ }
373
+ const isExistingAssetSender = (0, _arcblock_did.toTypeInfo)(from).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET && typeof statedb?.asset?.get === "function" && Boolean(await statedb.asset.get(from, context));
374
+ const config = context.config;
375
+ const txType = context.txType;
376
+ const shortTxType = require_gas_security_guard.normalizeShortTxType(txType);
377
+ const assertProtocolAdmissibleWithoutSenderState = async () => {
378
+ if (!isExistingAssetSender && !NON_EXISTENT_SENDER_CAPABLE_TX_TYPES.has(shortTxType)) throw new _ocap_util_lib_error.CustomError("INVALID_SENDER_STATE", `Invalid state extracted for ACCOUNT: ${from}`, { persist: false });
379
+ if (shortTxType === "transfer_v3" || shortTxType === "stake" || shortTxType === "burn_token" || shortTxType === "mint_token" || shortTxType === "acquire_asset_v3") {
380
+ const inputs = (0, _ocap_util_lib_get_list_field.getListField)(context.itx, "inputs") || [];
381
+ if ((shortTxType === "transfer_v3" || shortTxType === "stake" || shortTxType === "burn_token") && inputs.length === 0) throw new _ocap_util_lib_error.CustomError("INVALID_TX", "Invalid itx: inputs must not be empty", { persist: false });
382
+ for (const inp of inputs) {
383
+ if (!inp?.owner) throw new _ocap_util_lib_error.CustomError("INVALID_TX", "Invalid itx: input owner is required", { persist: false });
384
+ if (!(Boolean(await accountStore.get(inp.owner, context)) || (0, _arcblock_did.toTypeInfo)(inp.owner).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET && typeof statedb?.asset?.get === "function" && Boolean(await statedb.asset.get(inp.owner, context)))) throw new _ocap_util_lib_error.CustomError("INVALID_SIGNER_STATE", `Invalid state extracted for ACCOUNT: ${inp.owner}`, { persist: false });
385
+ }
386
+ } else if (shortTxType === "deposit_token_v2") {
387
+ const signatures = (0, _ocap_util_lib_get_list_field.getListField)(context.tx, "signatures") || [];
388
+ if (signatures.length === 0) throw new _ocap_util_lib_error.CustomError("INVALID_TX", "itx.proposer must exist in signatures", { persist: false });
389
+ for (const sig of signatures) if (!sig?.signer || !await accountStore.get(sig.signer, context)) throw new _ocap_util_lib_error.CustomError("INVALID_SIGNER_STATE", `Invalid state extracted for ACCOUNT: ${sig?.signer || ""}`, { persist: false });
390
+ }
391
+ };
392
+ const txFeeMap = config?.transaction?.txFee || {};
393
+ const rawTxFee = txType ? txFeeMap[txType] : void 0;
394
+ const feeCost = typeof rawTxFee === "number" && rawTxFee > 0 && Boolean(config?.token?.decimal) ? (0, _ocap_util.fromTokenToUnit)(rawTxFee, config.token.decimal) : ZERO;
395
+ const txGasCfg = config?.transaction?.txGas;
396
+ const gasPriceRaw = txGasCfg?.price;
397
+ const gasPrice = txGasCfg?.enabled !== false && gasPriceRaw !== void 0 && gasPriceRaw !== null && /^\d+$/.test(String(gasPriceRaw)) ? new _ocap_util.BN(String(gasPriceRaw)) : ZERO;
398
+ const estimatedOps = await estimatePreLedgerGasOps(context, shortTxType, from, statedb, isExistingAssetSender);
399
+ const gasEstimate = {
400
+ create: estimatedOps.create,
401
+ update: estimatedOps.update
402
+ };
403
+ const estimatedTotalGas = Boolean(context.txBaseGas) && !estimatedOps.isGasSelfStakeTx && gasPrice.gt(ZERO) ? gasPrice.mul(new _ocap_util.BN(txGasCfg?.dataStorage || 0)).mul(new _ocap_util.BN(context.txSize || 0)).add(gasPrice.mul(new _ocap_util.BN(txGasCfg?.createState || 0)).mul(new _ocap_util.BN(estimatedOps.create + 1))).add(gasPrice.mul(new _ocap_util.BN(txGasCfg?.updateState || 0)).mul(new _ocap_util.BN(estimatedOps.update))) : ZERO;
404
+ const requiresGasPayment = estimatedTotalGas.gt(ZERO);
405
+ const txSize = context._baseTxSize ?? context.txSize;
406
+ const secCfg = require_gas_security_guard.resolveGasSecurityConfig(config);
407
+ if (feeCost.lte(ZERO)) {
408
+ if (!requiresGasPayment) {
409
+ await assertProtocolAdmissibleWithoutSenderState();
410
+ return;
411
+ }
412
+ if (ONBOARDING_FREE_TX_TYPES.has(shortTxType) && (txSize || 0) <= secCfg.maxFreeGasTxSize) {
413
+ await assertProtocolAdmissibleWithoutSenderState();
414
+ return;
415
+ }
416
+ }
417
+ const extra = context.extra || {};
418
+ const txExtra = extra.txExtra && typeof extra.txExtra === "object" ? extra.txExtra : void 0;
419
+ const { token, pk } = extra.gasStakeHeaders || {};
420
+ const rawGasPass = extra.gasPass || txExtra?.gasPass;
421
+ const txHash = context.txHash || "";
422
+ const txTime = context.txTime;
423
+ const nowMs = txTime ? +new Date(txTime) : Date.now();
424
+ const officialTok = config?.token?.address || "";
425
+ const resolveSelfGasStake = async () => {
426
+ if (!officialTok || typeof statedb?.stake?.get !== "function") return {
427
+ hasSelfStake: false,
428
+ state: null,
429
+ valid: false
430
+ };
431
+ const candidates = Array.from(new Set([from, context.tx?.delegator].filter(Boolean)));
432
+ for (const candidate of candidates) {
433
+ const stakeId = (0, _arcblock_did_util.toStakeAddress)(candidate, candidate);
434
+ const selfStake = await statedb.stake.get(stakeId, context);
435
+ if (new _ocap_util.BN(selfStake?.tokens?.[officialTok] || 0).gt(ZERO)) return {
436
+ hasSelfStake: true,
437
+ state: selfStake,
438
+ valid: require_util.isGasStakeValid(selfStake, config)
439
+ };
440
+ }
441
+ return {
442
+ hasSelfStake: false,
443
+ state: null,
444
+ valid: false
445
+ };
446
+ };
447
+ if (feeCost.lte(ZERO)) {
448
+ if (rawGasPass) {
449
+ const passStakeState = rawGasPass.stakeId && typeof statedb?.stake?.get === "function" ? await statedb.stake.get(rawGasPass.stakeId, context) : null;
450
+ const passResult = require_gas_security_guard.verifyAndConsumeUnlinkableGasPass({
451
+ gasPass: rawGasPass,
452
+ stakeState: passStakeState,
453
+ txHash,
454
+ nowMs,
455
+ config,
456
+ statedb,
457
+ consumeNullifier: false
458
+ });
459
+ if (!passResult.valid) {
460
+ const passErr = new _ocap_util_lib_error.CustomError(passResult.reason || "INVALID_GAS_PASS", `Invalid unlinkable gas pass: ${passResult.reason}`, { persist: false });
461
+ passErr._unauthenticatedExtraFailure = true;
462
+ throw passErr;
463
+ }
464
+ const passOwner = passStakeState?.sender || rawGasPass.stakeId;
465
+ const isThirdPartyGasPass = Boolean(passOwner && !(0, _ocap_util.isSameDid)(passOwner, from) && (!context.tx?.delegator || !(0, _ocap_util.isSameDid)(passOwner, context.tx.delegator)));
466
+ const selfStakeInfo = isThirdPartyGasPass ? await resolveSelfGasStake() : null;
467
+ const selfStakeEligible = Boolean(selfStakeInfo?.valid) && require_gas_security_guard.evaluateStakeForGasEligibility({
468
+ txType,
469
+ txSize,
470
+ gasEstimate,
471
+ isFailedTxGasCharge: false,
472
+ isThirdPartySponsor: false,
473
+ enforceSponsor3DEligibility: false,
474
+ config
475
+ }).eligible;
476
+ const effectiveStakeState = selfStakeInfo?.valid && selfStakeEligible ? selfStakeInfo.state : passStakeState;
477
+ const eligibility = require_gas_security_guard.evaluateStakeForGasEligibility({
478
+ txType,
479
+ txSize,
480
+ gasEstimate,
481
+ isFailedTxGasCharge: false,
482
+ isThirdPartySponsor: selfStakeInfo?.valid && selfStakeEligible ? false : isThirdPartyGasPass,
483
+ enforceSponsor3DEligibility: false,
484
+ config
485
+ });
486
+ if (require_util.isGasStakeValid(effectiveStakeState, config) && eligibility.eligible) {
487
+ await assertProtocolAdmissibleWithoutSenderState();
488
+ return;
489
+ }
490
+ } else if (token && pk) {
491
+ let decoded = {};
492
+ let sponsorAddress = "";
493
+ let issuerMatchesPk = false;
494
+ try {
495
+ if (typeof token === "string" && typeof pk === "string") {
496
+ decoded = _arcblock_jwt.decode(token) || {};
497
+ sponsorAddress = (0, _arcblock_did.toAddress)(decoded.iss || "");
498
+ issuerMatchesPk = Boolean(sponsorAddress && (0, _arcblock_did.isFromPublicKey)(sponsorAddress, pk));
499
+ }
500
+ } catch {
501
+ issuerMatchesPk = false;
502
+ }
503
+ if (!issuerMatchesPk) {
504
+ const hdrErr = new _ocap_util_lib_error.CustomError("INVALID_GAS_STAKE_HEADERS", "Gas stake JWT issuer does not match signer public key", { persist: false });
505
+ hdrErr._unauthenticatedExtraFailure = true;
506
+ throw hdrErr;
507
+ }
508
+ require_bridge_reserve.assertBridgeReserveNotSponsor(sponsorAddress);
509
+ let jwtVerified = false;
510
+ try {
511
+ jwtVerified = Boolean(await _arcblock_jwt.verify(token, pk, {
512
+ enforceTimestamp: !txTime,
513
+ tolerance: 5
514
+ }));
515
+ } catch {
516
+ jwtVerified = false;
517
+ }
518
+ if (jwtVerified) {
519
+ const toleranceSec = 5;
520
+ const nowSec = txTime ? Math.floor(+new Date(txTime) / 1e3) : Math.floor(Date.now() / 1e3);
521
+ const expNum = decoded?.exp != null && decoded.exp !== "" ? Number(decoded.exp) : NaN;
522
+ const expValid = Number.isFinite(expNum) && expNum > 0 && expNum + toleranceSec >= nowSec;
523
+ const nbfNum = decoded?.nbf != null && decoded.nbf !== "" ? Number(decoded.nbf) : NaN;
524
+ const nbfValid = decoded?.nbf == null || decoded.nbf === "" || Number.isFinite(nbfNum) && nbfNum - toleranceSec <= nowSec;
525
+ const iatNum = decoded?.iat != null && decoded.iat !== "" ? Number(decoded.iat) : NaN;
526
+ const iatValid = decoded?.iat == null || decoded.iat === "" || Number.isFinite(iatNum) && iatNum - toleranceSec <= nowSec;
527
+ const txHashes = (decoded.txHash || "").split(",").map((x) => x.trim()).filter(Boolean);
528
+ if (expValid && nbfValid && iatValid && txHashes.includes(txHash)) {
529
+ const sponsorState = await accountStore.get(sponsorAddress, {
530
+ ...context,
531
+ traceMigration: false
532
+ });
533
+ if (sponsorState?.pk && !isMatchingAccountPublicKey(sponsorState.pk, pk)) {
534
+ const pkErr = new _ocap_util_lib_error.CustomError("INVALID_GAS_STAKE_HEADERS", "Gas stake JWT signer public key does not match on-chain sponsor account", { persist: false });
535
+ pkErr._unauthenticatedExtraFailure = true;
536
+ throw pkErr;
537
+ }
538
+ const isSponsorMigrated = Array.isArray(sponsorState?.migratedTo) && sponsorState.migratedTo.length > 0;
539
+ const sponsorAddresses = (0, _ocap_util_lib_get_related_addr.getRelatedAddresses)(sponsorState || { address: sponsorAddress });
540
+ const checkBlocked = async (checker, addr) => {
541
+ if (typeof checker?.isBlocked !== "function") return false;
542
+ if (await Promise.resolve(checker.isBlocked(addr))) return true;
543
+ return Boolean(await Promise.resolve(checker.isBlocked([addr])));
544
+ };
545
+ let isSponsorBlocked = false;
546
+ for (const addr of sponsorAddresses) if (await checkBlocked(filter, addr) || await checkBlocked(statedb?.blacklist, addr)) {
547
+ isSponsorBlocked = true;
548
+ break;
549
+ }
550
+ if (!isSponsorMigrated && !isSponsorBlocked) {
551
+ const sponsorStakeId = (0, _arcblock_did_util.toStakeAddress)(sponsorAddress, sponsorAddress);
552
+ const isDirectMode = decoded.mode === "paymaster" || decoded.chargeSponsorBalance === true;
553
+ const sponsorStakeState = !isDirectMode && typeof statedb?.stake?.get === "function" ? await statedb.stake.get(sponsorStakeId, context) : null;
554
+ const minSponsorBalance = estimatedTotalGas.gt(ZERO) ? estimatedTotalGas : new _ocap_util.BN(1);
555
+ const sponsorIsBacked = isDirectMode ? Boolean(sponsorState && officialTok && new _ocap_util.BN(sponsorState.tokens?.[officialTok] || 0).gte(minSponsorBalance)) : require_util.isGasStakeValid(sponsorStakeState, config);
556
+ const paymasterCheck = require_gas_security_guard.verifyPaymasterConstraints({
557
+ decoded,
558
+ tx: context.tx,
559
+ itx: context.itx,
560
+ txType,
561
+ totalGas: estimatedTotalGas
562
+ });
563
+ if (!paymasterCheck.valid) {
564
+ const pmErr = new _ocap_util_lib_error.CustomError(paymasterCheck.reason || "PAYMASTER_VIOLATION", `Paymaster sponsorship constraint violated: ${paymasterCheck.reason}`, { persist: false });
565
+ pmErr._strikeRecorded = true;
566
+ pmErr._unauthenticatedExtraFailure = true;
567
+ throw pmErr;
568
+ }
569
+ if (paymasterCheck.isPaymasterDirectCharge) {
570
+ const txTargets = require_gas_security_guard.extractTransactionTargets(context.tx, context.itx, txType);
571
+ if ([
572
+ from,
573
+ context.tx?.delegator,
574
+ context.gasVault,
575
+ context.feeVault,
576
+ config?.vaults?.txFee,
577
+ ...Array.isArray(config?.vaults?.txGas) ? config.vaults.txGas : [],
578
+ ...Array.isArray(config?.vaults?.txFees) ? config.vaults.txFees : [],
579
+ ...txTargets
580
+ ].filter(Boolean).some((candidate) => (0, _ocap_util.isSameDid)(sponsorAddress, candidate) || sponsorAddress === candidate)) {
581
+ const aliasErr = new _ocap_util_lib_error.CustomError("PAYMASTER_SPONSOR_ALIAS_FORBIDDEN", "Paymaster direct-charge sponsor cannot alias transaction sender, delegator, target, or vault", { persist: false });
582
+ aliasErr._unauthenticatedExtraFailure = true;
583
+ throw aliasErr;
584
+ }
585
+ }
586
+ const selfStakeInfo = await resolveSelfGasStake();
587
+ const selfStakeEligible = Boolean(selfStakeInfo.valid) && require_gas_security_guard.evaluateStakeForGasEligibility({
588
+ txType,
589
+ txSize,
590
+ gasEstimate,
591
+ isFailedTxGasCharge: false,
592
+ isThirdPartySponsor: false,
593
+ enforceSponsor3DEligibility: false,
594
+ config
595
+ }).eligible;
596
+ if (selfStakeInfo.valid && selfStakeEligible) {
597
+ await assertProtocolAdmissibleWithoutSenderState();
598
+ return;
599
+ }
600
+ if (!sponsorIsBacked && selfStakeInfo.hasSelfStake) {} else if (paymasterCheck.isPaymasterDirectCharge) {
601
+ if (sponsorIsBacked) {
602
+ await assertProtocolAdmissibleWithoutSenderState();
603
+ return;
604
+ }
605
+ } else {
606
+ const eligibility = require_gas_security_guard.evaluateStakeForGasEligibility({
607
+ txType,
608
+ txSize,
609
+ gasEstimate,
610
+ isFailedTxGasCharge: false,
611
+ isThirdPartySponsor: true,
612
+ enforceSponsor3DEligibility: decoded.enforce3DEligibility === true || (config?.transaction?.txGas)?.enforceSponsor3DEligibility === true,
613
+ config
614
+ });
615
+ if (require_util.isGasStakeValid(sponsorStakeState, config) && eligibility.eligible) {
616
+ await assertProtocolAdmissibleWithoutSenderState();
617
+ return;
618
+ }
619
+ }
620
+ }
621
+ }
622
+ }
623
+ }
624
+ if (officialTok && typeof statedb?.stake?.get === "function") {
625
+ const directStakeId = (0, _arcblock_did_util.toStakeAddress)(from, from);
626
+ if (require_util.isGasStakeValid(await statedb.stake.get(directStakeId, context), config)) {
627
+ if (require_gas_security_guard.evaluateStakeForGasEligibility({
628
+ txType,
629
+ txSize,
630
+ gasEstimate,
631
+ isFailedTxGasCharge: false,
632
+ isThirdPartySponsor: false,
633
+ enforceSponsor3DEligibility: false,
634
+ config
635
+ }).eligible) {
636
+ await assertProtocolAdmissibleWithoutSenderState();
637
+ return;
638
+ }
639
+ }
640
+ }
641
+ }
642
+ if (isExistingAssetSender) throw new _ocap_util_lib_error.CustomError("INSUFFICIENT_FUND", `Insufficient fund to pay for tx cost from ${from}`, { persist: false });
643
+ if (txType === "fg:t:account_migrate" || Boolean(token || pk) || Boolean(rawGasPass)) throw new _ocap_util_lib_error.CustomError("INVALID_GAS_PAYER", `Gas payer ${from} does not exist on chain`, { persist: false });
644
+ if (!NON_EXISTENT_SENDER_CAPABLE_TX_TYPES.has(shortTxType)) throw new _ocap_util_lib_error.CustomError("INVALID_SENDER_STATE", `Invalid state extracted for ACCOUNT: ${from}`, { persist: false });
645
+ throw new _ocap_util_lib_error.CustomError("INVALID_SENDER_STATE", `Invalid state extracted for ACCOUNT: ${from}`, { persist: false });
646
+ };
166
647
  const assertSenderNonceFresh = async (context) => {
167
648
  const from = context.tx?.from;
168
649
  const accountStore = context.statedb?.account;
169
- if (!from || typeof accountStore?.get !== "function") return;
650
+ if (!from || typeof accountStore?.get !== "function") return null;
170
651
  const senderState = await accountStore.get(from, context);
171
- if (!senderState) return;
652
+ if (!senderState) return null;
172
653
  if (senderState.address !== from && senderState.address !== _ocap_state.account.ensureChecksumAddress(from)) throw new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `account ${from} is migrated`);
173
654
  const incomingNonceBn = (0, _ocap_state.parseNonceBn)(context.tx?.nonce);
174
655
  const currentNonceBn = (0, _ocap_state.parseNonceBn)(senderState.nonce) ?? new _ocap_util.BN(0);
175
656
  if (!incomingNonceBn || incomingNonceBn.lte(currentNonceBn)) throw new _ocap_util_lib_error.CustomError("INVALID_NONCE", "nonce must be greater in newer transactions");
657
+ return senderState;
176
658
  };
177
659
  /**
178
660
  * Pre-ledger delegation authorization check, run under the pre-write lock BEFORE WriteLedger.
@@ -225,14 +707,62 @@ const createExecute = ({ filter, runAsLambda }) => {
225
707
  }
226
708
  };
227
709
  const pre = new _ocap_tx_pipeline.Runner("pre-execute");
228
- pre.use(_ocap_tx_pipeline.pipes.DecodeTx);
710
+ pre.use((context, next) => {
711
+ context._preFlightSnapshotApplied = false;
712
+ if (tryApplyPreFlightVerifiedSnapshot(context)) {
713
+ context._preFlightSnapshotApplied = true;
714
+ return next();
715
+ }
716
+ return _ocap_tx_pipeline.pipes.DecodeTx(context, next);
717
+ });
229
718
  pre.use(_ocap_tx_pipeline.pipes.VerifyBlocked({
230
719
  filter,
231
720
  stateKeys: ["tx.from"]
232
721
  }));
233
- pre.use(_ocap_tx_pipeline.pipes.DecodeItx);
234
- pre.use(_ocap_tx_pipeline.pipes.VerifyTx);
235
- pre.use(_ocap_tx_pipeline.pipes.VerifyServiceFee);
722
+ pre.use((context, next) => {
723
+ if (context._preFlightSnapshotApplied) {
724
+ context.logger?.info("Tx decoded", {
725
+ txBase64: context.txBase64,
726
+ txHash: context.txHash,
727
+ txTime: context.txTime,
728
+ txSize: context.txSize,
729
+ txType: context.txType,
730
+ request: context.extra?.request
731
+ });
732
+ context.timer?.mark?.("decode");
733
+ return next();
734
+ }
735
+ return _ocap_tx_pipeline.pipes.DecodeItx(context, next);
736
+ });
737
+ pre.use((context, next) => {
738
+ if (context._preFlightSnapshotApplied) return next();
739
+ return _ocap_tx_pipeline.pipes.VerifyTx(context, next);
740
+ });
741
+ pre.use((context, next) => {
742
+ const protocolsMap = context._protocols;
743
+ if (protocolsMap && context.txType && !protocolsMap[getTxName(context.txType)]) return next(new _ocap_util_lib_error.CustomError("UNSUPPORTED_TX", `Unsupported tx type ${context.txType}`, { persist: false }));
744
+ return next();
745
+ });
746
+ pre.use((context, next) => {
747
+ try {
748
+ require_bridge_reserve.assertBridgeReserveNotActor(context);
749
+ return next();
750
+ } catch (err) {
751
+ return next(err);
752
+ }
753
+ });
754
+ pre.use(async (context, next) => {
755
+ try {
756
+ await require_stateless_prefix.assertStatelessTxRules(context, context._protocols);
757
+ return next();
758
+ } catch (err) {
759
+ return next(err);
760
+ }
761
+ });
762
+ pre.use((context, next) => {
763
+ if (context._preFlightSnapshotApplied) return next();
764
+ return _ocap_tx_pipeline.pipes.VerifyServiceFee(context, next);
765
+ });
236
766
  pre.use(async (context, next) => {
237
767
  const syncState = getSyncState(context);
238
768
  const execId = context.executionId;
@@ -248,9 +778,21 @@ const createExecute = ({ filter, runAsLambda }) => {
248
778
  filter.add(context.txHash);
249
779
  return next();
250
780
  });
251
- pre.use(_ocap_tx_pipeline.pipes.VerifyTxSize);
252
- pre.use(_ocap_tx_pipeline.pipes.PreFlightWaf);
253
- pre.use(_ocap_tx_pipeline.pipes.VerifySignature);
781
+ pre.use((context, next) => {
782
+ if (context._preFlightSnapshotApplied) return next();
783
+ return _ocap_tx_pipeline.pipes.VerifyTxSize(context, next);
784
+ });
785
+ pre.use((context, next) => {
786
+ if (context._preFlightSnapshotApplied) return next();
787
+ return _ocap_tx_pipeline.pipes.PreFlightWaf(context, next);
788
+ });
789
+ pre.use((context, next) => {
790
+ if (context._preFlightSnapshotApplied) {
791
+ context.timer?.mark?.("verify");
792
+ return next();
793
+ }
794
+ return _ocap_tx_pipeline.pipes.VerifySignature(context, next);
795
+ });
254
796
  pre.use((context, next) => {
255
797
  context.isSignatureVerified = true;
256
798
  return next();
@@ -265,16 +807,16 @@ const createExecute = ({ filter, runAsLambda }) => {
265
807
  const existingTxOwner = syncState.inFlightTxHashes.get(context.txHash);
266
808
  if (existingTxOwner && existingTxOwner !== execId) throw new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
267
809
  }
268
- await assertSenderNonceFresh(context);
810
+ const senderState = await assertSenderNonceFresh(context);
269
811
  await assertDelegationAuthorized(context);
270
812
  if (context.unsignedTxHash) {
271
813
  const existingUnsignedOwner = syncState.inFlightUnsignedTxHashes.get(context.unsignedTxHash);
272
814
  if (existingUnsignedOwner && existingUnsignedOwner !== execId) throw new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
273
815
  }
274
816
  if (await hasCommittedUnsignedTx(context)) throw new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
817
+ if (!senderState) await assertNonExistentSenderAdmissible(context);
275
818
  if (context.txHash) syncState.inFlightTxHashes.set(context.txHash, execId);
276
819
  if (context.unsignedTxHash) syncState.inFlightUnsignedTxHashes.set(context.unsignedTxHash, execId);
277
- await runSinglePipe(require_pipes_write_ledger.WriteLedger, context);
278
820
  });
279
821
  return next();
280
822
  } catch (err) {
@@ -283,8 +825,16 @@ const createExecute = ({ filter, runAsLambda }) => {
283
825
  });
284
826
  const ensureGasFeePaid = (context) => {
285
827
  const gasRunner = new _ocap_tx_pipeline.Runner("ensure-gas-fee-paid");
286
- gasRunner.use((ctx, next) => {
828
+ gasRunner.use(async (ctx, next) => {
287
829
  if (ctx.senderState?.address && ctx.stateSnapshot?.[ctx.senderState.address]) ctx.senderState = (0, lodash_cloneDeep.default)(ctx.stateSnapshot[ctx.senderState.address]);
830
+ else if (!ctx.senderState && ctx.tx?.from && typeof ctx.statedb?.account?.get === "function") {
831
+ const fetched = await ctx.statedb.account.get(ctx.tx.from, ctx);
832
+ if (fetched && (fetched.address === ctx.tx.from || (0, _ocap_util.isSameDid)(fetched.address, ctx.tx.from)) && !(Array.isArray(fetched.migratedTo) && fetched.migratedTo.length > 0)) ctx.senderState = fetched;
833
+ }
834
+ if (ctx.senderState?.address && !ctx.stateSnapshot?.[ctx.senderState.address]) ctx.stateSnapshot = {
835
+ ...ctx.stateSnapshot || {},
836
+ [ctx.senderState.address]: (0, lodash_cloneDeep.default)(ctx.senderState)
837
+ };
288
838
  ctx.isFailedTxGasCharge = true;
289
839
  ctx.gasPaid = false;
290
840
  ctx.senderUpdates = {};
@@ -308,7 +858,7 @@ const createExecute = ({ filter, runAsLambda }) => {
308
858
  }, ctx);
309
859
  ctx.senderState = await statedb.account.update(senderState.address, updates, ctx) || senderState;
310
860
  if (updateVaults) await updateVaults();
311
- }
861
+ } else if (updateVaults) await updateVaults();
312
862
  return next();
313
863
  });
314
864
  return new Promise((resolve, reject) => {
@@ -358,6 +908,7 @@ const createExecute = ({ filter, runAsLambda }) => {
358
908
  if (slashEvidence && !err.slashEvidence) err.slashEvidence = slashEvidence;
359
909
  };
360
910
  const execute = async (context, protocols, isRetrySupported = false) => new Promise((resolve, reject) => {
911
+ context._protocols = protocols;
361
912
  pre.run(context, async (err) => {
362
913
  if (err) {
363
914
  if (!isRetrySupported) await attachSecurityStrikeToError(err, context);
@@ -377,6 +928,7 @@ const createExecute = ({ filter, runAsLambda }) => {
377
928
  let error = rawError;
378
929
  context.timer?.mark("protocol");
379
930
  if (!error) try {
931
+ await (0, _ocap_tx_pipeline.prepareBridgeReserveGate)(context);
380
932
  (0, _ocap_tx_pipeline.inspectPostExecutionInvariants)(context);
381
933
  } catch (invariantErr) {
382
934
  error = invariantErr;
@@ -398,6 +950,20 @@ const createExecute = ({ filter, runAsLambda }) => {
398
950
  await ensureGasFeePaid(context);
399
951
  txState = states.tx.create(context, txStatus);
400
952
  }
953
+ try {
954
+ await appendLedgerEntry(context);
955
+ } catch (ledgerErr) {
956
+ if (!error) {
957
+ await (0, _ocap_tx_pipeline.rollbackTrackedStateWrites)(context);
958
+ context.events = [];
959
+ }
960
+ context.logger?.error("Failed to append transaction to ledger", {
961
+ error: ledgerErr,
962
+ txError: error,
963
+ txHash: context.txHash
964
+ });
965
+ return reject(error || ledgerErr);
966
+ }
401
967
  await context.statedb.tx.create(txState.hash, txState, context);
402
968
  await recordUnsignedTxInStateDb(context, txState.hash);
403
969
  context.timer?.mark("txstate");
@@ -456,15 +1022,17 @@ const createExecute = ({ filter, runAsLambda }) => {
456
1022
  "extra",
457
1023
  "logger",
458
1024
  "ledgerSequence",
459
- "height",
460
1025
  "timer",
461
1026
  "executionId"
462
1027
  ]);
1028
+ const preFlightSnapshot = context[PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL];
1029
+ if (preFlightSnapshot !== void 0) ctx[PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL] = preFlightSnapshot;
463
1030
  ctx.txn = txn;
464
1031
  if (savedLedgerSequence !== void 0) ctx.ledgerSequence = savedLedgerSequence;
465
1032
  ctx.timer?.mark("lockWait");
466
1033
  try {
467
1034
  await execute(ctx, protocols, true);
1035
+ await appendLedgerEntry(ctx);
468
1036
  } finally {
469
1037
  if (ctx.ledgerSequence && !savedLedgerSequence) {
470
1038
  savedLedgerSequence = ctx.ledgerSequence;
@@ -551,6 +1119,11 @@ const createExecute = ({ filter, runAsLambda }) => {
551
1119
  try {
552
1120
  await ensureGasFeePaid(ctx);
553
1121
  await attachSecurityStrikeToError(err, ctx);
1122
+ await appendLedgerEntry(ctx);
1123
+ if (ctx.ledgerSequence && !savedLedgerSequence) {
1124
+ savedLedgerSequence = ctx.ledgerSequence;
1125
+ context.ledgerSequence = ctx.ledgerSequence;
1126
+ }
554
1127
  const state = getStates(context).tx.create(ctx, txStatus);
555
1128
  await ctx.statedb.tx.create(state.hash, state, ctx);
556
1129
  await recordUnsignedTxInStateDb(ctx, state.hash);
@@ -693,6 +1266,8 @@ const createExecute = ({ filter, runAsLambda }) => {
693
1266
  var execute_default = createExecute;
694
1267
 
695
1268
  //#endregion
1269
+ exports.PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL = PREFLIGHT_VERIFIED_SNAPSHOT_SYMBOL;
696
1270
  exports.UNSIGNED_TX_EVIDENCE_DATA_PREFIX = UNSIGNED_TX_EVIDENCE_DATA_PREFIX;
697
1271
  exports.default = execute_default;
698
- exports.toUnsignedEvidenceKey = toUnsignedEvidenceKey;
1272
+ exports.toUnsignedEvidenceKey = toUnsignedEvidenceKey;
1273
+ exports.tryApplyPreFlightVerifiedSnapshot = tryApplyPreFlightVerifiedSnapshot;