@tetherto/wdk-wallet-evm-erc-4337 1.0.0-beta.2 → 1.0.0-beta.21
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.
- package/AGENTS.md +50 -0
- package/LICENSE +176 -0
- package/README.md +93 -680
- package/hardhat.config.js +20 -0
- package/index.js +31 -1
- package/package.json +35 -13
- package/src/errors.js +35 -0
- package/src/wallet-account-evm-erc-4337.js +394 -88
- package/src/wallet-account-read-only-evm-erc-4337.js +826 -118
- package/src/wallet-manager-evm-erc-4337.js +35 -22
- package/types/index.d.ts +26 -1
- package/types/src/errors.d.ts +14 -0
- package/types/src/wallet-account-evm-erc-4337.d.ts +112 -21
- package/types/src/wallet-account-read-only-evm-erc-4337.d.ts +488 -40
- package/types/src/wallet-manager-evm-erc-4337.d.ts +11 -8
|
@@ -14,43 +14,74 @@
|
|
|
14
14
|
|
|
15
15
|
'use strict'
|
|
16
16
|
|
|
17
|
-
import { Contract } from 'ethers'
|
|
17
|
+
import { Contract, hexlify, keccak256, randomBytes, toUtf8Bytes } from 'ethers'
|
|
18
|
+
|
|
19
|
+
import { MaximumFeeExceededError, ProviderRequiredError, TransactionError, TransactionErrorReason, UnsupportedOperationError, ValueError } from '@tetherto/wdk-wallet'
|
|
18
20
|
|
|
19
21
|
import { WalletAccountEvm } from '@tetherto/wdk-wallet-evm'
|
|
20
22
|
|
|
21
|
-
import {
|
|
23
|
+
import { ENTRYPOINT_V7, calculateUserOperationMaxGasCost, fetchAccountNonce } from 'abstractionkit'
|
|
24
|
+
|
|
25
|
+
import WalletAccountReadOnlyEvmErc4337, { FEE_TOLERANCE_COEFFICIENT } from './wallet-account-read-only-evm-erc-4337.js'
|
|
22
26
|
|
|
23
|
-
|
|
27
|
+
/** @typedef {import('abstractionkit').UserOperationV7} UserOperationV7 */
|
|
28
|
+
/** @typedef {import('abstractionkit').SafeAccountV0_3_0} SafeAccountV0_3_0 */
|
|
24
29
|
|
|
25
|
-
/**
|
|
30
|
+
/**
|
|
31
|
+
* @internal
|
|
32
|
+
* @typedef {Object} TransactionQuote
|
|
33
|
+
* @property {bigint} fee - The estimated fee with tolerance buffer applied.
|
|
34
|
+
* @property {number} createdAt - The timestamp when the quote was created.
|
|
35
|
+
* @property {UserOperationV7} [userOp] - The built UserOperation, reusable by sendTransaction.
|
|
36
|
+
* @property {SafeAccountV0_3_0} [smartAccount] - The smart account instance used to build the UserOperation.
|
|
37
|
+
* @property {bigint} [chainId] - The chain id captured at quote time, used to sign the cached UserOperation for the right network.
|
|
38
|
+
*/
|
|
26
39
|
|
|
27
40
|
/** @typedef {import('@tetherto/wdk-wallet').IWalletAccount} IWalletAccount */
|
|
28
41
|
|
|
29
42
|
/** @typedef {import('@tetherto/wdk-wallet-evm').KeyPair} KeyPair */
|
|
30
43
|
|
|
31
|
-
/** @typedef {import('@tetherto/wdk-wallet-evm').EvmTransaction} EvmTransaction */
|
|
32
44
|
/** @typedef {import('@tetherto/wdk-wallet-evm').TransactionResult} TransactionResult */
|
|
33
|
-
/** @typedef {import('@tetherto/wdk-wallet-evm').TransferOptions} TransferOptions */
|
|
34
45
|
/** @typedef {import('@tetherto/wdk-wallet-evm').TransferResult} TransferResult */
|
|
35
46
|
/** @typedef {import('@tetherto/wdk-wallet-evm').ApproveOptions} ApproveOptions */
|
|
36
47
|
|
|
48
|
+
/** @typedef {import('./wallet-account-read-only-evm-erc-4337.js').EvmErc4337Transaction} EvmErc4337Transaction */
|
|
49
|
+
/** @typedef {import('./wallet-account-read-only-evm-erc-4337.js').EvmErc4337GasOverrides} EvmErc4337GasOverrides */
|
|
50
|
+
/** @typedef {import('./wallet-account-read-only-evm-erc-4337.js').EvmErc4337TransferOptions} EvmErc4337TransferOptions */
|
|
37
51
|
/** @typedef {import('./wallet-account-read-only-evm-erc-4337.js').EvmErc4337WalletConfig} EvmErc4337WalletConfig */
|
|
52
|
+
/** @typedef {import('./wallet-account-read-only-evm-erc-4337.js').EvmErc4337WalletPaymasterTokenConfig} EvmErc4337WalletPaymasterTokenConfig */
|
|
53
|
+
/** @typedef {import('./wallet-account-read-only-evm-erc-4337.js').EvmErc4337WalletSponsorshipPolicyConfig} EvmErc4337WalletSponsorshipPolicyConfig */
|
|
54
|
+
/** @typedef {import('./wallet-account-read-only-evm-erc-4337.js').TypedData} TypedData */
|
|
55
|
+
/** @typedef {import('./wallet-account-read-only-evm-erc-4337.js').EvmErc4337WalletNativeCoinsConfig} EvmErc4337WalletNativeCoinsConfig */
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The options of a token approval, extended with the optional UserOperationV7 gas overrides.
|
|
59
|
+
*
|
|
60
|
+
* @typedef {ApproveOptions & EvmErc4337GasOverrides} EvmErc4337ApproveOptions
|
|
61
|
+
*/
|
|
62
|
+
|
|
63
|
+
const QUOTE_MAX_AGE_MS = 2 * 60 * 1_000
|
|
38
64
|
|
|
39
|
-
const
|
|
65
|
+
const NONCE_KEY_SHIFT = 64n
|
|
66
|
+
|
|
67
|
+
const MAX_UINT192 = (1n << 192n) - 1n
|
|
40
68
|
|
|
41
69
|
const USDT_MAINNET_ADDRESS = '0xdAC17F958D2ee523a2206206994597C13D831ec7'
|
|
42
70
|
|
|
43
|
-
/** @implements {IWalletAccount} */
|
|
71
|
+
/** @implements {IWalletAccount<UserOperationV7>} */
|
|
44
72
|
export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc4337 {
|
|
45
73
|
/**
|
|
46
74
|
* Creates a new evm [erc-4337](https://www.erc4337.io/docs) wallet account.
|
|
47
75
|
*
|
|
48
|
-
* @param {string | Uint8Array} seed -
|
|
76
|
+
* @param {string | Uint8Array} seed - A [BIP-39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) mnemonic seed phrase, or a raw BIP-32 master seed (16-64 bytes).
|
|
49
77
|
* @param {string} path - The BIP-44 derivation path (e.g. "0'/0/0").
|
|
50
78
|
* @param {EvmErc4337WalletConfig} config - The configuration object.
|
|
51
79
|
*/
|
|
52
80
|
constructor (seed, path, config) {
|
|
53
|
-
|
|
81
|
+
// Owner EOA only needs keys/address for 4337; strip `provider` so
|
|
82
|
+
// wdk-wallet-evm does not open a second JsonRpcProvider.
|
|
83
|
+
const { provider: _provider, ...ownerConfig } = config
|
|
84
|
+
const ownerAccount = new WalletAccountEvm(seed, path, ownerConfig)
|
|
54
85
|
|
|
55
86
|
super(ownerAccount._address, config)
|
|
56
87
|
|
|
@@ -64,6 +95,27 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
|
|
|
64
95
|
|
|
65
96
|
/** @private */
|
|
66
97
|
this._ownerAccount = ownerAccount
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Cached quotes from fee estimations, keyed by serialized transaction.
|
|
101
|
+
*
|
|
102
|
+
* @private
|
|
103
|
+
* @type {Map<string, TransactionQuote>}
|
|
104
|
+
*/
|
|
105
|
+
this._quoteCache = new Map()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Creates a read-only account for a safe whose address is already known. Not supported on the writable
|
|
110
|
+
* account: a safe address cannot produce a signer. Use {@link WalletAccountReadOnlyEvmErc4337.fromSafeAddress}.
|
|
111
|
+
*
|
|
112
|
+
* @param {string} safeAddress - The safe's evm address.
|
|
113
|
+
* @param {Omit<EvmErc4337WalletConfig, 'transferMaxFee' | 'transactionMaxFee'>} config - The configuration object.
|
|
114
|
+
* @throws {UnsupportedOperationError} Always; a writable account cannot be created from a safe address.
|
|
115
|
+
* @returns {never}
|
|
116
|
+
*/
|
|
117
|
+
static fromSafeAddress (safeAddress, config) {
|
|
118
|
+
throw new UnsupportedOperationError('fromSafeAddress(safeAddress, config)')
|
|
67
119
|
}
|
|
68
120
|
|
|
69
121
|
/**
|
|
@@ -87,6 +139,10 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
|
|
|
87
139
|
/**
|
|
88
140
|
* The account's key pair.
|
|
89
141
|
*
|
|
142
|
+
* The uint8 arrays are bound to the wallet account, so any external change will reflect to the internal representation. For this reason,
|
|
143
|
+
* it's strongly recommended to treat the key pair as a read-only view of the keys. While it's still technically possible to alter their
|
|
144
|
+
* content, client code should never do so.
|
|
145
|
+
*
|
|
90
146
|
* @type {KeyPair}
|
|
91
147
|
*/
|
|
92
148
|
get keyPair () {
|
|
@@ -104,26 +160,62 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
|
|
|
104
160
|
}
|
|
105
161
|
|
|
106
162
|
/**
|
|
107
|
-
*
|
|
163
|
+
* Signs typed data according to EIP-712.
|
|
164
|
+
*
|
|
165
|
+
* @param {TypedData} typedData - The typed data to sign.
|
|
166
|
+
* @returns {Promise<string>} The typed data signature.
|
|
167
|
+
*/
|
|
168
|
+
async signTypedData ({ domain, types, message }) {
|
|
169
|
+
return await this._ownerAccount.signTypedData({ domain, types, message })
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Signs a user operation built from the given transaction.
|
|
108
174
|
*
|
|
109
|
-
*
|
|
110
|
-
*
|
|
111
|
-
* @
|
|
175
|
+
* If the transaction is not sponsored, it also estimates the transaction's costs and checks them against the transaction max. fee option.
|
|
176
|
+
*
|
|
177
|
+
* @param {EvmErc4337Transaction} tx - The transaction to include in the user operation.
|
|
178
|
+
* @param {Partial<EvmErc4337WalletPaymasterTokenConfig | EvmErc4337WalletSponsorshipPolicyConfig | EvmErc4337WalletNativeCoinsConfig>} [config] - If set, overrides the given configuration options.
|
|
179
|
+
* @returns {Promise<UserOperationV7>} The signed user operation.
|
|
180
|
+
* @throws {ConfigurationError} If the override `config` is invalid or has missing required fields.
|
|
181
|
+
* @throws {ConfigurationError} If, in token mode, the configured `paymasterAddress` does not match the paymaster address returned by the paymaster RPC. This guards against the auto-generated ERC-20 approval targeting an unexpected paymaster contract.
|
|
182
|
+
* @throws {MaximumFeeExceededError} If the transaction is not sponsored, and the transaction's cost surpasses the transaction max. fee option.
|
|
183
|
+
* @throws {TransactionError} If the paymaster reports AA50 (the account cannot repay the paymaster).
|
|
112
184
|
*/
|
|
113
|
-
async
|
|
114
|
-
|
|
185
|
+
async signTransaction (tx, config) {
|
|
186
|
+
const mergedConfig = { ...this._config, ...config }
|
|
187
|
+
|
|
188
|
+
if (config) {
|
|
189
|
+
this._validateConfig(mergedConfig)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const prepared = await this._prepareForSend(tx, [tx], mergedConfig)
|
|
193
|
+
|
|
194
|
+
const fee = prepared.fee
|
|
195
|
+
|
|
196
|
+
const { isSponsored, transactionMaxFee } = mergedConfig
|
|
197
|
+
if (!isSponsored && transactionMaxFee !== undefined && fee > transactionMaxFee) {
|
|
198
|
+
throw new MaximumFeeExceededError('Exceeded maximum fee cost for transaction operation.')
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const { userOp } = await this._signUserOperation([tx], { config: mergedConfig, cachedBuild: prepared })
|
|
202
|
+
|
|
203
|
+
this._quoteCache.clear()
|
|
204
|
+
|
|
205
|
+
return userOp
|
|
115
206
|
}
|
|
116
207
|
|
|
117
208
|
/**
|
|
118
209
|
* Approves a specific amount of tokens to a spender.
|
|
119
210
|
*
|
|
120
|
-
* @param {
|
|
121
|
-
* @returns {Promise<TransactionResult>} - The transaction
|
|
122
|
-
* @throws {
|
|
211
|
+
* @param {EvmErc4337ApproveOptions} options - The approve options, including any UserOperationV7 gas/fee overrides to apply to the underlying transaction.
|
|
212
|
+
* @returns {Promise<TransactionResult>} - The transaction's result.
|
|
213
|
+
* @throws {ProviderRequiredError} - If the wallet is not connected to a provider.
|
|
214
|
+
* @throws {ValueError} - If trying to approve usdts on ethereum with allowance not equal to zero (due to the usdt allowance reset requirement).
|
|
123
215
|
*/
|
|
124
216
|
async approve (options) {
|
|
125
|
-
if (!this.
|
|
126
|
-
throw new
|
|
217
|
+
if (!this._provider) {
|
|
218
|
+
throw new ProviderRequiredError('The wallet must be connected to a provider to approve funds.')
|
|
127
219
|
}
|
|
128
220
|
|
|
129
221
|
const { token, spender, amount } = options
|
|
@@ -132,68 +224,163 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
|
|
|
132
224
|
if (chainId === 1n && token.toLowerCase() === USDT_MAINNET_ADDRESS.toLowerCase()) {
|
|
133
225
|
const currentAllowance = await this.getAllowance(token, spender)
|
|
134
226
|
if (currentAllowance > 0n && BigInt(amount) > 0n) {
|
|
135
|
-
throw new
|
|
227
|
+
throw new ValueError(
|
|
136
228
|
'USDT requires the current allowance to be reset to 0 before setting a new non-zero value. Please send an "approve" transaction with an amount of 0 first.'
|
|
137
229
|
)
|
|
138
230
|
}
|
|
139
231
|
}
|
|
140
232
|
|
|
141
233
|
const abi = ['function approve(address spender, uint256 amount) returns (bool)']
|
|
142
|
-
|
|
234
|
+
|
|
235
|
+
// No runner needed - only encoding calldata for the UserOperation.
|
|
236
|
+
const contract = new Contract(token, abi)
|
|
143
237
|
|
|
144
238
|
const tx = {
|
|
145
239
|
to: token,
|
|
146
240
|
value: 0,
|
|
147
|
-
data: contract.interface.encodeFunctionData('approve', [spender, amount])
|
|
241
|
+
data: contract.interface.encodeFunctionData('approve', [spender, amount]),
|
|
242
|
+
...WalletAccountReadOnlyEvmErc4337._extractGasOverrides(options)
|
|
148
243
|
}
|
|
149
244
|
|
|
150
245
|
return await this.sendTransaction(tx)
|
|
151
246
|
}
|
|
152
247
|
|
|
248
|
+
/**
|
|
249
|
+
* Quotes the costs of a send transaction operation.
|
|
250
|
+
*
|
|
251
|
+
* The result is cached internally for up to 2 minutes. A subsequent `sendTransaction` with the
|
|
252
|
+
* same transaction reuses the cached operation — skipping the gas-estimation and paymaster
|
|
253
|
+
* round-trips — after a lightweight on-chain nonce check, re-quoting only if the nonce has moved.
|
|
254
|
+
*
|
|
255
|
+
* In a batched call (`tx` passed as `[tx1, tx2, ...]`), only the gas overrides on `tx1` are
|
|
256
|
+
* honored — a UserOperation has a single set of gas fields regardless of how many calls it batches.
|
|
257
|
+
*
|
|
258
|
+
* An already-signed UserOperation (as returned by `signTransaction`) may also be passed; in that case
|
|
259
|
+
* its fee is read from its own gas fields (in token-paymaster mode this reflects the native gas ceiling,
|
|
260
|
+
* not the token amount).
|
|
261
|
+
*
|
|
262
|
+
* @param {EvmErc4337Transaction | EvmErc4337Transaction[] | UserOperationV7} tx - The transaction, an array of multiple transactions to send in batch, or an already-signed UserOperation.
|
|
263
|
+
* @param {Partial<EvmErc4337WalletPaymasterTokenConfig | EvmErc4337WalletSponsorshipPolicyConfig | EvmErc4337WalletNativeCoinsConfig>} [config] - If set, overrides the given configuration options.
|
|
264
|
+
* @returns {Promise<Omit<TransactionResult, 'hash'>>} The transaction's quotes.
|
|
265
|
+
* @throws {ConfigurationError} If the override `config` is invalid or has missing required fields.
|
|
266
|
+
* @throws {ConfigurationError} If, in token mode, the configured `paymasterAddress` does not match the paymaster address returned by the paymaster RPC. This guards against the auto-generated ERC-20 approval targeting an unexpected paymaster contract.
|
|
267
|
+
* @throws {TransactionError} If the paymaster reports AA50 (the account cannot repay the paymaster).
|
|
268
|
+
*/
|
|
269
|
+
async quoteSendTransaction (tx, config) {
|
|
270
|
+
const mergedConfig = { ...this._config, ...config }
|
|
271
|
+
|
|
272
|
+
if (config) {
|
|
273
|
+
this._validateConfig(mergedConfig)
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (WalletAccountEvmErc4337._isSignedUserOperation(tx)) {
|
|
277
|
+
return { fee: mergedConfig.isSponsored ? 0n : WalletAccountEvmErc4337._getSignedUserOperationFee(tx) }
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const txKey = WalletAccountEvmErc4337._getTxKey(tx)
|
|
281
|
+
|
|
282
|
+
if (mergedConfig.isSponsored) {
|
|
283
|
+
this._quoteCache.set(txKey, { fee: 0n, createdAt: Date.now() })
|
|
284
|
+
return { fee: 0n }
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const gasCostResult = await this._getUserOperationGasCost([tx].flat(), mergedConfig)
|
|
288
|
+
|
|
289
|
+
const fee = BigInt(gasCostResult.fee) * FEE_TOLERANCE_COEFFICIENT / 100n
|
|
290
|
+
|
|
291
|
+
this._quoteCache.set(txKey, {
|
|
292
|
+
fee,
|
|
293
|
+
createdAt: Date.now(),
|
|
294
|
+
userOp: gasCostResult.userOp,
|
|
295
|
+
smartAccount: gasCostResult.smartAccount,
|
|
296
|
+
chainId: gasCostResult.chainId
|
|
297
|
+
})
|
|
298
|
+
|
|
299
|
+
return { fee }
|
|
300
|
+
}
|
|
301
|
+
|
|
153
302
|
/**
|
|
154
303
|
* Sends a transaction.
|
|
155
304
|
*
|
|
156
|
-
*
|
|
157
|
-
*
|
|
305
|
+
* In a batched call (`tx` passed as `[tx1, tx2, ...]`), only the gas overrides on `tx1` are
|
|
306
|
+
* honored — a UserOperation has a single set of gas fields regardless of how many calls it batches.
|
|
307
|
+
*
|
|
308
|
+
* If the transaction is not sponsored, it also estimates the transaction's costs and checks them against the transaction max. fee option.
|
|
309
|
+
*
|
|
310
|
+
* An already-signed UserOperation (as returned by `signTransaction`) may also be passed; in that case it is
|
|
311
|
+
* broadcast directly to the bundler, reusing the nonce baked in at sign time. The max-fee check is skipped
|
|
312
|
+
* (it was already enforced during `signTransaction`).
|
|
313
|
+
*
|
|
314
|
+
* @param {EvmErc4337Transaction | EvmErc4337Transaction[] | UserOperationV7} tx - The transaction, an array of multiple transactions to send in batch, or an already-signed UserOperation.
|
|
315
|
+
* @param {Partial<EvmErc4337WalletPaymasterTokenConfig | EvmErc4337WalletSponsorshipPolicyConfig | EvmErc4337WalletNativeCoinsConfig>} [config] - If set, overrides the given configuration options.
|
|
158
316
|
* @returns {Promise<TransactionResult>} The transaction's result.
|
|
317
|
+
* @throws {ConfigurationError} If the override `config` is invalid or has missing required fields.
|
|
318
|
+
* @throws {ConfigurationError} If, in token mode, the configured `paymasterAddress` does not match the paymaster address returned by the paymaster RPC. This guards against the auto-generated ERC-20 approval targeting an unexpected paymaster contract.
|
|
319
|
+
* @throws {MaximumFeeExceededError} If the transaction is not sponsored, and the transaction's cost surpasses the transaction max. fee option.
|
|
320
|
+
* @throws {ValueError} If `nonceKey` is a bigint outside the uint192 range (0 to 2^192 - 1).
|
|
321
|
+
* @throws {TransactionError} If the paymaster reports AA50 (the account cannot repay the paymaster).
|
|
159
322
|
*/
|
|
160
323
|
async sendTransaction (tx, config) {
|
|
161
|
-
const
|
|
324
|
+
const mergedConfig = { ...this._config, ...config }
|
|
162
325
|
|
|
163
|
-
|
|
326
|
+
if (config) {
|
|
327
|
+
this._validateConfig(mergedConfig)
|
|
328
|
+
}
|
|
164
329
|
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
amountToApprove: BigInt(fee * FEE_TOLERANCE_COEFFICIENT / 100n)
|
|
168
|
-
})
|
|
330
|
+
if (WalletAccountEvmErc4337._isSignedUserOperation(tx)) {
|
|
331
|
+
const fee = mergedConfig.isSponsored ? 0n : WalletAccountEvmErc4337._getSignedUserOperationFee(tx)
|
|
169
332
|
|
|
170
|
-
|
|
333
|
+
const hash = await this._broadcastSignedUserOperation(tx)
|
|
334
|
+
|
|
335
|
+
return { hash, fee }
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const txs = [tx].flat()
|
|
339
|
+
const prepared = await this._prepareForSend(tx, txs, mergedConfig)
|
|
340
|
+
|
|
341
|
+
const { isSponsored, transactionMaxFee } = mergedConfig
|
|
342
|
+
if (!isSponsored && transactionMaxFee !== undefined && prepared.fee > transactionMaxFee) {
|
|
343
|
+
throw new MaximumFeeExceededError('Exceeded maximum fee cost for transaction operation.')
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const hash = await this._sendUserOperation(txs, { config: mergedConfig, cachedBuild: prepared })
|
|
347
|
+
return { hash, fee: prepared.fee }
|
|
171
348
|
}
|
|
172
349
|
|
|
173
350
|
/**
|
|
174
351
|
* Transfers a token to another address.
|
|
175
352
|
*
|
|
176
|
-
*
|
|
177
|
-
*
|
|
353
|
+
* If the transaction is not sponsored, it also estimates the transfer's costs and checks them against the transfer max. fee option.
|
|
354
|
+
*
|
|
355
|
+
* @param {EvmErc4337TransferOptions} options - The transfer's options, including any UserOperationV7 gas/fee overrides to apply to the underlying transaction.
|
|
356
|
+
* @param {Partial<EvmErc4337WalletPaymasterTokenConfig | EvmErc4337WalletSponsorshipPolicyConfig | EvmErc4337WalletNativeCoinsConfig>} [config] - If set, overrides the given configuration options.
|
|
178
357
|
* @returns {Promise<TransferResult>} The transfer's result.
|
|
358
|
+
* @throws {ConfigurationError} If the override `config` is invalid or has missing required fields.
|
|
359
|
+
* @throws {ConfigurationError} If, in token mode, the configured `paymasterAddress` does not match the paymaster address returned by the paymaster RPC. This guards against the auto-generated ERC-20 approval targeting an unexpected paymaster contract.
|
|
360
|
+
* @throws {MaximumFeeExceededError} If the transaction is not sponsored, and the transfer's cost surpasses the transfer max. fee option.
|
|
361
|
+
* @throws {ValueError} If `nonceKey` is a bigint outside the uint192 range (0 to 2^192 - 1).
|
|
362
|
+
* @throws {TransactionError} If the paymaster reports AA50 (the account cannot repay the paymaster).
|
|
179
363
|
*/
|
|
180
364
|
async transfer (options, config) {
|
|
181
|
-
const
|
|
365
|
+
const mergedConfig = { ...this._config, ...config }
|
|
182
366
|
|
|
183
|
-
|
|
367
|
+
if (config) {
|
|
368
|
+
this._validateConfig(mergedConfig)
|
|
369
|
+
}
|
|
184
370
|
|
|
185
|
-
const {
|
|
371
|
+
const { isSponsored, transferMaxFee } = mergedConfig
|
|
186
372
|
|
|
187
|
-
|
|
188
|
-
throw new Error('Exceeded maximum fee cost for transfer operation.')
|
|
189
|
-
}
|
|
373
|
+
const tx = await WalletAccountReadOnlyEvmErc4337._getTransferTransaction(options)
|
|
190
374
|
|
|
191
|
-
const
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
375
|
+
const txs = [tx]
|
|
376
|
+
const prepared = await this._prepareForSend(tx, txs, mergedConfig)
|
|
377
|
+
|
|
378
|
+
if (!isSponsored && transferMaxFee !== undefined && prepared.fee > transferMaxFee) {
|
|
379
|
+
throw new MaximumFeeExceededError('Exceeded maximum fee cost for transfer operation.')
|
|
380
|
+
}
|
|
195
381
|
|
|
196
|
-
|
|
382
|
+
const hash = await this._sendUserOperation(txs, { config: mergedConfig, cachedBuild: prepared })
|
|
383
|
+
return { hash, fee: prepared.fee }
|
|
197
384
|
}
|
|
198
385
|
|
|
199
386
|
/**
|
|
@@ -216,64 +403,183 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
|
|
|
216
403
|
this._ownerAccount.dispose()
|
|
217
404
|
}
|
|
218
405
|
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
owners: [owner],
|
|
230
|
-
threshold: 1,
|
|
231
|
-
saltNonce: SALT_NONCE
|
|
232
|
-
},
|
|
233
|
-
paymasterOptions: {
|
|
234
|
-
paymasterUrl: this._config.paymasterUrl,
|
|
235
|
-
paymasterAddress: this._config.paymasterAddress,
|
|
236
|
-
paymasterTokenAddress: this._config.paymasterToken.address,
|
|
237
|
-
skipApproveTransaction: true
|
|
238
|
-
},
|
|
239
|
-
customContracts: {
|
|
240
|
-
entryPointAddress: this._config.entryPointAddress
|
|
406
|
+
/** @private */
|
|
407
|
+
async _prepareForSend (tx, txs, config) {
|
|
408
|
+
const nonce = await this._resolveNonce(config)
|
|
409
|
+
|
|
410
|
+
if (nonce === undefined) {
|
|
411
|
+
const cached = this._consumeCachedQuote(tx)
|
|
412
|
+
if (cached?.userOp) {
|
|
413
|
+
const onChainNonce = await fetchAccountNonce(this._eip1193Provider, cached.smartAccount.entrypointAddress, cached.smartAccount.accountAddress)
|
|
414
|
+
if (cached.userOp.nonce === onChainNonce) {
|
|
415
|
+
return cached
|
|
241
416
|
}
|
|
242
|
-
}
|
|
417
|
+
}
|
|
243
418
|
}
|
|
244
419
|
|
|
245
|
-
return this.
|
|
420
|
+
return await this._buildAtNonce(txs, nonce, config)
|
|
246
421
|
}
|
|
247
422
|
|
|
248
423
|
/** @private */
|
|
249
|
-
async
|
|
250
|
-
const
|
|
424
|
+
async _buildAtNonce (txs, nonce, config) {
|
|
425
|
+
const calls = WalletAccountReadOnlyEvmErc4337._toMetaTransactions(txs)
|
|
426
|
+
const txOverrides = {
|
|
427
|
+
...WalletAccountReadOnlyEvmErc4337._extractGasOverrides(txs[0]),
|
|
428
|
+
...(nonce !== undefined ? { nonce } : {})
|
|
429
|
+
}
|
|
251
430
|
|
|
252
|
-
|
|
431
|
+
let userOp, smartAccount, chainId, tokenQuote
|
|
432
|
+
try {
|
|
433
|
+
;({ userOp, smartAccount, chainId, tokenQuote } = await this._buildUserOperation(calls, config, txOverrides))
|
|
434
|
+
} catch (err) {
|
|
435
|
+
if (WalletAccountReadOnlyEvmErc4337._isAA50Error(err)) {
|
|
436
|
+
throw new TransactionError('Not enough funds on the safe account to repay the paymaster.', {
|
|
437
|
+
reason: TransactionErrorReason.INSUFFICIENT_BALANCE,
|
|
438
|
+
cause: err
|
|
439
|
+
})
|
|
440
|
+
}
|
|
441
|
+
throw err
|
|
442
|
+
}
|
|
253
443
|
|
|
254
|
-
const
|
|
444
|
+
const fee = config.isSponsored
|
|
445
|
+
? 0n
|
|
446
|
+
: BigInt(tokenQuote ? tokenQuote.tokenCost : calculateUserOperationMaxGasCost(userOp)) * FEE_TOLERANCE_COEFFICIENT / 100n
|
|
255
447
|
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
448
|
+
return { fee, userOp, smartAccount, chainId }
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** @private */
|
|
452
|
+
async _resolveNonce (config) {
|
|
453
|
+
if (config.nonceKey !== undefined && config.nonceKey !== null) {
|
|
454
|
+
let key
|
|
455
|
+
if (typeof config.nonceKey === 'string') {
|
|
456
|
+
key = BigInt(keccak256(toUtf8Bytes(config.nonceKey))) & MAX_UINT192
|
|
457
|
+
} else {
|
|
458
|
+
key = BigInt(config.nonceKey)
|
|
459
|
+
if (key < 0n || key > MAX_UINT192) {
|
|
460
|
+
throw new ValueError('nonceKey must be within the uint192 range (0 to 2^192 - 1).')
|
|
263
461
|
}
|
|
264
|
-
}
|
|
462
|
+
}
|
|
463
|
+
return await fetchAccountNonce(this._eip1193Provider, ENTRYPOINT_V7, this._address, key)
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
if (config.parallel) {
|
|
467
|
+
return BigInt(hexlify(randomBytes(24))) << NONCE_KEY_SHIFT
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
return undefined
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** @private */
|
|
474
|
+
static _getTxKey (tx) {
|
|
475
|
+
return JSON.stringify([tx].flat(), (_, v) => typeof v === 'bigint' ? v.toString() : v)
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/** @private */
|
|
479
|
+
_consumeCachedQuote (tx) {
|
|
480
|
+
const txKey = WalletAccountEvmErc4337._getTxKey(tx)
|
|
481
|
+
const quote = this._quoteCache.get(txKey)
|
|
482
|
+
|
|
483
|
+
if (!quote) {
|
|
484
|
+
return undefined
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
this._quoteCache.delete(txKey)
|
|
265
488
|
|
|
266
|
-
|
|
489
|
+
if (Date.now() - quote.createdAt > QUOTE_MAX_AGE_MS) {
|
|
490
|
+
return undefined
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
return quote
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** @private */
|
|
497
|
+
async _signUserOperation (txs, { config, cachedBuild }) {
|
|
498
|
+
const { userOp, smartAccount, chainId } = cachedBuild?.userOp
|
|
499
|
+
? cachedBuild
|
|
500
|
+
: await this._buildUserOperation(
|
|
501
|
+
WalletAccountReadOnlyEvmErc4337._toMetaTransactions(txs),
|
|
502
|
+
config,
|
|
503
|
+
WalletAccountReadOnlyEvmErc4337._extractGasOverrides(txs[0])
|
|
504
|
+
)
|
|
505
|
+
|
|
506
|
+
const signer = {
|
|
507
|
+
address: this._ownerAccountAddress,
|
|
508
|
+
signHash: async (hash) => this._ownerAccount._signer._account.signingKey.sign(hash).serialized
|
|
509
|
+
}
|
|
510
|
+
userOp.signature = await smartAccount.signUserOperationWithSigners(
|
|
511
|
+
userOp,
|
|
512
|
+
[signer],
|
|
513
|
+
chainId
|
|
514
|
+
)
|
|
515
|
+
|
|
516
|
+
return { userOp, smartAccount, chainId }
|
|
517
|
+
}
|
|
267
518
|
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
519
|
+
/** @private */
|
|
520
|
+
async _sendUserOperation (txs, { config, cachedBuild }) {
|
|
521
|
+
try {
|
|
522
|
+
const { userOp, smartAccount } = await this._signUserOperation(txs, { config, cachedBuild })
|
|
523
|
+
|
|
524
|
+
return await this._getBundler().sendUserOperation(userOp, smartAccount.entrypointAddress)
|
|
271
525
|
} catch (err) {
|
|
272
|
-
if (
|
|
273
|
-
throw new
|
|
526
|
+
if (WalletAccountReadOnlyEvmErc4337._isAA50Error(err)) {
|
|
527
|
+
throw new TransactionError('Not enough funds on the safe account to repay the paymaster.', {
|
|
528
|
+
reason: TransactionErrorReason.INSUFFICIENT_BALANCE,
|
|
529
|
+
cause: err
|
|
530
|
+
})
|
|
274
531
|
}
|
|
532
|
+
throw err
|
|
533
|
+
}
|
|
534
|
+
}
|
|
275
535
|
|
|
536
|
+
/**
|
|
537
|
+
* Broadcasts an already-signed UserOperation directly to the bundler.
|
|
538
|
+
*
|
|
539
|
+
* @private
|
|
540
|
+
* @param {UserOperationV7} userOp - The signed UserOperation.
|
|
541
|
+
* @returns {Promise<string>} The user operation hash.
|
|
542
|
+
* @throws {TransactionError} If the paymaster reports AA50 (the account cannot repay the paymaster).
|
|
543
|
+
*/
|
|
544
|
+
async _broadcastSignedUserOperation (userOp) {
|
|
545
|
+
try {
|
|
546
|
+
return await this._getBundler().sendUserOperation(userOp, ENTRYPOINT_V7)
|
|
547
|
+
} catch (err) {
|
|
548
|
+
if (WalletAccountReadOnlyEvmErc4337._isAA50Error(err)) {
|
|
549
|
+
throw new TransactionError('Not enough funds on the safe account to repay the paymaster.', {
|
|
550
|
+
reason: TransactionErrorReason.INSUFFICIENT_BALANCE,
|
|
551
|
+
cause: err
|
|
552
|
+
})
|
|
553
|
+
}
|
|
276
554
|
throw err
|
|
277
555
|
}
|
|
278
556
|
}
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* Determines whether a value is an already-signed UserOperation (as returned by `signTransaction`)
|
|
560
|
+
* rather than an unsigned {@link EvmErc4337Transaction} (or array of them).
|
|
561
|
+
*
|
|
562
|
+
* @private
|
|
563
|
+
* @param {EvmErc4337Transaction | EvmErc4337Transaction[] | UserOperationV7} tx - The value to inspect.
|
|
564
|
+
* @returns {boolean} True if the value is a signed UserOperation.
|
|
565
|
+
*/
|
|
566
|
+
static _isSignedUserOperation (tx) {
|
|
567
|
+
return !!tx.signature
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/**
|
|
571
|
+
* Computes the fee (with tolerance buffer) for an already-signed UserOperation, reusing the
|
|
572
|
+
* same native gas-cost formula as the unsigned native path.
|
|
573
|
+
*
|
|
574
|
+
* In token-paymaster mode this reflects the native gas ceiling rather than the token amount:
|
|
575
|
+
* the token cost is set by the paymaster at sign time and cannot be reproduced from the signed
|
|
576
|
+
* UserOperation.
|
|
577
|
+
*
|
|
578
|
+
* @private
|
|
579
|
+
* @param {UserOperationV7} userOp - The signed UserOperation.
|
|
580
|
+
* @returns {bigint} The fee, in the smart account's native coin (wei).
|
|
581
|
+
*/
|
|
582
|
+
static _getSignedUserOperationFee (userOp) {
|
|
583
|
+
return BigInt(calculateUserOperationMaxGasCost(userOp)) * FEE_TOLERANCE_COEFFICIENT / 100n
|
|
584
|
+
}
|
|
279
585
|
}
|