@tetherto/wdk-wallet-evm 1.0.0-beta.2 → 1.0.0-beta.21

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/index.js CHANGED
@@ -13,19 +13,42 @@
13
13
  // limitations under the License.
14
14
  'use strict'
15
15
 
16
+ /** @typedef {import('ethers').TypedDataDomain} TypedDataDomain */
17
+ /** @typedef {import('ethers').TypedDataField} TypedDataField */
18
+ /** @typedef {import('ethers').AuthorizationRequest} AuthorizationRequest */
19
+ /** @typedef {import('ethers').Authorization} Authorization */
20
+ /** @typedef {import('ethers').AuthorizationLike} AuthorizationLike */
16
21
  /** @typedef {import('ethers').TransactionReceipt} EvmTransactionReceipt */
22
+ /** @typedef {import('ethers').TransactionResponse} EvmTransactionResponse */
23
+ /** @typedef {import('ethers').TransactionRequest} EvmTransactionRequest */
24
+ /** @typedef {import('ethers').BlobLike} BlobLike */
17
25
 
18
26
  /** @typedef {import('@tetherto/wdk-wallet').FeeRates} FeeRates */
19
27
  /** @typedef {import('@tetherto/wdk-wallet').KeyPair} KeyPair */
20
28
  /** @typedef {import('@tetherto/wdk-wallet').TransactionResult} TransactionResult */
21
- /** @typedef {import('@tetherto/wdk-wallet').TransferOptions} TransferOptions */
22
29
  /** @typedef {import('@tetherto/wdk-wallet').TransferResult} TransferResult */
30
+ /** @typedef {import('@tetherto/wdk-wallet').TransferOptions} TransferOptions */
31
+ /** @typedef {import('@tetherto/wdk-wallet').Finality} Finality */
32
+ /** @typedef {import('@tetherto/wdk-wallet').TransactionReceipt} TransactionReceipt */
33
+ /** @typedef {import('@tetherto/wdk-wallet').WaitForTransactionTarget} WaitForTransactionTarget */
34
+ /** @typedef {import('@tetherto/wdk-wallet').WaitForTransactionOptions} WaitForTransactionOptions */
23
35
 
36
+ /** @typedef {import('./src/wallet-account-read-only-evm.js').TypedData} TypedData */
37
+ /** @typedef {import('./src/wallet-account-read-only-evm.js').DelegationInfo} DelegationInfo */
24
38
  /** @typedef {import('./src/wallet-account-read-only-evm.js').EvmTransaction} EvmTransaction */
39
+ /** @typedef {import('./src/wallet-account-read-only-evm.js').EvmGasOverrides} EvmGasOverrides */
40
+ /** @typedef {import('./src/wallet-account-read-only-evm.js').EvmTransferOptions} EvmTransferOptions */
25
41
  /** @typedef {import('./src/wallet-account-read-only-evm.js').EvmWalletConfig} EvmWalletConfig */
42
+ /** @typedef {import('./src/wallet-account-read-only-evm.js').EvmTransactionDetails} EvmTransactionDetails */
43
+
44
+ /** @typedef {import('./src/wallet-account-evm.js').ApproveOptions} ApproveOptions */
45
+ /** @typedef {import('./src/wallet-account-evm.js').SignerOptions} SignerOptions */
46
+ /** @typedef {import('./src/wallet-account-evm.js').EvmApproveOptions} EvmApproveOptions */
26
47
 
27
48
  export { default } from './src/wallet-manager-evm.js'
28
49
 
29
50
  export { default as WalletAccountReadOnlyEvm } from './src/wallet-account-read-only-evm.js'
30
51
 
31
52
  export { default as WalletAccountEvm } from './src/wallet-account-evm.js'
53
+
54
+ export { ISigner } from '@tetherto/wdk-wallet'
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@tetherto/wdk-wallet-evm",
3
- "version": "1.0.0-beta.2",
4
- "description": "A simple package to manage BIP-32 wallets for evm blockchains.",
3
+ "version": "1.0.0-beta.21",
4
+ "description": "EVM wallet module for WDK (Wallet Development Kit) by Tether.",
5
+ "homepage": "https://docs.wdk.tether.io/sdk/wallet-modules/wallet-evm/",
5
6
  "keywords": [
6
7
  "wdk",
7
8
  "wallet",
@@ -21,28 +22,38 @@
21
22
  "build:types": "tsc",
22
23
  "lint": "standard",
23
24
  "lint:fix": "standard --fix",
24
- "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest",
25
- "test:coverage": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --coverage",
26
- "test:integration": "cross-env NODE_OPTIONS=--experimental-vm-modules jest tests/integration",
27
- "test:integration:coverage": "cross-env NODE_OPTIONS=--experimental-vm-modules jest tests/integration --coverage"
25
+ "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --testPathIgnorePatterns=/tests/integration/",
26
+ "test:coverage": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --coverage --testPathIgnorePatterns=/tests/integration/",
27
+ "test:integration-wait": "wait-on tcp:127.0.0.1:8545 && cross-env NODE_OPTIONS=--experimental-vm-modules jest tests/integration --runInBand",
28
+ "test:integration-wait:coverage": "wait-on tcp:127.0.0.1:8545 && cross-env NODE_OPTIONS=--experimental-vm-modules jest tests/integration --coverage --runInBand",
29
+ "test:integration": "concurrently -k -s first -n \"NODE,TEST\" -c \"black,green\" --hide NODE \"npx hardhat node --network hardhat\" \"npm run test:integration-wait\"",
30
+ "test:integration:coverage": "concurrently -k -s first -n \"NODE,TEST\" -c \"black,green\" --hide NODE \"npx hardhat node --network hardhat\" \"npm run test:integration-wait:coverage\""
28
31
  },
29
32
  "dependencies": {
30
- "@noble/curves": "1.9.2",
31
33
  "@noble/hashes": "1.8.0",
32
34
  "@noble/secp256k1": "2.2.3",
33
- "@tetherto/wdk-wallet": "^1.0.0-beta.1",
34
- "bare-wdk-runtime": "2.0.0",
35
+ "@tetherto/wdk-wallet": "1.0.0-beta.21",
36
+ "@tetherto/wdk-failover-provider": "1.0.0-beta.2",
37
+ "bare-node-runtime": "^1.5.0",
35
38
  "bip39": "3.1.0",
36
- "ethers": "6.14.3",
39
+ "ethers": "6.17.0",
37
40
  "sodium-universal": "5.0.1"
38
41
  },
39
42
  "devDependencies": {
40
- "@nomicfoundation/hardhat-ethers": "3.0.9",
43
+ "concurrently": "9.2.0",
41
44
  "cross-env": "7.0.3",
42
- "hardhat": "2.24.2",
45
+ "hardhat": "3.12.0",
43
46
  "jest": "29.7.0",
44
47
  "standard": "17.1.2",
45
- "typescript": "5.8.3"
48
+ "typescript": "5.8.3",
49
+ "wait-on": "8.0.4"
50
+ },
51
+ "devEngines": {
52
+ "runtime": {
53
+ "name": "node",
54
+ "version": ">=22.13.0",
55
+ "onFail": "error"
56
+ }
46
57
  },
47
58
  "exports": {
48
59
  ".": {
@@ -50,17 +61,23 @@
50
61
  "bare": "./bare.js",
51
62
  "default": "./index.js"
52
63
  },
64
+ "./signers": {
65
+ "types": "./types/src/signers/index.d.ts",
66
+ "bare": "./src/signers/bare.js",
67
+ "default": "./src/signers/index.js"
68
+ },
53
69
  "./package": {
54
70
  "default": "./package.json"
55
71
  }
56
72
  },
57
73
  "publishConfig": {
58
- "access": "restricted",
74
+ "access": "public",
59
75
  "registry": "https://registry.npmjs.org/"
60
76
  },
61
77
  "standard": {
62
78
  "ignore": [
63
79
  "bare.js",
80
+ "src/signers/bare.js",
64
81
  "tests/**/*.js"
65
82
  ]
66
83
  }
@@ -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,75 @@
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
+
15
+ 'use strict'
16
+
17
+ import { AbiCoder, concat, decodeBase64, hexlify } from 'ethers'
18
+
19
+ /** @typedef {import('ethers').Provider} Provider */
20
+
21
+ /**
22
+ * @internal
23
+ * @typedef {Object} MulticallRequest
24
+ * @property {string} to - The target contract address.
25
+ * @property {string} data - The ABI-encoded calldata.
26
+ */
27
+
28
+ /**
29
+ * @internal
30
+ * @typedef {Object} MulticallResult
31
+ * @property {boolean} status - Whether the call succeeded.
32
+ * @property {string} data - The ABI-encoded return data.
33
+ */
34
+
35
+ /**
36
+ * Compiled multicall constructor bytecode. Executes calls via staticcall and
37
+ * returns results without deploying. Source: ethers-io/ext-provider-multicall (MIT).
38
+ *
39
+ * @type {string}
40
+ */
41
+ const _MULTICALL_BYTECODE = hexlify(decodeBase64('YIBgQFI0gBVhABBXYACA/VtQYEBRYQSxOAOAYQSxgzmBAWBAgZBSYQAvkWECWlZbYACBUWABYEBgAgoDgREVYQBKV2EASmEBr1ZbYEBRkICCUoBgIAJgIAGCAWBAUoAVYQCQV4FgIAFbYECAUYCCAZCRUmAAgVJgYGAgggFSgVJgIAGQYAGQA5CBYQBoV5BQW1CQUGAAW4JRgRAVYQE/V2EA8oOCgVGBEGEAtFdhALRhA+NWW2AgAmAgAQFRYAABUYSDgVGBEGEA0ldhANJhA+NWW2AgAmAgAQFRYCABUWEBbmQBAAAAAAJkAQAAAACQBFZbg4OBUYEQYQEEV2EBBGED41ZbYCACYCABAVFgAAGEhIFRgRBhASFXYQEhYQPjVltgIJCBApGQkQGBAVEBkZCRUpAVFZBSYAEBYQCWVltQYABDgmBAUWAgAWEBVZKRkGEEElZbYEBRYCCBgwMDgVKQYEBSkFCAUWAgggHzW2AAYGBgQFGQUGAAgVJgIIEBYEBSYACAhFFgIIYBh1r6YD89AWAfGRaCAWBAUj2CUpFQPWAAYCCDAT6SUJKQUFZbf05Ie3EAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYABSYEFgBFJgJGAA/VtgQIBRkIEBYAFgQGACCgOBEYKCEBcVYQIAV2ECAGEBr1ZbYEBSkFZbYEBRYB+CAWAfGRaBAWABYEBgAgoDgRGCghAXFWECLldhAi5hAa9WW2BAUpGQUFZbYABbg4EQFWECUVeBgQFRg4IBUmAgAWECOVZbUFBgAJEBUlZbYABgIIKEAxIVYQJsV2AAgP1bgVFgAWBAYAIKA4ERFWECgldgAID9W4IBYB+BAYQTYQKTV2AAgP1bgFFgAWBAYAIKA4ERFWECrFdhAqxhAa9WW2AggQJhArxgIIIBYQIGVluRglJgIIGEAYEBkpCBAZCHhBEVYQLYV2AAgP1bYCCFAZJQW4ODEBVhA9hXglFgAWBAYAIKA4ERFWEC/VdgAID9W4UBYECBigNgHxkBEhVhAxNXYACA/VthAxthAd5WW2AgggFRYAFgoGACCgOBFoEUYQM1V2AAgP1bgVJgQIIBUWABYEBgAgoDgREVYQNQV2AAgP1bYCCBhAEBklBQiWAfgwESYQNoV2AAgP1bgVFgAWBAYAIKA4ERFWEDgVdhA4FhAa9WW2EDlGAfggFgHxkWYCABYQIGVluBgVKLYCCDhgEBERVhA6lXYACA/VthA7qCYCCDAWAghwFhAjZWW4BgIIQBUlBQgIRSUFBgIIIBkVBgIIMBklBhAt9WW5eWUFBQUFBQUFZbf05Ie3EAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYABSYDJgBFJgJGAA/VtgAGBAggGEg1JgQGAghAFSgIRRgINSYGCFAZFQYGBgIIIChgEBklBgIIYBYABbgoEQFWEEo1dgXxmHhgMBhFKBUYBRFRWGUmAggQFRkFBgQGAghwFSgFGAYECIAVJhBICBYGCJAWAghQFhAjZWW2AfAWAfGRaVkJUBYGABlFBgIJOEAZORkJEBkGABAWEEQFZbUJKXllBQUFBQUFBW/g=='))
42
+
43
+ /**
44
+ * Executes multiple read-only contract calls in a single RPC round-trip.
45
+ *
46
+ * @internal
47
+ * @param {Provider} provider - An ethers provider.
48
+ * @param {MulticallRequest[]} calls - The calls to batch.
49
+ * @returns {Promise<MulticallResult[]>} The result of each call.
50
+ */
51
+ export async function multicall (provider, calls) {
52
+ if (calls.length === 0) {
53
+ return []
54
+ }
55
+
56
+ const data = concat([
57
+ _MULTICALL_BYTECODE,
58
+ AbiCoder.defaultAbiCoder().encode(
59
+ ['tuple(address, bytes)[]'],
60
+ [calls.map(call => [call.to, call.data])]
61
+ )
62
+ ])
63
+
64
+ const resultData = await provider.call({ data })
65
+
66
+ const [, results] = AbiCoder.defaultAbiCoder().decode(
67
+ ['uint', 'tuple(bool, bytes)[]'],
68
+ resultData
69
+ )
70
+
71
+ return results.map(result => ({
72
+ status: result[0],
73
+ data: result[1]
74
+ }))
75
+ }
@@ -0,0 +1,20 @@
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 'bare-node-runtime/global'
17
+
18
+ export * from './index.js' with { imports: 'bare-node-runtime/imports' }
19
+
20
+ export { default } from './index.js' with { imports: 'bare-node-runtime/imports' }
@@ -0,0 +1,18 @@
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
+ export { ISignerEvm } from './signer-evm.js'
15
+ export { default, default as SeedSignerEvm } from './seed-signer-evm.js'
16
+ export { default as PrivateKeySignerEvm } from './private-key-signer-evm.js'
17
+
18
+ /** @typedef {import('./signer-evm.js').TransactionLike} TransactionLike */
@@ -0,0 +1,166 @@
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 { UnsupportedOperationError } from '@tetherto/wdk-wallet'
19
+
20
+ import MemorySafeSigningKey from '../memory-safe/signing-key.js'
21
+
22
+ /** @typedef {import('./signer-evm.js').ISignerEvm} ISignerEvm */
23
+ /** @typedef {import('@tetherto/wdk-wallet').KeyPair} KeyPair */
24
+ /** @typedef {import('@tetherto/wdk-wallet').ValueError} ValueError */
25
+ /** @typedef {import('ethers').TransactionLike} TransactionLike */
26
+ /** @typedef {import('ethers').AuthorizationRequest} AuthorizationRequest */
27
+ /** @typedef {import('ethers').Authorization} Authorization */
28
+ /** @typedef {import('../wallet-account-read-only-evm.js').TypedData} TypedData */
29
+
30
+ /**
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
+ * @implements {ISignerEvm}
36
+ */
37
+ export default class PrivateKeySignerEvm {
38
+ /**
39
+ * Create a signer from a raw private key.
40
+ *
41
+ * The supplied key is copied: the signer keeps its own internal copy alive until
42
+ * {@link dispose} zeroes it, and never wipes the supplied key, whose disposal
43
+ * remains the caller's responsibility.
44
+ *
45
+ * @param {string | Uint8Array} privateKey - The private key's hex string (with or without 0x) or byte sequence.
46
+ */
47
+ constructor (privateKey) {
48
+ privateKey = typeof privateKey === 'string'
49
+ ? Buffer.from(privateKey.startsWith('0x') ? privateKey.slice(2) : privateKey, 'hex')
50
+ : Buffer.from(privateKey)
51
+
52
+ /** @private */
53
+ this._signingKey = new MemorySafeSigningKey(privateKey)
54
+
55
+ /** @private */
56
+ this._wallet = new BaseWallet(this._signingKey)
57
+
58
+ /** @private */
59
+ this._address = this._wallet.address
60
+ }
61
+
62
+ /**
63
+ * Whether this signer can derive child signers.
64
+ *
65
+ * @type {false}
66
+ */
67
+ get isDerivable () {
68
+ return false
69
+ }
70
+
71
+ /**
72
+ * The BIP 0044 derivation path.
73
+ *
74
+ * @type {string | null}
75
+ */
76
+ get path () { return null }
77
+
78
+ /**
79
+ * The account's address.
80
+ *
81
+ * @deprecated Use {@link getAddress} instead. This property will be removed in an upcoming
82
+ * release: not all signers (e.g. hardware signers) can expose the address synchronously.
83
+ * @type {string}
84
+ */
85
+ get address () { return this._address }
86
+
87
+ /**
88
+ * The account's key pair (private and public key buffers).
89
+ *
90
+ * @type {KeyPair}
91
+ */
92
+ get keyPair () {
93
+ return {
94
+ privateKey: this._signingKey.privateKeyBuffer ?? null,
95
+ publicKey: this._signingKey.publicKeyBuffer
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Derive a child signer using a relative path (e.g., "0'/0/0").
101
+ *
102
+ * @param {string} path - The relative derivation path.
103
+ * @returns {Promise<never>} The derived signer.
104
+ * @throws {UnsupportedOperationError} If the signer does not support account derivation.
105
+ * @throws {ValueError} If the path is not valid.
106
+ */
107
+ async derive (path) {
108
+ throw new UnsupportedOperationError('derive(path)')
109
+ }
110
+
111
+ /**
112
+ * Returns the account's address.
113
+ *
114
+ * @returns {Promise<string>} The account's address.
115
+ */
116
+ async getAddress () {
117
+ return this._address
118
+ }
119
+
120
+ /**
121
+ * Signs a message.
122
+ *
123
+ * @param {string} message - The message to sign.
124
+ * @returns {Promise<string>} The message's signature.
125
+ */
126
+ async sign (message) {
127
+ return this._wallet.signMessage(message)
128
+ }
129
+
130
+ /**
131
+ * Signs a transaction.
132
+ *
133
+ * @param {TransactionLike} tx - The transaction to sign.
134
+ * @returns {Promise<string>} The signed transaction as a hex string.
135
+ */
136
+ async signTransaction (tx) {
137
+ return this._wallet.signTransaction(tx)
138
+ }
139
+
140
+ /**
141
+ * Signs typed data according to EIP-712.
142
+ *
143
+ * @param {TypedData} typedData - The typed data to sign.
144
+ * @returns {Promise<string>} The typed data signature.
145
+ */
146
+ async signTypedData ({ domain, types, message }) {
147
+ return this._wallet.signTypedData(domain, types, message)
148
+ }
149
+
150
+ /**
151
+ * Signs an ERC-7702 authorization tuple.
152
+ *
153
+ * @param {AuthorizationRequest} auth - The authorization request.
154
+ * @returns {Promise<Authorization>} The signed authorization.
155
+ */
156
+ async signAuthorization (auth) {
157
+ return this._wallet.authorizeSync(auth)
158
+ }
159
+
160
+ /**
161
+ * Disposes the signer, securely erasing its internal copy of the private key from memory.
162
+ */
163
+ dispose () {
164
+ this._signingKey.dispose()
165
+ }
166
+ }
@@ -0,0 +1,185 @@
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 { ValueError } from '@tetherto/wdk-wallet'
19
+
20
+ import MemorySafeHDNodeWallet from '../memory-safe/hd-node-wallet.js'
21
+
22
+ /** @typedef {import('./signer-evm.js').ISignerEvm} ISignerEvm */
23
+ /** @typedef {import('@tetherto/wdk-wallet').KeyPair} KeyPair */
24
+ /** @typedef {import('ethers').TransactionLike} TransactionLike */
25
+ /** @typedef {import('ethers').AuthorizationRequest} AuthorizationRequest */
26
+ /** @typedef {import('ethers').Authorization} Authorization */
27
+ /** @typedef {import('../wallet-account-read-only-evm.js').TypedData} TypedData */
28
+ /** @typedef {import('../memory-safe/hd-node-wallet.js').default} MemorySafeHDNodeWallet */
29
+
30
+ /**
31
+ * Absolute BIP-44 prefix for Ethereum (m/purpose'/coin_type'). Exported so callers that want
32
+ * "the standard Ethereum path" (WalletAccountEvm's seed overload, WalletManagerEvm's own
33
+ * internal default signer) can compose an absolute path without hardcoding it themselves.
34
+ *
35
+ * @internal
36
+ */
37
+ export const BIP_44_ETH_DERIVATION_PATH_PREFIX = "m/44'/60'"
38
+
39
+ /**
40
+ * Signer implementation that derives keys from a BIP-39 seed using an HD path. Every signer
41
+ * holds exactly one HD node (the Ethereum BIP-44 coin node "m/44'/60'" by default, ready to
42
+ * derive accounts below it) and can derive child signers below its own path. Each signer owns
43
+ * an independent copy of its key, so disposing one never affects its parent, children or
44
+ * siblings.
45
+ *
46
+ * @implements {ISignerEvm}
47
+ */
48
+ export default class SeedSignerEvm {
49
+ /**
50
+ * Create a SeedSignerEvm from a BIP-39 seed.
51
+ *
52
+ * @param {string|Uint8Array} seed - A BIP-39 mnemonic seed phrase, or a raw BIP-32 master seed (16-64 bytes).
53
+ * @param {string} [path] - A BIP-32 path (default: "m/44'/60'").
54
+ * @throws {ValueError} If the given seed phrase is invalid.
55
+ */
56
+ constructor (seed, path = BIP_44_ETH_DERIVATION_PATH_PREFIX) {
57
+ if (typeof seed === 'string') {
58
+ if (!bip39.validateMnemonic(seed)) {
59
+ throw new ValueError('The seed phrase is invalid.')
60
+ }
61
+
62
+ seed = bip39.mnemonicToSeedSync(seed)
63
+ }
64
+
65
+ const root = MemorySafeHDNodeWallet.fromSeed(seed)
66
+ const account = root.derivePath(path)
67
+ if (account !== root) root.dispose()
68
+
69
+ /** @private */
70
+ this._account = account
71
+ }
72
+
73
+ /**
74
+ * Whether this signer can derive child signers. Always true: every seed signer holds an
75
+ * HD node with a private key and can derive below its own path.
76
+ *
77
+ * @type {true}
78
+ */
79
+ get isDerivable () {
80
+ return true
81
+ }
82
+
83
+ /**
84
+ * The signer's absolute derivation path.
85
+ *
86
+ * @type {string}
87
+ */
88
+ get path () {
89
+ return this._account.path
90
+ }
91
+
92
+ /**
93
+ * The account's derived address.
94
+ *
95
+ * @deprecated Use {@link getAddress} instead. This property will be removed in an upcoming
96
+ * release: not all signers (e.g. hardware signers) can expose the address synchronously.
97
+ * @type {string}
98
+ */
99
+ get address () {
100
+ return this._account.address
101
+ }
102
+
103
+ /**
104
+ * The account's key pair (private and public key buffers).
105
+ *
106
+ * @type {KeyPair}
107
+ */
108
+ get keyPair () {
109
+ return {
110
+ privateKey: this._account.privateKeyBuffer ?? null,
111
+ publicKey: this._account.publicKeyBuffer
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Derive a child signer relative to this signer's own path (e.g. calling derive("0'/0/1") on
117
+ * a signer at "m/44'/60'" yields a child at "m/44'/60'/0'/0/1"). Purely self-relative: no
118
+ * coin-specific prefix is ever assumed or injected. The child owns an independent copy of
119
+ * its key and can itself derive further.
120
+ *
121
+ * @param {string} relPath - The path segment to derive, relative to this signer's own path.
122
+ * @returns {Promise<SeedSignerEvm>} The derived child signer.
123
+ */
124
+ async derive (relPath) {
125
+ const signer = Object.create(SeedSignerEvm.prototype)
126
+ signer._account = this._account.derivePath(relPath)
127
+ return signer
128
+ }
129
+
130
+ /**
131
+ * Returns the account's derived address.
132
+ *
133
+ * @returns {Promise<string>} The account's address.
134
+ */
135
+ async getAddress () {
136
+ return this._account.address
137
+ }
138
+
139
+ /**
140
+ * Signs a message.
141
+ *
142
+ * @param {string} message - The message to sign.
143
+ * @returns {Promise<string>} The message's signature.
144
+ */
145
+ async sign (message) {
146
+ return this._account.signMessage(message)
147
+ }
148
+
149
+ /**
150
+ * Signs a transaction.
151
+ *
152
+ * @param {TransactionLike} tx - The transaction to sign.
153
+ * @returns {Promise<string>} The signed transaction as a hex string.
154
+ */
155
+ async signTransaction (tx) {
156
+ return this._account.signTransaction(tx)
157
+ }
158
+
159
+ /**
160
+ * Signs typed data according to EIP-712.
161
+ *
162
+ * @param {TypedData} typedData - The typed data to sign.
163
+ * @returns {Promise<string>} The typed data signature.
164
+ */
165
+ async signTypedData ({ domain, types, message }) {
166
+ return this._account.signTypedData(domain, types, message)
167
+ }
168
+
169
+ /**
170
+ * Signs an ERC-7702 authorization tuple.
171
+ *
172
+ * @param {AuthorizationRequest} auth - The authorization request.
173
+ * @returns {Promise<Authorization>} The signed authorization.
174
+ */
175
+ async signAuthorization (auth) {
176
+ return this._account.authorizeSync(auth)
177
+ }
178
+
179
+ /**
180
+ * Disposes the signer, erasing its secrets from memory.
181
+ */
182
+ dispose () {
183
+ this._account.dispose()
184
+ }
185
+ }