@tetherto/wdk-wallet-evm 1.0.0-beta.13 → 1.0.0-beta.15

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