@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,52 +14,77 @@
14
14
 
15
15
  'use strict'
16
16
 
17
- import { verifyMessage } from 'ethers'
17
+ import { MaximumFeeExceededError, ProviderRequiredError, ValueError } from '@tetherto/wdk-wallet'
18
18
 
19
- import * as bip39 from 'bip39'
19
+ import { Contract, Transaction, ZeroAddress } from 'ethers'
20
20
 
21
21
  import WalletAccountReadOnlyEvm from './wallet-account-read-only-evm.js'
22
22
 
23
- import MemorySafeHDNodeWallet from './memory-safe/hd-node-wallet.js'
23
+ import SeedSignerEvm from './signers/seed-signer-evm.js'
24
+ import PrivateKeySignerEvm from './signers/private-key-signer-evm.js'
25
+ import { populateTransactionEvm } from './utils/tx-populator-evm.js'
24
26
 
27
+ /** @typedef {import('./signers/seed-signer-evm.js').ISignerEvm} ISignerEvm */
25
28
  /** @typedef {import('ethers').HDNodeWallet} HDNodeWallet */
29
+ /** @typedef {import('ethers').AuthorizationRequest} AuthorizationRequest */
30
+ /** @typedef {import('ethers').Authorization} Authorization */
31
+ /** @typedef {import('ethers').AuthorizationLike} AuthorizationLike */
26
32
 
27
33
  /** @typedef {import('@tetherto/wdk-wallet').IWalletAccount} IWalletAccount */
28
34
 
29
35
  /** @typedef {import('@tetherto/wdk-wallet').KeyPair} KeyPair */
30
36
  /** @typedef {import('@tetherto/wdk-wallet').TransactionResult} TransactionResult */
31
- /** @typedef {import('@tetherto/wdk-wallet').TransferOptions} TransferOptions */
32
37
  /** @typedef {import('@tetherto/wdk-wallet').TransferResult} TransferResult */
33
38
 
39
+ /** @typedef {import('./wallet-account-read-only-evm.js').TypedData} TypedData */
34
40
  /** @typedef {import('./wallet-account-read-only-evm.js').EvmTransaction} EvmTransaction */
41
+ /** @typedef {import('./wallet-account-read-only-evm.js').EvmTransferOptions} EvmTransferOptions */
42
+ /** @typedef {import('./wallet-account-read-only-evm.js').EvmGasOverrides} EvmGasOverrides */
35
43
  /** @typedef {import('./wallet-account-read-only-evm.js').EvmWalletConfig} EvmWalletConfig */
36
44
 
37
- const BIP_44_ETH_DERIVATION_PATH_PREFIX = "m/44'/60'"
45
+ /**
46
+ * @typedef {Object} ApproveOptions
47
+ * @property {string} token - The address of the token to approve.
48
+ * @property {string} spender - The spender's address.
49
+ * @property {number | bigint} amount - The amount of tokens to approve to the spender.
50
+ */
38
51
 
39
- /** @implements {IWalletAccount} */
52
+ /**
53
+ * The options of a token approval, extended with the optional gas overrides of an evm transaction.
54
+ *
55
+ * @typedef {ApproveOptions & EvmGasOverrides} EvmApproveOptions
56
+ */
57
+
58
+ const USDT_MAINNET_ADDRESS = '0xdAC17F958D2ee523a2206206994597C13D831ec7'
59
+
60
+ const DELEGATION_TX_GAS_LIMIT = 100_000
61
+
62
+ /** @implements {IWalletAccount<string>} */
40
63
  export default class WalletAccountEvm extends WalletAccountReadOnlyEvm {
41
64
  /**
42
- * Creates a new evm wallet account.
65
+ * Creates a new evm wallet account from a BIP-39 seed, deriving the account's key at the
66
+ * given BIP-44 path.
43
67
  *
44
- * @param {string | Uint8Array} seed - The wallet's [BIP-39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) seed phrase.
68
+ * @overload
69
+ * @param {string | Uint8Array} seed - A BIP-39 mnemonic seed phrase, or a raw BIP-32 master seed (16-64 bytes).
45
70
  * @param {string} path - The BIP-44 derivation path (e.g. "0'/0/0").
46
71
  * @param {EvmWalletConfig} [config] - The configuration object.
47
72
  */
48
- constructor (seed, path, config = {}) {
49
- if (typeof seed === 'string') {
50
- if (!bip39.validateMnemonic(seed)) {
51
- throw new Error('The seed phrase is invalid.')
52
- }
53
73
 
54
- seed = bip39.mnemonicToSeedSync(seed)
55
- }
56
-
57
- path = BIP_44_ETH_DERIVATION_PATH_PREFIX + '/' + path
74
+ /**
75
+ * Creates a new evm wallet account using a signer.
76
+ *
77
+ * @overload
78
+ * @param {ISignerEvm} signer - A signer implementing the EVM signer interface.
79
+ * @param {EvmWalletConfig} [config] - The configuration object.
80
+ */
58
81
 
59
- const account = MemorySafeHDNodeWallet.fromSeed(seed)
60
- .derivePath(path)
82
+ constructor (seedOrSigner, pathOrConfig = {}, config = {}) {
83
+ const [signer, configuration] = typeof seedOrSigner === 'string' || seedOrSigner instanceof Uint8Array
84
+ ? [new SeedSignerEvm(seedOrSigner, { path: pathOrConfig, isChild: true }), config]
85
+ : [seedOrSigner, pathOrConfig]
61
86
 
62
- super(account.address, config)
87
+ super(signer.address, configuration)
63
88
 
64
89
  /**
65
90
  * The wallet account configuration.
@@ -67,19 +92,10 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm {
67
92
  * @protected
68
93
  * @type {EvmWalletConfig}
69
94
  */
70
- this._config = config
71
-
72
- /**
73
- * The account.
74
- *
75
- * @protected
76
- * @type {HDNodeWallet}
77
- */
78
- this._account = account
95
+ this._config = configuration
79
96
 
80
- if (this._provider) {
81
- this._account = this._account.connect(this._provider)
82
- }
97
+ /** @private */
98
+ this._signer = signer
83
99
  }
84
100
 
85
101
  /**
@@ -88,7 +104,7 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm {
88
104
  * @type {number}
89
105
  */
90
106
  get index () {
91
- return this._account.index
107
+ return this._signer.index
92
108
  }
93
109
 
94
110
  /**
@@ -97,19 +113,45 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm {
97
113
  * @type {string}
98
114
  */
99
115
  get path () {
100
- return this._account.path
116
+ return this._signer.path
101
117
  }
102
118
 
103
119
  /**
104
120
  * The account's key pair.
105
121
  *
122
+ * The uint8 arrays are bound to the wallet account, so any external change will reflect to the internal representation. For this reason,
123
+ * it's strongly recommended to treat the key pair as a read-only view of the keys. While it's still technically possible to alter their
124
+ * content, client code should never do so.
125
+ *
106
126
  * @type {KeyPair}
107
127
  */
108
128
  get keyPair () {
109
- return {
110
- privateKey: this._account.privateKeyBuffer,
111
- publicKey: this._account.publicKeyBuffer
112
- }
129
+ return this._signer.keyPair
130
+ }
131
+
132
+ /**
133
+ * Creates a new evm wallet account from a raw private key.
134
+ *
135
+ * @param {string | Uint8Array} privateKey - The raw private key (hex string with or without 0x, or 32 bytes).
136
+ * @param {EvmWalletConfig} [config] - The configuration object.
137
+ * @returns {WalletAccountEvm} The wallet account.
138
+ */
139
+ static fromPrivateKey (privateKey, config = {}) {
140
+ const signer = new PrivateKeySignerEvm(privateKey)
141
+ return new WalletAccountEvm(signer, config)
142
+ }
143
+
144
+ /**
145
+ * Returns the account's address. If it wasn't resolved at construction time (e.g hardware signers), it asks the
146
+ * underlying signer to resolve it, then caches it locally.
147
+ *
148
+ * @returns {Promise<string>} The account's address.
149
+ */
150
+ async getAddress () {
151
+ if (this._address) return this._address
152
+ const addr = await this._signer.getAddress()
153
+ this.__address = addr
154
+ return addr
113
155
  }
114
156
 
115
157
  /**
@@ -119,82 +161,249 @@ export default class WalletAccountEvm extends WalletAccountReadOnlyEvm {
119
161
  * @returns {Promise<string>} The message's signature.
120
162
  */
121
163
  async sign (message) {
122
- return await this._account.signMessage(message)
164
+ return await this._signer.sign(message)
123
165
  }
124
166
 
125
167
  /**
126
- * Verifies a message's signature.
168
+ * Signs typed data according to EIP-712.
127
169
  *
128
- * @param {string} message - The original message.
129
- * @param {string} signature - The signature to verify.
130
- * @returns {Promise<boolean>} True if the signature is valid.
170
+ * @param {TypedData} typedData - The typed data to sign.
171
+ * @returns {Promise<string>} The typed data signature.
131
172
  */
132
- async verify (message, signature) {
133
- const address = await verifyMessage(message, signature)
173
+ async signTypedData ({ domain, types, message }) {
174
+ return await this._signer.signTypedData({ domain, types, message })
175
+ }
134
176
 
135
- return address.toLowerCase() === this._account.address.toLowerCase()
177
+ /**
178
+ * Signs a transaction.
179
+ *
180
+ * If a provider is set, it also estimates the transaction's costs and checks them against the transaction max. fee option.
181
+ *
182
+ * @param {EvmTransaction} tx - The transaction to sign.
183
+ * @returns {Promise<string>} The signed transaction as a hex string.
184
+ * @throws {MaximumFeeExceededError} If a provider is set, and the transaction's cost surpasses the transaction max. fee option.
185
+ */
186
+ async signTransaction (tx) {
187
+ if (this._provider && this._config.transactionMaxFee !== undefined) {
188
+ const { fee } = await this.quoteSendTransaction(tx)
189
+
190
+ if (fee > this._config.transactionMaxFee) {
191
+ throw new MaximumFeeExceededError('Exceeded maximum fee cost for transaction operation.')
192
+ }
193
+ }
194
+ return await this._signer.signTransaction({
195
+ from: await this.getAddress(),
196
+ ...tx
197
+ })
136
198
  }
137
199
 
138
200
  /**
139
201
  * Sends a transaction.
140
202
  *
141
- * @param {EvmTransaction} tx - The transaction.
203
+ * @param {EvmTransaction | string} tx - The transaction, or a signed raw transaction as a hex string.
142
204
  * @returns {Promise<TransactionResult>} The transaction's result.
205
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
206
+ * @throws {MaximumFeeExceededError} If the transaction's cost exceeds the maximum transaction fee option.
207
+ * @throws {ValueError} If the transaction mixes fee fields that its type doesn't support, or a type 3 transaction omits `maxFeePerBlobGas`.
143
208
  */
144
209
  async sendTransaction (tx) {
145
- if (!this._account.provider) {
146
- throw new Error('The wallet must be connected to a provider to send transactions.')
210
+ if (!this._provider) {
211
+ throw new ProviderRequiredError('The wallet must be connected to a provider to send transactions.')
147
212
  }
148
-
149
213
  const { fee } = await this.quoteSendTransaction(tx)
214
+ if (this._config.transactionMaxFee !== undefined && fee > this._config.transactionMaxFee) {
215
+ throw new MaximumFeeExceededError('Exceeded maximum fee cost for transaction operation.')
216
+ }
150
217
 
151
- const { hash } = await this._account.sendTransaction({
152
- from: await this.getAddress(),
153
- ...tx
154
- })
218
+ if (typeof tx === 'string') {
219
+ const hash = await this._provider.send('eth_sendRawTransaction', [tx])
220
+ return { hash, fee }
221
+ }
155
222
 
223
+ // Build, sign and broadcast raw transaction using the signer
224
+ const from = await this.getAddress()
225
+ const unsignedTx = await populateTransactionEvm(this._provider, from, tx)
226
+ const signed = await this._signer.signTransaction(unsignedTx)
227
+ const hash = await this._provider.send('eth_sendRawTransaction', [signed])
156
228
  return { hash, fee }
157
229
  }
158
230
 
231
+ /**
232
+ * Quotes the costs of a send transaction operation.
233
+ *
234
+ * The transaction is always simulated through gas estimation, so one that would revert is rejected here instead of
235
+ * reaching the signer. A `gasLimit` set on the transaction replaces the estimated gas in the quote, and a `maxFeePerGas`
236
+ * (or `gasPrice`) set on it replaces the fee rate fetched from the provider, so the quote is the transaction's maximum
237
+ * cost as it will be sent.
238
+ * A signed raw transaction is simulated the same way and quoted from its own gas limit and fee cap.
239
+ *
240
+ * @param {EvmTransaction | string} tx - The transaction, or a signed raw transaction as a hex string.
241
+ * @returns {Promise<Omit<TransactionResult, 'hash'>>} The transaction's quotes.
242
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
243
+ * @throws {Error} If the simulation of the transaction reverts, as an ethers error with code `CALL_EXCEPTION`.
244
+ */
245
+ async quoteSendTransaction (tx) {
246
+ if (typeof tx === 'string') {
247
+ if (!this._provider) {
248
+ throw new ProviderRequiredError('The wallet must be connected to a provider to quote send transaction operations.')
249
+ }
250
+
251
+ const { from, to, value, data, gasLimit, gasPrice, maxFeePerGas, maxPriorityFeePerGas, type, nonce, chainId, authorizationList } = Transaction.from(tx)
252
+
253
+ await this._estimateGas({ from, to, value, data, gasLimit, gasPrice, maxFeePerGas, maxPriorityFeePerGas, type, nonce, chainId, authorizationList })
254
+
255
+ return { fee: gasLimit * (maxFeePerGas ?? gasPrice) }
256
+ }
257
+
258
+ return await super.quoteSendTransaction(tx)
259
+ }
260
+
159
261
  /**
160
262
  * Transfers a token to another address.
161
263
  *
162
- * @param {TransferOptions} options - The transfer's options.
264
+ * @param {EvmTransferOptions} options - The transfer's options, including any gas overrides to carry onto the transaction.
163
265
  * @returns {Promise<TransferResult>} The transfer's result.
266
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
267
+ * @throws {MaximumFeeExceededError} If the transfer's cost exceeds the maximum transfer fee option.
164
268
  */
165
269
  async transfer (options) {
166
- if (!this._account.provider) {
167
- throw new Error('The wallet must be connected to a provider to transfer tokens.')
270
+ if (!this._provider) {
271
+ throw new ProviderRequiredError('The wallet must be connected to a provider to transfer tokens.')
168
272
  }
169
273
 
170
274
  const tx = await WalletAccountEvm._getTransferTransaction(options)
171
275
 
172
276
  const { fee } = await this.quoteSendTransaction(tx)
173
277
 
174
- if (this._config.transferMaxFee !== undefined && fee >= this._config.transferMaxFee) {
175
- throw new Error('Exceeded maximum fee cost for transfer operation.')
278
+ if (this._config.transferMaxFee !== undefined && fee > this._config.transferMaxFee) {
279
+ throw new MaximumFeeExceededError('Exceeded maximum fee cost for transfer operation.')
176
280
  }
177
281
 
178
- const { hash } = await this._account.sendTransaction(tx)
282
+ const { hash } = await this.sendTransaction(tx)
179
283
 
180
284
  return { hash, fee }
181
285
  }
182
286
 
287
+ /**
288
+ * Approves a specific amount of tokens to a spender.
289
+ *
290
+ * @param {EvmApproveOptions} options - The approve options, including any gas overrides to carry onto the transaction.
291
+ * @returns {Promise<TransactionResult>} The transaction's result.
292
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
293
+ * @throws {ValueError} If trying to approve usdts on ethereum with allowance not equal to zero (due to the usdt allowance reset requirement).
294
+ */
295
+ async approve (options) {
296
+ if (!this._provider) {
297
+ throw new ProviderRequiredError('The wallet must be connected to a provider to approve funds.')
298
+ }
299
+
300
+ const { token, spender, amount } = options
301
+ const { chainId } = await this._provider.getNetwork()
302
+
303
+ if (chainId === 1n && token.toLowerCase() === USDT_MAINNET_ADDRESS.toLowerCase()) {
304
+ const currentAllowance = await this.getAllowance(token, spender)
305
+ if (currentAllowance > 0n && BigInt(amount) > 0n) {
306
+ throw new ValueError(
307
+ '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.'
308
+ )
309
+ }
310
+ }
311
+
312
+ const abi = ['function approve(address spender, uint256 amount) returns (bool)']
313
+ const contract = new Contract(token, abi, this._provider)
314
+
315
+ const tx = {
316
+ to: token,
317
+ value: 0,
318
+ data: contract.interface.encodeFunctionData('approve', [spender, amount]),
319
+ ...WalletAccountReadOnlyEvm._getGasOverrides(options)
320
+ }
321
+
322
+ return await this.sendTransaction(tx)
323
+ }
324
+
183
325
  /**
184
326
  * Returns a read-only copy of the account.
185
327
  *
186
328
  * @returns {Promise<WalletAccountReadOnlyEvm>} The read-only account.
187
329
  */
188
330
  async toReadOnlyAccount () {
189
- const readOnlyAccount = new WalletAccountReadOnlyEvm(this._account.address, this._config)
331
+ if (!this._evmReadOnlyAccount) {
332
+ this._evmReadOnlyAccount = new WalletAccountReadOnlyEvm(await this.getAddress(), this._config)
333
+ }
334
+
335
+ return this._evmReadOnlyAccount
336
+ }
190
337
 
191
- return readOnlyAccount
338
+ /**
339
+ * Signs an ERC-7702 authorization tuple.
340
+ *
341
+ * @param {AuthorizationRequest} auth - The authorization request.
342
+ * @returns {Promise<Authorization>} The signed authorization.
343
+ */
344
+ async signAuthorization (auth) {
345
+ const populated = { ...auth }
346
+ if (this._provider) {
347
+ if (populated.chainId == null) {
348
+ const { chainId } = await this._provider.getNetwork()
349
+ populated.chainId = chainId
350
+ }
351
+ if (populated.nonce == null) {
352
+ const address = await this.getAddress()
353
+ populated.nonce = await this._provider.getTransactionCount(address)
354
+ }
355
+ }
356
+ return await this._signer.signAuthorization(populated)
357
+ }
358
+
359
+ /**
360
+ * Delegates this EOA to a smart contract via an ERC-7702 type 4 transaction.
361
+ *
362
+ * The transaction is sent to the EOA itself with zero value and no data.
363
+ * A fixed gas limit is used because `eth_estimateGas` may revert when
364
+ * the delegate contract lacks a `receive`/`fallback` function.
365
+ *
366
+ * @param {string} delegateAddress - The address of the contract to delegate to.
367
+ * @returns {Promise<TransactionResult>} The transaction result.
368
+ * @throws {ProviderRequiredError} If the wallet is not connected to a provider.
369
+ */
370
+ async delegate (delegateAddress) {
371
+ if (!this._provider) {
372
+ throw new ProviderRequiredError('The wallet must be connected to a provider to delegate.')
373
+ }
374
+
375
+ const address = await this.getAddress()
376
+ const nonceHex = await this._provider.send('eth_getTransactionCount', [address, 'latest'])
377
+ const nonce = Number(nonceHex)
378
+
379
+ const auth = await this.signAuthorization({
380
+ address: delegateAddress,
381
+ nonce: nonce + 1
382
+ })
383
+
384
+ return await this.sendTransaction({
385
+ type: 4,
386
+ nonce,
387
+ to: address,
388
+ value: 0,
389
+ gasLimit: DELEGATION_TX_GAS_LIMIT,
390
+ authorizationList: [auth]
391
+ })
392
+ }
393
+
394
+ /**
395
+ * Revokes any active ERC-7702 delegation by delegating to the zero address.
396
+ *
397
+ * @returns {Promise<TransactionResult>} The transaction result.
398
+ */
399
+ async revokeDelegation () {
400
+ return await this.delegate(ZeroAddress)
192
401
  }
193
402
 
194
403
  /**
195
404
  * Disposes the wallet account, erasing the private key from the memory.
196
405
  */
197
406
  dispose () {
198
- this._account.dispose()
407
+ this._signer.dispose()
199
408
  }
200
409
  }