@ocap/tx-protocols 1.30.25 → 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
@@ -0,0 +1,1101 @@
1
+ import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
2
+ import { toStakeAddress } from "@arcblock/did-util";
3
+ import { getHasher, getSigner } from "@ocap/mcrypto";
4
+ import { account, evidence, parseNonceBn, stake } from "@ocap/state";
5
+ import { pipes } from "@ocap/tx-pipeline";
6
+ import { BN, fromTokenToUnit, isSameDid, toAddress as toAddress$1 } from "@ocap/util";
7
+ import { CustomError } from "@ocap/util/lib/error";
8
+ import { getListField } from "@ocap/util/lib/get-list-field";
9
+ import cloneDeep from "lodash/cloneDeep.js";
10
+ import { createHash } from "node:crypto";
11
+ import { fromPublicKey as fromPublicKey$1 } from "@ocap/wallet";
12
+
13
+ //#region src/gas-security-guard.ts
14
+ const ZERO = new BN(0);
15
+ const BPS_DENOMINATOR = new BN(1e4);
16
+ const DEFAULT_MAX_FREE_GAS_TX_SIZE = 4096;
17
+ const DEFAULT_MAX_FREE_GAS_STATE_OPS = 6;
18
+ const DEFAULT_BURST_WINDOW_MS = 6e4;
19
+ const DEFAULT_BASE_BURST_ALLOWANCE = 10;
20
+ const DEFAULT_BURST_REJECT_MULTIPLE = 100;
21
+ const DEFAULT_DELEGATED_BURST_MULTIPLE = 20;
22
+ const DEFAULT_STRIKE_WINDOW_MS = 6e5;
23
+ const DEFAULT_WARNING_STRIKE_THRESHOLD = 2;
24
+ const DEFAULT_THROTTLE_STRIKE_THRESHOLD = 5;
25
+ const DEFAULT_SLASH_STRIKE_THRESHOLD = 10;
26
+ const DEFAULT_THROTTLE_COOLDOWN_MS = 15e3;
27
+ const DEFAULT_GAS_PASS_EPOCH_SECONDS = 60;
28
+ const DEFAULT_FISHERMAN_BOUNTY_BPS = 1e3;
29
+ const MAX_TRACKED_ACTORS = 1e4;
30
+ const MAX_NULLIFIERS_PER_STAKE = 5e3;
31
+ const MAX_FREE_VARIANTS = 2;
32
+ /**
33
+ * High-overhead creator, factory, token-issuance, rollup, and batch transaction types
34
+ * that ALWAYS require direct gas payment (`requiresDirectGas: true`) and cannot waive
35
+ * gas via self-staked `Stake-for-Gas` or Unlinkable Gas Pass.
36
+ */
37
+ const DIRECT_GAS_REQUIRED_TX_TYPES = new Set([
38
+ "create_token",
39
+ "create_token_factory",
40
+ "update_token_factory",
41
+ "create_factory",
42
+ "create_asset",
43
+ "mint_asset",
44
+ "update_asset",
45
+ "create_rollup",
46
+ "update_rollup",
47
+ "create_rollup_block",
48
+ "join_rollup",
49
+ "leave_rollup",
50
+ "pause_rollup",
51
+ "resume_rollup",
52
+ "close_rollup",
53
+ "migrate_rollup",
54
+ "claim_block_reward",
55
+ "slash_stake",
56
+ "return_stake",
57
+ "execute_transaction_block"
58
+ ]);
59
+ /**
60
+ * Everyday end-user transaction types eligible for `Stake-for-Gas` free gas waiver
61
+ * when within the 3D envelope (`txType` allowlist + `txSize <= 4096` + `stateOps <= 6`).
62
+ */
63
+ const FREE_GAS_ELIGIBLE_TX_TYPES = new Set([
64
+ "transfer",
65
+ "transfer_v2",
66
+ "transfer_v3",
67
+ "exchange",
68
+ "exchange_v2",
69
+ "declare",
70
+ "account_migrate",
71
+ "delegate",
72
+ "revoke_delegate",
73
+ "stake",
74
+ "revoke_stake",
75
+ "claim_stake",
76
+ "consume_asset",
77
+ "acquire_asset_v2",
78
+ "acquire_asset_v3",
79
+ "mint_token",
80
+ "burn_token",
81
+ "deposit_token_v2",
82
+ "withdraw_token_v2",
83
+ "poke"
84
+ ]);
85
+ const registryByStateDb = /* @__PURE__ */ new WeakMap();
86
+ let defaultGlobalRegistry = createEmptyRegistry();
87
+ function createEmptyRegistry() {
88
+ return {
89
+ actors: /* @__PURE__ */ new Map(),
90
+ consumedNullifiers: /* @__PURE__ */ new Map(),
91
+ txWarningsByHash: /* @__PURE__ */ new Map()
92
+ };
93
+ }
94
+ function getUnderlyingTarget(statedb) {
95
+ if (!statedb || typeof statedb !== "object") return null;
96
+ const raw = statedb._underlyingStateDb || statedb;
97
+ const accountTable = raw.account;
98
+ if (accountTable && typeof accountTable === "object") return accountTable;
99
+ return raw;
100
+ }
101
+ function getGasSecurityRegistry(statedb) {
102
+ const target = getUnderlyingTarget(statedb);
103
+ if (!target) return defaultGlobalRegistry;
104
+ let reg = registryByStateDb.get(target);
105
+ if (!reg) {
106
+ reg = createEmptyRegistry();
107
+ registryByStateDb.set(target, reg);
108
+ }
109
+ return reg;
110
+ }
111
+ function resetGasSecurityState(statedb) {
112
+ const target = getUnderlyingTarget(statedb);
113
+ if (target) registryByStateDb.set(target, createEmptyRegistry());
114
+ defaultGlobalRegistry = createEmptyRegistry();
115
+ }
116
+ function normalizeActorAddress(raw) {
117
+ if (typeof raw !== "string") return "";
118
+ const trimmed = raw.trim();
119
+ if (!trimmed) return "";
120
+ const stripped = trimmed.startsWith("did:abt:") ? toAddress$1(trimmed) : trimmed;
121
+ if (/^0x[0-9a-fA-F]{40}$/.test(stripped)) return account.ensureChecksumAddress(stripped.toLowerCase());
122
+ return account.ensureChecksumAddress(stripped);
123
+ }
124
+ function normalizeShortTxType(txType) {
125
+ if (typeof txType !== "string" || !txType.trim()) return "";
126
+ const parts = txType.trim().split(":");
127
+ return parts[parts.length - 1] || "";
128
+ }
129
+ function resolveGasSecurityConfig(config) {
130
+ const txGas = config?.transaction?.txGas || {};
131
+ const sec = (config?.transaction)?.security || {};
132
+ const numOr = (val, fallback) => typeof val === "number" && Number.isFinite(val) && val > 0 ? val : fallback;
133
+ const boolOr = (val, fallback) => typeof val === "boolean" ? val : fallback;
134
+ return {
135
+ enabled: boolOr(sec.enabled, true),
136
+ throttle: boolOr(sec.throttle, true),
137
+ burstEscalation: boolOr(sec.burstEscalation, true),
138
+ autoSlash: boolOr(sec.autoSlash, false),
139
+ gasPassNullifierCheck: boolOr(sec.gasPassNullifierCheck, false),
140
+ burstRejectMultiple: numOr(sec.burstRejectMultiple, DEFAULT_BURST_REJECT_MULTIPLE),
141
+ exemptActors: Array.isArray(sec.exemptActors) ? sec.exemptActors.map((a) => normalizeActorAddress(a)).filter(Boolean) : [],
142
+ delegatedBurstMultiple: numOr(sec.delegatedBurstMultiple, DEFAULT_DELEGATED_BURST_MULTIPLE),
143
+ maxFreeGasTxSize: numOr(txGas.maxFreeGasTxSize, DEFAULT_MAX_FREE_GAS_TX_SIZE),
144
+ maxFreeGasStateOps: numOr(txGas.maxFreeGasStateOps, DEFAULT_MAX_FREE_GAS_STATE_OPS),
145
+ burstWindowMs: numOr(txGas.burstWindowMs, DEFAULT_BURST_WINDOW_MS),
146
+ baseBurstAllowance: numOr(txGas.baseBurstAllowance, DEFAULT_BASE_BURST_ALLOWANCE),
147
+ strikeWindowMs: numOr(sec.strikeWindowMs, DEFAULT_STRIKE_WINDOW_MS),
148
+ warningThreshold: numOr(sec.warningThreshold, DEFAULT_WARNING_STRIKE_THRESHOLD),
149
+ throttleThreshold: numOr(sec.throttleThreshold, DEFAULT_THROTTLE_STRIKE_THRESHOLD),
150
+ slashThreshold: numOr(sec.slashThreshold, DEFAULT_SLASH_STRIKE_THRESHOLD),
151
+ throttleCooldownMs: numOr(sec.throttleCooldownMs, DEFAULT_THROTTLE_COOLDOWN_MS),
152
+ gasPassEpochSeconds: numOr(sec.gasPassEpochSeconds, DEFAULT_GAS_PASS_EPOCH_SECONDS),
153
+ fishermanBountyBps: typeof sec.fishermanBountyBps === "number" && Number.isFinite(sec.fishermanBountyBps) && sec.fishermanBountyBps >= 0 && sec.fishermanBountyBps <= 5e3 ? Math.floor(sec.fishermanBountyBps) : DEFAULT_FISHERMAN_BOUNTY_BPS
154
+ };
155
+ }
156
+ /** Actor keys are addresses, or `signer>principal` pairs for delegated-tx burst windows. */
157
+ function normalizeActorKey(raw) {
158
+ return raw.includes(">") ? raw.split(">").map((part) => part === "*" ? part : normalizeActorAddress(part)).join(">") : normalizeActorAddress(raw);
159
+ }
160
+ function getOrCreateActorRecord(reg, rawActor, nowMs, cfg) {
161
+ const actor = normalizeActorKey(rawActor);
162
+ let rec = reg.actors.get(actor);
163
+ if (rec) {
164
+ reg.actors.delete(actor);
165
+ reg.actors.set(actor, rec);
166
+ } else {
167
+ if (reg.actors.size >= MAX_TRACKED_ACTORS) {
168
+ let victim;
169
+ for (const [key, candidate] of reg.actors) if (candidate.cooldownUntilMs <= nowMs) {
170
+ victim = key;
171
+ break;
172
+ }
173
+ victim = victim ?? reg.actors.keys().next().value;
174
+ if (victim) reg.actors.delete(victim);
175
+ }
176
+ rec = {
177
+ actor,
178
+ bursts: [],
179
+ strikes: [],
180
+ cooldownUntilMs: 0
181
+ };
182
+ reg.actors.set(actor, rec);
183
+ }
184
+ const burstCutoff = nowMs - cfg.burstWindowMs;
185
+ rec.bursts = rec.bursts.filter((b) => b.t > burstCutoff);
186
+ const strikeCutoff = nowMs - cfg.strikeWindowMs;
187
+ rec.strikes = rec.strikes.filter((s) => s.timestampMs > strikeCutoff);
188
+ return rec;
189
+ }
190
+ /**
191
+ * 3D `Stake-for-Gas` Eligibility Gate:
192
+ * 1. `txType` must be in `FREE_GAS_ELIGIBLE_TX_TYPES` (everyday user actions only).
193
+ * 2. `txSize` must be <= `maxFreeGasTxSize` (default 4096 bytes).
194
+ * 3. `stateOps` (`estimate.create + estimate.update`) must be <= `maxFreeGasStateOps` (default 6).
195
+ * 4. Failed transactions (`isFailedTxGasCharge === true`) NEVER waive gas.
196
+ */
197
+ function evaluateStakeForGasEligibility(params) {
198
+ const cfg = resolveGasSecurityConfig(params.config);
199
+ if (params.isFailedTxGasCharge) return {
200
+ eligible: false,
201
+ reason: "FAILED_TX_REQUIRES_DIRECT_GAS"
202
+ };
203
+ const shortType = normalizeShortTxType(params.txType);
204
+ const customAllowlist = (params.config?.transaction?.txGas)?.freeGasAllowedTxTypes;
205
+ if ((!params.isThirdPartySponsor || params.enforceSponsor3DEligibility === true) && shortType) {
206
+ if (Array.isArray(customAllowlist) && customAllowlist.length > 0) {
207
+ if (!customAllowlist.some((t) => normalizeShortTxType(t) === shortType || t === params.txType)) return {
208
+ eligible: false,
209
+ reason: "TX_TYPE_REQUIRES_DIRECT_GAS"
210
+ };
211
+ } else if (DIRECT_GAS_REQUIRED_TX_TYPES.has(shortType) || typeof params.txType === "string" && params.txType.startsWith("fg:t:") && !FREE_GAS_ELIGIBLE_TX_TYPES.has(shortType)) return {
212
+ eligible: false,
213
+ reason: "TX_TYPE_REQUIRES_DIRECT_GAS"
214
+ };
215
+ }
216
+ if ((typeof params.txSize === "number" ? params.txSize : 0) > cfg.maxFreeGasTxSize) return {
217
+ eligible: false,
218
+ reason: "TX_SIZE_EXCEEDS_FREE_GAS_CEILING"
219
+ };
220
+ if ((params.gasEstimate?.create || 0) + (params.gasEstimate?.update || 0) > cfg.maxFreeGasStateOps) return {
221
+ eligible: false,
222
+ reason: "STATE_OPS_EXCEED_FREE_GAS_CEILING"
223
+ };
224
+ return { eligible: true };
225
+ }
226
+ const CREATION_TARGET_TX_TYPES = new Set([
227
+ "create_asset",
228
+ "acquire_asset",
229
+ "acquire_asset_v2",
230
+ "acquire_asset_v3",
231
+ "create_factory",
232
+ "create_token",
233
+ "create_token_factory"
234
+ ]);
235
+ /**
236
+ * Extracts all target DIDs referenced by a transaction (`itx.to`, `itx.factory`, `itx.tokenFactory`,
237
+ * `itx.address`, `itx.assets`, `itx.inputs`, `itx.outputs`, `itx.sender`, `itx.receiver`) for
238
+ * Paymaster `allowedTargets` scoping.
239
+ */
240
+ function extractTransactionTargets(tx$1, decodedItx, txType) {
241
+ if ((!tx$1 || typeof tx$1 !== "object") && (!decodedItx || typeof decodedItx !== "object")) return [];
242
+ const targets = /* @__PURE__ */ new Set();
243
+ const addTarget = (candidate) => {
244
+ const norm = normalizeActorAddress(candidate);
245
+ if (norm) targets.add(norm);
246
+ };
247
+ const shortType = normalizeShortTxType(txType || (tx$1?.itx)?.typeUrl);
248
+ const rawItx = decodedItx || tx$1?.itxJson || tx$1?.itx;
249
+ const itx = rawItx && typeof rawItx === "object" && !Buffer.isBuffer(rawItx) && typeof rawItx.value !== "string" ? rawItx : decodedItx;
250
+ if (itx && typeof itx === "object") {
251
+ const scalarFields = [
252
+ "to",
253
+ "factory",
254
+ "receiver",
255
+ "rollup",
256
+ "tokenAddress",
257
+ "factoryAddress",
258
+ "tokenFactory",
259
+ "owner",
260
+ "parent",
261
+ "issuer",
262
+ "validator",
263
+ "contract",
264
+ "delegatee"
265
+ ];
266
+ if (!CREATION_TARGET_TX_TYPES.has(shortType)) scalarFields.push("address");
267
+ for (const field of scalarFields) if (typeof itx[field] === "string" && itx[field]) addTarget(itx[field]);
268
+ const extractPartySubTargets = (party) => {
269
+ if (!party || typeof party !== "object") return;
270
+ const p = party;
271
+ addTarget(p.address);
272
+ addTarget(p.owner);
273
+ addTarget(p.to);
274
+ const pAssets = getListField(p, "assets");
275
+ if (Array.isArray(pAssets)) for (const a of pAssets) addTarget(a);
276
+ const pTokens = getListField(p, "tokens");
277
+ if (Array.isArray(pTokens)) {
278
+ for (const tok of pTokens) if (tok && typeof tok === "object") addTarget(tok.address);
279
+ }
280
+ };
281
+ if (itx.sender && typeof itx.sender === "object") extractPartySubTargets(itx.sender);
282
+ if (itx.receiver && typeof itx.receiver === "object") extractPartySubTargets(itx.receiver);
283
+ const assets = getListField(itx, "assets");
284
+ if (Array.isArray(assets)) for (const a of assets) addTarget(a);
285
+ const inputs = getListField(itx, "inputs");
286
+ if (Array.isArray(inputs)) for (const inp of inputs) extractPartySubTargets(inp);
287
+ const outputs = getListField(itx, "outputs");
288
+ if (Array.isArray(outputs)) for (const out of outputs) extractPartySubTargets(out);
289
+ }
290
+ return Array.from(targets);
291
+ }
292
+ /**
293
+ * Verifies Merchant / DApp Paymaster (`extra.gasStakeHeaders` JWT) scope constraints:
294
+ * - `allowedTxTypes`: if present, transaction type must be in `allowedTxTypes`.
295
+ * - `allowedTargets`: if present, transaction must touch at least one target and EVERY target
296
+ * touched by the transaction (excluding the sender `tx.from` itself in multi-input change)
297
+ * must be in `allowedTargets`.
298
+ * - `maxGasPerTx`: if present, `totalGas` must not exceed `maxGasPerTx`.
299
+ */
300
+ function verifyPaymasterConstraints(params) {
301
+ const { decoded, tx: tx$1, itx, txType, totalGas } = params;
302
+ const isPaymasterDirectCharge = decoded.mode === "paymaster" || decoded.chargeSponsorBalance === true;
303
+ if (Array.isArray(decoded.allowedTxTypes)) {
304
+ if (decoded.allowedTxTypes.length === 0) return {
305
+ valid: false,
306
+ reason: "PAYMASTER_TX_TYPE_FORBIDDEN",
307
+ isPaymasterDirectCharge
308
+ };
309
+ const shortType = normalizeShortTxType(txType);
310
+ if (!decoded.allowedTxTypes.some((allowed) => allowed === txType || normalizeShortTxType(allowed) === shortType)) return {
311
+ valid: false,
312
+ reason: "PAYMASTER_TX_TYPE_FORBIDDEN",
313
+ isPaymasterDirectCharge
314
+ };
315
+ }
316
+ if (Array.isArray(decoded.allowedTargets)) {
317
+ const normalizedAllowed = decoded.allowedTargets.map((t) => normalizeActorAddress(t)).filter(Boolean);
318
+ if (normalizedAllowed.length === 0) return {
319
+ valid: false,
320
+ reason: "PAYMASTER_TARGET_FORBIDDEN",
321
+ isPaymasterDirectCharge
322
+ };
323
+ const txFrom = normalizeActorAddress(tx$1?.from);
324
+ const allTargets = extractTransactionTargets(tx$1, itx, txType).filter((t) => t !== txFrom);
325
+ if (allTargets.length === 0) return {
326
+ valid: false,
327
+ reason: "PAYMASTER_TARGET_FORBIDDEN",
328
+ isPaymasterDirectCharge
329
+ };
330
+ if (!allTargets.every((target) => normalizedAllowed.some((allowed) => isSameDid(target, allowed) || target === allowed))) return {
331
+ valid: false,
332
+ reason: "PAYMASTER_TARGET_FORBIDDEN",
333
+ isPaymasterDirectCharge
334
+ };
335
+ }
336
+ if (decoded.maxGasPerTx !== void 0 && decoded.maxGasPerTx !== null && decoded.maxGasPerTx !== "") {
337
+ const capStr = String(decoded.maxGasPerTx).trim();
338
+ if (!/^(0|[1-9]\d*)$/.test(capStr)) return {
339
+ valid: false,
340
+ reason: "PAYMASTER_MAX_GAS_EXCEEDED",
341
+ isPaymasterDirectCharge
342
+ };
343
+ const capBN = new BN(capStr, 10);
344
+ if ((totalGas ?? ZERO).gt(capBN)) return {
345
+ valid: false,
346
+ reason: "PAYMASTER_MAX_GAS_EXCEEDED",
347
+ isPaymasterDirectCharge
348
+ };
349
+ }
350
+ return {
351
+ valid: true,
352
+ isPaymasterDirectCharge
353
+ };
354
+ }
355
+ /**
356
+ * Computes the SHA-256 hash of a stake owner's secret for Unlinkable Gas Pass verification:
357
+ * `SHA256("ocap:gas-pass-secret:v1:" + passSecret)`
358
+ */
359
+ function computeUnlinkableGasPassSecretHash(passSecret) {
360
+ return createHash("sha256").update(`ocap:gas-pass-secret:v1:${passSecret}`).digest("hex").toLowerCase();
361
+ }
362
+ /**
363
+ * Computes the deterministic commitment for a Consumer Self-Use Unlinkable Gas Pass:
364
+ * `SHA256("ocap:gas-pass:v1:" + normalizeActorAddress(stakeId) + ":" + epoch + ":" + nullifier + ":" + txHash)`
365
+ */
366
+ function computeUnlinkableGasPassCommitment(params) {
367
+ const normStakeId = normalizeActorAddress(params.stakeId);
368
+ return createHash("sha256").update(`ocap:gas-pass:v1:${normStakeId}:${params.epoch}:${params.nullifier}:${params.txHash}`).digest("hex");
369
+ }
370
+ /**
371
+ * Verifies and consumes a Consumer Self-Use Unlinkable Gas Pass (`extra.gasPass`),
372
+ * allowing a user who staked ABT on their main DID to pay/waive gas from a fresh
373
+ * unlinked sub-DID without revealing their main DID on-chain in `tx.from`, while
374
+ * strictly enforcing cryptographic authorization (`passSecret` matching `stakeState.gasPassSecretHash`
375
+ * or `pk`+`signature` signed by `stakeState.sender`), `nullifier` single-use per epoch, and
376
+ * stake-proportional quota.
377
+ */
378
+ function verifyAndConsumeUnlinkableGasPass(params) {
379
+ const { gasPass, stakeState, txHash, config, statedb } = params;
380
+ if (!gasPass || typeof gasPass !== "object") return {
381
+ valid: false,
382
+ reason: "INVALID_GAS_PASS"
383
+ };
384
+ const stakeId = normalizeActorAddress(gasPass.stakeId);
385
+ const nullifier = typeof gasPass.nullifier === "string" ? gasPass.nullifier.trim() : "";
386
+ const commitment = typeof gasPass.commitment === "string" ? gasPass.commitment.trim().toLowerCase() : "";
387
+ const epoch = typeof gasPass.epoch === "number" && Number.isInteger(gasPass.epoch) ? gasPass.epoch : -1;
388
+ if (!stakeId || !nullifier || nullifier.length < 16 || nullifier.length > 256 || !commitment || epoch < 0) return {
389
+ valid: false,
390
+ reason: "INVALID_GAS_PASS_FORMAT"
391
+ };
392
+ if (!stakeState || normalizeActorAddress(stakeState.address) !== stakeId) return {
393
+ valid: false,
394
+ reason: "GAS_PASS_STAKE_NOT_FOUND"
395
+ };
396
+ const stakeSender = normalizeActorAddress(stakeState.sender);
397
+ const stakeReceiver = normalizeActorAddress(stakeState.receiver);
398
+ if (!stakeSender || stakeSender !== stakeReceiver || toStakeAddress(stakeSender, stakeSender) !== stakeId) return {
399
+ valid: false,
400
+ reason: "GAS_PASS_NOT_SELF_STAKE"
401
+ };
402
+ const minStakeUnit = fromTokenToUnit(config.transaction.txGas.minStake, config.token.decimal);
403
+ if (new BN(stakeState.tokens?.[config.token.address] || 0).lt(minStakeUnit)) return {
404
+ valid: false,
405
+ reason: "GAS_PASS_INSUFFICIENT_STAKE"
406
+ };
407
+ const cfg = resolveGasSecurityConfig(config);
408
+ const nowSec = Math.floor((params.nowMs ?? Date.now()) / 1e3);
409
+ const currentEpoch = Math.floor(nowSec / cfg.gasPassEpochSeconds);
410
+ if (Math.abs(epoch - currentEpoch) > 1) return {
411
+ valid: false,
412
+ reason: "GAS_PASS_EPOCH_EXPIRED"
413
+ };
414
+ const expectedCommitment = computeUnlinkableGasPassCommitment({
415
+ stakeId,
416
+ epoch,
417
+ nullifier,
418
+ txHash
419
+ }).toLowerCase();
420
+ if (commitment !== expectedCommitment) return {
421
+ valid: false,
422
+ reason: "GAS_PASS_COMMITMENT_MISMATCH"
423
+ };
424
+ const stakeRecord = stakeState;
425
+ const stakeData = stakeRecord.data;
426
+ const rawSecretHash = stakeRecord.gasPassSecretHash || stakeData?.gasPassSecretHash;
427
+ let isAuthorized = false;
428
+ if (typeof gasPass.passSecret === "string" && gasPass.passSecret.length > 0 && typeof rawSecretHash === "string" && rawSecretHash.length > 0) {
429
+ if (computeUnlinkableGasPassSecretHash(gasPass.passSecret) === rawSecretHash.trim().toLowerCase()) isAuthorized = true;
430
+ }
431
+ if (!isAuthorized && typeof gasPass.pk === "string" && gasPass.pk && typeof gasPass.signature === "string" && gasPass.signature) try {
432
+ const didType = toTypeInfo(stakeSender);
433
+ if (normalizeActorAddress(fromPublicKey$1(gasPass.pk, didType).address) === stakeSender || isFromPublicKey(stakeSender, gasPass.pk)) {
434
+ const signer = getSigner(didType.pk);
435
+ const hashedMsg = getHasher(didType.hash)(expectedCommitment, 1);
436
+ if (signer.verify(hashedMsg, gasPass.signature, gasPass.pk) || signer.verify(expectedCommitment, gasPass.signature, gasPass.pk)) isAuthorized = true;
437
+ }
438
+ } catch {
439
+ isAuthorized = false;
440
+ }
441
+ if (!isAuthorized) return {
442
+ valid: false,
443
+ reason: "GAS_PASS_UNAUTHORIZED"
444
+ };
445
+ if (!cfg.gasPassNullifierCheck) return {
446
+ valid: true,
447
+ stakeId
448
+ };
449
+ const reg = getGasSecurityRegistry(statedb);
450
+ let nullifierMap = reg.consumedNullifiers.get(stakeId);
451
+ if (!nullifierMap) {
452
+ nullifierMap = /* @__PURE__ */ new Map();
453
+ reg.consumedNullifiers.set(stakeId, nullifierMap);
454
+ }
455
+ for (const [k, entry] of nullifierMap.entries()) if (entry.epoch < currentEpoch - 2) nullifierMap.delete(k);
456
+ const existingNullifier = nullifierMap.get(nullifier);
457
+ if (existingNullifier) {
458
+ if (existingNullifier.txHash && txHash && existingNullifier.txHash === txHash) return {
459
+ valid: true,
460
+ stakeId
461
+ };
462
+ return {
463
+ valid: false,
464
+ reason: "GAS_PASS_NULLIFIER_ALREADY_SPENT"
465
+ };
466
+ }
467
+ if (nullifierMap.size >= MAX_NULLIFIERS_PER_STAKE) {
468
+ const oldest = nullifierMap.keys().next().value;
469
+ if (oldest) nullifierMap.delete(oldest);
470
+ }
471
+ nullifierMap.set(nullifier, {
472
+ epoch,
473
+ txHash
474
+ });
475
+ return {
476
+ valid: true,
477
+ stakeId
478
+ };
479
+ }
480
+ function computeStakeMultiple(config, stakeState) {
481
+ const minStakeUnit = fromTokenToUnit(config.transaction.txGas.minStake || 1, config.token.decimal);
482
+ const maxStakeUnit = fromTokenToUnit(config.transaction.txGas.maxStake || 1e4, config.token.decimal);
483
+ const stakedUnit = new BN(stakeState?.tokens?.[config.token.address] || 0);
484
+ if (minStakeUnit.gt(ZERO) && stakedUnit.gte(minStakeUnit)) {
485
+ const cappedStake = stakedUnit.gt(maxStakeUnit) && maxStakeUnit.gt(ZERO) ? maxStakeUnit : stakedUnit;
486
+ return Math.max(1, Math.min(1e4, cappedStake.div(minStakeUnit).toNumber()));
487
+ }
488
+ return 1;
489
+ }
490
+ /**
491
+ * Stake-scaled per-sender burst quota (`rho = n_burst / B_normal(S)`) with machine-readable telemetry.
492
+ *
493
+ * RELIABILITY CONTRACT: the counter is process-local, so it is used for ADMISSION only (reject before the
494
+ * single-writer queue). It never reprices gas, never changes a waiver and never touches receipts; the executed
495
+ * outcome of a tx is a pure function of (tx, on-chain state). A request is rejected only above
496
+ * `baseBurstAllowance * stakeMultiple * burstRejectMultiple` (`hardLimitExceeded`); between 1x and the hard limit
497
+ * it is admitted and only advisory telemetry is returned (`quotaExceeded`).
498
+ */
499
+ function evaluateBurstQuota(params) {
500
+ const { config, statedb } = params;
501
+ const baseGas = params.baseGas ?? ZERO;
502
+ const cfg = resolveGasSecurityConfig(config);
503
+ const nowMs = params.nowMs ?? Date.now();
504
+ const rec = getOrCreateActorRecord(getGasSecurityRegistry(statedb), normalizeActorKey(params.actor || "anonymous"), nowMs, cfg);
505
+ const normHash = params.txHash ? params.txHash.trim().toUpperCase() : void 0;
506
+ const variantHash = params.variantHash ? params.variantHash.trim().toUpperCase() : void 0;
507
+ const existing = normHash ? rec.bursts.find((b) => b.h === normHash) : void 0;
508
+ let alreadyCounted = false;
509
+ if (existing) {
510
+ if (!variantHash || (existing.variants || []).includes(variantHash)) alreadyCounted = true;
511
+ else if ((existing.variants || []).length < MAX_FREE_VARIANTS) {
512
+ alreadyCounted = true;
513
+ if (params.recordBurst !== false) existing.variants = [...existing.variants || [], variantHash];
514
+ }
515
+ }
516
+ const burstCount = Math.max(1, rec.bursts.length + (alreadyCounted ? 0 : 1));
517
+ const stakeMultiple = computeStakeMultiple(config, params.stakeState);
518
+ const minStakeUnit = fromTokenToUnit(config.transaction.txGas.minStake || 1, config.token.decimal);
519
+ const normalAllowance = cfg.baseBurstAllowance * stakeMultiple;
520
+ const hardLimit = Math.ceil(normalAllowance * (params.rejectMultiple ?? cfg.burstRejectMultiple));
521
+ const rawRho = burstCount / normalAllowance;
522
+ const loadRatio = Number(rawRho.toFixed(4));
523
+ const quotaExceeded = rawRho > 1;
524
+ const hardLimitExceeded = burstCount > hardLimit;
525
+ if (params.recordBurst !== false && !alreadyCounted && !hardLimitExceeded) rec.bursts.push({
526
+ t: nowMs,
527
+ h: existing && variantHash ? `${normHash}#${variantHash}` : normHash,
528
+ variants: variantHash ? [variantHash] : void 0
529
+ });
530
+ const recommendedBackoffMs = rawRho <= 1 ? 0 : Math.min(cfg.burstWindowMs, Math.ceil((rawRho - 1) * (cfg.burstWindowMs / 2)));
531
+ const requiredMultiplesFor1x = Math.max(1, Math.ceil(burstCount / cfg.baseBurstAllowance));
532
+ return {
533
+ burstCount,
534
+ normalAllowance,
535
+ hardLimit,
536
+ loadRatio,
537
+ quotaExceeded,
538
+ hardLimitExceeded,
539
+ telemetry: {
540
+ loadRatio,
541
+ remainingNormalQuota: Math.max(0, normalAllowance - burstCount),
542
+ currentGasMultiplier: 1,
543
+ nextTxEstimatedGas: baseGas.toString(10),
544
+ recommendedBackoffMs,
545
+ stakeRequiredFor1x: minStakeUnit.mul(new BN(requiredMultiplesFor1x)).toString(10)
546
+ }
547
+ };
548
+ }
549
+ function getStrikeWeight(category) {
550
+ switch (category) {
551
+ case "INVARIANT_VIOLATION": return 3;
552
+ case "WAF_REJECT":
553
+ case "PAYMASTER_VIOLATION": return 2;
554
+ case "BENIGN_REJECT":
555
+ case "QUOTA_EXCEEDED": return 0;
556
+ default: return 1;
557
+ }
558
+ }
559
+ const BENIGN_REJECT_CODES = new Set([
560
+ "INVALID_NONCE",
561
+ "DUPLICATE_TX",
562
+ "ACCOUNT_MIGRATED",
563
+ "INVALID_TX_TIME",
564
+ "EXPIRED",
565
+ "TX_EXPIRED",
566
+ "NOT_FOUND",
567
+ "STAKE_NOT_FOUND",
568
+ "INVALID_LOCK_STATUS",
569
+ "ACCOUNT_NOT_FOUND"
570
+ ]);
571
+ function classifyErrorStrikeCategory(err) {
572
+ const code = err?.code || "INTERNAL";
573
+ const msg = err?.message || "";
574
+ if (code.startsWith("WAF_") || /Pre-Flight WAF/i.test(msg)) return {
575
+ shouldRecordStrike: true,
576
+ category: "WAF_REJECT",
577
+ code
578
+ };
579
+ if (code.endsWith("_VIOLATION") || code === "STATE_DELETION_FORBIDDEN" || code === "RW_SET_CEILING_EXCEEDED" || /Post-Execution Invariant Gate/i.test(msg)) return {
580
+ shouldRecordStrike: true,
581
+ category: "INVARIANT_VIOLATION",
582
+ code
583
+ };
584
+ if (code.startsWith("PAYMASTER_") || code.startsWith("GAS_PASS_")) return {
585
+ shouldRecordStrike: true,
586
+ category: "PAYMASTER_VIOLATION",
587
+ code
588
+ };
589
+ if (code === "TOO_MANY_TXS" || code === "ABUSE_SLASH_TRIGGERED") return {
590
+ shouldRecordStrike: false,
591
+ category: "QUOTA_EXCEEDED",
592
+ code
593
+ };
594
+ if (code.startsWith("INSUFFICIENT_") || BENIGN_REJECT_CODES.has(code)) return {
595
+ shouldRecordStrike: false,
596
+ category: "BENIGN_REJECT",
597
+ code
598
+ };
599
+ return {
600
+ shouldRecordStrike: true,
601
+ category: "PROTOCOL_REJECT",
602
+ code
603
+ };
604
+ }
605
+ function computeActorTier(strikeCount, cfg) {
606
+ if (strikeCount >= cfg.slashThreshold) return "SLASH_TRIGGERED";
607
+ if (strikeCount >= cfg.throttleThreshold) return "THROTTLED";
608
+ if (strikeCount >= cfg.warningThreshold) return "WARNING";
609
+ return "NORMAL";
610
+ }
611
+ function getActorSecurityStatus(params) {
612
+ const cfg = resolveGasSecurityConfig(params.config);
613
+ const nowMs = params.nowMs ?? Date.now();
614
+ const reg = getGasSecurityRegistry(params.statedb);
615
+ const actor = normalizeActorAddress(params.actor);
616
+ if (!actor) return {
617
+ strikeCount: 0,
618
+ tier: "NORMAL",
619
+ cooldownUntilMs: 0
620
+ };
621
+ const rec = getOrCreateActorRecord(reg, actor, nowMs, cfg);
622
+ const strikeCount = rec.strikes.reduce((acc, s) => acc + s.weight, 0);
623
+ const tier = computeActorTier(strikeCount, cfg);
624
+ const defaultTelemetry = params.telemetry || {
625
+ loadRatio: 0,
626
+ remainingNormalQuota: cfg.baseBurstAllowance,
627
+ currentGasMultiplier: 1,
628
+ nextTxEstimatedGas: "0",
629
+ recommendedBackoffMs: 0,
630
+ stakeRequiredFor1x: "0"
631
+ };
632
+ let warning;
633
+ if (tier !== "NORMAL" || defaultTelemetry.loadRatio >= .8) {
634
+ warning = {
635
+ tier,
636
+ code: tier === "SLASH_TRIGGERED" ? "ABUSE_SLASH_TRIGGERED" : tier === "THROTTLED" ? "ACTOR_THROTTLED" : tier === "WARNING" ? "SECURITY_STRIKE_WARNING" : "GAS_QUOTA_ADVISORY",
637
+ message: tier === "SLASH_TRIGGERED" ? `Actor ${actor} reached slash threshold (${strikeCount}/${cfg.slashThreshold}); new submissions are rejected during the cooldown${cfg.autoSlash ? " and Stake-for-Gas is subject to automatic slashing" : ""}.` : tier === "THROTTLED" ? `Actor ${actor} is throttled (${strikeCount}/${cfg.throttleThreshold} strikes); new submissions are rejected during the cooldown.` : tier === "WARNING" ? `Actor ${actor} accumulated ${strikeCount} security strikes (throttle at ${cfg.throttleThreshold}, slash at ${cfg.slashThreshold}).` : `Actor ${actor} burst gas load ratio is ${defaultTelemetry.loadRatio} (remaining normal quota: ${defaultTelemetry.remainingNormalQuota}).`,
638
+ actor,
639
+ strikeCount,
640
+ warningThreshold: cfg.warningThreshold,
641
+ throttleThreshold: cfg.throttleThreshold,
642
+ slashThreshold: cfg.slashThreshold,
643
+ gasStakeQuotaRemaining: defaultTelemetry.remainingNormalQuota,
644
+ cooldownUntilMs: rec.cooldownUntilMs,
645
+ telemetry: defaultTelemetry
646
+ };
647
+ rec.lastWarning = warning;
648
+ }
649
+ return {
650
+ strikeCount,
651
+ tier,
652
+ cooldownUntilMs: rec.cooldownUntilMs,
653
+ lastSlashEvidence: rec.lastSlashEvidence,
654
+ warning
655
+ };
656
+ }
657
+ /**
658
+ * Resolves the list of cryptographically verified actor addresses that may be penalized
659
+ * with a security strike for a failed or rejected transaction:
660
+ * - Never attributes strikes to `tx.from` or `tx.delegator` unless `VerifySignature` has
661
+ * cryptographically verified the transaction signature (`CRITICAL-2` protection).
662
+ * - When `tx.delegator` is present, attributes strikes ONLY to `tx.delegator` (the verified signer / delegatee),
663
+ * never to the principal `tx.from`, whether or not the delegation verified.
664
+ * - Never attributes sender-induced strikes to a third-party `gasStake.owner` (`CRITICAL-3`).
665
+ */
666
+ async function resolveVerifiedStrikeActors(ctx) {
667
+ if (!ctx || typeof ctx !== "object") return [];
668
+ const tx$1 = ctx.tx;
669
+ if (!tx$1 || typeof tx$1 !== "object") return [];
670
+ const signer = tx$1.delegator || tx$1.from;
671
+ if (!signer || !tx$1.pk || !tx$1.signature) return [];
672
+ let sigVerified = ctx.isSignatureVerified === true || ctx._preFlightVerified === true;
673
+ if (!sigVerified) try {
674
+ if (!isFromPublicKey(signer, tx$1.pk)) return [];
675
+ await new Promise((resolve, reject) => {
676
+ const verifyFn = pipes.VerifySignature;
677
+ Promise.resolve(verifyFn(ctx, (err) => err ? reject(err) : resolve())).catch(reject);
678
+ });
679
+ ctx.isSignatureVerified = true;
680
+ sigVerified = true;
681
+ } catch {
682
+ return [];
683
+ }
684
+ if (!sigVerified) return [];
685
+ const normSigner = normalizeActorAddress(signer);
686
+ if (!normSigner) return [];
687
+ return [normSigner];
688
+ }
689
+ /**
690
+ * Records a weighted security strike against one or more verified actor addresses,
691
+ * updates their tier (`NORMAL` -> `WARNING` -> `THROTTLED` -> `SLASH_TRIGGERED`), and if `SLASH_TRIGGERED` is reached,
692
+ * executes automatic `Stake-for-Gas` slashing into `config.vaults.slashedStake` (with optional Fisherman bounty split
693
+ * and 0% token burn per Axiom #3).
694
+ */
695
+ async function recordActorSecurityStrike(params) {
696
+ const cfg = resolveGasSecurityConfig(params.config);
697
+ if (!cfg.enabled) return {};
698
+ const nowMs = params.nowMs ?? Date.now();
699
+ const reg = getGasSecurityRegistry(params.statedb);
700
+ const weight = getStrikeWeight(params.category);
701
+ if (weight <= 0) return {};
702
+ const normTxHash = params.txHash ? params.txHash.trim().toUpperCase() : void 0;
703
+ const uniqueActors = Array.from(new Set(params.actors.map((a) => normalizeActorAddress(a)).filter(Boolean))).filter((a) => !cfg.exemptActors.includes(a));
704
+ let primaryWarning;
705
+ let slashEvidence;
706
+ for (const actor of uniqueActors) {
707
+ const rec = getOrCreateActorRecord(reg, actor, nowMs, cfg);
708
+ const prevStrikes = rec.strikes.map((s) => ({ ...s }));
709
+ const prevCooldown = rec.cooldownUntilMs;
710
+ const prevSlashEvidence = rec.lastSlashEvidence;
711
+ const prevWarning = rec.lastWarning;
712
+ if (!(normTxHash ? rec.strikes.some((s) => s.txHash === normTxHash) : false)) rec.strikes.push({
713
+ timestampMs: nowMs,
714
+ weight,
715
+ code: params.reasonCode,
716
+ txHash: normTxHash
717
+ });
718
+ const strikeCount = rec.strikes.reduce((acc, s) => acc + s.weight, 0);
719
+ const tier = computeActorTier(strikeCount, cfg);
720
+ if (tier === "THROTTLED" || tier === "SLASH_TRIGGERED") rec.cooldownUntilMs = Math.max(rec.cooldownUntilMs, nowMs + cfg.throttleCooldownMs);
721
+ const status = getActorSecurityStatus({
722
+ actor,
723
+ config: params.config,
724
+ statedb: params.statedb,
725
+ nowMs,
726
+ telemetry: params.telemetry
727
+ });
728
+ if (status.warning && !primaryWarning) primaryWarning = status.warning;
729
+ if (tier === "SLASH_TRIGGERED" && cfg.autoSlash && params.txn) try {
730
+ const evidence$1 = await executeAutoGasStakeSlash({
731
+ offender: actor,
732
+ strikeCount,
733
+ strikes: rec.strikes,
734
+ config: params.config,
735
+ statedb: params.statedb,
736
+ txn: params.txn,
737
+ fishermanAddress: params.fishermanAddress,
738
+ nowMs
739
+ });
740
+ if (evidence$1) {
741
+ slashEvidence = evidence$1;
742
+ rec.lastSlashEvidence = evidence$1;
743
+ rec.strikes = [];
744
+ }
745
+ } catch (slashErr) {
746
+ rec.strikes = prevStrikes;
747
+ rec.cooldownUntilMs = prevCooldown;
748
+ rec.lastSlashEvidence = prevSlashEvidence;
749
+ rec.lastWarning = prevWarning;
750
+ throw slashErr;
751
+ }
752
+ }
753
+ if (params.txHash && primaryWarning) setTxSecurityWarningForHash(params.txHash, primaryWarning, params.statedb);
754
+ return {
755
+ primaryWarning,
756
+ slashEvidence
757
+ };
758
+ }
759
+ function snapshotActorSecurityRecords(actors, statedb, txHash) {
760
+ const reg = getGasSecurityRegistry(statedb);
761
+ const map = /* @__PURE__ */ new Map();
762
+ for (const raw of actors) {
763
+ const actor = normalizeActorAddress(raw);
764
+ if (!actor) continue;
765
+ const existing = reg.actors.get(actor);
766
+ map.set(actor, existing ? cloneDeep(existing) : null);
767
+ }
768
+ const normHash = txHash ? txHash.trim().toUpperCase() : void 0;
769
+ return {
770
+ actors: map,
771
+ txWarningExisted: normHash ? reg.txWarningsByHash.has(normHash) : false,
772
+ prevTxWarning: normHash ? reg.txWarningsByHash.get(normHash) : void 0,
773
+ txHash: normHash
774
+ };
775
+ }
776
+ function restoreActorSecurityRecords(snapshot, statedb) {
777
+ const reg = getGasSecurityRegistry(statedb);
778
+ for (const [actor, record] of snapshot.actors.entries()) if (record) reg.actors.set(actor, cloneDeep(record));
779
+ else reg.actors.delete(actor);
780
+ if (snapshot.txHash) if (snapshot.txWarningExisted && snapshot.prevTxWarning) reg.txWarningsByHash.set(snapshot.txHash, snapshot.prevTxWarning);
781
+ else reg.txWarningsByHash.delete(snapshot.txHash);
782
+ }
783
+ /**
784
+ * Executes automatic `Stake-for-Gas` slashing when an actor crosses `slashThreshold` (opt-in via
785
+ * `transaction.security.autoSlash`; ONLY inside the enclosing queued tx's own write set, `params.txn` is required):
786
+ * - Transfers 100% of the offender's staked official tokens out of `toStakeAddress(offender, offender)`:
787
+ * - `fishermanBountyBps` (default 10%) to `fishermanAddress` (if provided and distinct from `offender`).
788
+ * - Remaining 90% (or 100% if no fisherman) to `config.vaults.slashedStake` (or `config.vaults.txGas[0]` / `config.vaults.txFee`).
789
+ * - ZERO official tokens are ever burned (Axiom #3).
790
+ * - Creates and persists a deterministic `IAbuseSlashEvidence` record in `statedb.evidence`.
791
+ */
792
+ async function executeAutoGasStakeSlash(params) {
793
+ if (!params.txn) return null;
794
+ const offender = normalizeActorAddress(params.offender);
795
+ const stakeAddress = toStakeAddress(offender, offender);
796
+ const cfg = resolveGasSecurityConfig(params.config);
797
+ const nowIso = new Date(params.nowMs ?? Date.now()).toISOString();
798
+ const officialToken = params.config?.token?.address || "";
799
+ const vaults = params.config?.vaults || {};
800
+ const txGasVaults = Array.isArray(vaults.txGas) ? vaults.txGas : [];
801
+ const configuredVault = normalizeActorAddress(vaults.slashedStake || txGasVaults[0] || vaults.txFee || "");
802
+ const fallbackVaultSink = toStakeAddress(officialToken || stakeAddress, "slashed-stake-vault");
803
+ const vaultDestination = configuredVault && configuredVault !== offender ? configuredVault : fallbackVaultSink;
804
+ const fisherman = normalizeActorAddress(params.fishermanAddress);
805
+ const validFisherman = fisherman && fisherman !== offender && fisherman !== vaultDestination ? fisherman : void 0;
806
+ const reasonCodes = Array.from(new Set(params.strikes.map((s) => s.code)));
807
+ const recentTxHashes = Array.from(new Set(params.strikes.map((s) => s.txHash).filter(Boolean))).slice(-10);
808
+ let fishermanBountyBN = ZERO;
809
+ let vaultAmountBN = ZERO;
810
+ const slashedTokens = {};
811
+ const rawDb = params.statedb?._underlyingStateDb || params.statedb;
812
+ const stakeTable = rawDb?.stake;
813
+ const accountTable = rawDb?.account;
814
+ const evidenceTable = rawDb?.evidence;
815
+ const stateCtx = {
816
+ txHash: recentTxHashes.find((h) => /^[0-9a-fA-F]{64}$/.test(h)) || "",
817
+ txTime: nowIso,
818
+ txn: params.txn
819
+ };
820
+ if (stakeTable && typeof stakeTable.get === "function" && typeof stakeTable.update === "function" && officialToken) {
821
+ const performSlashMutations = async (activeCtx) => {
822
+ const stakeState = await stakeTable.get(stakeAddress, activeCtx);
823
+ const currentStaked = new BN(stakeState?.tokens?.[officialToken] || 0);
824
+ if (!stakeState || currentStaked.lte(ZERO)) return;
825
+ const originalStakeSnapshot = cloneDeep(stakeState);
826
+ const existingVaultSnapshot = accountTable && typeof accountTable.get === "function" ? cloneDeep(await accountTable.get(vaultDestination, activeCtx)) : null;
827
+ slashedTokens[officialToken] = currentStaked.toString(10);
828
+ if (validFisherman && cfg.fishermanBountyBps > 0) fishermanBountyBN = currentStaked.mul(new BN(cfg.fishermanBountyBps)).div(BPS_DENOMINATOR);
829
+ vaultAmountBN = currentStaked.sub(fishermanBountyBN);
830
+ const updatedStakeTokens = {
831
+ ...stakeState.tokens || {},
832
+ [officialToken]: "0"
833
+ };
834
+ const defaultGenesisCtx = {
835
+ genesisTime: nowIso,
836
+ genesisTx: "",
837
+ renaissanceTime: nowIso,
838
+ renaissanceTx: ""
839
+ };
840
+ let updatedStake;
841
+ try {
842
+ updatedStake = stake.update({
843
+ context: defaultGenesisCtx,
844
+ ...cloneDeep(stakeState)
845
+ }, {
846
+ tokens: updatedStakeTokens,
847
+ message: "auto-slashed:abuse-strike-threshold"
848
+ }, activeCtx);
849
+ } catch {
850
+ updatedStake = {
851
+ ...cloneDeep(stakeState),
852
+ tokens: updatedStakeTokens,
853
+ message: "auto-slashed:abuse-strike-threshold"
854
+ };
855
+ }
856
+ let stakeDebited = false;
857
+ let vaultCredited = false;
858
+ try {
859
+ await stakeTable.update(stakeAddress, updatedStake, activeCtx);
860
+ stakeDebited = true;
861
+ const creditAccount = async (targetAddr, deltaBN) => {
862
+ if (!targetAddr || deltaBN.lte(ZERO) || !accountTable || typeof accountTable.get !== "function") return;
863
+ const existing = await accountTable.get(targetAddr, activeCtx);
864
+ const prevBal = new BN(existing?.tokens?.[officialToken] || 0);
865
+ const nextTokens = {
866
+ ...existing?.tokens || {},
867
+ [officialToken]: prevBal.add(deltaBN).toString(10)
868
+ };
869
+ if (existing && typeof accountTable.update === "function") {
870
+ let nextAcc;
871
+ try {
872
+ nextAcc = account.update({
873
+ context: defaultGenesisCtx,
874
+ ...cloneDeep(existing)
875
+ }, { tokens: nextTokens }, activeCtx);
876
+ } catch {
877
+ nextAcc = {
878
+ ...cloneDeep(existing),
879
+ tokens: nextTokens
880
+ };
881
+ }
882
+ await accountTable.update(targetAddr, nextAcc, activeCtx);
883
+ } else if (typeof accountTable.updateOrCreate === "function") {
884
+ const nextAcc = account.updateOrCreate(existing ?? null, {
885
+ address: targetAddr,
886
+ tokens: nextTokens
887
+ }, activeCtx);
888
+ await accountTable.updateOrCreate(existing ?? null, nextAcc, activeCtx);
889
+ } else if (typeof accountTable.create === "function") {
890
+ const nextAcc = account.create({
891
+ address: targetAddr,
892
+ tokens: nextTokens
893
+ }, activeCtx);
894
+ await accountTable.create(targetAddr, nextAcc, activeCtx);
895
+ }
896
+ };
897
+ await creditAccount(vaultDestination, vaultAmountBN);
898
+ vaultCredited = true;
899
+ if (validFisherman && fishermanBountyBN.gt(ZERO)) await creditAccount(validFisherman, fishermanBountyBN);
900
+ } catch (slashWriteErr) {
901
+ delete slashedTokens[officialToken];
902
+ vaultAmountBN = ZERO;
903
+ fishermanBountyBN = ZERO;
904
+ if (stakeDebited) try {
905
+ await stakeTable.update(stakeAddress, originalStakeSnapshot, activeCtx);
906
+ } catch {}
907
+ if (vaultCredited && existingVaultSnapshot && accountTable && typeof accountTable.update === "function") try {
908
+ await accountTable.update(vaultDestination, existingVaultSnapshot, activeCtx);
909
+ } catch {}
910
+ throw slashWriteErr;
911
+ }
912
+ };
913
+ await performSlashMutations(stateCtx);
914
+ }
915
+ if (Object.keys(slashedTokens).length === 0) return null;
916
+ const evidencePayload = {
917
+ type: "AbuseSlashEvidence",
918
+ offender,
919
+ stakeAddress,
920
+ strikeCount: params.strikeCount,
921
+ reasonCodes,
922
+ recentTxHashes,
923
+ slashedTokens,
924
+ fishermanAddress: validFisherman,
925
+ fishermanBounty: fishermanBountyBN.toString(10),
926
+ vaultDestination,
927
+ vaultAmount: vaultAmountBN.toString(10),
928
+ timestamp: nowIso
929
+ };
930
+ const evidenceHash = createHash("sha256").update(`ocap:abuse-slash:v1:${JSON.stringify(evidencePayload)}`).digest("hex").toUpperCase();
931
+ const evidenceRecord = {
932
+ evidenceHash,
933
+ ...evidencePayload
934
+ };
935
+ if (evidenceTable && typeof evidenceTable.create === "function") try {
936
+ if (!(typeof evidenceTable.get === "function" ? await evidenceTable.get(evidenceHash, stateCtx) : null)) {
937
+ const evState = evidence.create({
938
+ hash: evidenceHash,
939
+ data: JSON.stringify(evidenceRecord)
940
+ }, {
941
+ txHash: evidenceHash,
942
+ txTime: nowIso
943
+ });
944
+ await evidenceTable.create(evidenceHash, evState, stateCtx);
945
+ }
946
+ } catch {}
947
+ return evidenceRecord;
948
+ }
949
+ /**
950
+ * Pre-queue ADMISSION control. This is the only consumer of the process-local strike / burst counters:
951
+ * it decides whether a request is accepted into the single-writer queue at all. It never changes the gas,
952
+ * waiver or receipts of a tx that is admitted, so executed outcomes stay a pure function of (tx, chain state)
953
+ * and cannot diverge between the two OS processes on main or across restarts.
954
+ *
955
+ * - `throttle`: the verified signer (`tx.delegator || tx.from`, i.e. the delegatee for delegated txs) is rejected
956
+ * with `TOO_MANY_TXS` while its strike-driven cooldown is active. Cooldowns always expire; actors without any
957
+ * strikes (and actors without stake) are never locked.
958
+ * - `burstEscalation`: the per-sender sliding-window quota rejects with `TOO_MANY_TXS` only above
959
+ * `baseBurstAllowance * stakeMultiple * burstRejectMultiple`. Keyed by the sender, never by the gas sponsor, so a
960
+ * sponsoring app is not capped across all of its users.
961
+ */
962
+ async function assertTxAdmission(params) {
963
+ const cfg = resolveGasSecurityConfig(params.config);
964
+ if (!cfg.enabled) return {};
965
+ const nowMs = params.nowMs ?? Date.now();
966
+ const signer = normalizeActorAddress(params.tx?.delegator || params.tx?.from || "");
967
+ const principal = normalizeActorAddress(params.tx?.from || signer);
968
+ if (!signer || cfg.exemptActors.includes(signer)) return {};
969
+ const dbTx = params.statedb?.tx;
970
+ if (params.txHash && typeof dbTx?.get === "function") {
971
+ let committed = null;
972
+ try {
973
+ committed = await dbTx.get(params.txHash);
974
+ } catch {
975
+ committed = null;
976
+ }
977
+ if (committed) {
978
+ const dup = new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
979
+ dup._strikeRecorded = true;
980
+ throw dup;
981
+ }
982
+ }
983
+ const dbAccount = params.statedb?.account;
984
+ if (!params.tx?.delegator && params.tx?.from && typeof dbAccount?.get === "function") try {
985
+ const senderState = await dbAccount.get(params.tx.from);
986
+ const incoming = parseNonceBn(params.tx.nonce);
987
+ if (senderState && incoming && incoming.lte(parseNonceBn(senderState.nonce) ?? new BN(0))) {
988
+ const stale = new CustomError("INVALID_NONCE", "nonce must be greater in newer transactions");
989
+ stale._strikeRecorded = true;
990
+ throw stale;
991
+ }
992
+ } catch (e) {
993
+ if (e?.code === "INVALID_NONCE") throw e;
994
+ }
995
+ const countedHash = params.unsignedTxHash || params.txHash;
996
+ const burstKey = principal && principal !== signer ? `${signer}>${principal}` : signer;
997
+ if (cfg.throttle) {
998
+ const status = getActorSecurityStatus({
999
+ actor: signer,
1000
+ config: params.config,
1001
+ statedb: params.statedb,
1002
+ nowMs
1003
+ });
1004
+ if (status.tier !== "NORMAL" && status.tier !== "WARNING" && status.cooldownUntilMs > nowMs) {
1005
+ const err = new CustomError("TOO_MANY_TXS", status.warning?.message || `Actor ${signer} is throttled; retry after ${status.cooldownUntilMs - nowMs}ms cooldown`);
1006
+ err.warning = status.warning;
1007
+ throw err;
1008
+ }
1009
+ }
1010
+ let telemetry;
1011
+ if (cfg.burstEscalation && params.config?.transaction?.txGas && params.config?.token) {
1012
+ const config = params.config;
1013
+ let stakeState = null;
1014
+ try {
1015
+ const stakeId = toStakeAddress(signer, signer);
1016
+ stakeState = await params.statedb?.stake?.get?.(stakeId) || null;
1017
+ } catch {
1018
+ stakeState = null;
1019
+ }
1020
+ if (burstKey !== signer) {
1021
+ const agg = evaluateBurstQuota({
1022
+ actor: `${signer}>*`,
1023
+ stakeState,
1024
+ config,
1025
+ statedb: params.statedb,
1026
+ nowMs,
1027
+ txHash: countedHash,
1028
+ variantHash: params.txHash,
1029
+ recordBurst: false,
1030
+ rejectMultiple: cfg.burstRejectMultiple * cfg.delegatedBurstMultiple
1031
+ });
1032
+ if (agg.hardLimitExceeded) throw new CustomError("TOO_MANY_TXS", `Delegatee ${signer} exceeded the aggregate delegated burst limit (${agg.burstCount} > ${agg.hardLimit} per ${cfg.burstWindowMs}ms)`);
1033
+ }
1034
+ const evalRes = evaluateBurstQuota({
1035
+ actor: burstKey,
1036
+ stakeState,
1037
+ config,
1038
+ statedb: params.statedb,
1039
+ nowMs,
1040
+ txHash: countedHash,
1041
+ variantHash: params.txHash,
1042
+ recordBurst: false
1043
+ });
1044
+ telemetry = evalRes.telemetry;
1045
+ if (evalRes.hardLimitExceeded) {
1046
+ const status = getActorSecurityStatus({
1047
+ actor: signer,
1048
+ config: params.config,
1049
+ statedb: params.statedb,
1050
+ nowMs,
1051
+ telemetry
1052
+ });
1053
+ const err = new CustomError("TOO_MANY_TXS", `Actor ${signer} exceeded the burst limit (${evalRes.burstCount} > ${evalRes.hardLimit} per ${cfg.burstWindowMs}ms); retry after ${telemetry.recommendedBackoffMs}ms or stake more for a larger quota`);
1054
+ err.warning = status.warning || {
1055
+ tier: "NORMAL",
1056
+ code: "GAS_QUOTA_ADVISORY",
1057
+ message: `Actor ${signer} burst gas load ratio is ${telemetry.loadRatio}`,
1058
+ actor: signer,
1059
+ strikeCount: 0,
1060
+ warningThreshold: cfg.warningThreshold,
1061
+ throttleThreshold: cfg.throttleThreshold,
1062
+ slashThreshold: cfg.slashThreshold,
1063
+ gasStakeQuotaRemaining: 0,
1064
+ cooldownUntilMs: 0,
1065
+ telemetry
1066
+ };
1067
+ throw err;
1068
+ }
1069
+ const record = (actor, rejectMultiple) => evaluateBurstQuota({
1070
+ actor,
1071
+ stakeState,
1072
+ config,
1073
+ statedb: params.statedb,
1074
+ nowMs,
1075
+ txHash: countedHash,
1076
+ variantHash: params.txHash,
1077
+ rejectMultiple
1078
+ });
1079
+ if (burstKey !== signer) record(`${signer}>*`, cfg.burstRejectMultiple * cfg.delegatedBurstMultiple);
1080
+ record(burstKey);
1081
+ }
1082
+ return { telemetry };
1083
+ }
1084
+ function getTxSecurityWarningByHash(txHash, statedb) {
1085
+ if (!txHash || typeof txHash !== "string") return void 0;
1086
+ return getGasSecurityRegistry(statedb).txWarningsByHash.get(txHash.trim().toUpperCase());
1087
+ }
1088
+ function setTxSecurityWarningForHash(txHash, warning, statedb) {
1089
+ if (!txHash || typeof txHash !== "string" || !warning) return;
1090
+ const normKey = txHash.trim().toUpperCase();
1091
+ if (!normKey) return;
1092
+ const reg = getGasSecurityRegistry(statedb);
1093
+ if (!reg.txWarningsByHash.has(normKey) && reg.txWarningsByHash.size >= MAX_TRACKED_ACTORS) {
1094
+ const oldest = reg.txWarningsByHash.keys().next().value;
1095
+ if (oldest) reg.txWarningsByHash.delete(oldest);
1096
+ }
1097
+ reg.txWarningsByHash.set(normKey, warning);
1098
+ }
1099
+
1100
+ //#endregion
1101
+ export { DEFAULT_BASE_BURST_ALLOWANCE, DEFAULT_BURST_REJECT_MULTIPLE, DEFAULT_BURST_WINDOW_MS, DEFAULT_DELEGATED_BURST_MULTIPLE, DEFAULT_FISHERMAN_BOUNTY_BPS, DEFAULT_GAS_PASS_EPOCH_SECONDS, DEFAULT_MAX_FREE_GAS_STATE_OPS, DEFAULT_MAX_FREE_GAS_TX_SIZE, DEFAULT_SLASH_STRIKE_THRESHOLD, DEFAULT_STRIKE_WINDOW_MS, DEFAULT_THROTTLE_COOLDOWN_MS, DEFAULT_THROTTLE_STRIKE_THRESHOLD, DEFAULT_WARNING_STRIKE_THRESHOLD, DIRECT_GAS_REQUIRED_TX_TYPES, FREE_GAS_ELIGIBLE_TX_TYPES, assertTxAdmission, classifyErrorStrikeCategory, computeActorTier, computeUnlinkableGasPassCommitment, computeUnlinkableGasPassSecretHash, evaluateBurstQuota, evaluateStakeForGasEligibility, executeAutoGasStakeSlash, extractTransactionTargets, getActorSecurityStatus, getGasSecurityRegistry, getTxSecurityWarningByHash, normalizeActorAddress, normalizeShortTxType, recordActorSecurityStrike, resetGasSecurityState, resolveGasSecurityConfig, resolveVerifiedStrikeActors, restoreActorSecurityRecords, setTxSecurityWarningForHash, snapshotActorSecurityRecords, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints };