@tetherto/wdk-wallet-evm 1.0.0-beta.2 → 1.0.0-beta.20

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,41 +14,101 @@
14
14
 
15
15
  'use strict'
16
16
 
17
- import { WalletAccountReadOnly } from '@tetherto/wdk-wallet'
17
+ import { WalletAccountReadOnly, NoSuchElementError, ProviderRequiredError, ValueError } from '@tetherto/wdk-wallet'
18
18
 
19
- import { BrowserProvider, Contract, JsonRpcProvider } from 'ethers'
19
+ import { BrowserProvider, Contract, Interface, isError, isHexString, JsonRpcProvider, Network, Signature, toQuantity, verifyMessage, verifyTypedData } from 'ethers'
20
+
21
+ import { multicall } from './multicall.js'
22
+
23
+ import FailoverProvider from '@tetherto/wdk-failover-provider'
20
24
 
21
25
  /** @typedef {import('ethers').Provider} Provider */
22
26
  /** @typedef {import('ethers').Eip1193Provider} Eip1193Provider */
27
+ /** @typedef {import('ethers').TypedDataDomain} TypedDataDomain */
28
+ /** @typedef {import('ethers').TypedDataField} TypedDataField */
29
+ /** @typedef {import('ethers').AuthorizationLike} AuthorizationLike */
30
+ /** @typedef {import('ethers').BlobLike} BlobLike */
23
31
  /** @typedef {import('ethers').TransactionReceipt} EvmTransactionReceipt */
32
+ /** @typedef {import('ethers').TransactionResponse} EvmTransactionResponse */
33
+ /** @typedef {import('ethers').TransactionRequest} EvmTransactionRequest */
24
34
 
25
35
  /** @typedef {import('@tetherto/wdk-wallet').TransactionResult} TransactionResult */
26
- /** @typedef {import('@tetherto/wdk-wallet').TransferOptions} TransferOptions */
27
36
  /** @typedef {import('@tetherto/wdk-wallet').TransferResult} TransferResult */
37
+ /** @typedef {import('@tetherto/wdk-wallet').TransactionReceipt} TransactionReceipt */
38
+ /** @typedef {import('@tetherto/wdk-wallet').WaitForTransactionOptions} WaitForTransactionOptions */
39
+ /** @typedef {import('@tetherto/wdk-wallet').TransferOptions} TransferOptions */
40
+
41
+ /**
42
+ * The EVM-specific fields added to a normalized transaction receipt.
43
+ *
44
+ * @typedef {Object} EvmTransactionDetails
45
+ * @property {number} confirmations - The number of confirmations (0 while pending or dropped).
46
+ * @property {EvmTransactionReceipt | null} receipt - The native ethers receipt, or null while the transaction is pending or dropped.
47
+ */
48
+
49
+ /**
50
+ * @typedef {Object} TypedData
51
+ * @property {TypedDataDomain} domain - The domain separator.
52
+ * @property {Record<string, TypedDataField[]>} types - The type definitions.
53
+ * @property {Record<string, unknown>} message - The message data.
54
+ */
55
+
56
+ /**
57
+ * @typedef {Object} DelegationInfo
58
+ * @property {boolean} isDelegated - Whether the account has an active ERC-7702 delegation.
59
+ * @property {string | null} delegateAddress - The address of the delegate contract, or null if not delegated.
60
+ */
28
61
 
29
62
  /**
30
63
  * @typedef {Object} EvmTransaction
31
- * @property {string} to - The transaction's recipient.
64
+ * @property {string | null} [to] - The transaction's recipient. Omit or pass null to deploy a contract.
32
65
  * @property {number | bigint} value - The amount of ethers to send to the recipient (in weis).
33
66
  * @property {string} [data] - The transaction's data in hex format.
34
67
  * @property {number | bigint} [gasLimit] - The maximum amount of gas this transaction is permitted to use.
35
68
  * @property {number | bigint} [gasPrice] - The price (in wei) per unit of gas this transaction will pay.
36
69
  * @property {number | bigint} [maxFeePerGas] - The maximum price (in wei) per unit of gas this transaction will pay for the combined [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) block's base fee and this transaction's priority fee.
37
70
  * @property {number | bigint} [maxPriorityFeePerGas] - The price (in wei) per unit of gas this transaction will allow in addition to the [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) block's base fee to bribe miners into giving this transaction priority. This is included in the maxFeePerGas, so this will not affect the total maximum cost set with maxFeePerGas.
71
+ * @property {number} [type] - The transaction type (e.g. 4 for ERC-7702).
72
+ * @property {number} [nonce] - The transaction nonce.
73
+ * @property {number | bigint} [chainId] - The chain ID of the network.
74
+ * @property {number | bigint} [maxFeePerBlobGas] - The maximum price (in wei) per unit of blob gas this transaction will pay for [EIP-4844](https://eips.ethereum.org/EIPS/eip-4844) blob data. Required for type 3 (blob) transactions.
75
+ * @property {BlobLike[]} [blobs] - The blobs of an [EIP-4844](https://eips.ethereum.org/EIPS/eip-4844) type 3 transaction.
76
+ * @property {string[]} [blobVersionedHashes] - The versioned hashes of the blobs of an [EIP-4844](https://eips.ethereum.org/EIPS/eip-4844) type 3 transaction.
77
+ * @property {AuthorizationLike[]} [authorizationList] - An optional list of ERC-7702 signed authorizations for type 4 transactions.
78
+ */
79
+
80
+ /**
81
+ * The gas and fee fields of an evm transaction that can be set on transfer and approve options.
82
+ *
83
+ * @typedef {Pick<EvmTransaction, 'gasLimit' | 'gasPrice' | 'maxFeePerGas' | 'maxPriorityFeePerGas'>} EvmGasOverrides
84
+ */
85
+
86
+ /**
87
+ * The options of a token transfer, extended with the optional gas overrides and ERC-7702 authorizations of an evm
88
+ * transaction.
89
+ *
90
+ * @typedef {TransferOptions & EvmGasOverrides & Pick<EvmTransaction, 'authorizationList'>} EvmTransferOptions
38
91
  */
39
92
 
40
93
  /**
41
94
  * @typedef {Object} EvmWalletConfig
42
- * @property {string | Eip1193Provider} [provider] - The url of the rpc provider, or an instance of a class that implements eip-1193.
95
+ * @property {string | Provider | Eip1193Provider | Array<string | Provider | Eip1193Provider>} [provider] - The url of the rpc provider, an already-built ethers provider (e.g. a `JsonRpcProvider` or a failover wrapper), 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. An already-built provider is reused as-is, which lets a manager share a single provider across all the accounts it creates.
96
+ * @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.
97
+ * @property {number} [chainId] - The chain ID of the network. When provided, skips automatic chain ID detection from the provider.
43
98
  * @property {number | bigint} [transferMaxFee] - The maximum fee amount for transfer operations.
99
+ * @property {number | bigint} [transactionMaxFee] - The maximum fee amount for sendTransaction and signTransaction operations.
44
100
  */
45
101
 
102
+ const DELEGATION_DESIGNATOR_PREFIX = '0xef0100'
103
+
104
+ const DELEGATION_DESIGNATOR_LENGTH = 48
105
+
46
106
  export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
47
107
  /**
48
108
  * Creates a new evm read-only wallet account.
49
109
  *
50
110
  * @param {string} address - The account's address.
51
- * @param {Omit<EvmWalletConfig, 'transferMaxFee'>} [config] - The configuration object.
111
+ * @param {Omit<EvmWalletConfig, 'transferMaxFee' | 'transactionMaxFee'>} [config] - The configuration object.
52
112
  */
53
113
  constructor (address, config = { }) {
54
114
  super(address)
@@ -57,33 +117,97 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
57
117
  * The read-only wallet account configuration.
58
118
  *
59
119
  * @protected
60
- * @type {Omit<EvmWalletConfig, 'transferMaxFee'>}
120
+ * @type {Omit<EvmWalletConfig, 'transferMaxFee' | 'transactionMaxFee'>}
61
121
  */
62
122
  this._config = config
63
123
 
64
- const { provider } = config
124
+ /**
125
+ * An ethers provider to interact with a node of the blockchain.
126
+ *
127
+ * @protected
128
+ * @type {Provider | undefined}
129
+ */
130
+ this._provider = WalletAccountReadOnlyEvm._buildProvider(config)
131
+ }
132
+
133
+ /**
134
+ * Whether a value is an EIP-1193 provider (e.g. a browser wallet).
135
+ *
136
+ * @protected
137
+ * @param {string | Eip1193Provider | Provider} value - The value to inspect.
138
+ * @returns {boolean} True if the value is an EIP-1193 provider.
139
+ */
140
+ static _isEip1193Provider (value) {
141
+ return typeof value.request === 'function'
142
+ }
143
+
144
+ /**
145
+ * Builds an ethers provider from the wallet configuration:
146
+ * - a url string -> a new `JsonRpcProvider`
147
+ * - an already-built ethers provider (or failover wrapper) -> reused as-is
148
+ * - anything else (EIP-1193 / browser wallet) -> wrapped in a `BrowserProvider`
149
+ * - an array of the above -> a `FailoverProvider` across each entry
150
+ *
151
+ * @protected
152
+ * @param {Omit<EvmWalletConfig, 'transferMaxFee' | 'transactionMaxFee'>} [config] - The configuration object.
153
+ * @returns {Provider | undefined} The provider, or undefined if none is configured.
154
+ */
155
+ static _buildProvider (config = {}) {
156
+ const { provider, retries = 3 } = config
157
+ const network = config.chainId ? Network.from(config.chainId) : undefined
158
+ const providerOpts = config.chainId ? { staticNetwork: true } : undefined
159
+
160
+ const toOption = (entry) => {
161
+ if (typeof entry === 'string') {
162
+ return new JsonRpcProvider(entry, network, providerOpts)
163
+ }
164
+
165
+ if (WalletAccountReadOnlyEvm._isEip1193Provider(entry)) {
166
+ return new BrowserProvider(entry)
167
+ }
168
+
169
+ return entry
170
+ }
171
+
172
+ if (Array.isArray(provider)) {
173
+ if (provider.length === 0) {
174
+ return undefined
175
+ }
176
+
177
+ const failoverProvider = new FailoverProvider({ retries })
178
+
179
+ for (const entry of provider) {
180
+ failoverProvider.addProvider(toOption(entry))
181
+ }
182
+
183
+ return failoverProvider.initialize()
184
+ }
65
185
 
66
186
  if (provider) {
67
- /**
68
- * An ethers provider to interact with a node of the blockchain.
69
- *
70
- * @protected
71
- * @type {Provider | undefined}
72
- */
73
- this._provider = typeof provider === 'string'
74
- ? new JsonRpcProvider(provider)
75
- : new BrowserProvider(provider)
187
+ return toOption(provider)
76
188
  }
189
+
190
+ return undefined
191
+ }
192
+
193
+ /**
194
+ * The account's address.
195
+ *
196
+ * @type {string}
197
+ */
198
+ get address () {
199
+ return this._address
77
200
  }
78
201
 
79
202
  /**
80
203
  * Returns the account's eth balance.
81
204
  *
82
205
  * @returns {Promise<bigint>} The eth balance (in weis).
206
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
83
207
  */
84
208
  async getBalance () {
85
209
  if (!this._provider) {
86
- throw new Error('The wallet must be connected to a provider to retrieve balances.')
210
+ throw new ProviderRequiredError('The wallet must be connected to a provider to retrieve balances.')
87
211
  }
88
212
 
89
213
  const address = await this.getAddress()
@@ -98,10 +222,11 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
98
222
  *
99
223
  * @param {string} tokenAddress - The smart contract address of the token.
100
224
  * @returns {Promise<bigint>} The token balance (in base unit).
225
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
101
226
  */
102
227
  async getTokenBalance (tokenAddress) {
103
228
  if (!this._provider) {
104
- throw new Error('The wallet must be connected to a provider to retrieve token balances.')
229
+ throw new ProviderRequiredError('The wallet must be connected to a provider to retrieve token balances.')
105
230
  }
106
231
 
107
232
  const address = await this.getAddress()
@@ -113,36 +238,82 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
113
238
  return balance
114
239
  }
115
240
 
241
+ /**
242
+ * Returns the account balances for multiple tokens.
243
+ *
244
+ * @param {string[]} tokenAddresses - The smart contract addresses of the tokens.
245
+ * @returns {Promise<Record<string, bigint>>} A mapping of token addresses to their balances (in base units).
246
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
247
+ */
248
+ async getTokenBalances (tokenAddresses) {
249
+ if (!this._provider) {
250
+ throw new ProviderRequiredError(
251
+ 'The wallet must be connected to a provider to retrieve token balances.'
252
+ )
253
+ }
254
+
255
+ if (tokenAddresses.length === 0) {
256
+ return {}
257
+ }
258
+
259
+ const address = await this.getAddress()
260
+ const iface = new Interface(['function balanceOf(address owner) view returns (uint256)'])
261
+ const calldata = iface.encodeFunctionData('balanceOf', [address])
262
+
263
+ const calls = tokenAddresses.map(tokenAddress => ({
264
+ to: tokenAddress,
265
+ data: calldata
266
+ }))
267
+
268
+ const results = await multicall(this._provider, calls)
269
+
270
+ return tokenAddresses.reduce((acc, tokenAddress, index) => {
271
+ const result = results[index]
272
+ acc[tokenAddress] = result.status
273
+ ? iface.decodeFunctionResult('balanceOf', result.data)[0]
274
+ : 0n
275
+ return acc
276
+ }, {})
277
+ }
278
+
116
279
  /**
117
280
  * Quotes the costs of a send transaction operation.
118
281
  *
282
+ * The transaction is always simulated through gas estimation, so one that would revert is rejected here instead of
283
+ * reaching the signer. A `gasLimit` set on the transaction replaces the estimated gas in the quote, and a `maxFeePerGas`
284
+ * (or `gasPrice`) set on it replaces the fee rate fetched from the provider, so the quote is the transaction's maximum
285
+ * cost as it will be sent.
286
+ *
119
287
  * @param {EvmTransaction} tx - The transaction.
120
288
  * @returns {Promise<Omit<TransactionResult, 'hash'>>} The transaction's quotes.
289
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
290
+ * @throws {Error} If the simulation of the transaction reverts, as an ethers error with code `CALL_EXCEPTION`.
121
291
  */
122
292
  async quoteSendTransaction (tx) {
123
293
  if (!this._provider) {
124
- throw new Error('The wallet must be connected to a provider to quote send transaction operations.')
294
+ throw new ProviderRequiredError('The wallet must be connected to a provider to quote send transaction operations.')
125
295
  }
126
296
 
127
- const gas = await this._provider.estimateGas({
128
- from: await this.getAddress(),
129
- ...tx
130
- })
297
+ const from = await this.getAddress()
298
+
299
+ const estimatedGas = await this._estimateGas({ from, ...tx })
131
300
 
132
- const { maxFeePerGas } = await this._provider.getFeeData()
301
+ const gas = tx.gasLimit ?? estimatedGas
302
+ const feeRate = tx.maxFeePerGas ?? tx.gasPrice ?? await this._getFeeRate()
133
303
 
134
- return { fee: gas * maxFeePerGas }
304
+ return { fee: BigInt(gas) * BigInt(feeRate) }
135
305
  }
136
306
 
137
307
  /**
138
308
  * Quotes the costs of a transfer operation.
139
309
  *
140
- * @param {TransferOptions} options - The transfer's options.
310
+ * @param {EvmTransferOptions} options - The transfer's options, including any gas overrides to carry onto the transaction.
141
311
  * @returns {Promise<Omit<TransferResult, 'hash'>>} The transfer's quotes.
312
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
142
313
  */
143
314
  async quoteTransfer (options) {
144
315
  if (!this._provider) {
145
- throw new Error('The wallet must be connected to a provider to quote transfer operations.')
316
+ throw new ProviderRequiredError('The wallet must be connected to a provider to quote transfer operations.')
146
317
  }
147
318
 
148
319
  const tx = await WalletAccountReadOnlyEvm._getTransferTransaction(options)
@@ -155,26 +326,250 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
155
326
  /**
156
327
  * Returns a transaction's receipt.
157
328
  *
329
+ * @deprecated Use {@link getTransaction} instead, which returns a normalized, finality-based receipt. The raw ethers receipt remains available on its `receipt` property.
158
330
  * @param {string} hash - The transaction's hash.
159
331
  * @returns {Promise<EvmTransactionReceipt | null>} – The receipt, or null if the transaction has not been included in a block yet.
332
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
160
333
  */
161
334
  async getTransactionReceipt (hash) {
162
335
  if (!this._provider) {
163
- throw new Error('The wallet must be connected to a provider to fetch transaction receipts.')
336
+ throw new ProviderRequiredError('The wallet must be connected to a provider to fetch transaction receipts.')
164
337
  }
165
338
 
166
339
  return await this._provider.getTransactionReceipt(hash)
167
340
  }
168
341
 
342
+ /**
343
+ * Returns a normalized, finality-based receipt for a transaction.
344
+ *
345
+ * @param {string} hash - The transaction's hash.
346
+ * @returns {Promise<TransactionReceipt & EvmTransactionDetails>} The normalized receipt.
347
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
348
+ * @throws {ValueError} If the hash is not a valid transaction hash.
349
+ * @throws {NoSuchElementError} If no transaction has been found for the given hash.
350
+ */
351
+ async getTransaction (hash) {
352
+ if (!this._provider) {
353
+ throw new ProviderRequiredError('The wallet must be connected to a provider to fetch transactions.')
354
+ }
355
+
356
+ if (!isHexString(hash, 32)) {
357
+ throw new ValueError(`Invalid transaction hash: '${hash}'.`)
358
+ }
359
+
360
+ const [transaction, receipt] = await Promise.all([
361
+ this._provider.getTransaction(hash),
362
+ this._provider.getTransactionReceipt(hash)
363
+ ])
364
+
365
+ if (!transaction && !receipt) {
366
+ throw new NoSuchElementError(`No transaction found for '${hash}'.`)
367
+ }
368
+
369
+ if (!receipt) {
370
+ const dropped = transaction
371
+ ? await this._isReplaced(transaction)
372
+ : false
373
+
374
+ return {
375
+ hash,
376
+ finality: dropped ? 'dropped' : 'pending',
377
+ confirmations: 0,
378
+ receipt: null
379
+ }
380
+ }
381
+
382
+ const confirmations = await receipt.confirmations()
383
+ const finalized = await this._isFinalized(receipt.blockNumber)
384
+
385
+ return {
386
+ hash,
387
+ finality: finalized ? 'final' : 'confirmed',
388
+ success: receipt.status === 1,
389
+ block: receipt.blockNumber,
390
+ fee: receipt.fee,
391
+ confirmations,
392
+ receipt
393
+ }
394
+ }
395
+
396
+ /**
397
+ * Blocks until a transaction reaches a terminal state (the requested finality target or `dropped`), or times out.
398
+ *
399
+ * @param {string} hash - The transaction's hash.
400
+ * @param {WaitForTransactionOptions} [options] - The wait options.
401
+ * @returns {Promise<TransactionReceipt & EvmTransactionDetails>} The terminal receipt: the finality target reached (inspect `success` to tell success from revert), or `dropped`.
402
+ * @throws {TimeoutError} If the target is not reached before the timeout.
403
+ */
404
+ async waitForTransaction (hash, options = {}) {
405
+ return await super.waitForTransaction(hash, options)
406
+ }
407
+
408
+ /**
409
+ * Returns whether a block is at or below the chain's `finalized` block. Chains that don't support the tag are treated as not finalized.
410
+ *
411
+ * @protected
412
+ * @param {number} blockNumber - The block number to check.
413
+ * @returns {Promise<boolean>} True if the block is finalized.
414
+ */
415
+ async _isFinalized (blockNumber) {
416
+ try {
417
+ const finalizedBlock = await this._provider.getBlock('finalized')
418
+ return !!finalizedBlock && blockNumber <= finalizedBlock.number
419
+ } catch (error) {
420
+ // Treat an unsupported 'finalized' block tag as not-finalized; let real failures propagate.
421
+ const rpcCode = error?.info?.error?.code
422
+
423
+ if (isError(error, 'UNSUPPORTED_OPERATION') || rpcCode === -32601 || rpcCode === -32602) {
424
+ return false
425
+ }
426
+
427
+ throw error
428
+ }
429
+ }
430
+
431
+ /**
432
+ * Returns whether an unmined transaction has been replaced, i.e. its sender's mined nonce has already advanced past the transaction's nonce.
433
+ *
434
+ * @protected
435
+ * @param {EvmTransactionResponse} transaction - The unmined transaction.
436
+ * @returns {Promise<boolean>} True if the transaction's nonce slot is already taken.
437
+ */
438
+ async _isReplaced (transaction) {
439
+ const accountNonce = await this._provider.getTransactionCount(transaction.from, 'latest')
440
+ return accountNonce > transaction.nonce
441
+ }
442
+
443
+ /**
444
+ * Overrides the base default to allow for slower EVM inclusion and confirmation.
445
+ *
446
+ * @type {number}
447
+ */
448
+ get defaultWaitTimeout () {
449
+ return 120000
450
+ }
451
+
452
+ /**
453
+ * Returns the current allowance for the given token and spender.
454
+ * @param {string} token The token's address.
455
+ * @param {string} spender The spender's address.
456
+ * @returns {Promise<bigint>} The allowance.
457
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
458
+ */
459
+ async getAllowance (token, spender) {
460
+ if (!this._provider) {
461
+ throw new ProviderRequiredError('The wallet must be connected to a provider to retrieve allowances.')
462
+ }
463
+
464
+ const address = await this.getAddress()
465
+ const abi = ['function allowance(address owner, address spender) view returns (uint256)']
466
+ const contract = new Contract(token, abi, this._provider)
467
+ const allowance = await contract.allowance(address, spender)
468
+ return allowance
469
+ }
470
+
471
+ /**
472
+ * Verifies a message's signature.
473
+ *
474
+ * @param {string} message - The original message.
475
+ * @param {string} signature - The signature to verify.
476
+ * @returns {Promise<boolean>} True if the signature is valid.
477
+ */
478
+ async verify (message, signature) {
479
+ const address = await verifyMessage(message, signature)
480
+ const accountAddress = await this.getAddress()
481
+
482
+ return address.toLowerCase() === accountAddress.toLowerCase()
483
+ }
484
+
485
+ /**
486
+ * Verifies a typed data signature.
487
+ *
488
+ * @param {TypedData} typedData - The typed data to verify.
489
+ * @param {string} signature - The signature to verify.
490
+ * @returns {Promise<boolean>} True if the signature is valid.
491
+ */
492
+ async verifyTypedData (typedData, signature) {
493
+ const { domain, types, message } = typedData
494
+ const address = verifyTypedData(domain, types, message, signature)
495
+ const accountAddress = await this.getAddress()
496
+
497
+ return address.toLowerCase() === accountAddress.toLowerCase()
498
+ }
499
+
500
+ /**
501
+ * Checks if this account has an active ERC-7702 delegation.
502
+ *
503
+ * @returns {Promise<DelegationInfo>} The delegation info.
504
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
505
+ */
506
+ async getDelegation () {
507
+ if (!this._provider) {
508
+ throw new ProviderRequiredError('The wallet must be connected to a provider to check delegation.')
509
+ }
510
+
511
+ const address = await this.getAddress()
512
+ const code = await this._provider.send('eth_getCode', [address, 'latest'])
513
+
514
+ if (
515
+ code &&
516
+ code.toLowerCase().startsWith(DELEGATION_DESIGNATOR_PREFIX) &&
517
+ code.length === DELEGATION_DESIGNATOR_LENGTH
518
+ ) {
519
+ const delegateAddress = '0x' + code.slice(DELEGATION_DESIGNATOR_PREFIX.length)
520
+
521
+ return {
522
+ isDelegated: true,
523
+ delegateAddress
524
+ }
525
+ }
526
+
527
+ return {
528
+ isDelegated: false,
529
+ delegateAddress: null
530
+ }
531
+ }
532
+
533
+ /**
534
+ * Estimates the gas of a transaction by simulating it against the connected provider, using the authorization-list
535
+ * aware estimation for ERC-7702 transactions.
536
+ *
537
+ * @protected
538
+ * @param {EvmTransactionRequest} tx - The transaction to simulate, including its `from` address.
539
+ * @returns {Promise<bigint>} The gas units the simulated transaction consumed.
540
+ */
541
+ async _estimateGas (tx) {
542
+ return tx.authorizationList
543
+ ? await this._estimateGasWithAuthList(tx)
544
+ : await this._provider.estimateGas(tx)
545
+ }
546
+
547
+ /**
548
+ * Extracts the gas and fee overrides set on transfer or approve options.
549
+ *
550
+ * @protected
551
+ * @param {EvmGasOverrides} options - The options to read the overrides from.
552
+ * @returns {EvmGasOverrides} Only the gas and fee fields that are set on the options.
553
+ */
554
+ static _getGasOverrides (options) {
555
+ const overrides = {}
556
+
557
+ for (const field of ['gasLimit', 'gasPrice', 'maxFeePerGas', 'maxPriorityFeePerGas']) {
558
+ if (options[field] !== undefined) overrides[field] = options[field]
559
+ }
560
+
561
+ return overrides
562
+ }
563
+
169
564
  /**
170
565
  * Returns an evm transaction to execute the given token transfer.
171
566
  *
172
567
  * @protected
173
- * @param {TransferOptions} options - The transfer's options.
174
- * @returns {Promise<EvmTransaction>} The evm transaction.
568
+ * @param {EvmTransferOptions} options - The transfer's options, including any gas overrides and ERC-7702 authorizations to carry onto the transaction.
569
+ * @returns {Promise<EvmTransaction>} The ERC-20 transfer call as an evm transaction, with the options' gas overrides and authorizations applied.
175
570
  */
176
571
  static async _getTransferTransaction (options) {
177
- const { token, recipient, amount } = options
572
+ const { token, recipient, amount, authorizationList } = options
178
573
 
179
574
  const abi = ['function transfer(address to, uint256 amount) returns (bool)']
180
575
 
@@ -183,9 +578,51 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
183
578
  const tx = {
184
579
  to: token,
185
580
  value: 0,
186
- data: contract.interface.encodeFunctionData('transfer', [recipient, amount])
581
+ data: contract.interface.encodeFunctionData('transfer', [recipient, amount]),
582
+ ...WalletAccountReadOnlyEvm._getGasOverrides(options),
583
+ authorizationList
187
584
  }
188
585
 
189
586
  return tx
190
587
  }
588
+
589
+ /** @private */
590
+ async _estimateGasWithAuthList ({ from, to, value, data, authorizationList }) {
591
+ const formatAuth = (auth) => {
592
+ const { address, nonce, chainId } = auth
593
+
594
+ const signature = auth.signature instanceof Signature
595
+ ? auth.signature
596
+ : Signature.from(auth.signature)
597
+
598
+ return {
599
+ address,
600
+ nonce: toQuantity(nonce),
601
+ chainId: toQuantity(chainId),
602
+ r: toQuantity(signature.r),
603
+ s: toQuantity(signature.s),
604
+ yParity: toQuantity(signature.yParity)
605
+ }
606
+ }
607
+
608
+ const rpcTx = {
609
+ from,
610
+ to,
611
+ value: toQuantity(value),
612
+ data: data ?? '0x',
613
+ type: '0x04',
614
+ authorizationList: authorizationList.map(formatAuth)
615
+ }
616
+
617
+ const result = await this._provider.send('eth_estimateGas', [rpcTx])
618
+
619
+ return BigInt(result)
620
+ }
621
+
622
+ /** @private */
623
+ async _getFeeRate () {
624
+ const { maxFeePerGas, gasPrice } = await this._provider.getFeeData()
625
+
626
+ return maxFeePerGas || gasPrice
627
+ }
191
628
  }