@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.
@@ -14,94 +14,311 @@
14
14
 
15
15
  'use strict'
16
16
 
17
- import { WalletAccountReadOnly } from '@tetherto/wdk-wallet'
17
+ import { getAddress, isAddress, isHexString } from 'ethers'
18
+
19
+ import { WalletAccountReadOnly, NoSuchElementError, TransactionError, TransactionErrorReason, UnsupportedOperationError, ValueError } from '@tetherto/wdk-wallet'
18
20
 
19
21
  import { WalletAccountReadOnlyEvm } from '@tetherto/wdk-wallet-evm'
20
22
 
21
- import { Safe4337Pack, GenericFeeEstimator } from '@wdk-safe-global/relay-kit'
23
+ import {
24
+ // eslint-disable-next-line camelcase
25
+ SafeAccountV0_3_0 as SafeAccount030,
26
+ AbstractionKitError,
27
+ Bundler,
28
+ Erc7677Paymaster,
29
+ HttpTransport,
30
+ ENTRYPOINT_V7,
31
+ calculateUserOperationMaxGasCost
32
+ } from 'abstractionkit'
33
+
34
+ /** @typedef {import('abstractionkit').InitCodeOverrides} InitCodeOverrides */
35
+ /** @typedef {import('abstractionkit').MetaTransaction} MetaTransaction */
36
+ /** @typedef {import('abstractionkit').SafeAccountV0_3_0} SafeAccountV0_3_0 */
37
+
38
+ import { ConfigurationError } from './errors.js'
39
+
40
+ const PaymasterMode = {
41
+ NATIVE: 'native',
42
+ SPONSORED: 'sponsored',
43
+ TOKEN: 'token'
44
+ }
45
+
46
+ export const FEE_TOLERANCE_COEFFICIENT = 120n
22
47
 
48
+ /** @typedef {import('ethers').Provider} Provider */
23
49
  /** @typedef {import('ethers').Eip1193Provider} Eip1193Provider */
24
50
 
25
- /** @typedef {import('@tetherto/wdk-wallet-evm').EvmTransaction} EvmTransaction */
26
51
  /** @typedef {import('@tetherto/wdk-wallet-evm').TransactionResult} TransactionResult */
27
52
  /** @typedef {import('@tetherto/wdk-wallet-evm').TransferOptions} TransferOptions */
28
53
  /** @typedef {import('@tetherto/wdk-wallet-evm').TransferResult} TransferResult */
29
54
 
30
55
  /** @typedef {import('@tetherto/wdk-wallet-evm').EvmTransactionReceipt} EvmTransactionReceipt */
31
56
 
57
+ /** @typedef {import('@tetherto/wdk-wallet-evm').TypedData} TypedData */
58
+
59
+ /** @typedef {import('abstractionkit').UserOperationReceiptResult} UserOperationReceipt */
60
+ /** @typedef {import('abstractionkit').UserOperationV7} UserOperationV7 */
61
+ /** @typedef {import('abstractionkit').TokenQuote} TokenQuote */
62
+
63
+ /** @typedef {import('@tetherto/wdk-wallet').TransactionReceipt} TransactionReceipt */
64
+ /** @typedef {import('@tetherto/wdk-wallet').WaitForTransactionOptions} WaitForTransactionOptions */
65
+
66
+ /**
67
+ * The ERC-4337-specific fields added to a normalized transaction receipt.
68
+ *
69
+ * @typedef {Object} EvmErc4337TransactionDetails
70
+ * @property {number} confirmations - The number of confirmations (0 while pending or dropped).
71
+ * @property {EvmTransactionReceipt | null} receipt - The native ethers receipt, or null while the user operation is pending or dropped.
72
+ * @property {UserOperationReceipt | null} userOperationReceipt - The user operation receipt, or null while pending or unavailable.
73
+ */
74
+
75
+ /**
76
+ * @typedef {Object} BuiltUserOperation
77
+ * @property {UserOperationV7} userOp - The fully-populated UserOperation ready to sign.
78
+ * @property {SafeAccountV0_3_0} smartAccount - The Safe account that will execute the operation.
79
+ * @property {'native' | 'sponsored' | 'token'} mode - The paymaster mode used to build the operation.
80
+ * @property {bigint} chainId - The chain id captured at build time.
81
+ * @property {TokenQuote} [tokenQuote] - The paymaster token quote, present only in token mode.
82
+ */
83
+
32
84
  /**
33
- * @typedef {Object} EvmErc4337WalletConfig
85
+ * An EVM transaction shape used to build an ERC-4337 UserOperation.
86
+ *
87
+ * @typedef {Object} EvmErc4337Transaction
88
+ * @property {string} to - The call's recipient.
89
+ * @property {number | bigint} value - The amount of native coin to send to the recipient (in wei).
90
+ * @property {string} [data] - The call's data in hex format.
91
+ * @property {number | bigint} [callGasLimit] - If set, overrides the user operations' call gas limit.
92
+ * @property {number | bigint} [verificationGasLimit] - If set, overrides the user operations' verification gas limit.
93
+ * @property {number | bigint} [preVerificationGas] - If set, overrides the user operations' pre-verification gas.
94
+ * @property {number | bigint} [maxFeePerGas] - If set, overrides the user operations' max fee per gas (EIP-1559 cap). Treated as a pair with `maxPriorityFeePerGas`: setting either disables the bundler-fetched fee fallback for both.
95
+ * @property {number | bigint} [maxPriorityFeePerGas] - If set, overrides the user operations' max priority fee per gas. Treated as a pair with `maxFeePerGas`: setting either disables the bundler-fetched fee fallback for both.
96
+ */
97
+
98
+ /**
99
+ * Gas-related UserOperationV7 overrides. Numeric fields accept `number` or `bigint`; numbers are
100
+ * coerced to `bigint` by `_extractGasOverrides` before the operation is built. All fields are
101
+ * optional; absent fields fall back to the bundler-fetched gas price (fee pair) or the bundler's
102
+ * gas estimation (gas limits).
103
+ *
104
+ * @typedef {Object} EvmErc4337GasOverrides
105
+ * @property {number | bigint} [callGasLimit] - Override for the UserOperation's call gas limit.
106
+ * @property {number | bigint} [verificationGasLimit] - Override for the UserOperation's verification gas limit.
107
+ * @property {number | bigint} [preVerificationGas] - Override for the UserOperation's pre-verification gas.
108
+ * @property {number | bigint} [maxFeePerGas] - Override for the UserOperation's max fee per gas (EIP-1559 cap).
109
+ * @property {number | bigint} [maxPriorityFeePerGas] - Override for the UserOperation's max priority fee per gas.
110
+ */
111
+
112
+ /**
113
+ * The options of a token transfer, extended with the optional UserOperationV7 gas overrides.
114
+ *
115
+ * @typedef {TransferOptions & EvmErc4337GasOverrides} EvmErc4337TransferOptions
116
+ */
117
+
118
+ /**
119
+ * A single explicit UserOperationV7 `nonce`, combined with `EvmErc4337GasOverrides` for the build
120
+ * step to place the operation in a specific two-dimensional nonce lane. The `nonce` is derived
121
+ * internally from the account's `parallel`/`nonceKey` configuration, never from user-supplied
122
+ * transaction fields.
123
+ *
124
+ * @typedef {Object} Nonce
125
+ * @property {number | bigint} [nonce] - Full 256-bit UserOperation nonce (`key << 64 | sequence`) placing the op in a specific lane. Omitted for default (key-0) sends, in which case the account fetches the current on-chain nonce.
126
+ */
127
+
128
+ /**
129
+ * @typedef {Object} OnChainIdentifier
130
+ * @property {string} project - The project name included in the 50-byte on-chain marker.
131
+ * @property {'Web' | 'Mobile' | 'Safe App' | 'Widget'} [platform] - The platform type (default: 'Web').
132
+ * @property {string} [tool] - The tool name used to create the UserOperation.
133
+ * @property {string} [toolVersion] - Semver-style tool version string included in the on-chain marker (e.g. "1.0.0").
134
+ */
135
+
136
+ /**
137
+ * @typedef {Object} EvmErc4337WalletCommonConfig
34
138
  * @property {number} chainId - The blockchain's id (e.g., 1 for ethereum).
35
- * @property {string | Eip1193Provider} provider - The url of the rpc provider, or an instance of a class that implements eip-1193.
139
+ * @property {string | Provider | Eip1193Provider | Array<string | Provider | Eip1193Provider>} provider - The url of the rpc provider, an already-built ethers `Provider` (reused as-is), or an instance of a class that implements eip-1193. It's also possible to provide an array of these instead. In such case, connection errors will cause the wallet to automatically fallback on the next provider in the list.
140
+ * @property {number} [retries] - If set and if 'provider' is a list of urls or EIP 1193 providers, the number of additional retry attempts after the initial call fails. Total attempts = `1 + retries`. For example, `retries: 3` with 4 providers will try each provider once before throwing. If `retries` exceeds the number of providers, the failover will loop back and retry already-failed providers in round-robin order. Default: 3.
36
141
  * @property {string} bundlerUrl - The url of the bundler service.
142
+ * @property {Record<string, string>} [bundlerHeaders] - Optional HTTP headers sent on every request to the bundler (e.g. `{ Authorization: 'Bearer <key>' }`). Use for bundlers that require authentication.
143
+ * @property {string} safeModulesVersion - Version of the Safe 4337 module set to deploy with the account (e.g. "0.3.0"). Determines the module addresses used in init code.
144
+ * @property {OnChainIdentifier | string} [onChainIdentifier] - Optional on-chain identifier. Appends a 50-byte project marker to every UserOperation callData. Pass a string to reuse it as the project name, or a full object for more control.
145
+ * @property {boolean} [parallel] - When true, each send is placed in a fresh, independent nonce lane (a random 192-bit key at sequence 0) so concurrent or back-to-back sends don't collide on the nonce. Ordering between such sends is not guaranteed and each consumes a new EntryPoint nonce slot. Ignored when `nonceKey` is set. Overridable per call.
146
+ * @property {number | bigint | string} [nonceKey] - Send in an explicit nonce lane. A string is hashed to a deterministic key — a reusable named lane that resumes the same sequence across sessions; a number or bigint is used as the raw uint192 key and must be within the uint192 range (0 to 2^192 - 1), otherwise the send throws (pass a bigint or string for keys above 2^53). Sends sharing a key are ordered sequentially; different keys run in parallel. Overridable per call.
147
+ */
148
+
149
+ /**
150
+ * @typedef {Object} EvmErc4337WalletPaymasterTokenConfig
151
+ * @property {false} [isSponsored] - Whether the paymaster is sponsoring the account.
152
+ * @property {false} [useNativeCoins] - Whether to use native coins instead of a paymaster to pay for gas fees.
37
153
  * @property {string} paymasterUrl - The url of the paymaster service.
154
+ * @property {Record<string, string>} [paymasterHeaders] - Optional HTTP headers sent on every request to the paymaster (e.g. `{ Authorization: 'Bearer <key>' }`). Use for paymasters that require authentication.
38
155
  * @property {string} paymasterAddress - The address of the paymaster smart contract.
39
- * @property {string} entryPointAddress - The address of the entry point smart contract.
40
- * @property {string} safeModulesVersion - The safe modules version.
41
156
  * @property {Object} paymasterToken - The paymaster token configuration.
42
157
  * @property {string} paymasterToken.address - The address of the paymaster token.
43
158
  * @property {number | bigint} [transferMaxFee] - The maximum fee amount for transfer operations.
159
+ * @property {number | bigint} [transactionMaxFee] - The maximum fee amount for sendTransaction and signTransaction operations.
160
+ */
161
+
162
+ /**
163
+ * @typedef {Object} EvmErc4337WalletSponsorshipPolicyConfig
164
+ * @property {true} isSponsored - Whether the paymaster is sponsoring the account.
165
+ * @property {false} [useNativeCoins] - Whether to use native coins instead of a paymaster to pay for gas fees.
166
+ * @property {string} paymasterUrl - The url of the paymaster service.
167
+ * @property {Record<string, string>} [paymasterHeaders] - Optional HTTP headers sent on every request to the paymaster (e.g. `{ Authorization: 'Bearer <key>' }`). Use for paymasters that require authentication.
168
+ * @property {string} [sponsorshipPolicyId] - Identifier of the paymaster sponsorship policy to apply (provider-specific). Optional; some paymasters infer the policy from the project key.
169
+ */
170
+
171
+ /**
172
+ * @typedef {Object} EvmErc4337WalletNativeCoinsConfig
173
+ * @property {false} [isSponsored] - Whether the paymaster is sponsoring the account.
174
+ * @property {true} useNativeCoins - Whether to use native coins instead of a paymaster to pay for gas fees.
175
+ * @property {number | bigint} [transferMaxFee] - The maximum fee amount for transfer operations.
176
+ * @property {number | bigint} [transactionMaxFee] - The maximum fee amount for sendTransaction and signTransaction operations.
177
+ */
178
+
179
+ /**
180
+ * @typedef {EvmErc4337WalletCommonConfig & (EvmErc4337WalletPaymasterTokenConfig | EvmErc4337WalletSponsorshipPolicyConfig | EvmErc4337WalletNativeCoinsConfig)} EvmErc4337WalletConfig
44
181
  */
45
182
 
46
183
  export const SALT_NONCE = '0x69b348339eea4ed93f9d11931c3b894c8f9d8c7663a053024b11cb7eb4e5a1f6'
47
184
 
185
+ const SAFE_MODULES_MAP = {
186
+ '0.3.0': {
187
+ safe4337ModuleAddress: '0x75cf11467937ce3F2f357CE24ffc3DBF8fD5c226',
188
+ safeModuleSetupAddress: '0x2dd68b007B46fBe91B9A7c3EDa5A7a1063cB5b47'
189
+ }
190
+ }
191
+
192
+ const PINNED_SAFE_ADDRESS = Symbol('pinnedSafeAddress')
193
+
48
194
  export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOnly {
49
195
  /**
50
196
  * Creates a new read-only evm [erc-4337](https://www.erc4337.io/docs) wallet account.
51
197
  *
52
- * @param {string} address - The evm account's address.
53
- * @param {Omit<EvmErc4337WalletConfig, 'transferMaxFee'>} config - The configuration object.
198
+ * `address` is the safe owner's address; the account's own address is the counterfactual safe address derived
199
+ * from it. To read a safe whose address is already known, use {@link fromSafeAddress}.
200
+ *
201
+ * @param {string} address - The safe owner's evm address.
202
+ * @param {Omit<EvmErc4337WalletConfig, 'transferMaxFee' | 'transactionMaxFee'>} config - The configuration object.
203
+ * @throws {ValueError} If `address` is not a well-formed evm address.
204
+ * @throws {ValueError} If the `provider` option is set to an empty array.
205
+ * @throws {ConfigurationError} If `config.safeModulesVersion` is not in the supported set.
54
206
  */
55
207
  constructor (address, config) {
56
- super(undefined)
208
+ if (!SAFE_MODULES_MAP[config.safeModulesVersion]) {
209
+ throw new ConfigurationError(`Unsupported safe modules version: ${config.safeModulesVersion}`)
210
+ }
211
+
212
+ const { [PINNED_SAFE_ADDRESS]: pinnedSafeAddress, ...unpinnedConfig } = config
213
+ const [accountConfig, ownerAccountAddress] = pinnedSafeAddress === undefined
214
+ ? [config, address]
215
+ : [unpinnedConfig, undefined]
216
+
217
+ super(pinnedSafeAddress ?? WalletAccountReadOnlyEvmErc4337.predictSafeAddress(address, config))
57
218
 
58
219
  /**
59
220
  * The read-only evm erc-4337 wallet account configuration.
60
221
  *
61
222
  * @protected
62
- * @type {Omit<EvmErc4337WalletConfig, 'transferMaxFee'>}
223
+ * @type {Omit<EvmErc4337WalletConfig, 'transferMaxFee' | 'transactionMaxFee'>}
63
224
  */
64
- this._config = config
225
+ this._config = accountConfig
65
226
 
66
227
  /**
67
- * The safe's implementation of the erc-4337 standard.
228
+ * Cached AbstractionKit bundler.
68
229
  *
69
230
  * @protected
70
- * @type {Safe4337Pack | undefined}
231
+ * @type {Bundler | undefined}
71
232
  */
72
- this._safe4337Pack = undefined
233
+ this._bundler = undefined
73
234
 
74
235
  /**
75
- * The safe's fee estimator.
236
+ * The chain id.
76
237
  *
77
238
  * @protected
78
- * @type {GenericFeeEstimator | undefined}
239
+ * @type {bigint | undefined}
79
240
  */
80
- this._feeEstimator = undefined
241
+ this._chainId = undefined
81
242
 
82
243
  /**
83
- * The chain id.
244
+ * Cached Erc7677Paymaster instances keyed by URL.
84
245
  *
85
246
  * @protected
86
- * @type {bigint | undefined}
247
+ * @type {Map<string, Erc7677Paymaster>}
87
248
  */
88
- this._chainId = undefined
249
+ this._paymasters = new Map()
250
+
251
+ /**
252
+ * The safe owner's address, or `undefined` when the account was created from a safe address.
253
+ *
254
+ * @protected
255
+ * @type {string | undefined}
256
+ */
257
+ this._ownerAccountAddress = ownerAccountAddress
258
+
259
+ /**
260
+ * The shared ethers provider used to interact with the blockchain. A single instance is
261
+ * built here (or reused from the manager) and passed to every nested `WalletAccountReadOnlyEvm`
262
+ * so accounts do not open their own connection.
263
+ *
264
+ * @protected
265
+ * @type {Provider}
266
+ */
267
+ this._provider = this._buildProvider(this._config)
268
+
269
+ /**
270
+ * The EIP-1193 view of {@link _provider} that abstractionkit (Safe4337Pack) requires. Built
271
+ * once and backed by the same underlying connection as {@link _provider}.
272
+ *
273
+ * @protected
274
+ * @type {Eip1193Provider}
275
+ */
276
+ this._eip1193Provider = WalletAccountReadOnlyEvmErc4337._buildEip1193Provider(this._provider, this._config)
89
277
 
90
278
  /** @private */
91
- this._ownerAccountAddress = address
279
+ this._deployedSmartAccount = undefined
280
+
281
+ /** @private */
282
+ this._evmReadOnlyAccount = undefined
92
283
  }
93
284
 
94
285
  /**
95
- * Returns the account's address.
286
+ * Predicts the address of a safe account.
96
287
  *
97
- * @returns {Promise<string>} The account's address.
288
+ * @param {string} owner - The safe owner's address.
289
+ * @param {Pick<EvmErc4337WalletConfig, 'safeModulesVersion' | 'onChainIdentifier'>} config - The safe configuration.
290
+ * @throws {ValueError} If `owner` is not a well-formed evm address.
291
+ * @returns {string} The Safe address.
98
292
  */
99
- async getAddress () {
100
- const safe4337pack = await this._getSafe4337Pack()
293
+ static predictSafeAddress (owner, config) {
294
+ if (!isAddress(owner)) {
295
+ throw new ValueError(`Invalid owner address: '${owner}'.`)
296
+ }
101
297
 
102
- const address = await safe4337pack.protocolKit.getAddress()
298
+ const overrides = WalletAccountReadOnlyEvmErc4337._getInitCodeOverrides(config)
299
+ return SafeAccount030.createAccountAddress([owner], overrides)
300
+ }
103
301
 
104
- return address
302
+ /**
303
+ * Creates a read-only account for a safe whose address is already known.
304
+ *
305
+ * The address is used as the account's own address, so balances, allowances and quotes resolve against that
306
+ * safe. Its owner is unknown to the account: {@link verify} and {@link verifyTypedData} throw, and the safe must
307
+ * already be deployed for {@link quoteSendTransaction} and {@link quoteTransfer}.
308
+ *
309
+ * @param {string} safeAddress - The safe's evm address. Normalized to its checksummed form.
310
+ * @param {Omit<EvmErc4337WalletConfig, 'transferMaxFee' | 'transactionMaxFee'>} config - The configuration object.
311
+ * @throws {ValueError} If `safeAddress` is not a well-formed evm address.
312
+ * @throws {ValueError} If the `provider` option is set to an empty array.
313
+ * @throws {ConfigurationError} If `config.safeModulesVersion` is not in the supported set.
314
+ * @returns {WalletAccountReadOnlyEvmErc4337} A read-only account whose address is `safeAddress`.
315
+ */
316
+ static fromSafeAddress (safeAddress, config) {
317
+ if (!isAddress(safeAddress)) {
318
+ throw new ValueError(`Invalid safe address: '${safeAddress}'.`)
319
+ }
320
+
321
+ return new WalletAccountReadOnlyEvmErc4337(undefined, { ...config, [PINNED_SAFE_ADDRESS]: getAddress(safeAddress) })
105
322
  }
106
323
 
107
324
  /**
@@ -127,75 +344,193 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
127
344
  return await evmReadOnlyAccount.getTokenBalance(tokenAddress)
128
345
  }
129
346
 
347
+ /**
348
+ * Returns the account balances for multiple tokens.
349
+ *
350
+ * @param {string[]} tokenAddresses - The smart contract addresses of the tokens.
351
+ * @returns {Promise<Record<string, bigint>>} A mapping of token addresses to their balances (in base units).
352
+ */
353
+ async getTokenBalances (tokenAddresses) {
354
+ const evmReadOnlyAccount = await this._getEvmReadOnlyAccount()
355
+
356
+ return await evmReadOnlyAccount.getTokenBalances(tokenAddresses)
357
+ }
358
+
130
359
  /**
131
360
  * Returns the account's balance for the paymaster token provided in the wallet account configuration.
132
361
  *
133
362
  * @returns {Promise<bigint>} The paymaster token balance (in base unit).
363
+ * @throws {ConfigurationError} If no paymaster token is configured (sponsored or native-coins mode).
134
364
  */
135
365
  async getPaymasterTokenBalance () {
136
366
  const { paymasterToken } = this._config
137
367
 
368
+ if (!paymasterToken) {
369
+ throw new ConfigurationError('Paymaster token is not configured.')
370
+ }
371
+
138
372
  return await this.getTokenBalance(paymasterToken.address)
139
373
  }
140
374
 
141
375
  /**
142
376
  * Quotes the costs of a send transaction operation.
143
377
  *
144
- * @param {EvmTransaction | EvmTransaction[]} tx - The transaction, or an array of multiple transactions to send in batch.
145
- * @param {Pick<EvmErc4337WalletConfig, 'paymasterToken'>} [config] - If set, overrides the 'paymasterToken' option defined in the wallet account configuration.
378
+ * The result is cached internally for up to 2 minutes. If `sendTransaction` is called with the
379
+ * same transaction within that window, the cached fee is reused without an additional RPC round-trip.
380
+ *
381
+ * In a batched call (`tx` passed as `[tx1, tx2, ...]`), only the gas overrides on `tx1` are
382
+ * honored — a UserOperation has a single set of gas fields regardless of how many calls it batches.
383
+ *
384
+ * @param {EvmErc4337Transaction | EvmErc4337Transaction[]} tx - The transaction, or an array of multiple transactions to send in batch.
385
+ * @param {Partial<EvmErc4337WalletPaymasterTokenConfig | EvmErc4337WalletSponsorshipPolicyConfig | EvmErc4337WalletNativeCoinsConfig>} [config] - If set, overrides the given configuration options.
146
386
  * @returns {Promise<Omit<TransactionResult, 'hash'>>} The transaction's quotes.
387
+ * @throws {ConfigurationError} If the override `config` is invalid or has missing required fields.
388
+ * @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.
389
+ * @throws {TransactionError} If the token paymaster reports AA50 (account does not hold the paymaster token).
390
+ * @throws {ConfigurationError} If the account was created from a safe address that is not deployed.
147
391
  */
148
392
  async quoteSendTransaction (tx, config) {
149
- const { paymasterToken } = config ?? this._config
393
+ const mergedConfig = { ...this._config, ...config }
150
394
 
151
- const fee = await this._getUserOperationGasCost([tx].flat(), {
152
- paymasterTokenAddress: paymasterToken.address,
153
- amountToApprove: BigInt(Number.MAX_SAFE_INTEGER)
154
- })
395
+ if (config) {
396
+ this._validateConfig(mergedConfig)
397
+ }
155
398
 
156
- return { fee: BigInt(fee) }
399
+ const { isSponsored } = mergedConfig
400
+
401
+ if (isSponsored) {
402
+ return { fee: 0n }
403
+ }
404
+
405
+ const gasCostResult = await this._getUserOperationGasCost([tx].flat(), mergedConfig)
406
+
407
+ const fee = BigInt(gasCostResult.fee) * FEE_TOLERANCE_COEFFICIENT / 100n
408
+
409
+ return { fee }
157
410
  }
158
411
 
159
412
  /**
160
413
  * Quotes the costs of a transfer operation.
161
414
  *
162
- * @param {TransferOptions} options - The transfer's options.
163
- * @param {Pick<EvmErc4337WalletConfig, 'paymasterToken'>} [config] - If set, overrides the 'paymasterToken' option defined in the wallet account configuration.
415
+ * The result is cached internally for up to 2 minutes. If `transfer` is called with the
416
+ * same transaction within that window, the cached fee is reused without an additional RPC round-trip.
417
+ *
418
+ * @param {EvmErc4337TransferOptions} options - The transfer's options, including any UserOperationV7 gas/fee overrides to apply to the underlying transaction.
419
+ * @param {Partial<EvmErc4337WalletPaymasterTokenConfig | EvmErc4337WalletSponsorshipPolicyConfig | EvmErc4337WalletNativeCoinsConfig>} [config] - If set, overrides the given configuration options.
164
420
  * @returns {Promise<Omit<TransferResult, 'hash'>>} The transfer's quotes.
421
+ * @throws {ConfigurationError} If the override `config` is invalid or has missing required fields.
422
+ * @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.
423
+ * @throws {TransactionError} If the token paymaster reports AA50 (account does not hold the paymaster token).
424
+ * @throws {ConfigurationError} If the account was created from a safe address that is not deployed.
165
425
  */
166
426
  async quoteTransfer (options, config) {
167
- const tx = await WalletAccountReadOnlyEvm._getTransferTransaction(options)
427
+ const tx = await WalletAccountReadOnlyEvmErc4337._getTransferTransaction(options)
168
428
 
169
- const result = await this.quoteSendTransaction(tx, config)
170
-
171
- return result
429
+ return await this.quoteSendTransaction(tx, config)
172
430
  }
173
431
 
174
432
  /**
175
433
  * Returns a transaction's receipt.
176
434
  *
435
+ * @deprecated Use {@link getTransaction} instead, which returns a normalized, finality-based receipt. The raw ethers receipt and the user operation receipt remain available on its `receipt` and `userOperationReceipt` properties.
177
436
  * @param {string} hash - The user operation hash.
178
437
  * @returns {Promise<EvmTransactionReceipt | null>} – The receipt, or null if the transaction has not been included in a block yet.
179
438
  */
180
439
  async getTransactionReceipt (hash) {
181
- const safe4337Pack = await this._getSafe4337Pack()
182
-
440
+ const bundler = this._getBundler()
183
441
  const evmReadOnlyAccount = await this._getEvmReadOnlyAccount()
184
442
 
185
- const { transactionHash } = await safe4337Pack.getUserOperationByHash(hash)
443
+ const result = await bundler.getUserOperationByHash(hash)
444
+ if (!result || !result.transactionHash) return null
186
445
 
187
- if (!transactionHash) {
188
- return null
446
+ return await evmReadOnlyAccount.getTransactionReceipt(result.transactionHash)
447
+ }
448
+
449
+ /**
450
+ * Returns a normalized, finality-based receipt for a user operation. Finality and confirmations come from the bundling transaction; `success` and `fee` come from the user operation.
451
+ *
452
+ * @param {string} hash - The user operation hash.
453
+ * @returns {Promise<TransactionReceipt & EvmErc4337TransactionDetails>} The normalized receipt.
454
+ * @throws {ValueError} If the hash is not a valid user operation hash.
455
+ * @throws {NoSuchElementError} If no user operation has been found for the given hash.
456
+ */
457
+ async getTransaction (hash) {
458
+ if (!isHexString(hash, 32)) {
459
+ throw new ValueError(`Invalid user operation hash: '${hash}'.`)
460
+ }
461
+
462
+ const bundler = this._getBundler()
463
+
464
+ const userOpByHash = await bundler.getUserOperationByHash(hash)
465
+ if (!userOpByHash) {
466
+ throw new NoSuchElementError(`No user operation found for '${hash}'.`)
467
+ }
468
+
469
+ if (!userOpByHash.transactionHash) {
470
+ return {
471
+ hash,
472
+ finality: 'pending',
473
+ confirmations: 0,
474
+ receipt: null,
475
+ userOperationReceipt: null
476
+ }
189
477
  }
190
478
 
191
- return await evmReadOnlyAccount.getTransactionReceipt(transactionHash)
479
+ const [evmReadOnlyAccount, userOpReceipt] = await Promise.all([
480
+ this._getEvmReadOnlyAccount(),
481
+ bundler.getUserOperationReceipt(hash)
482
+ ])
483
+
484
+ const info = await evmReadOnlyAccount.getTransaction(userOpByHash.transactionHash)
485
+
486
+ return {
487
+ ...info,
488
+ hash,
489
+ success: userOpReceipt ? userOpReceipt.success : info.success,
490
+ fee: userOpReceipt ? userOpReceipt.actualGasCost : info.fee,
491
+ userOperationReceipt: userOpReceipt
492
+ }
493
+ }
494
+
495
+ /**
496
+ * Blocks until a user operation reaches a terminal state (the requested finality target or `dropped`), or times out.
497
+ *
498
+ * @param {string} hash - The user operation hash.
499
+ * @param {WaitForTransactionOptions} [options] - The wait options.
500
+ * @returns {Promise<TransactionReceipt & EvmErc4337TransactionDetails>} The terminal receipt: the finality target reached (inspect `success` to tell success from revert), or `dropped`.
501
+ * @throws {TimeoutError} If the target is not reached before the timeout.
502
+ */
503
+ async waitForTransaction (hash, options = {}) {
504
+ return await super.waitForTransaction(hash, options)
505
+ }
506
+
507
+ /**
508
+ * Overrides the base default to allow for slower ERC-4337 bundling, inclusion, and confirmation.
509
+ *
510
+ * @type {number}
511
+ */
512
+ get defaultWaitTimeout () {
513
+ return 180000
514
+ }
515
+
516
+ /**
517
+ * Returns a user operation's receipt.
518
+ *
519
+ * @param {string} hash - The user operation hash.
520
+ * @returns {Promise<UserOperationReceipt | null>} – The receipt, or null if the user operation has not been included in a block yet.
521
+ */
522
+ async getUserOperationReceipt (hash) {
523
+ const bundler = this._getBundler()
524
+
525
+ return await bundler.getUserOperationReceipt(hash)
192
526
  }
193
527
 
194
528
  /**
195
529
  * Returns the current allowance for the given token and spender.
196
- * @param {string} token - The token’s address.
197
- * @param {string} spender - The spender’s address.
198
- * @returns {Promise<bigint>} - The allowance.
530
+ *
531
+ * @param {string} token - The token's address.
532
+ * @param {string} spender - The spender's address.
533
+ * @returns {Promise<bigint>} The allowance.
199
534
  */
200
535
  async getAllowance (token, spender) {
201
536
  const readOnlyAccount = await this._getEvmReadOnlyAccount()
@@ -204,48 +539,175 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
204
539
  }
205
540
 
206
541
  /**
207
- * Returns the safe's erc-4337 pack of the account.
542
+ * Verifies a message's signature.
543
+ *
544
+ * @param {string} message - The original message.
545
+ * @param {string} signature - The signature to verify.
546
+ * @throws {UnsupportedOperationError} If the account was created from a safe address, whose owner is unknown.
547
+ * @returns {Promise<boolean>} True if the signature is valid.
548
+ */
549
+ async verify (message, signature) {
550
+ if (this._ownerAccountAddress === undefined) {
551
+ throw new UnsupportedOperationError('verify(message, signature)')
552
+ }
553
+
554
+ const evmReadOnlyAccount = new WalletAccountReadOnlyEvm(this._ownerAccountAddress, {
555
+ ...this._config,
556
+ provider: this._provider
557
+ })
558
+ return await evmReadOnlyAccount.verify(message, signature)
559
+ }
560
+
561
+ /**
562
+ * Verifies a typed data signature.
563
+ *
564
+ * @param {TypedData} typedData - The typed data to verify.
565
+ * @param {string} signature - The signature to verify.
566
+ * @throws {UnsupportedOperationError} If the account was created from a safe address, whose owner is unknown.
567
+ * @returns {Promise<boolean>} True if the signature is valid.
568
+ */
569
+ async verifyTypedData (typedData, signature) {
570
+ if (this._ownerAccountAddress === undefined) {
571
+ throw new UnsupportedOperationError('verifyTypedData(typedData, signature)')
572
+ }
573
+
574
+ const evmReadOnlyAccount = new WalletAccountReadOnlyEvm(this._ownerAccountAddress, {
575
+ ...this._config,
576
+ provider: this._provider
577
+ })
578
+
579
+ return await evmReadOnlyAccount.verifyTypedData(typedData, signature)
580
+ }
581
+
582
+ /**
583
+ * Validates the configuration to ensure all required fields are present.
208
584
  *
209
585
  * @protected
210
- * @returns {Promise<Safe4337Pack>} The safe's erc-4337 pack.
211
- */
212
- async _getSafe4337Pack () {
213
- if (!this._safe4337Pack) {
214
- this._safe4337Pack = await Safe4337Pack.init({
215
- provider: this._config.provider,
216
- bundlerUrl: this._config.bundlerUrl,
217
- safeModulesVersion: this._config.safeModulesVersion,
218
- options: {
219
- owners: [this._ownerAccountAddress],
220
- threshold: 1,
221
- saltNonce: SALT_NONCE
222
- },
223
- paymasterOptions: {
224
- paymasterUrl: this._config.paymasterUrl,
225
- paymasterAddress: this._config.paymasterAddress,
226
- paymasterTokenAddress: this._config.paymasterToken.address,
227
- skipApproveTransaction: true
228
- },
229
- customContracts: {
230
- entryPointAddress: this._config.entryPointAddress
231
- }
232
- })
586
+ * @param {Omit<EvmErc4337WalletConfig, 'transferMaxFee' | 'transactionMaxFee'>} config - The configuration to validate.
587
+ * @throws {ConfigurationError} If the configuration is invalid or has missing required fields.
588
+ * @returns {void}
589
+ */
590
+ _validateConfig (config) {
591
+ const { isSponsored, useNativeCoins, paymasterUrl, paymasterAddress, paymasterToken } = config
592
+ const missingFields = []
593
+
594
+ if (isSponsored && useNativeCoins) {
595
+ throw new ConfigurationError("Cannot use both 'isSponsored: true' and 'useNativeCoins: true'. Please use only one.")
233
596
  }
234
597
 
235
- return this._safe4337Pack
598
+ if (!isSponsored && !useNativeCoins) {
599
+ if (!paymasterUrl) {
600
+ missingFields.push('paymasterUrl')
601
+ }
602
+ if (!paymasterAddress) {
603
+ missingFields.push('paymasterAddress')
604
+ }
605
+ if (!paymasterToken) {
606
+ missingFields.push('paymasterToken')
607
+ }
608
+
609
+ if (missingFields.length > 0) {
610
+ throw new ConfigurationError(`Missing required paymaster token configuration fields: ${missingFields.join(', ')}.`)
611
+ }
612
+ } else if (isSponsored) {
613
+ if (!paymasterUrl) {
614
+ missingFields.push('paymasterUrl')
615
+ }
616
+
617
+ if (missingFields.length > 0) {
618
+ throw new ConfigurationError(`Missing required sponsorship policy configuration fields: ${missingFields.join(', ')}.`)
619
+ }
620
+ }
236
621
  }
237
622
 
238
623
  /**
239
- * Returns the chain id.
624
+ * Builds a safe account instance for the current owner.
625
+ *
626
+ * @protected
627
+ * @param {Omit<EvmErc4337WalletConfig, 'transferMaxFee' | 'transactionMaxFee'>} [config] - The wallet configuration. Defaults to the instance configuration.
628
+ * @throws {ConfigurationError} If the account was created from a safe address that is not deployed.
629
+ * @returns {Promise<SafeAccountV0_3_0>} The safe account instance.
630
+ */
631
+ async _getSmartAccount (config = this._config) {
632
+ if (this._deployedSmartAccount) return this._deployedSmartAccount
633
+
634
+ const overrides = WalletAccountReadOnlyEvmErc4337._getInitCodeOverrides(config)
635
+ const safeAddress = await this.getAddress()
636
+
637
+ if (await SafeAccount030.isDeployed(safeAddress, this._eip1193Provider)) {
638
+ this._deployedSmartAccount = new SafeAccount030(safeAddress, overrides)
639
+ return this._deployedSmartAccount
640
+ }
641
+
642
+ if (this._ownerAccountAddress === undefined) {
643
+ throw new ConfigurationError(`The safe at '${safeAddress}' is not deployed. Deploying it requires the owner's address, which an account created from a safe address does not have.`)
644
+ }
645
+
646
+ return SafeAccount030.initializeNewAccount([this._ownerAccountAddress], overrides)
647
+ }
648
+
649
+ /**
650
+ * Builds the RPC transport for an AbstractionKit client (Bundler / Erc7677Paymaster).
651
+ *
652
+ * When `headers` are provided, the transport injects them on every request (e.g.
653
+ * `{ Authorization: 'Bearer <key>' }` for authenticated bundlers/paymasters).
654
+ *
655
+ * @protected
656
+ * @param {string} url - The bundler or paymaster RPC url.
657
+ * @param {Record<string, string>} [headers] - Optional HTTP headers to inject on every request.
658
+ * @returns {HttpTransport} An HttpTransport for the url, carrying the headers when set.
659
+ */
660
+ static _rpcTarget (url, headers) {
661
+ return new HttpTransport(url, headers ? { headers } : {})
662
+ }
663
+
664
+ /**
665
+ * Returns an AbstractionKit Bundler for querying UserOperations.
666
+ *
667
+ * @protected
668
+ * @returns {Bundler} The bundler.
669
+ */
670
+ _getBundler () {
671
+ if (!this._bundler) {
672
+ const rpc = WalletAccountReadOnlyEvmErc4337._rpcTarget(this._config.bundlerUrl, this._config.bundlerHeaders)
673
+ this._bundler = new Bundler(rpc)
674
+ }
675
+ return this._bundler
676
+ }
677
+
678
+ /** @private */
679
+ _getPaymaster (url, headers, options = {}) {
680
+ const key = JSON.stringify([url, headers ?? null])
681
+ if (!this._paymasters.has(key)) {
682
+ const provider = WalletAccountReadOnlyEvmErc4337._detectProvider(url)
683
+ const rpc = WalletAccountReadOnlyEvmErc4337._rpcTarget(url, headers)
684
+ this._paymasters.set(key, new Erc7677Paymaster(rpc, { ...options, provider }))
685
+ }
686
+ return this._paymasters.get(key)
687
+ }
688
+
689
+ /**
690
+ * Returns the chain id, asserting the provider is on the configured network.
691
+ *
692
+ * The value is read once from the provider (`eth_chainId`), checked against
693
+ * `config.chainId`, and cached. Every UserOperation is built and signed against
694
+ * this value, so a provider reporting a different chain than the one the
695
+ * application configured must fail here rather than produce a signature for the
696
+ * wrong network.
240
697
  *
241
698
  * @protected
242
699
  * @returns {Promise<bigint>} - The chain id.
700
+ * @throws {ConfigurationError} If the provider's chain id does not match `config.chainId`.
243
701
  */
244
702
  async _getChainId () {
245
703
  if (!this._chainId) {
246
- const evmReadOnlyAccount = await this._getEvmReadOnlyAccount()
704
+ const chainId = BigInt(await this._eip1193Provider.request({ method: 'eth_chainId' }))
247
705
 
248
- const { chainId } = await evmReadOnlyAccount._provider.getNetwork()
706
+ if (this._config.chainId !== undefined && chainId !== BigInt(this._config.chainId)) {
707
+ throw new ConfigurationError(
708
+ `Provider is on chain ${chainId} but the wallet is configured for chain ${this._config.chainId}`
709
+ )
710
+ }
249
711
 
250
712
  this._chainId = chainId
251
713
  }
@@ -253,66 +715,312 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
253
715
  return this._chainId
254
716
  }
255
717
 
718
+ /**
719
+ * Adapts an ethers provider (or failover aggregate) to the EIP-1193 interface required by
720
+ * abstractionkit (Safe4337Pack), without constructing a new provider. Already-EIP-1193 objects
721
+ * (e.g. a browser wallet or a `BrowserProvider`) are returned as-is; ethers providers are wrapped
722
+ * so `request` forwards to `send`, reusing the same underlying connection.
723
+ *
724
+ * @protected
725
+ * @param {Provider | Eip1193Provider} provider - The ethers provider (or EIP-1193 provider) to adapt.
726
+ * @returns {Eip1193Provider} An EIP-1193-compatible provider that reuses the given client.
727
+ */
728
+ static _asEip1193 (provider) {
729
+ if (typeof provider.request === 'function') {
730
+ return provider
731
+ }
732
+
733
+ return {
734
+ request ({ method, params }) {
735
+ return provider.send(method, params ?? [])
736
+ }
737
+ }
738
+ }
739
+
740
+ /**
741
+ * Builds the EIP-1193 view that abstractionkit needs. A caller-supplied EIP-1193 provider is
742
+ * reused directly (so abstractionkit talks to it without an extra `BrowserProvider` round-trip);
743
+ * otherwise the shared ethers provider is adapted so `request` forwards to `send`. Both share the
744
+ * same underlying connection as {@link _provider}.
745
+ *
746
+ * @protected
747
+ * @param {Provider} provider - The shared ethers provider built from `config`.
748
+ * @param {Omit<EvmErc4337WalletConfig, 'transferMaxFee' | 'transactionMaxFee'>} config - The configuration object.
749
+ * @returns {Eip1193Provider} The EIP-1193 provider that reuses the given connection.
750
+ */
751
+ static _buildEip1193Provider (provider, config) {
752
+ const { provider: configured } = config
753
+ const source = configured && typeof configured.request === 'function' ? configured : provider
754
+
755
+ return WalletAccountReadOnlyEvmErc4337._asEip1193(source)
756
+ }
757
+
758
+ /**
759
+ * Builds the single shared ethers provider from the configuration. Construction (url ->
760
+ * `JsonRpcProvider`, EIP-1193 -> `BrowserProvider`, array -> failover) and the reuse of an
761
+ * already-built provider are delegated to wdk-wallet-evm, so a manager can build one instance
762
+ * and share it with every account.
763
+ *
764
+ * @protected
765
+ * @param {Omit<EvmErc4337WalletConfig, 'transferMaxFee' | 'transactionMaxFee'>} [config] - The configuration object.
766
+ * @returns {Provider} The shared provider.
767
+ * @throws {ValueError} If the `provider` option is set to an empty array.
768
+ */
769
+ _buildProvider (config = this._config) {
770
+ if (Array.isArray(config.provider) && config.provider.length === 0) {
771
+ throw new ValueError("The 'provider' option cannot be set to an empty list.")
772
+ }
773
+
774
+ return WalletAccountReadOnlyEvm._buildProvider(config)
775
+ }
776
+
256
777
  /** @private */
257
778
  async _getEvmReadOnlyAccount () {
258
- const address = await this.getAddress()
779
+ if (!this._evmReadOnlyAccount) {
780
+ const address = await this.getAddress()
781
+ this._evmReadOnlyAccount = new WalletAccountReadOnlyEvm(address, {
782
+ ...this._config,
783
+ provider: this._provider
784
+ })
785
+ }
786
+
787
+ return this._evmReadOnlyAccount
788
+ }
789
+
790
+ /**
791
+ * Converts EVM transactions to AbstractionKit MetaTransaction calls.
792
+ *
793
+ * @protected
794
+ * @param {EvmErc4337Transaction[]} txs - The transactions to convert.
795
+ * @returns {MetaTransaction[]} The calls array for createUserOperation.
796
+ */
797
+ static _toMetaTransactions (txs) {
798
+ return txs.map(tx => ({
799
+ to: tx.to,
800
+ value: tx.value !== undefined ? BigInt(tx.value) : 0n,
801
+ data: tx.data ?? '0x'
802
+ }))
803
+ }
804
+
805
+ /**
806
+ * Builds the init code overrides from the wallet configuration.
807
+ *
808
+ * @protected
809
+ * @param {Pick<EvmErc4337WalletConfig, 'safeModulesVersion' | 'onChainIdentifier'>} config - The wallet configuration fields used for init code generation.
810
+ * @returns {InitCodeOverrides} The init code overrides for SafeAccount creation.
811
+ */
812
+ static _getInitCodeOverrides (config) {
813
+ const { safeModulesVersion, onChainIdentifier } = config
814
+ const modules = SAFE_MODULES_MAP[safeModulesVersion]
815
+
816
+ const overrides = {
817
+ c2Nonce: BigInt(SALT_NONCE),
818
+ entrypointAddress: ENTRYPOINT_V7,
819
+ safe4337ModuleAddress: modules.safe4337ModuleAddress,
820
+ safeModuleSetupAddress: modules.safeModuleSetupAddress
821
+ }
259
822
 
260
- const evmReadOnlyAccount = new WalletAccountReadOnlyEvm(address, this._config)
823
+ if (onChainIdentifier) {
824
+ overrides.onChainIdentifierParams = typeof onChainIdentifier === 'string'
825
+ ? { project: onChainIdentifier }
826
+ : onChainIdentifier
827
+ }
261
828
 
262
- return evmReadOnlyAccount
829
+ return overrides
263
830
  }
264
831
 
265
- /** @private */
266
- async _getFeeEstimator () {
267
- if (!this._feeEstimator) {
268
- const chainId = await this._getChainId()
832
+ /**
833
+ * Builds a UserOperation with paymaster fields applied.
834
+ *
835
+ * @protected
836
+ * @param {MetaTransaction[]} calls - The meta-transactions to include in the UserOperation.
837
+ * @param {Omit<EvmErc4337WalletConfig, 'transferMaxFee' | 'transactionMaxFee'>} config - The wallet configuration.
838
+ * @param {EvmErc4337GasOverrides & Nonce} [txOverrides] - Optional UserOperationV7 gas overrides extracted from the input transaction(s), plus an optional explicit lane `nonce`.
839
+ * @returns {Promise<BuiltUserOperation>} The built operation, signing context, and (in token mode) the paymaster quote.
840
+ * @throws {ConfigurationError} If the account was created from a safe address that is not deployed.
841
+ */
842
+ async _buildUserOperation (calls, config, txOverrides = {}) {
843
+ const chainId = await this._getChainId()
844
+ const smartAccount = await this._getSmartAccount(config)
269
845
 
270
- this._feeEstimator = new GenericFeeEstimator(
271
- this._config.provider,
272
- `0x${chainId.toString(16)}`
273
- )
846
+ const mode = WalletAccountReadOnlyEvmErc4337._resolvePaymasterMode(config)
847
+ const provider = mode !== PaymasterMode.NATIVE
848
+ ? WalletAccountReadOnlyEvmErc4337._detectProvider(config.paymasterUrl)
849
+ : null
850
+
851
+ const gasPrice = await this._fetchBundlerGasPrice(config.bundlerUrl, config.bundlerHeaders)
852
+
853
+ const feePairOverridden = txOverrides.maxFeePerGas !== undefined || txOverrides.maxPriorityFeePerGas !== undefined
854
+ const overrides = feePairOverridden
855
+ ? { ...txOverrides }
856
+ : { ...gasPrice, ...txOverrides }
857
+
858
+ const bundlerRpc = WalletAccountReadOnlyEvmErc4337._rpcTarget(config.bundlerUrl, config.bundlerHeaders)
859
+ const baseUserOp = (mode === PaymasterMode.NATIVE || provider === 'candide')
860
+ ? await smartAccount.createUserOperation(calls, this._eip1193Provider, bundlerRpc, overrides)
861
+ : await smartAccount.createUserOperation(calls, this._eip1193Provider, undefined, { skipGasEstimation: true, ...overrides })
862
+
863
+ if (mode === PaymasterMode.NATIVE) {
864
+ return { userOp: baseUserOp, smartAccount, mode, chainId }
274
865
  }
275
866
 
276
- return this._feeEstimator
867
+ const { userOp, tokenQuote } = await this._applyPaymasterToUserOp({
868
+ mode, smartAccount, userOp: baseUserOp, config, chainId, txOverrides
869
+ })
870
+ return { userOp, smartAccount, mode, chainId, tokenQuote }
277
871
  }
278
872
 
279
- /** @private */
280
- async _getUserOperationGasCost (txs, options) {
281
- const safe4337Pack = await this._getSafe4337Pack()
873
+ /**
874
+ * Returns an evm transaction to execute the given token transfer, carrying any UserOperationV7
875
+ * gas overrides set on the options.
876
+ *
877
+ * @protected
878
+ * @param {EvmErc4337TransferOptions} options - The transfer's options, including any gas/fee overrides to carry onto the transaction.
879
+ * @returns {Promise<EvmErc4337Transaction>} The ERC-20 transfer call as an evm transaction, with the options' gas overrides applied.
880
+ */
881
+ static async _getTransferTransaction (options) {
882
+ const tx = await WalletAccountReadOnlyEvm._getTransferTransaction(options)
282
883
 
283
- const address = await this.getAddress()
884
+ return { ...tx, ...WalletAccountReadOnlyEvmErc4337._extractGasOverrides(options) }
885
+ }
284
886
 
285
- try {
286
- const safeOperation = await safe4337Pack.createTransaction({
287
- transactions: txs.map(tx => ({ from: address, ...tx })),
288
- options: {
289
- feeEstimator: await this._getFeeEstimator(),
290
- ...options
291
- }
292
- })
887
+ /**
888
+ * Extracts the optional UserOperationV7 gas overrides from a transaction or an options object.
889
+ *
890
+ * Only the fields actually consumed by AbstractionKit's `CreateUserOperationOverrides`
891
+ * are picked. Numeric values are coerced to bigint.
892
+ *
893
+ * @protected
894
+ * @param {EvmErc4337GasOverrides} [source] - The transaction or options object to read overrides from.
895
+ * @returns {EvmErc4337GasOverrides} The overrides object (empty if `source` is falsy or has no override fields).
896
+ */
897
+ static _extractGasOverrides (source) {
898
+ const overrides = {}
899
+ if (!source) return overrides
293
900
 
294
- const {
295
- callGasLimit,
296
- verificationGasLimit,
297
- preVerificationGas,
298
- paymasterVerificationGasLimit,
299
- paymasterPostOpGasLimit,
300
- maxFeePerGas
301
- } = safeOperation.userOperation
901
+ const fields = ['callGasLimit', 'verificationGasLimit', 'preVerificationGas', 'maxFeePerGas', 'maxPriorityFeePerGas']
902
+ for (const field of fields) {
903
+ if (source[field] !== undefined) overrides[field] = BigInt(source[field])
904
+ }
302
905
 
303
- const gasCost = Number((callGasLimit + verificationGasLimit + preVerificationGas + paymasterVerificationGasLimit + paymasterPostOpGasLimit) * maxFeePerGas)
906
+ return overrides
907
+ }
304
908
 
305
- const exchangeRate = await safe4337Pack.getTokenExchangeRate(options.paymasterTokenAddress)
909
+ /**
910
+ * Determines whether an error from AbstractionKit is an AA50 paymaster funds error.
911
+ *
912
+ * Checked via `aaCode` first; falls back to matching the substring in `message` for
913
+ * bundlers/paymasters that don't populate `aaCode`.
914
+ *
915
+ * @protected
916
+ * @param {unknown} err - The error to inspect.
917
+ * @returns {boolean} `true` if `err` represents an AA50 error.
918
+ */
919
+ static _isAA50Error (err) {
920
+ return err instanceof AbstractionKitError && (err.aaCode === 'AA50' || err.message.includes('AA50'))
921
+ }
306
922
 
307
- const gasCostInPaymasterToken = Math.ceil(gasCost * exchangeRate / 10 ** 18)
923
+ /**
924
+ * Builds a UserOperation and returns its estimated gas cost.
925
+ *
926
+ * Returns the cost in the paymaster token when a token quote is available, otherwise in
927
+ * native wei. Used by `quoteSendTransaction` and reused by `sendTransaction` via the cache.
928
+ *
929
+ * In a batched call, only `txs[0]`'s gas overrides are honored — a UserOperation
930
+ * carries a single set of gas fields regardless of how many calls it batches.
931
+ *
932
+ * @protected
933
+ * @param {EvmErc4337Transaction[]} txs - The EVM transactions to include in the UserOperation.
934
+ * @param {Omit<EvmErc4337WalletConfig, 'transferMaxFee' | 'transactionMaxFee'>} config - The wallet configuration to use for the build.
935
+ * @returns {Promise<BuiltUserOperation & Omit<TransactionResult, 'hash'>>} The built operation plus its raw fee (no tolerance buffer applied).
936
+ * @throws {TransactionError} If the token paymaster reports AA50 (account does not hold the paymaster token).
937
+ */
938
+ async _getUserOperationGasCost (txs, config) {
939
+ const calls = WalletAccountReadOnlyEvmErc4337._toMetaTransactions(txs)
940
+ const txOverrides = WalletAccountReadOnlyEvmErc4337._extractGasOverrides(txs[0])
941
+
942
+ try {
943
+ const buildResult = await this._buildUserOperation(calls, config, txOverrides)
308
944
 
309
- return gasCostInPaymasterToken
945
+ const fee = buildResult.tokenQuote
946
+ ? buildResult.tokenQuote.tokenCost
947
+ : calculateUserOperationMaxGasCost(buildResult.userOp)
948
+
949
+ return { fee, ...buildResult }
310
950
  } catch (error) {
311
- if (error.message.includes('AA50')) {
312
- throw new Error('Simulation failed: not enough funds in the safe account to repay the paymaster.')
951
+ if (WalletAccountReadOnlyEvmErc4337._isAA50Error(error)) {
952
+ throw new TransactionError(
953
+ 'Token paymaster requires the account to hold the paymaster token for fee estimation. ' +
954
+ 'Fund the account with the paymaster token before quoting.',
955
+ { reason: TransactionErrorReason.INSUFFICIENT_BALANCE, cause: error }
956
+ )
313
957
  }
314
-
315
958
  throw error
316
959
  }
317
960
  }
961
+
962
+ /** @private */
963
+ static _resolvePaymasterMode (config) {
964
+ if (config.useNativeCoins) return PaymasterMode.NATIVE
965
+ if (config.isSponsored) return PaymasterMode.SPONSORED
966
+ return PaymasterMode.TOKEN
967
+ }
968
+
969
+ /** @private */
970
+ async _fetchBundlerGasPrice (bundlerUrl, bundlerHeaders) {
971
+ if (WalletAccountReadOnlyEvmErc4337._detectProvider(bundlerUrl) !== 'pimlico') return undefined
972
+
973
+ const erc7677 = new Erc7677Paymaster(WalletAccountReadOnlyEvmErc4337._rpcTarget(bundlerUrl, bundlerHeaders))
974
+ const result = await erc7677.sendRPCRequest('pimlico_getUserOperationGasPrice', [])
975
+ if (!result?.fast) return undefined
976
+
977
+ return {
978
+ maxFeePerGas: BigInt(result.fast.maxFeePerGas),
979
+ maxPriorityFeePerGas: BigInt(result.fast.maxPriorityFeePerGas)
980
+ }
981
+ }
982
+
983
+ /** @private */
984
+ static _detectProvider (url) {
985
+ const detected = Erc7677Paymaster.detectProvider(url)
986
+ if (detected) return detected
987
+ if (url?.includes('pimlico')) return 'pimlico'
988
+ if (url?.includes('candide')) return 'candide'
989
+ return null
990
+ }
991
+
992
+ /** @private */
993
+ async _applyPaymasterToUserOp ({ mode, smartAccount, userOp, config, chainId, txOverrides = {} }) {
994
+ const erc7677 = this._getPaymaster(config.paymasterUrl, config.paymasterHeaders, { chainId: BigInt(chainId) })
995
+
996
+ const context = mode === PaymasterMode.TOKEN
997
+ ? { token: config.paymasterToken.address }
998
+ : { sponsorshipPolicyId: config.sponsorshipPolicyId }
999
+
1000
+ const paymasterOverrides = { entrypoint: ENTRYPOINT_V7 }
1001
+ if (txOverrides.callGasLimit !== undefined) paymasterOverrides.callGasLimit = txOverrides.callGasLimit
1002
+ if (txOverrides.verificationGasLimit !== undefined) paymasterOverrides.verificationGasLimit = txOverrides.verificationGasLimit
1003
+ if (txOverrides.preVerificationGas !== undefined) paymasterOverrides.preVerificationGas = txOverrides.preVerificationGas
1004
+
1005
+ const bundlerRpc = WalletAccountReadOnlyEvmErc4337._rpcTarget(config.bundlerUrl, config.bundlerHeaders)
1006
+ const result = await erc7677.createPaymasterUserOperation(
1007
+ smartAccount,
1008
+ userOp,
1009
+ bundlerRpc,
1010
+ context,
1011
+ paymasterOverrides
1012
+ )
1013
+
1014
+ const sponsoredOp = result.userOperation
1015
+
1016
+ if (mode === PaymasterMode.TOKEN && sponsoredOp.paymaster &&
1017
+ sponsoredOp.paymaster.toLowerCase() !== config.paymasterAddress.toLowerCase()) {
1018
+ throw new ConfigurationError(
1019
+ `paymasterAddress mismatch: configured ${config.paymasterAddress} but RPC ${config.paymasterUrl} returned ${sponsoredOp.paymaster}. ` +
1020
+ 'The generated ERC-20 approval would target an unexpected paymaster.'
1021
+ )
1022
+ }
1023
+
1024
+ return { userOp: sponsoredOp, tokenQuote: result.tokenQuote }
1025
+ }
318
1026
  }