@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.
@@ -0,0 +1,314 @@
1
+ // Copyright 2024 Tether Operations Limited
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ 'use strict'
15
+
16
+ import * as bip39 from 'bip39'
17
+
18
+ import MemorySafeHDNodeWallet from '../memory-safe/hd-node-wallet.js'
19
+ import { ISigner, InvalidSignerError, NotImplementedError, ValueError } from '@tetherto/wdk-wallet'
20
+
21
+ const BIP_44_ETH_DERIVATION_PATH_PREFIX = "m/44'/60'"
22
+
23
+ // Relative path of the account derived when none is provided.
24
+ const DEFAULT_ACCOUNT_PATH = "0'/0/0"
25
+
26
+ /** @typedef {import('../utils/tx-populator-evm.js').UnsignedEvmTransaction} UnsignedEvmTransaction */
27
+ /** @typedef {import('@tetherto/wdk-wallet').ISigner} ISigner */
28
+ /** @typedef {import('@tetherto/wdk-wallet').KeyPair} KeyPair */
29
+ /** @typedef {import('ethers').AuthorizationRequest} AuthorizationRequest */
30
+ /** @typedef {import('ethers').Authorization} Authorization */
31
+ /** @typedef {import('../wallet-account-read-only-evm.js').TypedData} TypedData */
32
+ /** @typedef {import('../memory-safe/hd-node-wallet.js').default} MemorySafeHDNodeWallet */
33
+
34
+ /**
35
+ * @typedef {Object} SeedSignerEvmOpts
36
+ * @property {MemorySafeHDNodeWallet} [root] - An existing HD node wallet root to derive from.
37
+ * @property {string} [path] - Relative BIP-44 path segment (e.g. "0'/0/0"). Defaults to the account at index 0.
38
+ * @property {boolean} [isChild] - When true, the signer is a derived child and does not retain the root.
39
+ */
40
+
41
+ /**
42
+ * Interface for EVM signers, extending the base `ISigner` from `@tetherto/wdk-wallet`.
43
+ *
44
+ * @extends {ISigner}
45
+ * @interface
46
+ */
47
+ export class ISignerEvm extends ISigner {
48
+ /**
49
+ * Whether this signer can derive child signers (i.e. it holds an HD root). Non-derivable
50
+ * signers (e.g. private-key signers) are bound directly to an account; derivable signers
51
+ * derive child accounts and keep the root for management only.
52
+ * @type {boolean}
53
+ */
54
+ get isDerivable () {
55
+ throw new NotImplementedError('isDerivable')
56
+ }
57
+
58
+ /**
59
+ * The last component index for the derivation path of this signer, when applicable.
60
+ * @type {number|undefined}
61
+ */
62
+ get index () {
63
+ throw new NotImplementedError('index')
64
+ }
65
+
66
+ /**
67
+ * The full derivation path if this is a child signer.
68
+ * @type {string|undefined}
69
+ */
70
+ get path () {
71
+ throw new NotImplementedError('path')
72
+ }
73
+
74
+ /**
75
+ * The account's address, if available.
76
+ * @type {string|undefined}
77
+ */
78
+ get address () {
79
+ throw new NotImplementedError('address')
80
+ }
81
+
82
+ /**
83
+ * The account's key pair.
84
+ * @type {KeyPair}
85
+ */
86
+ get keyPair () {
87
+ throw new NotImplementedError('keyPair')
88
+ }
89
+
90
+ /**
91
+ * Derive a child signer from this signer using a relative path (e.g. "0'/0/0").
92
+ *
93
+ * @param {string} relPath - The relative BIP-44 path segment.
94
+ * @returns {Promise<ISignerEvm>} The derived child signer.
95
+ * @throws {InvalidSignerError} If the signer does not support derivation (e.g. private-key signers).
96
+ */
97
+ async derive (relPath) {
98
+ throw new NotImplementedError('derive(relPath)')
99
+ }
100
+
101
+ /**
102
+ * Returns the account's address.
103
+ * @returns {Promise<string>}
104
+ */
105
+ async getAddress () {
106
+ throw new NotImplementedError('getAddress()')
107
+ }
108
+
109
+ /**
110
+ * Sign a plain message.
111
+ * @param {string} message
112
+ * @returns {Promise<string>}
113
+ */
114
+ async sign (message) {
115
+ throw new NotImplementedError('sign(message)')
116
+ }
117
+
118
+ /**
119
+ * Sign a transaction-like object compatible with ethers Transaction.from.
120
+ * @param {UnsignedEvmTransaction} unsignedTx
121
+ * @returns {Promise<string>} The serialized signed transaction hex.
122
+ */
123
+ async signTransaction (unsignedTx) {
124
+ throw new NotImplementedError('signTransaction(unsignedTx)')
125
+ }
126
+
127
+ /**
128
+ * Signs typed data according to EIP-712.
129
+ *
130
+ * @param {TypedData} typedData - The typed data to sign.
131
+ * @returns {Promise<string>} The typed data signature.
132
+ */
133
+ async signTypedData ({ domain, types, message }) {
134
+ throw new NotImplementedError('signTypedData(typedData)')
135
+ }
136
+
137
+ /**
138
+ * Sign an ERC-7702 authorization tuple.
139
+ * @param {AuthorizationRequest} auth
140
+ * @returns {Promise<Authorization>}
141
+ */
142
+ async signAuthorization (auth) {
143
+ throw new NotImplementedError('signAuthorization(auth)')
144
+ }
145
+
146
+ /** Clear any secret material from memory. */
147
+ dispose () {
148
+ throw new NotImplementedError('dispose()')
149
+ }
150
+ }
151
+
152
+ /**
153
+ * @extends {ISignerEvm}
154
+ * Signer implementation that derives keys from a BIP-39 seed using the BIP-44 Ethereum path.
155
+ * Always holds a derived account (index 0 by default). A root signer also retains the HD root
156
+ * and can derive child signers; a derived child holds only its own account.
157
+ */
158
+ export default class SeedSignerEvm extends ISignerEvm {
159
+ /**
160
+ * Create a SeedSignerEvm.
161
+ * Provide either a mnemonic/seed or an existing root via opts.root (for children root is not stored internally)
162
+ *
163
+ * @param {string|Uint8Array|null} seed - A BIP-39 mnemonic seed phrase, or a raw BIP-32 master seed (16-64 bytes). Omit when providing `opts.root`.
164
+ * @param {SeedSignerEvmOpts} [opts] - Construction options for root reuse, direct child derivation or path definition (default is index 0).
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.
167
+ */
168
+ constructor (seed, opts = {}) {
169
+ super()
170
+
171
+ // If a root is provided, do not expect a seed
172
+ if (opts.root && seed) {
173
+ throw new ValueError('Provide either a seed or a root, not both.')
174
+ }
175
+
176
+ if (!opts.root && !seed) {
177
+ throw new ValueError('Seed or root is required.')
178
+ }
179
+
180
+ if (typeof seed === 'string') {
181
+ if (!bip39.validateMnemonic(seed)) {
182
+ throw new ValueError('The seed phrase is invalid.')
183
+ }
184
+ seed = bip39.mnemonicToSeedSync(seed)
185
+ }
186
+
187
+ const root = opts.root || (seed ? MemorySafeHDNodeWallet.fromSeed(seed) : undefined)
188
+
189
+ const fullPath = `${BIP_44_ETH_DERIVATION_PATH_PREFIX}/${opts.path || DEFAULT_ACCOUNT_PATH}`
190
+ const account = root.derivePath(fullPath)
191
+
192
+ if (opts.isChild && !opts.root) root.dispose()
193
+
194
+ /** @private */
195
+ this._account = account
196
+ /** @private */
197
+ this._address = account.address
198
+ /** @private */
199
+ this._path = fullPath
200
+ /** @private */
201
+ this._root = opts.isChild ? undefined : root
202
+ }
203
+
204
+ /**
205
+ * Whether this signer can derive child signers. True for a root signer (which holds the
206
+ * HD root); false for a derived child, which does not retain the root.
207
+ * @type {boolean}
208
+ */
209
+ get isDerivable () {
210
+ return Boolean(this._root)
211
+ }
212
+
213
+ /**
214
+ * The last component index of the derivation path, if available.
215
+ * @type {number|undefined}
216
+ */
217
+ get index () {
218
+ if (!this._path) return undefined
219
+ return +this._path.split('/').pop()
220
+ }
221
+
222
+ /**
223
+ * The full derivation path of this signer's account.
224
+ * @type {string|undefined}
225
+ */
226
+ get path () {
227
+ return this._path
228
+ }
229
+
230
+ /**
231
+ * The account's derived address.
232
+ * @type {string}
233
+ */
234
+ get address () {
235
+ return this._address
236
+ }
237
+
238
+ /**
239
+ * The account's key pair (private and public key buffers).
240
+ * @type {KeyPair}
241
+ */
242
+ get keyPair () {
243
+ return {
244
+ privateKey: this._account ? this._account.privateKeyBuffer : null,
245
+ publicKey: this._account ? this._account.publicKeyBuffer : null
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Derive a child signer using the provided relative path (e.g. "0'/0/0").
251
+ * @param {string} relPath
252
+ * @returns {Promise<SeedSignerEvm>}
253
+ * @throws {InvalidSignerError} If called on a derived child signer, which does not retain the root.
254
+ */
255
+ async derive (relPath) {
256
+ if (!this._root) {
257
+ throw new InvalidSignerError('Cannot derive: this signer has no root (it is a derived child or has been disposed).')
258
+ }
259
+ return new SeedSignerEvm(null, { root: this._root, path: relPath, isChild: true })
260
+ }
261
+
262
+ /**
263
+ * Returns the account's derived address.
264
+ * @returns {Promise<string>}
265
+ */
266
+ async getAddress () {
267
+ return this._address
268
+ }
269
+
270
+ /**
271
+ * Sign a plain message string.
272
+ * @param {string} message
273
+ * @returns {Promise<string>}
274
+ */
275
+ async sign (message) {
276
+ return this._account.signMessage(message)
277
+ }
278
+
279
+ /**
280
+ * Sign a transaction object and return its serialized form.
281
+ * @param {UnsignedEvmTransaction} unsignedTx
282
+ * @returns {Promise<string>}
283
+ */
284
+ async signTransaction (unsignedTx) {
285
+ return this._account.signTransaction(unsignedTx)
286
+ }
287
+
288
+ /**
289
+ * Signs typed data according to EIP-712.
290
+ *
291
+ * @param {TypedData} typedData - The typed data to sign.
292
+ * @returns {Promise<string>} The typed data signature.
293
+ */
294
+ async signTypedData ({ domain, types, message }) {
295
+ return this._account.signTypedData(domain, types, message)
296
+ }
297
+
298
+ /**
299
+ * Sign an ERC-7702 authorization tuple.
300
+ * @param {AuthorizationRequest} auth
301
+ * @returns {Promise<Authorization>}
302
+ */
303
+ async signAuthorization (auth) {
304
+ return this._account.authorizeSync(auth)
305
+ }
306
+
307
+ /** Disposes secrets from memory. */
308
+ dispose () {
309
+ if (this._account) this._account.dispose()
310
+ this._account = undefined
311
+ if (this._root) this._root.dispose()
312
+ this._root = undefined
313
+ }
314
+ }
@@ -0,0 +1,202 @@
1
+ // Copyright 2024 Tether Operations Limited
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ 'use strict'
15
+
16
+ import { ValueError } from '@tetherto/wdk-wallet'
17
+
18
+ import { Signature, toQuantity } from 'ethers'
19
+
20
+ /** @typedef {import('ethers').Provider} Provider */
21
+ /** @typedef {import('ethers').AuthorizationLike} AuthorizationLike */
22
+
23
+ /**
24
+ * A fully or partially specified EVM transaction, prior to signing.
25
+ *
26
+ * @typedef {Object} UnsignedEvmTransaction
27
+ * @property {number} chainId - The id of the chain the transaction targets.
28
+ * @property {number} nonce - The sender's transaction count, used to order transactions.
29
+ * @property {string} from - The sender's address.
30
+ * @property {string|null} to - The recipient's address, or null for contract creation.
31
+ * @property {string} data - The transaction's calldata as a hex string.
32
+ * @property {number|bigint} value - The amount of native currency (in wei) to transfer.
33
+ * @property {number} type - The EIP-2718 transaction type (0/1 legacy, 2 EIP-1559, 3 EIP-4844, 4 EIP-7702).
34
+ * @property {number|bigint} gasLimit - The maximum amount of gas the transaction may consume.
35
+ * @property {number|bigint} [gasPrice] - The gas price (in wei) for legacy (type 0/1) transactions.
36
+ * @property {number|bigint} [maxFeePerGas] - The maximum total fee (in wei) per gas for EIP-1559 transactions.
37
+ * @property {number|bigint} [maxPriorityFeePerGas] - The maximum priority fee (in wei) per gas for EIP-1559 transactions.
38
+ * @property {any[]} [accessList] - The EIP-2930 access list of addresses and storage keys.
39
+ * @property {number|bigint} [maxFeePerBlobGas] - The maximum fee (in wei) per blob gas for EIP-4844 transactions.
40
+ * @property {any[]} [blobs] - The blobs to include in an EIP-4844 transaction.
41
+ * @property {string[]} [blobVersionedHashes] - The versioned hashes of the EIP-4844 blobs.
42
+ * @property {AuthorizationLike[]} [authorizationList] - The EIP-7702 authorization tuples.
43
+ */
44
+
45
+ /**
46
+ * Build a fully populated unsigned transaction ready for signing.
47
+ *
48
+ * Resolves chain ID, nonce, gas limit and fee fields from the provider when not
49
+ * explicitly supplied in `tx`. Supports legacy (type 0/1), EIP-1559 (type 2),
50
+ * EIP-4844 (type 3) and EIP-7702 (type 4) transaction styles.
51
+ *
52
+ * @param {Provider} provider - An ethers-compatible JSON-RPC provider.
53
+ * @param {string} from - The sender address.
54
+ * @param {UnsignedEvmTransaction} tx - The partial transaction to populate.
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`.
57
+ */
58
+ export async function populateTransactionEvm (provider, from, tx) {
59
+ const net = await provider.getNetwork()
60
+ const chainId = Number(net.chainId)
61
+
62
+ const has1559 = (tx.maxFeePerGas != null || tx.maxPriorityFeePerGas != null)
63
+ const hasLegacy = (tx.gasPrice != null)
64
+ const hasAccessList = (tx.accessList != null && Array.isArray(tx.accessList))
65
+ const hasBlobs = (tx.blobs != null || tx.blobVersionedHashes != null || tx.maxFeePerBlobGas != null)
66
+ const hasAuthList = (tx.authorizationList != null && Array.isArray(tx.authorizationList))
67
+
68
+ const explicitType = (tx.type != null) ? Number(tx.type) : null
69
+
70
+ if ((explicitType === 2 || (explicitType == null && has1559)) && hasLegacy) {
71
+ throw new ValueError('eip-1559 transaction does not support gasPrice')
72
+ }
73
+ if ((explicitType === 0 || explicitType === 1) && has1559) {
74
+ throw new ValueError('pre-eip-1559 transaction does not support maxFeePerGas/maxPriorityFeePerGas')
75
+ }
76
+ if ((explicitType === 3 || hasBlobs) && hasLegacy) {
77
+ throw new ValueError('blob transaction does not support gasPrice')
78
+ }
79
+ if ((explicitType === 4 || (explicitType == null && hasAuthList)) && hasLegacy) {
80
+ throw new ValueError('eip-7702 transaction does not support gasPrice')
81
+ }
82
+
83
+ const feeData = await provider.getFeeData()
84
+
85
+ let type = explicitType
86
+ if (type == null) {
87
+ if (hasAuthList) {
88
+ type = 4
89
+ } else if (hasBlobs) {
90
+ type = 3
91
+ } else if (feeData.maxFeePerGas != null && feeData.maxPriorityFeePerGas != null) {
92
+ type = 2
93
+ } else {
94
+ type = 0
95
+ }
96
+ }
97
+
98
+ let gasLimit
99
+ if (tx.gasLimit != null) {
100
+ gasLimit = tx.gasLimit
101
+ } else if (hasAuthList) {
102
+ gasLimit = await _estimateGasWithAuthList(provider, { from, ...tx })
103
+ } else {
104
+ gasLimit = await provider.estimateGas({ from, to: tx.to ?? null, data: tx.data ?? '0x', value: tx.value ?? 0 })
105
+ }
106
+
107
+ const populated = {
108
+ from,
109
+ to: tx.to ?? null,
110
+ data: tx.data ?? '0x',
111
+ value: tx.value ?? 0,
112
+ chainId,
113
+ nonce: (tx.nonce != null) ? Number(tx.nonce) : Number(await provider.getTransactionCount(from, 'pending')),
114
+ gasLimit
115
+ }
116
+
117
+ if (type === 0 || type === 1) {
118
+ populated.type = type
119
+ populated.gasPrice = tx.gasPrice ?? feeData.gasPrice ?? feeData.maxFeePerGas
120
+ if (type === 1 && hasAccessList) populated.accessList = tx.accessList
121
+ return populated
122
+ }
123
+
124
+ if (type === 2) {
125
+ populated.type = 2
126
+ if (tx.gasPrice != null) {
127
+ populated.maxFeePerGas = tx.gasPrice
128
+ populated.maxPriorityFeePerGas = tx.gasPrice
129
+ } else {
130
+ populated.maxFeePerGas = tx.maxFeePerGas ?? feeData.maxFeePerGas
131
+ populated.maxPriorityFeePerGas = tx.maxPriorityFeePerGas ?? feeData.maxPriorityFeePerGas
132
+ }
133
+ if (hasAccessList) populated.accessList = tx.accessList
134
+ return populated
135
+ }
136
+
137
+ if (type === 3) {
138
+ populated.type = 3
139
+ populated.maxFeePerGas = tx.maxFeePerGas ?? feeData.maxFeePerGas
140
+ populated.maxPriorityFeePerGas = tx.maxPriorityFeePerGas ?? feeData.maxPriorityFeePerGas
141
+ if (tx.maxFeePerBlobGas == null) throw new ValueError('maxFeePerBlobGas is required for type 3 transactions')
142
+ populated.maxFeePerBlobGas = tx.maxFeePerBlobGas
143
+ if (tx.blobs != null) populated.blobs = tx.blobs
144
+ if (tx.blobVersionedHashes != null) populated.blobVersionedHashes = tx.blobVersionedHashes
145
+ if (hasAccessList) populated.accessList = tx.accessList
146
+ return populated
147
+ }
148
+
149
+ if (type === 4) {
150
+ populated.type = 4
151
+ populated.maxFeePerGas = tx.maxFeePerGas ?? feeData.maxFeePerGas
152
+ populated.maxPriorityFeePerGas = tx.maxPriorityFeePerGas ?? feeData.maxPriorityFeePerGas
153
+ if (hasAccessList) populated.accessList = tx.accessList
154
+ if (tx.authorizationList != null) populated.authorizationList = tx.authorizationList
155
+ return populated
156
+ }
157
+
158
+ // Future types; pass-through
159
+ populated.type = type
160
+ if (hasAccessList) populated.accessList = tx.accessList
161
+ if (hasLegacy) {
162
+ populated.gasPrice = tx.gasPrice
163
+ } else {
164
+ populated.maxFeePerGas = tx.maxFeePerGas ?? feeData.maxFeePerGas
165
+ populated.maxPriorityFeePerGas = tx.maxPriorityFeePerGas ?? feeData.maxPriorityFeePerGas
166
+ }
167
+ if (hasBlobs) {
168
+ populated.maxFeePerBlobGas = tx.maxFeePerBlobGas
169
+ if (tx.blobs != null) populated.blobs = tx.blobs
170
+ if (tx.blobVersionedHashes != null) populated.blobVersionedHashes = tx.blobVersionedHashes
171
+ }
172
+ if (tx.authorizationList != null) populated.authorizationList = tx.authorizationList
173
+
174
+ return populated
175
+ }
176
+
177
+ async function _estimateGasWithAuthList (provider, { from, to, value, data, authorizationList }) {
178
+ const formatAuth = (auth) => {
179
+ const { address, nonce, chainId } = auth
180
+ const signature = auth.signature instanceof Signature
181
+ ? auth.signature
182
+ : Signature.from(auth.signature)
183
+ return {
184
+ address,
185
+ nonce: toQuantity(nonce),
186
+ chainId: toQuantity(chainId),
187
+ r: toQuantity(signature.r),
188
+ s: toQuantity(signature.s),
189
+ yParity: toQuantity(signature.yParity)
190
+ }
191
+ }
192
+ const rpcTx = {
193
+ from,
194
+ to,
195
+ value: toQuantity(value ?? 0),
196
+ data: data ?? '0x',
197
+ type: '0x04',
198
+ authorizationList: authorizationList.map(formatAuth)
199
+ }
200
+ const result = await provider.send('eth_estimateGas', [rpcTx])
201
+ return BigInt(result)
202
+ }