@metamask/eth-ledger-bridge-keyring 11.1.1 → 11.2.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.
@@ -0,0 +1,223 @@
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 _LedgerKeyringV2_instances, _LedgerKeyringV2_getChecksumHexAddress, _LedgerKeyringV2_parseDerivationPath, _LedgerKeyringV2_getIndexForAddress, _LedgerKeyringV2_createKeyringAccount;
7
+ import { EthAccountType, EthKeyringWrapper, EthMethod, EthScope, KeyringAccountEntropyTypeOption, KeyringType } from "@metamask/keyring-api";
8
+ import { add0x, getChecksumAddress } from "@metamask/utils";
9
+ /**
10
+ * Methods supported by Ledger keyring EOA accounts.
11
+ * Ledger keyrings support a subset of signing methods (no encryption, app keys, or EIP-7702).
12
+ */
13
+ const LEDGER_KEYRING_METHODS = [
14
+ EthMethod.SignTransaction,
15
+ EthMethod.PersonalSign,
16
+ EthMethod.SignTypedDataV4,
17
+ ];
18
+ const ledgerKeyringV2Capabilities = {
19
+ scopes: [EthScope.Eoa],
20
+ bip44: {
21
+ deriveIndex: true,
22
+ derivePath: true,
23
+ },
24
+ };
25
+ /**
26
+ * Ledger Live HD path constant.
27
+ */
28
+ const LEDGER_LIVE_HD_PATH = `m/44'/60'/0'/0/0`;
29
+ /**
30
+ * BIP-44 standard HD path prefix constant for Ethereum.
31
+ */
32
+ const BIP44_HD_PATH_PREFIX = `m/44'/60'/0'/0`;
33
+ /**
34
+ * Regex pattern for validating and parsing Ledger Live derivation paths.
35
+ * Format: m/44'/60'/{index}'/0/0
36
+ */
37
+ const LEDGER_LIVE_PATH_PATTERN = /^m\/44'\/60'\/(\d+)'\/0\/0$/u;
38
+ /**
39
+ * Regex pattern for validating and parsing non-Ledger-Live derivation paths.
40
+ * Supports Legacy (m/44'/60'/0'/{index}), BIP44 (m/44'/60'/0'/0/{index}),
41
+ * and custom paths that follow the m/44'/60'/... pattern.
42
+ */
43
+ const INDEX_AT_END_PATH_PATTERN = /^(m\/44'\/60'(?:\/\d+'?)*)\/(\d+)$/u;
44
+ export class LedgerKeyringV2 extends EthKeyringWrapper {
45
+ constructor(options) {
46
+ super({
47
+ type: KeyringType.Ledger,
48
+ inner: options.legacyKeyring,
49
+ capabilities: ledgerKeyringV2Capabilities,
50
+ });
51
+ _LedgerKeyringV2_instances.add(this);
52
+ this.entropySource = options.entropySource;
53
+ }
54
+ async getAccounts() {
55
+ const addresses = await this.inner.getAccounts();
56
+ if (addresses.length === 0) {
57
+ return [];
58
+ }
59
+ return addresses.map((address) => {
60
+ // Check if we already have this account in the registry
61
+ const existingId = this.registry.getAccountId(address);
62
+ if (existingId) {
63
+ const cached = this.registry.get(existingId);
64
+ if (cached) {
65
+ return cached;
66
+ }
67
+ }
68
+ const addressIndex = __classPrivateFieldGet(this, _LedgerKeyringV2_instances, "m", _LedgerKeyringV2_getIndexForAddress).call(this, address);
69
+ return __classPrivateFieldGet(this, _LedgerKeyringV2_instances, "m", _LedgerKeyringV2_createKeyringAccount).call(this, address, addressIndex);
70
+ });
71
+ }
72
+ async createAccounts(options) {
73
+ return this.withLock(async () => {
74
+ if (options.type === 'bip44:derive-path' ||
75
+ options.type === 'bip44:derive-index') {
76
+ // Validate that the entropy source matches this keyring's entropy source
77
+ if (options.entropySource !== this.entropySource) {
78
+ throw new Error(`Entropy source mismatch: expected '${this.entropySource}', got '${options.entropySource}'`);
79
+ }
80
+ }
81
+ else {
82
+ throw new Error(`Unsupported account creation type for LedgerKeyring: ${String(options.type)}`);
83
+ }
84
+ // Check if an account at this index already exists with the same derivation path
85
+ const currentAccounts = await this.getAccounts();
86
+ let targetIndex;
87
+ let basePath;
88
+ let derivationPath;
89
+ if (options.type === 'bip44:derive-path') {
90
+ // Parse the derivation path to extract base path and index
91
+ const parsed = __classPrivateFieldGet(this, _LedgerKeyringV2_instances, "m", _LedgerKeyringV2_parseDerivationPath).call(this, options.derivationPath);
92
+ targetIndex = parsed.index;
93
+ basePath = parsed.basePath;
94
+ derivationPath = options.derivationPath;
95
+ }
96
+ else {
97
+ // derive-index uses BIP-44 standard path by default
98
+ targetIndex = options.groupIndex;
99
+ basePath = BIP44_HD_PATH_PREFIX;
100
+ derivationPath = `${basePath}/${targetIndex}`;
101
+ }
102
+ const existingAccount = currentAccounts.find((account) => {
103
+ return (account.options.entropy.groupIndex === targetIndex &&
104
+ account.options.entropy.derivationPath === derivationPath);
105
+ });
106
+ if (existingAccount) {
107
+ return [existingAccount];
108
+ }
109
+ // Derive the account at the specified index
110
+ this.inner.setHdPath(basePath);
111
+ this.inner.setAccountToUnlock(targetIndex);
112
+ const [newAddress] = await this.inner.addAccounts(1);
113
+ if (!newAddress) {
114
+ throw new Error('Failed to create new account');
115
+ }
116
+ const newAccount = __classPrivateFieldGet(this, _LedgerKeyringV2_instances, "m", _LedgerKeyringV2_createKeyringAccount).call(this, newAddress, targetIndex);
117
+ return [newAccount];
118
+ });
119
+ }
120
+ /**
121
+ * Delete an account from the keyring.
122
+ *
123
+ * @param accountId - The account ID to delete.
124
+ */
125
+ async deleteAccount(accountId) {
126
+ await this.withLock(async () => {
127
+ const { address } = await this.getAccount(accountId);
128
+ const hexAddress = this.toHexAddress(address);
129
+ // Remove from the legacy keyring
130
+ this.inner.removeAccount(hexAddress);
131
+ // Remove from the registry
132
+ this.registry.delete(accountId);
133
+ });
134
+ }
135
+ }
136
+ _LedgerKeyringV2_instances = new WeakSet(), _LedgerKeyringV2_getChecksumHexAddress = function _LedgerKeyringV2_getChecksumHexAddress(address) {
137
+ return getChecksumAddress(add0x(address));
138
+ }, _LedgerKeyringV2_parseDerivationPath = function _LedgerKeyringV2_parseDerivationPath(derivationPath) {
139
+ // Try Ledger Live format first: m/44'/60'/{index}'/0/0
140
+ const ledgerLiveMatch = derivationPath.match(LEDGER_LIVE_PATH_PATTERN);
141
+ if (ledgerLiveMatch?.[1]) {
142
+ return {
143
+ // This constant is used by `inner.setHdPath` to determine which derivation
144
+ // mode we should use (Ledger Live derivation mode here).
145
+ basePath: LEDGER_LIVE_HD_PATH,
146
+ index: parseInt(ledgerLiveMatch[1], 10),
147
+ };
148
+ }
149
+ // Try index-at-end format: m/44'/60'/.../{index}
150
+ const indexAtEndMatch = derivationPath.match(INDEX_AT_END_PATH_PATTERN);
151
+ if (indexAtEndMatch) {
152
+ // If the condition is true, indexAtEndMatch[1] and indexAtEndMatch[2] are defined, so
153
+ // we can safely cast them to string.
154
+ // This is necessary to get 100% code coverage.
155
+ return {
156
+ // Here, we use a derivation path prefix for `inner.setHdPath`
157
+ // (prefix + index derivation mode).
158
+ basePath: indexAtEndMatch[1],
159
+ index: parseInt(indexAtEndMatch[2], 10),
160
+ };
161
+ }
162
+ throw new Error(`Invalid derivation path format: ${derivationPath}. ` +
163
+ `Expected Ledger Live (m/44'/60'/{index}'/0/0) or index-at-end (m/44'/60'/.../{index}) format.`);
164
+ }, _LedgerKeyringV2_getIndexForAddress = function _LedgerKeyringV2_getIndexForAddress(address) {
165
+ const checksummedAddress = __classPrivateFieldGet(this, _LedgerKeyringV2_instances, "m", _LedgerKeyringV2_getChecksumHexAddress).call(this, address);
166
+ const details = this.inner.accountDetails[checksummedAddress];
167
+ if (!details) {
168
+ throw new Error(`Address ${checksummedAddress} not found in account details`);
169
+ }
170
+ // Extract index from hdPath
171
+ const { hdPath } = details;
172
+ if (!hdPath) {
173
+ throw new Error(`No HD path found for address ${checksummedAddress}`);
174
+ }
175
+ // Ledger supports multiple derivation path formats:
176
+ // - Ledger Live (bip44: true): m/44'/60'/{index}'/0/0 - index at position 3
177
+ // - Other paths (bip44: false): {hdPath}/{index} - index at end
178
+ // - BIP44: m/44'/60'/0'/0/{index}
179
+ // - Legacy: m/44'/60'/0'/{index}
180
+ // - Custom paths via setHdPath
181
+ //
182
+ // We use the `bip44` flag to determine which extraction pattern to use.
183
+ if (details.bip44) {
184
+ // Ledger Live format: m/44'/60'/{index}'/0/0
185
+ const match = hdPath.match(LEDGER_LIVE_PATH_PATTERN);
186
+ if (match?.[1]) {
187
+ return parseInt(match[1], 10);
188
+ }
189
+ }
190
+ else {
191
+ // Index-at-end format: m/44'/60'/.../{index}
192
+ const match = hdPath.match(INDEX_AT_END_PATH_PATTERN);
193
+ if (match?.[2]) {
194
+ return parseInt(match[2], 10);
195
+ }
196
+ }
197
+ throw new Error(`Could not extract index from HD path: ${hdPath}`);
198
+ }, _LedgerKeyringV2_createKeyringAccount = function _LedgerKeyringV2_createKeyringAccount(address, addressIndex) {
199
+ const id = this.registry.register(address);
200
+ const checksummedAddress = __classPrivateFieldGet(this, _LedgerKeyringV2_instances, "m", _LedgerKeyringV2_getChecksumHexAddress).call(this, address);
201
+ const details = this.inner.accountDetails[checksummedAddress];
202
+ if (!details?.hdPath) {
203
+ throw new Error(`No HD path found for address ${checksummedAddress}. Cannot create account.`);
204
+ }
205
+ const account = {
206
+ id,
207
+ type: EthAccountType.Eoa,
208
+ address,
209
+ scopes: [...this.capabilities.scopes],
210
+ methods: [...LEDGER_KEYRING_METHODS],
211
+ options: {
212
+ entropy: {
213
+ type: KeyringAccountEntropyTypeOption.Mnemonic,
214
+ id: this.entropySource,
215
+ groupIndex: addressIndex,
216
+ derivationPath: details.hdPath,
217
+ },
218
+ },
219
+ };
220
+ this.registry.set(account);
221
+ return account;
222
+ };
223
+ //# sourceMappingURL=ledger-keyring-v2.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ledger-keyring-v2.mjs","sourceRoot":"","sources":["../src/ledger-keyring-v2.ts"],"names":[],"mappings":";;;;;;AACA,OAAO,EAEL,cAAc,EACd,iBAAiB,EACjB,SAAS,EACT,QAAQ,EAER,+B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,kBAAkB,GAAG,uBAAA,IAAI,0EAAuB,MAA3B,IAAI,EAAwB,OAAO,CAAC,CAAC;IAChE,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,kBAAkB,CAAC,CAAC;IAE9D,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CACb,gCAAgC,kBAAkB,0BAA0B,CAC7E,CAAC;IACJ,CAAC;IAED,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,sBAAsB,CAAC;QACpC,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,OAAO,CAAC,MAAM;aAC/B;SACF;KACF,CAAC;IAEF,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC3B,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { Bip44Account } from '@metamask/account-api';\nimport {\n type CreateAccountOptions,\n EthAccountType,\n EthKeyringWrapper,\n EthMethod,\n EthScope,\n type KeyringAccount,\n KeyringAccountEntropyTypeOption,\n type KeyringCapabilities,\n type KeyringV2,\n KeyringType,\n type EntropySourceId,\n} from '@metamask/keyring-api';\nimport type { AccountId, EthKeyring } from '@metamask/keyring-utils';\nimport { add0x, getChecksumAddress, type Hex } from '@metamask/utils';\n\nimport type { LedgerKeyring } from './ledger-keyring';\n\n/**\n * Methods supported by Ledger keyring EOA accounts.\n * Ledger keyrings support a subset of signing methods (no encryption, app keys, or EIP-7702).\n */\nconst LEDGER_KEYRING_METHODS = [\n EthMethod.SignTransaction,\n EthMethod.PersonalSign,\n EthMethod.SignTypedDataV4,\n];\n\nconst ledgerKeyringV2Capabilities: KeyringCapabilities = {\n scopes: [EthScope.Eoa],\n bip44: {\n deriveIndex: true,\n derivePath: true,\n },\n};\n\n/**\n * Ledger Live HD path constant.\n */\nconst LEDGER_LIVE_HD_PATH = `m/44'/60'/0'/0/0`;\n\n/**\n * BIP-44 standard HD path prefix constant for Ethereum.\n */\nconst BIP44_HD_PATH_PREFIX = `m/44'/60'/0'/0`;\n\n/**\n * Regex pattern for validating and parsing Ledger Live derivation paths.\n * Format: m/44'/60'/{index}'/0/0\n */\nconst LEDGER_LIVE_PATH_PATTERN = /^m\\/44'\\/60'\\/(\\d+)'\\/0\\/0$/u;\n\n/**\n * Regex pattern for validating and parsing non-Ledger-Live derivation paths.\n * Supports Legacy (m/44'/60'/0'/{index}), BIP44 (m/44'/60'/0'/0/{index}),\n * and custom paths that follow the m/44'/60'/... pattern.\n */\nconst INDEX_AT_END_PATH_PATTERN = /^(m\\/44'\\/60'(?:\\/\\d+'?)*)\\/(\\d+)$/u;\n\n/**\n * Concrete {@link KeyringV2} adapter for {@link LedgerKeyring}.\n *\n * This wrapper exposes the accounts and signing capabilities of the legacy\n * Ledger keyring via the unified V2 interface.\n *\n * All Ledger keyring accounts are BIP-44 derived from the device.\n */\nexport type LedgerKeyringV2Options = {\n legacyKeyring: LedgerKeyring;\n entropySource: EntropySourceId;\n};\n\n// LedgerKeyring.signTransaction returns `TypedTransaction | OldEthJsTransaction` for\n// backwards compatibility with old ethereumjs-tx, but EthKeyring expects `TypedTxData`.\n// The runtime behavior is correct - we cast the type to satisfy the constraint.\ntype LedgerKeyringAsEthKeyring = LedgerKeyring & EthKeyring;\n\nexport class LedgerKeyringV2\n extends EthKeyringWrapper<\n LedgerKeyringAsEthKeyring,\n Bip44Account<KeyringAccount>\n >\n implements KeyringV2\n{\n readonly entropySource: EntropySourceId;\n\n constructor(options: LedgerKeyringV2Options) {\n super({\n type: KeyringType.Ledger,\n inner: options.legacyKeyring as LedgerKeyringAsEthKeyring,\n capabilities: ledgerKeyringV2Capabilities,\n });\n this.entropySource = options.entropySource;\n }\n\n /**\n * Normalizes an address to a checksummed hex address.\n *\n * @param address - The address to normalize.\n * @returns The checksummed hex address.\n */\n #getChecksumHexAddress(address: string): Hex {\n return getChecksumAddress(add0x(address));\n }\n\n /**\n * Parses a derivation path to extract the base HD path and account index.\n *\n * Supports two path formats:\n * - Ledger Live: m/44'/60'/{index}'/0/0 → base: m/44'/60'/0'/0/0, index from position 3\n * - Index at end: m/44'/60'/.../{index} → base: m/44'/60'/..., index from last segment\n *\n * @param derivationPath - The full derivation path.\n * @returns The base HD path and account index.\n * @throws If the path format is invalid.\n */\n #parseDerivationPath(derivationPath: string): {\n basePath: string;\n index: number;\n } {\n // Try Ledger Live format first: m/44'/60'/{index}'/0/0\n const ledgerLiveMatch = derivationPath.match(LEDGER_LIVE_PATH_PATTERN);\n if (ledgerLiveMatch?.[1]) {\n return {\n // This constant is used by `inner.setHdPath` to determine which derivation\n // mode we should use (Ledger Live derivation mode here).\n basePath: LEDGER_LIVE_HD_PATH,\n index: parseInt(ledgerLiveMatch[1], 10),\n };\n }\n\n // Try index-at-end format: m/44'/60'/.../{index}\n const indexAtEndMatch = derivationPath.match(INDEX_AT_END_PATH_PATTERN);\n if (indexAtEndMatch) {\n // If the condition is true, indexAtEndMatch[1] and indexAtEndMatch[2] are defined, so\n // we can safely cast them to string.\n // This is necessary to get 100% code coverage.\n return {\n // Here, we use a derivation path prefix for `inner.setHdPath`\n // (prefix + index derivation mode).\n basePath: indexAtEndMatch[1] as string,\n index: parseInt(indexAtEndMatch[2] as string, 10),\n };\n }\n\n throw new Error(\n `Invalid derivation path format: ${derivationPath}. ` +\n `Expected Ledger Live (m/44'/60'/{index}'/0/0) or index-at-end (m/44'/60'/.../{index}) format.`,\n );\n }\n\n /**\n * Gets the index for an address from the account details.\n *\n * @param address - The address to get the index for.\n * @returns The index for the address.\n * @throws If the address is not found in account details.\n */\n #getIndexForAddress(address: Hex): number {\n const checksummedAddress = this.#getChecksumHexAddress(address);\n const details = this.inner.accountDetails[checksummedAddress];\n\n if (!details) {\n throw new Error(\n `Address ${checksummedAddress} not found in account details`,\n );\n }\n\n // Extract index from hdPath\n const { hdPath } = details;\n if (!hdPath) {\n throw new Error(`No HD path found for address ${checksummedAddress}`);\n }\n\n // Ledger supports multiple derivation path formats:\n // - Ledger Live (bip44: true): m/44'/60'/{index}'/0/0 - index at position 3\n // - Other paths (bip44: false): {hdPath}/{index} - index at end\n // - BIP44: m/44'/60'/0'/0/{index}\n // - Legacy: m/44'/60'/0'/{index}\n // - Custom paths via setHdPath\n //\n // We use the `bip44` flag to determine which extraction pattern to use.\n if (details.bip44) {\n // Ledger Live format: m/44'/60'/{index}'/0/0\n const match = hdPath.match(LEDGER_LIVE_PATH_PATTERN);\n if (match?.[1]) {\n return parseInt(match[1], 10);\n }\n } else {\n // Index-at-end format: m/44'/60'/.../{index}\n const match = hdPath.match(INDEX_AT_END_PATH_PATTERN);\n if (match?.[2]) {\n return parseInt(match[2], 10);\n }\n }\n\n throw new Error(`Could not extract index from HD path: ${hdPath}`);\n }\n\n /**\n * Creates a Bip44Account object for the given address.\n *\n * @param address - The account address.\n * @param addressIndex - The account index in the derivation path.\n * @returns The created Bip44Account.\n */\n #createKeyringAccount(\n address: Hex,\n addressIndex: number,\n ): Bip44Account<KeyringAccount> {\n const id = this.registry.register(address);\n\n const checksummedAddress = this.#getChecksumHexAddress(address);\n const details = this.inner.accountDetails[checksummedAddress];\n\n if (!details?.hdPath) {\n throw new Error(\n `No HD path found for address ${checksummedAddress}. Cannot create account.`,\n );\n }\n\n const account: Bip44Account<KeyringAccount> = {\n id,\n type: EthAccountType.Eoa,\n address,\n scopes: [...this.capabilities.scopes],\n methods: [...LEDGER_KEYRING_METHODS],\n options: {\n entropy: {\n type: KeyringAccountEntropyTypeOption.Mnemonic,\n id: this.entropySource,\n groupIndex: addressIndex,\n derivationPath: details.hdPath,\n },\n },\n };\n\n this.registry.set(account);\n return account;\n }\n\n async getAccounts(): Promise<Bip44Account<KeyringAccount>[]> {\n const addresses = await this.inner.getAccounts();\n\n if (addresses.length === 0) {\n return [];\n }\n\n return addresses.map((address) => {\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 const addressIndex = this.#getIndexForAddress(address);\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 if (\n options.type === 'bip44:derive-path' ||\n options.type === 'bip44:derive-index'\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 } else {\n throw new Error(\n `Unsupported account creation type for LedgerKeyring: ${String(\n options.type,\n )}`,\n );\n }\n\n // Check if an account at this index already exists with the same derivation path\n const currentAccounts = await this.getAccounts();\n\n let targetIndex: number;\n let basePath: string;\n let derivationPath: string;\n\n if (options.type === 'bip44:derive-path') {\n // Parse the derivation path to extract base path and index\n const parsed = this.#parseDerivationPath(options.derivationPath);\n targetIndex = parsed.index;\n basePath = parsed.basePath;\n\n derivationPath = options.derivationPath;\n } else {\n // derive-index uses BIP-44 standard path by default\n targetIndex = options.groupIndex;\n basePath = BIP44_HD_PATH_PREFIX;\n derivationPath = `${basePath}/${targetIndex}`;\n }\n\n const existingAccount = currentAccounts.find((account) => {\n return (\n account.options.entropy.groupIndex === targetIndex &&\n account.options.entropy.derivationPath === derivationPath\n );\n });\n\n if (existingAccount) {\n return [existingAccount];\n }\n\n // Derive the account at the specified index\n this.inner.setHdPath(basePath);\n this.inner.setAccountToUnlock(targetIndex);\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 * @param accountId - The account ID to delete.\n */\n async deleteAccount(accountId: AccountId): Promise<void> {\n await this.withLock(async () => {\n const { address } = await this.getAccount(accountId);\n const hexAddress = this.toHexAddress(address);\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"]}
@@ -7,7 +7,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
7
7
  var __importDefault = (this && this.__importDefault) || function (mod) {
8
8
  return (mod && mod.__esModule) ? mod : { "default": mod };
9
9
  };
10
- var _LedgerKeyring_instances, _LedgerKeyring_migrateAccountDetails, _LedgerKeyring_signTransaction, _LedgerKeyring_getPage, _LedgerKeyring_getAccountsBIP44, _LedgerKeyring_getAccountsLegacy, _LedgerKeyring_addressFromIndex, _LedgerKeyring_pathFromAddress, _LedgerKeyring_getPathForIndex, _LedgerKeyring_isLedgerLiveHdPath, _LedgerKeyring_toLedgerPath, _LedgerKeyring_hasPreviousTransactions, _LedgerKeyring_getApiUrl, _LedgerKeyring_getChecksumHexAddress;
10
+ var _LedgerKeyring_instances, _LedgerKeyring_migrateAccountDetails, _LedgerKeyring_signTransaction, _LedgerKeyring_getPage, _LedgerKeyring_getAccountsBIP44, _LedgerKeyring_getAccountsLegacy, _LedgerKeyring_addressFromIndex, _LedgerKeyring_pathFromAddress, _LedgerKeyring_getPathForIndex, _LedgerKeyring_isLedgerLiveHdPath, _LedgerKeyring_toLedgerPath, _LedgerKeyring_hasPreviousTransactions, _LedgerKeyring_getApiUrl, _LedgerKeyring_getChecksumHexAddress, _LedgerKeyring_normalizeRecoveryParam;
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.LedgerKeyring = void 0;
13
13
  const rlp_1 = require("@ethereumjs/rlp");
@@ -278,10 +278,7 @@ class LedgerKeyring {
278
278
  catch (error) {
279
279
  (0, ledger_error_handler_1.handleLedgerTransportError)(error, 'Ledger: Unknown error while signing message');
280
280
  }
281
- let modifiedV = parseInt(String(payload.v), 10).toString(16);
282
- if (modifiedV.length < 2) {
283
- modifiedV = `0${modifiedV}`;
284
- }
281
+ const modifiedV = __classPrivateFieldGet(this, _LedgerKeyring_instances, "m", _LedgerKeyring_normalizeRecoveryParam).call(this, parseInt(String(payload.v), 10));
285
282
  const signature = `0x${payload.r}${payload.s}${modifiedV}`;
286
283
  const addressSignedWith = (0, eth_sig_util_1.recoverPersonalSignature)({
287
284
  data: message,
@@ -342,10 +339,7 @@ class LedgerKeyring {
342
339
  catch (error) {
343
340
  (0, ledger_error_handler_1.handleLedgerTransportError)(error, 'Ledger: Unknown error while signing message');
344
341
  }
345
- let recoveryId = parseInt(String(payload.v), 10).toString(16);
346
- if (recoveryId.length < 2) {
347
- recoveryId = `0${recoveryId}`;
348
- }
342
+ const recoveryId = __classPrivateFieldGet(this, _LedgerKeyring_instances, "m", _LedgerKeyring_normalizeRecoveryParam).call(this, parseInt(String(payload.v), 10));
349
343
  const signature = `0x${payload.r}${payload.s}${recoveryId}`;
350
344
  const addressSignedWith = (0, eth_sig_util_1.recoverTypedSignature)({
351
345
  data,
@@ -501,6 +495,11 @@ async function _LedgerKeyring_getPage(increment) {
501
495
  return this.network;
502
496
  }, _LedgerKeyring_getChecksumHexAddress = function _LedgerKeyring_getChecksumHexAddress(address) {
503
497
  return (0, utils_1.getChecksumAddress)((0, utils_1.add0x)(address));
498
+ }, _LedgerKeyring_normalizeRecoveryParam = function _LedgerKeyring_normalizeRecoveryParam(recoveryParam) {
499
+ if (recoveryParam === 0 || recoveryParam === 1) {
500
+ return (recoveryParam + 27).toString(16);
501
+ }
502
+ return recoveryParam.toString(16);
504
503
  };
505
504
  LedgerKeyring.type = keyringType;
506
505
  //# sourceMappingURL=ledger-keyring.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ledger-keyring.cjs","sourceRoot":"","sources":["../src/ledger-ke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Q,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;AAC3C,CAAC,2CAED,KAAK,iDAA0B,OAAe;IAC5C,MAAM,MAAM,GAAG,uBAAA,IAAI,0DAAW,MAAf,IAAI,CAAa,CAAC;IACjC,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,KAAK,CACjC,GAAG,MAAM,6CAA6C,OAAO,6BAA6B,CAC3F,CAAC;IACF,MAAM,cAAc,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;IAC7C,OAAO,cAAc,CAAC,MAAM,KAAK,GAAG,IAAI,cAAc,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;AAC3E,CAAC;IAGC,OAAO,IAAI,CAAC,OAAO,CAAC;AACtB,CAAC,uFAEsB,OAAe;IACpC,OAAO,IAAA,0BAAkB,EAAC,IAAA,aAAK,EAAC,OAAO,CAAC,CAAC,CAAC;AAC5C,CAAC;AA7lBM,kBAAI,GAAW,WAAW,AAAtB,CAAuB","sourcesContent":["import { RLP } from '@ethereumjs/rlp';\nimport {\n TransactionFactory,\n TypedTxData,\n type TypedTransaction,\n} from '@ethereumjs/tx';\nimport { publicToAddress } from '@ethereumjs/util';\nimport type { MessageTypes, TypedMessage } from '@metamask/eth-sig-util';\nimport {\n recoverPersonalSignature,\n recoverTypedSignature,\n SignTypedDataVersion,\n TypedDataUtils,\n} from '@metamask/eth-sig-util';\nimport type { Keyring } from '@metamask/keyring-utils';\nimport {\n add0x,\n bytesToHex,\n getChecksumAddress,\n Hex,\n remove0x,\n} from '@metamask/utils';\nimport { Buffer } from 'buffer';\nimport type OldEthJsTransaction from 'ethereumjs-tx';\nimport HDKey from 'hdkey';\n\nimport { LedgerBridge, LedgerBridgeOptions } from './ledger-bridge';\nimport { handleLedgerTransportError } from './ledger-error-handler';\nimport { LedgerIframeBridgeOptions } from './ledger-iframe-bridge';\n\nconst pathBase = 'm';\nconst hdPathString = `${pathBase}/44'/60'/0'`;\nconst keyringType = 'Ledger Hardware';\n\n// This number causes one of our failing tests to run very slowly, as the for loop needs to iterate 1000 times.\nconst MAX_INDEX = 1000;\n\nenum NetworkApiUrls {\n Ropsten = 'https://api-ropsten.etherscan.io',\n Kovan = 'https://api-kovan.etherscan.io',\n Rinkeby = 'https://api-rinkeby.etherscan.io',\n Mainnet = `https://api.etherscan.io`,\n}\n\ntype SignTransactionPayload = Awaited<\n ReturnType<LedgerBridge<LedgerIframeBridgeOptions>['deviceSignTransaction']>\n>;\n\nexport type AccountPageEntry = {\n address: string;\n balance: number | null;\n index: number;\n};\n\nexport type AccountPage = AccountPageEntry[];\n\nexport type AccountDetails = {\n index?: number;\n bip44?: boolean;\n hdPath?: string;\n};\n\nexport type LedgerBridgeKeyringOptions = {\n hdPath: string;\n accounts: Hex[];\n deviceId: string;\n accountDetails: Readonly<Record<Hex, AccountDetails>>;\n accountIndexes: Readonly<Record<Hex, number>>;\n implementFullBIP44: boolean;\n};\n\nexport type LedgerKeyringSerializedState = Partial<LedgerBridgeKeyringOptions>;\n\n/**\n * Check if the given transaction is made with ethereumjs-tx or @ethereumjs/tx\n *\n * Transactions built with older versions of ethereumjs-tx have a\n * getChainId method that newer versions do not.\n * Older versions are mutable\n * while newer versions default to being immutable.\n * Expected shape and type\n * of data for v, r and s differ (Buffer (old) vs BN (new)).\n *\n * @param tx - Transaction to check, instance of either ethereumjs-tx or @ethereumjs/tx.\n * @returns Returns `true` if tx is an old-style ethereumjs-tx transaction.\n */\nfunction isOldStyleEthereumjsTx(\n tx: TypedTransaction | OldEthJsTransaction,\n): tx is OldEthJsTransaction {\n return 'getChainId' in tx && typeof tx.getChainId === 'function';\n}\n\nexport class LedgerKeyring implements Keyring {\n static type: string = keyringType;\n\n deviceId = '';\n\n readonly type: string = keyringType;\n\n page = 0;\n\n perPage = 5;\n\n unlockedAccount = 0;\n\n accounts: readonly Hex[] = [];\n\n accountDetails: Record<string, AccountDetails> = {};\n\n hdk = new HDKey();\n\n hdPath = hdPathString;\n\n paths: Record<string, number> = {};\n\n network: NetworkApiUrls = NetworkApiUrls.Mainnet;\n\n implementFullBIP44 = false;\n\n bridge: LedgerBridge<LedgerBridgeOptions>;\n\n constructor({ bridge }: { bridge: LedgerBridge<LedgerBridgeOptions> }) {\n if (!bridge) {\n throw new Error('Bridge is a required dependency for the keyring');\n }\n\n this.bridge = bridge;\n }\n\n async init(): Promise<void> {\n return this.bridge.init();\n }\n\n async destroy(): Promise<void> {\n return this.bridge.destroy();\n }\n\n async serialize(): Promise<\n Omit<LedgerKeyringSerializedState, 'accountIndexes'>\n > {\n return {\n hdPath: this.hdPath,\n accounts: this.accounts.slice(),\n deviceId: this.deviceId,\n accountDetails: this.accountDetails,\n implementFullBIP44: false,\n };\n }\n\n async deserialize(opts: LedgerKeyringSerializedState): Promise<void> {\n this.hdPath = opts.hdPath ?? hdPathString;\n this.accounts = opts.accounts ?? [];\n this.deviceId = opts.deviceId ?? '';\n this.accountDetails = opts.accountDetails ?? {};\n\n if (!opts.accountDetails) {\n this.#migrateAccountDetails(opts);\n }\n\n this.implementFullBIP44 = opts.implementFullBIP44 ?? false;\n\n const keys = new Set<string>(Object.keys(this.accountDetails));\n // Remove accounts that don't have corresponding account details\n this.accounts = this.accounts.filter((account) =>\n keys.has(this.#getChecksumHexAddress(account)),\n );\n\n return Promise.resolve();\n }\n\n public setDeviceId(deviceId: string): void {\n this.deviceId = deviceId;\n }\n\n public getDeviceId(): string {\n return this.deviceId;\n }\n\n #migrateAccountDetails(opts: Partial<LedgerBridgeKeyringOptions>): void {\n if (this.#isLedgerLiveHdPath() && opts.accountIndexes) {\n for (const [account, index] of Object.entries(opts.accountIndexes)) {\n this.accountDetails[account] = {\n bip44: true,\n hdPath: this.#getPathForIndex(index),\n };\n }\n }\n const keys = new Set<string>(Object.keys(this.accountDetails));\n // try to migrate non-LedgerLive accounts too\n if (!this.#isLedgerLiveHdPath()) {\n this.accounts.forEach((account) => {\n const key = this.#getChecksumHexAddress(account);\n\n if (!keys.has(key)) {\n this.accountDetails[key] = {\n bip44: false,\n hdPath: this.#pathFromAddress(account),\n };\n }\n });\n }\n }\n\n isUnlocked(): boolean {\n return Boolean(this.hdk.publicKey);\n }\n\n isConnected(): boolean {\n return this.bridge.isDeviceConnected;\n }\n\n setAccountToUnlock(index: number): void {\n this.unlockedAccount = index;\n }\n\n setHdPath(hdPath: string): void {\n // Reset HDKey if the path changes\n if (this.hdPath !== hdPath) {\n this.hdk = new HDKey();\n }\n this.hdPath = hdPath;\n }\n\n async unlock(hdPath?: string, updateHdk = true): Promise<Hex> {\n if (this.isUnlocked() && !hdPath) {\n // if the device is already unlocked and no path is provided,\n // we return the checksummed address of the public key stored in\n // `this.hdk`, which is the root address of the last unlocked path.\n return this.#getChecksumHexAddress(\n bytesToHex(publicToAddress(this.hdk.publicKey, true)),\n );\n }\n const path = hdPath ? this.#toLedgerPath(hdPath) : this.hdPath;\n\n let payload;\n try {\n payload = await this.bridge.getPublicKey({\n hdPath: path,\n });\n } catch (error: unknown) {\n handleLedgerTransportError(\n error,\n 'Ledger: Unknown error while unlocking account',\n );\n }\n\n if (updateHdk && payload.chainCode) {\n this.hdk.publicKey = Buffer.from(payload.publicKey, 'hex');\n this.hdk.chainCode = Buffer.from(payload.chainCode, 'hex');\n }\n\n return add0x(payload.address);\n }\n\n async addAccounts(amount: number): Promise<Hex[]> {\n return new Promise((resolve, reject) => {\n this.unlock()\n .then(async (_) => {\n const from = this.unlockedAccount;\n const to = from + amount;\n const newAccounts: Hex[] = [];\n for (let i = from; i < to; i++) {\n const path = this.#getPathForIndex(i);\n let address: Hex;\n if (this.#isLedgerLiveHdPath()) {\n address = await this.unlock(path);\n } else {\n address = this.#addressFromIndex(pathBase, i);\n }\n\n this.accountDetails[this.#getChecksumHexAddress(address)] = {\n // TODO: consider renaming this property, as the current name is misleading\n // It's currently used to represent whether an account uses the Ledger Live path.\n bip44: this.#isLedgerLiveHdPath(),\n hdPath: path,\n };\n\n if (!this.accounts.includes(address)) {\n this.accounts = [...this.accounts, address];\n newAccounts.push(address);\n }\n this.page = 0;\n }\n resolve(newAccounts);\n })\n .catch(reject);\n });\n }\n\n getName(): string {\n return keyringType;\n }\n\n async getFirstPage(): Promise<AccountPage> {\n this.page = 0;\n return this.#getPage(1);\n }\n\n async getNextPage(): Promise<AccountPage> {\n return this.#getPage(1);\n }\n\n async getPreviousPage(): Promise<AccountPage> {\n return this.#getPage(-1);\n }\n\n async getAccounts(): Promise<Hex[]> {\n return Promise.resolve(this.accounts.slice());\n }\n\n removeAccount(address: string): void {\n const filteredAccounts = this.accounts.filter(\n (a) => a.toLowerCase() !== address.toLowerCase(),\n );\n\n if (filteredAccounts.length === this.accounts.length) {\n throw new Error(`Address ${address} not found in this keyring`);\n }\n\n this.accounts = filteredAccounts;\n delete this.accountDetails[this.#getChecksumHexAddress(address)];\n }\n\n async attemptMakeApp(): Promise<boolean> {\n return this.bridge.attemptMakeApp();\n }\n\n async updateTransportMethod(transportType: string): Promise<boolean> {\n return this.bridge.updateTransportMethod(transportType);\n }\n\n // tx is an instance of the ethereumjs-transaction class.\n async signTransaction(\n address: Hex,\n tx: TypedTransaction | OldEthJsTransaction,\n ): Promise<TypedTransaction | OldEthJsTransaction> {\n let rawTxHex;\n // transactions built with older versions of ethereumjs-tx have a\n // getChainId method that newer versions do not. Older versions are mutable\n // while newer versions default to being immutable. Expected shape and type\n // of data for v, r and s differ (Buffer (old) vs BN (new))\n if (isOldStyleEthereumjsTx(tx)) {\n // In this version of ethereumjs-tx we must add the chainId in hex format\n // to the initial v value. The chainId must be included in the serialized\n // transaction which is only communicated to ethereumjs-tx in this\n // value. In newer versions the chainId is communicated via the 'Common'\n // object.\n tx.v = tx.getChainId();\n // @ts-expect-error tx.r should be a Buffer, but we are assigning a string\n tx.r = '0x00';\n // @ts-expect-error tx.s should be a Buffer, but we are assigning a string\n tx.s = '0x00';\n\n rawTxHex = tx.serialize().toString('hex');\n\n return this.#signTransaction(address, rawTxHex, (payload) => {\n tx.v = Buffer.from(payload.v, 'hex');\n tx.r = Buffer.from(payload.r, 'hex');\n tx.s = Buffer.from(payload.s, 'hex');\n return tx;\n });\n }\n\n // The below `encode` call is only necessary for legacy transactions, as `getMessageToSign`\n // calls `rlp.encode` internally for non-legacy transactions. As per the \"Transaction Execution\"\n // section of the ethereum yellow paper, transactions need to be \"well-formed RLP, with no additional\n // trailing bytes\".\n\n // Note also that `getMessageToSign` will return valid RLP for all transaction types, whereas the\n // `serialize` method will not for any transaction type except legacy. This is because `serialize` includes\n // empty r, s and v values in the encoded rlp. This is why we use `getMessageToSign` here instead of `serialize`.\n const messageToSign = tx.getMessageToSign();\n\n rawTxHex = Array.isArray(messageToSign)\n ? Buffer.from(RLP.encode(messageToSign)).toString('hex')\n : bytesToHex(messageToSign);\n\n return this.#signTransaction(address, rawTxHex, (payload) => {\n // Because tx will be immutable, first get a plain javascript object that\n // represents the transaction. Using txData here as it aligns with the\n // nomenclature of ethereumjs/tx.\n const txData: TypedTxData = tx.toJSON();\n // The fromTxData utility expects a type to support transactions with a type other than 0\n txData.type = tx.type;\n // The fromTxData utility expects v,r and s to be hex prefixed\n txData.v = add0x(payload.v);\n txData.r = add0x(payload.r);\n txData.s = add0x(payload.s);\n // Adopt the 'common' option from the original transaction and set the\n // returned object to be frozen if the original is frozen.\n return TransactionFactory.fromTxData(txData, {\n common: tx.common,\n freeze: Object.isFrozen(tx),\n });\n });\n }\n\n async #signTransaction(\n address: Hex,\n rawTxHex: string,\n handleSigning: (\n payload: SignTransactionPayload,\n ) => TypedTransaction | OldEthJsTransaction,\n ): Promise<TypedTransaction | OldEthJsTransaction> {\n const hdPath = await this.unlockAccountByAddress(address);\n\n if (!hdPath) {\n throw new Error('Ledger: hdPath is empty while signing transaction');\n }\n\n let payload;\n\n try {\n payload = await this.bridge.deviceSignTransaction({\n tx: remove0x(rawTxHex),\n hdPath,\n });\n } catch (error: unknown) {\n handleLedgerTransportError(\n error,\n 'Ledger: Unknown error while signing transaction',\n );\n }\n\n const newOrMutatedTx = handleSigning(payload);\n const valid = newOrMutatedTx.verifySignature();\n if (valid) {\n return newOrMutatedTx;\n }\n throw new Error('Ledger: The transaction signature is not valid');\n }\n\n async signMessage(withAccount: Hex, data: string): Promise<string> {\n return this.signPersonalMessage(withAccount, data);\n }\n\n // For personal_sign, we need to prefix the message:\n async signPersonalMessage(\n withAccount: Hex,\n message: string,\n ): Promise<string> {\n const hdPath = await this.unlockAccountByAddress(withAccount);\n\n if (!hdPath) {\n throw new Error('Ledger: Unknown error while signing message');\n }\n\n let payload;\n try {\n payload = await this.bridge.deviceSignMessage({\n hdPath,\n message: remove0x(message),\n });\n } catch (error: unknown) {\n handleLedgerTransportError(\n error,\n 'Ledger: Unknown error while signing message',\n );\n }\n\n let modifiedV = parseInt(String(payload.v), 10).toString(16);\n if (modifiedV.length < 2) {\n modifiedV = `0${modifiedV}`;\n }\n\n const signature = `0x${payload.r}${payload.s}${modifiedV}`;\n const addressSignedWith = recoverPersonalSignature({\n data: message,\n signature,\n });\n if (\n this.#getChecksumHexAddress(addressSignedWith) !==\n this.#getChecksumHexAddress(withAccount)\n ) {\n throw new Error('Ledger: The signature doesnt match the right address');\n }\n return signature;\n }\n\n async unlockAccountByAddress(address: Hex): Promise<string | undefined> {\n const checksummedAddress = this.#getChecksumHexAddress(address);\n const accountDetails = this.accountDetails[checksummedAddress];\n if (!accountDetails) {\n throw new Error(\n `Ledger: Account for address '${checksummedAddress}' not found`,\n );\n }\n const { hdPath } = accountDetails;\n const unlockedAddress = await this.unlock(hdPath, false);\n\n // unlock resolves to the address for the given hdPath as reported by the ledger device\n // if that address is not the requested address, then this account belongs to a different device or seed\n if (unlockedAddress.toLowerCase() !== address.toLowerCase()) {\n throw new Error(\n `Ledger: Account ${address} does not belong to the connected device`,\n );\n }\n return hdPath;\n }\n\n async signTypedData<\n Version extends SignTypedDataVersion.V4,\n Types extends MessageTypes,\n Options extends { version?: Version },\n >(\n withAccount: Hex,\n data: TypedMessage<Types>,\n options?: Options,\n ): Promise<string> {\n const { version } = options ?? {};\n const isV4 = version === 'V4';\n if (!isV4) {\n throw new Error(\n 'Ledger: Only version 4 of typed data signing is supported',\n );\n }\n\n const { domain, types, primaryType, message } =\n TypedDataUtils.sanitizeData(data);\n\n const hdPath = await this.unlockAccountByAddress(withAccount);\n\n if (!hdPath) {\n throw new Error('Ledger: Unknown error while signing message');\n }\n\n let payload;\n try {\n payload = await this.bridge.deviceSignTypedData({\n hdPath,\n message: {\n domain: {\n name: domain.name,\n chainId: domain.chainId,\n version: domain.version,\n verifyingContract: domain.verifyingContract,\n salt:\n domain.salt instanceof ArrayBuffer\n ? Buffer.from(domain.salt).toString('hex')\n : domain.salt,\n },\n types,\n primaryType: primaryType.toString(),\n message,\n },\n });\n } catch (error: unknown) {\n handleLedgerTransportError(\n error,\n 'Ledger: Unknown error while signing message',\n );\n }\n\n let recoveryId = parseInt(String(payload.v), 10).toString(16);\n if (recoveryId.length < 2) {\n recoveryId = `0${recoveryId}`;\n }\n const signature = `0x${payload.r}${payload.s}${recoveryId}`;\n const addressSignedWith = recoverTypedSignature({\n data,\n signature,\n version: SignTypedDataVersion.V4,\n });\n\n if (\n this.#getChecksumHexAddress(addressSignedWith) !==\n this.#getChecksumHexAddress(withAccount)\n ) {\n throw new Error('Ledger: The signature doesnt match the right address');\n }\n return signature;\n }\n\n forgetDevice(): void {\n this.deviceId = '';\n this.accounts = [];\n this.page = 0;\n this.unlockedAccount = 0;\n this.paths = {};\n this.accountDetails = {};\n this.hdk = new HDKey();\n }\n\n /* PRIVATE METHODS */\n async #getPage(increment: number): Promise<AccountPage> {\n this.page += increment;\n\n if (this.page <= 0) {\n this.page = 1;\n }\n const from = (this.page - 1) * this.perPage;\n const to = from + this.perPage;\n\n await this.unlock();\n let accounts;\n if (this.#isLedgerLiveHdPath()) {\n accounts = await this.#getAccountsBIP44(from, to);\n } else {\n accounts = this.#getAccountsLegacy(from, to);\n }\n return accounts;\n }\n\n async #getAccountsBIP44(from: number, to: number): Promise<AccountPage> {\n const accounts: AccountPage = [];\n\n for (let i = from; i < to; i++) {\n const path = this.#getPathForIndex(i);\n const address = await this.unlock(path);\n const valid = this.implementFullBIP44\n ? await this.#hasPreviousTransactions(address)\n : true;\n accounts.push({\n address,\n balance: null,\n index: i,\n });\n\n // PER BIP44\n // \"Software should prevent a creation of an account if\n // a previous account does not have a transaction history\n // (meaning none of its addresses have been used before).\"\n if (!valid) {\n break;\n }\n }\n return accounts;\n }\n\n #getAccountsLegacy(from: number, to: number): AccountPage {\n const accounts: AccountPage = [];\n\n for (let i = from; i < to; i++) {\n const address = this.#addressFromIndex(pathBase, i);\n accounts.push({\n address,\n balance: null,\n index: i,\n });\n this.paths[this.#getChecksumHexAddress(address)] = i;\n }\n return accounts;\n }\n\n #addressFromIndex(basePath: string, i: number): Hex {\n const dkey = this.hdk.derive(`${basePath}/${i}`);\n const address = bytesToHex(publicToAddress(dkey.publicKey, true));\n return this.#getChecksumHexAddress(address);\n }\n\n #pathFromAddress(address: string): string {\n const checksummedAddress = this.#getChecksumHexAddress(address);\n let index = this.paths[checksummedAddress];\n if (typeof index === 'undefined') {\n for (let i = 0; i < MAX_INDEX; i++) {\n if (checksummedAddress === this.#addressFromIndex(pathBase, i)) {\n index = i;\n break;\n }\n }\n }\n\n if (typeof index === 'undefined') {\n throw new Error('Unknown address');\n }\n return this.#getPathForIndex(index);\n }\n\n #getPathForIndex(index: number): string {\n // Check if the path is BIP 44 (Ledger Live)\n return this.#isLedgerLiveHdPath()\n ? `m/44'/60'/${index}'/0/0`\n : `${this.hdPath}/${index}`;\n }\n\n #isLedgerLiveHdPath(): boolean {\n return this.hdPath === `m/44'/60'/0'/0/0`;\n }\n\n #toLedgerPath(path: string): string {\n return path.toString().replace('m/', '');\n }\n\n async #hasPreviousTransactions(address: string): Promise<boolean> {\n const apiUrl = this.#getApiUrl();\n const response = await window.fetch(\n `${apiUrl}/api?module=account&action=txlist&address=${address}&tag=latest&page=1&offset=1`,\n );\n const parsedResponse = await response.json();\n return parsedResponse.status !== '0' && parsedResponse.result.length > 0;\n }\n\n #getApiUrl(): NetworkApiUrls {\n return this.network;\n }\n\n #getChecksumHexAddress(address: string): Hex {\n return getChecksumAddress(add0x(address));\n }\n}\n"]}
1
+ {"version":3,"file":"ledger-keyring.cjs","sourceRoot":"","sources":["../src/ledger-keyring.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,yCAAsC;AACtC,uCAIwB;AACxB,2CAAmD;AAEnD,yDAKgC;AAEhC,2CAMyB;AACzB,mCAAgC;AAEhC,kDAA0B;AAG1B,qEAAoE;AAGpE,MAAM,QAAQ,GAAG,GAAG,CAAC;AACrB,MAAM,YAAY,GAAG,GAAG,QAAQ,aAAa,CAAC;AAC9C,MAAM,WAAW,GAAG,iBAAiB,CAAC;AAEtC,+GAA+G;AAC/G,MAAM,SAAS,GAAG,IAAI,CAAC;AAEvB,IAAK,cAKJ;AALD,WAAK,cAAc;IACjB,8DAA4C,CAAA;IAC5C,0DAAwC,CAAA;IACxC,8DAA4C,CAAA;IAC5C,sDAAoC,CAAA;AACtC,CAAC,EALI,cAAc,KAAd,cAAc,QAKlB;AA+BD;;;;;;;;;;;;GAYG;AACH,SAAS,sBAAsB,CAC7B,EAA0C;IAE1C,OAAO,YAAY,IAAI,EAAE,IAAI,OAAO,EAAE,CAAC,UAAU,KAAK,UAAU,CAAC;AACnE,CAAC;AAED,MAAa,aAAa;IA6BxB,YAAY,EAAE,MAAM,EAAiD;;QA1BrE,aAAQ,GAAG,EAAE,CAAC;QAEL,SAAI,GAAW,WAAW,CAAC;QAEpC,SAAI,GAAG,CAAC,CAAC;QAET,YAAO,GAAG,CAAC,CAAC;QAEZ,oBAAe,GAAG,CAAC,CAAC;QAEpB,aAAQ,GAAmB,EAAE,CAAC;QAE9B,mBAAc,GAAmC,EAAE,CAAC;QAEpD,QAAG,GAAG,IAAI,eAAK,EAAE,CAAC;QAElB,WAAM,GAAG,YAAY,CAAC;QAEtB,UAAK,GAA2B,EAAE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IAAI,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;AAC3C,CAAC,2CAED,KAAK,iDAA0B,OAAe;IAC5C,MAAM,MAAM,GAAG,uBAAA,IAAI,0DAAW,MAAf,IAAI,CAAa,CAAC;IACjC,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,KAAK,CACjC,GAAG,MAAM,6CAA6C,OAAO,6BAA6B,CAC3F,CAAC;IACF,MAAM,cAAc,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;IAC7C,OAAO,cAAc,CAAC,MAAM,KAAK,GAAG,IAAI,cAAc,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;AAC3E,CAAC;IAGC,OAAO,IAAI,CAAC,OAAO,CAAC;AACtB,CAAC,uFAEsB,OAAe;IACpC,OAAO,IAAA,0BAAkB,EAAC,IAAA,aAAK,EAAC,OAAO,CAAC,CAAC,CAAC;AAC5C,CAAC,yFAUuB,aAAqB;IAC3C,IAAI,aAAa,KAAK,CAAC,IAAI,aAAa,KAAK,CAAC,EAAE,CAAC;QAC/C,OAAO,CAAC,aAAa,GAAG,EAAE,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IAC3C,CAAC;IACD,OAAO,aAAa,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;AACpC,CAAC;AA1mBM,kBAAI,GAAW,WAAW,AAAtB,CAAuB","sourcesContent":["import { RLP } from '@ethereumjs/rlp';\nimport {\n TransactionFactory,\n TypedTxData,\n type TypedTransaction,\n} from '@ethereumjs/tx';\nimport { publicToAddress } from '@ethereumjs/util';\nimport type { MessageTypes, TypedMessage } from '@metamask/eth-sig-util';\nimport {\n recoverPersonalSignature,\n recoverTypedSignature,\n SignTypedDataVersion,\n TypedDataUtils,\n} from '@metamask/eth-sig-util';\nimport type { Keyring } from '@metamask/keyring-utils';\nimport {\n add0x,\n bytesToHex,\n getChecksumAddress,\n Hex,\n remove0x,\n} from '@metamask/utils';\nimport { Buffer } from 'buffer';\nimport type OldEthJsTransaction from 'ethereumjs-tx';\nimport HDKey from 'hdkey';\n\nimport { LedgerBridge, LedgerBridgeOptions } from './ledger-bridge';\nimport { handleLedgerTransportError } from './ledger-error-handler';\nimport { LedgerIframeBridgeOptions } from './ledger-iframe-bridge';\n\nconst pathBase = 'm';\nconst hdPathString = `${pathBase}/44'/60'/0'`;\nconst keyringType = 'Ledger Hardware';\n\n// This number causes one of our failing tests to run very slowly, as the for loop needs to iterate 1000 times.\nconst MAX_INDEX = 1000;\n\nenum NetworkApiUrls {\n Ropsten = 'https://api-ropsten.etherscan.io',\n Kovan = 'https://api-kovan.etherscan.io',\n Rinkeby = 'https://api-rinkeby.etherscan.io',\n Mainnet = `https://api.etherscan.io`,\n}\n\ntype SignTransactionPayload = Awaited<\n ReturnType<LedgerBridge<LedgerIframeBridgeOptions>['deviceSignTransaction']>\n>;\n\nexport type AccountPageEntry = {\n address: string;\n balance: number | null;\n index: number;\n};\n\nexport type AccountPage = AccountPageEntry[];\n\nexport type AccountDetails = {\n index?: number;\n bip44?: boolean;\n hdPath?: string;\n};\n\nexport type LedgerBridgeKeyringOptions = {\n hdPath: string;\n accounts: Hex[];\n deviceId: string;\n accountDetails: Readonly<Record<Hex, AccountDetails>>;\n accountIndexes: Readonly<Record<Hex, number>>;\n implementFullBIP44: boolean;\n};\n\nexport type LedgerKeyringSerializedState = Partial<LedgerBridgeKeyringOptions>;\n\n/**\n * Check if the given transaction is made with ethereumjs-tx or @ethereumjs/tx\n *\n * Transactions built with older versions of ethereumjs-tx have a\n * getChainId method that newer versions do not.\n * Older versions are mutable\n * while newer versions default to being immutable.\n * Expected shape and type\n * of data for v, r and s differ (Buffer (old) vs BN (new)).\n *\n * @param tx - Transaction to check, instance of either ethereumjs-tx or @ethereumjs/tx.\n * @returns Returns `true` if tx is an old-style ethereumjs-tx transaction.\n */\nfunction isOldStyleEthereumjsTx(\n tx: TypedTransaction | OldEthJsTransaction,\n): tx is OldEthJsTransaction {\n return 'getChainId' in tx && typeof tx.getChainId === 'function';\n}\n\nexport class LedgerKeyring implements Keyring {\n static type: string = keyringType;\n\n deviceId = '';\n\n readonly type: string = keyringType;\n\n page = 0;\n\n perPage = 5;\n\n unlockedAccount = 0;\n\n accounts: readonly Hex[] = [];\n\n accountDetails: Record<string, AccountDetails> = {};\n\n hdk = new HDKey();\n\n hdPath = hdPathString;\n\n paths: Record<string, number> = {};\n\n network: NetworkApiUrls = NetworkApiUrls.Mainnet;\n\n implementFullBIP44 = false;\n\n bridge: LedgerBridge<LedgerBridgeOptions>;\n\n constructor({ bridge }: { bridge: LedgerBridge<LedgerBridgeOptions> }) {\n if (!bridge) {\n throw new Error('Bridge is a required dependency for the keyring');\n }\n\n this.bridge = bridge;\n }\n\n async init(): Promise<void> {\n return this.bridge.init();\n }\n\n async destroy(): Promise<void> {\n return this.bridge.destroy();\n }\n\n async serialize(): Promise<\n Omit<LedgerKeyringSerializedState, 'accountIndexes'>\n > {\n return {\n hdPath: this.hdPath,\n accounts: this.accounts.slice(),\n deviceId: this.deviceId,\n accountDetails: this.accountDetails,\n implementFullBIP44: false,\n };\n }\n\n async deserialize(opts: LedgerKeyringSerializedState): Promise<void> {\n this.hdPath = opts.hdPath ?? hdPathString;\n this.accounts = opts.accounts ?? [];\n this.deviceId = opts.deviceId ?? '';\n this.accountDetails = opts.accountDetails ?? {};\n\n if (!opts.accountDetails) {\n this.#migrateAccountDetails(opts);\n }\n\n this.implementFullBIP44 = opts.implementFullBIP44 ?? false;\n\n const keys = new Set<string>(Object.keys(this.accountDetails));\n // Remove accounts that don't have corresponding account details\n this.accounts = this.accounts.filter((account) =>\n keys.has(this.#getChecksumHexAddress(account)),\n );\n\n return Promise.resolve();\n }\n\n public setDeviceId(deviceId: string): void {\n this.deviceId = deviceId;\n }\n\n public getDeviceId(): string {\n return this.deviceId;\n }\n\n #migrateAccountDetails(opts: Partial<LedgerBridgeKeyringOptions>): void {\n if (this.#isLedgerLiveHdPath() && opts.accountIndexes) {\n for (const [account, index] of Object.entries(opts.accountIndexes)) {\n this.accountDetails[account] = {\n bip44: true,\n hdPath: this.#getPathForIndex(index),\n };\n }\n }\n const keys = new Set<string>(Object.keys(this.accountDetails));\n // try to migrate non-LedgerLive accounts too\n if (!this.#isLedgerLiveHdPath()) {\n this.accounts.forEach((account) => {\n const key = this.#getChecksumHexAddress(account);\n\n if (!keys.has(key)) {\n this.accountDetails[key] = {\n bip44: false,\n hdPath: this.#pathFromAddress(account),\n };\n }\n });\n }\n }\n\n isUnlocked(): boolean {\n return Boolean(this.hdk.publicKey);\n }\n\n isConnected(): boolean {\n return this.bridge.isDeviceConnected;\n }\n\n setAccountToUnlock(index: number): void {\n this.unlockedAccount = index;\n }\n\n setHdPath(hdPath: string): void {\n // Reset HDKey if the path changes\n if (this.hdPath !== hdPath) {\n this.hdk = new HDKey();\n }\n this.hdPath = hdPath;\n }\n\n async unlock(hdPath?: string, updateHdk = true): Promise<Hex> {\n if (this.isUnlocked() && !hdPath) {\n // if the device is already unlocked and no path is provided,\n // we return the checksummed address of the public key stored in\n // `this.hdk`, which is the root address of the last unlocked path.\n return this.#getChecksumHexAddress(\n bytesToHex(publicToAddress(this.hdk.publicKey, true)),\n );\n }\n const path = hdPath ? this.#toLedgerPath(hdPath) : this.hdPath;\n\n let payload;\n try {\n payload = await this.bridge.getPublicKey({\n hdPath: path,\n });\n } catch (error: unknown) {\n handleLedgerTransportError(\n error,\n 'Ledger: Unknown error while unlocking account',\n );\n }\n\n if (updateHdk && payload.chainCode) {\n this.hdk.publicKey = Buffer.from(payload.publicKey, 'hex');\n this.hdk.chainCode = Buffer.from(payload.chainCode, 'hex');\n }\n\n return add0x(payload.address);\n }\n\n async addAccounts(amount: number): Promise<Hex[]> {\n return new Promise((resolve, reject) => {\n this.unlock()\n .then(async (_) => {\n const from = this.unlockedAccount;\n const to = from + amount;\n const newAccounts: Hex[] = [];\n for (let i = from; i < to; i++) {\n const path = this.#getPathForIndex(i);\n let address: Hex;\n if (this.#isLedgerLiveHdPath()) {\n address = await this.unlock(path);\n } else {\n address = this.#addressFromIndex(pathBase, i);\n }\n\n this.accountDetails[this.#getChecksumHexAddress(address)] = {\n // TODO: consider renaming this property, as the current name is misleading\n // It's currently used to represent whether an account uses the Ledger Live path.\n bip44: this.#isLedgerLiveHdPath(),\n hdPath: path,\n };\n\n if (!this.accounts.includes(address)) {\n this.accounts = [...this.accounts, address];\n newAccounts.push(address);\n }\n this.page = 0;\n }\n resolve(newAccounts);\n })\n .catch(reject);\n });\n }\n\n getName(): string {\n return keyringType;\n }\n\n async getFirstPage(): Promise<AccountPage> {\n this.page = 0;\n return this.#getPage(1);\n }\n\n async getNextPage(): Promise<AccountPage> {\n return this.#getPage(1);\n }\n\n async getPreviousPage(): Promise<AccountPage> {\n return this.#getPage(-1);\n }\n\n async getAccounts(): Promise<Hex[]> {\n return Promise.resolve(this.accounts.slice());\n }\n\n removeAccount(address: string): void {\n const filteredAccounts = this.accounts.filter(\n (a) => a.toLowerCase() !== address.toLowerCase(),\n );\n\n if (filteredAccounts.length === this.accounts.length) {\n throw new Error(`Address ${address} not found in this keyring`);\n }\n\n this.accounts = filteredAccounts;\n delete this.accountDetails[this.#getChecksumHexAddress(address)];\n }\n\n async attemptMakeApp(): Promise<boolean> {\n return this.bridge.attemptMakeApp();\n }\n\n async updateTransportMethod(transportType: string): Promise<boolean> {\n return this.bridge.updateTransportMethod(transportType);\n }\n\n // tx is an instance of the ethereumjs-transaction class.\n async signTransaction(\n address: Hex,\n tx: TypedTransaction | OldEthJsTransaction,\n ): Promise<TypedTransaction | OldEthJsTransaction> {\n let rawTxHex;\n // transactions built with older versions of ethereumjs-tx have a\n // getChainId method that newer versions do not. Older versions are mutable\n // while newer versions default to being immutable. Expected shape and type\n // of data for v, r and s differ (Buffer (old) vs BN (new))\n if (isOldStyleEthereumjsTx(tx)) {\n // In this version of ethereumjs-tx we must add the chainId in hex format\n // to the initial v value. The chainId must be included in the serialized\n // transaction which is only communicated to ethereumjs-tx in this\n // value. In newer versions the chainId is communicated via the 'Common'\n // object.\n tx.v = tx.getChainId();\n // @ts-expect-error tx.r should be a Buffer, but we are assigning a string\n tx.r = '0x00';\n // @ts-expect-error tx.s should be a Buffer, but we are assigning a string\n tx.s = '0x00';\n\n rawTxHex = tx.serialize().toString('hex');\n\n return this.#signTransaction(address, rawTxHex, (payload) => {\n tx.v = Buffer.from(payload.v, 'hex');\n tx.r = Buffer.from(payload.r, 'hex');\n tx.s = Buffer.from(payload.s, 'hex');\n return tx;\n });\n }\n\n // The below `encode` call is only necessary for legacy transactions, as `getMessageToSign`\n // calls `rlp.encode` internally for non-legacy transactions. As per the \"Transaction Execution\"\n // section of the ethereum yellow paper, transactions need to be \"well-formed RLP, with no additional\n // trailing bytes\".\n\n // Note also that `getMessageToSign` will return valid RLP for all transaction types, whereas the\n // `serialize` method will not for any transaction type except legacy. This is because `serialize` includes\n // empty r, s and v values in the encoded rlp. This is why we use `getMessageToSign` here instead of `serialize`.\n const messageToSign = tx.getMessageToSign();\n\n rawTxHex = Array.isArray(messageToSign)\n ? Buffer.from(RLP.encode(messageToSign)).toString('hex')\n : bytesToHex(messageToSign);\n\n return this.#signTransaction(address, rawTxHex, (payload) => {\n // Because tx will be immutable, first get a plain javascript object that\n // represents the transaction. Using txData here as it aligns with the\n // nomenclature of ethereumjs/tx.\n const txData: TypedTxData = tx.toJSON();\n // The fromTxData utility expects a type to support transactions with a type other than 0\n txData.type = tx.type;\n // The fromTxData utility expects v,r and s to be hex prefixed\n txData.v = add0x(payload.v);\n txData.r = add0x(payload.r);\n txData.s = add0x(payload.s);\n // Adopt the 'common' option from the original transaction and set the\n // returned object to be frozen if the original is frozen.\n return TransactionFactory.fromTxData(txData, {\n common: tx.common,\n freeze: Object.isFrozen(tx),\n });\n });\n }\n\n async #signTransaction(\n address: Hex,\n rawTxHex: string,\n handleSigning: (\n payload: SignTransactionPayload,\n ) => TypedTransaction | OldEthJsTransaction,\n ): Promise<TypedTransaction | OldEthJsTransaction> {\n const hdPath = await this.unlockAccountByAddress(address);\n\n if (!hdPath) {\n throw new Error('Ledger: hdPath is empty while signing transaction');\n }\n\n let payload;\n\n try {\n payload = await this.bridge.deviceSignTransaction({\n tx: remove0x(rawTxHex),\n hdPath,\n });\n } catch (error: unknown) {\n handleLedgerTransportError(\n error,\n 'Ledger: Unknown error while signing transaction',\n );\n }\n\n const newOrMutatedTx = handleSigning(payload);\n const valid = newOrMutatedTx.verifySignature();\n if (valid) {\n return newOrMutatedTx;\n }\n throw new Error('Ledger: The transaction signature is not valid');\n }\n\n async signMessage(withAccount: Hex, data: string): Promise<string> {\n return this.signPersonalMessage(withAccount, data);\n }\n\n // For personal_sign, we need to prefix the message:\n async signPersonalMessage(\n withAccount: Hex,\n message: string,\n ): Promise<string> {\n const hdPath = await this.unlockAccountByAddress(withAccount);\n\n if (!hdPath) {\n throw new Error('Ledger: Unknown error while signing message');\n }\n\n let payload;\n try {\n payload = await this.bridge.deviceSignMessage({\n hdPath,\n message: remove0x(message),\n });\n } catch (error: unknown) {\n handleLedgerTransportError(\n error,\n 'Ledger: Unknown error while signing message',\n );\n }\n\n const modifiedV = this.#normalizeRecoveryParam(\n parseInt(String(payload.v), 10),\n );\n\n const signature = `0x${payload.r}${payload.s}${modifiedV}`;\n const addressSignedWith = recoverPersonalSignature({\n data: message,\n signature,\n });\n if (\n this.#getChecksumHexAddress(addressSignedWith) !==\n this.#getChecksumHexAddress(withAccount)\n ) {\n throw new Error('Ledger: The signature doesnt match the right address');\n }\n return signature;\n }\n\n async unlockAccountByAddress(address: Hex): Promise<string | undefined> {\n const checksummedAddress = this.#getChecksumHexAddress(address);\n const accountDetails = this.accountDetails[checksummedAddress];\n if (!accountDetails) {\n throw new Error(\n `Ledger: Account for address '${checksummedAddress}' not found`,\n );\n }\n const { hdPath } = accountDetails;\n const unlockedAddress = await this.unlock(hdPath, false);\n\n // unlock resolves to the address for the given hdPath as reported by the ledger device\n // if that address is not the requested address, then this account belongs to a different device or seed\n if (unlockedAddress.toLowerCase() !== address.toLowerCase()) {\n throw new Error(\n `Ledger: Account ${address} does not belong to the connected device`,\n );\n }\n return hdPath;\n }\n\n async signTypedData<\n Version extends SignTypedDataVersion.V4,\n Types extends MessageTypes,\n Options extends { version?: Version },\n >(\n withAccount: Hex,\n data: TypedMessage<Types>,\n options?: Options,\n ): Promise<string> {\n const { version } = options ?? {};\n const isV4 = version === 'V4';\n if (!isV4) {\n throw new Error(\n 'Ledger: Only version 4 of typed data signing is supported',\n );\n }\n\n const { domain, types, primaryType, message } =\n TypedDataUtils.sanitizeData(data);\n\n const hdPath = await this.unlockAccountByAddress(withAccount);\n\n if (!hdPath) {\n throw new Error('Ledger: Unknown error while signing message');\n }\n\n let payload;\n try {\n payload = await this.bridge.deviceSignTypedData({\n hdPath,\n message: {\n domain: {\n name: domain.name,\n chainId: domain.chainId,\n version: domain.version,\n verifyingContract: domain.verifyingContract,\n salt:\n domain.salt instanceof ArrayBuffer\n ? Buffer.from(domain.salt).toString('hex')\n : domain.salt,\n },\n types,\n primaryType: primaryType.toString(),\n message,\n },\n });\n } catch (error: unknown) {\n handleLedgerTransportError(\n error,\n 'Ledger: Unknown error while signing message',\n );\n }\n\n const recoveryId = this.#normalizeRecoveryParam(\n parseInt(String(payload.v), 10),\n );\n const signature = `0x${payload.r}${payload.s}${recoveryId}`;\n const addressSignedWith = recoverTypedSignature({\n data,\n signature,\n version: SignTypedDataVersion.V4,\n });\n\n if (\n this.#getChecksumHexAddress(addressSignedWith) !==\n this.#getChecksumHexAddress(withAccount)\n ) {\n throw new Error('Ledger: The signature doesnt match the right address');\n }\n return signature;\n }\n\n forgetDevice(): void {\n this.deviceId = '';\n this.accounts = [];\n this.page = 0;\n this.unlockedAccount = 0;\n this.paths = {};\n this.accountDetails = {};\n this.hdk = new HDKey();\n }\n\n /* PRIVATE METHODS */\n async #getPage(increment: number): Promise<AccountPage> {\n this.page += increment;\n\n if (this.page <= 0) {\n this.page = 1;\n }\n const from = (this.page - 1) * this.perPage;\n const to = from + this.perPage;\n\n await this.unlock();\n let accounts;\n if (this.#isLedgerLiveHdPath()) {\n accounts = await this.#getAccountsBIP44(from, to);\n } else {\n accounts = this.#getAccountsLegacy(from, to);\n }\n return accounts;\n }\n\n async #getAccountsBIP44(from: number, to: number): Promise<AccountPage> {\n const accounts: AccountPage = [];\n\n for (let i = from; i < to; i++) {\n const path = this.#getPathForIndex(i);\n const address = await this.unlock(path);\n const valid = this.implementFullBIP44\n ? await this.#hasPreviousTransactions(address)\n : true;\n accounts.push({\n address,\n balance: null,\n index: i,\n });\n\n // PER BIP44\n // \"Software should prevent a creation of an account if\n // a previous account does not have a transaction history\n // (meaning none of its addresses have been used before).\"\n if (!valid) {\n break;\n }\n }\n return accounts;\n }\n\n #getAccountsLegacy(from: number, to: number): AccountPage {\n const accounts: AccountPage = [];\n\n for (let i = from; i < to; i++) {\n const address = this.#addressFromIndex(pathBase, i);\n accounts.push({\n address,\n balance: null,\n index: i,\n });\n this.paths[this.#getChecksumHexAddress(address)] = i;\n }\n return accounts;\n }\n\n #addressFromIndex(basePath: string, i: number): Hex {\n const dkey = this.hdk.derive(`${basePath}/${i}`);\n const address = bytesToHex(publicToAddress(dkey.publicKey, true));\n return this.#getChecksumHexAddress(address);\n }\n\n #pathFromAddress(address: string): string {\n const checksummedAddress = this.#getChecksumHexAddress(address);\n let index = this.paths[checksummedAddress];\n if (typeof index === 'undefined') {\n for (let i = 0; i < MAX_INDEX; i++) {\n if (checksummedAddress === this.#addressFromIndex(pathBase, i)) {\n index = i;\n break;\n }\n }\n }\n\n if (typeof index === 'undefined') {\n throw new Error('Unknown address');\n }\n return this.#getPathForIndex(index);\n }\n\n #getPathForIndex(index: number): string {\n // Check if the path is BIP 44 (Ledger Live)\n return this.#isLedgerLiveHdPath()\n ? `m/44'/60'/${index}'/0/0`\n : `${this.hdPath}/${index}`;\n }\n\n #isLedgerLiveHdPath(): boolean {\n return this.hdPath === `m/44'/60'/0'/0/0`;\n }\n\n #toLedgerPath(path: string): string {\n return path.toString().replace('m/', '');\n }\n\n async #hasPreviousTransactions(address: string): Promise<boolean> {\n const apiUrl = this.#getApiUrl();\n const response = await window.fetch(\n `${apiUrl}/api?module=account&action=txlist&address=${address}&tag=latest&page=1&offset=1`,\n );\n const parsedResponse = await response.json();\n return parsedResponse.status !== '0' && parsedResponse.result.length > 0;\n }\n\n #getApiUrl(): NetworkApiUrls {\n return this.network;\n }\n\n #getChecksumHexAddress(address: string): Hex {\n return getChecksumAddress(add0x(address));\n }\n\n /**\n * Normalizes the signature recovery parameter (v) to legacy format.\n * Ledger devices may return v as 0 or 1 (modern format), but signature\n * recovery expects 27 or 28 (legacy format per EIP-191/EIP-712).\n *\n * @param recoveryParam - The recovery parameter from Ledger.\n * @returns The normalized recovery parameter as a hex string.\n */\n #normalizeRecoveryParam(recoveryParam: number): string {\n if (recoveryParam === 0 || recoveryParam === 1) {\n return (recoveryParam + 27).toString(16);\n }\n return recoveryParam.toString(16);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"ledger-keyring.d.cts","sourceRoot":"","sources":["../src/ledger-keyring.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,KAAK,gBAAgB,EACtB,uBAAuB;AAExB,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,+BAA+B;AACzE,OAAO,EAGL,oBAAoB,EAErB,+BAA+B;AAChC,OAAO,KAAK,EAAE,OAAO,EAAE,gCAAgC;AACvD,OAAO,EAIL,GAAG,EAEJ,wBAAwB;AAEzB,OAAO,KAAK,mBAAmB,sBAAsB;AACrD,OAAO,KAAK,cAAc;AAE1B,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,4BAAwB;AAWpE,aAAK,cAAc;IACjB,OAAO,qCAAqC;IAC5C,KAAK,mCAAmC;IACxC,OAAO,qCAAqC;IAC5C,OAAO,6BAA6B;CACrC;AAMD,MAAM,MAAM,gBAAgB,GAAG;IAC7B,OAAO,EA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AChB,IAAI,EAAE,YAAY,CAAC,KAAK,CAAC,EACzB,OAAO,CAAC,EAAE,OAAO,GAChB,OAAO,CAAC,MAAM,CAAC;IAgElB,YAAY,IAAI,IAAI;CA6IrB"}
@@ -3,7 +3,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
3
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
4
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
5
  };
6
- var _LedgerKeyring_instances, _LedgerKeyring_migrateAccountDetails, _LedgerKeyring_signTransaction, _LedgerKeyring_getPage, _LedgerKeyring_getAccountsBIP44, _LedgerKeyring_getAccountsLegacy, _LedgerKeyring_addressFromIndex, _LedgerKeyring_pathFromAddress, _LedgerKeyring_getPathForIndex, _LedgerKeyring_isLedgerLiveHdPath, _LedgerKeyring_toLedgerPath, _LedgerKeyring_hasPreviousTransactions, _LedgerKeyring_getApiUrl, _LedgerKeyring_getChecksumHexAddress;
6
+ var _LedgerKeyring_instances, _LedgerKeyring_migrateAccountDetails, _LedgerKeyring_signTransaction, _LedgerKeyring_getPage, _LedgerKeyring_getAccountsBIP44, _LedgerKeyring_getAccountsLegacy, _LedgerKeyring_addressFromIndex, _LedgerKeyring_pathFromAddress, _LedgerKeyring_getPathForIndex, _LedgerKeyring_isLedgerLiveHdPath, _LedgerKeyring_toLedgerPath, _LedgerKeyring_hasPreviousTransactions, _LedgerKeyring_getApiUrl, _LedgerKeyring_getChecksumHexAddress, _LedgerKeyring_normalizeRecoveryParam;
7
7
  function $importDefault(module) {
8
8
  if (module?.__esModule) {
9
9
  return module.default;
@@ -279,10 +279,7 @@ export class LedgerKeyring {
279
279
  catch (error) {
280
280
  handleLedgerTransportError(error, 'Ledger: Unknown error while signing message');
281
281
  }
282
- let modifiedV = parseInt(String(payload.v), 10).toString(16);
283
- if (modifiedV.length < 2) {
284
- modifiedV = `0${modifiedV}`;
285
- }
282
+ const modifiedV = __classPrivateFieldGet(this, _LedgerKeyring_instances, "m", _LedgerKeyring_normalizeRecoveryParam).call(this, parseInt(String(payload.v), 10));
286
283
  const signature = `0x${payload.r}${payload.s}${modifiedV}`;
287
284
  const addressSignedWith = recoverPersonalSignature({
288
285
  data: message,
@@ -343,10 +340,7 @@ export class LedgerKeyring {
343
340
  catch (error) {
344
341
  handleLedgerTransportError(error, 'Ledger: Unknown error while signing message');
345
342
  }
346
- let recoveryId = parseInt(String(payload.v), 10).toString(16);
347
- if (recoveryId.length < 2) {
348
- recoveryId = `0${recoveryId}`;
349
- }
343
+ const recoveryId = __classPrivateFieldGet(this, _LedgerKeyring_instances, "m", _LedgerKeyring_normalizeRecoveryParam).call(this, parseInt(String(payload.v), 10));
350
344
  const signature = `0x${payload.r}${payload.s}${recoveryId}`;
351
345
  const addressSignedWith = recoverTypedSignature({
352
346
  data,
@@ -501,6 +495,11 @@ async function _LedgerKeyring_getPage(increment) {
501
495
  return this.network;
502
496
  }, _LedgerKeyring_getChecksumHexAddress = function _LedgerKeyring_getChecksumHexAddress(address) {
503
497
  return getChecksumAddress(add0x(address));
498
+ }, _LedgerKeyring_normalizeRecoveryParam = function _LedgerKeyring_normalizeRecoveryParam(recoveryParam) {
499
+ if (recoveryParam === 0 || recoveryParam === 1) {
500
+ return (recoveryParam + 27).toString(16);
501
+ }
502
+ return recoveryParam.toString(16);
504
503
  };
505
504
  LedgerKeyring.type = keyringType;
506
505
  //# sourceMappingURL=ledger-keyring.mjs.map