@metamask/eth-hd-keyring 13.0.0 → 13.1.0

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/CHANGELOG.md CHANGED
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [13.1.0]
11
+
12
+ ### Added
13
+
14
+ - Add `HdKeyringV2` class implementing `KeyringV2` interface ([#398](https://github.com/MetaMask/accounts/pull/398)), ([#402](https://github.com/MetaMask/accounts/pull/402)), ([#404](https://github.com/MetaMask/accounts/pull/404)), ([#410](https://github.com/MetaMask/accounts/pull/410)), ([#413](https://github.com/MetaMask/accounts/pull/413)), ([#451](https://github.com/MetaMask/accounts/pull/451)), ([#453](https://github.com/MetaMask/accounts/pull/453))
15
+ - Wraps legacy `HdKeyring` to expose accounts via the unified `KeyringV2` API and the `KeyringAccount` type.
16
+ - Extends `EthKeyringWrapper` for common Ethereum logic.
17
+
18
+ ### Fixed
19
+
20
+ - Enforce mnemonics validation ([#450](https://github.com/MetaMask/accounts/pull/450))
21
+ - Validates mnemonics against BIP39 specification (word count, wordlist, checksum) before use.
22
+ - Throws for invalid mnemonics.
23
+
10
24
  ## [13.0.0]
11
25
 
12
26
  ### Added
@@ -221,7 +235,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
221
235
  - Deserialize method (and `HdKeyring` constructor by extension) can no longer be passed an options object containing a value for `numberOfAccounts` if it is not also containing a value for `mnemonic`.
222
236
  - Package name changed from `eth-hd-keyring` to `@metamask/eth-hd-keyring`.
223
237
 
224
- [Unreleased]: https://github.com/MetaMask/accounts/compare/@metamask/eth-hd-keyring@13.0.0...HEAD
238
+ [Unreleased]: https://github.com/MetaMask/accounts/compare/@metamask/eth-hd-keyring@13.1.0...HEAD
239
+ [13.1.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-hd-keyring@13.0.0...@metamask/eth-hd-keyring@13.1.0
225
240
  [13.0.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-hd-keyring@12.1.0...@metamask/eth-hd-keyring@13.0.0
226
241
  [12.1.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-hd-keyring@12.0.0...@metamask/eth-hd-keyring@12.1.0
227
242
  [12.0.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-hd-keyring@11.0.0...@metamask/eth-hd-keyring@12.0.0
@@ -0,0 +1,180 @@
1
+ "use strict";
2
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
+ };
7
+ var _HdKeyringV2_instances, _HdKeyringV2_isLastAccount, _HdKeyringV2_createKeyringAccount;
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.HdKeyringV2 = void 0;
10
+ const keyring_api_1 = require("@metamask/keyring-api");
11
+ const utils_1 = require("@metamask/utils");
12
+ /**
13
+ * Methods supported by HD keyring EOA accounts.
14
+ * HD keyrings support all standard signing methods plus encryption and app keys.
15
+ */
16
+ const HD_KEYRING_METHODS = [
17
+ keyring_api_1.EthMethod.SignTransaction,
18
+ keyring_api_1.EthMethod.Sign,
19
+ keyring_api_1.EthMethod.PersonalSign,
20
+ keyring_api_1.EthMethod.SignTypedDataV1,
21
+ keyring_api_1.EthMethod.SignTypedDataV3,
22
+ keyring_api_1.EthMethod.SignTypedDataV4,
23
+ keyring_api_1.EthKeyringMethod.Decrypt,
24
+ keyring_api_1.EthKeyringMethod.GetEncryptionPublicKey,
25
+ keyring_api_1.EthKeyringMethod.GetAppKeyAddress,
26
+ keyring_api_1.EthKeyringMethod.SignEip7702Authorization,
27
+ ];
28
+ const hdKeyringV2Capabilities = {
29
+ scopes: [keyring_api_1.EthScope.Eoa],
30
+ bip44: {
31
+ deriveIndex: true,
32
+ },
33
+ privateKey: {
34
+ exportFormats: [{ encoding: keyring_api_1.PrivateKeyEncoding.Hexadecimal }],
35
+ },
36
+ };
37
+ class HdKeyringV2 extends keyring_api_1.EthKeyringWrapper {
38
+ constructor(options) {
39
+ super({
40
+ type: keyring_api_1.KeyringType.Hd,
41
+ inner: options.legacyKeyring,
42
+ capabilities: hdKeyringV2Capabilities,
43
+ });
44
+ _HdKeyringV2_instances.add(this);
45
+ this.entropySource = options.entropySource;
46
+ }
47
+ async getAccounts() {
48
+ const addresses = await this.inner.getAccounts();
49
+ return addresses.map((address, addressIndex) => {
50
+ // Check if we already have this account in the registry
51
+ const existingId = this.registry.getAccountId(address);
52
+ if (existingId) {
53
+ const cached = this.registry.get(existingId);
54
+ if (cached) {
55
+ return cached;
56
+ }
57
+ }
58
+ // Create and register the account if not already cached
59
+ return __classPrivateFieldGet(this, _HdKeyringV2_instances, "m", _HdKeyringV2_createKeyringAccount).call(this, address, addressIndex);
60
+ });
61
+ }
62
+ async createAccounts(options) {
63
+ return this.withLock(async () => {
64
+ // For HD keyring, we only support BIP-44 derive index
65
+ if (options.type !== 'bip44:derive-index') {
66
+ throw new Error(`Unsupported account creation type for HdKeyring: ${options.type}`);
67
+ }
68
+ // Validate that the entropy source matches this keyring's entropy source
69
+ if (options.entropySource !== this.entropySource) {
70
+ throw new Error(`Entropy source mismatch: expected '${this.entropySource}', got '${options.entropySource}'`);
71
+ }
72
+ // Sync with the inner keyring state in case it was modified externally
73
+ // This ensures our cache is up-to-date before we make changes
74
+ const currentAccounts = await this.getAccounts();
75
+ const currentCount = currentAccounts.length;
76
+ const targetIndex = options.groupIndex;
77
+ // Check if an account at this index already exists
78
+ // Since only the last account can be deleted, array position always equals groupIndex
79
+ const existingAccount = currentAccounts[targetIndex];
80
+ if (existingAccount) {
81
+ return [existingAccount];
82
+ }
83
+ // Only allow derivation of the next account in sequence
84
+ if (targetIndex !== currentCount) {
85
+ throw new Error(`Can only create the next account in sequence. ` +
86
+ `Expected groupIndex ${currentCount}, got ${targetIndex}.`);
87
+ }
88
+ // Add the next account
89
+ const [newAddress] = await this.inner.addAccounts(1);
90
+ if (!newAddress) {
91
+ throw new Error('Failed to create new account');
92
+ }
93
+ const newAccount = __classPrivateFieldGet(this, _HdKeyringV2_instances, "m", _HdKeyringV2_createKeyringAccount).call(this, newAddress, targetIndex);
94
+ return [newAccount];
95
+ });
96
+ }
97
+ /**
98
+ * Delete an account from the keyring.
99
+ *
100
+ * ⚠️ Warning: Only deleting the last account is possible.
101
+ *
102
+ * @param accountId - The account ID to delete.
103
+ */
104
+ async deleteAccount(accountId) {
105
+ await this.withLock(async () => {
106
+ // Get the account first, before any registry operations
107
+ const { address } = await this.getAccount(accountId);
108
+ const hexAddress = this.toHexAddress(address);
109
+ // Assert that the account to delete is the last one in the inner keyring
110
+ // We check against the inner keyring directly to avoid stale registry issues
111
+ if (!(await __classPrivateFieldGet(this, _HdKeyringV2_instances, "m", _HdKeyringV2_isLastAccount).call(this, address))) {
112
+ throw new Error('Can only delete the last account in the HD keyring due to derivation index constraints.');
113
+ }
114
+ // Remove from the legacy keyring
115
+ this.inner.removeAccount(hexAddress);
116
+ // Remove from the registry
117
+ this.registry.delete(accountId);
118
+ });
119
+ }
120
+ /**
121
+ * Export the private key for an account in hexadecimal format.
122
+ *
123
+ * @param accountId - The ID of the account to export.
124
+ * @param options - Export options (only hexadecimal encoding is supported).
125
+ * @returns The exported account with private key.
126
+ */
127
+ async exportAccount(accountId, options) {
128
+ const account = await this.getAccount(accountId);
129
+ // Validate encoding - we only support hexadecimal for Ethereum keys
130
+ const requestedEncoding = options?.encoding ?? keyring_api_1.PrivateKeyEncoding.Hexadecimal;
131
+ if (requestedEncoding !== keyring_api_1.PrivateKeyEncoding.Hexadecimal) {
132
+ throw new Error(`Unsupported encoding for Ethereum HD keyring: ${requestedEncoding}. Only '${keyring_api_1.PrivateKeyEncoding.Hexadecimal}' is supported.`);
133
+ }
134
+ // The legacy HdKeyring returns a hex string without 0x prefix.
135
+ const privateKeyWithout0x = await this.inner.exportAccount(this.toHexAddress(account.address));
136
+ const privateKey = (0, utils_1.add0x)(privateKeyWithout0x);
137
+ return {
138
+ type: 'private-key',
139
+ privateKey,
140
+ encoding: keyring_api_1.PrivateKeyEncoding.Hexadecimal,
141
+ };
142
+ }
143
+ }
144
+ exports.HdKeyringV2 = HdKeyringV2;
145
+ _HdKeyringV2_instances = new WeakSet(), _HdKeyringV2_isLastAccount =
146
+ /**
147
+ * Checks if the given address is the last account in the inner keyring.
148
+ * This compares against the actual inner keyring state, not the registry,
149
+ * to avoid issues with stale registry entries.
150
+ *
151
+ * @param address - The address to check.
152
+ * @returns True if this is the last account in the inner keyring.
153
+ */
154
+ async function _HdKeyringV2_isLastAccount(address) {
155
+ const innerAddresses = await this.inner.getAccounts();
156
+ const lastAddress = innerAddresses[innerAddresses.length - 1];
157
+ return address === lastAddress;
158
+ }, _HdKeyringV2_createKeyringAccount = function _HdKeyringV2_createKeyringAccount(address, addressIndex) {
159
+ const id = this.registry.register(address);
160
+ const account = {
161
+ id,
162
+ type: keyring_api_1.EthAccountType.Eoa,
163
+ address,
164
+ scopes: [...this.capabilities.scopes],
165
+ methods: [...HD_KEYRING_METHODS],
166
+ options: {
167
+ entropy: {
168
+ type: keyring_api_1.KeyringAccountEntropyTypeOption.Mnemonic,
169
+ id: this.entropySource,
170
+ groupIndex: addressIndex,
171
+ derivationPath: `${this.inner.hdPath}/${addressIndex}`,
172
+ },
173
+ exportable: true,
174
+ },
175
+ };
176
+ // Add the account to the registry
177
+ this.registry.set(account);
178
+ return account;
179
+ };
180
+ //# sourceMappingURL=hd-keyring-v2.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hd-keyring-v2.cjs","sourceRoot":"","sources":["../src/hd-keyring-v2.ts"],"names":[],"mappings":";;;;;;;;;AACA,uDAgB+B;AAE/B,2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KACF,CAAC;IAEF,kCAAkC;IAClC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAE3B,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { Bip44Account } from '@metamask/account-api';\nimport {\n type CreateAccountOptions,\n EthAccountType,\n EthKeyringMethod,\n EthKeyringWrapper,\n EthMethod,\n EthScope,\n type ExportAccountOptions,\n type ExportedAccount,\n type KeyringAccount,\n KeyringAccountEntropyTypeOption,\n type KeyringCapabilities,\n type KeyringV2,\n KeyringType,\n PrivateKeyEncoding,\n type EntropySourceId,\n} from '@metamask/keyring-api';\nimport type { AccountId } from '@metamask/keyring-utils';\nimport { add0x, type Hex } from '@metamask/utils';\n\nimport type { HdKeyring } from './hd-keyring';\n\n/**\n * Methods supported by HD keyring EOA accounts.\n * HD keyrings support all standard signing methods plus encryption and app keys.\n */\nconst HD_KEYRING_METHODS = [\n EthMethod.SignTransaction,\n EthMethod.Sign,\n EthMethod.PersonalSign,\n EthMethod.SignTypedDataV1,\n EthMethod.SignTypedDataV3,\n EthMethod.SignTypedDataV4,\n EthKeyringMethod.Decrypt,\n EthKeyringMethod.GetEncryptionPublicKey,\n EthKeyringMethod.GetAppKeyAddress,\n EthKeyringMethod.SignEip7702Authorization,\n];\n\nconst hdKeyringV2Capabilities: KeyringCapabilities = {\n scopes: [EthScope.Eoa],\n bip44: {\n deriveIndex: true,\n },\n privateKey: {\n exportFormats: [{ encoding: PrivateKeyEncoding.Hexadecimal }],\n },\n};\n\n/**\n * Concrete {@link KeyringV2} adapter for {@link HdKeyring}.\n *\n * This wrapper exposes the accounts and signing capabilities of the legacy\n * HD keyring via the unified V2 interface.\n */\nexport type HdKeyringV2Options = {\n legacyKeyring: HdKeyring;\n entropySource: EntropySourceId;\n};\n\nexport class HdKeyringV2\n extends EthKeyringWrapper<HdKeyring, Bip44Account<KeyringAccount>>\n implements KeyringV2\n{\n protected readonly entropySource: EntropySourceId;\n\n constructor(options: HdKeyringV2Options) {\n super({\n type: KeyringType.Hd,\n inner: options.legacyKeyring,\n capabilities: hdKeyringV2Capabilities,\n });\n this.entropySource = options.entropySource;\n }\n\n /**\n * Checks if the given address is the last account in the inner keyring.\n * This compares against the actual inner keyring state, not the registry,\n * to avoid issues with stale registry entries.\n *\n * @param address - The address to check.\n * @returns True if this is the last account in the inner keyring.\n */\n async #isLastAccount(address: string): Promise<boolean> {\n const innerAddresses = await this.inner.getAccounts();\n const lastAddress = innerAddresses[innerAddresses.length - 1];\n return address === lastAddress;\n }\n\n /**\n * Creates a KeyringAccount object for the given address and index.\n *\n * @param address - The account address.\n * @param addressIndex - The account index in the HD path.\n * @returns The created KeyringAccount.\n */\n #createKeyringAccount(\n address: Hex,\n addressIndex: number,\n ): Bip44Account<KeyringAccount> {\n const id = this.registry.register(address);\n\n const account: Bip44Account<KeyringAccount> = {\n id,\n type: EthAccountType.Eoa,\n address,\n scopes: [...this.capabilities.scopes],\n methods: [...HD_KEYRING_METHODS],\n options: {\n entropy: {\n type: KeyringAccountEntropyTypeOption.Mnemonic,\n id: this.entropySource,\n groupIndex: addressIndex,\n derivationPath: `${this.inner.hdPath}/${addressIndex}`,\n },\n exportable: true,\n },\n };\n\n // Add the account to the registry\n this.registry.set(account);\n\n return account;\n }\n\n async getAccounts(): Promise<Bip44Account<KeyringAccount>[]> {\n const addresses = await this.inner.getAccounts();\n\n return addresses.map((address, addressIndex) => {\n // Check if we already have this account in the registry\n const existingId = this.registry.getAccountId(address);\n if (existingId) {\n const cached = this.registry.get(existingId);\n if (cached) {\n return cached;\n }\n }\n\n // Create and register the account if not already cached\n return this.#createKeyringAccount(address, addressIndex);\n });\n }\n\n async createAccounts(\n options: CreateAccountOptions,\n ): Promise<Bip44Account<KeyringAccount>[]> {\n return this.withLock(async () => {\n // For HD keyring, we only support BIP-44 derive index\n if (options.type !== 'bip44:derive-index') {\n throw new Error(\n `Unsupported account creation type for HdKeyring: ${options.type}`,\n );\n }\n\n // Validate that the entropy source matches this keyring's entropy source\n if (options.entropySource !== this.entropySource) {\n throw new Error(\n `Entropy source mismatch: expected '${this.entropySource}', got '${options.entropySource}'`,\n );\n }\n\n // Sync with the inner keyring state in case it was modified externally\n // This ensures our cache is up-to-date before we make changes\n const currentAccounts = await this.getAccounts();\n const currentCount = currentAccounts.length;\n const targetIndex = options.groupIndex;\n\n // Check if an account at this index already exists\n // Since only the last account can be deleted, array position always equals groupIndex\n const existingAccount = currentAccounts[targetIndex];\n if (existingAccount) {\n return [existingAccount];\n }\n\n // Only allow derivation of the next account in sequence\n if (targetIndex !== currentCount) {\n throw new Error(\n `Can only create the next account in sequence. ` +\n `Expected groupIndex ${currentCount}, got ${targetIndex}.`,\n );\n }\n\n // Add the next account\n const [newAddress] = await this.inner.addAccounts(1);\n\n if (!newAddress) {\n throw new Error('Failed to create new account');\n }\n\n const newAccount = this.#createKeyringAccount(newAddress, targetIndex);\n\n return [newAccount];\n });\n }\n\n /**\n * Delete an account from the keyring.\n *\n * ⚠️ Warning: Only deleting the last account is possible.\n *\n * @param accountId - The account ID to delete.\n */\n async deleteAccount(accountId: AccountId): Promise<void> {\n await this.withLock(async () => {\n // Get the account first, before any registry operations\n const { address } = await this.getAccount(accountId);\n const hexAddress = this.toHexAddress(address);\n\n // Assert that the account to delete is the last one in the inner keyring\n // We check against the inner keyring directly to avoid stale registry issues\n if (!(await this.#isLastAccount(address))) {\n throw new Error(\n 'Can only delete the last account in the HD keyring due to derivation index constraints.',\n );\n }\n\n // Remove from the legacy keyring\n this.inner.removeAccount(hexAddress);\n\n // Remove from the registry\n this.registry.delete(accountId);\n });\n }\n\n /**\n * Export the private key for an account in hexadecimal format.\n *\n * @param accountId - The ID of the account to export.\n * @param options - Export options (only hexadecimal encoding is supported).\n * @returns The exported account with private key.\n */\n async exportAccount(\n accountId: AccountId,\n options?: ExportAccountOptions,\n ): Promise<ExportedAccount> {\n const account = await this.getAccount(accountId);\n\n // Validate encoding - we only support hexadecimal for Ethereum keys\n const requestedEncoding =\n options?.encoding ?? PrivateKeyEncoding.Hexadecimal;\n\n if (requestedEncoding !== PrivateKeyEncoding.Hexadecimal) {\n throw new Error(\n `Unsupported encoding for Ethereum HD keyring: ${requestedEncoding}. Only '${PrivateKeyEncoding.Hexadecimal}' is supported.`,\n );\n }\n\n // The legacy HdKeyring returns a hex string without 0x prefix.\n const privateKeyWithout0x = await this.inner.exportAccount(\n this.toHexAddress(account.address),\n );\n const privateKey = add0x(privateKeyWithout0x);\n\n return {\n type: 'private-key',\n privateKey,\n encoding: PrivateKeyEncoding.Hexadecimal,\n };\n }\n}\n"]}
@@ -0,0 +1,38 @@
1
+ import type { Bip44Account } from "@metamask/account-api";
2
+ import { type CreateAccountOptions, EthKeyringWrapper, type ExportAccountOptions, type ExportedAccount, type KeyringAccount, type KeyringV2, type EntropySourceId } from "@metamask/keyring-api";
3
+ import type { AccountId } from "@metamask/keyring-utils";
4
+ import type { HdKeyring } from "./hd-keyring.cjs";
5
+ /**
6
+ * Concrete {@link KeyringV2} adapter for {@link HdKeyring}.
7
+ *
8
+ * This wrapper exposes the accounts and signing capabilities of the legacy
9
+ * HD keyring via the unified V2 interface.
10
+ */
11
+ export type HdKeyringV2Options = {
12
+ legacyKeyring: HdKeyring;
13
+ entropySource: EntropySourceId;
14
+ };
15
+ export declare class HdKeyringV2 extends EthKeyringWrapper<HdKeyring, Bip44Account<KeyringAccount>> implements KeyringV2 {
16
+ #private;
17
+ protected readonly entropySource: EntropySourceId;
18
+ constructor(options: HdKeyringV2Options);
19
+ getAccounts(): Promise<Bip44Account<KeyringAccount>[]>;
20
+ createAccounts(options: CreateAccountOptions): Promise<Bip44Account<KeyringAccount>[]>;
21
+ /**
22
+ * Delete an account from the keyring.
23
+ *
24
+ * ⚠️ Warning: Only deleting the last account is possible.
25
+ *
26
+ * @param accountId - The account ID to delete.
27
+ */
28
+ deleteAccount(accountId: AccountId): Promise<void>;
29
+ /**
30
+ * Export the private key for an account in hexadecimal format.
31
+ *
32
+ * @param accountId - The ID of the account to export.
33
+ * @param options - Export options (only hexadecimal encoding is supported).
34
+ * @returns The exported account with private key.
35
+ */
36
+ exportAccount(accountId: AccountId, options?: ExportAccountOptions): Promise<ExportedAccount>;
37
+ }
38
+ //# sourceMappingURL=hd-keyring-v2.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hd-keyring-v2.d.cts","sourceRoot":"","sources":["../src/hd-keyring-v2.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,8BAA8B;AAC1D,OAAO,EACL,KAAK,oBAAoB,EAGzB,iBAAiB,EAGjB,KAAK,oBAAoB,EACzB,KAAK,eAAe,EACpB,KAAK,cAAc,EAGnB,KAAK,SAAS,EAGd,KAAK,eAAe,EACrB,8BAA8B;AAC/B,OAAO,KAAK,EAAE,SAAS,EAAE,gCAAgC;AAGzD,OAAO,KAAK,EAAE,SAAS,EAAE,yBAAqB;AA6B9C;;;;;GAKG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,aAAa,EAAE,SAAS,CAAC;IACzB,aAAa,EAAE,eAAe,CAAC;CAChC,CAAC;AAEF,qBAAa,WACX,SAAQ,iBAAiB,CAAC,SAAS,EAAE,YAAY,CAAC,cAAc,CAAC,CACjE,YAAW,SAAS;;IAEpB,SAAS,CAAC,QAAQ,CAAC,aAAa,EAAE,eAAe,CAAC;gBAEtC,OAAO,EAAE,kBAAkB;IA2DjC,WAAW,IAAI,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,EAAE,CAAC;IAkBtD,cAAc,CAClB,OAAO,EAAE,oBAAoB,GAC5B,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,EAAE,CAAC;IAkD1C;;;;;;OAMG;IACG,aAAa,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC;IAsBxD;;;;;;OAMG;IACG,aAAa,CACjB,SAAS,EAAE,SAAS,EACpB,OAAO,CAAC,EAAE,oBAAoB,GAC7B,OAAO,CAAC,eAAe,CAAC;CAyB5B"}
@@ -0,0 +1,38 @@
1
+ import type { Bip44Account } from "@metamask/account-api";
2
+ import { type CreateAccountOptions, EthKeyringWrapper, type ExportAccountOptions, type ExportedAccount, type KeyringAccount, type KeyringV2, type EntropySourceId } from "@metamask/keyring-api";
3
+ import type { AccountId } from "@metamask/keyring-utils";
4
+ import type { HdKeyring } from "./hd-keyring.mjs";
5
+ /**
6
+ * Concrete {@link KeyringV2} adapter for {@link HdKeyring}.
7
+ *
8
+ * This wrapper exposes the accounts and signing capabilities of the legacy
9
+ * HD keyring via the unified V2 interface.
10
+ */
11
+ export type HdKeyringV2Options = {
12
+ legacyKeyring: HdKeyring;
13
+ entropySource: EntropySourceId;
14
+ };
15
+ export declare class HdKeyringV2 extends EthKeyringWrapper<HdKeyring, Bip44Account<KeyringAccount>> implements KeyringV2 {
16
+ #private;
17
+ protected readonly entropySource: EntropySourceId;
18
+ constructor(options: HdKeyringV2Options);
19
+ getAccounts(): Promise<Bip44Account<KeyringAccount>[]>;
20
+ createAccounts(options: CreateAccountOptions): Promise<Bip44Account<KeyringAccount>[]>;
21
+ /**
22
+ * Delete an account from the keyring.
23
+ *
24
+ * ⚠️ Warning: Only deleting the last account is possible.
25
+ *
26
+ * @param accountId - The account ID to delete.
27
+ */
28
+ deleteAccount(accountId: AccountId): Promise<void>;
29
+ /**
30
+ * Export the private key for an account in hexadecimal format.
31
+ *
32
+ * @param accountId - The ID of the account to export.
33
+ * @param options - Export options (only hexadecimal encoding is supported).
34
+ * @returns The exported account with private key.
35
+ */
36
+ exportAccount(accountId: AccountId, options?: ExportAccountOptions): Promise<ExportedAccount>;
37
+ }
38
+ //# sourceMappingURL=hd-keyring-v2.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hd-keyring-v2.d.mts","sourceRoot":"","sources":["../src/hd-keyring-v2.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,8BAA8B;AAC1D,OAAO,EACL,KAAK,oBAAoB,EAGzB,iBAAiB,EAGjB,KAAK,oBAAoB,EACzB,KAAK,eAAe,EACpB,KAAK,cAAc,EAGnB,KAAK,SAAS,EAGd,KAAK,eAAe,EACrB,8BAA8B;AAC/B,OAAO,KAAK,EAAE,SAAS,EAAE,gCAAgC;AAGzD,OAAO,KAAK,EAAE,SAAS,EAAE,yBAAqB;AA6B9C;;;;;GAKG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,aAAa,EAAE,SAAS,CAAC;IACzB,aAAa,EAAE,eAAe,CAAC;CAChC,CAAC;AAEF,qBAAa,WACX,SAAQ,iBAAiB,CAAC,SAAS,EAAE,YAAY,CAAC,cAAc,CAAC,CACjE,YAAW,SAAS;;IAEpB,SAAS,CAAC,QAAQ,CAAC,aAAa,EAAE,eAAe,CAAC;gBAEtC,OAAO,EAAE,kBAAkB;IA2DjC,WAAW,IAAI,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,EAAE,CAAC;IAkBtD,cAAc,CAClB,OAAO,EAAE,oBAAoB,GAC5B,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,EAAE,CAAC;IAkD1C;;;;;;OAMG;IACG,aAAa,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC;IAsBxD;;;;;;OAMG;IACG,aAAa,CACjB,SAAS,EAAE,SAAS,EACpB,OAAO,CAAC,EAAE,oBAAoB,GAC7B,OAAO,CAAC,eAAe,CAAC;CAyB5B"}
@@ -0,0 +1,176 @@
1
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
+ };
6
+ var _HdKeyringV2_instances, _HdKeyringV2_isLastAccount, _HdKeyringV2_createKeyringAccount;
7
+ import { EthAccountType, EthKeyringMethod, EthKeyringWrapper, EthMethod, EthScope, KeyringAccountEntropyTypeOption, KeyringType, PrivateKeyEncoding } from "@metamask/keyring-api";
8
+ import { add0x } from "@metamask/utils";
9
+ /**
10
+ * Methods supported by HD keyring EOA accounts.
11
+ * HD keyrings support all standard signing methods plus encryption and app keys.
12
+ */
13
+ const HD_KEYRING_METHODS = [
14
+ EthMethod.SignTransaction,
15
+ EthMethod.Sign,
16
+ EthMethod.PersonalSign,
17
+ EthMethod.SignTypedDataV1,
18
+ EthMethod.SignTypedDataV3,
19
+ EthMethod.SignTypedDataV4,
20
+ EthKeyringMethod.Decrypt,
21
+ EthKeyringMethod.GetEncryptionPublicKey,
22
+ EthKeyringMethod.GetAppKeyAddress,
23
+ EthKeyringMethod.SignEip7702Authorization,
24
+ ];
25
+ const hdKeyringV2Capabilities = {
26
+ scopes: [EthScope.Eoa],
27
+ bip44: {
28
+ deriveIndex: true,
29
+ },
30
+ privateKey: {
31
+ exportFormats: [{ encoding: PrivateKeyEncoding.Hexadecimal }],
32
+ },
33
+ };
34
+ export class HdKeyringV2 extends EthKeyringWrapper {
35
+ constructor(options) {
36
+ super({
37
+ type: KeyringType.Hd,
38
+ inner: options.legacyKeyring,
39
+ capabilities: hdKeyringV2Capabilities,
40
+ });
41
+ _HdKeyringV2_instances.add(this);
42
+ this.entropySource = options.entropySource;
43
+ }
44
+ async getAccounts() {
45
+ const addresses = await this.inner.getAccounts();
46
+ return addresses.map((address, addressIndex) => {
47
+ // Check if we already have this account in the registry
48
+ const existingId = this.registry.getAccountId(address);
49
+ if (existingId) {
50
+ const cached = this.registry.get(existingId);
51
+ if (cached) {
52
+ return cached;
53
+ }
54
+ }
55
+ // Create and register the account if not already cached
56
+ return __classPrivateFieldGet(this, _HdKeyringV2_instances, "m", _HdKeyringV2_createKeyringAccount).call(this, address, addressIndex);
57
+ });
58
+ }
59
+ async createAccounts(options) {
60
+ return this.withLock(async () => {
61
+ // For HD keyring, we only support BIP-44 derive index
62
+ if (options.type !== 'bip44:derive-index') {
63
+ throw new Error(`Unsupported account creation type for HdKeyring: ${options.type}`);
64
+ }
65
+ // Validate that the entropy source matches this keyring's entropy source
66
+ if (options.entropySource !== this.entropySource) {
67
+ throw new Error(`Entropy source mismatch: expected '${this.entropySource}', got '${options.entropySource}'`);
68
+ }
69
+ // Sync with the inner keyring state in case it was modified externally
70
+ // This ensures our cache is up-to-date before we make changes
71
+ const currentAccounts = await this.getAccounts();
72
+ const currentCount = currentAccounts.length;
73
+ const targetIndex = options.groupIndex;
74
+ // Check if an account at this index already exists
75
+ // Since only the last account can be deleted, array position always equals groupIndex
76
+ const existingAccount = currentAccounts[targetIndex];
77
+ if (existingAccount) {
78
+ return [existingAccount];
79
+ }
80
+ // Only allow derivation of the next account in sequence
81
+ if (targetIndex !== currentCount) {
82
+ throw new Error(`Can only create the next account in sequence. ` +
83
+ `Expected groupIndex ${currentCount}, got ${targetIndex}.`);
84
+ }
85
+ // Add the next account
86
+ const [newAddress] = await this.inner.addAccounts(1);
87
+ if (!newAddress) {
88
+ throw new Error('Failed to create new account');
89
+ }
90
+ const newAccount = __classPrivateFieldGet(this, _HdKeyringV2_instances, "m", _HdKeyringV2_createKeyringAccount).call(this, newAddress, targetIndex);
91
+ return [newAccount];
92
+ });
93
+ }
94
+ /**
95
+ * Delete an account from the keyring.
96
+ *
97
+ * ⚠️ Warning: Only deleting the last account is possible.
98
+ *
99
+ * @param accountId - The account ID to delete.
100
+ */
101
+ async deleteAccount(accountId) {
102
+ await this.withLock(async () => {
103
+ // Get the account first, before any registry operations
104
+ const { address } = await this.getAccount(accountId);
105
+ const hexAddress = this.toHexAddress(address);
106
+ // Assert that the account to delete is the last one in the inner keyring
107
+ // We check against the inner keyring directly to avoid stale registry issues
108
+ if (!(await __classPrivateFieldGet(this, _HdKeyringV2_instances, "m", _HdKeyringV2_isLastAccount).call(this, address))) {
109
+ throw new Error('Can only delete the last account in the HD keyring due to derivation index constraints.');
110
+ }
111
+ // Remove from the legacy keyring
112
+ this.inner.removeAccount(hexAddress);
113
+ // Remove from the registry
114
+ this.registry.delete(accountId);
115
+ });
116
+ }
117
+ /**
118
+ * Export the private key for an account in hexadecimal format.
119
+ *
120
+ * @param accountId - The ID of the account to export.
121
+ * @param options - Export options (only hexadecimal encoding is supported).
122
+ * @returns The exported account with private key.
123
+ */
124
+ async exportAccount(accountId, options) {
125
+ const account = await this.getAccount(accountId);
126
+ // Validate encoding - we only support hexadecimal for Ethereum keys
127
+ const requestedEncoding = options?.encoding ?? PrivateKeyEncoding.Hexadecimal;
128
+ if (requestedEncoding !== PrivateKeyEncoding.Hexadecimal) {
129
+ throw new Error(`Unsupported encoding for Ethereum HD keyring: ${requestedEncoding}. Only '${PrivateKeyEncoding.Hexadecimal}' is supported.`);
130
+ }
131
+ // The legacy HdKeyring returns a hex string without 0x prefix.
132
+ const privateKeyWithout0x = await this.inner.exportAccount(this.toHexAddress(account.address));
133
+ const privateKey = add0x(privateKeyWithout0x);
134
+ return {
135
+ type: 'private-key',
136
+ privateKey,
137
+ encoding: PrivateKeyEncoding.Hexadecimal,
138
+ };
139
+ }
140
+ }
141
+ _HdKeyringV2_instances = new WeakSet(), _HdKeyringV2_isLastAccount =
142
+ /**
143
+ * Checks if the given address is the last account in the inner keyring.
144
+ * This compares against the actual inner keyring state, not the registry,
145
+ * to avoid issues with stale registry entries.
146
+ *
147
+ * @param address - The address to check.
148
+ * @returns True if this is the last account in the inner keyring.
149
+ */
150
+ async function _HdKeyringV2_isLastAccount(address) {
151
+ const innerAddresses = await this.inner.getAccounts();
152
+ const lastAddress = innerAddresses[innerAddresses.length - 1];
153
+ return address === lastAddress;
154
+ }, _HdKeyringV2_createKeyringAccount = function _HdKeyringV2_createKeyringAccount(address, addressIndex) {
155
+ const id = this.registry.register(address);
156
+ const account = {
157
+ id,
158
+ type: EthAccountType.Eoa,
159
+ address,
160
+ scopes: [...this.capabilities.scopes],
161
+ methods: [...HD_KEYRING_METHODS],
162
+ options: {
163
+ entropy: {
164
+ type: KeyringAccountEntropyTypeOption.Mnemonic,
165
+ id: this.entropySource,
166
+ groupIndex: addressIndex,
167
+ derivationPath: `${this.inner.hdPath}/${addressIndex}`,
168
+ },
169
+ exportable: true,
170
+ },
171
+ };
172
+ // Add the account to the registry
173
+ this.registry.set(account);
174
+ return account;
175
+ };
176
+ //# sourceMappingURL=hd-keyring-v2.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hd-keyring-v2.mjs","sourceRoot":"","sources":["../src/hd-keyring-v2.ts"],"names":[],"mappings":";;;;;;AACA,OAAO,EAEL,cAAc,EACd,gBAAgB,EAChB,iBAAiB,EACjB,SAAS,EACT,QAAQ,EAIR,+BAA+B,EAG/B,WAAW,EACX,kBAAkB,EAEnB,8BAA8B;AAE/B,OAAO,EAAE,KAAK,EAAY,wBAAwB;AAIlD;;;GAGG;AACH,MAAM,kBAAkB,GAAG;IACzB,SAAS,CAAC,eAAe;IACzB,SAAS,CAAC,IAAI;IACd,SAAS,CAAC,YAAY;IACtB,SAAS,CAAC,eAAe;IACzB,SAAS,CAAC,eAAe;IACzB,SAAS,CAAC,eAAe;IACzB,gBAAgB,CAAC,OAAO;IACxB,gBAAgB,CAAC,sBAAsB;IACvC,gBAAgB,CAAC,gBAAgB;IACjC,gBAAgB,CAAC,wBAAwB;CAC1C,CAAC;AAEF,MAAM,uBAAuB,GAAwB;IACnD,MAAM,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC;IACtB,KAAK,EAAE;QACL,WAAW,EAAE,IAAI;KAClB;IACD,UAAU,EAAE;QACV,aAAa,EAAE,CAAC,EAAE,QAAQ,EAAE,kBAAkB,CAAC,WAAW,EAAE,CAAC;KAC9D;CACF,CAAC;AAaF,MAAM,OAAO,WACX,SAAQ,iBAA0D;IAKlE,YAAY,OAA2B;QACrC,KAAK,CAAC;YACJ,IAAI,EAAE,WAAW,CAAC,EAAE;YACpB,KAAK,EAAE,OAAO,CAAC,aAAa;YAC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G,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IAE3C,MAAM,OAAO,GAAiC;QAC5C,EAAE;QACF,IAAI,EAAE,cAAc,CAAC,GAAG;QACxB,OAAO;QACP,MAAM,EAAE,CAAC,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC;QACrC,OAAO,EAAE,CAAC,GAAG,kBAAkB,CAAC;QAChC,OAAO,EAAE;YACP,OAAO,EAAE;gBACP,IAAI,EAAE,+BAA+B,CAAC,QAAQ;gBAC9C,EAAE,EAAE,IAAI,CAAC,aAAa;gBACtB,UAAU,EAAE,YAAY;gBACxB,cAAc,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,YAAY,EAAE;aACvD;YACD,UAAU,EAAE,IAAI;SACjB;KACF,CAAC;IAEF,kCAAkC;IAClC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAE3B,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { Bip44Account } from '@metamask/account-api';\nimport {\n type CreateAccountOptions,\n EthAccountType,\n EthKeyringMethod,\n EthKeyringWrapper,\n EthMethod,\n EthScope,\n type ExportAccountOptions,\n type ExportedAccount,\n type KeyringAccount,\n KeyringAccountEntropyTypeOption,\n type KeyringCapabilities,\n type KeyringV2,\n KeyringType,\n PrivateKeyEncoding,\n type EntropySourceId,\n} from '@metamask/keyring-api';\nimport type { AccountId } from '@metamask/keyring-utils';\nimport { add0x, type Hex } from '@metamask/utils';\n\nimport type { HdKeyring } from './hd-keyring';\n\n/**\n * Methods supported by HD keyring EOA accounts.\n * HD keyrings support all standard signing methods plus encryption and app keys.\n */\nconst HD_KEYRING_METHODS = [\n EthMethod.SignTransaction,\n EthMethod.Sign,\n EthMethod.PersonalSign,\n EthMethod.SignTypedDataV1,\n EthMethod.SignTypedDataV3,\n EthMethod.SignTypedDataV4,\n EthKeyringMethod.Decrypt,\n EthKeyringMethod.GetEncryptionPublicKey,\n EthKeyringMethod.GetAppKeyAddress,\n EthKeyringMethod.SignEip7702Authorization,\n];\n\nconst hdKeyringV2Capabilities: KeyringCapabilities = {\n scopes: [EthScope.Eoa],\n bip44: {\n deriveIndex: true,\n },\n privateKey: {\n exportFormats: [{ encoding: PrivateKeyEncoding.Hexadecimal }],\n },\n};\n\n/**\n * Concrete {@link KeyringV2} adapter for {@link HdKeyring}.\n *\n * This wrapper exposes the accounts and signing capabilities of the legacy\n * HD keyring via the unified V2 interface.\n */\nexport type HdKeyringV2Options = {\n legacyKeyring: HdKeyring;\n entropySource: EntropySourceId;\n};\n\nexport class HdKeyringV2\n extends EthKeyringWrapper<HdKeyring, Bip44Account<KeyringAccount>>\n implements KeyringV2\n{\n protected readonly entropySource: EntropySourceId;\n\n constructor(options: HdKeyringV2Options) {\n super({\n type: KeyringType.Hd,\n inner: options.legacyKeyring,\n capabilities: hdKeyringV2Capabilities,\n });\n this.entropySource = options.entropySource;\n }\n\n /**\n * Checks if the given address is the last account in the inner keyring.\n * This compares against the actual inner keyring state, not the registry,\n * to avoid issues with stale registry entries.\n *\n * @param address - The address to check.\n * @returns True if this is the last account in the inner keyring.\n */\n async #isLastAccount(address: string): Promise<boolean> {\n const innerAddresses = await this.inner.getAccounts();\n const lastAddress = innerAddresses[innerAddresses.length - 1];\n return address === lastAddress;\n }\n\n /**\n * Creates a KeyringAccount object for the given address and index.\n *\n * @param address - The account address.\n * @param addressIndex - The account index in the HD path.\n * @returns The created KeyringAccount.\n */\n #createKeyringAccount(\n address: Hex,\n addressIndex: number,\n ): Bip44Account<KeyringAccount> {\n const id = this.registry.register(address);\n\n const account: Bip44Account<KeyringAccount> = {\n id,\n type: EthAccountType.Eoa,\n address,\n scopes: [...this.capabilities.scopes],\n methods: [...HD_KEYRING_METHODS],\n options: {\n entropy: {\n type: KeyringAccountEntropyTypeOption.Mnemonic,\n id: this.entropySource,\n groupIndex: addressIndex,\n derivationPath: `${this.inner.hdPath}/${addressIndex}`,\n },\n exportable: true,\n },\n };\n\n // Add the account to the registry\n this.registry.set(account);\n\n return account;\n }\n\n async getAccounts(): Promise<Bip44Account<KeyringAccount>[]> {\n const addresses = await this.inner.getAccounts();\n\n return addresses.map((address, addressIndex) => {\n // Check if we already have this account in the registry\n const existingId = this.registry.getAccountId(address);\n if (existingId) {\n const cached = this.registry.get(existingId);\n if (cached) {\n return cached;\n }\n }\n\n // Create and register the account if not already cached\n return this.#createKeyringAccount(address, addressIndex);\n });\n }\n\n async createAccounts(\n options: CreateAccountOptions,\n ): Promise<Bip44Account<KeyringAccount>[]> {\n return this.withLock(async () => {\n // For HD keyring, we only support BIP-44 derive index\n if (options.type !== 'bip44:derive-index') {\n throw new Error(\n `Unsupported account creation type for HdKeyring: ${options.type}`,\n );\n }\n\n // Validate that the entropy source matches this keyring's entropy source\n if (options.entropySource !== this.entropySource) {\n throw new Error(\n `Entropy source mismatch: expected '${this.entropySource}', got '${options.entropySource}'`,\n );\n }\n\n // Sync with the inner keyring state in case it was modified externally\n // This ensures our cache is up-to-date before we make changes\n const currentAccounts = await this.getAccounts();\n const currentCount = currentAccounts.length;\n const targetIndex = options.groupIndex;\n\n // Check if an account at this index already exists\n // Since only the last account can be deleted, array position always equals groupIndex\n const existingAccount = currentAccounts[targetIndex];\n if (existingAccount) {\n return [existingAccount];\n }\n\n // Only allow derivation of the next account in sequence\n if (targetIndex !== currentCount) {\n throw new Error(\n `Can only create the next account in sequence. ` +\n `Expected groupIndex ${currentCount}, got ${targetIndex}.`,\n );\n }\n\n // Add the next account\n const [newAddress] = await this.inner.addAccounts(1);\n\n if (!newAddress) {\n throw new Error('Failed to create new account');\n }\n\n const newAccount = this.#createKeyringAccount(newAddress, targetIndex);\n\n return [newAccount];\n });\n }\n\n /**\n * Delete an account from the keyring.\n *\n * ⚠️ Warning: Only deleting the last account is possible.\n *\n * @param accountId - The account ID to delete.\n */\n async deleteAccount(accountId: AccountId): Promise<void> {\n await this.withLock(async () => {\n // Get the account first, before any registry operations\n const { address } = await this.getAccount(accountId);\n const hexAddress = this.toHexAddress(address);\n\n // Assert that the account to delete is the last one in the inner keyring\n // We check against the inner keyring directly to avoid stale registry issues\n if (!(await this.#isLastAccount(address))) {\n throw new Error(\n 'Can only delete the last account in the HD keyring due to derivation index constraints.',\n );\n }\n\n // Remove from the legacy keyring\n this.inner.removeAccount(hexAddress);\n\n // Remove from the registry\n this.registry.delete(accountId);\n });\n }\n\n /**\n * Export the private key for an account in hexadecimal format.\n *\n * @param accountId - The ID of the account to export.\n * @param options - Export options (only hexadecimal encoding is supported).\n * @returns The exported account with private key.\n */\n async exportAccount(\n accountId: AccountId,\n options?: ExportAccountOptions,\n ): Promise<ExportedAccount> {\n const account = await this.getAccount(accountId);\n\n // Validate encoding - we only support hexadecimal for Ethereum keys\n const requestedEncoding =\n options?.encoding ?? PrivateKeyEncoding.Hexadecimal;\n\n if (requestedEncoding !== PrivateKeyEncoding.Hexadecimal) {\n throw new Error(\n `Unsupported encoding for Ethereum HD keyring: ${requestedEncoding}. Only '${PrivateKeyEncoding.Hexadecimal}' is supported.`,\n );\n }\n\n // The legacy HdKeyring returns a hex string without 0x prefix.\n const privateKeyWithout0x = await this.inner.exportAccount(\n this.toHexAddress(account.address),\n );\n const privateKey = add0x(privateKeyWithout0x);\n\n return {\n type: 'private-key',\n privateKey,\n encoding: PrivateKeyEncoding.Hexadecimal,\n };\n }\n}\n"]}
@@ -10,7 +10,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
12
  };
13
- var _HdKeyring_instances, _HdKeyring_walletMap, _HdKeyring_cryptographicFunctions, _HdKeyring_uint8ArrayToString, _HdKeyring_stringToUint8Array, _HdKeyring_mnemonicToUint8Array, _HdKeyring_getPrivateKeyFor, _HdKeyring_getWalletForAccount, _HdKeyring_initFromMnemonic, _HdKeyring_addressFromPublicKey, _HdKeyring_normalizeAddress;
13
+ var _HdKeyring_instances, _HdKeyring_walletMap, _HdKeyring_cryptographicFunctions, _HdKeyring_uint8ArrayToString, _HdKeyring_stringToUint8Array, _HdKeyring_mnemonicToUint8Array, _HdKeyring_getPrivateKeyFor, _HdKeyring_getWalletForAccount, _HdKeyring_initFromMnemonic, _HdKeyring_addressFromPublicKey, _HdKeyring_normalizeAddress, _HdKeyring_assertValidMnemonic;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.HdKeyring = void 0;
16
16
  const util_1 = require("@ethereumjs/util");
@@ -365,7 +365,11 @@ async function _HdKeyring_initFromMnemonic(mnemonic) {
365
365
  if (this.root) {
366
366
  throw new Error('Eth-Hd-Keyring: Secret recovery phrase already provided');
367
367
  }
368
- this.mnemonic = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_mnemonicToUint8Array).call(this, mnemonic);
368
+ // Convert and validate before assigning to instance property
369
+ // to avoid inconsistent state if validation fails
370
+ const mnemonicAsUint8Array = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_mnemonicToUint8Array).call(this, mnemonic);
371
+ __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_assertValidMnemonic).call(this, mnemonicAsUint8Array);
372
+ this.mnemonic = mnemonicAsUint8Array;
369
373
  this.seed = await (0, key_tree_1.mnemonicToSeed)(this.mnemonic, '', // No passphrase
370
374
  __classPrivateFieldGet(this, _HdKeyring_cryptographicFunctions, "f"));
371
375
  this.hdWallet = hdkey_1.HDKey.fromMasterSeed(this.seed);
@@ -376,6 +380,11 @@ async function _HdKeyring_initFromMnemonic(mnemonic) {
376
380
  const normalized = (0, eth_sig_util_1.normalize)(address);
377
381
  (0, utils_1.assert)(normalized, 'Expected address to be set');
378
382
  return (0, utils_1.add0x)(normalized);
383
+ }, _HdKeyring_assertValidMnemonic = function _HdKeyring_assertValidMnemonic(mnemonic) {
384
+ const mnemonicString = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_uint8ArrayToString).call(this, mnemonic);
385
+ if (!(0, scure_bip39_1.validateMnemonic)(mnemonicString, english_1.wordlist)) {
386
+ throw new Error('Eth-Hd-Keyring: Invalid secret recovery phrase provided');
387
+ }
379
388
  };
380
389
  HdKeyring.type = type;
381
390
  //# sourceMappingURL=hd-keyring.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"hd-keyring.cjs","sourceRoot":"","sources":["../src/hd-keyring.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,2CAA4E;AAC5E,yDAcgC;AAChC,iDAG4B;AAE5B,uDAAyD;AACzD,6EAAwE;AACxE,2CAQyB;AACzB,uDAAoD;AACpD,yDAAyD;AAEzD,WAAW;AACX,MAAM,YAAY,GAAG,gBAAgB,CAAC;AACtC,MAAM,IAAI,GAAG,aAAa,CAAC;AAqD3B;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,KAAc;IACxC,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,MAAM,IAAI,KAAK;QACf,KAAK,CAAC,IAAI,KAAK,QAAQ;QACvB,MAAM,IAAI,KAAK;QACf,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAC1B,CAAC;AACJ,CAAC;AAED,MAAa,SAAS;IAmBpB,YAAY,OAAyB,EAAE;;QAhBvC,SAAI,GAAW,IAAI,CAAC;QAUpB,WAAM,GAAW,YAAY,CAAC;QAErB,+BAAa,IAAI,GAAG,EAAmB,EAAC;QAExC,oDAAiD;QAGxD,yHAAyH;QACzH,uBAAA,IAAI,qCAA2B,IAAI,CAAC,sBAAsB,MAAA,CAAC;IAC7D,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,sBAAsB;QAC1B,MAAM,uBAAA,IAAI,yDAAkB,MAAtB,IAAI,EAAmB,IAAA,8BAAgB,EAAC,kBAAQ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E;IAEpE,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;QACd,MAAM,IAAI,KAAK,CACb,yDAAyD,CAC1D,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,QAAQ,GAAG,uBAAA,IAAI,6DAAsB,MAA1B,IAAI,EAAuB,QAAQ,CAAC,CAAC;IAErD,IAAI,CAAC,IAAI,GAAG,MAAM,IAAA,yBAAc,EAC9B,IAAI,CAAC,QAAQ,EACb,EAAE,EAAE,gBAAgB;IACpB,uBAAA,IAAI,yCAAwB,CAC7B,CAAC;IACF,IAAI,CAAC,QAAQ,GAAG,aAAK,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAChD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAChD,CAAC,6EAQqB,SAAqB;IACzC,OAAO,IAAA,aAAK,EACV,IAAA,kBAAU,EAAC,IAAA,sBAAe,EAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,WAAW,EAAE,CACxE,CAAC;AACJ,CAAC,qEAQiB,OAAe;IAC/B,MAAM,UAAU,GAAG,IAAA,wBAAS,EAAC,OAAO,CAAC,CAAC;IACtC,IAAA,cAAM,EAAC,UAAU,EAAE,4BAA4B,CAAC,CAAC;IACjD,OAAO,IAAA,aAAK,EAAC,UAAU,CAAC,CAAC;AAC3B,CAAC;AAvhBM,cAAI,GAAW,IAAI,AAAf,CAAgB","sourcesContent":["import type { TypedTransaction } from '@ethereumjs/tx';\nimport { privateToPublic, publicToAddress, ecsign } from '@ethereumjs/util';\nimport {\n concatSig,\n decrypt,\n type EIP7702Authorization,\n type EthEncryptedData,\n getEncryptionPublicKey,\n type MessageTypes,\n normalize,\n personalSign,\n signEIP7702Authorization,\n signTypedData,\n SignTypedDataVersion,\n type TypedDataV1,\n type TypedMessage,\n} from '@metamask/eth-sig-util';\nimport {\n type CryptographicFunctions,\n mnemonicToSeed,\n} from '@metamask/key-tree';\nimport type { Keyring } from '@metamask/keyring-utils';\nimport { generateMnemonic } from '@metamask/scure-bip39';\nimport { wordlist } from '@metamask/scure-bip39/dist/wordlists/english';\nimport {\n add0x,\n assert,\n assertIsHexString,\n bigIntToBytes,\n bytesToHex,\n type Hex,\n remove0x,\n} from '@metamask/utils';\nimport { HDKey } from 'ethereum-cryptography/hdkey';\nimport { keccak256 } from 'ethereum-cryptography/keccak';\n\n// Options:\nconst hdPathString = `m/44'/60'/0'/0`;\nconst type = 'HD Key Tree';\n\nexport type HDKeyringOptions = {\n cryptographicFunctions?: CryptographicFunctions;\n};\n\n/**\n * The serialized state of an `HDKeyring` instance.\n *\n * @property mnemonic - The mnemonic seed phrase as an array of numbers.\n * @property numberOfAccounts - The number of accounts in the keyring.\n * @property hdPath - The HD path used to derive accounts.\n */\nexport type SerializedHDKeyringState = {\n mnemonic: number[];\n numberOfAccounts: number;\n hdPath: string;\n};\n\n/**\n * An object that can be passed to the Keyring.deserialize method to initialize\n * an `HDKeyring` instance.\n *\n * @property mnemonic - The mnemonic seed phrase as an array of numbers.\n * @property numberOfAccounts - The number of accounts in the keyring.\n * @property hdPath - The HD path used to derive accounts.\n */\nexport type DeserializableHDKeyringState = Omit<\n SerializedHDKeyringState,\n 'mnemonic'\n> & {\n mnemonic: number[] | SerializedBuffer | string;\n};\n\n/**\n * Options for selecting an account from an `HDKeyring` instance.\n *\n * @property withAppKeyOrigin - The origin of the app requesting the account.\n */\nexport type HDKeyringAccountSelectionOptions = {\n withAppKeyOrigin?: string;\n};\n\ntype SerializedBuffer = ReturnType<Buffer['toJSON']>;\n\n/**\n * Wallet storage object that contains both the HDKey and pre-computed address.\n */\ntype WalletData = {\n hdKey: HDKey;\n address: Hex;\n};\n\n/**\n * Checks if the given value is a valid serialized Buffer compatible with\n * the return type of `Buffer.toJSON`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid serialized buffer, `false` otherwise.\n */\nfunction isSerializedBuffer(value: unknown): value is SerializedBuffer {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'type' in value &&\n value.type === 'Buffer' &&\n 'data' in value &&\n Array.isArray(value.data)\n );\n}\n\nexport class HdKeyring implements Keyring {\n static type: string = type;\n\n type: string = type;\n\n mnemonic?: Uint8Array | null;\n\n seed?: Uint8Array | null;\n\n root?: HDKey | null;\n\n hdWallet?: HDKey;\n\n hdPath: string = hdPathString;\n\n readonly #walletMap = new Map<Hex, WalletData>();\n\n readonly #cryptographicFunctions?: CryptographicFunctions;\n\n constructor(opts: HDKeyringOptions = {}) {\n // Cryptographic functions to be used by `@metamask/key-tree`. It will use built-in implementations if not provided here.\n this.#cryptographicFunctions = opts.cryptographicFunctions;\n }\n\n /**\n * Initialize the keyring with a random mnemonic.\n *\n * @returns A promise that resolves when the process is complete.\n */\n async generateRandomMnemonic(): Promise<void> {\n await this.#initFromMnemonic(generateMnemonic(wordlist));\n }\n\n /**\n * Return the serialized state of the keyring.\n *\n * @returns The serialized state of the keyring.\n */\n async serialize(): Promise<SerializedHDKeyringState> {\n let mnemonic: number[] = [];\n\n if (this.mnemonic) {\n const mnemonicAsString = this.#uint8ArrayToString(this.mnemonic);\n mnemonic = Array.from(new TextEncoder().encode(mnemonicAsString));\n }\n\n return {\n mnemonic,\n numberOfAccounts: this.#walletMap.size,\n hdPath: this.hdPath,\n };\n }\n\n /**\n * Initialize the keyring with the given serialized state.\n *\n * @param opts - The serialized state of the keyring.\n * @returns An empty array.\n */\n async deserialize(\n opts: Partial<DeserializableHDKeyringState>,\n ): Promise<void> {\n if (opts.numberOfAccounts && !opts.mnemonic) {\n throw new Error(\n 'Eth-Hd-Keyring: Deserialize method cannot be called with an opts value for numberOfAccounts and no menmonic',\n );\n }\n\n if (this.root) {\n throw new Error(\n 'Eth-Hd-Keyring: Secret recovery phrase already provided',\n );\n }\n\n this.#walletMap.clear();\n this.mnemonic = null;\n this.seed = null;\n this.root = null;\n this.hdPath = opts.hdPath ?? hdPathString;\n\n if (opts.mnemonic) {\n await this.#initFromMnemonic(opts.mnemonic);\n }\n\n if (opts.numberOfAccounts) {\n await this.addAccounts(opts.numberOfAccounts);\n }\n }\n\n /**\n * Add new accounts to the keyring. The accounts will be derived\n * sequentially from the root HD wallet, using increasing indices.\n *\n * @param numberOfAccounts - The number of accounts to add.\n * @returns The addresses of the new accounts.\n */\n async addAccounts(numberOfAccounts = 1): Promise<Hex[]> {\n if (!this.root) {\n throw new Error('Eth-Hd-Keyring: No secret recovery phrase provided');\n }\n\n const oldLen = this.#walletMap.size;\n const newAddresses: Hex[] = [];\n for (let i = oldLen; i < numberOfAccounts + oldLen; i++) {\n const hdKey = this.root.deriveChild(i);\n assert(hdKey.publicKey, 'Expected public key to be set');\n\n const address = this.#addressFromPublicKey(hdKey.publicKey);\n const walletData: WalletData = {\n hdKey,\n address,\n };\n\n this.#walletMap.set(address, walletData);\n newAddresses.push(address);\n }\n\n return Promise.resolve(newAddresses);\n }\n\n /**\n * Get the addresses of all accounts in the keyring.\n *\n * @returns The addresses of all accounts in the keyring.\n */\n async getAccounts(): Promise<Hex[]> {\n return Array.from(this.#walletMap.keys());\n }\n\n /**\n * Get the public address of the account for the given app key origin.\n *\n * @param address - The address of the account.\n * @param origin - The origin of the app requesting the account.\n * @returns The public address of the account.\n */\n async getAppKeyAddress(address: Hex, origin: string): Promise<Hex> {\n if (!origin || typeof origin !== 'string') {\n throw new Error(`'origin' must be a non-empty string`);\n }\n const wallet = this.#getWalletForAccount(address, {\n withAppKeyOrigin: origin,\n });\n assert(wallet.publicKey, 'Expected public key to be set');\n const appKeyAddress = this.#normalizeAddress(\n bytesToHex(publicToAddress(wallet.publicKey)),\n );\n return appKeyAddress;\n }\n\n /**\n * Export the private key for a specific account.\n *\n * @param address - The address of the account.\n * @param opts - The options for exporting the account.\n * @param opts.withAppKeyOrigin - An optional string to export the account\n * for a specific app origin.\n * @returns The private key of the account.\n */\n async exportAccount(\n address: Hex,\n opts?: { withAppKeyOrigin: string },\n ): Promise<string> {\n const wallet = opts\n ? this.#getWalletForAccount(address, opts)\n : this.#getWalletForAccount(address);\n const { privateKey } = wallet;\n assert(\n privateKey instanceof Uint8Array,\n 'Expected private key to be of type Uint8Array',\n );\n return remove0x(bytesToHex(privateKey));\n }\n\n /**\n * Sign a transaction using the private key of the specified account.\n *\n * @param address - The address of the account.\n * @param tx - The transaction to sign.\n * @param opts - The options for signing the transaction.\n * @returns The signed transaction.\n */\n async signTransaction(\n address: Hex,\n tx: TypedTransaction,\n opts = {},\n ): Promise<TypedTransaction> {\n const privKey = this.#getPrivateKeyFor(address, opts);\n const signedTx = tx.sign(Buffer.from(privKey));\n // Newer versions of Ethereumjs-tx are immutable and return a new tx object\n return signedTx ?? tx;\n }\n\n /**\n * Sign a message using the private key of the specified account.\n *\n * @param address - The address of the account.\n * @param data - The data to sign.\n * @param opts - The options for signing the message.\n * @returns The signature of the message.\n */\n async signMessage(\n address: Hex,\n data: string,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n assertIsHexString(data);\n const message = remove0x(data);\n const privKey = this.#getPrivateKeyFor(address, opts);\n const msgSig = ecsign(Buffer.from(message, 'hex'), Buffer.from(privKey));\n const rawMsgSig = concatSig(\n Buffer.from(bigIntToBytes(msgSig.v)),\n Buffer.from(msgSig.r),\n Buffer.from(msgSig.s),\n );\n return rawMsgSig;\n }\n\n /**\n * Sign a personal message using the private key of the specified account.\n * This method is compatible with the `personal_sign` RPC method.\n *\n * @param address - The address of the account.\n * @param msgHex - The message to sign.\n * @param opts - The options for signing the message.\n * @returns The signature of the message.\n */\n async signPersonalMessage(\n address: Hex,\n msgHex: string,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n const privKey = this.#getPrivateKeyFor(address, opts);\n const privateKey = Buffer.from(privKey);\n return personalSign({ privateKey, data: msgHex });\n }\n\n /**\n * Decrypt an encrypted message using the private key of the specified account.\n * The message must be encrypted using the public key of the account.\n * This method is compatible with the `eth_decryptMessage` RPC method\n *\n * @param withAccount - The address of the account.\n * @param encryptedData - The encrypted data.\n * @returns The decrypted message.\n */\n async decryptMessage(\n withAccount: Hex,\n encryptedData: EthEncryptedData,\n ): Promise<string> {\n const wallet = this.#getWalletForAccount(withAccount);\n const { privateKey: privateKeyAsUint8Array } = wallet;\n assert(privateKeyAsUint8Array, 'Expected private key to be set');\n const privateKeyAsHex = Buffer.from(privateKeyAsUint8Array).toString('hex');\n return decrypt({ privateKey: privateKeyAsHex, encryptedData });\n }\n\n /**\n * Sign a typed message using the private key of the specified account.\n * This method is compatible with the `eth_signTypedData` RPC method.\n *\n * @param address - The address of the account.\n * @param data - The typed data to sign.\n * @param options - The options for signing the message.\n * @returns The signature of the message.\n */\n async signTypedData<\n Version extends SignTypedDataVersion,\n Types extends MessageTypes,\n Options extends { version?: Version },\n >(\n address: Hex,\n data: Version extends 'V1' ? TypedDataV1 : TypedMessage<Types>,\n options?: HDKeyringAccountSelectionOptions & Options,\n ): Promise<string> {\n let { version } = options ?? { version: SignTypedDataVersion.V1 };\n\n // Treat invalid versions as \"V1\"\n if (!version || !Object.keys(SignTypedDataVersion).includes(version)) {\n version = SignTypedDataVersion.V1;\n }\n\n const privateKey = this.#getPrivateKeyFor(address, options);\n return signTypedData({\n privateKey: Buffer.from(privateKey),\n data,\n version,\n });\n }\n\n /**\n * Sign an EIP-7702 authorization using the private key of the specified account.\n * This method is compatible with the EIP-7702 standard for enabling smart contract code for EOAs.\n *\n * @param withAccount - The address of the account.\n * @param authorization - The EIP-7702 authorization to sign.\n * @param opts - The options for selecting the account.\n * @returns The signature of the authorization.\n */\n async signEip7702Authorization(\n withAccount: Hex,\n authorization: EIP7702Authorization,\n opts?: HDKeyringAccountSelectionOptions,\n ): Promise<string> {\n const privateKey = this.#getPrivateKeyFor(withAccount, opts);\n return signEIP7702Authorization({\n privateKey: Buffer.from(privateKey),\n authorization,\n });\n }\n\n /**\n * Remove an account from the keyring.\n *\n * @param account - The address of the account to remove.\n */\n removeAccount(account: Hex): void {\n const address = this.#normalizeAddress(account);\n\n if (!this.#walletMap.has(address)) {\n throw new Error(`Address ${address} not found in this keyring`);\n }\n\n this.#walletMap.delete(address);\n }\n\n /**\n * Get the public key of the account to be used for encryption.\n *\n * @param withAccount - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns The public key of the account.\n */\n async getEncryptionPublicKey(\n withAccount: Hex,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n const privKey = this.#getPrivateKeyFor(withAccount, opts);\n const publicKey = getEncryptionPublicKey(remove0x(bytesToHex(privKey)));\n return publicKey;\n }\n\n /**\n * Convert a Uint8Array mnemonic to a secret recovery phrase,\n * using the english wordlist.\n *\n * @param mnemonic - The Uint8Array mnemonic.\n * @returns The string mnemonic.\n */\n #uint8ArrayToString(mnemonic: Uint8Array): string {\n const recoveredIndices = Array.from(\n new Uint16Array(new Uint8Array(mnemonic).buffer),\n );\n return recoveredIndices.map((i) => wordlist[i]).join(' ');\n }\n\n /**\n * Convert a secret recovery phrase to a Uint8Array mnemonic,\n * using the english wordlist.\n *\n * @param mnemonic - The string mnemonic.\n * @returns The Uint8Array mnemonic.\n */\n #stringToUint8Array(mnemonic: string): Uint8Array {\n const indices = mnemonic.split(' ').map((word) => wordlist.indexOf(word));\n return new Uint8Array(new Uint16Array(indices).buffer);\n }\n\n /**\n * Convert a mnemonic to a Uint8Array mnemonic.\n *\n * @param mnemonic - The mnemonic seed phrase.\n * @returns The Uint8Array mnemonic.\n */\n #mnemonicToUint8Array(\n mnemonic: Buffer | SerializedBuffer | string | Uint8Array | number[],\n ): Uint8Array {\n let mnemonicData: unknown = mnemonic;\n // When using `Buffer.toJSON()`, the Buffer is serialized into an object\n // with the structure `{ type: 'Buffer', data: [...] }`\n if (isSerializedBuffer(mnemonic)) {\n mnemonicData = mnemonic.data;\n }\n\n if (\n // this block is for backwards compatibility with vaults that were previously stored as buffers, number arrays or plain text strings\n typeof mnemonicData === 'string' ||\n Buffer.isBuffer(mnemonicData) ||\n Array.isArray(mnemonicData)\n ) {\n let mnemonicAsString: string;\n if (Array.isArray(mnemonicData)) {\n mnemonicAsString = Buffer.from(mnemonicData).toString();\n } else if (Buffer.isBuffer(mnemonicData)) {\n mnemonicAsString = mnemonicData.toString();\n } else {\n mnemonicAsString = mnemonicData;\n }\n return this.#stringToUint8Array(mnemonicAsString);\n } else if (\n mnemonicData instanceof Object &&\n !(mnemonicData instanceof Uint8Array)\n ) {\n // when encrypted/decrypted the Uint8Array becomes a js object we need to cast back to a Uint8Array\n return Uint8Array.from(Object.values(mnemonicData));\n }\n\n assert(mnemonicData instanceof Uint8Array, 'Expected Uint8Array mnemonic');\n return mnemonicData;\n }\n\n /**\n * Get the private key for the specified account.\n *\n * @param address - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns The private key of the account.\n */\n #getPrivateKeyFor(\n address: Hex,\n opts?: HDKeyringAccountSelectionOptions,\n ): Uint8Array | Buffer {\n if (!address) {\n throw new Error('Must specify address.');\n }\n const wallet = this.#getWalletForAccount(address, opts);\n assert(wallet.privateKey, 'Missing private key');\n return wallet.privateKey;\n }\n\n /**\n * Get the wallet for the specified account.\n *\n * @param account - The address of the account.\n * @returns The wallet for the account as HDKey.\n */\n #getWalletForAccount(account: Hex): HDKey;\n\n /**\n * Get the wallet for the specified account and app origin.\n *\n * @param account - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns A key pair representing the wallet.\n */\n #getWalletForAccount(\n accounts: Hex,\n opts: { withAppKeyOrigin: string },\n ): { privateKey: Buffer; publicKey: Buffer };\n\n /**\n * Get the wallet for the specified account with optional\n * additional options.\n *\n * @param account - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns A key pair representing the wallet.\n */\n #getWalletForAccount(\n account: Hex,\n opts?: HDKeyringAccountSelectionOptions,\n ): HDKey | { privateKey: Buffer; publicKey: Buffer };\n\n #getWalletForAccount(\n account: Hex,\n { withAppKeyOrigin }: HDKeyringAccountSelectionOptions = {},\n ): HDKey | { privateKey: Buffer; publicKey: Buffer } {\n const address = this.#normalizeAddress(account);\n const walletData = this.#walletMap.get(address);\n if (!walletData) {\n throw new Error('HD Keyring - Unable to find matching address.');\n }\n\n if (withAppKeyOrigin) {\n const { privateKey } = walletData.hdKey;\n assert(privateKey, 'Expected private key to be set');\n const appKeyOriginBuffer = Buffer.from(withAppKeyOrigin, 'utf8');\n const appKeyBuffer = Buffer.concat([privateKey, appKeyOriginBuffer]);\n const appKeyPrivateKey = Buffer.from(keccak256(appKeyBuffer));\n const appKeyPublicKey = Buffer.from(privateToPublic(appKeyPrivateKey));\n return { privateKey: appKeyPrivateKey, publicKey: appKeyPublicKey };\n }\n\n return walletData.hdKey;\n }\n\n /**\n * Sets appropriate properties for the keyring based on the given\n * BIP39-compliant mnemonic.\n *\n * @param mnemonic - A seed phrase represented\n * as a string, an array of UTF-8 bytes, or a Buffer. Mnemonic input\n * passed as type buffer or array of UTF-8 bytes must be NFKD normalized.\n */\n async #initFromMnemonic(\n mnemonic: string | number[] | SerializedBuffer | Buffer | Uint8Array,\n ): Promise<void> {\n if (this.root) {\n throw new Error(\n 'Eth-Hd-Keyring: Secret recovery phrase already provided',\n );\n }\n\n this.mnemonic = this.#mnemonicToUint8Array(mnemonic);\n\n this.seed = await mnemonicToSeed(\n this.mnemonic,\n '', // No passphrase\n this.#cryptographicFunctions,\n );\n this.hdWallet = HDKey.fromMasterSeed(this.seed);\n this.root = this.hdWallet.derive(this.hdPath);\n }\n\n /**\n * Get the address of the account from the public key.\n *\n * @param publicKey - The public key of the account.\n * @returns The address of the account.\n */\n #addressFromPublicKey(publicKey: Uint8Array): Hex {\n return add0x(\n bytesToHex(publicToAddress(Buffer.from(publicKey), true)).toLowerCase(),\n );\n }\n\n /**\n * Normalize an address to a lower-cased '0x'-prefixed hex string.\n *\n * @param address - The address to normalize.\n * @returns The normalized address.\n */\n #normalizeAddress(address: string): Hex {\n const normalized = normalize(address);\n assert(normalized, 'Expected address to be set');\n return add0x(normalized);\n }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sB,oBAAoB,CAAC,CAAC;IAChD,IAAI,CAAC,QAAQ,GAAG,oBAAoB,CAAC;IAErC,IAAI,CAAC,IAAI,GAAG,MAAM,IAAA,yBAAc,EAC9B,IAAI,CAAC,QAAQ,EACb,EAAE,EAAE,gBAAgB;IACpB,uBAAA,IAAI,yCAAwB,CAC7B,CAAC;IACF,IAAI,CAAC,QAAQ,GAAG,aAAK,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAChD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAChD,CAAC,6EAQqB,SAAqB;IACzC,OAAO,IAAA,aAAK,EACV,IAAA,kBAAU,EAAC,IAAA,sBAAe,EAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,WAAW,EAAE,CACxE,CAAC;AACJ,CAAC,qEAQiB,OAAe;IAC/B,MAAM,UAAU,GAAG,IAAA,wBAAS,EAAC,OAAO,CAAC,CAAC;IACtC,IAAA,cAAM,EAAC,UAAU,EAAE,4BAA4B,CAAC,CAAC;IACjD,OAAO,IAAA,aAAK,EAAC,UAAU,CAAC,CAAC;AAC3B,CAAC,2EASoB,QAAoB;IACvC,MAAM,cAAc,GAAG,uBAAA,IAAI,2DAAoB,MAAxB,IAAI,EAAqB,QAAQ,CAAC,CAAC;IAC1D,IAAI,CAAC,IAAA,8BAAgB,EAAC,cAAc,EAAE,kBAAQ,CAAC,EAAE,CAAC;QAChD,MAAM,IAAI,KAAK,CACb,yDAAyD,CAC1D,CAAC;IACJ,CAAC;AACH,CAAC;AAviBM,cAAI,GAAW,IAAI,AAAf,CAAgB","sourcesContent":["import type { TypedTransaction } from '@ethereumjs/tx';\nimport { privateToPublic, publicToAddress, ecsign } from '@ethereumjs/util';\nimport {\n concatSig,\n decrypt,\n type EIP7702Authorization,\n type EthEncryptedData,\n getEncryptionPublicKey,\n type MessageTypes,\n normalize,\n personalSign,\n signEIP7702Authorization,\n signTypedData,\n SignTypedDataVersion,\n type TypedDataV1,\n type TypedMessage,\n} from '@metamask/eth-sig-util';\nimport {\n type CryptographicFunctions,\n mnemonicToSeed,\n} from '@metamask/key-tree';\nimport type { Keyring } from '@metamask/keyring-utils';\nimport { generateMnemonic, validateMnemonic } from '@metamask/scure-bip39';\nimport { wordlist } from '@metamask/scure-bip39/dist/wordlists/english';\nimport {\n add0x,\n assert,\n assertIsHexString,\n bigIntToBytes,\n bytesToHex,\n type Hex,\n remove0x,\n} from '@metamask/utils';\nimport { HDKey } from 'ethereum-cryptography/hdkey';\nimport { keccak256 } from 'ethereum-cryptography/keccak';\n\n// Options:\nconst hdPathString = `m/44'/60'/0'/0`;\nconst type = 'HD Key Tree';\n\ntype Mnemonic = string | number[] | SerializedBuffer | Buffer | Uint8Array;\n\nexport type HDKeyringOptions = {\n cryptographicFunctions?: CryptographicFunctions;\n};\n\n/**\n * The serialized state of an `HDKeyring` instance.\n *\n * @property mnemonic - The mnemonic seed phrase as an array of numbers.\n * @property numberOfAccounts - The number of accounts in the keyring.\n * @property hdPath - The HD path used to derive accounts.\n */\nexport type SerializedHDKeyringState = {\n mnemonic: number[];\n numberOfAccounts: number;\n hdPath: string;\n};\n\n/**\n * An object that can be passed to the Keyring.deserialize method to initialize\n * an `HDKeyring` instance.\n *\n * @property mnemonic - The mnemonic seed phrase as an array of numbers.\n * @property numberOfAccounts - The number of accounts in the keyring.\n * @property hdPath - The HD path used to derive accounts.\n */\nexport type DeserializableHDKeyringState = Omit<\n SerializedHDKeyringState,\n 'mnemonic'\n> & {\n mnemonic: number[] | SerializedBuffer | string;\n};\n\n/**\n * Options for selecting an account from an `HDKeyring` instance.\n *\n * @property withAppKeyOrigin - The origin of the app requesting the account.\n */\nexport type HDKeyringAccountSelectionOptions = {\n withAppKeyOrigin?: string;\n};\n\ntype SerializedBuffer = ReturnType<Buffer['toJSON']>;\n\n/**\n * Wallet storage object that contains both the HDKey and pre-computed address.\n */\ntype WalletData = {\n hdKey: HDKey;\n address: Hex;\n};\n\n/**\n * Checks if the given value is a valid serialized Buffer compatible with\n * the return type of `Buffer.toJSON`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid serialized buffer, `false` otherwise.\n */\nfunction isSerializedBuffer(value: unknown): value is SerializedBuffer {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'type' in value &&\n value.type === 'Buffer' &&\n 'data' in value &&\n Array.isArray(value.data)\n );\n}\n\nexport class HdKeyring implements Keyring {\n static type: string = type;\n\n type: string = type;\n\n mnemonic?: Uint8Array | null;\n\n seed?: Uint8Array | null;\n\n root?: HDKey | null;\n\n hdWallet?: HDKey;\n\n hdPath: string = hdPathString;\n\n readonly #walletMap = new Map<Hex, WalletData>();\n\n readonly #cryptographicFunctions?: CryptographicFunctions;\n\n constructor(opts: HDKeyringOptions = {}) {\n // Cryptographic functions to be used by `@metamask/key-tree`. It will use built-in implementations if not provided here.\n this.#cryptographicFunctions = opts.cryptographicFunctions;\n }\n\n /**\n * Initialize the keyring with a random mnemonic.\n *\n * @returns A promise that resolves when the process is complete.\n */\n async generateRandomMnemonic(): Promise<void> {\n await this.#initFromMnemonic(generateMnemonic(wordlist));\n }\n\n /**\n * Return the serialized state of the keyring.\n *\n * @returns The serialized state of the keyring.\n */\n async serialize(): Promise<SerializedHDKeyringState> {\n let mnemonic: number[] = [];\n\n if (this.mnemonic) {\n const mnemonicAsString = this.#uint8ArrayToString(this.mnemonic);\n mnemonic = Array.from(new TextEncoder().encode(mnemonicAsString));\n }\n\n return {\n mnemonic,\n numberOfAccounts: this.#walletMap.size,\n hdPath: this.hdPath,\n };\n }\n\n /**\n * Initialize the keyring with the given serialized state.\n *\n * @param opts - The serialized state of the keyring.\n * @returns An empty array.\n */\n async deserialize(\n opts: Partial<DeserializableHDKeyringState>,\n ): Promise<void> {\n if (opts.numberOfAccounts && !opts.mnemonic) {\n throw new Error(\n 'Eth-Hd-Keyring: Deserialize method cannot be called with an opts value for numberOfAccounts and no menmonic',\n );\n }\n\n if (this.root) {\n throw new Error(\n 'Eth-Hd-Keyring: Secret recovery phrase already provided',\n );\n }\n\n this.#walletMap.clear();\n this.mnemonic = null;\n this.seed = null;\n this.root = null;\n this.hdPath = opts.hdPath ?? hdPathString;\n\n if (opts.mnemonic) {\n await this.#initFromMnemonic(opts.mnemonic);\n }\n\n if (opts.numberOfAccounts) {\n await this.addAccounts(opts.numberOfAccounts);\n }\n }\n\n /**\n * Add new accounts to the keyring. The accounts will be derived\n * sequentially from the root HD wallet, using increasing indices.\n *\n * @param numberOfAccounts - The number of accounts to add.\n * @returns The addresses of the new accounts.\n */\n async addAccounts(numberOfAccounts = 1): Promise<Hex[]> {\n if (!this.root) {\n throw new Error('Eth-Hd-Keyring: No secret recovery phrase provided');\n }\n\n const oldLen = this.#walletMap.size;\n const newAddresses: Hex[] = [];\n for (let i = oldLen; i < numberOfAccounts + oldLen; i++) {\n const hdKey = this.root.deriveChild(i);\n assert(hdKey.publicKey, 'Expected public key to be set');\n\n const address = this.#addressFromPublicKey(hdKey.publicKey);\n const walletData: WalletData = {\n hdKey,\n address,\n };\n\n this.#walletMap.set(address, walletData);\n newAddresses.push(address);\n }\n\n return Promise.resolve(newAddresses);\n }\n\n /**\n * Get the addresses of all accounts in the keyring.\n *\n * @returns The addresses of all accounts in the keyring.\n */\n async getAccounts(): Promise<Hex[]> {\n return Array.from(this.#walletMap.keys());\n }\n\n /**\n * Get the public address of the account for the given app key origin.\n *\n * @param address - The address of the account.\n * @param origin - The origin of the app requesting the account.\n * @returns The public address of the account.\n */\n async getAppKeyAddress(address: Hex, origin: string): Promise<Hex> {\n if (!origin || typeof origin !== 'string') {\n throw new Error(`'origin' must be a non-empty string`);\n }\n const wallet = this.#getWalletForAccount(address, {\n withAppKeyOrigin: origin,\n });\n assert(wallet.publicKey, 'Expected public key to be set');\n const appKeyAddress = this.#normalizeAddress(\n bytesToHex(publicToAddress(wallet.publicKey)),\n );\n return appKeyAddress;\n }\n\n /**\n * Export the private key for a specific account.\n *\n * @param address - The address of the account.\n * @param opts - The options for exporting the account.\n * @param opts.withAppKeyOrigin - An optional string to export the account\n * for a specific app origin.\n * @returns The private key of the account.\n */\n async exportAccount(\n address: Hex,\n opts?: { withAppKeyOrigin: string },\n ): Promise<string> {\n const wallet = opts\n ? this.#getWalletForAccount(address, opts)\n : this.#getWalletForAccount(address);\n const { privateKey } = wallet;\n assert(\n privateKey instanceof Uint8Array,\n 'Expected private key to be of type Uint8Array',\n );\n return remove0x(bytesToHex(privateKey));\n }\n\n /**\n * Sign a transaction using the private key of the specified account.\n *\n * @param address - The address of the account.\n * @param tx - The transaction to sign.\n * @param opts - The options for signing the transaction.\n * @returns The signed transaction.\n */\n async signTransaction(\n address: Hex,\n tx: TypedTransaction,\n opts = {},\n ): Promise<TypedTransaction> {\n const privKey = this.#getPrivateKeyFor(address, opts);\n const signedTx = tx.sign(Buffer.from(privKey));\n // Newer versions of Ethereumjs-tx are immutable and return a new tx object\n return signedTx ?? tx;\n }\n\n /**\n * Sign a message using the private key of the specified account.\n *\n * @param address - The address of the account.\n * @param data - The data to sign.\n * @param opts - The options for signing the message.\n * @returns The signature of the message.\n */\n async signMessage(\n address: Hex,\n data: string,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n assertIsHexString(data);\n const message = remove0x(data);\n const privKey = this.#getPrivateKeyFor(address, opts);\n const msgSig = ecsign(Buffer.from(message, 'hex'), Buffer.from(privKey));\n const rawMsgSig = concatSig(\n Buffer.from(bigIntToBytes(msgSig.v)),\n Buffer.from(msgSig.r),\n Buffer.from(msgSig.s),\n );\n return rawMsgSig;\n }\n\n /**\n * Sign a personal message using the private key of the specified account.\n * This method is compatible with the `personal_sign` RPC method.\n *\n * @param address - The address of the account.\n * @param msgHex - The message to sign.\n * @param opts - The options for signing the message.\n * @returns The signature of the message.\n */\n async signPersonalMessage(\n address: Hex,\n msgHex: string,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n const privKey = this.#getPrivateKeyFor(address, opts);\n const privateKey = Buffer.from(privKey);\n return personalSign({ privateKey, data: msgHex });\n }\n\n /**\n * Decrypt an encrypted message using the private key of the specified account.\n * The message must be encrypted using the public key of the account.\n * This method is compatible with the `eth_decryptMessage` RPC method\n *\n * @param withAccount - The address of the account.\n * @param encryptedData - The encrypted data.\n * @returns The decrypted message.\n */\n async decryptMessage(\n withAccount: Hex,\n encryptedData: EthEncryptedData,\n ): Promise<string> {\n const wallet = this.#getWalletForAccount(withAccount);\n const { privateKey: privateKeyAsUint8Array } = wallet;\n assert(privateKeyAsUint8Array, 'Expected private key to be set');\n const privateKeyAsHex = Buffer.from(privateKeyAsUint8Array).toString('hex');\n return decrypt({ privateKey: privateKeyAsHex, encryptedData });\n }\n\n /**\n * Sign a typed message using the private key of the specified account.\n * This method is compatible with the `eth_signTypedData` RPC method.\n *\n * @param address - The address of the account.\n * @param data - The typed data to sign.\n * @param options - The options for signing the message.\n * @returns The signature of the message.\n */\n async signTypedData<\n Version extends SignTypedDataVersion,\n Types extends MessageTypes,\n Options extends { version?: Version },\n >(\n address: Hex,\n data: Version extends 'V1' ? TypedDataV1 : TypedMessage<Types>,\n options?: HDKeyringAccountSelectionOptions & Options,\n ): Promise<string> {\n let { version } = options ?? { version: SignTypedDataVersion.V1 };\n\n // Treat invalid versions as \"V1\"\n if (!version || !Object.keys(SignTypedDataVersion).includes(version)) {\n version = SignTypedDataVersion.V1;\n }\n\n const privateKey = this.#getPrivateKeyFor(address, options);\n return signTypedData({\n privateKey: Buffer.from(privateKey),\n data,\n version,\n });\n }\n\n /**\n * Sign an EIP-7702 authorization using the private key of the specified account.\n * This method is compatible with the EIP-7702 standard for enabling smart contract code for EOAs.\n *\n * @param withAccount - The address of the account.\n * @param authorization - The EIP-7702 authorization to sign.\n * @param opts - The options for selecting the account.\n * @returns The signature of the authorization.\n */\n async signEip7702Authorization(\n withAccount: Hex,\n authorization: EIP7702Authorization,\n opts?: HDKeyringAccountSelectionOptions,\n ): Promise<string> {\n const privateKey = this.#getPrivateKeyFor(withAccount, opts);\n return signEIP7702Authorization({\n privateKey: Buffer.from(privateKey),\n authorization,\n });\n }\n\n /**\n * Remove an account from the keyring.\n *\n * @param account - The address of the account to remove.\n */\n removeAccount(account: Hex): void {\n const address = this.#normalizeAddress(account);\n\n if (!this.#walletMap.has(address)) {\n throw new Error(`Address ${address} not found in this keyring`);\n }\n\n this.#walletMap.delete(address);\n }\n\n /**\n * Get the public key of the account to be used for encryption.\n *\n * @param withAccount - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns The public key of the account.\n */\n async getEncryptionPublicKey(\n withAccount: Hex,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n const privKey = this.#getPrivateKeyFor(withAccount, opts);\n const publicKey = getEncryptionPublicKey(remove0x(bytesToHex(privKey)));\n return publicKey;\n }\n\n /**\n * Convert a Uint8Array mnemonic to a secret recovery phrase,\n * using the english wordlist.\n *\n * @param mnemonic - The Uint8Array mnemonic.\n * @returns The string mnemonic.\n */\n #uint8ArrayToString(mnemonic: Uint8Array): string {\n const recoveredIndices = Array.from(\n new Uint16Array(new Uint8Array(mnemonic).buffer),\n );\n return recoveredIndices.map((i) => wordlist[i]).join(' ');\n }\n\n /**\n * Convert a secret recovery phrase to a Uint8Array mnemonic,\n * using the english wordlist.\n *\n * @param mnemonic - The string mnemonic.\n * @returns The Uint8Array mnemonic.\n */\n #stringToUint8Array(mnemonic: string): Uint8Array {\n const indices = mnemonic.split(' ').map((word) => wordlist.indexOf(word));\n return new Uint8Array(new Uint16Array(indices).buffer);\n }\n\n /**\n * Convert a mnemonic to a Uint8Array mnemonic.\n *\n * @param mnemonic - The mnemonic seed phrase.\n * @returns The Uint8Array mnemonic.\n */\n #mnemonicToUint8Array(mnemonic: Mnemonic): Uint8Array {\n let mnemonicData: unknown = mnemonic;\n // When using `Buffer.toJSON()`, the Buffer is serialized into an object\n // with the structure `{ type: 'Buffer', data: [...] }`\n if (isSerializedBuffer(mnemonic)) {\n mnemonicData = mnemonic.data;\n }\n\n if (\n // this block is for backwards compatibility with vaults that were previously stored as buffers, number arrays or plain text strings\n typeof mnemonicData === 'string' ||\n Buffer.isBuffer(mnemonicData) ||\n Array.isArray(mnemonicData)\n ) {\n let mnemonicAsString: string;\n if (Array.isArray(mnemonicData)) {\n mnemonicAsString = Buffer.from(mnemonicData).toString();\n } else if (Buffer.isBuffer(mnemonicData)) {\n mnemonicAsString = mnemonicData.toString();\n } else {\n mnemonicAsString = mnemonicData;\n }\n return this.#stringToUint8Array(mnemonicAsString);\n } else if (\n mnemonicData instanceof Object &&\n !(mnemonicData instanceof Uint8Array)\n ) {\n // when encrypted/decrypted the Uint8Array becomes a js object we need to cast back to a Uint8Array\n return Uint8Array.from(Object.values(mnemonicData));\n }\n\n assert(mnemonicData instanceof Uint8Array, 'Expected Uint8Array mnemonic');\n return mnemonicData;\n }\n\n /**\n * Get the private key for the specified account.\n *\n * @param address - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns The private key of the account.\n */\n #getPrivateKeyFor(\n address: Hex,\n opts?: HDKeyringAccountSelectionOptions,\n ): Uint8Array | Buffer {\n if (!address) {\n throw new Error('Must specify address.');\n }\n const wallet = this.#getWalletForAccount(address, opts);\n assert(wallet.privateKey, 'Missing private key');\n return wallet.privateKey;\n }\n\n /**\n * Get the wallet for the specified account.\n *\n * @param account - The address of the account.\n * @returns The wallet for the account as HDKey.\n */\n #getWalletForAccount(account: Hex): HDKey;\n\n /**\n * Get the wallet for the specified account and app origin.\n *\n * @param account - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns A key pair representing the wallet.\n */\n #getWalletForAccount(\n accounts: Hex,\n opts: { withAppKeyOrigin: string },\n ): { privateKey: Buffer; publicKey: Buffer };\n\n /**\n * Get the wallet for the specified account with optional\n * additional options.\n *\n * @param account - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns A key pair representing the wallet.\n */\n #getWalletForAccount(\n account: Hex,\n opts?: HDKeyringAccountSelectionOptions,\n ): HDKey | { privateKey: Buffer; publicKey: Buffer };\n\n #getWalletForAccount(\n account: Hex,\n { withAppKeyOrigin }: HDKeyringAccountSelectionOptions = {},\n ): HDKey | { privateKey: Buffer; publicKey: Buffer } {\n const address = this.#normalizeAddress(account);\n const walletData = this.#walletMap.get(address);\n if (!walletData) {\n throw new Error('HD Keyring - Unable to find matching address.');\n }\n\n if (withAppKeyOrigin) {\n const { privateKey } = walletData.hdKey;\n assert(privateKey, 'Expected private key to be set');\n const appKeyOriginBuffer = Buffer.from(withAppKeyOrigin, 'utf8');\n const appKeyBuffer = Buffer.concat([privateKey, appKeyOriginBuffer]);\n const appKeyPrivateKey = Buffer.from(keccak256(appKeyBuffer));\n const appKeyPublicKey = Buffer.from(privateToPublic(appKeyPrivateKey));\n return { privateKey: appKeyPrivateKey, publicKey: appKeyPublicKey };\n }\n\n return walletData.hdKey;\n }\n\n /**\n * Sets appropriate properties for the keyring based on the given\n * BIP39-compliant mnemonic.\n *\n * @param mnemonic - A seed phrase represented\n * as a string, an array of UTF-8 bytes, or a Buffer. Mnemonic input\n * passed as type buffer or array of UTF-8 bytes must be NFKD normalized.\n */\n async #initFromMnemonic(mnemonic: Mnemonic): Promise<void> {\n if (this.root) {\n throw new Error(\n 'Eth-Hd-Keyring: Secret recovery phrase already provided',\n );\n }\n\n // Convert and validate before assigning to instance property\n // to avoid inconsistent state if validation fails\n const mnemonicAsUint8Array = this.#mnemonicToUint8Array(mnemonic);\n this.#assertValidMnemonic(mnemonicAsUint8Array);\n this.mnemonic = mnemonicAsUint8Array;\n\n this.seed = await mnemonicToSeed(\n this.mnemonic,\n '', // No passphrase\n this.#cryptographicFunctions,\n );\n this.hdWallet = HDKey.fromMasterSeed(this.seed);\n this.root = this.hdWallet.derive(this.hdPath);\n }\n\n /**\n * Get the address of the account from the public key.\n *\n * @param publicKey - The public key of the account.\n * @returns The address of the account.\n */\n #addressFromPublicKey(publicKey: Uint8Array): Hex {\n return add0x(\n bytesToHex(publicToAddress(Buffer.from(publicKey), true)).toLowerCase(),\n );\n }\n\n /**\n * Normalize an address to a lower-cased '0x'-prefixed hex string.\n *\n * @param address - The address to normalize.\n * @returns The normalized address.\n */\n #normalizeAddress(address: string): Hex {\n const normalized = normalize(address);\n assert(normalized, 'Expected address to be set');\n return add0x(normalized);\n }\n\n /**\n * Assert that the mnemonic seed phrase is valid.\n * Throws an error if the mnemonic is not a valid BIP39 phrase.\n *\n * @param mnemonic - The mnemonic seed phrase to validate (as Uint8Array).\n * @throws If the mnemonic is not a valid BIP39 secret recovery phrase.\n */\n #assertValidMnemonic(mnemonic: Uint8Array): void {\n const mnemonicString = this.#uint8ArrayToString(mnemonic);\n if (!validateMnemonic(mnemonicString, wordlist)) {\n throw new Error(\n 'Eth-Hd-Keyring: Invalid secret recovery phrase provided',\n );\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"hd-keyring.d.cts","sourceRoot":"","sources":["../src/hd-keyring.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,uBAAuB;AAEvD,OAAO,EAGL,KAAK,oBAAoB,EACzB,KAAK,gBAAgB,EAErB,KAAK,YAAY,EAKjB,oBAAoB,EACpB,KAAK,WAAW,EAChB,KAAK,YAAY,EAClB,+BAA+B;AAChC,OAAO,EACL,KAAK,sBAAsB,EAE5B,2BAA2B;AAC5B,OAAO,KAAK,EAAE,OAAO,EAAE,gCAAgC;AAGvD,OAAO,EAML,KAAK,GAAG,EAET,wBAAwB;AACzB,OAAO,EAAE,KAAK,EAAE,oCAAoC;AAOpD,MAAM,MAAM,gBAAgB,GAAG;IAC7B,sBAAsB,CAAC,EAAE,sBAAsB,CAAC;CACjD,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,wBAAwB,GAAG;IACrC,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,gBAAgB,EAAE,MAAM,CAAC;IACzB,MAAM,EAAE,MA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,GACR,OAAO,CAAC,gBAAgB,CAAC;IAO5B;;;;;;;OAOG;IACG,WAAW,CACf,OAAO,EAAE,GAAG,EACZ,IAAI,EAAE,MAAM,EACZ,IAAI,GAAE,gCAAqC,GAC1C,OAAO,CAAC,MAAM,CAAC;IAalB;;;;;;;;OAQG;IACG,mBAAmB,CACvB,OAAO,EAAE,GAAG,EACZ,MAAM,EAAE,MAAM,EACd,IAAI,GAAE,gCAAqC,GAC1C,OAAO,CAAC,MAAM,CAAC;IAMlB;;;;;;;;OAQG;IACG,cAAc,CAClB,WAAW,EAAE,GAAG,EAChB,aAAa,EAAE,gBAAgB,GAC9B,OAAO,CAAC,MAAM,CAAC;IAQlB;;;;;;;;OAQG;IACG,aAAa,CACjB,OAAO,SAAS,oBAAoB,EACpC,KAAK,SAAS,YAAY,EAC1B,OAAO,SAAS;QAAE,OAAO,CAAC,EAAE,OAAO,CAAA;KAAE,EAErC,OAAO,EAAE,GAAG,EACZ,IAAI,EAAE,OAAO,SAAS,IAAI,GAAG,WAAW,GAAG,YAAY,CAAC,KAAK,CAAC,EAC9D,OAAO,CAAC,EAAE,gCAAgC,GAAG,OAAO,GACnD,OAAO,CAAC,MAAM,CAAC;IAgBlB;;;;;;;;OAQG;IACG,wBAAwB,CAC5B,WAAW,EAAE,GAAG,EAChB,aAAa,EAAE,oBAAoB,EACnC,IAAI,CAAC,EAAE,gCAAgC,GACtC,OAAO,CAAC,MAAM,CAAC;IAQlB;;;;OAIG;IACH,aAAa,CAAC,OAAO,EAAE,GAAG,GAAG,IAAI;IAUjC;;;;;;OAMG;IACG,sBAAsB,CAC1B,WAAW,EAAE,GAAG,EAChB,IAAI,GAAE,gCAAqC,GAC1C,OAAO,CAAC,MAAM,CAAC;CAyNnB"}
@@ -9,11 +9,11 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _HdKeyring_instances, _HdKeyring_walletMap, _HdKeyring_cryptographicFunctions, _HdKeyring_uint8ArrayToString, _HdKeyring_stringToUint8Array, _HdKeyring_mnemonicToUint8Array, _HdKeyring_getPrivateKeyFor, _HdKeyring_getWalletForAccount, _HdKeyring_initFromMnemonic, _HdKeyring_addressFromPublicKey, _HdKeyring_normalizeAddress;
12
+ var _HdKeyring_instances, _HdKeyring_walletMap, _HdKeyring_cryptographicFunctions, _HdKeyring_uint8ArrayToString, _HdKeyring_stringToUint8Array, _HdKeyring_mnemonicToUint8Array, _HdKeyring_getPrivateKeyFor, _HdKeyring_getWalletForAccount, _HdKeyring_initFromMnemonic, _HdKeyring_addressFromPublicKey, _HdKeyring_normalizeAddress, _HdKeyring_assertValidMnemonic;
13
13
  import { privateToPublic, publicToAddress, ecsign } from "@ethereumjs/util";
14
14
  import { concatSig, decrypt, getEncryptionPublicKey, normalize, personalSign, signEIP7702Authorization, signTypedData, SignTypedDataVersion } from "@metamask/eth-sig-util";
15
15
  import { mnemonicToSeed } from "@metamask/key-tree";
16
- import { generateMnemonic } from "@metamask/scure-bip39";
16
+ import { generateMnemonic, validateMnemonic } from "@metamask/scure-bip39";
17
17
  import { wordlist } from "@metamask/scure-bip39/dist/wordlists/english.js";
18
18
  import { add0x, assert, assertIsHexString, bigIntToBytes, bytesToHex, remove0x } from "@metamask/utils";
19
19
  import { HDKey } from "ethereum-cryptography/hdkey";
@@ -361,7 +361,11 @@ async function _HdKeyring_initFromMnemonic(mnemonic) {
361
361
  if (this.root) {
362
362
  throw new Error('Eth-Hd-Keyring: Secret recovery phrase already provided');
363
363
  }
364
- this.mnemonic = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_mnemonicToUint8Array).call(this, mnemonic);
364
+ // Convert and validate before assigning to instance property
365
+ // to avoid inconsistent state if validation fails
366
+ const mnemonicAsUint8Array = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_mnemonicToUint8Array).call(this, mnemonic);
367
+ __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_assertValidMnemonic).call(this, mnemonicAsUint8Array);
368
+ this.mnemonic = mnemonicAsUint8Array;
365
369
  this.seed = await mnemonicToSeed(this.mnemonic, '', // No passphrase
366
370
  __classPrivateFieldGet(this, _HdKeyring_cryptographicFunctions, "f"));
367
371
  this.hdWallet = HDKey.fromMasterSeed(this.seed);
@@ -372,6 +376,11 @@ async function _HdKeyring_initFromMnemonic(mnemonic) {
372
376
  const normalized = normalize(address);
373
377
  assert(normalized, 'Expected address to be set');
374
378
  return add0x(normalized);
379
+ }, _HdKeyring_assertValidMnemonic = function _HdKeyring_assertValidMnemonic(mnemonic) {
380
+ const mnemonicString = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_uint8ArrayToString).call(this, mnemonic);
381
+ if (!validateMnemonic(mnemonicString, wordlist)) {
382
+ throw new Error('Eth-Hd-Keyring: Invalid secret recovery phrase provided');
383
+ }
375
384
  };
376
385
  HdKeyring.type = type;
377
386
  //# sourceMappingURL=hd-keyring.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"hd-keyring.mjs","sourceRoot":"","sources":["../src/hd-keyring.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,EAAE,yBAAyB;AAC5E,OAAO,EACL,SAAS,EACT,OAAO,EAGP,sBAAsB,EAEtB,SAAS,EACT,YAAY,EACZ,wBAAwB,EACxB,aAAa,EACb,oBAAoB,EAGrB,+BAA+B;AAChC,OAAO,EAEL,cAAc,EACf,2BAA2B;AAE5B,OAAO,EAAE,gBAAgB,EAAE,8BAA8B;AACzD,OAAO,EAAE,QAAQ,EAAE,wDAAqD;AACxE,OAAO,EACL,KAAK,EACL,MAAM,EACN,iBAAiB,EACjB,aAAa,EACb,UAAU,EAEV,QAAQ,EACT,wBAAwB;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AI,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,WAAW,EAAE,CACxE,CAAC;AACJ,CAAC,qEAQiB,OAAe;IAC/B,MAAM,UAAU,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;IACtC,MAAM,CAAC,UAAU,EAAE,4BAA4B,CAAC,CAAC;IACjD,OAAO,KAAK,CAAC,UAAU,CAAC,CAAC;AAC3B,CAAC;AAvhBM,cAAI,GAAW,IAAI,AAAf,CAAgB","sourcesContent":["import type { TypedTransaction } from '@ethereumjs/tx';\nimport { privateToPublic, publicToAddress, ecsign } from '@ethereumjs/util';\nimport {\n concatSig,\n decrypt,\n type EIP7702Authorization,\n type EthEncryptedData,\n getEncryptionPublicKey,\n type MessageTypes,\n normalize,\n personalSign,\n signEIP7702Authorization,\n signTypedData,\n SignTypedDataVersion,\n type TypedDataV1,\n type TypedMessage,\n} from '@metamask/eth-sig-util';\nimport {\n type CryptographicFunctions,\n mnemonicToSeed,\n} from '@metamask/key-tree';\nimport type { Keyring } from '@metamask/keyring-utils';\nimport { generateMnemonic } from '@metamask/scure-bip39';\nimport { wordlist } from '@metamask/scure-bip39/dist/wordlists/english';\nimport {\n add0x,\n assert,\n assertIsHexString,\n bigIntToBytes,\n bytesToHex,\n type Hex,\n remove0x,\n} from '@metamask/utils';\nimport { HDKey } from 'ethereum-cryptography/hdkey';\nimport { keccak256 } from 'ethereum-cryptography/keccak';\n\n// Options:\nconst hdPathString = `m/44'/60'/0'/0`;\nconst type = 'HD Key Tree';\n\nexport type HDKeyringOptions = {\n cryptographicFunctions?: CryptographicFunctions;\n};\n\n/**\n * The serialized state of an `HDKeyring` instance.\n *\n * @property mnemonic - The mnemonic seed phrase as an array of numbers.\n * @property numberOfAccounts - The number of accounts in the keyring.\n * @property hdPath - The HD path used to derive accounts.\n */\nexport type SerializedHDKeyringState = {\n mnemonic: number[];\n numberOfAccounts: number;\n hdPath: string;\n};\n\n/**\n * An object that can be passed to the Keyring.deserialize method to initialize\n * an `HDKeyring` instance.\n *\n * @property mnemonic - The mnemonic seed phrase as an array of numbers.\n * @property numberOfAccounts - The number of accounts in the keyring.\n * @property hdPath - The HD path used to derive accounts.\n */\nexport type DeserializableHDKeyringState = Omit<\n SerializedHDKeyringState,\n 'mnemonic'\n> & {\n mnemonic: number[] | SerializedBuffer | string;\n};\n\n/**\n * Options for selecting an account from an `HDKeyring` instance.\n *\n * @property withAppKeyOrigin - The origin of the app requesting the account.\n */\nexport type HDKeyringAccountSelectionOptions = {\n withAppKeyOrigin?: string;\n};\n\ntype SerializedBuffer = ReturnType<Buffer['toJSON']>;\n\n/**\n * Wallet storage object that contains both the HDKey and pre-computed address.\n */\ntype WalletData = {\n hdKey: HDKey;\n address: Hex;\n};\n\n/**\n * Checks if the given value is a valid serialized Buffer compatible with\n * the return type of `Buffer.toJSON`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid serialized buffer, `false` otherwise.\n */\nfunction isSerializedBuffer(value: unknown): value is SerializedBuffer {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'type' in value &&\n value.type === 'Buffer' &&\n 'data' in value &&\n Array.isArray(value.data)\n );\n}\n\nexport class HdKeyring implements Keyring {\n static type: string = type;\n\n type: string = type;\n\n mnemonic?: Uint8Array | null;\n\n seed?: Uint8Array | null;\n\n root?: HDKey | null;\n\n hdWallet?: HDKey;\n\n hdPath: string = hdPathString;\n\n readonly #walletMap = new Map<Hex, WalletData>();\n\n readonly #cryptographicFunctions?: CryptographicFunctions;\n\n constructor(opts: HDKeyringOptions = {}) {\n // Cryptographic functions to be used by `@metamask/key-tree`. It will use built-in implementations if not provided here.\n this.#cryptographicFunctions = opts.cryptographicFunctions;\n }\n\n /**\n * Initialize the keyring with a random mnemonic.\n *\n * @returns A promise that resolves when the process is complete.\n */\n async generateRandomMnemonic(): Promise<void> {\n await this.#initFromMnemonic(generateMnemonic(wordlist));\n }\n\n /**\n * Return the serialized state of the keyring.\n *\n * @returns The serialized state of the keyring.\n */\n async serialize(): Promise<SerializedHDKeyringState> {\n let mnemonic: number[] = [];\n\n if (this.mnemonic) {\n const mnemonicAsString = this.#uint8ArrayToString(this.mnemonic);\n mnemonic = Array.from(new TextEncoder().encode(mnemonicAsString));\n }\n\n return {\n mnemonic,\n numberOfAccounts: this.#walletMap.size,\n hdPath: this.hdPath,\n };\n }\n\n /**\n * Initialize the keyring with the given serialized state.\n *\n * @param opts - The serialized state of the keyring.\n * @returns An empty array.\n */\n async deserialize(\n opts: Partial<DeserializableHDKeyringState>,\n ): Promise<void> {\n if (opts.numberOfAccounts && !opts.mnemonic) {\n throw new Error(\n 'Eth-Hd-Keyring: Deserialize method cannot be called with an opts value for numberOfAccounts and no menmonic',\n );\n }\n\n if (this.root) {\n throw new Error(\n 'Eth-Hd-Keyring: Secret recovery phrase already provided',\n );\n }\n\n this.#walletMap.clear();\n this.mnemonic = null;\n this.seed = null;\n this.root = null;\n this.hdPath = opts.hdPath ?? hdPathString;\n\n if (opts.mnemonic) {\n await this.#initFromMnemonic(opts.mnemonic);\n }\n\n if (opts.numberOfAccounts) {\n await this.addAccounts(opts.numberOfAccounts);\n }\n }\n\n /**\n * Add new accounts to the keyring. The accounts will be derived\n * sequentially from the root HD wallet, using increasing indices.\n *\n * @param numberOfAccounts - The number of accounts to add.\n * @returns The addresses of the new accounts.\n */\n async addAccounts(numberOfAccounts = 1): Promise<Hex[]> {\n if (!this.root) {\n throw new Error('Eth-Hd-Keyring: No secret recovery phrase provided');\n }\n\n const oldLen = this.#walletMap.size;\n const newAddresses: Hex[] = [];\n for (let i = oldLen; i < numberOfAccounts + oldLen; i++) {\n const hdKey = this.root.deriveChild(i);\n assert(hdKey.publicKey, 'Expected public key to be set');\n\n const address = this.#addressFromPublicKey(hdKey.publicKey);\n const walletData: WalletData = {\n hdKey,\n address,\n };\n\n this.#walletMap.set(address, walletData);\n newAddresses.push(address);\n }\n\n return Promise.resolve(newAddresses);\n }\n\n /**\n * Get the addresses of all accounts in the keyring.\n *\n * @returns The addresses of all accounts in the keyring.\n */\n async getAccounts(): Promise<Hex[]> {\n return Array.from(this.#walletMap.keys());\n }\n\n /**\n * Get the public address of the account for the given app key origin.\n *\n * @param address - The address of the account.\n * @param origin - The origin of the app requesting the account.\n * @returns The public address of the account.\n */\n async getAppKeyAddress(address: Hex, origin: string): Promise<Hex> {\n if (!origin || typeof origin !== 'string') {\n throw new Error(`'origin' must be a non-empty string`);\n }\n const wallet = this.#getWalletForAccount(address, {\n withAppKeyOrigin: origin,\n });\n assert(wallet.publicKey, 'Expected public key to be set');\n const appKeyAddress = this.#normalizeAddress(\n bytesToHex(publicToAddress(wallet.publicKey)),\n );\n return appKeyAddress;\n }\n\n /**\n * Export the private key for a specific account.\n *\n * @param address - The address of the account.\n * @param opts - The options for exporting the account.\n * @param opts.withAppKeyOrigin - An optional string to export the account\n * for a specific app origin.\n * @returns The private key of the account.\n */\n async exportAccount(\n address: Hex,\n opts?: { withAppKeyOrigin: string },\n ): Promise<string> {\n const wallet = opts\n ? this.#getWalletForAccount(address, opts)\n : this.#getWalletForAccount(address);\n const { privateKey } = wallet;\n assert(\n privateKey instanceof Uint8Array,\n 'Expected private key to be of type Uint8Array',\n );\n return remove0x(bytesToHex(privateKey));\n }\n\n /**\n * Sign a transaction using the private key of the specified account.\n *\n * @param address - The address of the account.\n * @param tx - The transaction to sign.\n * @param opts - The options for signing the transaction.\n * @returns The signed transaction.\n */\n async signTransaction(\n address: Hex,\n tx: TypedTransaction,\n opts = {},\n ): Promise<TypedTransaction> {\n const privKey = this.#getPrivateKeyFor(address, opts);\n const signedTx = tx.sign(Buffer.from(privKey));\n // Newer versions of Ethereumjs-tx are immutable and return a new tx object\n return signedTx ?? tx;\n }\n\n /**\n * Sign a message using the private key of the specified account.\n *\n * @param address - The address of the account.\n * @param data - The data to sign.\n * @param opts - The options for signing the message.\n * @returns The signature of the message.\n */\n async signMessage(\n address: Hex,\n data: string,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n assertIsHexString(data);\n const message = remove0x(data);\n const privKey = this.#getPrivateKeyFor(address, opts);\n const msgSig = ecsign(Buffer.from(message, 'hex'), Buffer.from(privKey));\n const rawMsgSig = concatSig(\n Buffer.from(bigIntToBytes(msgSig.v)),\n Buffer.from(msgSig.r),\n Buffer.from(msgSig.s),\n );\n return rawMsgSig;\n }\n\n /**\n * Sign a personal message using the private key of the specified account.\n * This method is compatible with the `personal_sign` RPC method.\n *\n * @param address - The address of the account.\n * @param msgHex - The message to sign.\n * @param opts - The options for signing the message.\n * @returns The signature of the message.\n */\n async signPersonalMessage(\n address: Hex,\n msgHex: string,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n const privKey = this.#getPrivateKeyFor(address, opts);\n const privateKey = Buffer.from(privKey);\n return personalSign({ privateKey, data: msgHex });\n }\n\n /**\n * Decrypt an encrypted message using the private key of the specified account.\n * The message must be encrypted using the public key of the account.\n * This method is compatible with the `eth_decryptMessage` RPC method\n *\n * @param withAccount - The address of the account.\n * @param encryptedData - The encrypted data.\n * @returns The decrypted message.\n */\n async decryptMessage(\n withAccount: Hex,\n encryptedData: EthEncryptedData,\n ): Promise<string> {\n const wallet = this.#getWalletForAccount(withAccount);\n const { privateKey: privateKeyAsUint8Array } = wallet;\n assert(privateKeyAsUint8Array, 'Expected private key to be set');\n const privateKeyAsHex = Buffer.from(privateKeyAsUint8Array).toString('hex');\n return decrypt({ privateKey: privateKeyAsHex, encryptedData });\n }\n\n /**\n * Sign a typed message using the private key of the specified account.\n * This method is compatible with the `eth_signTypedData` RPC method.\n *\n * @param address - The address of the account.\n * @param data - The typed data to sign.\n * @param options - The options for signing the message.\n * @returns The signature of the message.\n */\n async signTypedData<\n Version extends SignTypedDataVersion,\n Types extends MessageTypes,\n Options extends { version?: Version },\n >(\n address: Hex,\n data: Version extends 'V1' ? TypedDataV1 : TypedMessage<Types>,\n options?: HDKeyringAccountSelectionOptions & Options,\n ): Promise<string> {\n let { version } = options ?? { version: SignTypedDataVersion.V1 };\n\n // Treat invalid versions as \"V1\"\n if (!version || !Object.keys(SignTypedDataVersion).includes(version)) {\n version = SignTypedDataVersion.V1;\n }\n\n const privateKey = this.#getPrivateKeyFor(address, options);\n return signTypedData({\n privateKey: Buffer.from(privateKey),\n data,\n version,\n });\n }\n\n /**\n * Sign an EIP-7702 authorization using the private key of the specified account.\n * This method is compatible with the EIP-7702 standard for enabling smart contract code for EOAs.\n *\n * @param withAccount - The address of the account.\n * @param authorization - The EIP-7702 authorization to sign.\n * @param opts - The options for selecting the account.\n * @returns The signature of the authorization.\n */\n async signEip7702Authorization(\n withAccount: Hex,\n authorization: EIP7702Authorization,\n opts?: HDKeyringAccountSelectionOptions,\n ): Promise<string> {\n const privateKey = this.#getPrivateKeyFor(withAccount, opts);\n return signEIP7702Authorization({\n privateKey: Buffer.from(privateKey),\n authorization,\n });\n }\n\n /**\n * Remove an account from the keyring.\n *\n * @param account - The address of the account to remove.\n */\n removeAccount(account: Hex): void {\n const address = this.#normalizeAddress(account);\n\n if (!this.#walletMap.has(address)) {\n throw new Error(`Address ${address} not found in this keyring`);\n }\n\n this.#walletMap.delete(address);\n }\n\n /**\n * Get the public key of the account to be used for encryption.\n *\n * @param withAccount - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns The public key of the account.\n */\n async getEncryptionPublicKey(\n withAccount: Hex,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n const privKey = this.#getPrivateKeyFor(withAccount, opts);\n const publicKey = getEncryptionPublicKey(remove0x(bytesToHex(privKey)));\n return publicKey;\n }\n\n /**\n * Convert a Uint8Array mnemonic to a secret recovery phrase,\n * using the english wordlist.\n *\n * @param mnemonic - The Uint8Array mnemonic.\n * @returns The string mnemonic.\n */\n #uint8ArrayToString(mnemonic: Uint8Array): string {\n const recoveredIndices = Array.from(\n new Uint16Array(new Uint8Array(mnemonic).buffer),\n );\n return recoveredIndices.map((i) => wordlist[i]).join(' ');\n }\n\n /**\n * Convert a secret recovery phrase to a Uint8Array mnemonic,\n * using the english wordlist.\n *\n * @param mnemonic - The string mnemonic.\n * @returns The Uint8Array mnemonic.\n */\n #stringToUint8Array(mnemonic: string): Uint8Array {\n const indices = mnemonic.split(' ').map((word) => wordlist.indexOf(word));\n return new Uint8Array(new Uint16Array(indices).buffer);\n }\n\n /**\n * Convert a mnemonic to a Uint8Array mnemonic.\n *\n * @param mnemonic - The mnemonic seed phrase.\n * @returns The Uint8Array mnemonic.\n */\n #mnemonicToUint8Array(\n mnemonic: Buffer | SerializedBuffer | string | Uint8Array | number[],\n ): Uint8Array {\n let mnemonicData: unknown = mnemonic;\n // When using `Buffer.toJSON()`, the Buffer is serialized into an object\n // with the structure `{ type: 'Buffer', data: [...] }`\n if (isSerializedBuffer(mnemonic)) {\n mnemonicData = mnemonic.data;\n }\n\n if (\n // this block is for backwards compatibility with vaults that were previously stored as buffers, number arrays or plain text strings\n typeof mnemonicData === 'string' ||\n Buffer.isBuffer(mnemonicData) ||\n Array.isArray(mnemonicData)\n ) {\n let mnemonicAsString: string;\n if (Array.isArray(mnemonicData)) {\n mnemonicAsString = Buffer.from(mnemonicData).toString();\n } else if (Buffer.isBuffer(mnemonicData)) {\n mnemonicAsString = mnemonicData.toString();\n } else {\n mnemonicAsString = mnemonicData;\n }\n return this.#stringToUint8Array(mnemonicAsString);\n } else if (\n mnemonicData instanceof Object &&\n !(mnemonicData instanceof Uint8Array)\n ) {\n // when encrypted/decrypted the Uint8Array becomes a js object we need to cast back to a Uint8Array\n return Uint8Array.from(Object.values(mnemonicData));\n }\n\n assert(mnemonicData instanceof Uint8Array, 'Expected Uint8Array mnemonic');\n return mnemonicData;\n }\n\n /**\n * Get the private key for the specified account.\n *\n * @param address - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns The private key of the account.\n */\n #getPrivateKeyFor(\n address: Hex,\n opts?: HDKeyringAccountSelectionOptions,\n ): Uint8Array | Buffer {\n if (!address) {\n throw new Error('Must specify address.');\n }\n const wallet = this.#getWalletForAccount(address, opts);\n assert(wallet.privateKey, 'Missing private key');\n return wallet.privateKey;\n }\n\n /**\n * Get the wallet for the specified account.\n *\n * @param account - The address of the account.\n * @returns The wallet for the account as HDKey.\n */\n #getWalletForAccount(account: Hex): HDKey;\n\n /**\n * Get the wallet for the specified account and app origin.\n *\n * @param account - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns A key pair representing the wallet.\n */\n #getWalletForAccount(\n accounts: Hex,\n opts: { withAppKeyOrigin: string },\n ): { privateKey: Buffer; publicKey: Buffer };\n\n /**\n * Get the wallet for the specified account with optional\n * additional options.\n *\n * @param account - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns A key pair representing the wallet.\n */\n #getWalletForAccount(\n account: Hex,\n opts?: HDKeyringAccountSelectionOptions,\n ): HDKey | { privateKey: Buffer; publicKey: Buffer };\n\n #getWalletForAccount(\n account: Hex,\n { withAppKeyOrigin }: HDKeyringAccountSelectionOptions = {},\n ): HDKey | { privateKey: Buffer; publicKey: Buffer } {\n const address = this.#normalizeAddress(account);\n const walletData = this.#walletMap.get(address);\n if (!walletData) {\n throw new Error('HD Keyring - Unable to find matching address.');\n }\n\n if (withAppKeyOrigin) {\n const { privateKey } = walletData.hdKey;\n assert(privateKey, 'Expected private key to be set');\n const appKeyOriginBuffer = Buffer.from(withAppKeyOrigin, 'utf8');\n const appKeyBuffer = Buffer.concat([privateKey, appKeyOriginBuffer]);\n const appKeyPrivateKey = Buffer.from(keccak256(appKeyBuffer));\n const appKeyPublicKey = Buffer.from(privateToPublic(appKeyPrivateKey));\n return { privateKey: appKeyPrivateKey, publicKey: appKeyPublicKey };\n }\n\n return walletData.hdKey;\n }\n\n /**\n * Sets appropriate properties for the keyring based on the given\n * BIP39-compliant mnemonic.\n *\n * @param mnemonic - A seed phrase represented\n * as a string, an array of UTF-8 bytes, or a Buffer. Mnemonic input\n * passed as type buffer or array of UTF-8 bytes must be NFKD normalized.\n */\n async #initFromMnemonic(\n mnemonic: string | number[] | SerializedBuffer | Buffer | Uint8Array,\n ): Promise<void> {\n if (this.root) {\n throw new Error(\n 'Eth-Hd-Keyring: Secret recovery phrase already provided',\n );\n }\n\n this.mnemonic = this.#mnemonicToUint8Array(mnemonic);\n\n this.seed = await mnemonicToSeed(\n this.mnemonic,\n '', // No passphrase\n this.#cryptographicFunctions,\n );\n this.hdWallet = HDKey.fromMasterSeed(this.seed);\n this.root = this.hdWallet.derive(this.hdPath);\n }\n\n /**\n * Get the address of the account from the public key.\n *\n * @param publicKey - The public key of the account.\n * @returns The address of the account.\n */\n #addressFromPublicKey(publicKey: Uint8Array): Hex {\n return add0x(\n bytesToHex(publicToAddress(Buffer.from(publicKey), true)).toLowerCase(),\n );\n }\n\n /**\n * Normalize an address to a lower-cased '0x'-prefixed hex string.\n *\n * @param address - The address to normalize.\n * @returns The normalized address.\n */\n #normalizeAddress(address: string): Hex {\n const normalized = normalize(address);\n assert(normalized, 'Expected address to be set');\n return add0x(normalized);\n }\n}\n"]}
1
+ {"version":3,"file":"hd-keyring.mjs","sourceRoot":"","sources":["../src/hd-keyring.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,EAAE,yBAAyB;AAC5E,OAAO,EACL,SAAS,EACT,OAAO,EAGP,sBAAsB,EAEtB,SAAS,EACT,YAAY,EACZ,wBAAwB,EACxB,aAAa,EACb,oBAAoB,EAGrB,+BAA+B;AAChC,OAAO,EAEL,cAAc,EACf,2BAA2B;AAE5B,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,8BAA8B;AAC3E,OAAO,EAAE,QAAQ,EAAE,wDAAqD;AACxE,OAAO,EACL,KAAK,EACL,MAAM,EACN,iBAAiB,EACjB,aAAa,EACb,UAAU,EAEV,QAAQ,EACT,wBAAwB;AACzB,OAAO,EAAE,KAAK,EAAE,oCAAoC;AACpD,OAAO,EAAE,SAAS,EAAE,qCAAqC;AAEzD,WAAW;AACX,MAAM,YAAY,GAAG,gBAAgB,CAAC;AAC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AM,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,WAAW,EAAE,CACxE,CAAC;AACJ,CAAC,qEAQiB,OAAe;IAC/B,MAAM,UAAU,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;IACtC,MAAM,CAAC,UAAU,EAAE,4BAA4B,CAAC,CAAC;IACjD,OAAO,KAAK,CAAC,UAAU,CAAC,CAAC;AAC3B,CAAC,2EASoB,QAAoB;IACvC,MAAM,cAAc,GAAG,uBAAA,IAAI,2DAAoB,MAAxB,IAAI,EAAqB,QAAQ,CAAC,CAAC;IAC1D,IAAI,CAAC,gBAAgB,CAAC,cAAc,EAAE,QAAQ,CAAC,EAAE,CAAC;QAChD,MAAM,IAAI,KAAK,CACb,yDAAyD,CAC1D,CAAC;IACJ,CAAC;AACH,CAAC;AAviBM,cAAI,GAAW,IAAI,AAAf,CAAgB","sourcesContent":["import type { TypedTransaction } from '@ethereumjs/tx';\nimport { privateToPublic, publicToAddress, ecsign } from '@ethereumjs/util';\nimport {\n concatSig,\n decrypt,\n type EIP7702Authorization,\n type EthEncryptedData,\n getEncryptionPublicKey,\n type MessageTypes,\n normalize,\n personalSign,\n signEIP7702Authorization,\n signTypedData,\n SignTypedDataVersion,\n type TypedDataV1,\n type TypedMessage,\n} from '@metamask/eth-sig-util';\nimport {\n type CryptographicFunctions,\n mnemonicToSeed,\n} from '@metamask/key-tree';\nimport type { Keyring } from '@metamask/keyring-utils';\nimport { generateMnemonic, validateMnemonic } from '@metamask/scure-bip39';\nimport { wordlist } from '@metamask/scure-bip39/dist/wordlists/english';\nimport {\n add0x,\n assert,\n assertIsHexString,\n bigIntToBytes,\n bytesToHex,\n type Hex,\n remove0x,\n} from '@metamask/utils';\nimport { HDKey } from 'ethereum-cryptography/hdkey';\nimport { keccak256 } from 'ethereum-cryptography/keccak';\n\n// Options:\nconst hdPathString = `m/44'/60'/0'/0`;\nconst type = 'HD Key Tree';\n\ntype Mnemonic = string | number[] | SerializedBuffer | Buffer | Uint8Array;\n\nexport type HDKeyringOptions = {\n cryptographicFunctions?: CryptographicFunctions;\n};\n\n/**\n * The serialized state of an `HDKeyring` instance.\n *\n * @property mnemonic - The mnemonic seed phrase as an array of numbers.\n * @property numberOfAccounts - The number of accounts in the keyring.\n * @property hdPath - The HD path used to derive accounts.\n */\nexport type SerializedHDKeyringState = {\n mnemonic: number[];\n numberOfAccounts: number;\n hdPath: string;\n};\n\n/**\n * An object that can be passed to the Keyring.deserialize method to initialize\n * an `HDKeyring` instance.\n *\n * @property mnemonic - The mnemonic seed phrase as an array of numbers.\n * @property numberOfAccounts - The number of accounts in the keyring.\n * @property hdPath - The HD path used to derive accounts.\n */\nexport type DeserializableHDKeyringState = Omit<\n SerializedHDKeyringState,\n 'mnemonic'\n> & {\n mnemonic: number[] | SerializedBuffer | string;\n};\n\n/**\n * Options for selecting an account from an `HDKeyring` instance.\n *\n * @property withAppKeyOrigin - The origin of the app requesting the account.\n */\nexport type HDKeyringAccountSelectionOptions = {\n withAppKeyOrigin?: string;\n};\n\ntype SerializedBuffer = ReturnType<Buffer['toJSON']>;\n\n/**\n * Wallet storage object that contains both the HDKey and pre-computed address.\n */\ntype WalletData = {\n hdKey: HDKey;\n address: Hex;\n};\n\n/**\n * Checks if the given value is a valid serialized Buffer compatible with\n * the return type of `Buffer.toJSON`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid serialized buffer, `false` otherwise.\n */\nfunction isSerializedBuffer(value: unknown): value is SerializedBuffer {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'type' in value &&\n value.type === 'Buffer' &&\n 'data' in value &&\n Array.isArray(value.data)\n );\n}\n\nexport class HdKeyring implements Keyring {\n static type: string = type;\n\n type: string = type;\n\n mnemonic?: Uint8Array | null;\n\n seed?: Uint8Array | null;\n\n root?: HDKey | null;\n\n hdWallet?: HDKey;\n\n hdPath: string = hdPathString;\n\n readonly #walletMap = new Map<Hex, WalletData>();\n\n readonly #cryptographicFunctions?: CryptographicFunctions;\n\n constructor(opts: HDKeyringOptions = {}) {\n // Cryptographic functions to be used by `@metamask/key-tree`. It will use built-in implementations if not provided here.\n this.#cryptographicFunctions = opts.cryptographicFunctions;\n }\n\n /**\n * Initialize the keyring with a random mnemonic.\n *\n * @returns A promise that resolves when the process is complete.\n */\n async generateRandomMnemonic(): Promise<void> {\n await this.#initFromMnemonic(generateMnemonic(wordlist));\n }\n\n /**\n * Return the serialized state of the keyring.\n *\n * @returns The serialized state of the keyring.\n */\n async serialize(): Promise<SerializedHDKeyringState> {\n let mnemonic: number[] = [];\n\n if (this.mnemonic) {\n const mnemonicAsString = this.#uint8ArrayToString(this.mnemonic);\n mnemonic = Array.from(new TextEncoder().encode(mnemonicAsString));\n }\n\n return {\n mnemonic,\n numberOfAccounts: this.#walletMap.size,\n hdPath: this.hdPath,\n };\n }\n\n /**\n * Initialize the keyring with the given serialized state.\n *\n * @param opts - The serialized state of the keyring.\n * @returns An empty array.\n */\n async deserialize(\n opts: Partial<DeserializableHDKeyringState>,\n ): Promise<void> {\n if (opts.numberOfAccounts && !opts.mnemonic) {\n throw new Error(\n 'Eth-Hd-Keyring: Deserialize method cannot be called with an opts value for numberOfAccounts and no menmonic',\n );\n }\n\n if (this.root) {\n throw new Error(\n 'Eth-Hd-Keyring: Secret recovery phrase already provided',\n );\n }\n\n this.#walletMap.clear();\n this.mnemonic = null;\n this.seed = null;\n this.root = null;\n this.hdPath = opts.hdPath ?? hdPathString;\n\n if (opts.mnemonic) {\n await this.#initFromMnemonic(opts.mnemonic);\n }\n\n if (opts.numberOfAccounts) {\n await this.addAccounts(opts.numberOfAccounts);\n }\n }\n\n /**\n * Add new accounts to the keyring. The accounts will be derived\n * sequentially from the root HD wallet, using increasing indices.\n *\n * @param numberOfAccounts - The number of accounts to add.\n * @returns The addresses of the new accounts.\n */\n async addAccounts(numberOfAccounts = 1): Promise<Hex[]> {\n if (!this.root) {\n throw new Error('Eth-Hd-Keyring: No secret recovery phrase provided');\n }\n\n const oldLen = this.#walletMap.size;\n const newAddresses: Hex[] = [];\n for (let i = oldLen; i < numberOfAccounts + oldLen; i++) {\n const hdKey = this.root.deriveChild(i);\n assert(hdKey.publicKey, 'Expected public key to be set');\n\n const address = this.#addressFromPublicKey(hdKey.publicKey);\n const walletData: WalletData = {\n hdKey,\n address,\n };\n\n this.#walletMap.set(address, walletData);\n newAddresses.push(address);\n }\n\n return Promise.resolve(newAddresses);\n }\n\n /**\n * Get the addresses of all accounts in the keyring.\n *\n * @returns The addresses of all accounts in the keyring.\n */\n async getAccounts(): Promise<Hex[]> {\n return Array.from(this.#walletMap.keys());\n }\n\n /**\n * Get the public address of the account for the given app key origin.\n *\n * @param address - The address of the account.\n * @param origin - The origin of the app requesting the account.\n * @returns The public address of the account.\n */\n async getAppKeyAddress(address: Hex, origin: string): Promise<Hex> {\n if (!origin || typeof origin !== 'string') {\n throw new Error(`'origin' must be a non-empty string`);\n }\n const wallet = this.#getWalletForAccount(address, {\n withAppKeyOrigin: origin,\n });\n assert(wallet.publicKey, 'Expected public key to be set');\n const appKeyAddress = this.#normalizeAddress(\n bytesToHex(publicToAddress(wallet.publicKey)),\n );\n return appKeyAddress;\n }\n\n /**\n * Export the private key for a specific account.\n *\n * @param address - The address of the account.\n * @param opts - The options for exporting the account.\n * @param opts.withAppKeyOrigin - An optional string to export the account\n * for a specific app origin.\n * @returns The private key of the account.\n */\n async exportAccount(\n address: Hex,\n opts?: { withAppKeyOrigin: string },\n ): Promise<string> {\n const wallet = opts\n ? this.#getWalletForAccount(address, opts)\n : this.#getWalletForAccount(address);\n const { privateKey } = wallet;\n assert(\n privateKey instanceof Uint8Array,\n 'Expected private key to be of type Uint8Array',\n );\n return remove0x(bytesToHex(privateKey));\n }\n\n /**\n * Sign a transaction using the private key of the specified account.\n *\n * @param address - The address of the account.\n * @param tx - The transaction to sign.\n * @param opts - The options for signing the transaction.\n * @returns The signed transaction.\n */\n async signTransaction(\n address: Hex,\n tx: TypedTransaction,\n opts = {},\n ): Promise<TypedTransaction> {\n const privKey = this.#getPrivateKeyFor(address, opts);\n const signedTx = tx.sign(Buffer.from(privKey));\n // Newer versions of Ethereumjs-tx are immutable and return a new tx object\n return signedTx ?? tx;\n }\n\n /**\n * Sign a message using the private key of the specified account.\n *\n * @param address - The address of the account.\n * @param data - The data to sign.\n * @param opts - The options for signing the message.\n * @returns The signature of the message.\n */\n async signMessage(\n address: Hex,\n data: string,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n assertIsHexString(data);\n const message = remove0x(data);\n const privKey = this.#getPrivateKeyFor(address, opts);\n const msgSig = ecsign(Buffer.from(message, 'hex'), Buffer.from(privKey));\n const rawMsgSig = concatSig(\n Buffer.from(bigIntToBytes(msgSig.v)),\n Buffer.from(msgSig.r),\n Buffer.from(msgSig.s),\n );\n return rawMsgSig;\n }\n\n /**\n * Sign a personal message using the private key of the specified account.\n * This method is compatible with the `personal_sign` RPC method.\n *\n * @param address - The address of the account.\n * @param msgHex - The message to sign.\n * @param opts - The options for signing the message.\n * @returns The signature of the message.\n */\n async signPersonalMessage(\n address: Hex,\n msgHex: string,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n const privKey = this.#getPrivateKeyFor(address, opts);\n const privateKey = Buffer.from(privKey);\n return personalSign({ privateKey, data: msgHex });\n }\n\n /**\n * Decrypt an encrypted message using the private key of the specified account.\n * The message must be encrypted using the public key of the account.\n * This method is compatible with the `eth_decryptMessage` RPC method\n *\n * @param withAccount - The address of the account.\n * @param encryptedData - The encrypted data.\n * @returns The decrypted message.\n */\n async decryptMessage(\n withAccount: Hex,\n encryptedData: EthEncryptedData,\n ): Promise<string> {\n const wallet = this.#getWalletForAccount(withAccount);\n const { privateKey: privateKeyAsUint8Array } = wallet;\n assert(privateKeyAsUint8Array, 'Expected private key to be set');\n const privateKeyAsHex = Buffer.from(privateKeyAsUint8Array).toString('hex');\n return decrypt({ privateKey: privateKeyAsHex, encryptedData });\n }\n\n /**\n * Sign a typed message using the private key of the specified account.\n * This method is compatible with the `eth_signTypedData` RPC method.\n *\n * @param address - The address of the account.\n * @param data - The typed data to sign.\n * @param options - The options for signing the message.\n * @returns The signature of the message.\n */\n async signTypedData<\n Version extends SignTypedDataVersion,\n Types extends MessageTypes,\n Options extends { version?: Version },\n >(\n address: Hex,\n data: Version extends 'V1' ? TypedDataV1 : TypedMessage<Types>,\n options?: HDKeyringAccountSelectionOptions & Options,\n ): Promise<string> {\n let { version } = options ?? { version: SignTypedDataVersion.V1 };\n\n // Treat invalid versions as \"V1\"\n if (!version || !Object.keys(SignTypedDataVersion).includes(version)) {\n version = SignTypedDataVersion.V1;\n }\n\n const privateKey = this.#getPrivateKeyFor(address, options);\n return signTypedData({\n privateKey: Buffer.from(privateKey),\n data,\n version,\n });\n }\n\n /**\n * Sign an EIP-7702 authorization using the private key of the specified account.\n * This method is compatible with the EIP-7702 standard for enabling smart contract code for EOAs.\n *\n * @param withAccount - The address of the account.\n * @param authorization - The EIP-7702 authorization to sign.\n * @param opts - The options for selecting the account.\n * @returns The signature of the authorization.\n */\n async signEip7702Authorization(\n withAccount: Hex,\n authorization: EIP7702Authorization,\n opts?: HDKeyringAccountSelectionOptions,\n ): Promise<string> {\n const privateKey = this.#getPrivateKeyFor(withAccount, opts);\n return signEIP7702Authorization({\n privateKey: Buffer.from(privateKey),\n authorization,\n });\n }\n\n /**\n * Remove an account from the keyring.\n *\n * @param account - The address of the account to remove.\n */\n removeAccount(account: Hex): void {\n const address = this.#normalizeAddress(account);\n\n if (!this.#walletMap.has(address)) {\n throw new Error(`Address ${address} not found in this keyring`);\n }\n\n this.#walletMap.delete(address);\n }\n\n /**\n * Get the public key of the account to be used for encryption.\n *\n * @param withAccount - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns The public key of the account.\n */\n async getEncryptionPublicKey(\n withAccount: Hex,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n const privKey = this.#getPrivateKeyFor(withAccount, opts);\n const publicKey = getEncryptionPublicKey(remove0x(bytesToHex(privKey)));\n return publicKey;\n }\n\n /**\n * Convert a Uint8Array mnemonic to a secret recovery phrase,\n * using the english wordlist.\n *\n * @param mnemonic - The Uint8Array mnemonic.\n * @returns The string mnemonic.\n */\n #uint8ArrayToString(mnemonic: Uint8Array): string {\n const recoveredIndices = Array.from(\n new Uint16Array(new Uint8Array(mnemonic).buffer),\n );\n return recoveredIndices.map((i) => wordlist[i]).join(' ');\n }\n\n /**\n * Convert a secret recovery phrase to a Uint8Array mnemonic,\n * using the english wordlist.\n *\n * @param mnemonic - The string mnemonic.\n * @returns The Uint8Array mnemonic.\n */\n #stringToUint8Array(mnemonic: string): Uint8Array {\n const indices = mnemonic.split(' ').map((word) => wordlist.indexOf(word));\n return new Uint8Array(new Uint16Array(indices).buffer);\n }\n\n /**\n * Convert a mnemonic to a Uint8Array mnemonic.\n *\n * @param mnemonic - The mnemonic seed phrase.\n * @returns The Uint8Array mnemonic.\n */\n #mnemonicToUint8Array(mnemonic: Mnemonic): Uint8Array {\n let mnemonicData: unknown = mnemonic;\n // When using `Buffer.toJSON()`, the Buffer is serialized into an object\n // with the structure `{ type: 'Buffer', data: [...] }`\n if (isSerializedBuffer(mnemonic)) {\n mnemonicData = mnemonic.data;\n }\n\n if (\n // this block is for backwards compatibility with vaults that were previously stored as buffers, number arrays or plain text strings\n typeof mnemonicData === 'string' ||\n Buffer.isBuffer(mnemonicData) ||\n Array.isArray(mnemonicData)\n ) {\n let mnemonicAsString: string;\n if (Array.isArray(mnemonicData)) {\n mnemonicAsString = Buffer.from(mnemonicData).toString();\n } else if (Buffer.isBuffer(mnemonicData)) {\n mnemonicAsString = mnemonicData.toString();\n } else {\n mnemonicAsString = mnemonicData;\n }\n return this.#stringToUint8Array(mnemonicAsString);\n } else if (\n mnemonicData instanceof Object &&\n !(mnemonicData instanceof Uint8Array)\n ) {\n // when encrypted/decrypted the Uint8Array becomes a js object we need to cast back to a Uint8Array\n return Uint8Array.from(Object.values(mnemonicData));\n }\n\n assert(mnemonicData instanceof Uint8Array, 'Expected Uint8Array mnemonic');\n return mnemonicData;\n }\n\n /**\n * Get the private key for the specified account.\n *\n * @param address - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns The private key of the account.\n */\n #getPrivateKeyFor(\n address: Hex,\n opts?: HDKeyringAccountSelectionOptions,\n ): Uint8Array | Buffer {\n if (!address) {\n throw new Error('Must specify address.');\n }\n const wallet = this.#getWalletForAccount(address, opts);\n assert(wallet.privateKey, 'Missing private key');\n return wallet.privateKey;\n }\n\n /**\n * Get the wallet for the specified account.\n *\n * @param account - The address of the account.\n * @returns The wallet for the account as HDKey.\n */\n #getWalletForAccount(account: Hex): HDKey;\n\n /**\n * Get the wallet for the specified account and app origin.\n *\n * @param account - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns A key pair representing the wallet.\n */\n #getWalletForAccount(\n accounts: Hex,\n opts: { withAppKeyOrigin: string },\n ): { privateKey: Buffer; publicKey: Buffer };\n\n /**\n * Get the wallet for the specified account with optional\n * additional options.\n *\n * @param account - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns A key pair representing the wallet.\n */\n #getWalletForAccount(\n account: Hex,\n opts?: HDKeyringAccountSelectionOptions,\n ): HDKey | { privateKey: Buffer; publicKey: Buffer };\n\n #getWalletForAccount(\n account: Hex,\n { withAppKeyOrigin }: HDKeyringAccountSelectionOptions = {},\n ): HDKey | { privateKey: Buffer; publicKey: Buffer } {\n const address = this.#normalizeAddress(account);\n const walletData = this.#walletMap.get(address);\n if (!walletData) {\n throw new Error('HD Keyring - Unable to find matching address.');\n }\n\n if (withAppKeyOrigin) {\n const { privateKey } = walletData.hdKey;\n assert(privateKey, 'Expected private key to be set');\n const appKeyOriginBuffer = Buffer.from(withAppKeyOrigin, 'utf8');\n const appKeyBuffer = Buffer.concat([privateKey, appKeyOriginBuffer]);\n const appKeyPrivateKey = Buffer.from(keccak256(appKeyBuffer));\n const appKeyPublicKey = Buffer.from(privateToPublic(appKeyPrivateKey));\n return { privateKey: appKeyPrivateKey, publicKey: appKeyPublicKey };\n }\n\n return walletData.hdKey;\n }\n\n /**\n * Sets appropriate properties for the keyring based on the given\n * BIP39-compliant mnemonic.\n *\n * @param mnemonic - A seed phrase represented\n * as a string, an array of UTF-8 bytes, or a Buffer. Mnemonic input\n * passed as type buffer or array of UTF-8 bytes must be NFKD normalized.\n */\n async #initFromMnemonic(mnemonic: Mnemonic): Promise<void> {\n if (this.root) {\n throw new Error(\n 'Eth-Hd-Keyring: Secret recovery phrase already provided',\n );\n }\n\n // Convert and validate before assigning to instance property\n // to avoid inconsistent state if validation fails\n const mnemonicAsUint8Array = this.#mnemonicToUint8Array(mnemonic);\n this.#assertValidMnemonic(mnemonicAsUint8Array);\n this.mnemonic = mnemonicAsUint8Array;\n\n this.seed = await mnemonicToSeed(\n this.mnemonic,\n '', // No passphrase\n this.#cryptographicFunctions,\n );\n this.hdWallet = HDKey.fromMasterSeed(this.seed);\n this.root = this.hdWallet.derive(this.hdPath);\n }\n\n /**\n * Get the address of the account from the public key.\n *\n * @param publicKey - The public key of the account.\n * @returns The address of the account.\n */\n #addressFromPublicKey(publicKey: Uint8Array): Hex {\n return add0x(\n bytesToHex(publicToAddress(Buffer.from(publicKey), true)).toLowerCase(),\n );\n }\n\n /**\n * Normalize an address to a lower-cased '0x'-prefixed hex string.\n *\n * @param address - The address to normalize.\n * @returns The normalized address.\n */\n #normalizeAddress(address: string): Hex {\n const normalized = normalize(address);\n assert(normalized, 'Expected address to be set');\n return add0x(normalized);\n }\n\n /**\n * Assert that the mnemonic seed phrase is valid.\n * Throws an error if the mnemonic is not a valid BIP39 phrase.\n *\n * @param mnemonic - The mnemonic seed phrase to validate (as Uint8Array).\n * @throws If the mnemonic is not a valid BIP39 secret recovery phrase.\n */\n #assertValidMnemonic(mnemonic: Uint8Array): void {\n const mnemonicString = this.#uint8ArrayToString(mnemonic);\n if (!validateMnemonic(mnemonicString, wordlist)) {\n throw new Error(\n 'Eth-Hd-Keyring: Invalid secret recovery phrase provided',\n );\n }\n }\n}\n"]}
package/dist/index.cjs CHANGED
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HdKeyring = void 0;
3
+ exports.HdKeyringV2 = exports.HdKeyring = void 0;
4
4
  var hd_keyring_1 = require("./hd-keyring.cjs");
5
5
  Object.defineProperty(exports, "HdKeyring", { enumerable: true, get: function () { return hd_keyring_1.HdKeyring; } });
6
+ var hd_keyring_v2_1 = require("./hd-keyring-v2.cjs");
7
+ Object.defineProperty(exports, "HdKeyringV2", { enumerable: true, get: function () { return hd_keyring_v2_1.HdKeyringV2; } });
6
8
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,+CAAyC;AAAhC,uGAAA,SAAS,OAAA","sourcesContent":["export { HdKeyring } from './hd-keyring';\nexport type {\n SerializedHDKeyringState,\n DeserializableHDKeyringState,\n HDKeyringOptions,\n HDKeyringAccountSelectionOptions,\n} from './hd-keyring';\n"]}
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,+CAAyC;AAAhC,uGAAA,SAAS,OAAA;AAOlB,qDAAuE;AAA9D,4GAAA,WAAW,OAAA","sourcesContent":["export { HdKeyring } from './hd-keyring';\nexport type {\n SerializedHDKeyringState,\n DeserializableHDKeyringState,\n HDKeyringOptions,\n HDKeyringAccountSelectionOptions,\n} from './hd-keyring';\nexport { HdKeyringV2, type HdKeyringV2Options } from './hd-keyring-v2';\n"]}
package/dist/index.d.cts CHANGED
@@ -1,3 +1,4 @@
1
1
  export { HdKeyring } from "./hd-keyring.cjs";
2
2
  export type { SerializedHDKeyringState, DeserializableHDKeyringState, HDKeyringOptions, HDKeyringAccountSelectionOptions, } from "./hd-keyring.cjs";
3
+ export { HdKeyringV2, type HdKeyringV2Options } from "./hd-keyring-v2.cjs";
3
4
  //# sourceMappingURL=index.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,yBAAqB;AACzC,YAAY,EACV,wBAAwB,EACxB,4BAA4B,EAC5B,gBAAgB,EAChB,gCAAgC,GACjC,yBAAqB"}
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,yBAAqB;AACzC,YAAY,EACV,wBAAwB,EACxB,4BAA4B,EAC5B,gBAAgB,EAChB,gCAAgC,GACjC,yBAAqB;AACtB,OAAO,EAAE,WAAW,EAAE,KAAK,kBAAkB,EAAE,4BAAwB"}
package/dist/index.d.mts CHANGED
@@ -1,3 +1,4 @@
1
1
  export { HdKeyring } from "./hd-keyring.mjs";
2
2
  export type { SerializedHDKeyringState, DeserializableHDKeyringState, HDKeyringOptions, HDKeyringAccountSelectionOptions, } from "./hd-keyring.mjs";
3
+ export { HdKeyringV2, type HdKeyringV2Options } from "./hd-keyring-v2.mjs";
3
4
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,yBAAqB;AACzC,YAAY,EACV,wBAAwB,EACxB,4BAA4B,EAC5B,gBAAgB,EAChB,gCAAgC,GACjC,yBAAqB"}
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,yBAAqB;AACzC,YAAY,EACV,wBAAwB,EACxB,4BAA4B,EAC5B,gBAAgB,EAChB,gCAAgC,GACjC,yBAAqB;AACtB,OAAO,EAAE,WAAW,EAAE,KAAK,kBAAkB,EAAE,4BAAwB"}
package/dist/index.mjs CHANGED
@@ -1,2 +1,3 @@
1
1
  export { HdKeyring } from "./hd-keyring.mjs";
2
+ export { HdKeyringV2 } from "./hd-keyring-v2.mjs";
2
3
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,yBAAqB","sourcesContent":["export { HdKeyring } from './hd-keyring';\nexport type {\n SerializedHDKeyringState,\n DeserializableHDKeyringState,\n HDKeyringOptions,\n HDKeyringAccountSelectionOptions,\n} from './hd-keyring';\n"]}
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,yBAAqB;AAOzC,OAAO,EAAE,WAAW,EAA2B,4BAAwB","sourcesContent":["export { HdKeyring } from './hd-keyring';\nexport type {\n SerializedHDKeyringState,\n DeserializableHDKeyringState,\n HDKeyringOptions,\n HDKeyringAccountSelectionOptions,\n} from './hd-keyring';\nexport { HdKeyringV2, type HdKeyringV2Options } from './hd-keyring-v2';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/eth-hd-keyring",
3
- "version": "13.0.0",
3
+ "version": "13.1.0",
4
4
  "description": "A simple standard interface for a seed phrase generated set of Ethereum accounts.",
5
5
  "keywords": [
6
6
  "ethereum",
@@ -43,18 +43,21 @@
43
43
  "test:clean": "jest --clearCache"
44
44
  },
45
45
  "dependencies": {
46
+ "@ethereumjs/tx": "^5.4.0",
46
47
  "@ethereumjs/util": "^9.1.0",
47
48
  "@metamask/eth-sig-util": "^8.2.0",
48
49
  "@metamask/key-tree": "^10.0.2",
50
+ "@metamask/keyring-api": "^21.3.0",
49
51
  "@metamask/keyring-utils": "^3.1.0",
50
52
  "@metamask/scure-bip39": "^2.1.1",
53
+ "@metamask/superstruct": "^3.1.0",
51
54
  "@metamask/utils": "^11.1.0",
52
55
  "ethereum-cryptography": "^2.1.2"
53
56
  },
54
57
  "devDependencies": {
55
- "@ethereumjs/tx": "^5.4.0",
56
58
  "@lavamoat/allow-scripts": "^3.2.1",
57
59
  "@lavamoat/preinstall-always-fail": "^2.1.0",
60
+ "@metamask/account-api": "^0.12.0",
58
61
  "@metamask/auto-changelog": "^3.4.4",
59
62
  "@metamask/bip39": "^4.0.0",
60
63
  "@ts-bridge/cli": "^0.6.3",