@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
@@ -1,11 +1,13 @@
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_util = require('../util.cjs');
5
+ let _arcblock_did = require("@arcblock/did");
6
+ let _arcblock_did_util = require("@arcblock/did-util");
4
7
  let _ocap_state = require("@ocap/state");
5
8
  let _ocap_util = require("@ocap/util");
6
9
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
7
- let _arcblock_did = require("@arcblock/did");
8
- let _arcblock_did_util = require("@arcblock/did-util");
10
+ let _ocap_util_lib_get_related_addr = require("@ocap/util/lib/get-related-addr");
9
11
  let _arcblock_jwt = require("@arcblock/jwt");
10
12
  _arcblock_jwt = require_rolldown_runtime.__toESM(_arcblock_jwt);
11
13
  let lodash_noop = require("lodash/noop");
@@ -16,34 +18,221 @@ debug = require_rolldown_runtime.__toESM(debug);
16
18
  //#region src/pipes/ensure-cost.ts
17
19
  const debug$1 = (0, debug.default)("@ocap/tx-protocols:pipes:ensure-cost");
18
20
  const ZERO = new _ocap_util.BN(0);
21
+ function isMatchingAccountPublicKey(onChainPk, headerPk) {
22
+ if (onChainPk === headerPk) return true;
23
+ try {
24
+ const headerBuf = (0, _ocap_util.toBuffer)(headerPk);
25
+ if ((0, _ocap_util.toBase58)(headerBuf) === onChainPk || (0, _ocap_util.toBase64)(headerBuf) === onChainPk) return true;
26
+ } catch {}
27
+ return false;
28
+ }
19
29
  /** Context for ensure cost pipe */ function CreateEnsureTxCostPipe({ attachSenderChanges = true, throwOnInsufficientFund = true, gasOnly = false } = {}) {
20
30
  return async function EnsureTxCost(context, next) {
21
31
  const { statedb, txType, senderState, gasEstimate, totalGas } = context;
22
32
  const { config } = context;
23
- const { tx, extra = {}, txHash = "" } = context;
33
+ const { tx, extra = {}, txHash = "", txTime } = context;
34
+ const isFailedTxGasCharge = Boolean(context.isFailedTxGasCharge);
35
+ const nowMs = txTime ? +new Date(txTime) : Date.now();
24
36
  const { token, pk } = extra.gasStakeHeaders || {};
37
+ const rawGasPass = extra.gasPass || extra.txExtra?.gasPass;
25
38
  const gasStake = {};
26
- if (token && pk && await _arcblock_jwt.verify(token, pk, {
27
- enforceTimestamp: true,
28
- tolerance: 5
29
- })) {
30
- const decoded = _arcblock_jwt.decode(token);
31
- if ((decoded.txHash || "").split(",").map((x) => x.trim()).filter(Boolean).includes(txHash)) {
32
- gasStake.owner = (0, _arcblock_did.toAddress)(decoded.iss);
33
- gasStake.stakeId = (0, _arcblock_did_util.toStakeAddress)(gasStake.owner, gasStake.owner);
34
- } else console.warn(`Invalid gas payer header for: ${txHash}`);
39
+ let isThirdPartySponsor = false;
40
+ let enforceSponsor3DEligibility = false;
41
+ let isPaymasterDirectCharge = false;
42
+ let sponsorAccountState = null;
43
+ const resolveSignerSelfGasStake = async () => {
44
+ const officialTok = config.token?.address || "";
45
+ if (!officialTok) return {
46
+ hasSelfStake: false,
47
+ owner: "",
48
+ stakeId: "",
49
+ state: null,
50
+ valid: false
51
+ };
52
+ const candidates = Array.from(new Set([tx?.from, tx?.delegator].filter(Boolean)));
53
+ for (const candidate of candidates) {
54
+ const stakeId = (0, _arcblock_did_util.toStakeAddress)(candidate, candidate);
55
+ const selfStake = await statedb.stake?.get?.(stakeId, context);
56
+ if (new _ocap_util.BN(selfStake?.tokens?.[officialTok] || 0).gt(ZERO)) return {
57
+ hasSelfStake: true,
58
+ owner: candidate,
59
+ stakeId,
60
+ state: selfStake || null,
61
+ valid: require_util.isGasStakeValid(selfStake, config)
62
+ };
63
+ }
64
+ return {
65
+ hasSelfStake: false,
66
+ owner: "",
67
+ stakeId: "",
68
+ state: null,
69
+ valid: false
70
+ };
71
+ };
72
+ let isThirdPartyGasPass = false;
73
+ if (!isFailedTxGasCharge && rawGasPass) {
74
+ const passStakeState = rawGasPass.stakeId ? await statedb.stake?.get?.(rawGasPass.stakeId, context) : null;
75
+ const passResult = require_gas_security_guard.verifyAndConsumeUnlinkableGasPass({
76
+ gasPass: rawGasPass,
77
+ stakeState: passStakeState,
78
+ txHash,
79
+ nowMs,
80
+ config,
81
+ statedb
82
+ });
83
+ if (!passResult.valid) {
84
+ const passErr = new _ocap_util_lib_error.CustomError(passResult.reason || "INVALID_GAS_PASS", `Invalid unlinkable gas pass: ${passResult.reason}`);
85
+ passErr._unauthenticatedExtraFailure = true;
86
+ return next(passErr);
87
+ }
88
+ const passOwner = passStakeState?.sender || rawGasPass.stakeId;
89
+ isThirdPartyGasPass = Boolean(passOwner && (!tx?.from || !(0, _ocap_util.isSameDid)(passOwner, tx.from)) && (!tx?.delegator || !(0, _ocap_util.isSameDid)(passOwner, tx.delegator)));
90
+ const selfStakeInfo = isThirdPartyGasPass ? await resolveSignerSelfGasStake() : null;
91
+ if (selfStakeInfo?.valid) {
92
+ gasStake.owner = selfStakeInfo.owner;
93
+ gasStake.stakeId = selfStakeInfo.stakeId;
94
+ gasStake.state = selfStakeInfo.state;
95
+ isThirdPartyGasPass = false;
96
+ } else {
97
+ gasStake.owner = passOwner;
98
+ gasStake.stakeId = passResult.stakeId;
99
+ gasStake.state = passStakeState;
100
+ }
101
+ } else if (!isFailedTxGasCharge && token && pk) {
102
+ const decoded = _arcblock_jwt.decode(token) || {};
103
+ const sponsorAddress = (0, _arcblock_did.toAddress)(decoded.iss || "");
104
+ if (!sponsorAddress || !(0, _arcblock_did.isFromPublicKey)(sponsorAddress, pk)) {
105
+ const hdrErr = new _ocap_util_lib_error.CustomError("INVALID_GAS_STAKE_HEADERS", "Gas stake JWT issuer does not match signer public key");
106
+ hdrErr._unauthenticatedExtraFailure = true;
107
+ return next(hdrErr);
108
+ }
109
+ if (await _arcblock_jwt.verify(token, pk, {
110
+ enforceTimestamp: !txTime,
111
+ tolerance: 5
112
+ })) {
113
+ const toleranceSec = 5;
114
+ const nowSec = txTime ? Math.floor(+new Date(txTime) / 1e3) : Math.floor(Date.now() / 1e3);
115
+ const expNum = decoded?.exp != null && decoded.exp !== "" ? Number(decoded.exp) : NaN;
116
+ const expValid = Number.isFinite(expNum) && expNum > 0 && expNum + toleranceSec >= nowSec;
117
+ const nbfNum = decoded?.nbf != null && decoded.nbf !== "" ? Number(decoded.nbf) : NaN;
118
+ const nbfValid = decoded?.nbf == null || decoded.nbf === "" || Number.isFinite(nbfNum) && nbfNum - toleranceSec <= nowSec;
119
+ const iatNum = decoded?.iat != null && decoded.iat !== "" ? Number(decoded.iat) : NaN;
120
+ const iatValid = decoded?.iat == null || decoded.iat === "" || Number.isFinite(iatNum) && iatNum - toleranceSec <= nowSec;
121
+ const txHashes = (decoded.txHash || "").split(",").map((x) => x.trim()).filter(Boolean);
122
+ if (expValid && nbfValid && iatValid && txHashes.includes(txHash)) {
123
+ const sponsorState = await statedb.account?.get?.(sponsorAddress, {
124
+ ...context,
125
+ traceMigration: false
126
+ });
127
+ if (sponsorState?.pk && !isMatchingAccountPublicKey(sponsorState.pk, pk)) {
128
+ 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");
129
+ pkErr._unauthenticatedExtraFailure = true;
130
+ return next(pkErr);
131
+ }
132
+ const isSponsorMigrated = Array.isArray(sponsorState?.migratedTo) && sponsorState.migratedTo.length > 0;
133
+ const sponsorAddresses = (0, _ocap_util_lib_get_related_addr.getRelatedAddresses)(sponsorState || { address: sponsorAddress });
134
+ const checkBlocked = async (checker, addr) => {
135
+ if (typeof checker?.isBlocked !== "function") return false;
136
+ if (await Promise.resolve(checker.isBlocked(addr))) return true;
137
+ return Boolean(await Promise.resolve(checker.isBlocked([addr])));
138
+ };
139
+ let isSponsorBlocked = false;
140
+ for (const addr of sponsorAddresses) if (await checkBlocked(context.filter, addr) || await checkBlocked(statedb.blacklist, addr)) {
141
+ isSponsorBlocked = true;
142
+ break;
143
+ }
144
+ if (!isSponsorMigrated && !isSponsorBlocked) {
145
+ const sponsorStakeId = (0, _arcblock_did_util.toStakeAddress)(sponsorAddress, sponsorAddress);
146
+ const isDirectMode = decoded.mode === "paymaster";
147
+ const sponsorStakeState = !isDirectMode ? await statedb.stake?.get?.(sponsorStakeId, context) : null;
148
+ const officialTok = config.token?.address || "";
149
+ const sponsorIsBacked = isDirectMode ? Boolean(sponsorState && officialTok && new _ocap_util.BN(sponsorState.tokens?.[officialTok] || 0).gte((totalGas ?? ZERO).gt(ZERO) ? totalGas ?? ZERO : new _ocap_util.BN(1))) : require_util.isGasStakeValid(sponsorStakeState, config);
150
+ const paymasterCheck = require_gas_security_guard.verifyPaymasterConstraints({
151
+ decoded,
152
+ tx,
153
+ itx: context.itx,
154
+ txType,
155
+ totalGas: totalGas ?? ZERO
156
+ });
157
+ if (!paymasterCheck.valid) {
158
+ const pmErr = new _ocap_util_lib_error.CustomError(paymasterCheck.reason || "PAYMASTER_VIOLATION", `Paymaster sponsorship constraint violated: ${paymasterCheck.reason}`);
159
+ pmErr._strikeRecorded = true;
160
+ pmErr._unauthenticatedExtraFailure = true;
161
+ return next(pmErr);
162
+ }
163
+ if (paymasterCheck.isPaymasterDirectCharge) {
164
+ const txTargets = require_gas_security_guard.extractTransactionTargets(tx, context.itx, txType);
165
+ if ([
166
+ tx?.from,
167
+ tx?.delegator,
168
+ context.gasVault,
169
+ context.feeVault,
170
+ config.vaults?.txFee,
171
+ ...Array.isArray(config.vaults?.txGas) ? config.vaults.txGas : [],
172
+ ...Array.isArray(config.vaults?.txFees) ? config.vaults.txFees : [],
173
+ ...txTargets
174
+ ].filter(Boolean).some((candidate) => (0, _ocap_util.isSameDid)(sponsorAddress, candidate) || sponsorAddress === candidate)) {
175
+ const aliasErr = new _ocap_util_lib_error.CustomError("PAYMASTER_SPONSOR_ALIAS_FORBIDDEN", "Paymaster direct-charge sponsor cannot alias transaction sender, delegator, target, or vault");
176
+ aliasErr._unauthenticatedExtraFailure = true;
177
+ return next(aliasErr);
178
+ }
179
+ }
180
+ const selfStakeInfo = await resolveSignerSelfGasStake();
181
+ if (selfStakeInfo.valid) {
182
+ gasStake.owner = selfStakeInfo.owner;
183
+ gasStake.stakeId = selfStakeInfo.stakeId;
184
+ gasStake.state = selfStakeInfo.state;
185
+ } else if (!sponsorIsBacked && selfStakeInfo.hasSelfStake) {} else {
186
+ isThirdPartySponsor = true;
187
+ enforceSponsor3DEligibility = decoded.enforce3DEligibility === true || (config.transaction?.txGas)?.enforceSponsor3DEligibility === true;
188
+ isPaymasterDirectCharge = paymasterCheck.isPaymasterDirectCharge;
189
+ sponsorAccountState = sponsorState || null;
190
+ if (isPaymasterDirectCharge && sponsorAccountState) context.sponsorState = sponsorAccountState;
191
+ gasStake.owner = sponsorAddress;
192
+ gasStake.stakeId = sponsorStakeId;
193
+ if (sponsorStakeState) gasStake.state = sponsorStakeState;
194
+ }
195
+ }
196
+ } else console.warn(`Invalid gas payer header for: ${txHash}`);
197
+ }
35
198
  }
36
199
  if (!gasStake.owner && tx?.from) {
37
200
  const owner = tx.from;
38
201
  gasStake.owner = owner;
39
202
  gasStake.stakeId = (0, _arcblock_did_util.toStakeAddress)(owner, owner);
40
203
  }
41
- gasStake.state = await statedb.stake.get(gasStake.stakeId, context);
42
- gasStake.valid = require_util.isGasStakeValid(gasStake.state, config);
204
+ if (!gasStake.state && gasStake.stakeId) gasStake.state = await statedb.stake.get(gasStake.stakeId, context);
205
+ const eligibility = require_gas_security_guard.evaluateStakeForGasEligibility({
206
+ txType,
207
+ txSize: context._baseTxSize ?? context.txSize,
208
+ gasEstimate,
209
+ isFailedTxGasCharge,
210
+ isThirdPartySponsor,
211
+ enforceSponsor3DEligibility,
212
+ config
213
+ });
214
+ const baseStakeValid = !isPaymasterDirectCharge && require_util.isGasStakeValid(gasStake.state, config) && eligibility.eligible;
215
+ const effectiveTotalGas = totalGas ?? ZERO;
216
+ const warnActor = tx?.delegator || tx?.from || "";
217
+ if (!isFailedTxGasCharge && warnActor && require_gas_security_guard.resolveGasSecurityConfig(config).enabled) {
218
+ const status = require_gas_security_guard.getActorSecurityStatus({
219
+ actor: warnActor,
220
+ config,
221
+ statedb,
222
+ nowMs
223
+ });
224
+ if (status.warning) {
225
+ context.securityWarning = status.warning;
226
+ if (txHash) require_gas_security_guard.setTxSecurityWarningForHash(txHash, status.warning, statedb);
227
+ }
228
+ }
229
+ gasStake.valid = baseStakeValid;
43
230
  context.gasStake = gasStake;
231
+ context.gasEligibility = eligibility;
44
232
  debug$1("gasStake", gasStake, context.extra);
45
233
  const changes = {};
46
234
  let txCost = new _ocap_util.BN(0);
235
+ let sponsorGasCost = new _ocap_util.BN(0);
47
236
  const txFeeMap = config.transaction.txFee;
48
237
  const txFee = txType ? txFeeMap[txType] : void 0;
49
238
  if (!gasOnly && txFee) {
@@ -55,76 +244,143 @@ const ZERO = new _ocap_util.BN(0);
55
244
  };
56
245
  context.feeVaultChange = changes.fee;
57
246
  }
58
- const totalGasBN = totalGas ?? ZERO;
247
+ const totalGasBN = effectiveTotalGas;
59
248
  if (!gasStake.valid && totalGasBN.gt(ZERO)) {
60
- txCost = txCost.add(totalGasBN);
61
249
  changes.gas = {
62
250
  address: config.token.address,
63
251
  value: totalGasBN.toString(10)
64
252
  };
65
253
  context.gasVaultChange = changes.gas;
254
+ if (isPaymasterDirectCharge && !isFailedTxGasCharge) sponsorGasCost = totalGasBN;
255
+ else txCost = txCost.add(totalGasBN);
66
256
  }
67
257
  if (changes.fee) if (config.vaults.txFees?.length) {
68
258
  const feeIndex = (0, _ocap_util.hexToNumber)(txHash.slice(-8)) % config.vaults.txFees.length;
69
259
  context.feeVault = config.vaults.txFees[feeIndex];
70
260
  } else context.feeVault = config.vaults.txFee;
261
+ if (changes.gas && !context.gasVault) {
262
+ if (config.vaults.txGas?.length) {
263
+ const gasIndex = (0, _ocap_util.hexToNumber)(txHash.slice(-8)) % config.vaults.txGas.length;
264
+ context.gasVault = config.vaults.txGas[gasIndex];
265
+ } else if (config.vaults.txFee) context.gasVault = config.vaults.txFee;
266
+ }
267
+ if (sponsorGasCost.gt(ZERO)) {
268
+ const sponsorBalance = new _ocap_util.BN(sponsorAccountState?.tokens?.[config.token.address] || 0);
269
+ if (!sponsorAccountState) {
270
+ const noSponsorErr = new _ocap_util_lib_error.CustomError("INVALID_GAS_PAYER", `Paymaster sponsor ${gasStake.owner} does not exist on chain`);
271
+ noSponsorErr._unauthenticatedExtraFailure = true;
272
+ return next(noSponsorErr);
273
+ }
274
+ if (sponsorBalance.lt(sponsorGasCost)) {
275
+ const sponsorFundErr = new _ocap_util_lib_error.CustomError("INSUFFICIENT_FUND", `Insufficient fund in paymaster sponsor ${sponsorAccountState.address} to pay gas`);
276
+ sponsorFundErr._unauthenticatedExtraFailure = true;
277
+ return next(sponsorFundErr);
278
+ }
279
+ }
71
280
  let isCostCharged = false;
72
- if (txCost.gt(ZERO)) {
281
+ if (txCost.gt(ZERO) || sponsorGasCost.gt(ZERO)) {
73
282
  const expected = new _ocap_util.BN(gasEstimate?.payment || 0).add(txCost);
74
283
  const actual = new _ocap_util.BN(senderState?.tokens?.[config.token.address] || 0);
75
- if (senderState && actual.gte(expected)) {
284
+ if (txCost.eq(ZERO) || Boolean(senderState) && actual.gte(expected)) {
76
285
  isCostCharged = true;
77
- context.senderUpdates = require_util.applyTokenUpdates([{
78
- address: config.token.address,
79
- value: txCost.toString(10)
80
- }], senderState, "sub");
81
- context.senderChange = {
82
- address: senderState.address,
83
- token: config.token.address,
84
- delta: `-${txCost.toString(10)}`
85
- };
286
+ if (txCost.gt(ZERO) && senderState) {
287
+ context.senderUpdates = require_util.applyTokenUpdates([{
288
+ address: config.token.address,
289
+ value: txCost.toString(10)
290
+ }], senderState, "sub");
291
+ context.senderChange = {
292
+ address: senderState.address,
293
+ token: config.token.address,
294
+ delta: `-${txCost.toString(10)}`
295
+ };
296
+ } else {
297
+ context.senderUpdates = {};
298
+ context.senderChange = null;
299
+ }
86
300
  debug$1({
87
301
  changes,
88
302
  senderUpdates: context.senderUpdates
89
303
  });
90
304
  context.updateVaults = async function updateVaults() {
91
- const [feeVaultState, gasVaultState] = await Promise.all([changes.fee && context.feeVault ? statedb.account.get(context.feeVault, context) : null, changes.gas && context.gasVault ? statedb.account.get(context.gasVault, context) : null]);
92
- const [newFeeVaultState, newGasVaultState] = await Promise.all([changes.fee && feeVaultState ? statedb.account.update(feeVaultState.address, _ocap_state.account.update(feeVaultState, require_util.applyTokenUpdates([changes.fee], feeVaultState, "add"), context), context) : null, changes.gas && gasVaultState ? statedb.account.update(gasVaultState.address, _ocap_state.account.update(gasVaultState, require_util.applyTokenUpdates([changes.gas], gasVaultState, "add"), context), context) : null]);
93
- if (newFeeVaultState) context.feeVaultState = newFeeVaultState;
94
- if (newGasVaultState) context.gasVaultState = newGasVaultState;
305
+ if (context.gasPaid) return;
306
+ if (sponsorGasCost.gt(ZERO) && sponsorAccountState && changes.gas) {
307
+ const latestSponsor = await statedb.account.get(sponsorAccountState.address, context) || sponsorAccountState;
308
+ const tokenDelta = require_util.applyTokenUpdates([changes.gas], latestSponsor, "sub");
309
+ let updatedSponsorPayload;
310
+ try {
311
+ updatedSponsorPayload = _ocap_state.account.update(latestSponsor, tokenDelta, context);
312
+ } catch {
313
+ updatedSponsorPayload = {
314
+ ...latestSponsor,
315
+ ...tokenDelta
316
+ };
317
+ }
318
+ const nextSponsorState = await statedb.account.update(latestSponsor.address, updatedSponsorPayload, context);
319
+ if (nextSponsorState && typeof nextSponsorState === "object") nextSponsorState._retrievedAt = Date.now() + 1;
320
+ context.sponsorState = nextSponsorState;
321
+ }
322
+ let feeVaultState = null;
323
+ let gasVaultState = null;
324
+ if (changes.fee && changes.gas && context.feeVault && context.gasVault && context.feeVault === context.gasVault) {
325
+ const sharedVaultState = await statedb.account.get(context.feeVault, context);
326
+ feeVaultState = sharedVaultState;
327
+ gasVaultState = sharedVaultState;
328
+ if (sharedVaultState) {
329
+ const combinedState = await statedb.account.update(sharedVaultState.address, _ocap_state.account.update(sharedVaultState, require_util.applyTokenUpdates([changes.fee, changes.gas], sharedVaultState, "add"), context), context);
330
+ context.feeVaultState = combinedState;
331
+ context.gasVaultState = combinedState;
332
+ }
333
+ } else {
334
+ [feeVaultState, gasVaultState] = await Promise.all([changes.fee && context.feeVault ? statedb.account.get(context.feeVault, context) : null, changes.gas && context.gasVault ? statedb.account.get(context.gasVault, context) : null]);
335
+ const [newFeeVaultState, newGasVaultState] = await Promise.all([changes.fee && feeVaultState ? statedb.account.update(feeVaultState.address, _ocap_state.account.update(feeVaultState, require_util.applyTokenUpdates([changes.fee], feeVaultState, "add"), context), context) : null, changes.gas && gasVaultState ? statedb.account.update(gasVaultState.address, _ocap_state.account.update(gasVaultState, require_util.applyTokenUpdates([changes.gas], gasVaultState, "add"), context), context) : null]);
336
+ if (newFeeVaultState) context.feeVaultState = newFeeVaultState;
337
+ if (newGasVaultState) context.gasVaultState = newGasVaultState;
338
+ }
95
339
  context.updatedAccounts = context.updatedAccounts || [];
96
340
  if (changes.fee && feeVaultState) {
97
- context.updatedAccounts.push({
98
- address: feeVaultState.address,
99
- token: config.token.address,
100
- delta: changes.fee.value,
101
- action: "fee"
102
- });
103
- if (attachSenderChanges) context.updatedAccounts.push({
104
- address: senderState.address,
105
- token: config.token.address,
106
- delta: `-${changes.fee.value}`,
107
- action: "fee"
108
- });
341
+ if (!Boolean(attachSenderChanges && senderState && (0, _ocap_util.isSameDid)(senderState.address, feeVaultState.address))) {
342
+ context.updatedAccounts.push({
343
+ address: feeVaultState.address,
344
+ token: config.token.address,
345
+ delta: changes.fee.value,
346
+ action: "fee"
347
+ });
348
+ if (attachSenderChanges && senderState) context.updatedAccounts.push({
349
+ address: senderState.address,
350
+ token: config.token.address,
351
+ delta: `-${changes.fee.value}`,
352
+ action: "fee"
353
+ });
354
+ }
109
355
  }
110
356
  if (changes.gas && gasVaultState) {
111
- context.updatedAccounts.push({
112
- address: gasVaultState.address,
113
- token: config.token.address,
114
- delta: changes.gas.value,
115
- action: "gas"
116
- });
117
- if (attachSenderChanges) context.updatedAccounts.push({
118
- address: senderState.address,
119
- token: config.token.address,
120
- delta: `-${changes.gas.value}`,
121
- action: "gas"
122
- });
357
+ const gasPayerAddress = sponsorGasCost.gt(ZERO) && sponsorAccountState ? sponsorAccountState.address : attachSenderChanges && senderState ? senderState.address : "";
358
+ if (!gasPayerAddress || !(0, _ocap_util.isSameDid)(gasPayerAddress, gasVaultState.address)) {
359
+ context.updatedAccounts.push({
360
+ address: gasVaultState.address,
361
+ token: config.token.address,
362
+ delta: changes.gas.value,
363
+ action: "gas"
364
+ });
365
+ if (gasPayerAddress) context.updatedAccounts.push({
366
+ address: gasPayerAddress,
367
+ token: config.token.address,
368
+ delta: `-${changes.gas.value}`,
369
+ action: "gas"
370
+ });
371
+ }
123
372
  }
124
373
  context.gasPaid = true;
125
374
  };
126
- } else if (!senderState) return next(new _ocap_util_lib_error.CustomError("INVALID_GAS_PAYER", `Gas payer ${tx.from} does not exist on chain`));
127
- else if (throwOnInsufficientFund) return next(new _ocap_util_lib_error.CustomError("INSUFFICIENT_FUND", `Insufficient fund to pay for tx cost from ${senderState.address || tx.from}, expected ${(0, _ocap_util.fromUnitToToken)(expected, config.token.decimal)} ${config.token.symbol}, got ${(0, _ocap_util.fromUnitToToken)(actual, config.token.decimal)} ${config.token.symbol}`));
375
+ } else if (!senderState) {
376
+ const noSenderErr = new _ocap_util_lib_error.CustomError("INVALID_GAS_PAYER", `Gas payer ${tx.from} does not exist on chain`);
377
+ if (isThirdPartySponsor || Boolean(rawGasPass) || Boolean(context.extra?.txExtra || context.extra?.coSignature || context.extra?.gasStakeHeaders)) noSenderErr._unauthenticatedExtraFailure = true;
378
+ return next(noSenderErr);
379
+ } else if (throwOnInsufficientFund) {
380
+ const senderFundErr = new _ocap_util_lib_error.CustomError("INSUFFICIENT_FUND", `Insufficient fund to pay for tx cost from ${senderState.address || tx.from}, expected ${(0, _ocap_util.fromUnitToToken)(expected, config.token.decimal)} ${config.token.symbol}, got ${(0, _ocap_util.fromUnitToToken)(actual, config.token.decimal)} ${config.token.symbol}`);
381
+ if (isThirdPartySponsor || Boolean(rawGasPass) || Boolean(context.extra?.txExtra || context.extra?.coSignature || context.extra?.gasStakeHeaders)) senderFundErr._unauthenticatedExtraFailure = true;
382
+ return next(senderFundErr);
383
+ }
128
384
  }
129
385
  if (!isCostCharged) {
130
386
  context.senderUpdates = {};
@@ -2,43 +2,59 @@ Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
3
3
  const require_pipes_ensure_cost = require('../../pipes/ensure-cost.cjs');
4
4
  const require_pipes_ensure_gas = require('../../pipes/ensure-gas.cjs');
5
+ let _arcblock_did = require("@arcblock/did");
6
+ let _arcblock_did_util = require("@arcblock/did-util");
7
+ let _ocap_mcrypto = require("@ocap/mcrypto");
5
8
  let _ocap_state = require("@ocap/state");
6
9
  let _ocap_tx_pipeline = require("@ocap/tx-pipeline");
7
10
  let _ocap_util = require("@ocap/util");
8
11
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
12
+ let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
13
+ let lodash_cloneDeep = require("lodash/cloneDeep");
14
+ lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
9
15
  let lodash_get = require("lodash/get");
10
16
  lodash_get = require_rolldown_runtime.__toESM(lodash_get);
11
17
  let lodash_pick = require("lodash/pick");
12
18
  lodash_pick = require_rolldown_runtime.__toESM(lodash_pick);
13
- let _arcblock_did_util = require("@arcblock/did-util");
14
19
  let debug = require("debug");
15
20
  debug = require_rolldown_runtime.__toESM(debug);
16
21
  let _ocap_message = require("@ocap/message");
17
- let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
18
- let lodash_cloneDeep = require("lodash/cloneDeep");
19
- lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
20
22
  let _arcblock_validator = require("@arcblock/validator");
21
23
 
22
24
  //#region src/protocols/account/delegate.ts
23
25
  const debug$1 = (0, debug.default)("@ocap/tx-protocols:delegate");
24
26
  const runner = new _ocap_tx_pipeline.Runner("delegate");
27
+ runner.use((context, next) => {
28
+ const signatures = (0, _ocap_util_lib_get_list_field.getListField)(context.tx, "signatures");
29
+ if (context.tx?.delegator || signatures.some((s) => Boolean(s?.delegator))) return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "Delegation is not supported for this transaction", { persist: false }));
30
+ return next();
31
+ });
25
32
  runner.use(_ocap_tx_pipeline.pipes.VerifyMultiSig(0));
26
33
  const rateLimit = _arcblock_validator.v.object({
27
34
  interval: _arcblock_validator.v.pipe(_arcblock_validator.v.number(), _arcblock_validator.v.integer(), _arcblock_validator.v.minValue(1)),
28
35
  anchor: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.pipe(_arcblock_validator.v.number(), _arcblock_validator.v.integer(), _arcblock_validator.v.minValue(0))), 0)
29
36
  });
30
- const tokenLimit = _arcblock_validator.v.object({
37
+ const vNonNegativeBN = () => _arcblock_validator.v.pipe((0, _arcblock_validator.vBN)(), _arcblock_validator.v.check((val) => /^\d+$/.test(String(val).trim()), "Allowance must be a non-negative integer string"));
38
+ const tokenLimit = _arcblock_validator.v.pipe(_arcblock_validator.v.object({
31
39
  address: (0, _arcblock_validator.vDID)({
32
40
  prefix: true,
33
41
  role: "ROLE_TOKEN"
34
42
  }),
35
43
  toList: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.pipe(_arcblock_validator.v.array((0, _arcblock_validator.vDID)({ prefix: true })), _arcblock_validator.v.maxLength(32))), []),
36
44
  txCount: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.pipe(_arcblock_validator.v.number(), _arcblock_validator.v.integer(), _arcblock_validator.v.minValue(0))), 0),
37
- txAllowance: _arcblock_validator.v.optional(_arcblock_validator.v.nullable((0, _arcblock_validator.vBN)()), "0"),
38
- totalAllowance: _arcblock_validator.v.optional(_arcblock_validator.v.nullable((0, _arcblock_validator.vBN)()), "0"),
45
+ txAllowance: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(vNonNegativeBN()), "0"),
46
+ maxPerTx: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(vNonNegativeBN())),
47
+ totalAllowance: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(vNonNegativeBN()), "0"),
39
48
  validUntil: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.pipe(_arcblock_validator.v.number(), _arcblock_validator.v.integer(), _arcblock_validator.v.minValue(0))), 0),
40
- rate: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(rateLimit))
41
- });
49
+ rate: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(rateLimit)),
50
+ windowLimit: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(vNonNegativeBN())),
51
+ windowSeconds: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.pipe(_arcblock_validator.v.number(), _arcblock_validator.v.integer(), _arcblock_validator.v.minValue(1)))),
52
+ coSignAllowance: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(vNonNegativeBN())),
53
+ coSignRequired: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.boolean())),
54
+ requirePinnedPayee: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.boolean())),
55
+ notifyBeforeDebit: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.boolean())),
56
+ notifyLeadSeconds: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.pipe(_arcblock_validator.v.number(), _arcblock_validator.v.integer(), _arcblock_validator.v.minValue(0))))
57
+ }), _arcblock_validator.v.check((t) => (!t.windowLimit || t.windowLimit === "0" || typeof t.windowSeconds === "number" && t.windowSeconds > 0) && (!t.windowSeconds || Boolean(t.windowLimit) && t.windowLimit !== "0"), "windowLimit and windowSeconds (> 0) must be configured together"), _arcblock_validator.v.check((t) => !t.requirePinnedPayee || Array.isArray(t.toList) && t.toList.length > 0, "requirePinnedPayee requires a non-empty toList"));
42
58
  const assetLimit = _arcblock_validator.v.object({
43
59
  address: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.pipe(_arcblock_validator.v.array((0, _arcblock_validator.vDID)({
44
60
  prefix: true,
@@ -58,8 +74,9 @@ const schema = _arcblock_validator.v.pipe(_arcblock_validator.v.object({
58
74
  opsList: _arcblock_validator.v.pipe(_arcblock_validator.v.array(_arcblock_validator.v.object({
59
75
  typeUrl: _arcblock_validator.v.string(),
60
76
  limit: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.object({
61
- tokensList: _arcblock_validator.v.optional(_arcblock_validator.v.pipe(_arcblock_validator.v.array(tokenLimit), _arcblock_validator.v.maxLength(32)), []),
62
- assetsList: _arcblock_validator.v.optional(_arcblock_validator.v.pipe(_arcblock_validator.v.array(assetLimit), _arcblock_validator.v.maxLength(32)), [])
77
+ tokensList: _arcblock_validator.v.optional(_arcblock_validator.v.pipe(_arcblock_validator.v.array(tokenLimit), _arcblock_validator.v.maxLength(32), _arcblock_validator.v.check((arr) => arr.every((item, idx) => arr.findIndex((other) => (0, _ocap_util.isSameDid)(other.address, item.address)) === idx), "tokensList must not contain duplicate token addresses")), []),
78
+ assetsList: _arcblock_validator.v.optional(_arcblock_validator.v.pipe(_arcblock_validator.v.array(assetLimit), _arcblock_validator.v.maxLength(32)), []),
79
+ unlimited: _arcblock_validator.v.optional(_arcblock_validator.v.nullable(_arcblock_validator.v.boolean()))
63
80
  })), {
64
81
  tokensList: [],
65
82
  assetsList: []
@@ -81,6 +98,19 @@ runner.use(_ocap_tx_pipeline.pipes.VerifyInfo([{
81
98
  message: "Delegation address does not match",
82
99
  fn: (ctx) => {
83
100
  const context = ctx;
101
+ const toInfo = (0, _arcblock_did.toTypeInfo)(context.itx.to);
102
+ if ([
103
+ _ocap_mcrypto.types.RoleType.ROLE_DELEGATION,
104
+ _ocap_mcrypto.types.RoleType.ROLE_STAKE,
105
+ _ocap_mcrypto.types.RoleType.ROLE_TOKEN,
106
+ _ocap_mcrypto.types.RoleType.ROLE_FACTORY,
107
+ _ocap_mcrypto.types.RoleType.ROLE_ROLLUP,
108
+ _ocap_mcrypto.types.RoleType.ROLE_TX,
109
+ _ocap_mcrypto.types.RoleType.ROLE_TETHER,
110
+ _ocap_mcrypto.types.RoleType.ROLE_SWAP,
111
+ _ocap_mcrypto.types.RoleType.ROLE_VC,
112
+ _ocap_mcrypto.types.RoleType.ROLE_ANY
113
+ ].includes(toInfo.role)) return false;
84
114
  return (0, _arcblock_did_util.toDelegateAddress)(context.tx.from, context.itx.to) === context.itx.address;
85
115
  }
86
116
  }, {
@@ -146,19 +176,37 @@ runner.use(async (context, next) => {
146
176
  const merged = (0, lodash_cloneDeep.default)(ops).reduce((acc, x, i) => {
147
177
  const tokens = x.limit?.tokens || [];
148
178
  const assets = x.limit?.assets || [];
179
+ const rawLimitInput = opsList[i]?.limit || {};
149
180
  acc[x.typeUrl] = { limit: {
181
+ ...rawLimitInput.unlimited === true ? { unlimited: true } : {},
150
182
  tokens: tokens.map((y, j) => {
151
183
  const input = (0, _ocap_util_lib_get_list_field.getListField)(opsList[i]?.limit, "tokens")[j] || {};
152
- return Object.assign(y, (0, lodash_pick.default)(input, [
184
+ const basePicked = (0, lodash_pick.default)(input, [
153
185
  "txCount",
154
186
  "txAllowance",
155
187
  "totalAllowance",
156
188
  "validUntil",
157
189
  "rate"
158
- ]), {
190
+ ]);
191
+ const extPicked = {};
192
+ for (const extKey of [
193
+ "maxPerTx",
194
+ "windowLimit",
195
+ "windowSeconds",
196
+ "coSignAllowance",
197
+ "coSignRequired",
198
+ "requirePinnedPayee",
199
+ "notifyBeforeDebit",
200
+ "notifyLeadSeconds"
201
+ ]) if (input[extKey] !== void 0 && input[extKey] !== null && input[extKey] !== "") extPicked[extKey] = input[extKey];
202
+ return Object.assign(y, basePicked, extPicked, {
159
203
  txSent: 0,
160
204
  lastTx: y.rate ? y.rate.anchor : 0,
161
- spentAllowance: "0"
205
+ spentAllowance: "0",
206
+ ...extPicked.windowLimit ? {
207
+ windowSpent: "0",
208
+ windowStart: 0
209
+ } : {}
162
210
  });
163
211
  }),
164
212
  assets: assets.map((y, j) => {
@@ -174,7 +222,7 @@ runner.use(async (context, next) => {
174
222
  })
175
223
  } };
176
224
  return acc;
177
- }, delegationState ? delegationState.ops : {});
225
+ }, delegationState ? (0, lodash_cloneDeep.default)(delegationState.ops) : {});
178
226
  const sender = senderState ? senderState.address : tx.from;
179
227
  const receiver = receiverState ? receiverState.address : itx.to;
180
228
  const tokenAddress = context.config.token.address;
@@ -183,7 +231,7 @@ runner.use(async (context, next) => {
183
231
  ...senderUpdates,
184
232
  address: sender,
185
233
  nonce: tx.nonce,
186
- pk: tx.pk
234
+ pk: tx.delegator ? senderState?.pk : senderState?.pk || tx.pk
187
235
  }, context), context),
188
236
  receiverState ? Promise.resolve(receiverState) : statedb.account.create(receiver, _ocap_state.account.create({
189
237
  address: receiver,