@ocap/tx-protocols 1.30.26 → 1.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/esm/execute.d.mts +11 -2
  2. package/esm/execute.mjs +724 -80
  3. package/esm/gas-security-guard.d.mts +375 -0
  4. package/esm/gas-security-guard.mjs +1103 -0
  5. package/esm/index.d.mts +36 -6
  6. package/esm/index.mjs +4 -2
  7. package/esm/pipes/ensure-cost.mjs +335 -59
  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 +115 -11
  29. package/esm/protocols/governance/return-stake.mjs +44 -12
  30. package/esm/protocols/governance/revoke-ledger.d.mts +34 -0
  31. package/esm/protocols/governance/revoke-ledger.mjs +179 -0
  32. package/esm/protocols/governance/revoke-stake.mjs +25 -5
  33. package/esm/protocols/governance/slash-stake.mjs +72 -25
  34. package/esm/protocols/governance/stake.mjs +63 -13
  35. package/esm/protocols/rollup/claim-reward.mjs +39 -20
  36. package/esm/protocols/rollup/close.mjs +1 -1
  37. package/esm/protocols/rollup/create-block.mjs +8 -7
  38. package/esm/protocols/rollup/create.mjs +17 -6
  39. package/esm/protocols/rollup/join.mjs +3 -3
  40. package/esm/protocols/rollup/leave.mjs +1 -1
  41. package/esm/protocols/rollup/migrate.mjs +7 -4
  42. package/esm/protocols/rollup/pipes/verify-evidence.mjs +12 -4
  43. package/esm/protocols/rollup/update.mjs +6 -1
  44. package/esm/protocols/token/create.mjs +23 -12
  45. package/esm/protocols/token/deposit-v2.d.mts +5 -1
  46. package/esm/protocols/token/deposit-v2.mjs +81 -29
  47. package/esm/protocols/token/withdraw-v2.mjs +33 -16
  48. package/esm/protocols/token-factory/burn.mjs +43 -10
  49. package/esm/protocols/token-factory/create.mjs +23 -14
  50. package/esm/protocols/token-factory/mint.mjs +54 -21
  51. package/esm/protocols/token-factory/pipes/verify-icon.mjs +1 -1
  52. package/esm/protocols/token-factory/update.mjs +16 -6
  53. package/esm/protocols/trade/exchange-v2.d.mts +4 -0
  54. package/esm/protocols/trade/exchange-v2.mjs +78 -22
  55. package/esm/protocols/trade/transfer-v2.mjs +44 -13
  56. package/esm/protocols/trade/transfer-v3.mjs +72 -31
  57. package/esm/util.d.mts +3 -1
  58. package/esm/util.mjs +26 -17
  59. package/lib/execute.cjs +724 -76
  60. package/lib/execute.d.cts +11 -2
  61. package/lib/gas-security-guard.cjs +1142 -0
  62. package/lib/gas-security-guard.d.cts +375 -0
  63. package/lib/index.cjs +124 -1
  64. package/lib/index.d.cts +37 -7
  65. package/lib/pipes/ensure-cost.cjs +334 -58
  66. package/lib/protocols/account/delegate.cjs +64 -16
  67. package/lib/protocols/account/migrate.cjs +235 -35
  68. package/lib/protocols/account/migrate.d.cts +3 -0
  69. package/lib/protocols/account/revoke-delegate.cjs +71 -39
  70. package/lib/protocols/account/revoke-delegate.d.cts +3 -3
  71. package/lib/protocols/asset/acquire-v2.cjs +28 -11
  72. package/lib/protocols/asset/acquire-v3.cjs +77 -20
  73. package/lib/protocols/asset/calls/transfer-token.cjs +3 -2
  74. package/lib/protocols/asset/calls/transfer.cjs +1 -0
  75. package/lib/protocols/asset/consume.cjs +11 -3
  76. package/lib/protocols/asset/create.cjs +19 -6
  77. package/lib/protocols/asset/mint.cjs +23 -1
  78. package/lib/protocols/asset/pipes/exec-mint-hook.cjs +117 -1
  79. package/lib/protocols/asset/pipes/exec-mint-hook.d.cts +21 -1
  80. package/lib/protocols/asset/pipes/extract-factory-tokens.cjs +14 -9
  81. package/lib/protocols/asset/pipes/verify-itx-address.cjs +9 -0
  82. package/lib/protocols/asset/pipes/verify-itx-assets.cjs +21 -5
  83. package/lib/protocols/asset/update.cjs +131 -12
  84. package/lib/protocols/asset/update.d.cts +13 -2
  85. package/lib/protocols/factory/create.cjs +14 -6
  86. package/lib/protocols/governance/claim-stake.cjs +115 -10
  87. package/lib/protocols/governance/claim-stake.d.cts +1 -1
  88. package/lib/protocols/governance/return-stake.cjs +44 -11
  89. package/lib/protocols/governance/return-stake.d.cts +1 -1
  90. package/lib/protocols/governance/revoke-ledger.cjs +184 -0
  91. package/lib/protocols/governance/revoke-ledger.d.cts +34 -0
  92. package/lib/protocols/governance/revoke-stake.cjs +25 -5
  93. package/lib/protocols/governance/revoke-stake.d.cts +1 -1
  94. package/lib/protocols/governance/slash-stake.cjs +72 -24
  95. package/lib/protocols/governance/slash-stake.d.cts +1 -1
  96. package/lib/protocols/governance/stake.cjs +65 -14
  97. package/lib/protocols/rollup/claim-reward.cjs +39 -20
  98. package/lib/protocols/rollup/close.cjs +1 -1
  99. package/lib/protocols/rollup/create-block.cjs +9 -8
  100. package/lib/protocols/rollup/create-block.d.cts +1 -1
  101. package/lib/protocols/rollup/create.cjs +18 -7
  102. package/lib/protocols/rollup/join.cjs +3 -3
  103. package/lib/protocols/rollup/leave.cjs +1 -1
  104. package/lib/protocols/rollup/migrate.cjs +7 -4
  105. package/lib/protocols/rollup/pipes/verify-evidence.cjs +11 -3
  106. package/lib/protocols/rollup/update.cjs +6 -1
  107. package/lib/protocols/token/create.cjs +24 -13
  108. package/lib/protocols/token/deposit-v2.cjs +80 -28
  109. package/lib/protocols/token/deposit-v2.d.cts +5 -1
  110. package/lib/protocols/token/withdraw-v2.cjs +32 -15
  111. package/lib/protocols/token-factory/burn.cjs +42 -9
  112. package/lib/protocols/token-factory/create.cjs +24 -15
  113. package/lib/protocols/token-factory/mint.cjs +53 -20
  114. package/lib/protocols/token-factory/pipes/verify-icon.cjs +1 -1
  115. package/lib/protocols/token-factory/update.cjs +16 -6
  116. package/lib/protocols/trade/exchange-v2.cjs +76 -20
  117. package/lib/protocols/trade/exchange-v2.d.cts +4 -0
  118. package/lib/protocols/trade/transfer-v2.cjs +45 -14
  119. package/lib/protocols/trade/transfer-v3.cjs +72 -30
  120. package/lib/util.cjs +26 -17
  121. package/lib/util.d.cts +4 -2
  122. package/package.json +16 -16
@@ -1,13 +1,15 @@
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');
4
- let _ocap_state = require("@ocap/state");
5
- let _ocap_util = require("@ocap/util");
6
- let _ocap_util_lib_error = require("@ocap/util/lib/error");
7
5
  let _arcblock_did = require("@arcblock/did");
8
6
  let _arcblock_did_util = require("@arcblock/did-util");
9
7
  let _arcblock_jwt = require("@arcblock/jwt");
10
8
  _arcblock_jwt = require_rolldown_runtime.__toESM(_arcblock_jwt);
9
+ let _ocap_state = require("@ocap/state");
10
+ let _ocap_util = require("@ocap/util");
11
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
12
+ let _ocap_util_lib_get_related_addr = require("@ocap/util/lib/get-related-addr");
11
13
  let lodash_noop = require("lodash/noop");
12
14
  lodash_noop = require_rolldown_runtime.__toESM(lodash_noop);
13
15
  let debug = require("debug");
@@ -16,34 +18,241 @@ 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 canChargeSenderDirectly = Boolean(senderState);
36
+ const txSize = context._baseTxSize ?? context.txSize;
37
+ const nowMs = txTime ? +new Date(txTime) : Date.now();
24
38
  const { token, pk } = extra.gasStakeHeaders || {};
39
+ const rawGasPass = extra.gasPass || extra.txExtra?.gasPass;
25
40
  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}`);
41
+ let isThirdPartySponsor = false;
42
+ let enforceSponsor3DEligibility = false;
43
+ let isPaymasterDirectCharge = false;
44
+ let sponsorAccountState = null;
45
+ const resolveSignerSelfGasStake = async () => {
46
+ const officialTok = config.token?.address || "";
47
+ if (!officialTok) return {
48
+ hasSelfStake: false,
49
+ owner: "",
50
+ stakeId: "",
51
+ state: null,
52
+ valid: false
53
+ };
54
+ const candidates = Array.from(new Set([tx?.from, tx?.delegator].filter(Boolean)));
55
+ for (const candidate of candidates) {
56
+ const stakeId = (0, _arcblock_did_util.toStakeAddress)(candidate, candidate);
57
+ const selfStake = await statedb.stake?.get?.(stakeId, context);
58
+ if (new _ocap_util.BN(selfStake?.tokens?.[officialTok] || 0).gt(ZERO)) return {
59
+ hasSelfStake: true,
60
+ owner: candidate,
61
+ stakeId,
62
+ state: selfStake || null,
63
+ valid: require_util.isGasStakeValid(selfStake, config)
64
+ };
65
+ }
66
+ return {
67
+ hasSelfStake: false,
68
+ owner: "",
69
+ stakeId: "",
70
+ state: null,
71
+ valid: false
72
+ };
73
+ };
74
+ let isThirdPartyGasPass = false;
75
+ if ((!isFailedTxGasCharge || !canChargeSenderDirectly) && rawGasPass) {
76
+ const passStakeState = rawGasPass.stakeId ? await statedb.stake?.get?.(rawGasPass.stakeId, context) : null;
77
+ const passResult = require_gas_security_guard.verifyAndConsumeUnlinkableGasPass({
78
+ gasPass: rawGasPass,
79
+ stakeState: passStakeState,
80
+ txHash,
81
+ nowMs,
82
+ config,
83
+ statedb
84
+ });
85
+ if (!passResult.valid) {
86
+ const passErr = new _ocap_util_lib_error.CustomError(passResult.reason || "INVALID_GAS_PASS", `Invalid unlinkable gas pass: ${passResult.reason}`);
87
+ passErr._unauthenticatedExtraFailure = true;
88
+ return next(passErr);
89
+ }
90
+ const passOwner = passStakeState?.sender || rawGasPass.stakeId;
91
+ isThirdPartyGasPass = Boolean(passOwner && (!tx?.from || !(0, _ocap_util.isSameDid)(passOwner, tx.from)) && (!tx?.delegator || !(0, _ocap_util.isSameDid)(passOwner, tx.delegator)));
92
+ const selfStakeInfo = isThirdPartyGasPass ? await resolveSignerSelfGasStake() : null;
93
+ const selfStakeEligible = Boolean(selfStakeInfo?.valid) && require_gas_security_guard.evaluateStakeForGasEligibility({
94
+ txType,
95
+ txSize,
96
+ gasEstimate,
97
+ isFailedTxGasCharge: isFailedTxGasCharge && canChargeSenderDirectly,
98
+ isThirdPartySponsor: false,
99
+ enforceSponsor3DEligibility: false,
100
+ config
101
+ }).eligible;
102
+ if (selfStakeInfo?.valid && selfStakeEligible) {
103
+ gasStake.owner = selfStakeInfo.owner;
104
+ gasStake.stakeId = selfStakeInfo.stakeId;
105
+ gasStake.state = selfStakeInfo.state;
106
+ isThirdPartyGasPass = false;
107
+ } else {
108
+ gasStake.owner = passOwner;
109
+ gasStake.stakeId = passResult.stakeId;
110
+ gasStake.state = passStakeState;
111
+ }
112
+ } else if ((!isFailedTxGasCharge || !canChargeSenderDirectly) && token && pk) {
113
+ const decoded = _arcblock_jwt.decode(token) || {};
114
+ const sponsorAddress = (0, _arcblock_did.toAddress)(decoded.iss || "");
115
+ if (!sponsorAddress || !(0, _arcblock_did.isFromPublicKey)(sponsorAddress, pk)) {
116
+ const hdrErr = new _ocap_util_lib_error.CustomError("INVALID_GAS_STAKE_HEADERS", "Gas stake JWT issuer does not match signer public key");
117
+ hdrErr._unauthenticatedExtraFailure = true;
118
+ return next(hdrErr);
119
+ }
120
+ if (await _arcblock_jwt.verify(token, pk, {
121
+ enforceTimestamp: !txTime,
122
+ tolerance: 5
123
+ })) {
124
+ const toleranceSec = 5;
125
+ const nowSec = txTime ? Math.floor(+new Date(txTime) / 1e3) : Math.floor(Date.now() / 1e3);
126
+ const expNum = decoded?.exp != null && decoded.exp !== "" ? Number(decoded.exp) : NaN;
127
+ const expValid = Number.isFinite(expNum) && expNum > 0 && expNum + toleranceSec >= nowSec;
128
+ const nbfNum = decoded?.nbf != null && decoded.nbf !== "" ? Number(decoded.nbf) : NaN;
129
+ const nbfValid = decoded?.nbf == null || decoded.nbf === "" || Number.isFinite(nbfNum) && nbfNum - toleranceSec <= nowSec;
130
+ const iatNum = decoded?.iat != null && decoded.iat !== "" ? Number(decoded.iat) : NaN;
131
+ const iatValid = decoded?.iat == null || decoded.iat === "" || Number.isFinite(iatNum) && iatNum - toleranceSec <= nowSec;
132
+ const txHashes = (decoded.txHash || "").split(",").map((x) => x.trim()).filter(Boolean);
133
+ if (expValid && nbfValid && iatValid && txHashes.includes(txHash)) {
134
+ const sponsorState = await statedb.account?.get?.(sponsorAddress, {
135
+ ...context,
136
+ traceMigration: false
137
+ });
138
+ if (sponsorState?.pk && !isMatchingAccountPublicKey(sponsorState.pk, pk)) {
139
+ 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");
140
+ pkErr._unauthenticatedExtraFailure = true;
141
+ return next(pkErr);
142
+ }
143
+ const isSponsorMigrated = Array.isArray(sponsorState?.migratedTo) && sponsorState.migratedTo.length > 0;
144
+ const sponsorAddresses = (0, _ocap_util_lib_get_related_addr.getRelatedAddresses)(sponsorState || { address: sponsorAddress });
145
+ const checkBlocked = async (checker, addr) => {
146
+ if (typeof checker?.isBlocked !== "function") return false;
147
+ if (await Promise.resolve(checker.isBlocked(addr))) return true;
148
+ return Boolean(await Promise.resolve(checker.isBlocked([addr])));
149
+ };
150
+ let isSponsorBlocked = false;
151
+ for (const addr of sponsorAddresses) if (await checkBlocked(context.filter, addr) || await checkBlocked(statedb.blacklist, addr)) {
152
+ isSponsorBlocked = true;
153
+ break;
154
+ }
155
+ if (!isSponsorMigrated && !isSponsorBlocked) {
156
+ const sponsorStakeId = (0, _arcblock_did_util.toStakeAddress)(sponsorAddress, sponsorAddress);
157
+ const isDirectMode = decoded.mode === "paymaster" || decoded.chargeSponsorBalance === true;
158
+ const sponsorStakeState = !isDirectMode ? await statedb.stake?.get?.(sponsorStakeId, context) : null;
159
+ const officialTok = config.token?.address || "";
160
+ 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);
161
+ const paymasterCheck = require_gas_security_guard.verifyPaymasterConstraints({
162
+ decoded,
163
+ tx,
164
+ itx: context.itx,
165
+ txType,
166
+ totalGas: totalGas ?? ZERO
167
+ });
168
+ if (!paymasterCheck.valid) {
169
+ const pmErr = new _ocap_util_lib_error.CustomError(paymasterCheck.reason || "PAYMASTER_VIOLATION", `Paymaster sponsorship constraint violated: ${paymasterCheck.reason}`);
170
+ pmErr._strikeRecorded = true;
171
+ pmErr._unauthenticatedExtraFailure = true;
172
+ return next(pmErr);
173
+ }
174
+ if (paymasterCheck.isPaymasterDirectCharge) {
175
+ const txTargets = require_gas_security_guard.extractTransactionTargets(tx, context.itx, txType);
176
+ if ([
177
+ tx?.from,
178
+ tx?.delegator,
179
+ context.gasVault,
180
+ context.feeVault,
181
+ config.vaults?.txFee,
182
+ ...Array.isArray(config.vaults?.txGas) ? config.vaults.txGas : [],
183
+ ...Array.isArray(config.vaults?.txFees) ? config.vaults.txFees : [],
184
+ ...txTargets
185
+ ].filter(Boolean).some((candidate) => (0, _ocap_util.isSameDid)(sponsorAddress, candidate) || sponsorAddress === candidate)) {
186
+ const aliasErr = new _ocap_util_lib_error.CustomError("PAYMASTER_SPONSOR_ALIAS_FORBIDDEN", "Paymaster direct-charge sponsor cannot alias transaction sender, delegator, target, or vault");
187
+ aliasErr._unauthenticatedExtraFailure = true;
188
+ return next(aliasErr);
189
+ }
190
+ }
191
+ const selfStakeInfo = await resolveSignerSelfGasStake();
192
+ const selfStakeEligible = Boolean(selfStakeInfo.valid) && require_gas_security_guard.evaluateStakeForGasEligibility({
193
+ txType,
194
+ txSize,
195
+ gasEstimate,
196
+ isFailedTxGasCharge: isFailedTxGasCharge && canChargeSenderDirectly,
197
+ isThirdPartySponsor: false,
198
+ enforceSponsor3DEligibility: false,
199
+ config
200
+ }).eligible;
201
+ if (selfStakeInfo.valid && selfStakeEligible) {
202
+ gasStake.owner = selfStakeInfo.owner;
203
+ gasStake.stakeId = selfStakeInfo.stakeId;
204
+ gasStake.state = selfStakeInfo.state;
205
+ } else if (!sponsorIsBacked && selfStakeInfo.hasSelfStake) {} else {
206
+ isThirdPartySponsor = true;
207
+ enforceSponsor3DEligibility = decoded.enforce3DEligibility === true || (config.transaction?.txGas)?.enforceSponsor3DEligibility === true;
208
+ isPaymasterDirectCharge = paymasterCheck.isPaymasterDirectCharge;
209
+ sponsorAccountState = sponsorState || null;
210
+ if (isPaymasterDirectCharge && sponsorAccountState) context.sponsorState = sponsorAccountState;
211
+ gasStake.owner = sponsorAddress;
212
+ gasStake.stakeId = sponsorStakeId;
213
+ if (sponsorStakeState) gasStake.state = sponsorStakeState;
214
+ }
215
+ }
216
+ } else console.warn(`Invalid gas payer header for: ${txHash}`);
217
+ }
35
218
  }
36
219
  if (!gasStake.owner && tx?.from) {
37
220
  const owner = tx.from;
38
221
  gasStake.owner = owner;
39
222
  gasStake.stakeId = (0, _arcblock_did_util.toStakeAddress)(owner, owner);
40
223
  }
41
- gasStake.state = await statedb.stake.get(gasStake.stakeId, context);
42
- gasStake.valid = require_util.isGasStakeValid(gasStake.state, config);
224
+ if (!gasStake.state && gasStake.stakeId) gasStake.state = await statedb.stake.get(gasStake.stakeId, context);
225
+ const eligibility = require_gas_security_guard.evaluateStakeForGasEligibility({
226
+ txType,
227
+ txSize,
228
+ gasEstimate,
229
+ isFailedTxGasCharge: isFailedTxGasCharge && canChargeSenderDirectly,
230
+ isThirdPartySponsor,
231
+ enforceSponsor3DEligibility,
232
+ config
233
+ });
234
+ const baseStakeValid = !isPaymasterDirectCharge && require_util.isGasStakeValid(gasStake.state, config) && eligibility.eligible;
235
+ const effectiveTotalGas = totalGas ?? ZERO;
236
+ const warnActor = tx?.delegator || tx?.from || "";
237
+ if (!isFailedTxGasCharge && warnActor && require_gas_security_guard.resolveGasSecurityConfig(config).enabled) {
238
+ const status = require_gas_security_guard.getActorSecurityStatus({
239
+ actor: warnActor,
240
+ config,
241
+ statedb,
242
+ nowMs
243
+ });
244
+ if (status.warning) {
245
+ context.securityWarning = status.warning;
246
+ if (txHash) require_gas_security_guard.setTxSecurityWarningForHash(txHash, status.warning, statedb);
247
+ }
248
+ }
249
+ gasStake.valid = baseStakeValid;
43
250
  context.gasStake = gasStake;
251
+ context.gasEligibility = eligibility;
44
252
  debug$1("gasStake", gasStake, context.extra);
45
253
  const changes = {};
46
254
  let txCost = new _ocap_util.BN(0);
255
+ let sponsorGasCost = new _ocap_util.BN(0);
47
256
  const txFeeMap = config.transaction.txFee;
48
257
  const txFee = txType ? txFeeMap[txType] : void 0;
49
258
  if (!gasOnly && txFee) {
@@ -55,76 +264,143 @@ const ZERO = new _ocap_util.BN(0);
55
264
  };
56
265
  context.feeVaultChange = changes.fee;
57
266
  }
58
- const totalGasBN = totalGas ?? ZERO;
267
+ const totalGasBN = effectiveTotalGas;
59
268
  if (!gasStake.valid && totalGasBN.gt(ZERO)) {
60
- txCost = txCost.add(totalGasBN);
61
269
  changes.gas = {
62
270
  address: config.token.address,
63
271
  value: totalGasBN.toString(10)
64
272
  };
65
273
  context.gasVaultChange = changes.gas;
274
+ if (isPaymasterDirectCharge && (!isFailedTxGasCharge || !canChargeSenderDirectly)) sponsorGasCost = totalGasBN;
275
+ else txCost = txCost.add(totalGasBN);
66
276
  }
67
277
  if (changes.fee) if (config.vaults.txFees?.length) {
68
278
  const feeIndex = (0, _ocap_util.hexToNumber)(txHash.slice(-8)) % config.vaults.txFees.length;
69
279
  context.feeVault = config.vaults.txFees[feeIndex];
70
280
  } else context.feeVault = config.vaults.txFee;
281
+ if (changes.gas && !context.gasVault) {
282
+ if (config.vaults.txGas?.length) {
283
+ const gasIndex = (0, _ocap_util.hexToNumber)(txHash.slice(-8)) % config.vaults.txGas.length;
284
+ context.gasVault = config.vaults.txGas[gasIndex];
285
+ } else if (config.vaults.txFee) context.gasVault = config.vaults.txFee;
286
+ }
287
+ if (sponsorGasCost.gt(ZERO)) {
288
+ const sponsorBalance = new _ocap_util.BN(sponsorAccountState?.tokens?.[config.token.address] || 0);
289
+ if (!sponsorAccountState) {
290
+ const noSponsorErr = new _ocap_util_lib_error.CustomError("INVALID_GAS_PAYER", `Paymaster sponsor ${gasStake.owner} does not exist on chain`);
291
+ noSponsorErr._unauthenticatedExtraFailure = true;
292
+ return next(noSponsorErr);
293
+ }
294
+ if (sponsorBalance.lt(sponsorGasCost)) {
295
+ const sponsorFundErr = new _ocap_util_lib_error.CustomError("INSUFFICIENT_FUND", `Insufficient fund in paymaster sponsor ${sponsorAccountState.address} to pay gas`);
296
+ sponsorFundErr._unauthenticatedExtraFailure = true;
297
+ return next(sponsorFundErr);
298
+ }
299
+ }
71
300
  let isCostCharged = false;
72
- if (txCost.gt(ZERO)) {
301
+ if (txCost.gt(ZERO) || sponsorGasCost.gt(ZERO)) {
73
302
  const expected = new _ocap_util.BN(gasEstimate?.payment || 0).add(txCost);
74
303
  const actual = new _ocap_util.BN(senderState?.tokens?.[config.token.address] || 0);
75
- if (senderState && actual.gte(expected)) {
304
+ if (txCost.eq(ZERO) || Boolean(senderState) && actual.gte(expected)) {
76
305
  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
- };
306
+ if (txCost.gt(ZERO) && senderState) {
307
+ context.senderUpdates = require_util.applyTokenUpdates([{
308
+ address: config.token.address,
309
+ value: txCost.toString(10)
310
+ }], senderState, "sub");
311
+ context.senderChange = {
312
+ address: senderState.address,
313
+ token: config.token.address,
314
+ delta: `-${txCost.toString(10)}`
315
+ };
316
+ } else {
317
+ context.senderUpdates = {};
318
+ context.senderChange = null;
319
+ }
86
320
  debug$1({
87
321
  changes,
88
322
  senderUpdates: context.senderUpdates
89
323
  });
90
324
  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;
325
+ if (context.gasPaid) return;
326
+ if (sponsorGasCost.gt(ZERO) && sponsorAccountState && changes.gas) {
327
+ const latestSponsor = await statedb.account.get(sponsorAccountState.address, context) || sponsorAccountState;
328
+ const tokenDelta = require_util.applyTokenUpdates([changes.gas], latestSponsor, "sub");
329
+ let updatedSponsorPayload;
330
+ try {
331
+ updatedSponsorPayload = _ocap_state.account.update(latestSponsor, tokenDelta, context);
332
+ } catch {
333
+ updatedSponsorPayload = {
334
+ ...latestSponsor,
335
+ ...tokenDelta
336
+ };
337
+ }
338
+ const nextSponsorState = await statedb.account.update(latestSponsor.address, updatedSponsorPayload, context);
339
+ if (nextSponsorState && typeof nextSponsorState === "object") nextSponsorState._retrievedAt = Date.now() + 1;
340
+ context.sponsorState = nextSponsorState;
341
+ }
342
+ let feeVaultState = null;
343
+ let gasVaultState = null;
344
+ if (changes.fee && changes.gas && context.feeVault && context.gasVault && context.feeVault === context.gasVault) {
345
+ const sharedVaultState = await statedb.account.get(context.feeVault, context);
346
+ feeVaultState = sharedVaultState;
347
+ gasVaultState = sharedVaultState;
348
+ if (sharedVaultState) {
349
+ const combinedState = await statedb.account.update(sharedVaultState.address, _ocap_state.account.update(sharedVaultState, require_util.applyTokenUpdates([changes.fee, changes.gas], sharedVaultState, "add"), context), context);
350
+ context.feeVaultState = combinedState;
351
+ context.gasVaultState = combinedState;
352
+ }
353
+ } else {
354
+ [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]);
355
+ 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]);
356
+ if (newFeeVaultState) context.feeVaultState = newFeeVaultState;
357
+ if (newGasVaultState) context.gasVaultState = newGasVaultState;
358
+ }
95
359
  context.updatedAccounts = context.updatedAccounts || [];
96
360
  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
- });
361
+ if (!Boolean(attachSenderChanges && senderState && (0, _ocap_util.isSameDid)(senderState.address, feeVaultState.address))) {
362
+ context.updatedAccounts.push({
363
+ address: feeVaultState.address,
364
+ token: config.token.address,
365
+ delta: changes.fee.value,
366
+ action: "fee"
367
+ });
368
+ if (attachSenderChanges && senderState) context.updatedAccounts.push({
369
+ address: senderState.address,
370
+ token: config.token.address,
371
+ delta: `-${changes.fee.value}`,
372
+ action: "fee"
373
+ });
374
+ }
109
375
  }
110
376
  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
- });
377
+ const gasPayerAddress = sponsorGasCost.gt(ZERO) && sponsorAccountState ? sponsorAccountState.address : attachSenderChanges && senderState ? senderState.address : "";
378
+ if (!gasPayerAddress || !(0, _ocap_util.isSameDid)(gasPayerAddress, gasVaultState.address)) {
379
+ context.updatedAccounts.push({
380
+ address: gasVaultState.address,
381
+ token: config.token.address,
382
+ delta: changes.gas.value,
383
+ action: "gas"
384
+ });
385
+ if (gasPayerAddress) context.updatedAccounts.push({
386
+ address: gasPayerAddress,
387
+ token: config.token.address,
388
+ delta: `-${changes.gas.value}`,
389
+ action: "gas"
390
+ });
391
+ }
123
392
  }
124
393
  context.gasPaid = true;
125
394
  };
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}`));
395
+ } else if (!senderState) {
396
+ const noSenderErr = new _ocap_util_lib_error.CustomError("INVALID_GAS_PAYER", `Gas payer ${tx.from} does not exist on chain`);
397
+ if (isThirdPartySponsor || Boolean(rawGasPass) || Boolean(context.extra?.txExtra || context.extra?.coSignature || context.extra?.gasStakeHeaders)) noSenderErr._unauthenticatedExtraFailure = true;
398
+ return next(noSenderErr);
399
+ } else if (throwOnInsufficientFund) {
400
+ 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}`);
401
+ if (isThirdPartySponsor || Boolean(rawGasPass) || Boolean(context.extra?.txExtra || context.extra?.coSignature || context.extra?.gasStakeHeaders)) senderFundErr._unauthenticatedExtraFailure = true;
402
+ return next(senderFundErr);
403
+ }
128
404
  }
129
405
  if (!isCostCharged) {
130
406
  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,