@faremeter/wallet-ledger 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1,3 @@
1
+ import type { LedgerEvmWallet } from "./types.js";
2
+ export declare function createLedgerEvmWallet(network: string, derivationPath: string): Promise<LedgerEvmWallet>;
3
+ //# sourceMappingURL=evm.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"evm.d.ts","sourceRoot":"","sources":["../../src/evm.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AA+B/C,wBAAsB,qBAAqB,CACzC,OAAO,EAAE,MAAM,EACf,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,eAAe,CAAC,CAqK1B"}
@@ -0,0 +1,154 @@
1
+ import { createWalletClient, http, hashDomain, hashStruct, } from "viem";
2
+ import { baseSepolia, mainnet, sepolia } from "viem/chains";
3
+ import Eth from "@ledgerhq/hw-app-eth/lib-es/Eth.js";
4
+ import { type } from "arktype";
5
+ import { createTransport } from "./transport.js";
6
+ const NETWORK_CONFIGS = new Map([
7
+ [
8
+ "base-sepolia",
9
+ {
10
+ chain: baseSepolia,
11
+ rpcUrl: "https://sepolia.base.org",
12
+ },
13
+ ],
14
+ [
15
+ "ethereum",
16
+ {
17
+ chain: mainnet,
18
+ rpcUrl: "https://ethereum-rpc.publicnode.com",
19
+ },
20
+ ],
21
+ [
22
+ "sepolia",
23
+ {
24
+ chain: sepolia,
25
+ rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
26
+ },
27
+ ],
28
+ ]);
29
+ export async function createLedgerEvmWallet(network, derivationPath) {
30
+ const config = NETWORK_CONFIGS.get(network);
31
+ if (!config) {
32
+ throw new Error(`Unsupported network: ${network}. Supported networks: ${Array.from(NETWORK_CONFIGS.keys()).join(", ")}`);
33
+ }
34
+ const transport = await createTransport();
35
+ const eth = new Eth(transport);
36
+ const { address } = await eth.getAddress(derivationPath);
37
+ const formattedAddress = (address.startsWith("0x") ? address : `0x${address}`).toLowerCase();
38
+ const ledgerAccount = {
39
+ address: formattedAddress,
40
+ publicKey: formattedAddress,
41
+ type: "local",
42
+ source: "custom",
43
+ signMessage: async ({ message }) => {
44
+ let messageToSign;
45
+ if (typeof message === "string") {
46
+ messageToSign = Buffer.from(message).toString("hex");
47
+ }
48
+ else if (message && typeof message === "object" && "raw" in message) {
49
+ const raw = message.raw;
50
+ messageToSign =
51
+ typeof raw === "string"
52
+ ? raw.slice(2)
53
+ : Buffer.from(raw).toString("hex");
54
+ }
55
+ else {
56
+ messageToSign = Buffer.from(String(message)).toString("hex");
57
+ }
58
+ const result = await eth.signPersonalMessage(derivationPath, messageToSign);
59
+ const signature = `0x${result.r}${result.s}${result.v.toString(16).padStart(2, "0")}`;
60
+ return signature;
61
+ },
62
+ signTransaction: async (transaction) => {
63
+ const toHex = (v, defaultValue) => v ? `0x${v.toString(16)}` : defaultValue;
64
+ const tx = {
65
+ to: transaction.to,
66
+ value: toHex(transaction.value, "0x0"),
67
+ data: transaction.data ?? "0x", // 0x is valid encoding for empty data in EVM
68
+ nonce: toHex(transaction.nonce, "0x0"),
69
+ gasLimit: toHex(transaction.gas, "0x5208"),
70
+ gasPrice: toHex(transaction.gasPrice),
71
+ maxFeePerGas: toHex(transaction.maxFeePerGas),
72
+ maxPriorityFeePerGas: toHex(transaction.maxPriorityFeePerGas),
73
+ chainId: config.chain.id,
74
+ };
75
+ const result = await eth.signTransaction(derivationPath, JSON.stringify(tx));
76
+ const signature = `0x${result.r}${result.s}${result.v}`;
77
+ return signature;
78
+ },
79
+ signTypedData: async (parameters) => {
80
+ const typedDataParams = type({
81
+ "domain?": {
82
+ "name?": "string",
83
+ "version?": "string",
84
+ "chainId?": "number",
85
+ "verifyingContract?": "string",
86
+ "salt?": "string",
87
+ },
88
+ types: "object",
89
+ primaryType: "string",
90
+ message: "object",
91
+ });
92
+ const validated = typedDataParams.assert(parameters);
93
+ const { domain, types, primaryType, message } = validated;
94
+ try {
95
+ // Use EIP-712 hashed message approach. This calculates the domain
96
+ // separator and message hash separately and sends them to the Ledger
97
+ // for signing.
98
+ // Build types with EIP712Domain
99
+ const typesWithDomain = {
100
+ EIP712Domain: [
101
+ ...(domain?.name ? [{ name: "name", type: "string" }] : []),
102
+ ...(domain?.version ? [{ name: "version", type: "string" }] : []),
103
+ ...(domain?.chainId ? [{ name: "chainId", type: "uint256" }] : []),
104
+ ...(domain?.verifyingContract
105
+ ? [{ name: "verifyingContract", type: "address" }]
106
+ : []),
107
+ ],
108
+ ...types,
109
+ };
110
+ // Calculate hashes using viem
111
+ const domainSeparator = hashDomain({
112
+ domain: domain ?? {},
113
+ types: typesWithDomain,
114
+ });
115
+ // types without domain for message hash
116
+ const messageHash = hashStruct({
117
+ data: message,
118
+ primaryType,
119
+ types,
120
+ });
121
+ console.log("\nEIP-712 hashes calculated:");
122
+ console.log(" Domain separator:", domainSeparator);
123
+ console.log(" Message hash:", messageHash);
124
+ console.log("\nPlease approve the transaction on your Ledger device...");
125
+ const result = await eth.signEIP712HashedMessage(derivationPath, domainSeparator.slice(2), messageHash.slice(2));
126
+ const signature = `0x${result.r}${result.s}${result.v.toString(16).padStart(2, "0")}`;
127
+ return signature;
128
+ }
129
+ catch (error) {
130
+ console.error("EIP-712 signing failed:", error);
131
+ throw error;
132
+ }
133
+ },
134
+ };
135
+ const client = createWalletClient({
136
+ account: ledgerAccount,
137
+ chain: config.chain,
138
+ transport: http(config.rpcUrl),
139
+ });
140
+ return {
141
+ network,
142
+ address: formattedAddress,
143
+ client,
144
+ signTransaction: async (tx) => {
145
+ return await ledgerAccount.signTransaction(tx);
146
+ },
147
+ signTypedData: async (params) => {
148
+ return await ledgerAccount.signTypedData(params);
149
+ },
150
+ disconnect: async () => {
151
+ await transport.close();
152
+ },
153
+ };
154
+ }
@@ -0,0 +1,5 @@
1
+ export { createLedgerEvmWallet } from "./evm.js";
2
+ export { createLedgerSolanaWallet } from "./solana.js";
3
+ export { selectLedgerAccount } from "./utils.js";
4
+ export type { LedgerEvmWallet, LedgerSolanaWallet } from "./types.js";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,OAAO,CAAC;AAC9C,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAC9C,YAAY,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { createLedgerEvmWallet } from "./evm.js";
2
+ export { createLedgerSolanaWallet } from "./solana.js";
3
+ export { selectLedgerAccount } from "./utils.js";
@@ -0,0 +1,3 @@
1
+ import type { LedgerSolanaWallet } from "./types.js";
2
+ export declare function createLedgerSolanaWallet(network: string, derivationPath: string): Promise<LedgerSolanaWallet>;
3
+ //# sourceMappingURL=solana.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"solana.d.ts","sourceRoot":"","sources":["../../src/solana.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAElD,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,MAAM,EACf,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,kBAAkB,CAAC,CA0B7B"}
@@ -0,0 +1,22 @@
1
+ import { PublicKey, VersionedTransaction } from "@solana/web3.js";
2
+ import Solana from "@ledgerhq/hw-app-solana/lib-es/Solana.js";
3
+ import { createTransport } from "./transport.js";
4
+ export async function createLedgerSolanaWallet(network, derivationPath) {
5
+ const transport = await createTransport();
6
+ const solana = new Solana(transport);
7
+ const { address } = await solana.getAddress(derivationPath);
8
+ const publicKey = new PublicKey(address);
9
+ return {
10
+ network,
11
+ publicKey,
12
+ updateTransaction: async (tx) => {
13
+ const message = tx.message.serialize();
14
+ const signature = await solana.signTransaction(derivationPath, Buffer.from(message));
15
+ tx.addSignature(publicKey, signature.signature);
16
+ return tx;
17
+ },
18
+ disconnect: async () => {
19
+ await transport.close();
20
+ },
21
+ };
22
+ }
@@ -0,0 +1,4 @@
1
+ import type Transport from "@ledgerhq/hw-transport";
2
+ export declare function translateLedgerError(error: unknown): Error;
3
+ export declare function createTransport(maxRetries?: number): Promise<Transport>;
4
+ //# sourceMappingURL=transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../src/transport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,MAAM,wBAAwB,CAAC;AAcpD,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,CAoB1D;AAED,wBAAsB,eAAe,CAAC,UAAU,SAAI,GAAG,OAAO,CAAC,SAAS,CAAC,CAyCxE"}
@@ -0,0 +1,55 @@
1
+ const LEDGER_ERRORS = {
2
+ "0x5515": "Ledger is locked. Please unlock your device.",
3
+ "0x6511": "Please unlock your Ledger and open the correct app.",
4
+ "0x6d00": "Wrong app open. Please open the correct app.",
5
+ "0x6d02": "No app open. Please open the correct app on your Ledger.",
6
+ "0x6e00": "Wrong app open. Please open the correct app on your Ledger.",
7
+ "0x6985": "Transaction rejected on Ledger device.",
8
+ "0x6a80": "Incorrect data. Please make sure the correct app is open on your Ledger.",
9
+ "0x6a83": "Wrong app open. Please open the correct app on your Ledger.",
10
+ };
11
+ export function translateLedgerError(error) {
12
+ const message = String(error instanceof Error ? error.message : error);
13
+ const hexMatch = /0x[0-9a-fA-F]{4}/.exec(message);
14
+ if (hexMatch && LEDGER_ERRORS[hexMatch[0]]) {
15
+ return new Error(LEDGER_ERRORS[hexMatch[0]]);
16
+ }
17
+ // Check for common connection errors
18
+ if (message.includes("NoDevice")) {
19
+ return new Error("No Ledger device found. Please connect your Ledger and unlock it.");
20
+ }
21
+ if (message.includes("Device busy")) {
22
+ return new Error("Ledger is in use by another app. Close Ledger Live.");
23
+ }
24
+ return error instanceof Error ? error : new Error(message);
25
+ }
26
+ export async function createTransport(maxRetries = 3) {
27
+ let lastError;
28
+ for (let i = 0; i < maxRetries; i++) {
29
+ try {
30
+ const isBrowser = typeof globalThis !== "undefined" && "window" in globalThis;
31
+ if (isBrowser) {
32
+ const { default: TransportWebUSB } = await import("@ledgerhq/hw-transport-webusb");
33
+ return await TransportWebUSB.create();
34
+ }
35
+ else {
36
+ const mod = await import("@ledgerhq/hw-transport-node-hid");
37
+ const TransportNodeHid = mod.default || mod;
38
+ return await TransportNodeHid.open("");
39
+ }
40
+ }
41
+ catch (error) {
42
+ const translatedError = translateLedgerError(error);
43
+ lastError = translatedError;
44
+ // Retry on generic USB errors
45
+ const errorMessage = translatedError.message;
46
+ if (i < maxRetries - 1 &&
47
+ (errorMessage.includes("USB") || errorMessage.includes("device"))) {
48
+ console.log(`USB connection attempt ${i + 1} failed, retrying...`);
49
+ await new Promise((resolve) => setTimeout(resolve, 1000));
50
+ continue;
51
+ }
52
+ }
53
+ }
54
+ throw lastError ?? new Error("Failed to connect to Ledger device");
55
+ }
@@ -0,0 +1,22 @@
1
+ import type { Hex, WalletClient, TransactionSerializable, TypedDataDefinition } from "viem";
2
+ import type { PublicKey, VersionedTransaction } from "@solana/web3.js";
3
+ import type Transport from "@ledgerhq/hw-transport";
4
+ export interface LedgerEvmWallet {
5
+ network: string;
6
+ address: Hex;
7
+ client: WalletClient;
8
+ signTransaction: (tx: TransactionSerializable) => Promise<Hex>;
9
+ signTypedData: (params: TypedDataDefinition) => Promise<Hex>;
10
+ disconnect: () => Promise<void>;
11
+ }
12
+ export interface LedgerSolanaWallet {
13
+ network: string;
14
+ publicKey: PublicKey;
15
+ updateTransaction: (tx: VersionedTransaction) => Promise<VersionedTransaction>;
16
+ disconnect: () => Promise<void>;
17
+ }
18
+ export interface LedgerTransportWrapper {
19
+ transport: Transport;
20
+ close: () => Promise<void>;
21
+ }
22
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,GAAG,EACH,YAAY,EACZ,uBAAuB,EACvB,mBAAmB,EACpB,MAAM,MAAM,CAAC;AACd,OAAO,KAAK,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvE,OAAO,KAAK,SAAS,MAAM,wBAAwB,CAAC;AAEpD,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,GAAG,CAAC;IACb,MAAM,EAAE,YAAY,CAAC;IACrB,eAAe,EAAE,CAAC,EAAE,EAAE,uBAAuB,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;IAC/D,aAAa,EAAE,CAAC,MAAM,EAAE,mBAAmB,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;IAC7D,UAAU,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CACjC;AAED,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,SAAS,CAAC;IACrB,iBAAiB,EAAE,CACjB,EAAE,EAAE,oBAAoB,KACrB,OAAO,CAAC,oBAAoB,CAAC,CAAC;IACnC,UAAU,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CACjC;AAED,MAAM,WAAW,sBAAsB;IACrC,SAAS,EAAE,SAAS,CAAC;IACrB,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5B"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ export declare function selectLedgerAccount(type: "evm" | "solana", numAccounts?: number): Promise<{
2
+ path: string;
3
+ address: string;
4
+ } | null>;
5
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAaA,wBAAsB,mBAAmB,CACvC,IAAI,EAAE,KAAK,GAAG,QAAQ,EACtB,WAAW,SAAI,GACd,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAAC,CAkEnD"}
@@ -0,0 +1,72 @@
1
+ import Eth from "@ledgerhq/hw-app-eth/lib-es/Eth.js";
2
+ import Solana from "@ledgerhq/hw-app-solana/lib-es/Solana.js";
3
+ import { PublicKey } from "@solana/web3.js";
4
+ import { createTransport, translateLedgerError } from "./transport.js";
5
+ function evmDerivationPath(index) {
6
+ return `m/44'/60'/${index}'/0/0`;
7
+ }
8
+ function solanaDerivationPath(index) {
9
+ return `44'/501'/${index}'`;
10
+ }
11
+ export async function selectLedgerAccount(type, numAccounts = 5) {
12
+ const isEvm = type === "evm";
13
+ console.log(`\nScanning first ${numAccounts} ${isEvm ? "Ethereum" : "Solana"} accounts...`);
14
+ const accounts = [];
15
+ const transport = await createTransport();
16
+ try {
17
+ if (isEvm) {
18
+ const eth = new Eth(transport);
19
+ for (let i = 0; i < numAccounts; i++) {
20
+ const path = evmDerivationPath(i);
21
+ let result;
22
+ try {
23
+ result = await eth.getAddress(path, false);
24
+ }
25
+ catch (error) {
26
+ throw translateLedgerError(error);
27
+ }
28
+ const address = result.address;
29
+ const normalizedAddress = address.startsWith("0x")
30
+ ? address
31
+ : `0x${address}`;
32
+ accounts.push({ path, address: normalizedAddress });
33
+ console.log(`${i + 1}. ${normalizedAddress}`);
34
+ }
35
+ }
36
+ else {
37
+ const solana = new Solana(transport);
38
+ for (let i = 0; i < numAccounts; i++) {
39
+ const path = solanaDerivationPath(i);
40
+ let result;
41
+ try {
42
+ result = await solana.getAddress(path, false);
43
+ }
44
+ catch (error) {
45
+ throw translateLedgerError(error);
46
+ }
47
+ const publicKey = new PublicKey(result.address);
48
+ const address = publicKey.toBase58();
49
+ accounts.push({ path, address });
50
+ console.log(`${i + 1}. ${address}`);
51
+ }
52
+ }
53
+ }
54
+ finally {
55
+ await transport.close();
56
+ }
57
+ const readline = await import("readline");
58
+ const rl = readline.createInterface({
59
+ input: process.stdin,
60
+ output: process.stdout,
61
+ });
62
+ const selection = await new Promise((resolve) => {
63
+ rl.question(`\nSelect account (1-${numAccounts}): `, resolve);
64
+ });
65
+ rl.close();
66
+ const index = parseInt(selection) - 1;
67
+ if (index < 0 || index >= accounts.length) {
68
+ console.log("Invalid selection");
69
+ return null;
70
+ }
71
+ return accounts[index] ?? null;
72
+ }