@swapkit/wallet-hardware 4.1.42 → 4.2.3

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 (48) hide show
  1. package/dist/index.cjs +2 -2
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.js +1 -2
  4. package/dist/index.js.map +1 -1
  5. package/dist/ledger/index.cjs +2 -2
  6. package/dist/ledger/index.cjs.map +3 -3
  7. package/dist/ledger/index.js +2 -2
  8. package/dist/ledger/index.js.map +3 -3
  9. package/dist/trezor/index.cjs +2 -2
  10. package/dist/trezor/index.cjs.map +3 -3
  11. package/dist/trezor/index.js +2 -2
  12. package/dist/trezor/index.js.map +3 -3
  13. package/dist/types/index.d.ts.map +1 -1
  14. package/dist/types/keepkey/index.d.ts +2 -2
  15. package/dist/types/ledger/helpers/getLedgerTransport.d.ts.map +1 -1
  16. package/dist/types/ledger/index.d.ts +2 -2
  17. package/dist/types/trezor/index.d.ts +2 -2
  18. package/package.json +53 -30
  19. package/src/index.ts +1 -0
  20. package/src/keepkey/chains/cosmos.ts +69 -0
  21. package/src/keepkey/chains/evm.ts +114 -0
  22. package/src/keepkey/chains/mayachain.ts +98 -0
  23. package/src/keepkey/chains/ripple.ts +88 -0
  24. package/src/keepkey/chains/thorchain.ts +93 -0
  25. package/src/keepkey/chains/utxo.ts +137 -0
  26. package/src/keepkey/coins.ts +67 -0
  27. package/src/keepkey/index.ts +153 -0
  28. package/src/ledger/clients/cosmos.ts +84 -0
  29. package/src/ledger/clients/evm.ts +140 -0
  30. package/src/ledger/clients/near.ts +63 -0
  31. package/src/ledger/clients/thorchain/common.ts +93 -0
  32. package/src/ledger/clients/thorchain/helpers.ts +120 -0
  33. package/src/ledger/clients/thorchain/index.ts +87 -0
  34. package/src/ledger/clients/thorchain/lib.ts +278 -0
  35. package/src/ledger/clients/thorchain/utils.ts +69 -0
  36. package/src/ledger/clients/tron.ts +85 -0
  37. package/src/ledger/clients/utxo.ts +154 -0
  38. package/src/ledger/clients/xrp.ts +50 -0
  39. package/src/ledger/cosmosTypes.ts +98 -0
  40. package/src/ledger/helpers/getLedgerAddress.ts +69 -0
  41. package/src/ledger/helpers/getLedgerClient.ts +113 -0
  42. package/src/ledger/helpers/getLedgerTransport.ts +102 -0
  43. package/src/ledger/helpers/index.ts +3 -0
  44. package/src/ledger/index.ts +297 -0
  45. package/src/ledger/interfaces/CosmosLedgerInterface.ts +54 -0
  46. package/src/ledger/types.ts +40 -0
  47. package/src/trezor/evmSigner.ts +177 -0
  48. package/src/trezor/index.ts +347 -0
@@ -0,0 +1,137 @@
1
+ import type { KeepKeySdk } from "@keepkey/keepkey-sdk";
2
+ import {
3
+ Chain,
4
+ DerivationPath,
5
+ type DerivationPathArray,
6
+ derivationPathToString,
7
+ FeeOption,
8
+ type GenericTransferParams,
9
+ SwapKitError,
10
+ type UTXOChain,
11
+ } from "@swapkit/helpers";
12
+ import type { UTXOToolboxes } from "@swapkit/toolboxes/utxo";
13
+ import type { Psbt } from "bitcoinjs-lib";
14
+ import { bip32ToAddressNList, ChainToKeepKeyName } from "../coins";
15
+
16
+ interface KeepKeyInputObject {
17
+ addressNList: number[];
18
+ scriptType: string;
19
+ amount: string;
20
+ vout: number;
21
+ txid: string;
22
+ hex: string;
23
+ }
24
+
25
+ export async function utxoWalletMethods({
26
+ sdk,
27
+ chain,
28
+ derivationPath,
29
+ }: {
30
+ sdk: KeepKeySdk;
31
+ chain: Exclude<UTXOChain, typeof Chain.Zcash>;
32
+ derivationPath?: DerivationPathArray;
33
+ }): Promise<
34
+ UTXOToolboxes[UTXOChain] & {
35
+ address: string;
36
+ signTransaction: (psbt: Psbt, inputs: KeepKeyInputObject[], memo?: string) => Promise<string>;
37
+ }
38
+ > {
39
+ const { getUtxoToolbox } = await import("@swapkit/toolboxes/utxo");
40
+ // This might not work for BCH
41
+ const toolbox = await getUtxoToolbox(chain);
42
+ const scriptType = [Chain.Bitcoin, Chain.Litecoin].includes(chain as typeof Chain.Bitcoin)
43
+ ? ("p2wpkh" as const)
44
+ : ("p2pkh" as const);
45
+
46
+ const derivationPathString = derivationPath ? derivationPathToString(derivationPath) : `${DerivationPath[chain]}/0`;
47
+
48
+ const addressInfo = {
49
+ address_n: bip32ToAddressNList(derivationPathString),
50
+ coin: ChainToKeepKeyName[chain],
51
+ script_type: scriptType,
52
+ };
53
+
54
+ const walletAddress: string = (await sdk.address.utxoGetAddress(addressInfo)).address;
55
+
56
+ const signTransaction = async (psbt: Psbt, inputs: KeepKeyInputObject[], memo = "") => {
57
+ const outputs = psbt.txOutputs
58
+ .map((output) => {
59
+ const { value, address, change } = output as {
60
+ address: string;
61
+ script: Buffer;
62
+ value: number;
63
+ change?: boolean;
64
+ };
65
+
66
+ const outputAddress =
67
+ // @ts-expect-error - stripToCashAddress is not defined in the UTXO toolbox just only on BCH
68
+ chain === Chain.BitcoinCash ? toolbox.stripToCashAddress(address) : address;
69
+
70
+ if (change || address === walletAddress) {
71
+ return {
72
+ addressNList: addressInfo.address_n,
73
+ addressType: "change",
74
+ amount: value,
75
+ isChange: true,
76
+ scriptType,
77
+ };
78
+ }
79
+
80
+ if (outputAddress) {
81
+ return { address: outputAddress, addressType: "spend", amount: value };
82
+ }
83
+
84
+ return null;
85
+ })
86
+ .filter(Boolean);
87
+
88
+ const removeNullAndEmptyObjectsFromArray = (arr: any[]) => {
89
+ return arr.filter((item) => item !== null && typeof item === "object" && Object.keys(item).length > 0);
90
+ };
91
+
92
+ const responseSign = await sdk.utxo.utxoSignTransaction({
93
+ coin: ChainToKeepKeyName[chain],
94
+ inputs,
95
+ opReturnData: memo,
96
+ outputs: removeNullAndEmptyObjectsFromArray(outputs),
97
+ });
98
+
99
+ return responseSign.serializedTx?.toString();
100
+ };
101
+
102
+ const transfer = async ({ recipient, feeOptionKey, feeRate, memo, ...rest }: GenericTransferParams) => {
103
+ if (!walletAddress)
104
+ throw new SwapKitError("wallet_keepkey_invalid_params", { reason: "From address must be provided" });
105
+ if (!recipient)
106
+ throw new SwapKitError("wallet_keepkey_invalid_params", { reason: "Recipient address must be provided" });
107
+
108
+ const createTxMethod =
109
+ chain === Chain.BitcoinCash
110
+ ? (toolbox as UTXOToolboxes["BCH"]).buildTx
111
+ : (toolbox as UTXOToolboxes["BTC"]).createTransaction;
112
+
113
+ const { psbt, inputs: rawInputs } = await createTxMethod({
114
+ ...rest,
115
+ feeRate: feeRate || (await toolbox.getFeeRates())[feeOptionKey || FeeOption.Fast],
116
+ fetchTxHex: true,
117
+ memo,
118
+ recipient,
119
+ sender: walletAddress,
120
+ });
121
+
122
+ const inputs = rawInputs.map(({ value, index, hash, txHex }) => ({
123
+ //@TODO don't hardcode master, lookup on blockbook what input this is for and what path that address is!
124
+ addressNList: addressInfo.address_n,
125
+ amount: value.toString(),
126
+ hex: txHex || "",
127
+ scriptType,
128
+ txid: hash,
129
+ vout: index,
130
+ }));
131
+
132
+ const txHex = await signTransaction(psbt, inputs, memo);
133
+ return toolbox.broadcastTx(txHex);
134
+ };
135
+
136
+ return { ...toolbox, address: walletAddress, signTransaction, transfer };
137
+ }
@@ -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,153 @@
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
+ name: "connectKeepkey",
56
+ supportedChains: [
57
+ Chain.Arbitrum,
58
+ Chain.Avalanche,
59
+ Chain.Base,
60
+ Chain.BinanceSmartChain,
61
+ Chain.Bitcoin,
62
+ Chain.BitcoinCash,
63
+ Chain.Cosmos,
64
+ Chain.Dogecoin,
65
+ Chain.Dash,
66
+ Chain.Ethereum,
67
+ Chain.Litecoin,
68
+ Chain.Ripple,
69
+ Chain.Optimism,
70
+ Chain.Polygon,
71
+ Chain.THORChain,
72
+ Chain.Maya,
73
+ Chain.XLayer,
74
+ ],
75
+ walletType: WalletOption.KEEPKEY,
76
+ });
77
+
78
+ export const KEEPKEY_SUPPORTED_CHAINS = getWalletSupportedChains(keepkeyWallet);
79
+
80
+ async function getWalletMethods({
81
+ sdk,
82
+ chain,
83
+ derivationPath,
84
+ }: {
85
+ sdk: KeepKeySdk;
86
+ chain: Chain;
87
+ derivationPath?: DerivationPathArray;
88
+ }) {
89
+ const { getProvider, getEvmToolbox } = await import("@swapkit/toolboxes/evm");
90
+
91
+ switch (chain) {
92
+ case Chain.BinanceSmartChain:
93
+ case Chain.Arbitrum:
94
+ case Chain.Optimism:
95
+ case Chain.Polygon:
96
+ case Chain.Avalanche:
97
+ case Chain.Base:
98
+ case Chain.Ethereum:
99
+ case Chain.XLayer: {
100
+ const provider = await getProvider(chain);
101
+ const signer = new KeepKeySigner({ chain, derivationPath, provider, sdk });
102
+ const toolbox = await getEvmToolbox(chain, { provider, signer });
103
+
104
+ return toolbox;
105
+ }
106
+ case Chain.Cosmos: {
107
+ return cosmosWalletMethods({ derivationPath, sdk });
108
+ }
109
+ case Chain.THORChain: {
110
+ return thorchainWalletMethods({ derivationPath, sdk });
111
+ }
112
+ case Chain.Maya: {
113
+ return mayachainWalletMethods({ derivationPath, sdk });
114
+ }
115
+ case Chain.Bitcoin:
116
+ case Chain.BitcoinCash:
117
+ case Chain.Dash:
118
+ case Chain.Dogecoin:
119
+ case Chain.Litecoin: {
120
+ return utxoWalletMethods({ chain, derivationPath, sdk });
121
+ }
122
+ case Chain.Ripple: {
123
+ const { rippleWalletMethods } = await import("./chains/ripple");
124
+ return rippleWalletMethods({ derivationPath, sdk });
125
+ }
126
+ default:
127
+ throw new SwapKitError("wallet_keepkey_chain_not_supported", { chain });
128
+ }
129
+ }
130
+
131
+ // kk-sdk docs: https://keepkey.com/blog/building_on_the_keepkey_sdk
132
+ // test spec: if offline, launch keepkey-bridge
133
+ async function checkAndLaunch(attempts = 0) {
134
+ if (attempts >= 3) {
135
+ alert("KeepKey desktop is required for keepkey-sdk, please go to https://keepkey.com/get-started");
136
+ }
137
+ const isAvailable = await checkKeepkeyAvailability();
138
+
139
+ if (!isAvailable) {
140
+ window.location.assign("keepkey://launch");
141
+ await new Promise((resolve) => setTimeout(resolve, 30000));
142
+ await checkAndLaunch(attempts + 1);
143
+ }
144
+ }
145
+
146
+ async function checkKeepkeyAvailability(spec = "http://localhost:1646/spec/swagger.json") {
147
+ try {
148
+ const response = await fetch(spec);
149
+ return response.status === 200;
150
+ } catch {
151
+ return false;
152
+ }
153
+ }
@@ -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,140 @@
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 { AbstractSigner, type Provider, type TransactionRequest } from "ethers";
10
+
11
+ import { getLedgerTransport } from "../helpers/getLedgerTransport";
12
+
13
+ class EVMLedgerInterface extends AbstractSigner {
14
+ chainId: ChainId = ChainId.Ethereum;
15
+ derivationPath = "";
16
+ ledgerApp: InstanceType<typeof EthereumApp> | null = null;
17
+ ledgerTimeout = 50000;
18
+
19
+ constructor({
20
+ provider,
21
+ derivationPath = NetworkDerivationPath.OP,
22
+ chainId = ChainId.Optimism,
23
+ }: { provider: Provider; derivationPath?: DerivationPathArray | string; chainId?: ChainId }) {
24
+ super(provider);
25
+
26
+ this.chainId = chainId || ChainId.Ethereum;
27
+ this.derivationPath = typeof derivationPath === "string" ? derivationPath : derivationPathToString(derivationPath);
28
+
29
+ Object.defineProperty(this, "provider", { enumerable: true, value: provider || null, writable: false });
30
+ }
31
+
32
+ connect = (provider: Provider) =>
33
+ new EVMLedgerInterface({ chainId: this.chainId, derivationPath: this.derivationPath, provider });
34
+
35
+ checkOrCreateTransportAndLedger = async () => {
36
+ if (this.ledgerApp) return;
37
+ await this.createTransportAndLedger();
38
+ };
39
+
40
+ createTransportAndLedger = async () => {
41
+ const transport = await getLedgerTransport();
42
+ const EthereumApp = (await import("@ledgerhq/hw-app-eth")).default;
43
+
44
+ this.ledgerApp = new EthereumApp(transport);
45
+ };
46
+
47
+ getAddress = async () => {
48
+ const response = await this.getAddressAndPubKey();
49
+ if (!response) throw new SwapKitError("wallet_ledger_failed_to_get_address");
50
+ return response.address;
51
+ };
52
+
53
+ getAddressAndPubKey = async () => {
54
+ await this.createTransportAndLedger();
55
+ return this.ledgerApp?.getAddress(this.derivationPath);
56
+ };
57
+
58
+ showAddressAndPubKey = async () => {
59
+ await this.createTransportAndLedger();
60
+ return this.ledgerApp?.getAddress(this.derivationPath, true);
61
+ };
62
+
63
+ signMessage = async (messageHex: string) => {
64
+ const { Signature } = await import("ethers");
65
+ await this.createTransportAndLedger();
66
+
67
+ const sig = await this.ledgerApp?.signPersonalMessage(this.derivationPath, messageHex);
68
+
69
+ if (!sig) throw new SwapKitError("wallet_ledger_signing_error");
70
+
71
+ sig.r = `0x${sig.r}`;
72
+ sig.s = `0x${sig.s}`;
73
+ return Signature.from(sig).serialized;
74
+ };
75
+
76
+ sendTransaction = async (tx: TransactionRequest): Promise<any> => {
77
+ if (!this.provider) throw new SwapKitError("wallet_ledger_no_provider");
78
+
79
+ const signedTxHex = await this.signTransaction(tx);
80
+
81
+ return await this.provider.broadcastTransaction(signedTxHex);
82
+ };
83
+
84
+ signTypedData(): Promise<string> {
85
+ throw new SwapKitError("wallet_ledger_method_not_supported", { method: "signTypedData" });
86
+ }
87
+
88
+ signTransaction = async (tx: TransactionRequest) => {
89
+ const { Transaction } = await import("ethers");
90
+ await this.createTransportAndLedger();
91
+
92
+ const transactionCount = await this.provider?.getTransactionCount(tx.from || (await this.getAddress()));
93
+
94
+ const baseTx = {
95
+ chainId: tx.chainId || this.chainId,
96
+ data: tx.data,
97
+ gasLimit: tx.gasLimit,
98
+ ...(tx.gasPrice && { gasPrice: tx.gasPrice }),
99
+ ...(!tx.gasPrice &&
100
+ tx.maxFeePerGas && { maxFeePerGas: tx.maxFeePerGas, maxPriorityFeePerGas: tx.maxPriorityFeePerGas }),
101
+ nonce: tx.nonce !== undefined ? Number((tx.nonce || transactionCount || 0).toString()) : transactionCount,
102
+ to: tx.to?.toString(),
103
+ type: tx.type && !Number.isNaN(tx.type) ? tx.type : tx.maxFeePerGas ? 2 : 0,
104
+ value: tx.value,
105
+ };
106
+
107
+ // ledger expects the tx to be serialized without the 0x prefix
108
+ const unsignedTx = Transaction.from(baseTx).unsignedSerialized.slice(2);
109
+
110
+ const { ledgerService } = await import("@ledgerhq/hw-app-eth");
111
+
112
+ const resolution = await ledgerService.resolveTransaction(unsignedTx, {}, { erc20: true, externalPlugins: true });
113
+
114
+ const signature = await this.ledgerApp?.signTransaction(this.derivationPath, unsignedTx, resolution);
115
+
116
+ if (!signature) throw new SwapKitError("wallet_ledger_signing_error");
117
+
118
+ const { r, s, v } = signature;
119
+
120
+ return Transaction.from({ ...baseTx, signature: { r: `0x${r}`, s: `0x${s}`, v: Number(BigInt(v)) } }).serialized;
121
+ };
122
+ }
123
+
124
+ type LedgerParams = { provider: Provider; derivationPath?: DerivationPathArray };
125
+
126
+ export const ArbitrumLedger = (params: LedgerParams) =>
127
+ new EVMLedgerInterface({ ...params, chainId: ChainId.Arbitrum });
128
+ export const AuroraLedger = (params: LedgerParams) => new EVMLedgerInterface({ ...params, chainId: ChainId.Aurora });
129
+ export const AvalancheLedger = (params: LedgerParams) =>
130
+ new EVMLedgerInterface({ ...params, chainId: ChainId.Avalanche });
131
+ export const BaseLedger = (params: LedgerParams) => new EVMLedgerInterface({ ...params, chainId: ChainId.Base });
132
+ export const EthereumLedger = (params: LedgerParams) =>
133
+ new EVMLedgerInterface({ ...params, chainId: ChainId.Ethereum });
134
+ export const GnosisLedger = (params: LedgerParams) => new EVMLedgerInterface({ ...params, chainId: ChainId.Gnosis });
135
+ export const OptimismLedger = (params: LedgerParams) =>
136
+ new EVMLedgerInterface({ ...params, chainId: ChainId.Optimism });
137
+ export const PolygonLedger = (params: LedgerParams) => new EVMLedgerInterface({ ...params, chainId: ChainId.Polygon });
138
+ export const BinanceSmartChainLedger = (params: LedgerParams) =>
139
+ new EVMLedgerInterface({ ...params, chainId: ChainId.BinanceSmartChain });
140
+ export const XLayerLedger = (params: LedgerParams) => new EVMLedgerInterface({ ...params, chainId: ChainId.XLayer });
@@ -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
+ }