@tetherto/wdk-wallet-evm 1.0.0-beta.17 → 1.0.0-beta.19

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tetherto/wdk-wallet-evm",
3
- "version": "1.0.0-beta.17",
3
+ "version": "1.0.0-beta.19",
4
4
  "description": "A simple package to manage BIP-32 wallets for evm blockchains.",
5
5
  "keywords": [
6
6
  "wdk",
@@ -16,7 +16,7 @@
16
16
  import * as bip39 from 'bip39'
17
17
 
18
18
  import MemorySafeHDNodeWallet from '../memory-safe/hd-node-wallet.js'
19
- import { ISigner, NotImplementedError } from '@tetherto/wdk-wallet'
19
+ import { ISigner, InvalidSignerError, NotImplementedError, ValueError } from '@tetherto/wdk-wallet'
20
20
 
21
21
  const BIP_44_ETH_DERIVATION_PATH_PREFIX = "m/44'/60'"
22
22
 
@@ -25,7 +25,6 @@ const DEFAULT_ACCOUNT_PATH = "0'/0/0"
25
25
 
26
26
  /** @typedef {import('../utils/tx-populator-evm.js').UnsignedEvmTransaction} UnsignedEvmTransaction */
27
27
  /** @typedef {import('@tetherto/wdk-wallet').ISigner} ISigner */
28
- /** @typedef {import('@tetherto/wdk-wallet').InvalidSignerError} InvalidSignerError */
29
28
  /** @typedef {import('@tetherto/wdk-wallet').KeyPair} KeyPair */
30
29
  /** @typedef {import('ethers').AuthorizationRequest} AuthorizationRequest */
31
30
  /** @typedef {import('ethers').Authorization} Authorization */
@@ -163,24 +162,24 @@ export default class SeedSignerEvm extends ISignerEvm {
163
162
  *
164
163
  * @param {string|Uint8Array|null} seed - BIP-39 mnemonic or seed bytes. Omit when providing `opts.root`.
165
164
  * @param {SeedSignerEvmOpts} [opts] - Construction options for root reuse, direct child derivation or path definition (default is index 0).
166
- * @throws {Error} If neither a seed nor a root is provided, or if both are provided.
167
- * @throws {Error} If a seed is provided but is not a valid BIP-39 mnemonic.
165
+ * @throws {ValueError} If neither a seed nor a root is provided, or if both are provided.
166
+ * @throws {ValueError} If a seed is provided but is not a valid BIP-39 mnemonic.
168
167
  */
169
168
  constructor (seed, opts = {}) {
170
169
  super()
171
170
 
172
171
  // If a root is provided, do not expect a seed
173
172
  if (opts.root && seed) {
174
- throw new Error('Provide either a seed or a root, not both.')
173
+ throw new ValueError('Provide either a seed or a root, not both.')
175
174
  }
176
175
 
177
176
  if (!opts.root && !seed) {
178
- throw new Error('Seed or root is required.')
177
+ throw new ValueError('Seed or root is required.')
179
178
  }
180
179
 
181
180
  if (typeof seed === 'string') {
182
181
  if (!bip39.validateMnemonic(seed)) {
183
- throw new Error('The seed phrase is invalid.')
182
+ throw new ValueError('The seed phrase is invalid.')
184
183
  }
185
184
  seed = bip39.mnemonicToSeedSync(seed)
186
185
  }
@@ -251,11 +250,11 @@ export default class SeedSignerEvm extends ISignerEvm {
251
250
  * Derive a child signer using the provided relative path (e.g. "0'/0/0").
252
251
  * @param {string} relPath
253
252
  * @returns {Promise<SeedSignerEvm>}
254
- * @throws {Error} If called on a derived child signer, which does not retain the root.
253
+ * @throws {InvalidSignerError} If called on a derived child signer, which does not retain the root.
255
254
  */
256
255
  async derive (relPath) {
257
256
  if (!this._root) {
258
- throw new Error('Cannot derive: this signer has no root (it is a derived child or has been disposed).')
257
+ throw new InvalidSignerError('Cannot derive: this signer has no root (it is a derived child or has been disposed).')
259
258
  }
260
259
  return new SeedSignerEvm(null, { root: this._root, path: relPath, isChild: true })
261
260
  }
@@ -13,6 +13,8 @@
13
13
  // limitations under the License.
14
14
  'use strict'
15
15
 
16
+ import { ValueError } from '@tetherto/wdk-wallet'
17
+
16
18
  import { Signature, toQuantity } from 'ethers'
17
19
 
18
20
  /** @typedef {import('ethers').Provider} Provider */
@@ -51,6 +53,7 @@ import { Signature, toQuantity } from 'ethers'
51
53
  * @param {string} from - The sender address.
52
54
  * @param {UnsignedEvmTransaction} tx - The partial transaction to populate.
53
55
  * @returns {Promise<UnsignedEvmTransaction>} The fully populated unsigned transaction.
56
+ * @throws {ValueError} If the transaction mixes fee fields that its type doesn't support, or a type 3 transaction omits `maxFeePerBlobGas`.
54
57
  */
55
58
  export async function populateTransactionEvm (provider, from, tx) {
56
59
  const net = await provider.getNetwork()
@@ -65,13 +68,13 @@ export async function populateTransactionEvm (provider, from, tx) {
65
68
  const explicitType = (tx.type != null) ? Number(tx.type) : null
66
69
 
67
70
  if ((explicitType === 2 || (explicitType == null && has1559)) && hasLegacy) {
68
- throw new Error('eip-1559 transaction does not support gasPrice')
71
+ throw new ValueError('eip-1559 transaction does not support gasPrice')
69
72
  }
70
73
  if ((explicitType === 0 || explicitType === 1) && has1559) {
71
- throw new Error('pre-eip-1559 transaction does not support maxFeePerGas/maxPriorityFeePerGas')
74
+ throw new ValueError('pre-eip-1559 transaction does not support maxFeePerGas/maxPriorityFeePerGas')
72
75
  }
73
76
  if ((explicitType === 3 || hasBlobs) && hasLegacy) {
74
- throw new Error('blob transaction does not support gasPrice')
77
+ throw new ValueError('blob transaction does not support gasPrice')
75
78
  }
76
79
 
77
80
  const feeData = await provider.getFeeData()
@@ -132,7 +135,7 @@ export async function populateTransactionEvm (provider, from, tx) {
132
135
  populated.type = 3
133
136
  populated.maxFeePerGas = tx.maxFeePerGas ?? feeData.maxFeePerGas
134
137
  populated.maxPriorityFeePerGas = tx.maxPriorityFeePerGas ?? feeData.maxPriorityFeePerGas
135
- if (tx.maxFeePerBlobGas == null) throw new Error('maxFeePerBlobGas is required for type 3 transactions')
138
+ if (tx.maxFeePerBlobGas == null) throw new ValueError('maxFeePerBlobGas is required for type 3 transactions')
136
139
  populated.maxFeePerBlobGas = tx.maxFeePerBlobGas
137
140
  if (tx.blobs != null) populated.blobs = tx.blobs
138
141
  if (tx.blobVersionedHashes != null) populated.blobVersionedHashes = tx.blobVersionedHashes
@@ -14,6 +14,8 @@
14
14
 
15
15
  'use strict'
16
16
 
17
+ import { MaximumFeeExceededError, ProviderRequiredError, ValueError } from '@tetherto/wdk-wallet'
18
+
17
19
  import { Contract, Transaction, ZeroAddress } from 'ethers'
18
20
 
19
21
  import WalletAccountReadOnlyEvm from './wallet-account-read-only-evm.js'
@@ -172,14 +174,14 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm {
172
174
  *
173
175
  * @param {EvmTransaction} tx - The transaction to sign.
174
176
  * @returns {Promise<string>} The signed transaction as a hex string.
175
- * @throws {Error} If a provider is set, and the transaction's cost surpasses the transaction max. fee option.
177
+ * @throws {MaximumFeeExceededError} If a provider is set, and the transaction's cost surpasses the transaction max. fee option.
176
178
  */
177
179
  async signTransaction (tx) {
178
180
  if (this._provider && this._config.transactionMaxFee !== undefined) {
179
181
  const { fee } = await this.quoteSendTransaction(tx)
180
182
 
181
183
  if (fee > this._config.transactionMaxFee) {
182
- throw new Error('Exceeded maximum fee cost for transaction operation.')
184
+ throw new MaximumFeeExceededError('Exceeded maximum fee cost for transaction operation.')
183
185
  }
184
186
  }
185
187
  return await this._signer.signTransaction({
@@ -191,18 +193,26 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm {
191
193
  /**
192
194
  * Sends a transaction.
193
195
  *
194
- * @param {EvmTransaction | string} tx - The transaction.
196
+ * @param {EvmTransaction | string} tx - The transaction, or a signed raw transaction as a hex string.
195
197
  * @returns {Promise<TransactionResult>} The transaction's result.
196
- * @throws {Error} If the transaction's cost exceeds the maximum transaction fee option.
198
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
199
+ * @throws {MaximumFeeExceededError} If the transaction's cost exceeds the maximum transaction fee option.
200
+ * @throws {ValueError} If the transaction mixes fee fields that its type doesn't support, or a type 3 transaction omits `maxFeePerBlobGas`.
197
201
  */
198
202
  async sendTransaction (tx) {
199
203
  if (!this._provider) {
200
- throw new Error('The wallet must be connected to a provider to send transactions.')
204
+ throw new ProviderRequiredError('The wallet must be connected to a provider to send transactions.')
201
205
  }
202
206
  const { fee } = await this.quoteSendTransaction(tx)
203
207
  if (this._config.transactionMaxFee !== undefined && fee > this._config.transactionMaxFee) {
204
- throw new Error('Exceeded maximum fee cost for transaction operation.')
208
+ throw new MaximumFeeExceededError('Exceeded maximum fee cost for transaction operation.')
205
209
  }
210
+
211
+ if (typeof tx === 'string') {
212
+ const hash = await this._provider.send('eth_sendRawTransaction', [tx])
213
+ return { hash, fee }
214
+ }
215
+
206
216
  // Build, sign and broadcast raw transaction using the signer
207
217
  const from = await this.getAddress()
208
218
  const unsignedTx = await populateTransactionEvm(this._provider, from, tx)
@@ -214,13 +224,14 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm {
214
224
  /**
215
225
  * Quotes the costs of a send transaction operation.
216
226
  *
217
- * @param {EvmTransaction | string} tx - The transaction.
227
+ * @param {EvmTransaction | string} tx - The transaction, or a signed raw transaction as a hex string.
218
228
  * @returns {Promise<Omit<TransactionResult, 'hash'>>} The transaction's quotes.
229
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
219
230
  */
220
231
  async quoteSendTransaction (tx) {
221
232
  if (typeof tx === 'string') {
222
233
  if (!this._provider) {
223
- throw new Error('The wallet must be connected to a provider to quote send transaction operations.')
234
+ throw new ProviderRequiredError('The wallet must be connected to a provider to quote send transaction operations.')
224
235
  }
225
236
 
226
237
  const { from, to, value, data, gasLimit, gasPrice, maxFeePerGas, maxPriorityFeePerGas, type, nonce, chainId, authorizationList } = Transaction.from(tx)
@@ -246,11 +257,12 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm {
246
257
  *
247
258
  * @param {EvmTransferOptions} options - The transfer's options.
248
259
  * @returns {Promise<TransferResult>} The transfer's result.
249
- * @throws {Error} If the transfer's cost exceeds the maximum transfer fee option.
260
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
261
+ * @throws {MaximumFeeExceededError} If the transfer's cost exceeds the maximum transfer fee option.
250
262
  */
251
263
  async transfer (options) {
252
264
  if (!this._provider) {
253
- throw new Error('The wallet must be connected to a provider to transfer tokens.')
265
+ throw new ProviderRequiredError('The wallet must be connected to a provider to transfer tokens.')
254
266
  }
255
267
 
256
268
  const tx = await WalletAccountEvm._getTransferTransaction(options)
@@ -258,7 +270,7 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm {
258
270
  const { fee } = await this.quoteSendTransaction(tx)
259
271
 
260
272
  if (this._config.transferMaxFee !== undefined && fee > this._config.transferMaxFee) {
261
- throw new Error('Exceeded maximum fee cost for transfer operation.')
273
+ throw new MaximumFeeExceededError('Exceeded maximum fee cost for transfer operation.')
262
274
  }
263
275
 
264
276
  const { hash } = await this.sendTransaction(tx)
@@ -271,11 +283,12 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm {
271
283
  *
272
284
  * @param {ApproveOptions} options The approve options.
273
285
  * @returns {Promise<TransactionResult>} The transaction's result.
274
- * @throws {Error} If trying to approve usdts on ethereum with allowance not equal to zero (due to the usdt allowance reset requirement).
286
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
287
+ * @throws {ValueError} If trying to approve usdts on ethereum with allowance not equal to zero (due to the usdt allowance reset requirement).
275
288
  */
276
289
  async approve (options) {
277
290
  if (!this._provider) {
278
- throw new Error('The wallet must be connected to a provider to approve funds.')
291
+ throw new ProviderRequiredError('The wallet must be connected to a provider to approve funds.')
279
292
  }
280
293
 
281
294
  const { token, spender, amount } = options
@@ -284,7 +297,7 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm {
284
297
  if (chainId === 1n && token.toLowerCase() === USDT_MAINNET_ADDRESS.toLowerCase()) {
285
298
  const currentAllowance = await this.getAllowance(token, spender)
286
299
  if (currentAllowance > 0n && BigInt(amount) > 0n) {
287
- throw new Error(
300
+ throw new ValueError(
288
301
  '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.'
289
302
  )
290
303
  }
@@ -345,10 +358,11 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm {
345
358
  *
346
359
  * @param {string} delegateAddress - The address of the contract to delegate to.
347
360
  * @returns {Promise<TransactionResult>} The transaction result.
361
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
348
362
  */
349
363
  async delegate (delegateAddress) {
350
364
  if (!this._provider) {
351
- throw new Error('The wallet must be connected to a provider to delegate.')
365
+ throw new ProviderRequiredError('The wallet must be connected to a provider to delegate.')
352
366
  }
353
367
 
354
368
  const address = await this.getAddress()
@@ -14,7 +14,7 @@
14
14
 
15
15
  'use strict'
16
16
 
17
- import { WalletAccountReadOnly, NoSuchElementError, ValueError } from '@tetherto/wdk-wallet'
17
+ import { WalletAccountReadOnly, NoSuchElementError, ProviderRequiredError, ValueError } from '@tetherto/wdk-wallet'
18
18
 
19
19
  import { BrowserProvider, Contract, Interface, isError, isHexString, JsonRpcProvider, Network, Signature, toQuantity, verifyMessage, verifyTypedData } from 'ethers'
20
20
 
@@ -81,7 +81,7 @@ import FailoverProvider from '@tetherto/wdk-failover-provider'
81
81
 
82
82
  /**
83
83
  * @typedef {Object} EvmWalletConfig
84
- * @property {string | Eip1193Provider | Array<string | Eip1193Provider>} [provider] - The url of the rpc provider, or an instance of a class that implements eip-1193. It's also possible to provide an array of urls or EIP 1193 providers instead. In such case, connection errors will cause the wallet to automatically fallback on the next provider in the list.
84
+ * @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.
85
85
  * @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.
86
86
  * @property {number} [chainId] - The chain ID of the network. When provided, skips automatic chain ID detection from the provider.
87
87
  * @property {number | bigint} [transferMaxFee] - The maximum fee amount for transfer operations.
@@ -116,31 +116,67 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
116
116
  * @protected
117
117
  * @type {Provider | undefined}
118
118
  */
119
- this._provider = undefined
119
+ this._provider = WalletAccountReadOnlyEvm._buildProvider(config)
120
+ }
121
+
122
+ /**
123
+ * Whether a value is an EIP-1193 provider (e.g. a browser wallet).
124
+ *
125
+ * @protected
126
+ * @param {string | Eip1193Provider | Provider} value - The value to inspect.
127
+ * @returns {boolean} True if the value is an EIP-1193 provider.
128
+ */
129
+ static _isEip1193Provider (value) {
130
+ return typeof value.request === 'function'
131
+ }
120
132
 
133
+ /**
134
+ * Builds an ethers provider from the wallet configuration:
135
+ * - a url string -> a new `JsonRpcProvider`
136
+ * - an already-built ethers provider (or failover wrapper) -> reused as-is
137
+ * - anything else (EIP-1193 / browser wallet) -> wrapped in a `BrowserProvider`
138
+ * - an array of the above -> a `FailoverProvider` across each entry
139
+ *
140
+ * @protected
141
+ * @param {Omit<EvmWalletConfig, 'transferMaxFee' | 'transactionMaxFee'>} [config] - The configuration object.
142
+ * @returns {Provider | undefined} The provider, or undefined if none is configured.
143
+ */
144
+ static _buildProvider (config = {}) {
121
145
  const { provider, retries = 3 } = config
122
146
  const network = config.chainId ? Network.from(config.chainId) : undefined
123
147
  const providerOpts = config.chainId ? { staticNetwork: true } : undefined
124
148
 
149
+ const toOption = (entry) => {
150
+ if (typeof entry === 'string') {
151
+ return new JsonRpcProvider(entry, network, providerOpts)
152
+ }
153
+
154
+ if (WalletAccountReadOnlyEvm._isEip1193Provider(entry)) {
155
+ return new BrowserProvider(entry)
156
+ }
157
+
158
+ return entry
159
+ }
160
+
125
161
  if (Array.isArray(provider)) {
126
- if (provider.length > 0) {
127
- const failoverProvider = new FailoverProvider({ retries })
162
+ if (provider.length === 0) {
163
+ return undefined
164
+ }
128
165
 
129
- for (const entry of provider) {
130
- const option = typeof entry === 'string'
131
- ? new JsonRpcProvider(entry, network, providerOpts)
132
- : new BrowserProvider(entry)
133
- failoverProvider.addProvider(option)
134
- }
166
+ const failoverProvider = new FailoverProvider({ retries })
135
167
 
136
- this._provider = failoverProvider.initialize()
168
+ for (const entry of provider) {
169
+ failoverProvider.addProvider(toOption(entry))
137
170
  }
138
- } else if (provider) {
139
- this._provider =
140
- typeof provider === 'string'
141
- ? new JsonRpcProvider(provider, network, providerOpts)
142
- : new BrowserProvider(provider)
171
+
172
+ return failoverProvider.initialize()
143
173
  }
174
+
175
+ if (provider) {
176
+ return toOption(provider)
177
+ }
178
+
179
+ return undefined
144
180
  }
145
181
 
146
182
  /**
@@ -156,10 +192,11 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
156
192
  * Returns the account's eth balance.
157
193
  *
158
194
  * @returns {Promise<bigint>} The eth balance (in weis).
195
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
159
196
  */
160
197
  async getBalance () {
161
198
  if (!this._provider) {
162
- throw new Error('The wallet must be connected to a provider to retrieve balances.')
199
+ throw new ProviderRequiredError('The wallet must be connected to a provider to retrieve balances.')
163
200
  }
164
201
 
165
202
  const address = await this.getAddress()
@@ -174,10 +211,11 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
174
211
  *
175
212
  * @param {string} tokenAddress - The smart contract address of the token.
176
213
  * @returns {Promise<bigint>} The token balance (in base unit).
214
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
177
215
  */
178
216
  async getTokenBalance (tokenAddress) {
179
217
  if (!this._provider) {
180
- throw new Error('The wallet must be connected to a provider to retrieve token balances.')
218
+ throw new ProviderRequiredError('The wallet must be connected to a provider to retrieve token balances.')
181
219
  }
182
220
 
183
221
  const address = await this.getAddress()
@@ -194,10 +232,11 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
194
232
  *
195
233
  * @param {string[]} tokenAddresses - The smart contract addresses of the tokens.
196
234
  * @returns {Promise<Record<string, bigint>>} A mapping of token addresses to their balances (in base units).
235
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
197
236
  */
198
237
  async getTokenBalances (tokenAddresses) {
199
238
  if (!this._provider) {
200
- throw new Error(
239
+ throw new ProviderRequiredError(
201
240
  'The wallet must be connected to a provider to retrieve token balances.'
202
241
  )
203
242
  }
@@ -231,10 +270,11 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
231
270
  *
232
271
  * @param {EvmTransaction} tx - The transaction.
233
272
  * @returns {Promise<Omit<TransactionResult, 'hash'>>} The transaction's quotes.
273
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
234
274
  */
235
275
  async quoteSendTransaction (tx) {
236
276
  if (!this._provider) {
237
- throw new Error('The wallet must be connected to a provider to quote send transaction operations.')
277
+ throw new ProviderRequiredError('The wallet must be connected to a provider to quote send transaction operations.')
238
278
  }
239
279
 
240
280
  const from = await this.getAddress()
@@ -255,10 +295,11 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
255
295
  *
256
296
  * @param {EvmTransferOptions} options - The transfer's options.
257
297
  * @returns {Promise<Omit<TransferResult, 'hash'>>} The transfer's quotes.
298
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
258
299
  */
259
300
  async quoteTransfer (options) {
260
301
  if (!this._provider) {
261
- throw new Error('The wallet must be connected to a provider to quote transfer operations.')
302
+ throw new ProviderRequiredError('The wallet must be connected to a provider to quote transfer operations.')
262
303
  }
263
304
 
264
305
  const tx = await WalletAccountReadOnlyEvm._getTransferTransaction(options)
@@ -274,10 +315,11 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
274
315
  * @deprecated Use {@link getTransaction} instead, which returns a normalized, finality-based receipt. The raw ethers receipt remains available on its `receipt` property.
275
316
  * @param {string} hash - The transaction's hash.
276
317
  * @returns {Promise<EvmTransactionReceipt | null>} – The receipt, or null if the transaction has not been included in a block yet.
318
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
277
319
  */
278
320
  async getTransactionReceipt (hash) {
279
321
  if (!this._provider) {
280
- throw new Error('The wallet must be connected to a provider to fetch transaction receipts.')
322
+ throw new ProviderRequiredError('The wallet must be connected to a provider to fetch transaction receipts.')
281
323
  }
282
324
 
283
325
  return await this._provider.getTransactionReceipt(hash)
@@ -288,12 +330,13 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
288
330
  *
289
331
  * @param {string} hash - The transaction's hash.
290
332
  * @returns {Promise<TransactionReceipt & EvmTransactionDetails>} The normalized receipt.
333
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
291
334
  * @throws {ValueError} If the hash is not a valid transaction hash.
292
335
  * @throws {NoSuchElementError} If no transaction has been found for the given hash.
293
336
  */
294
337
  async getTransaction (hash) {
295
338
  if (!this._provider) {
296
- throw new Error('The wallet must be connected to a provider to fetch transactions.')
339
+ throw new ProviderRequiredError('The wallet must be connected to a provider to fetch transactions.')
297
340
  }
298
341
 
299
342
  if (!isHexString(hash, 32)) {
@@ -397,10 +440,11 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
397
440
  * @param {string} token The token's address.
398
441
  * @param {string} spender The spender's address.
399
442
  * @returns {Promise<bigint>} The allowance.
443
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
400
444
  */
401
445
  async getAllowance (token, spender) {
402
446
  if (!this._provider) {
403
- throw new Error('The wallet must be connected to a provider to retrieve allowances.')
447
+ throw new ProviderRequiredError('The wallet must be connected to a provider to retrieve allowances.')
404
448
  }
405
449
 
406
450
  const address = await this.getAddress()
@@ -443,10 +487,11 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
443
487
  * Checks if this account has an active ERC-7702 delegation.
444
488
  *
445
489
  * @returns {Promise<DelegationInfo>} The delegation info.
490
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
446
491
  */
447
492
  async getDelegation () {
448
493
  if (!this._provider) {
449
- throw new Error('The wallet must be connected to a provider to check delegation.')
494
+ throw new ProviderRequiredError('The wallet must be connected to a provider to check delegation.')
450
495
  }
451
496
 
452
497
  const address = await this.getAddress()
@@ -14,11 +14,7 @@
14
14
 
15
15
  'use strict'
16
16
 
17
- import WalletManager from '@tetherto/wdk-wallet'
18
-
19
- import { BrowserProvider, JsonRpcProvider } from 'ethers'
20
-
21
- import FailoverProvider from '@tetherto/wdk-failover-provider'
17
+ import WalletManager, { InvalidSignerError, ProviderRequiredError } from '@tetherto/wdk-wallet'
22
18
 
23
19
  import WalletAccountEvm from './wallet-account-evm.js'
24
20
  import SeedSignerEvm from './signers/seed-signer-evm.js'
@@ -28,7 +24,7 @@ import SeedSignerEvm from './signers/seed-signer-evm.js'
28
24
 
29
25
  /** @typedef {import("@tetherto/wdk-wallet").FeeRates} FeeRates */
30
26
  /** @typedef {import("@tetherto/wdk-wallet").ISigner} ISigner */
31
- /** @typedef {import("@tetherto/wdk-wallet").InvalidSignerError} InvalidSignerError */
27
+ /** @typedef {import("@tetherto/wdk-wallet").NoSuchElementError} NoSuchElementError */
32
28
 
33
29
  /** @typedef {import('./wallet-account-evm.js').EvmWalletConfig} EvmWalletConfig */
34
30
 
@@ -59,6 +55,7 @@ export default class WalletManagerEvm extends WalletManager {
59
55
  *
60
56
  * @param {string|Uint8Array|ISigner} seedOrSigner - A BIP-39 seed phrase, seed bytes, or a root signer. Root signers must be derivable — non-derivable signers (e.g. private-key signers) can only be registered by name via {@link addSigner}.
61
57
  * @param {EvmWalletConfig} [config] - The configuration object.
58
+ * @throws {InvalidSignerError} If the default signer doesn't support account derivation.
62
59
  */
63
60
  constructor (seedOrSigner, config = {}) {
64
61
  let signer = seedOrSigner
@@ -66,7 +63,7 @@ export default class WalletManagerEvm extends WalletManager {
66
63
  signer = new SeedSignerEvm(seedOrSigner)
67
64
  }
68
65
  if (!signer.isDerivable) {
69
- throw new Error('The default signer must be derivable. Non-derivable signers (e.g. private-key signers) can only be registered by name via addSigner.')
66
+ throw new InvalidSignerError('The default signer must be derivable. Non-derivable signers (e.g. private-key signers) can only be registered by name via addSigner.')
70
67
  }
71
68
  super(signer, config)
72
69
 
@@ -79,34 +76,13 @@ export default class WalletManagerEvm extends WalletManager {
79
76
  this._config = config
80
77
 
81
78
  /**
82
- * An ethers provider to interact with a node of the blockchain.
79
+ * An ethers provider to interact with a node of the blockchain. Shared with every account
80
+ * this manager creates, so two accounts never open two clients for the same endpoint.
83
81
  *
84
82
  * @protected
85
83
  * @type {Provider | undefined}
86
84
  */
87
- this._provider = undefined
88
-
89
- const { provider, retries = 3 } = config
90
-
91
- if (Array.isArray(provider)) {
92
- if (provider.length > 0) {
93
- const failoverProvider = new FailoverProvider({ retries })
94
-
95
- for (const entry of provider) {
96
- const option = typeof entry === 'string'
97
- ? new JsonRpcProvider(entry)
98
- : new BrowserProvider(entry)
99
- failoverProvider.addProvider(option)
100
- }
101
-
102
- this._provider = failoverProvider.initialize()
103
- }
104
- } else if (provider) {
105
- this._provider =
106
- typeof provider === 'string'
107
- ? new JsonRpcProvider(provider)
108
- : new BrowserProvider(provider)
109
- }
85
+ this._provider = WalletAccountEvm._buildProvider(config)
110
86
  }
111
87
 
112
88
  /**
@@ -117,7 +93,7 @@ export default class WalletManagerEvm extends WalletManager {
117
93
  * @param {Object} [options] - Account options.
118
94
  * @param {string} [options.signerName] - The signer name. Omit to use the default signer.
119
95
  * @returns {Promise<WalletAccountEvm>} The account.
120
- * @throws {Error} If a signer name is given but no signer exists with that name.
96
+ * @throws {NoSuchElementError} If a signer name is given but no signer exists with that name.
121
97
  * @throws {InvalidSignerError} If the signer doesn't support account derivation.
122
98
  */
123
99
 
@@ -129,7 +105,7 @@ export default class WalletManagerEvm extends WalletManager {
129
105
  * @overload
130
106
  * @param {string} signerName - The signer name registered via {@link addSigner}.
131
107
  * @returns {Promise<WalletAccountEvm>} The account.
132
- * @throws {Error} If no signer exists with the given name.
108
+ * @throws {NoSuchElementError} If no signer exists with the given name.
133
109
  */
134
110
 
135
111
  async getAccount (indexOrSignerName = 0, options = {}) {
@@ -142,7 +118,7 @@ export default class WalletManagerEvm extends WalletManager {
142
118
  const accountSigner = signer.isDerivable
143
119
  ? await signer.derive(signer.path.split('/').slice(-3).join('/'))
144
120
  : signer
145
- const account = new WalletAccountEvm(accountSigner, this._config)
121
+ const account = new WalletAccountEvm(accountSigner, this._accountConfig())
146
122
  this._accounts[key] = account
147
123
  return account
148
124
  }
@@ -158,7 +134,7 @@ export default class WalletManagerEvm extends WalletManager {
158
134
  * @param {Object} [options] - Account options.
159
135
  * @param {string} [options.signerName] - The signer name. Omit to use the default signer.
160
136
  * @returns {Promise<WalletAccountEvm>} The account.
161
- * @throws {Error} If a signer name is given but no signer exists with that name.
137
+ * @throws {NoSuchElementError} If a signer name is given but no signer exists with that name.
162
138
  * @throws {InvalidSignerError} If the signer doesn't support account derivation.
163
139
  */
164
140
  async getAccountByPath (path, options = {}) {
@@ -169,19 +145,31 @@ export default class WalletManagerEvm extends WalletManager {
169
145
  }
170
146
  const signer = this.getSigner(signerName)
171
147
  const childSigner = await signer.derive(path)
172
- const account = new WalletAccountEvm(childSigner, this._config)
148
+ const account = new WalletAccountEvm(childSigner, this._accountConfig())
173
149
  this._accounts[key] = account
174
150
  return account
175
151
  }
176
152
 
153
+ /**
154
+ * Builds the account config, injecting the manager's shared provider so accounts reuse
155
+ * it instead of opening their own client.
156
+ *
157
+ * @private
158
+ * @returns {EvmWalletConfig} The account configuration.
159
+ */
160
+ _accountConfig () {
161
+ return { ...this._config, provider: this._provider }
162
+ }
163
+
177
164
  /**
178
165
  * Returns the current fee rates.
179
166
  *
180
167
  * @returns {Promise<FeeRates>} The fee rates (in weis).
168
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
181
169
  */
182
170
  async getFeeRates () {
183
171
  if (!this._provider) {
184
- throw new Error('The wallet must be connected to a provider to get fee rates.')
172
+ throw new ProviderRequiredError('The wallet must be connected to a provider to get fee rates.')
185
173
  }
186
174
 
187
175
  const data = await this._provider.getFeeData()
@@ -128,8 +128,8 @@ export default class SeedSignerEvm extends ISignerEvm {
128
128
  *
129
129
  * @param {string|Uint8Array|null} seed - BIP-39 mnemonic or seed bytes. Omit when providing `opts.root`.
130
130
  * @param {SeedSignerEvmOpts} [opts] - Construction options for root reuse, direct child derivation or path definition (default is index 0).
131
- * @throws {Error} If neither a seed nor a root is provided, or if both are provided.
132
- * @throws {Error} If a seed is provided but is not a valid BIP-39 mnemonic.
131
+ * @throws {ValueError} If neither a seed nor a root is provided, or if both are provided.
132
+ * @throws {ValueError} If a seed is provided but is not a valid BIP-39 mnemonic.
133
133
  */
134
134
  constructor(seed: string | Uint8Array | null, opts?: SeedSignerEvmOpts);
135
135
  /** @private */
@@ -149,7 +149,7 @@ export default class SeedSignerEvm extends ISignerEvm {
149
149
  * Derive a child signer using the provided relative path (e.g. "0'/0/0").
150
150
  * @param {string} relPath
151
151
  * @returns {Promise<SeedSignerEvm>}
152
- * @throws {Error} If called on a derived child signer, which does not retain the root.
152
+ * @throws {InvalidSignerError} If called on a derived child signer, which does not retain the root.
153
153
  */
154
154
  derive(relPath: string): Promise<SeedSignerEvm>;
155
155
  /**
@@ -80,5 +80,6 @@ export type AuthorizationLike = import("ethers").AuthorizationLike;
80
80
  * @param {string} from - The sender address.
81
81
  * @param {UnsignedEvmTransaction} tx - The partial transaction to populate.
82
82
  * @returns {Promise<UnsignedEvmTransaction>} The fully populated unsigned transaction.
83
+ * @throws {ValueError} If the transaction mixes fee fields that its type doesn't support, or a type 3 transaction omits `maxFeePerBlobGas`.
83
84
  */
84
85
  export function populateTransactionEvm(provider: Provider, from: string, tx: UnsignedEvmTransaction): Promise<UnsignedEvmTransaction>;
@@ -83,7 +83,7 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm implement
83
83
  *
84
84
  * @param {EvmTransaction} tx - The transaction to sign.
85
85
  * @returns {Promise<string>} The signed transaction as a hex string.
86
- * @throws {Error} If a provider is set, and the transaction's cost surpasses the transaction max. fee option.
86
+ * @throws {MaximumFeeExceededError} If a provider is set, and the transaction's cost surpasses the transaction max. fee option.
87
87
  */
88
88
  signTransaction(tx: EvmTransaction): Promise<string>;
89
89
  /**
@@ -91,7 +91,9 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm implement
91
91
  *
92
92
  * @param {EvmTransaction | string} tx - The transaction.
93
93
  * @returns {Promise<TransactionResult>} The transaction's result.
94
- * @throws {Error} If the transaction's cost exceeds the maximum transaction fee option.
94
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
95
+ * @throws {MaximumFeeExceededError} If the transaction's cost exceeds the maximum transaction fee option.
96
+ * @throws {ValueError} If the transaction mixes fee fields that its type doesn't support, or a type 3 transaction omits `maxFeePerBlobGas`.
95
97
  */
96
98
  sendTransaction(tx: EvmTransaction | string): Promise<TransactionResult>;
97
99
  /**
@@ -99,6 +101,7 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm implement
99
101
  *
100
102
  * @param {EvmTransaction | string} tx - The transaction.
101
103
  * @returns {Promise<Omit<TransactionResult, 'hash'>>} The transaction's quotes.
104
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
102
105
  */
103
106
  quoteSendTransaction(tx: EvmTransaction | string): Promise<Omit<TransactionResult, "hash">>;
104
107
  /**
@@ -106,7 +109,8 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm implement
106
109
  *
107
110
  * @param {EvmTransferOptions} options - The transfer's options.
108
111
  * @returns {Promise<TransferResult>} The transfer's result.
109
- * @throws {Error} If the transfer's cost exceeds the maximum transfer fee option.
112
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
113
+ * @throws {MaximumFeeExceededError} If the transfer's cost exceeds the maximum transfer fee option.
110
114
  */
111
115
  transfer(options: EvmTransferOptions): Promise<TransferResult>;
112
116
  /**
@@ -114,7 +118,8 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm implement
114
118
  *
115
119
  * @param {ApproveOptions} options The approve options.
116
120
  * @returns {Promise<TransactionResult>} The transaction's result.
117
- * @throws {Error} If trying to approve usdts on ethereum with allowance not equal to zero (due to the usdt allowance reset requirement).
121
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
122
+ * @throws {ValueError} If trying to approve usdts on ethereum with allowance not equal to zero (due to the usdt allowance reset requirement).
118
123
  */
119
124
  approve(options: ApproveOptions): Promise<TransactionResult>;
120
125
  /**
@@ -139,6 +144,7 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm implement
139
144
  *
140
145
  * @param {string} delegateAddress - The address of the contract to delegate to.
141
146
  * @returns {Promise<TransactionResult>} The transaction result.
147
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
142
148
  */
143
149
  delegate(delegateAddress: string): Promise<TransactionResult>;
144
150
  /**
@@ -38,6 +38,7 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
38
38
  * Returns the account's eth balance.
39
39
  *
40
40
  * @returns {Promise<bigint>} The eth balance (in weis).
41
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
41
42
  */
42
43
  getBalance(): Promise<bigint>;
43
44
  /**
@@ -45,6 +46,7 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
45
46
  *
46
47
  * @param {string} tokenAddress - The smart contract address of the token.
47
48
  * @returns {Promise<bigint>} The token balance (in base unit).
49
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
48
50
  */
49
51
  getTokenBalance(tokenAddress: string): Promise<bigint>;
50
52
  /**
@@ -52,6 +54,7 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
52
54
  *
53
55
  * @param {string[]} tokenAddresses - The smart contract addresses of the tokens.
54
56
  * @returns {Promise<Record<string, bigint>>} A mapping of token addresses to their balances (in base units).
57
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
55
58
  */
56
59
  getTokenBalances(tokenAddresses: string[]): Promise<Record<string, bigint>>;
57
60
  /**
@@ -59,6 +62,7 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
59
62
  *
60
63
  * @param {EvmTransaction} tx - The transaction.
61
64
  * @returns {Promise<Omit<TransactionResult, 'hash'>>} The transaction's quotes.
65
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
62
66
  */
63
67
  quoteSendTransaction(tx: EvmTransaction): Promise<Omit<TransactionResult, "hash">>;
64
68
  /**
@@ -66,6 +70,7 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
66
70
  *
67
71
  * @param {EvmTransferOptions} options - The transfer's options.
68
72
  * @returns {Promise<Omit<TransferResult, 'hash'>>} The transfer's quotes.
73
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
69
74
  */
70
75
  quoteTransfer(options: EvmTransferOptions): Promise<Omit<TransferResult, "hash">>;
71
76
  /**
@@ -74,6 +79,7 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
74
79
  * @deprecated Use {@link getTransaction} instead, which returns a normalized, finality-based receipt. The raw ethers receipt remains available on its `receipt` property.
75
80
  * @param {string} hash - The transaction's hash.
76
81
  * @returns {Promise<EvmTransactionReceipt | null>} – The receipt, or null if the transaction has not been included in a block yet.
82
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
77
83
  */
78
84
  getTransactionReceipt(hash: string): Promise<EvmTransactionReceipt | null>;
79
85
  /**
@@ -81,6 +87,7 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
81
87
  *
82
88
  * @param {string} hash - The transaction's hash.
83
89
  * @returns {Promise<TransactionReceipt & EvmTransactionDetails>} The normalized receipt.
90
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
84
91
  * @throws {ValueError} If the hash is not a valid transaction hash.
85
92
  * @throws {NoSuchElementError} If no transaction has been found for the given hash.
86
93
  */
@@ -121,6 +128,7 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
121
128
  * @param {string} token The token's address.
122
129
  * @param {string} spender The spender's address.
123
130
  * @returns {Promise<bigint>} The allowance.
131
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
124
132
  */
125
133
  getAllowance(token: string, spender: string): Promise<bigint>;
126
134
  /**
@@ -143,6 +151,7 @@ export default class WalletAccountReadOnlyEvm extends WalletAccountReadOnly {
143
151
  * Checks if this account has an active ERC-7702 delegation.
144
152
  *
145
153
  * @returns {Promise<DelegationInfo>} The delegation info.
154
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
146
155
  */
147
156
  getDelegation(): Promise<DelegationInfo>;
148
157
  /** @private */
@@ -1,6 +1,7 @@
1
1
  /** @typedef {import('ethers').Provider} Provider */
2
2
  /** @typedef {import("@tetherto/wdk-wallet").FeeRates} FeeRates */
3
3
  /** @typedef {import("@tetherto/wdk-wallet").ISigner} ISigner */
4
+ /** @typedef {import("@tetherto/wdk-wallet").NoSuchElementError} NoSuchElementError */
4
5
  /** @typedef {import('./wallet-account-evm.js').EvmWalletConfig} EvmWalletConfig */
5
6
  export default class WalletManagerEvm extends WalletManager {
6
7
  /**
@@ -27,6 +28,7 @@ export default class WalletManagerEvm extends WalletManager {
27
28
  *
28
29
  * @param {string|Uint8Array|ISigner} seedOrSigner - A BIP-39 seed phrase, seed bytes, or a root signer. Root signers must be derivable — non-derivable signers (e.g. private-key signers) can only be registered by name via {@link addSigner}.
29
30
  * @param {EvmWalletConfig} [config] - The configuration object.
31
+ * @throws {InvalidSignerError} If the default signer doesn't support account derivation.
30
32
  */
31
33
  constructor(seedOrSigner: string | Uint8Array | ISigner, config?: EvmWalletConfig);
32
34
  /**
@@ -43,7 +45,7 @@ export default class WalletManagerEvm extends WalletManager {
43
45
  * @param {Object} [options] - Account options.
44
46
  * @param {string} [options.signerName] - The signer name. Omit to use the default signer.
45
47
  * @returns {Promise<WalletAccountEvm>} The account.
46
- * @throws {Error} If a signer name is given but no signer exists with that name.
48
+ * @throws {NoSuchElementError} If a signer name is given but no signer exists with that name.
47
49
  * @throws {InvalidSignerError} If the signer doesn't support account derivation.
48
50
  */
49
51
  getAccount(index?: number, options?: {
@@ -56,7 +58,7 @@ export default class WalletManagerEvm extends WalletManager {
56
58
  *
57
59
  * @param {string} signerName - The signer name registered via {@link addSigner}.
58
60
  * @returns {Promise<WalletAccountEvm>} The account.
59
- * @throws {Error} If no signer exists with the given name.
61
+ * @throws {NoSuchElementError} If no signer exists with the given name.
60
62
  */
61
63
  getAccount(signerName: string): Promise<WalletAccountEvm>;
62
64
  /**
@@ -66,7 +68,7 @@ export default class WalletManagerEvm extends WalletManager {
66
68
  * @param {Object} [options] - Account options.
67
69
  * @param {string} [options.signerName] - The signer name. Omit to use the default signer.
68
70
  * @returns {Promise<WalletAccountEvm>} The account.
69
- * @throws {Error} If a signer name is given but no signer exists with that name.
71
+ * @throws {NoSuchElementError} If a signer name is given but no signer exists with that name.
70
72
  * @throws {InvalidSignerError} If the signer doesn't support account derivation.
71
73
  */
72
74
  getAccountByPath(path: string, options?: {
@@ -76,6 +78,7 @@ export default class WalletManagerEvm extends WalletManager {
76
78
  * Returns the current fee rates.
77
79
  *
78
80
  * @returns {Promise<FeeRates>} The fee rates (in weis).
81
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
79
82
  */
80
83
  getFeeRates(): Promise<FeeRates>;
81
84
  }
@@ -83,6 +86,7 @@ export type ISignerEvm = import("./signers/seed-signer-evm.js").ISignerEvm;
83
86
  export type Provider = import("ethers").Provider;
84
87
  export type FeeRates = import("@tetherto/wdk-wallet").FeeRates;
85
88
  export type ISigner = import("@tetherto/wdk-wallet").ISigner;
89
+ export type NoSuchElementError = import("@tetherto/wdk-wallet").NoSuchElementError;
86
90
  export type EvmWalletConfig = import("./wallet-account-evm.js").EvmWalletConfig;
87
91
  import WalletManager from '@tetherto/wdk-wallet';
88
92
  import WalletAccountEvm from './wallet-account-evm.js';