@swapkit/wallet-hardware 4.8.0 → 4.8.2

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.
Files changed (38) hide show
  1. package/dist/keepkey/index.cjs.map +2 -2
  2. package/dist/keepkey/index.js.map +2 -2
  3. package/dist/types/keepkey/chains/utxo.d.ts +5 -379
  4. package/dist/types/keepkey/chains/utxo.d.ts.map +1 -1
  5. package/package.json +5 -7
  6. package/src/index.ts +1 -0
  7. package/src/keepkey/chains/cosmos.ts +69 -0
  8. package/src/keepkey/chains/evm.ts +141 -0
  9. package/src/keepkey/chains/mayachain.ts +98 -0
  10. package/src/keepkey/chains/ripple.ts +88 -0
  11. package/src/keepkey/chains/thorchain.ts +93 -0
  12. package/src/keepkey/chains/utxo.ts +364 -0
  13. package/src/keepkey/coins.ts +67 -0
  14. package/src/keepkey/index.ts +174 -0
  15. package/src/ledger/clients/cosmos.ts +84 -0
  16. package/src/ledger/clients/evm.ts +186 -0
  17. package/src/ledger/clients/near.ts +63 -0
  18. package/src/ledger/clients/sui.ts +130 -0
  19. package/src/ledger/clients/thorchain/common.ts +93 -0
  20. package/src/ledger/clients/thorchain/helpers.ts +120 -0
  21. package/src/ledger/clients/thorchain/index.ts +87 -0
  22. package/src/ledger/clients/thorchain/lib.ts +258 -0
  23. package/src/ledger/clients/thorchain/utils.ts +69 -0
  24. package/src/ledger/clients/tron.ts +85 -0
  25. package/src/ledger/clients/utxo-legacy-adapter.ts +71 -0
  26. package/src/ledger/clients/utxo-psbt.ts +145 -0
  27. package/src/ledger/clients/utxo.ts +359 -0
  28. package/src/ledger/clients/xrp.ts +50 -0
  29. package/src/ledger/cosmosTypes.ts +98 -0
  30. package/src/ledger/helpers/getLedgerAddress.ts +76 -0
  31. package/src/ledger/helpers/getLedgerClient.ts +124 -0
  32. package/src/ledger/helpers/getLedgerTransport.ts +102 -0
  33. package/src/ledger/helpers/index.ts +3 -0
  34. package/src/ledger/index.ts +546 -0
  35. package/src/ledger/interfaces/CosmosLedgerInterface.ts +54 -0
  36. package/src/ledger/types.ts +42 -0
  37. package/src/trezor/evmSigner.ts +210 -0
  38. package/src/trezor/index.ts +847 -0
@@ -0,0 +1,67 @@
1
+ /*
2
+ KeepKey Specific bip32 path conventions
3
+ */
4
+
5
+ import { SwapKitError } from "@swapkit/helpers";
6
+
7
+ const HARDENED = 0x80000000;
8
+
9
+ export enum ChainToKeepKeyName {
10
+ BTC = "Bitcoin",
11
+ BCH = "BitcoinCash",
12
+ DOGE = "Dogecoin",
13
+ LTC = "Litecoin",
14
+ DASH = "Dash",
15
+ XRP = "Ripple",
16
+ }
17
+
18
+ export function addressNListToBIP32(address: number[]) {
19
+ return `m/${address.map((num) => (num >= HARDENED ? `${num - HARDENED}'` : num)).join("/")}`;
20
+ }
21
+
22
+ export function bip32Like(path: string) {
23
+ if (path === "m/") return true;
24
+
25
+ return /^m(((\/[0-9]+h)+|(\/[0-9]+H)+|(\/[0-9]+')*)((\/[0-9]+)*))$/.test(path);
26
+ }
27
+
28
+ export function bip32ToAddressNList(initPath: string): number[] {
29
+ let path = initPath;
30
+
31
+ if (!bip32Like(path)) {
32
+ throw new SwapKitError("wallet_keepkey_invalid_params", { reason: `Not a bip32 path: '${path}'` });
33
+ }
34
+
35
+ if (/^m\//i.test(path)) {
36
+ path = path.slice(2);
37
+ }
38
+ const segments = path.split("/");
39
+
40
+ if (segments.length === 1 && segments[0] === "") return [];
41
+
42
+ const ret = new Array(segments.length);
43
+
44
+ for (let i = 0; i < segments.length; i++) {
45
+ // TODO: Check for better way instead of exec
46
+ const segment = segments[i];
47
+ if (segment) {
48
+ const tmp = /(\d+)([hH']?)/.exec(segment);
49
+ if (tmp === null) throw new SwapKitError("wallet_keepkey_invalid_params", { reason: "Invalid input" });
50
+
51
+ const [, num = "", modifier = ""] = tmp;
52
+
53
+ ret[i] = Number.parseInt(num, 10);
54
+
55
+ if (ret[i] >= HARDENED)
56
+ throw new SwapKitError("wallet_keepkey_invalid_params", { reason: "Invalid child index" });
57
+
58
+ if (modifier === "h" || modifier === "H" || modifier === "'") {
59
+ ret[i] += HARDENED;
60
+ } else if (modifier.length > 0) {
61
+ throw new SwapKitError("wallet_keepkey_invalid_params", { reason: "Invalid modifier" });
62
+ }
63
+ }
64
+ }
65
+
66
+ return ret;
67
+ }
@@ -0,0 +1,174 @@
1
+ import { KeepKeySdk } from "@keepkey/keepkey-sdk";
2
+ import {
3
+ Chain,
4
+ type DerivationPathArray,
5
+ filterSupportedChains,
6
+ NetworkDerivationPath,
7
+ SKConfig,
8
+ SwapKitError,
9
+ WalletOption,
10
+ } from "@swapkit/helpers";
11
+
12
+ export type { PairingInfo } from "@keepkey/keepkey-sdk";
13
+
14
+ import { createWallet, getWalletSupportedChains } from "@swapkit/wallet-core";
15
+ import { cosmosWalletMethods } from "./chains/cosmos";
16
+ import { KeepKeySigner } from "./chains/evm";
17
+ import { mayachainWalletMethods } from "./chains/mayachain";
18
+ import { thorchainWalletMethods } from "./chains/thorchain";
19
+ import { utxoWalletMethods } from "./chains/utxo";
20
+
21
+ export const keepkeyWallet = createWallet({
22
+ connect: ({ addChain, supportedChains, walletType }) =>
23
+ async function connectKeepkey(chains: Chain[], derivationPathMap?: Record<Chain, DerivationPathArray>) {
24
+ const filteredChains = filterSupportedChains({ chains, supportedChains, walletType });
25
+ const pairingInfo = SKConfig.get("integrations").keepKey;
26
+ if (!pairingInfo) throw new Error("KeepKey config not found");
27
+
28
+ const initialApiKey = SKConfig.get("apiKeys").keepKey || "1234";
29
+
30
+ await checkAndLaunch();
31
+
32
+ // Conform to the expected { apiKey, pairingInfo } structure
33
+ const keepkeyConfig = { apiKey: initialApiKey, pairingInfo };
34
+ const keepKeySdk = await KeepKeySdk.create(keepkeyConfig);
35
+
36
+ // Persist the new API key via SKConfig after pairing
37
+ if (keepkeyConfig.apiKey && keepkeyConfig.apiKey !== initialApiKey) {
38
+ SKConfig.setApiKey("keepKey", keepkeyConfig.apiKey);
39
+ }
40
+
41
+ await Promise.all(
42
+ filteredChains.map(async (chain) => {
43
+ const walletMethods = await getWalletMethods({
44
+ chain,
45
+ derivationPath: derivationPathMap?.[chain] || NetworkDerivationPath[chain],
46
+ sdk: keepKeySdk,
47
+ });
48
+ const address = (await walletMethods.getAddress()) || "";
49
+
50
+ addChain({ ...walletMethods, address, chain, walletType: WalletOption.KEEPKEY });
51
+ }),
52
+ );
53
+ return true;
54
+ },
55
+ directSigningSupport: {
56
+ [Chain.Arbitrum]: true,
57
+ [Chain.Avalanche]: true,
58
+ [Chain.Base]: true,
59
+ [Chain.Berachain]: true,
60
+ [Chain.BinanceSmartChain]: true,
61
+ [Chain.Ethereum]: true,
62
+ [Chain.Gnosis]: true,
63
+ [Chain.Monad]: true,
64
+ [Chain.Optimism]: true,
65
+ [Chain.Polygon]: true,
66
+ [Chain.Ripple]: true,
67
+ [Chain.XLayer]: true,
68
+ // BTC/BCH/DASH/DOGE/LTC/Cosmos/THORChain/Maya: pending KeepKey SDK signer wrappers (V3 plan PRs)
69
+ },
70
+ name: "connectKeepkey",
71
+ supportedChains: [
72
+ Chain.Arbitrum,
73
+ Chain.Avalanche,
74
+ Chain.Base,
75
+ Chain.Berachain,
76
+ Chain.BinanceSmartChain,
77
+ Chain.Bitcoin,
78
+ Chain.BitcoinCash,
79
+ Chain.Cosmos,
80
+ Chain.Dogecoin,
81
+ Chain.Dash,
82
+ Chain.Ethereum,
83
+ Chain.Gnosis,
84
+ Chain.Litecoin,
85
+ Chain.Monad,
86
+ Chain.Ripple,
87
+ Chain.Optimism,
88
+ Chain.Polygon,
89
+ Chain.THORChain,
90
+ Chain.Maya,
91
+ Chain.XLayer,
92
+ ],
93
+ walletType: WalletOption.KEEPKEY,
94
+ });
95
+
96
+ export const KEEPKEY_SUPPORTED_CHAINS = getWalletSupportedChains(keepkeyWallet);
97
+
98
+ async function getWalletMethods({
99
+ sdk,
100
+ chain,
101
+ derivationPath,
102
+ }: {
103
+ sdk: KeepKeySdk;
104
+ chain: Chain;
105
+ derivationPath?: DerivationPathArray;
106
+ }) {
107
+ const { getProvider, getEvmToolboxAsync } = await import("@swapkit/toolboxes/evm");
108
+
109
+ switch (chain) {
110
+ case Chain.BinanceSmartChain:
111
+ case Chain.Arbitrum:
112
+ case Chain.Berachain:
113
+ case Chain.Optimism:
114
+ case Chain.Polygon:
115
+ case Chain.Avalanche:
116
+ case Chain.Base:
117
+ case Chain.Ethereum:
118
+ case Chain.Gnosis:
119
+ case Chain.Monad:
120
+ case Chain.XLayer: {
121
+ const provider = await getProvider(chain);
122
+ const signer = new KeepKeySigner({ chain, derivationPath, provider, sdk });
123
+ const toolbox = await getEvmToolboxAsync(chain, { provider, signer });
124
+
125
+ return toolbox;
126
+ }
127
+ case Chain.Cosmos: {
128
+ return cosmosWalletMethods({ derivationPath, sdk });
129
+ }
130
+ case Chain.THORChain: {
131
+ return thorchainWalletMethods({ derivationPath, sdk });
132
+ }
133
+ case Chain.Maya: {
134
+ return mayachainWalletMethods({ derivationPath, sdk });
135
+ }
136
+ case Chain.Bitcoin:
137
+ case Chain.BitcoinCash:
138
+ case Chain.Dash:
139
+ case Chain.Dogecoin:
140
+ case Chain.Litecoin: {
141
+ return utxoWalletMethods({ chain, derivationPath, sdk });
142
+ }
143
+ case Chain.Ripple: {
144
+ const { rippleWalletMethods } = await import("./chains/ripple");
145
+ return rippleWalletMethods({ derivationPath, sdk });
146
+ }
147
+ default:
148
+ throw new SwapKitError("wallet_keepkey_chain_not_supported", { chain });
149
+ }
150
+ }
151
+
152
+ // kk-sdk docs: https://keepkey.com/blog/building_on_the_keepkey_sdk
153
+ // test spec: if offline, launch keepkey-bridge
154
+ async function checkAndLaunch(attempts = 0) {
155
+ if (attempts >= 3) {
156
+ alert("KeepKey desktop is required for keepkey-sdk, please go to https://keepkey.com/get-started");
157
+ }
158
+ const isAvailable = await checkKeepkeyAvailability();
159
+
160
+ if (!isAvailable) {
161
+ window.location.assign("keepkey://launch");
162
+ await new Promise((resolve) => setTimeout(resolve, 30000));
163
+ await checkAndLaunch(attempts + 1);
164
+ }
165
+ }
166
+
167
+ async function checkKeepkeyAvailability(spec = "http://localhost:1646/spec/swagger.json") {
168
+ try {
169
+ const response = await fetch(spec);
170
+ return response.status === 200;
171
+ } catch {
172
+ return false;
173
+ }
174
+ }
@@ -0,0 +1,84 @@
1
+ import {
2
+ type DerivationPathArray,
3
+ derivationPathToString,
4
+ NetworkDerivationPath,
5
+ SwapKitError,
6
+ } from "@swapkit/helpers";
7
+ import { CosmosLedgerInterface } from "../interfaces/CosmosLedgerInterface";
8
+
9
+ export class CosmosLedger extends CosmosLedgerInterface {
10
+ private pubKey: string | null = null;
11
+
12
+ derivationPath: string;
13
+
14
+ constructor(derivationPath: DerivationPathArray = NetworkDerivationPath.GAIA) {
15
+ super();
16
+ this.chain = "cosmos";
17
+ this.derivationPath = derivationPathToString(derivationPath);
18
+ }
19
+
20
+ connect = async () => {
21
+ await this.checkOrCreateTransportAndLedger(true);
22
+ const { publicKey, address } = await this.getAddressAndPubKey();
23
+
24
+ this.pubKey = Buffer.from(publicKey, "hex").toString("base64");
25
+
26
+ return address;
27
+ };
28
+
29
+ getAddressAndPubKey = async () => {
30
+ await this.checkOrCreateTransportAndLedger(true);
31
+
32
+ const response = await this.ledgerApp.getAddress(this.derivationPath, this.chain);
33
+
34
+ return response;
35
+ };
36
+
37
+ signTransaction = async (rawTx: string, sequence = "0") => {
38
+ await this.checkOrCreateTransportAndLedger(true);
39
+
40
+ const { return_code, error_message, signature } = await this.ledgerApp.sign(this.derivationPath, rawTx);
41
+
42
+ if (!this.pubKey) throw new SwapKitError("wallet_ledger_pubkey_not_found");
43
+
44
+ this.validateResponse(return_code, error_message);
45
+
46
+ return [{ pub_key: { type: "tendermint/PubKeySecp256k1", value: this.pubKey }, sequence, signature }];
47
+ };
48
+
49
+ signAmino = async (signerAddress: string, signDoc: any): Promise<any> => {
50
+ await this.checkOrCreateTransportAndLedger(true);
51
+
52
+ const accounts = await this.getAccounts();
53
+ const accountIndex = accounts.findIndex((account) => account.address === signerAddress);
54
+
55
+ if (accountIndex === -1) {
56
+ throw new SwapKitError("wallet_ledger_address_not_found", { address: signerAddress });
57
+ }
58
+
59
+ const importedAmino = await import("@cosmjs/amino");
60
+ const encodeSecp256k1Signature =
61
+ importedAmino.encodeSecp256k1Signature ?? importedAmino.default?.encodeSecp256k1Signature;
62
+ const serializeSignDoc = importedAmino.serializeSignDoc ?? importedAmino.default?.serializeSignDoc;
63
+ const importedCrypto = await import("@cosmjs/crypto");
64
+ const Secp256k1Signature = importedCrypto.Secp256k1Signature ?? importedCrypto.default?.Secp256k1Signature;
65
+
66
+ const message = serializeSignDoc(signDoc);
67
+ const signature = await this.ledgerApp.sign(this.derivationPath, message);
68
+
69
+ this.validateResponse(signature.return_code, signature.error_message);
70
+
71
+ const secpSignature = Secp256k1Signature.fromDer(signature.signature).toFixedLength();
72
+
73
+ return { signature: encodeSecp256k1Signature(accounts[0].pubkey, secpSignature), signed: signDoc };
74
+ };
75
+
76
+ getAccounts = async () => {
77
+ await this.checkOrCreateTransportAndLedger(true);
78
+
79
+ const addressAndPubKey = await this.getAddressAndPubKey();
80
+ return [
81
+ { address: addressAndPubKey.address, algo: "secp256k1", pubkey: Buffer.from(addressAndPubKey.publicKey, "hex") },
82
+ ] as any[];
83
+ };
84
+ }
@@ -0,0 +1,186 @@
1
+ import type EthereumApp from "@ledgerhq/hw-app-eth";
2
+ import {
3
+ ChainId,
4
+ type DerivationPathArray,
5
+ derivationPathToString,
6
+ NetworkDerivationPath,
7
+ SwapKitError,
8
+ } from "@swapkit/helpers";
9
+ import {
10
+ AbstractSigner,
11
+ type Provider,
12
+ type TransactionRequest,
13
+ type TypedDataDomain,
14
+ type TypedDataField,
15
+ } from "ethers";
16
+
17
+ import { getLedgerTransport } from "../helpers/getLedgerTransport";
18
+
19
+ class EVMLedgerInterface extends AbstractSigner {
20
+ chainId: ChainId = ChainId.Ethereum;
21
+ derivationPath = "";
22
+ ledgerApp: InstanceType<typeof EthereumApp> | null = null;
23
+ ledgerTimeout = 50000;
24
+
25
+ constructor({
26
+ provider,
27
+ derivationPath = NetworkDerivationPath.OP,
28
+ chainId = ChainId.Optimism,
29
+ }: { provider: Provider; derivationPath?: DerivationPathArray | string; chainId?: ChainId }) {
30
+ super(provider);
31
+
32
+ this.chainId = chainId || ChainId.Ethereum;
33
+ this.derivationPath = typeof derivationPath === "string" ? derivationPath : derivationPathToString(derivationPath);
34
+
35
+ Object.defineProperty(this, "provider", { enumerable: true, value: provider || null, writable: false });
36
+ }
37
+
38
+ connect = (provider: Provider) =>
39
+ new EVMLedgerInterface({ chainId: this.chainId, derivationPath: this.derivationPath, provider });
40
+
41
+ checkOrCreateTransportAndLedger = async () => {
42
+ if (this.ledgerApp) return;
43
+ await this.createTransportAndLedger();
44
+ };
45
+
46
+ createTransportAndLedger = async () => {
47
+ const transport = await getLedgerTransport();
48
+ const EthereumApp = (await import("@ledgerhq/hw-app-eth")).default;
49
+
50
+ this.ledgerApp = new EthereumApp(transport);
51
+ };
52
+
53
+ getAddress = async () => {
54
+ const response = await this.getAddressAndPubKey();
55
+ if (!response) throw new SwapKitError("wallet_ledger_failed_to_get_address");
56
+ return response.address;
57
+ };
58
+
59
+ getAddressAndPubKey = async () => {
60
+ await this.createTransportAndLedger();
61
+ return this.ledgerApp?.getAddress(this.derivationPath);
62
+ };
63
+
64
+ showAddressAndPubKey = async () => {
65
+ await this.createTransportAndLedger();
66
+ return this.ledgerApp?.getAddress(this.derivationPath, true);
67
+ };
68
+
69
+ signMessage = async (messageHex: string) => {
70
+ const { Signature } = await import("ethers");
71
+ await this.createTransportAndLedger();
72
+
73
+ const sig = await this.ledgerApp?.signPersonalMessage(this.derivationPath, messageHex);
74
+
75
+ if (!sig) throw new SwapKitError("wallet_ledger_signing_error");
76
+
77
+ sig.r = `0x${sig.r}`;
78
+ sig.s = `0x${sig.s}`;
79
+ return Signature.from(sig).serialized;
80
+ };
81
+
82
+ sendTransaction = async (tx: TransactionRequest): Promise<any> => {
83
+ if (!this.provider) throw new SwapKitError("wallet_ledger_no_provider");
84
+
85
+ const signedTxHex = await this.signTransaction(tx);
86
+
87
+ return await this.provider.broadcastTransaction(signedTxHex);
88
+ };
89
+
90
+ signTypedData = async (
91
+ domain: TypedDataDomain,
92
+ types: Record<string, TypedDataField[]>,
93
+ value: Record<string, unknown>,
94
+ explicitPrimaryType?: string,
95
+ ) => {
96
+ const { buildEIP712DomainType } = await import("@swapkit/toolboxes/evm");
97
+ const { Signature, TypedDataEncoder } = await import("ethers");
98
+ await this.createTransportAndLedger();
99
+
100
+ const { EIP712Domain: _, ...filteredTypes } = types;
101
+ const primaryType = explicitPrimaryType ?? TypedDataEncoder.from(filteredTypes).primaryType;
102
+
103
+ let sig: { v: number; s: string; r: string } | undefined;
104
+
105
+ try {
106
+ sig = await this.ledgerApp?.signEIP712Message(this.derivationPath, {
107
+ domain: domain as Record<string, unknown>,
108
+ message: value,
109
+ primaryType,
110
+ types: { EIP712Domain: buildEIP712DomainType(domain), ...filteredTypes },
111
+ });
112
+ } catch (error) {
113
+ const isLedgerDeviceError = error instanceof Error && "statusCode" in error;
114
+ if (!isLedgerDeviceError || (isLedgerDeviceError && (error as { statusCode: number }).statusCode === 0x6985)) {
115
+ throw error;
116
+ }
117
+
118
+ const domainSeparator = TypedDataEncoder.hashDomain(domain).slice(2);
119
+ const messageHash = TypedDataEncoder.from(filteredTypes).hash(value).slice(2);
120
+
121
+ sig = await this.ledgerApp?.signEIP712HashedMessage(this.derivationPath, domainSeparator, messageHash);
122
+ }
123
+
124
+ if (!sig) throw new SwapKitError("wallet_ledger_signing_error");
125
+
126
+ sig.r = `0x${sig.r}`;
127
+ sig.s = `0x${sig.s}`;
128
+ return Signature.from(sig).serialized;
129
+ };
130
+
131
+ signTransaction = async (tx: TransactionRequest) => {
132
+ const { Transaction } = await import("ethers");
133
+ await this.createTransportAndLedger();
134
+
135
+ const transactionCount = await this.provider?.getTransactionCount(tx.from || (await this.getAddress()));
136
+
137
+ const baseTx = {
138
+ chainId: tx.chainId || this.chainId,
139
+ data: tx.data,
140
+ gasLimit: tx.gasLimit,
141
+ ...(tx.gasPrice && { gasPrice: tx.gasPrice }),
142
+ ...(!tx.gasPrice &&
143
+ tx.maxFeePerGas && { maxFeePerGas: tx.maxFeePerGas, maxPriorityFeePerGas: tx.maxPriorityFeePerGas }),
144
+ nonce: tx.nonce !== undefined ? Number((tx.nonce || transactionCount || 0).toString()) : transactionCount,
145
+ to: tx.to?.toString(),
146
+ type: tx.type && !Number.isNaN(tx.type) ? tx.type : tx.maxFeePerGas ? 2 : 0,
147
+ value: tx.value,
148
+ };
149
+
150
+ // ledger expects the tx to be serialized without the 0x prefix
151
+ const unsignedTx = Transaction.from(baseTx).unsignedSerialized.slice(2);
152
+
153
+ const { ledgerService } = await import("@ledgerhq/hw-app-eth");
154
+
155
+ const resolution = await ledgerService.resolveTransaction(unsignedTx, {}, { erc20: true, externalPlugins: true });
156
+
157
+ const signature = await this.ledgerApp?.signTransaction(this.derivationPath, unsignedTx, resolution);
158
+
159
+ if (!signature) throw new SwapKitError("wallet_ledger_signing_error");
160
+
161
+ const { r, s, v } = signature;
162
+
163
+ return Transaction.from({ ...baseTx, signature: { r: `0x${r}`, s: `0x${s}`, v: Number(BigInt(v)) } }).serialized;
164
+ };
165
+ }
166
+
167
+ type LedgerParams = { provider: Provider; derivationPath?: DerivationPathArray };
168
+
169
+ export const ArbitrumLedger = (params: LedgerParams) =>
170
+ new EVMLedgerInterface({ ...params, chainId: ChainId.Arbitrum });
171
+ export const AuroraLedger = (params: LedgerParams) => new EVMLedgerInterface({ ...params, chainId: ChainId.Aurora });
172
+ export const AvalancheLedger = (params: LedgerParams) =>
173
+ new EVMLedgerInterface({ ...params, chainId: ChainId.Avalanche });
174
+ export const BaseLedger = (params: LedgerParams) => new EVMLedgerInterface({ ...params, chainId: ChainId.Base });
175
+ export const EthereumLedger = (params: LedgerParams) =>
176
+ new EVMLedgerInterface({ ...params, chainId: ChainId.Ethereum });
177
+ export const GnosisLedger = (params: LedgerParams) => new EVMLedgerInterface({ ...params, chainId: ChainId.Gnosis });
178
+ export const OptimismLedger = (params: LedgerParams) =>
179
+ new EVMLedgerInterface({ ...params, chainId: ChainId.Optimism });
180
+ export const PolygonLedger = (params: LedgerParams) => new EVMLedgerInterface({ ...params, chainId: ChainId.Polygon });
181
+ export const BinanceSmartChainLedger = (params: LedgerParams) =>
182
+ new EVMLedgerInterface({ ...params, chainId: ChainId.BinanceSmartChain });
183
+ export const MonadLedger = (params: LedgerParams) => new EVMLedgerInterface({ ...params, chainId: ChainId.Monad });
184
+ export const XLayerLedger = (params: LedgerParams) => new EVMLedgerInterface({ ...params, chainId: ChainId.XLayer });
185
+ export const BerachainLedger = (params: LedgerParams) =>
186
+ new EVMLedgerInterface({ ...params, chainId: ChainId.Berachain });
@@ -0,0 +1,63 @@
1
+ import type { SignedTransaction, Transaction } from "@near-js/transactions";
2
+ import type { DerivationPathArray } from "@swapkit/helpers";
3
+ import type { NearSigner } from "@swapkit/toolboxes/near";
4
+ import { getLedgerTransport } from "../helpers/getLedgerTransport";
5
+
6
+ export async function getNearLedgerClient(derivationPath?: DerivationPathArray) {
7
+ const Near = (await import("@ledgerhq/hw-app-near")).default;
8
+ const { Chain, NetworkDerivationPath, SwapKitError } = await import("@swapkit/helpers");
9
+ const transport = await getLedgerTransport();
10
+ const nearApp = new Near(transport);
11
+
12
+ const path = (derivationPath || NetworkDerivationPath[Chain.Near]).join("'/").concat("'");
13
+
14
+ const { address, publicKey: pubKeyHex } = await nearApp.getAddress(path);
15
+
16
+ const signer = {
17
+ getAddress() {
18
+ return Promise.resolve(address);
19
+ },
20
+ async getPublicKey() {
21
+ const { PublicKey } = await import("@near-js/crypto");
22
+ return PublicKey.fromString(`ed25519:${pubKeyHex}`);
23
+ },
24
+
25
+ signDelegateAction(_delegateAction: any) {
26
+ return Promise.reject(
27
+ new SwapKitError("wallet_ledger_method_not_supported", { method: "signDelegateAction", wallet: "Ledger" }),
28
+ );
29
+ },
30
+
31
+ signNep413Message(
32
+ _message: string,
33
+ _accountId: string,
34
+ _recipient: string,
35
+ _nonce: Uint8Array,
36
+ _callbackUrl?: string,
37
+ ) {
38
+ return Promise.reject(
39
+ new SwapKitError("wallet_ledger_method_not_supported", { method: "signNep413Message", wallet: "Ledger" }),
40
+ );
41
+ },
42
+
43
+ async signTransaction(transaction: Transaction) {
44
+ const { Signature, SignedTransaction } = await import("@near-js/transactions");
45
+ try {
46
+ const signatureArray = await nearApp.signTransaction(transaction.encode(), path);
47
+ if (!signatureArray) {
48
+ throw new Error("Signature undefined");
49
+ }
50
+
51
+ const signature = new Signature({ data: signatureArray, keyType: 0 });
52
+
53
+ const signedTransaction = new SignedTransaction({ signature, transaction });
54
+
55
+ return [signatureArray, signedTransaction] as [Uint8Array<ArrayBufferLike>, SignedTransaction];
56
+ } catch (error) {
57
+ throw new SwapKitError("wallet_ledger_signing_error", { error });
58
+ }
59
+ },
60
+ };
61
+
62
+ return signer as NearSigner;
63
+ }