@ocap/tx-protocols 1.30.26 → 1.31.0

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 (118) hide show
  1. package/esm/execute.d.mts +7 -0
  2. package/esm/execute.mjs +196 -71
  3. package/esm/gas-security-guard.d.mts +374 -0
  4. package/esm/gas-security-guard.mjs +1101 -0
  5. package/esm/index.d.mts +35 -5
  6. package/esm/index.mjs +3 -1
  7. package/esm/pipes/ensure-cost.mjs +314 -58
  8. package/esm/protocols/account/delegate.mjs +64 -16
  9. package/esm/protocols/account/migrate.d.mts +3 -0
  10. package/esm/protocols/account/migrate.mjs +235 -35
  11. package/esm/protocols/account/revoke-delegate.d.mts +3 -3
  12. package/esm/protocols/account/revoke-delegate.mjs +70 -38
  13. package/esm/protocols/asset/acquire-v2.mjs +29 -12
  14. package/esm/protocols/asset/acquire-v3.mjs +78 -22
  15. package/esm/protocols/asset/calls/transfer-token.mjs +2 -1
  16. package/esm/protocols/asset/calls/transfer.mjs +1 -0
  17. package/esm/protocols/asset/consume.mjs +12 -4
  18. package/esm/protocols/asset/create.mjs +18 -5
  19. package/esm/protocols/asset/mint.mjs +23 -1
  20. package/esm/protocols/asset/pipes/exec-mint-hook.d.mts +21 -1
  21. package/esm/protocols/asset/pipes/exec-mint-hook.mjs +115 -1
  22. package/esm/protocols/asset/pipes/extract-factory-tokens.mjs +14 -8
  23. package/esm/protocols/asset/pipes/verify-itx-address.mjs +9 -0
  24. package/esm/protocols/asset/pipes/verify-itx-assets.mjs +21 -5
  25. package/esm/protocols/asset/update.d.mts +13 -2
  26. package/esm/protocols/asset/update.mjs +133 -14
  27. package/esm/protocols/factory/create.mjs +14 -6
  28. package/esm/protocols/governance/claim-stake.mjs +92 -10
  29. package/esm/protocols/governance/return-stake.mjs +44 -12
  30. package/esm/protocols/governance/revoke-stake.mjs +17 -5
  31. package/esm/protocols/governance/slash-stake.mjs +64 -25
  32. package/esm/protocols/governance/stake.mjs +63 -13
  33. package/esm/protocols/rollup/claim-reward.mjs +39 -20
  34. package/esm/protocols/rollup/close.mjs +1 -1
  35. package/esm/protocols/rollup/create-block.mjs +8 -7
  36. package/esm/protocols/rollup/create.mjs +17 -6
  37. package/esm/protocols/rollup/join.mjs +3 -3
  38. package/esm/protocols/rollup/leave.mjs +1 -1
  39. package/esm/protocols/rollup/migrate.mjs +7 -4
  40. package/esm/protocols/rollup/pipes/verify-evidence.mjs +12 -4
  41. package/esm/protocols/rollup/update.mjs +6 -1
  42. package/esm/protocols/token/create.mjs +23 -12
  43. package/esm/protocols/token/deposit-v2.d.mts +5 -1
  44. package/esm/protocols/token/deposit-v2.mjs +81 -29
  45. package/esm/protocols/token/withdraw-v2.mjs +33 -16
  46. package/esm/protocols/token-factory/burn.mjs +43 -10
  47. package/esm/protocols/token-factory/create.mjs +23 -14
  48. package/esm/protocols/token-factory/mint.mjs +54 -21
  49. package/esm/protocols/token-factory/pipes/verify-icon.mjs +1 -1
  50. package/esm/protocols/token-factory/update.mjs +16 -6
  51. package/esm/protocols/trade/exchange-v2.d.mts +4 -0
  52. package/esm/protocols/trade/exchange-v2.mjs +78 -22
  53. package/esm/protocols/trade/transfer-v2.mjs +44 -13
  54. package/esm/protocols/trade/transfer-v3.mjs +72 -31
  55. package/esm/util.d.mts +3 -1
  56. package/esm/util.mjs +26 -17
  57. package/lib/execute.cjs +193 -67
  58. package/lib/execute.d.cts +7 -0
  59. package/lib/gas-security-guard.cjs +1140 -0
  60. package/lib/gas-security-guard.d.cts +374 -0
  61. package/lib/index.cjs +122 -1
  62. package/lib/index.d.cts +36 -6
  63. package/lib/pipes/ensure-cost.cjs +313 -57
  64. package/lib/protocols/account/delegate.cjs +64 -16
  65. package/lib/protocols/account/migrate.cjs +235 -35
  66. package/lib/protocols/account/migrate.d.cts +3 -0
  67. package/lib/protocols/account/revoke-delegate.cjs +71 -39
  68. package/lib/protocols/account/revoke-delegate.d.cts +3 -3
  69. package/lib/protocols/asset/acquire-v2.cjs +28 -11
  70. package/lib/protocols/asset/acquire-v3.cjs +77 -20
  71. package/lib/protocols/asset/calls/transfer-token.cjs +3 -2
  72. package/lib/protocols/asset/calls/transfer.cjs +1 -0
  73. package/lib/protocols/asset/consume.cjs +11 -3
  74. package/lib/protocols/asset/create.cjs +19 -6
  75. package/lib/protocols/asset/mint.cjs +23 -1
  76. package/lib/protocols/asset/pipes/exec-mint-hook.cjs +117 -1
  77. package/lib/protocols/asset/pipes/exec-mint-hook.d.cts +21 -1
  78. package/lib/protocols/asset/pipes/extract-factory-tokens.cjs +14 -9
  79. package/lib/protocols/asset/pipes/verify-itx-address.cjs +9 -0
  80. package/lib/protocols/asset/pipes/verify-itx-assets.cjs +21 -5
  81. package/lib/protocols/asset/update.cjs +131 -12
  82. package/lib/protocols/asset/update.d.cts +13 -2
  83. package/lib/protocols/factory/create.cjs +14 -6
  84. package/lib/protocols/governance/claim-stake.cjs +92 -9
  85. package/lib/protocols/governance/claim-stake.d.cts +1 -1
  86. package/lib/protocols/governance/return-stake.cjs +44 -11
  87. package/lib/protocols/governance/return-stake.d.cts +1 -1
  88. package/lib/protocols/governance/revoke-stake.cjs +17 -5
  89. package/lib/protocols/governance/revoke-stake.d.cts +1 -1
  90. package/lib/protocols/governance/slash-stake.cjs +64 -24
  91. package/lib/protocols/governance/slash-stake.d.cts +1 -1
  92. package/lib/protocols/governance/stake.cjs +65 -14
  93. package/lib/protocols/rollup/claim-reward.cjs +39 -20
  94. package/lib/protocols/rollup/close.cjs +1 -1
  95. package/lib/protocols/rollup/create-block.cjs +9 -8
  96. package/lib/protocols/rollup/create-block.d.cts +1 -1
  97. package/lib/protocols/rollup/create.cjs +18 -7
  98. package/lib/protocols/rollup/join.cjs +3 -3
  99. package/lib/protocols/rollup/leave.cjs +1 -1
  100. package/lib/protocols/rollup/migrate.cjs +7 -4
  101. package/lib/protocols/rollup/pipes/verify-evidence.cjs +11 -3
  102. package/lib/protocols/rollup/update.cjs +6 -1
  103. package/lib/protocols/token/create.cjs +24 -13
  104. package/lib/protocols/token/deposit-v2.cjs +80 -28
  105. package/lib/protocols/token/deposit-v2.d.cts +5 -1
  106. package/lib/protocols/token/withdraw-v2.cjs +32 -15
  107. package/lib/protocols/token-factory/burn.cjs +42 -9
  108. package/lib/protocols/token-factory/create.cjs +24 -15
  109. package/lib/protocols/token-factory/mint.cjs +53 -20
  110. package/lib/protocols/token-factory/pipes/verify-icon.cjs +1 -1
  111. package/lib/protocols/token-factory/update.cjs +16 -6
  112. package/lib/protocols/trade/exchange-v2.cjs +76 -20
  113. package/lib/protocols/trade/exchange-v2.d.cts +4 -0
  114. package/lib/protocols/trade/transfer-v2.cjs +45 -14
  115. package/lib/protocols/trade/transfer-v3.cjs +72 -30
  116. package/lib/util.cjs +26 -17
  117. package/lib/util.d.cts +4 -2
  118. package/package.json +16 -16
package/lib/execute.cjs CHANGED
@@ -1,16 +1,23 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
3
+ const require_gas_security_guard = require('./gas-security-guard.cjs');
3
4
  const require_pipes_ensure_cost = require('./pipes/ensure-cost.cjs');
4
5
  const require_pipes_ensure_gas = require('./pipes/ensure-gas.cjs');
5
6
  const require_pipes_write_ledger = require('./pipes/write-ledger.cjs');
6
7
  const require_tx_timer = require('./tx-timer.cjs');
8
+ let _arcblock_did = require("@arcblock/did");
9
+ let _arcblock_did_util = require("@arcblock/did-util");
7
10
  let _ocap_mcrypto = require("@ocap/mcrypto");
8
11
  let _ocap_state = require("@ocap/state");
9
12
  let _ocap_tx_pipeline = require("@ocap/tx-pipeline");
10
13
  let _ocap_util = require("@ocap/util");
11
14
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
15
+ let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
16
+ let _ocap_util_lib_get_related_addr = require("@ocap/util/lib/get-related-addr");
12
17
  let lodash_camelCase = require("lodash/camelCase");
13
18
  lodash_camelCase = require_rolldown_runtime.__toESM(lodash_camelCase);
19
+ let lodash_cloneDeep = require("lodash/cloneDeep");
20
+ lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
14
21
  let lodash_get = require("lodash/get");
15
22
  lodash_get = require_rolldown_runtime.__toESM(lodash_get);
16
23
  let lodash_merge = require("lodash/merge");
@@ -45,7 +52,33 @@ const flushEvents = (context, extra = {}) => {
45
52
  });
46
53
  context.events = [];
47
54
  };
48
- const shouldPersistTx = (err) => !err || Boolean((0, lodash_get.default)(err, "props.persist"));
55
+ const SINGLE_SIG_DELEGATION_TX_TYPES = new Set([
56
+ "fg:t:acquire_asset_v2",
57
+ "fg:t:acquire_asset_v3",
58
+ "fg:t:create_asset",
59
+ "fg:t:update_asset",
60
+ "fg:t:create_factory",
61
+ "fg:t:create_rollup",
62
+ "fg:t:create_token_factory",
63
+ "fg:t:update_token_factory",
64
+ "fg:t:create_token",
65
+ "fg:t:exchange_v2",
66
+ "fg:t:transfer",
67
+ "fg:t:transfer_v2",
68
+ "fg:t:transfer_v3"
69
+ ]);
70
+ const MULTISIG_DELEGATION_TX_TYPES = new Set([
71
+ "fg:t:acquire_asset_v3",
72
+ "fg:t:exchange_v2",
73
+ "fg:t:transfer_v3"
74
+ ]);
75
+ const shouldPersistTx = (err, context) => {
76
+ if (!err) return true;
77
+ if (!(0, lodash_get.default)(err, "props.persist")) return false;
78
+ if (context?.tx?.delegator && !context.delegationState && !context.isImplicitDelegation) return false;
79
+ if (((0, _ocap_util_lib_get_list_field.getListField)(context?.tx, "signatures") || []).some((s) => Boolean(s?.delegator)) && !context.isMultiSigDelegationVerified && !context.delegationStates) return false;
80
+ return true;
81
+ };
49
82
  const toUnsignedEvidenceKey = (unsignedTxHash) => (0, _ocap_mcrypto.toTxHash)(Buffer.from(`unsigned-tx:${unsignedTxHash}`));
50
83
  const UNSIGNED_TX_EVIDENCE_DATA_PREFIX = "unsigned-tx:";
51
84
  const hasEvidenceStore = (statedb) => Boolean(statedb && typeof statedb.evidence?.get === "function" && typeof statedb.evidence?.create === "function");
@@ -62,18 +95,11 @@ const getOrCreateSyncState = (target) => {
62
95
  }
63
96
  return state;
64
97
  };
65
- /**
66
- * Determine whether `unsignedTxHash` deduplication in `statedb.evidence` is active
67
- * for the current execution context.
68
- */
69
- const isUnsignedDedupActive = async (context) => {
70
- if (!context.unsignedTxHash) return false;
71
- return (0, _ocap_tx_pipeline.isDedupHeightActive)(context);
72
- };
73
98
  const createExecute = ({ filter, runAsLambda }) => {
74
99
  const fallbackSyncTarget = {};
75
100
  const getSyncState = (context) => {
76
- return getOrCreateSyncState((context?.statedb && typeof context.statedb === "object" ? context.statedb : null) || (context?.ledger && typeof context.ledger === "object" ? context.ledger : null) || fallbackSyncTarget);
101
+ const rawDb = (context?.statedb)?._underlyingStateDb || context?.statedb;
102
+ return getOrCreateSyncState((rawDb && typeof rawDb === "object" ? rawDb : null) || (context?.ledger && typeof context.ledger === "object" ? context.ledger : null) || fallbackSyncTarget);
77
103
  };
78
104
  const withPreWriteLock = async (context, fn) => {
79
105
  const syncState = getSyncState(context);
@@ -110,7 +136,6 @@ const createExecute = ({ filter, runAsLambda }) => {
110
136
  };
111
137
  const recordUnsignedTxInStateDb = async (context, txHash) => {
112
138
  if (!context.unsignedTxHash || !hasEvidenceStore(context.statedb)) return;
113
- if (!await isUnsignedDedupActive(context)) return;
114
139
  const unsignedKey = toUnsignedEvidenceKey(context.unsignedTxHash);
115
140
  if (!await context.statedb.evidence.get(unsignedKey, { txn: context.txn })) {
116
141
  const evState = _ocap_state.evidence.create({
@@ -124,9 +149,9 @@ const createExecute = ({ filter, runAsLambda }) => {
124
149
  }
125
150
  };
126
151
  /**
127
- * Post-activation sender nonce precheck, run under the pre-write lock BEFORE WriteLedger.
152
+ * Sender nonce precheck, run under the pre-write lock BEFORE WriteLedger.
128
153
  *
129
- * Every persisted pre-activation tx has `nonce <= sender.nonce` once the offline migration
154
+ * Every persisted pre-#1127 tx has `nonce <= sender.nonce` once the offline migration
130
155
  * restored each account's max historical nonce. Rejecting stale nonces here (instead of
131
156
  * relying on each protocol's `account.update` after WriteLedger) means a signature-malleated
132
157
  * twin of ANY historical tx is refused without appending a ledger row and without depending
@@ -137,10 +162,6 @@ const createExecute = ({ filter, runAsLambda }) => {
137
162
  * decides as before.
138
163
  * - Sender migrated (statedb resolves `tx.from` to its successor): reject like
139
164
  * VerifyAccountMigration, but before the ledger write.
140
- *
141
- * Activation boundary: only runs when the tx is already active at the expected sequence. A tx
142
- * that is pre-activation here but lands on the activation sequence after WriteLedger skips this
143
- * precheck once; the post-write nonce/dedup checks and the protocol's account.update still apply.
144
165
  */
145
166
  const assertSenderNonceFresh = async (context) => {
146
167
  const from = context.tx?.from;
@@ -153,12 +174,57 @@ const createExecute = ({ filter, runAsLambda }) => {
153
174
  const currentNonceBn = (0, _ocap_state.parseNonceBn)(senderState.nonce) ?? new _ocap_util.BN(0);
154
175
  if (!incomingNonceBn || incomingNonceBn.lte(currentNonceBn)) throw new _ocap_util_lib_error.CustomError("INVALID_NONCE", "nonce must be greater in newer transactions");
155
176
  };
177
+ /**
178
+ * Pre-ledger delegation authorization check, run under the pre-write lock BEFORE WriteLedger.
179
+ *
180
+ * Unauthenticated delegated transactions (`tx.delegator` or multisig `signatures[].delegator`
181
+ * without valid on-chain delegation or implicit asset ownership) are rejected with
182
+ * `persist: false` so they cannot charge gas or advance nonces on the target account.
183
+ * Rejecting them before `WriteLedger` prevents unauthenticated actors from appending
184
+ * orphaned, unpersisted entries to the immutable ledger.
185
+ */
186
+ const assertDelegatorPairAuthorized = async (context, signerAddress, delegatorAddress, noDelegationMsg) => {
187
+ if (!signerAddress || !delegatorAddress) return;
188
+ const statedb = context.statedb;
189
+ const accountStore = statedb?.account;
190
+ if (typeof accountStore?.get !== "function") return;
191
+ const delegatorState = await accountStore.get(delegatorAddress, context);
192
+ if (delegatorState && (!(0, _ocap_util.isSameDid)(delegatorState.address, delegatorAddress) || Array.isArray(delegatorState.migratedTo) && delegatorState.migratedTo.length > 0)) throw new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `Delegator account ${delegatorAddress} is migrated`, { persist: false });
193
+ if ((0, _arcblock_did.toTypeInfo)(signerAddress).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET) {
194
+ if (typeof statedb?.asset?.get !== "function") return;
195
+ let isOwner = false;
196
+ try {
197
+ isOwner = await (0, _ocap_tx_pipeline.verifyImplicitAssetOwnership)(signerAddress, delegatorState || { address: delegatorAddress }, context, delegatorAddress);
198
+ } catch (err) {
199
+ if (err && typeof err === "object") err.props = {
200
+ ...err.props || {},
201
+ persist: false
202
+ };
203
+ throw err;
204
+ }
205
+ if (!isOwner) throw new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", `Account ${delegatorState?.address || delegatorAddress} is not the owner of asset ${signerAddress}`, { persist: false });
206
+ return;
207
+ }
208
+ if (typeof statedb?.delegation?.get !== "function") return;
209
+ const signerState = await accountStore.get(signerAddress, context);
210
+ if (signerState && (!(0, _ocap_util.isSameDid)(signerState.address, signerAddress) || Array.isArray(signerState.migratedTo) && signerState.migratedTo.length > 0)) throw new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `account ${signerAddress} is migrated`, { persist: false });
211
+ if (!signerState || !delegatorState) throw new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", noDelegationMsg, { persist: false });
212
+ const related = (0, _ocap_util_lib_get_related_addr.getRelatedAddresses)(delegatorState);
213
+ if (!(await Promise.all(related.map((x) => statedb.delegation.get((0, _arcblock_did_util.toDelegateAddress)(signerState.address, x), context)))).some(Boolean)) throw new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", noDelegationMsg, { persist: false });
214
+ };
215
+ const assertDelegationAuthorized = async (context) => {
216
+ const tx = context.tx;
217
+ if (tx?.delegator) {
218
+ if (context.txType && !SINGLE_SIG_DELEGATION_TX_TYPES.has(context.txType)) throw new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "Delegation is not supported for this transaction", { persist: false });
219
+ await assertDelegatorPairAuthorized(context, tx.from, tx.delegator, "No delegation found between sender and delegator");
220
+ }
221
+ const signatures = (0, _ocap_util_lib_get_list_field.getListField)(tx, "signatures") || [];
222
+ for (const sig of signatures) if (sig?.delegator) {
223
+ if (context.txType && !MULTISIG_DELEGATION_TX_TYPES.has(context.txType)) throw new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "Delegation is not supported for this transaction", { persist: false });
224
+ await assertDelegatorPairAuthorized(context, sig.signer, sig.delegator, "No delegation found between signer and delegator");
225
+ }
226
+ };
156
227
  const pre = new _ocap_tx_pipeline.Runner("pre-execute");
157
- pre.use(async (context, next) => {
158
- const dedupHeight = (0, _ocap_state.resolveDedupActivationHeight)(context);
159
- if (dedupHeight > 0 && dedupHeight < _ocap_state.PENDING_DEDUP_ACTIVATION_HEIGHT) await (0, _ocap_tx_pipeline.resolveEffectiveHeight)(context);
160
- return next();
161
- });
162
228
  pre.use(_ocap_tx_pipeline.pipes.DecodeTx);
163
229
  pre.use(_ocap_tx_pipeline.pipes.VerifyBlocked({
164
230
  filter,
@@ -175,57 +241,40 @@ const createExecute = ({ filter, runAsLambda }) => {
175
241
  if (filter.has(context.txHash)) {
176
242
  if (await context.statedb.tx.get(context.txHash, context)) return next(new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction"));
177
243
  }
178
- if (await isUnsignedDedupActive(context)) {
179
- const inFlightUnsignedOwner = context.unsignedTxHash ? syncState.inFlightUnsignedTxHashes.get(context.unsignedTxHash) : void 0;
244
+ if (context.unsignedTxHash) {
245
+ const inFlightUnsignedOwner = syncState.inFlightUnsignedTxHashes.get(context.unsignedTxHash);
180
246
  if (inFlightUnsignedOwner && inFlightUnsignedOwner !== execId || await hasCommittedUnsignedTx(context)) return next(new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction"));
181
247
  }
182
248
  filter.add(context.txHash);
183
249
  return next();
184
250
  });
185
251
  pre.use(_ocap_tx_pipeline.pipes.VerifyTxSize);
252
+ pre.use(_ocap_tx_pipeline.pipes.PreFlightWaf);
186
253
  pre.use(_ocap_tx_pipeline.pipes.VerifySignature);
254
+ pre.use((context, next) => {
255
+ context.isSignatureVerified = true;
256
+ return next();
257
+ });
187
258
  pre.use(async (context, next) => {
188
259
  try {
189
260
  await withPreWriteLock(context, async () => {
190
261
  const syncState = getSyncState(context);
191
- if (context.height === void 0 && !context.ledgerSequence) {
192
- delete context.expectedLedgerSequence;
193
- delete context.dedupActive;
194
- const dedupHeight = (0, _ocap_state.resolveDedupActivationHeight)(context);
195
- if (dedupHeight > 0 && dedupHeight < _ocap_state.PENDING_DEDUP_ACTIVATION_HEIGHT) await (0, _ocap_tx_pipeline.resolveEffectiveHeight)(context);
196
- }
197
- const isActiveNow = await isUnsignedDedupActive(context);
198
- context.dedupActive = isActiveNow;
199
262
  const execId = context.executionId || Symbol("tx-exec");
200
263
  context.executionId = execId;
201
264
  if (context.txHash) {
202
265
  const existingTxOwner = syncState.inFlightTxHashes.get(context.txHash);
203
266
  if (existingTxOwner && existingTxOwner !== execId) throw new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
204
267
  }
205
- if (isActiveNow) {
206
- (0, _ocap_tx_pipeline.assertCanonicalActiveTx)(context);
207
- const nonceBn = (0, _ocap_state.parseNonceBn)(context.tx?.nonce);
208
- if (!nonceBn || nonceBn.lte(new _ocap_util.BN(0))) throw new _ocap_util_lib_error.CustomError("INVALID_NONCE", "tx.nonce should be a positive integer");
209
- await assertSenderNonceFresh(context);
210
- if (context.unsignedTxHash) {
211
- const existingUnsignedOwner = syncState.inFlightUnsignedTxHashes.get(context.unsignedTxHash);
212
- if (existingUnsignedOwner && existingUnsignedOwner !== execId) throw new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
213
- }
214
- if (await hasCommittedUnsignedTx(context)) throw new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
268
+ await assertSenderNonceFresh(context);
269
+ await assertDelegationAuthorized(context);
270
+ if (context.unsignedTxHash) {
271
+ const existingUnsignedOwner = syncState.inFlightUnsignedTxHashes.get(context.unsignedTxHash);
272
+ if (existingUnsignedOwner && existingUnsignedOwner !== execId) throw new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
215
273
  }
274
+ if (await hasCommittedUnsignedTx(context)) throw new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
216
275
  if (context.txHash) syncState.inFlightTxHashes.set(context.txHash, execId);
217
- if (isActiveNow && context.unsignedTxHash) syncState.inFlightUnsignedTxHashes.set(context.unsignedTxHash, execId);
276
+ if (context.unsignedTxHash) syncState.inFlightUnsignedTxHashes.set(context.unsignedTxHash, execId);
218
277
  await runSinglePipe(require_pipes_write_ledger.WriteLedger, context);
219
- delete context.dedupActive;
220
- const isActiveAfterWrite = await isUnsignedDedupActive(context);
221
- context.dedupActive = isActiveAfterWrite;
222
- if (isActiveAfterWrite) {
223
- if (!isActiveNow) (0, _ocap_tx_pipeline.assertCanonicalActiveTx)(context);
224
- const nonceBn = (0, _ocap_state.parseNonceBn)(context.tx?.nonce);
225
- if (!nonceBn || nonceBn.lte(new _ocap_util.BN(0))) throw new _ocap_util_lib_error.CustomError("INVALID_NONCE", "tx.nonce should be a positive integer");
226
- if (await hasCommittedUnsignedTx(context)) throw new _ocap_util_lib_error.CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
227
- if (context.unsignedTxHash) syncState.inFlightUnsignedTxHashes.set(context.unsignedTxHash, execId);
228
- }
229
278
  });
230
279
  return next();
231
280
  } catch (err) {
@@ -234,18 +283,30 @@ const createExecute = ({ filter, runAsLambda }) => {
234
283
  });
235
284
  const ensureGasFeePaid = (context) => {
236
285
  const gasRunner = new _ocap_tx_pipeline.Runner("ensure-gas-fee-paid");
286
+ gasRunner.use((ctx, next) => {
287
+ if (ctx.senderState?.address && ctx.stateSnapshot?.[ctx.senderState.address]) ctx.senderState = (0, lodash_cloneDeep.default)(ctx.stateSnapshot[ctx.senderState.address]);
288
+ ctx.isFailedTxGasCharge = true;
289
+ ctx.gasPaid = false;
290
+ ctx.senderUpdates = {};
291
+ ctx.senderChange = void 0;
292
+ ctx.updatedAccounts = [];
293
+ ctx.feeVaultChange = void 0;
294
+ ctx.gasVaultChange = void 0;
295
+ return next();
296
+ });
237
297
  gasRunner.use(ensureTxGas);
238
298
  gasRunner.use(ensureTxCost);
239
299
  gasRunner.use(async (ctx, next) => {
240
300
  const { tx, statedb, senderUpdates, updateVaults } = ctx;
241
301
  if (ctx.senderState && ctx.states && tx) {
242
- const senderState = ctx.stateSnapshot?.[ctx.senderState.address] || ctx.senderState;
302
+ if (tx.delegator && !ctx.delegationState && !ctx.isImplicitDelegation) return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "Cannot charge gas to sender without verified delegation"));
303
+ const senderState = ctx.senderState;
243
304
  const updates = ctx.states.account.update(senderState, {
244
305
  nonce: tx.nonce,
245
- pk: tx.pk,
306
+ pk: tx.delegator ? senderState.pk : tx.pk,
246
307
  ...senderUpdates
247
308
  }, ctx);
248
- await statedb.account.update(senderState.address, updates, ctx);
309
+ ctx.senderState = await statedb.account.update(senderState.address, updates, ctx) || senderState;
249
310
  if (updateVaults) await updateVaults();
250
311
  }
251
312
  return next();
@@ -266,9 +327,40 @@ const createExecute = ({ filter, runAsLambda }) => {
266
327
  });
267
328
  });
268
329
  };
330
+ const attachSecurityStrikeToError = async (err, ctx) => {
331
+ if (!err || err._strikeRecorded || err._unauthenticatedExtraFailure === true) return;
332
+ const classified = require_gas_security_guard.classifyErrorStrikeCategory(err);
333
+ if (!classified.shouldRecordStrike) return;
334
+ const secCfg = ctx.config?.transaction?.security;
335
+ const strikeOnAllErrors = secCfg?.strikeOnAllErrors === true;
336
+ if (!(classified.category === "WAF_REJECT" || classified.category === "INVARIANT_VIOLATION" || classified.category === "PAYMASTER_VIOLATION" || strikeOnAllErrors)) return;
337
+ const actors = await require_gas_security_guard.resolveVerifiedStrikeActors(ctx);
338
+ if (actors.length === 0) return;
339
+ err._strikeRecorded = true;
340
+ const fishermanAddress = secCfg?.fishermanAddress;
341
+ const nowMs = ctx.txTime ? +new Date(ctx.txTime) : Date.now();
342
+ const { primaryWarning, slashEvidence } = await require_gas_security_guard.recordActorSecurityStrike({
343
+ actors,
344
+ category: classified.category,
345
+ reasonCode: classified.code,
346
+ txHash: ctx.txHash,
347
+ config: ctx.config,
348
+ statedb: ctx.statedb,
349
+ txn: ctx.txn,
350
+ fishermanAddress,
351
+ nowMs,
352
+ telemetry: ctx.gasQuotaTelemetry
353
+ });
354
+ if (primaryWarning && !err.warning) {
355
+ err.warning = primaryWarning;
356
+ ctx.securityWarning = primaryWarning;
357
+ }
358
+ if (slashEvidence && !err.slashEvidence) err.slashEvidence = slashEvidence;
359
+ };
269
360
  const execute = async (context, protocols, isRetrySupported = false) => new Promise((resolve, reject) => {
270
- pre.run(context, (err) => {
361
+ pre.run(context, async (err) => {
271
362
  if (err) {
363
+ if (!isRetrySupported) await attachSecurityStrikeToError(err, context);
272
364
  context.logger?.error("Failed to prepare transaction", {
273
365
  error: err,
274
366
  txHash: context.txHash,
@@ -278,16 +370,30 @@ const createExecute = ({ filter, runAsLambda }) => {
278
370
  }
279
371
  const protocol = protocols[getTxName(context.txType)];
280
372
  if (!protocol) return reject(new _ocap_util_lib_error.CustomError("UNSUPPORTED_TX", `Unsupported tx type ${context.txType}`));
281
- protocol.run(context, async (error) => {
373
+ (0, _ocap_tx_pipeline.installStateWriteInterceptor)(context);
374
+ protocol.run(context, async (rawError) => {
375
+ const underlyingDb = context.statedb?._underlyingStateDb;
376
+ if (underlyingDb) context.statedb = underlyingDb;
377
+ let error = rawError;
282
378
  context.timer?.mark("protocol");
379
+ if (!error) try {
380
+ (0, _ocap_tx_pipeline.inspectPostExecutionInvariants)(context);
381
+ } catch (invariantErr) {
382
+ error = invariantErr;
383
+ }
283
384
  if (isRetrySupported) {
284
385
  if (error) return reject(error);
285
386
  return resolve(context);
286
387
  }
388
+ if (error) {
389
+ await (0, _ocap_tx_pipeline.rollbackTrackedStateWrites)(context);
390
+ context.events = [];
391
+ await attachSecurityStrikeToError(error, context);
392
+ }
287
393
  const txStatus = error ? error.code || "INTERNAL" : "OK";
288
394
  const states = getStates(context);
289
395
  let txState = states.tx.create(context, txStatus);
290
- if (shouldPersistTx(error)) try {
396
+ if (shouldPersistTx(error, context)) try {
291
397
  if (error) {
292
398
  await ensureGasFeePaid(context);
293
399
  txState = states.tx.create(context, txStatus);
@@ -312,7 +418,7 @@ const createExecute = ({ filter, runAsLambda }) => {
312
418
  txSize: context.txSize,
313
419
  senderAddr: context.tx?.from,
314
420
  ledgerSequence: context.ledgerSequence,
315
- status: error ? shouldPersistTx(error) ? "PERSISTED_FAILED" : "FAILED" : "OK",
421
+ status: error ? shouldPersistTx(error, context) ? "PERSISTED_FAILED" : "FAILED" : "OK",
316
422
  errorCode: error ? error.code || "INTERNAL" : null,
317
423
  retried: Boolean(error)
318
424
  });
@@ -425,7 +531,7 @@ const createExecute = ({ filter, runAsLambda }) => {
425
531
  txState,
426
532
  request: context.extra?.request
427
533
  });
428
- if (txState && shouldPersistTx(err)) {
534
+ if (txState && shouldPersistTx(err, ctx)) {
429
535
  ctx.events = [];
430
536
  try {
431
537
  txState = await runAsLambda(async (txn) => {
@@ -434,12 +540,30 @@ const createExecute = ({ filter, runAsLambda }) => {
434
540
  cacheStates: null
435
541
  });
436
542
  ctx.timer?.mark("lockWait");
437
- await ensureGasFeePaid(ctx);
438
- const state = getStates(context).tx.create(ctx, txStatus);
439
- await ctx.statedb.tx.create(state.hash, state, ctx);
440
- await recordUnsignedTxInStateDb(ctx, state.hash);
441
- ctx.timer?.mark("txstate");
442
- return state;
543
+ const strikeSnapshot = require_gas_security_guard.snapshotActorSecurityRecords([
544
+ ctx.tx?.delegator || "",
545
+ ctx.tx?.from || "",
546
+ ctx.gasStake?.sponsorAddress || ""
547
+ ].filter(Boolean), ctx.statedb, ctx.txHash);
548
+ const hadStrikeBefore = Boolean(err._strikeRecorded);
549
+ const prevWarning = err.warning;
550
+ const prevSlashEvidence = err.slashEvidence;
551
+ try {
552
+ await ensureGasFeePaid(ctx);
553
+ await attachSecurityStrikeToError(err, ctx);
554
+ const state = getStates(context).tx.create(ctx, txStatus);
555
+ await ctx.statedb.tx.create(state.hash, state, ctx);
556
+ await recordUnsignedTxInStateDb(ctx, state.hash);
557
+ ctx.timer?.mark("txstate");
558
+ return state;
559
+ } catch (lambdaErr) {
560
+ require_gas_security_guard.restoreActorSecurityRecords(strikeSnapshot, ctx.statedb);
561
+ err._strikeRecorded = hadStrikeBefore;
562
+ err.warning = prevWarning;
563
+ err.slashEvidence = prevSlashEvidence;
564
+ ctx.securityWarning = prevWarning;
565
+ throw lambdaErr;
566
+ }
443
567
  }, {
444
568
  cleanWorkingSet: true,
445
569
  verifyHash: true,
@@ -487,6 +611,7 @@ const createExecute = ({ filter, runAsLambda }) => {
487
611
  perf: ctx.timer?.summaryV2()
488
612
  });
489
613
  } catch (innerErr) {
614
+ await attachSecurityStrikeToError(err, Object.assign({}, ctx, { txn: void 0 }));
490
615
  ctx.logger?.error("Failed to save invalid transaction to statedb", {
491
616
  error: innerErr,
492
617
  txError: error,
@@ -497,6 +622,7 @@ const createExecute = ({ filter, runAsLambda }) => {
497
622
  throw error;
498
623
  }
499
624
  } else {
625
+ await attachSecurityStrikeToError(err, Object.assign({}, ctx, { txn: void 0 }));
500
626
  ctx.timer?.setMeta({
501
627
  txType: ctx.txType,
502
628
  txSize: ctx.txSize,
package/lib/execute.d.cts CHANGED
@@ -1,3 +1,4 @@
1
+ import { ITxGasQuotaTelemetry, ITxSecurityWarning } from "./gas-security-guard.cjs";
1
2
  import { TxTimer } from "./tx-timer.cjs";
2
3
  import { Blacklist } from "@ocap/state";
3
4
  import { IAccountState, IGasContext } from "@ocap/types";
@@ -36,6 +37,12 @@ interface IExecutionContext extends IGasContext {
36
37
  timer?: TxTimer;
37
38
  /** Per-invocation identifier for in-flight deduplication across retries */
38
39
  executionId?: symbol;
40
+ /** True when charging gas on a failed persisted transaction */
41
+ isFailedTxGasCharge?: boolean;
42
+ /** Machine-readable gas quota & burst escalation telemetry */
43
+ gasQuotaTelemetry?: ITxGasQuotaTelemetry;
44
+ /** Structured progressive strike warning */
45
+ securityWarning?: ITxSecurityWarning;
39
46
  }
40
47
  /** Protocol runner interface */
41
48
  interface IProtocolRunner {