@tetherto/wdk-wallet-evm 1.0.0-beta.14 → 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.
package/README.md CHANGED
@@ -15,30 +15,299 @@ This module is part of the [**WDK (Wallet Development Kit)**](https://docs.wdk.t
15
15
 
16
16
  For detailed documentation about the complete WDK ecosystem, visit [docs.wdk.tether.io](https://docs.wdk.tether.io).
17
17
 
18
- ## Installation
18
+ ## ⬇️ Installation
19
+
20
+ To install the `@tetherto/wdk-wallet-evm` package, follow these instructions:
21
+
22
+ You can install it using npm:
19
23
 
20
24
  ```bash
21
25
  npm install @tetherto/wdk-wallet-evm
22
26
  ```
23
27
 
24
- ## Quick Start
28
+ ## 🚀 Quick Start
29
+
30
+ ### Importing from `@tetherto/wdk-wallet-evm`
31
+
32
+ ```javascript
33
+ import WalletManagerEvm, {
34
+ WalletAccountEvm,
35
+ WalletAccountReadOnlyEvm,
36
+ } from '@tetherto/wdk-wallet-evm'
37
+
38
+ // Signers are exported under the /signers subpath
39
+ import {
40
+ SeedSignerEvm,
41
+ PrivateKeySignerEvm,
42
+ } from '@tetherto/wdk-wallet-evm/signers'
43
+ ```
44
+
45
+ ### Create a Wallet Manager (seed-based)
46
+
47
+ ```javascript
48
+ import WalletManagerEvm from '@tetherto/wdk-wallet-evm'
49
+ import { SeedSignerEvm } from '@tetherto/wdk-wallet-evm/signers'
50
+
51
+ // Use a BIP-39 seed phrase (replace with your own secure phrase)
52
+ const seedPhrase =
53
+ 'test only example nut use this real life secret phrase must random'
54
+
55
+ // Create a root signer from the seed phrase
56
+ const root = new SeedSignerEvm(seedPhrase)
57
+
58
+ // Create wallet manager with provider config (provider is required for chain ops)
59
+ const wallet = new WalletManagerEvm(root, {
60
+ // Option 1: Using RPC URL
61
+ provider: 'https://sepolia.drpc.org', // any EVM RPC
62
+ transferMaxFee: 100000000000000n, // Optional: max fee in wei (BigInt)
63
+ })
64
+
65
+ // OR
66
+
67
+ // Option 2: Using EIP-1193 provider (e.g., from browser wallet)
68
+ const wallet2 = new WalletManagerEvm(root, {
69
+ provider: window.ethereum, // EIP-1193 provider
70
+ transferMaxFee: 100000000000000n, // Optional
71
+ })
72
+
73
+ // Get a full access account
74
+ const account0 = await wallet.getAccount(0)
75
+
76
+ // Convert to a read-only account
77
+ const readOnlyAccount = await account0.toReadOnlyAccount()
78
+ ```
79
+
80
+ ### Single Account (no manager): Private key
81
+
82
+ ```javascript
83
+ import { WalletAccountEvm } from '@tetherto/wdk-wallet-evm'
84
+ import { PrivateKeySignerEvm } from '@tetherto/wdk-wallet-evm/signers'
85
+
86
+ // From a raw private key (hex string or bytes)
87
+ const pkSigner = new PrivateKeySignerEvm('0x0123...abcd')
88
+ const pkAccount = new WalletAccountEvm(pkSigner, {
89
+ provider: 'https://eth-mainnet.g.alchemy.com/v2/your-api-key',
90
+ })
91
+ ```
92
+
93
+ ### Single Account (no manager): Seed + path
94
+
95
+ ```javascript
96
+ import { WalletAccountEvm } from '@tetherto/wdk-wallet-evm'
97
+
98
+ // From a BIP-39 seed phrase (or seed bytes) and a BIP-44 derivation path
99
+ const account = new WalletAccountEvm(mnemonic, "0'/0/0", {
100
+ provider: 'https://eth-mainnet.g.alchemy.com/v2/your-api-key',
101
+ })
102
+ ```
103
+
104
+ ### Managing Multiple Accounts (seed-based manager)
25
105
 
26
106
  ```javascript
27
107
  import WalletManagerEvm from '@tetherto/wdk-wallet-evm'
108
+ import { SeedSignerEvm } from '@tetherto/wdk-wallet-evm/signers'
109
+
110
+ const root = new SeedSignerEvm(mnemonic)
111
+ const wallet = new WalletManagerEvm(root, {
112
+ provider: 'https://eth-mainnet.g.alchemy.com/v2/your-api-key',
113
+ })
114
+
115
+ // Get the first account (index 0)
116
+ const account = await wallet.getAccount(0) // m/44'/60'/0'/0/0
117
+ const address = await account.getAddress() // 0x...
118
+ console.log('Account 0 address:', address)
119
+
120
+ // Get the second account (index 1)
121
+ const account1 = await wallet.getAccount(1) // m/44'/60'/0'/0/1
122
+ const address1 = await account1.getAddress() // 0x...
123
+ console.log('Account 1 address:', address1)
124
+
125
+ // Get account by custom derivation path
126
+ // Full path will be m/44'/60'/0'/0/5
127
+ const customAccount = await wallet.getAccountByPath('0\'/0/5')
128
+ const customAddress = await customAccount.getAddress()
129
+ console.log('Custom account address:', customAddress)
28
130
 
29
- const seedPhrase = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'
131
+ // Note: All addresses are checksummed Ethereum addresses (0x...)
132
+ // All accounts inherit the provider configuration from the wallet manager
133
+ ```
134
+
135
+ ### Checking Balances
136
+
137
+ #### Owned Account
138
+
139
+ For accounts where you have the seed phrase and full access:
140
+
141
+ ```javascript
142
+ // Assume wallet and account are already created
143
+ // Get native token balance (in wei)
144
+ const balance = await account.getBalance()
145
+ console.log('Native balance:', balance, 'wei') // 1 ETH = 1000000000000000000 wei
146
+
147
+ // Get ERC20 token balance
148
+ const tokenContract = '0x...' // ERC20 contract address
149
+ const tokenBalance = await account.getTokenBalance(tokenContract)
150
+ console.log('Token balance:', tokenBalance)
151
+
152
+ // Note: Provider is required for balance checks
153
+ // Make sure wallet was created with a provider configuration
154
+ ```
155
+
156
+ #### Read-Only Account
157
+
158
+ For addresses where you don't have the seed phrase:
159
+
160
+ ```javascript
161
+ import { WalletAccountReadOnlyEvm } from '@tetherto/wdk-wallet-evm'
30
162
 
31
- const wallet = new WalletManagerEvm(seedPhrase, {
32
- provider: 'https://sepolia.drpc.org',
163
+ // Create a read-only account
164
+ const readOnlyAccount = new WalletAccountReadOnlyEvm('0x...', {
165
+ // Ethereum address
166
+ provider: 'https://sepolia.drpc.org', // Required for balance checks
33
167
  })
34
168
 
35
- const account = await wallet.getAccount(0)
36
- const address = await account.getAddress()
37
- console.log('Address:', address)
169
+ // Check native token balance
170
+ const balance = await readOnlyAccount.getBalance()
171
+ console.log('Native balance:', balance, 'wei')
38
172
 
173
+ // Check ERC20 token balance using contract
174
+ const tokenBalance = await readOnlyAccount.getTokenBalance('0x...') // ERC20 contract address
175
+ console.log('Token balance:', tokenBalance)
176
+
177
+ // Note: ERC20 balance checks use the standard balanceOf(address) function
178
+ // Make sure the contract address is correct and implements the ERC20 standard
179
+ ```
180
+
181
+ ### Sending Transactions
182
+
183
+ Send native tokens and estimate fees using `WalletAccountEvm`. Supports EIP-1559 and auto-populates gas/fee fields where possible.
184
+
185
+ ```javascript
186
+ // Send native tokens
187
+ // Modern EIP-1559 style transaction (recommended)
188
+ const result = await account.sendTransaction({
189
+ to: '0x...', // Recipient address
190
+ value: 1000000000000000000n, // 1 ETH in wei
191
+ maxFeePerGas: 30000000000n, // Optional: max fee per gas (in wei)
192
+ maxPriorityFeePerGas: 2000000000n, // Optional: max priority fee per gas (in wei)
193
+ })
194
+ console.log('Transaction hash:', result.hash)
195
+ console.log('Transaction fee:', result.fee, 'wei')
196
+
197
+ // OR Legacy style transaction
198
+ const legacyResult = await account.sendTransaction({
199
+ to: '0x...',
200
+ value: 1000000000000000000n,
201
+ gasPrice: 20000000000n, // Optional: legacy gas price (in wei)
202
+ gasLimit: 21000, // Optional: gas limit
203
+ })
204
+
205
+ // Get transaction fee estimate
206
+ const quote = await account.quoteSendTransaction({
207
+ to: '0x...',
208
+ value: 1000000000000000000n,
209
+ })
210
+ console.log('Estimated fee:', quote.fee, 'wei')
211
+ ```
212
+
213
+ ### Token Transfers
214
+
215
+ Transfer ERC20 tokens and estimate fees using `WalletAccountEvm`. Uses standard ERC20 `transfer` function.
216
+
217
+ ```javascript
218
+ // Transfer ERC20 tokens
219
+ const transferResult = await account.transfer({
220
+ token: '0x...', // ERC20 contract address
221
+ recipient: '0x...', // Recipient's address
222
+ amount: 1000000n, // Amount in token's base units (use BigInt for large numbers)
223
+ })
224
+ console.log('Transfer hash:', transferResult.hash)
225
+ console.log('Transfer fee:', transferResult.fee, 'wei')
226
+
227
+ // Quote token transfer fee
228
+ const transferQuote = await account.quoteTransfer({
229
+ token: '0x...', // ERC20 contract address
230
+ recipient: '0x...', // Recipient's address
231
+ amount: 1000000n, // Amount in token's base units
232
+ })
233
+ console.log('Transfer fee estimate:', transferQuote.fee, 'wei')
234
+ ```
235
+
236
+ ### Token Approvals
237
+
238
+ Approve a spender for a specific amount (uses ERC20 `approve`):
239
+
240
+ ```javascript
241
+ const approval = await account.approve({
242
+ token: '0x...', // ERC20 contract
243
+ spender: '0x...', // Spender address
244
+ amount: 1000000n, // Allowance amount in base units
245
+ })
246
+ console.log('Approval tx hash:', approval.hash)
247
+ ```
248
+
249
+ ### Message Signing and Verification
250
+
251
+ Sign messages using `WalletAccountEvm` and verify signatures using `WalletAccountReadOnlyEvm`.
252
+
253
+ ```javascript
254
+ // Sign a message
255
+ const message = 'Hello, Ethereum!'
256
+ const signature = await account.sign(message)
257
+ console.log('Signature:', signature)
258
+
259
+ // Verify a signature (can use read-only account)
260
+ const isValid = await readOnlyAccount.verify(message, signature)
261
+ console.log('Signature valid:', isValid)
262
+ ```
263
+
264
+ ### Fee Management
265
+
266
+ Retrieve current fee rates using `WalletManagerEvm`. Supports EIP-1559 fee model.
267
+
268
+ ```javascript
269
+ // Get current fee rates
270
+ const feeRates = await wallet.getFeeRates()
271
+ console.log('Normal fee rate:', feeRates.normal, 'wei') // 1.1x base fee
272
+ console.log('Fast fee rate:', feeRates.fast, 'wei') // 2.0x base fee
273
+ ```
274
+
275
+ ### Memory Management
276
+
277
+ Clear sensitive data from memory using `dispose` methods in `WalletAccountEvm` and `WalletManagerEvm`.
278
+
279
+ ```javascript
280
+ // Dispose wallet accounts to clear private keys from memory
281
+ account.dispose()
282
+
283
+ // Dispose entire wallet manager
39
284
  wallet.dispose()
40
285
  ```
41
286
 
287
+ ## 🔐 Signers
288
+
289
+ Signers provide the cryptographic primitives for accounts. There are two signer implementations:
290
+
291
+ - **SeedSignerEvm (root + child)**: Derives accounts from a BIP-39 seed using the BIP-44 Ethereum path. Can act as a root (for `WalletManagerEvm`) and derive children (for `WalletAccountEvm`).
292
+ - **PrivateKeySignerEvm (child only)**: Wraps a raw private key in a memory-safe buffer. Cannot derive. Use directly with `WalletAccountEvm`. Not supported by `WalletManagerEvm`.
293
+
294
+ Examples:
295
+
296
+ ```javascript
297
+ // Root + manager (seed)
298
+ import WalletManagerEvm from '@tetherto/wdk-wallet-evm'
299
+ import { SeedSignerEvm } from '@tetherto/wdk-wallet-evm/signers'
300
+ const root = new SeedSignerEvm(mnemonic)
301
+ const wallet = new WalletManagerEvm(root, { provider: 'https://...' })
302
+ const account0 = await wallet.getAccount(0)
303
+
304
+ // Single account from a private key
305
+ import { WalletAccountEvm } from '@tetherto/wdk-wallet-evm'
306
+ import { PrivateKeySignerEvm } from '@tetherto/wdk-wallet-evm/signers'
307
+ const signer = new PrivateKeySignerEvm('0x0123...')
308
+ const account = new WalletAccountEvm(signer, { provider: 'https://...' })
309
+ ```
310
+
42
311
  ## Key Capabilities
43
312
 
44
313
  - **BIP-39 Seed Phrase Support**: Generate and validate mnemonic seed phrases
@@ -49,6 +318,8 @@ wallet.dispose()
49
318
  - **Message Signing**: Sign and verify messages (EIP-191 and EIP-712)
50
319
  - **Fee Estimation**: Real-time network fee rates with normal/fast tiers
51
320
  - **Secure Memory Disposal**: Clear private keys from memory when done
321
+ - **Signer Submodule**: Create your own signer from ISignerEvm, support for Seed and Private key signers
322
+ - **EIP-7702 Delegation**: Delegate EOAs to smart contracts, sign authorizations, and send type 4 transactions
52
323
 
53
324
  ## Compatibility
54
325
 
@@ -58,26 +329,26 @@ wallet.dispose()
58
329
 
59
330
  ## Documentation
60
331
 
61
- | Topic | Description | Link |
62
- |-------|-------------|------|
63
- | Overview | Module overview and feature summary | [Wallet EVM Overview](https://docs.wdk.tether.io/sdk/wallet-modules/wallet-evm) |
64
- | Usage | End-to-end integration walkthrough | [Wallet EVM Usage](https://docs.wdk.tether.io/sdk/wallet-modules/wallet-evm/usage) |
332
+ | Topic | Description | Link |
333
+ | ------------- | ----------------------------------------- | -------------------------------------------------------------------------------------------------- |
334
+ | Overview | Module overview and feature summary | [Wallet EVM Overview](https://docs.wdk.tether.io/sdk/wallet-modules/wallet-evm) |
335
+ | Usage | End-to-end integration walkthrough | [Wallet EVM Usage](https://docs.wdk.tether.io/sdk/wallet-modules/wallet-evm/usage) |
65
336
  | Configuration | Provider, fees, and network configuration | [Wallet EVM Configuration](https://docs.wdk.tether.io/sdk/wallet-modules/wallet-evm/configuration) |
66
- | API Reference | Complete class and type reference | [Wallet EVM API Reference](https://docs.wdk.tether.io/sdk/wallet-modules/wallet-evm/api-reference) |
337
+ | API Reference | Complete class and type reference | [Wallet EVM API Reference](https://docs.wdk.tether.io/sdk/wallet-modules/wallet-evm/api-reference) |
67
338
 
68
339
  ## Examples
69
340
 
70
- | Example | Description |
71
- |---------|-------------|
72
- | [Create Wallet](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/create-wallet.ts) | Initialize a wallet manager and derive accounts from a seed phrase |
73
- | [Manage Accounts](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/manage-accounts.ts) | Work with multiple accounts and custom derivation paths |
74
- | [Check Balances](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/check-balances.ts) | Query native token and ERC-20 balances for owned accounts |
75
- | [Read-Only Account](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/read-only-account.ts) | Monitor balances for any address without a private key |
76
- | [Send Transaction](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/send-transaction.ts) | Estimate fees and send native token transactions (EIP-1559 + legacy) |
77
- | [Token Transfer](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/token-transfer.ts) | Transfer ERC-20 tokens and estimate transfer fees |
78
- | [Sign & Verify Message](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/sign-verify-message.ts) | Sign messages and verify signatures |
79
- | [Fee Management](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/fee-management.ts) | Retrieve current network fee rates |
80
- | [Memory Management](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/memory-management.ts) | Securely dispose wallets and clear private keys from memory |
341
+ | Example | Description |
342
+ | ------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
343
+ | [Create Wallet](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/create-wallet.ts) | Initialize a wallet manager and derive accounts from a seed phrase |
344
+ | [Manage Accounts](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/manage-accounts.ts) | Work with multiple accounts and custom derivation paths |
345
+ | [Check Balances](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/check-balances.ts) | Query native token and ERC-20 balances for owned accounts |
346
+ | [Read-Only Account](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/read-only-account.ts) | Monitor balances for any address without a private key |
347
+ | [Send Transaction](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/send-transaction.ts) | Estimate fees and send native token transactions (EIP-1559 + legacy) |
348
+ | [Token Transfer](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/token-transfer.ts) | Transfer ERC-20 tokens and estimate transfer fees |
349
+ | [Sign & Verify Message](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/sign-verify-message.ts) | Sign messages and verify signatures |
350
+ | [Fee Management](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/fee-management.ts) | Retrieve current network fee rates |
351
+ | [Memory Management](https://github.com/tetherto/wdk-examples/blob/main/wallet-evm/memory-management.ts) | Securely dispose wallets and clear private keys from memory |
81
352
 
82
353
  > For detailed walkthroughs, see the [Usage Guide](https://docs.wdk.tether.io/sdk/wallet-modules/wallet-evm/usage).
83
354
  > See all runnable examples in the [wdk-examples](https://github.com/tetherto/wdk-examples) repository.
package/index.js CHANGED
@@ -33,6 +33,8 @@
33
33
 
34
34
  /** @typedef {import('./src/wallet-account-evm.js').ApproveOptions} ApproveOptions */
35
35
 
36
+ /** @typedef {import('./src/utils/tx-populator-evm.js').UnsignedEvmTransaction} UnsignedEvmTransaction */
37
+
36
38
  export { default } from './src/wallet-manager-evm.js'
37
39
 
38
40
  export { default as WalletAccountReadOnlyEvm } from './src/wallet-account-read-only-evm.js'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tetherto/wdk-wallet-evm",
3
- "version": "1.0.0-beta.14",
3
+ "version": "1.0.0-beta.15",
4
4
  "description": "A simple package to manage BIP-32 wallets for evm blockchains.",
5
5
  "keywords": [
6
6
  "wdk",
@@ -27,14 +27,13 @@
27
27
  "test:integration:coverage": "cross-env NODE_OPTIONS=--experimental-vm-modules jest tests/integration --coverage"
28
28
  },
29
29
  "dependencies": {
30
- "@noble/curves": "1.9.2",
31
30
  "@noble/hashes": "1.8.0",
32
31
  "@noble/secp256k1": "2.2.3",
32
+ "@tetherto/wdk-wallet": "1.0.0-beta.13",
33
33
  "@tetherto/wdk-failover-provider": "1.0.0-beta.2",
34
- "@tetherto/wdk-wallet": "1.0.0-beta.11",
35
34
  "bare-node-runtime": "^1.5.0",
36
35
  "bip39": "3.1.0",
37
- "ethers": "6.14.4",
36
+ "ethers": "6.17.0",
38
37
  "sodium-universal": "5.0.1"
39
38
  },
40
39
  "devDependencies": {
@@ -61,6 +60,10 @@
61
60
  "bare": "./bare.js",
62
61
  "default": "./index.js"
63
62
  },
63
+ "./signers": {
64
+ "types": "./types/src/signers/index.d.ts",
65
+ "default": "./src/signers/index.js"
66
+ },
64
67
  "./package": {
65
68
  "default": "./package.json"
66
69
  }
@@ -156,14 +156,15 @@ export default class MemorySafeHDNodeWallet extends BaseWallet {
156
156
  }
157
157
 
158
158
  const { IR, IL } = serI(index, this.chainCode, this.publicKey, this.privateKeyBuffer)
159
+ const childPriv = new Uint8Array(this.privateKeyBuffer)
159
160
 
160
- const overflow = addToPrivateKey(this.privateKeyBuffer, IL)
161
+ const overflow = addToPrivateKey(childPriv, IL)
161
162
 
162
- if (overflow || compareWithCurveOrder(this.privateKeyBuffer) >= 0) {
163
- subtractCurveOrderFromPrivateKey(this.privateKeyBuffer)
163
+ if (overflow || compareWithCurveOrder(childPriv) >= 0) {
164
+ subtractCurveOrderFromPrivateKey(childPriv)
164
165
  }
165
166
 
166
- const ki = new MemorySafeSigningKey(this.privateKeyBuffer)
167
+ const ki = new MemorySafeSigningKey(childPriv)
167
168
 
168
169
  return new MemorySafeHDNodeWallet(_guard, ki, this.fingerprint, hexlify(IR),
169
170
  path, index, this.depth + 1, this.mnemonic, this.provider)
@@ -70,8 +70,9 @@ export default class MemorySafeSigningKey extends SigningKey {
70
70
  }
71
71
 
72
72
  dispose () {
73
- sodium_memzero(this._privateKeyBuffer)
74
-
75
- this._privateKeyBuffer = undefined
73
+ if (this._privateKeyBuffer) {
74
+ sodium_memzero(this._privateKeyBuffer)
75
+ this._privateKeyBuffer = undefined
76
+ }
76
77
  }
77
78
  }
@@ -0,0 +1,25 @@
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
+ // src/signers/index.js
15
+ /**
16
+ * Barrel exports for EVM signers.
17
+ *
18
+ * - `SeedSignerEvm`: derives accounts from a BIP-39 seed (BIP-44 path).
19
+ * - `PrivateKeySignerEvm`: memory-safe wrapper around a raw private key.
20
+ */
21
+
22
+ /** @typedef {import('../utils/tx-populator-evm.js').UnsignedEvmTransaction} UnsignedEvmTransaction */
23
+
24
+ export { default, default as SeedSignerEvm } from './seed-signer-evm.js'
25
+ export { default as PrivateKeySignerEvm } from './private-key-signer-evm.js'
@@ -0,0 +1,156 @@
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 { BaseWallet } from 'ethers'
17
+
18
+ import { SignerError } from '@tetherto/wdk-wallet'
19
+
20
+ import MemorySafeSigningKey from '../memory-safe/signing-key.js'
21
+ import { ISignerEvm } from './seed-signer-evm.js'
22
+
23
+ /** @typedef {import('../utils/tx-populator-evm.js').UnsignedEvmTransaction} UnsignedEvmTransaction */
24
+ /** @typedef {import('@tetherto/wdk-wallet').KeyPair} KeyPair */
25
+ /** @typedef {import('ethers').AuthorizationRequest} AuthorizationRequest */
26
+ /** @typedef {import('ethers').Authorization} Authorization */
27
+ /** @typedef {import('../wallet-account-read-only-evm.js').TypedData} TypedData */
28
+
29
+ /**
30
+ * @extends {ISignerEvm}
31
+ * Signer that wraps a raw private key in a memory-safe buffer, exposing a minimal
32
+ * interface for signing messages, transactions and typed data. This signer does
33
+ * not support derivation and always represents a single account.
34
+ */
35
+ export default class PrivateKeySignerEvm extends ISignerEvm {
36
+ /**
37
+ * Create a signer from a raw private key.
38
+ *
39
+ * @param {string|Uint8Array} privateKey - Hex string (with/without 0x) or raw key bytes.
40
+ */
41
+ constructor (privateKey) {
42
+ super()
43
+
44
+ // Expect a Uint8Array buffer; accept hex string as convenience
45
+ let privateKeyBuffer = privateKey
46
+ if (typeof privateKey === 'string') {
47
+ const hex = privateKey.startsWith('0x') ? privateKey.slice(2) : privateKey
48
+ privateKeyBuffer = new Uint8Array(Buffer.from(hex, 'hex'))
49
+ }
50
+
51
+ /** @private */
52
+ this._signingKey = new MemorySafeSigningKey(privateKeyBuffer)
53
+ /** @private */
54
+ this._wallet = new BaseWallet(this._signingKey, null)
55
+ /** @private */
56
+ this._address = this._wallet.address
57
+ /** @private */
58
+ this._path = undefined
59
+ }
60
+
61
+ /**
62
+ * Whether this signer can derive child signers. Always false: a private-key signer is a
63
+ * single standalone account and is bound directly to a wallet account.
64
+ * @type {boolean}
65
+ */
66
+ get isDerivable () { return false }
67
+
68
+ /**
69
+ * The account index. Always undefined for private key signers: a raw key has no
70
+ * BIP-44 position, so reporting an index would be misleading.
71
+ * @type {number|undefined}
72
+ */
73
+ get index () { return undefined }
74
+
75
+ /**
76
+ * The derivation path. Always undefined for private key signers.
77
+ * @type {string|undefined}
78
+ */
79
+ get path () { return this._path }
80
+
81
+ /**
82
+ * The account's address.
83
+ * @type {string}
84
+ */
85
+ get address () { return this._address }
86
+ /**
87
+ * The account's key pair (private and public key buffers).
88
+ * @type {KeyPair}
89
+ */
90
+ get keyPair () {
91
+ return {
92
+ privateKey: this._signingKey ? this._signingKey.privateKeyBuffer : null,
93
+ publicKey: this._signingKey ? this._signingKey.publicKeyBuffer : null
94
+ }
95
+ }
96
+
97
+ /**
98
+ * PrivateKeySignerEvm is not a hierarchical signer and cannot derive.
99
+ * @returns {Promise<never>}
100
+ * @throws {SignerError} Always — private-key signers do not support derivation.
101
+ */
102
+ async derive () {
103
+ throw new SignerError('PrivateKeySignerEvm does not support derivation.')
104
+ }
105
+
106
+ /** @returns {Promise<string>} */
107
+ async getAddress () {
108
+ return this._address
109
+ }
110
+
111
+ /**
112
+ * Signs a message.
113
+ *
114
+ * @param {string} message - The message to sign.
115
+ * @returns {Promise<string>} The message's signature.
116
+ */
117
+ async sign (message) {
118
+ return this._wallet.signMessage(message)
119
+ }
120
+
121
+ /**
122
+ * Signs a transaction and returns the serialized signed transaction hex.
123
+ *
124
+ * @param {UnsignedEvmTransaction} unsignedTx - The unsigned transaction object.
125
+ * @returns {Promise<string>}
126
+ */
127
+ async signTransaction (unsignedTx) {
128
+ return this._wallet.signTransaction(unsignedTx)
129
+ }
130
+
131
+ /**
132
+ * Signs typed data according to EIP-712.
133
+ *
134
+ * @param {TypedData} typedData - The typed data to sign.
135
+ * @returns {Promise<string>} The typed data signature.
136
+ */
137
+ async signTypedData ({ domain, types, message }) {
138
+ return this._wallet.signTypedData(domain, types, message)
139
+ }
140
+
141
+ /**
142
+ * Sign an ERC-7702 authorization tuple.
143
+ * @param {AuthorizationRequest} auth
144
+ * @returns {Promise<Authorization>}
145
+ */
146
+ async signAuthorization (auth) {
147
+ return this._wallet.authorizeSync(auth)
148
+ }
149
+
150
+ /** Dispose secrets from memory. */
151
+ dispose () {
152
+ if (this._signingKey) this._signingKey.dispose()
153
+ this._signingKey = undefined
154
+ this._wallet = undefined
155
+ }
156
+ }