@swapkit/wallet-hardware 4.9.5 → 4.9.6

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,4 @@
1
+ var C=require("@scure/base"),F=require("@scure/bip32"),R=require("@swapkit/helpers");function b(G){switch(G){case"bech32":return"wpkh(@0/**)";case"p2sh":return"sh(wpkh(@0/**))";case"legacy":return"pkh(@0/**)";default:return"wpkh(@0/**)"}}function P(G){return typeof G==="string"?G:R.derivationPathToString(G)}function X(G){return G.replace(/^m\//,"").replace(/^\/+/,"")}function x(G){return G.replace(/^m\//,"").split("/").filter(Boolean).map((Q)=>{let V=Q.endsWith("'"),Y=Number.parseInt(V?Q.slice(0,-1):Q,10);return V?(Y|2147483648)>>>0:Y})}function g(G,Q){let V=G.getInput(Q);return Boolean(V.bip32Derivation?.length)}var S=({chain:G})=>{return(Q,V)=>{let Y,H;async function $(){if(!Y){let q=V??await k(),{AppClient:J}=await import("ledger-bitcoin");Y=new J(q)}return Y}async function L(){if(!H)H=await(await $()).getMasterFingerprint();return H}let j=X(Q?P(Q):"84'/0'/0'/0/0"),w=j.split("/").filter(Boolean),N=w.slice(0,3).join("/"),E=w.slice(3),K=Number(E[0]??0),B=Number(E[1]??0),T=R.getWalletFormatFor(j),I=b(T),z,O;async function U(){let q=await $(),J=await L();if(!z)z=await q.getExtendedPubkey(`m/${N}`);let{DefaultWalletPolicy:M}=await import("ledger-bitcoin"),W=new M(I,`[${J}/${N}]${z}`);return{app:q,fpr:J,policy:W,xpub:z}}async function v(){if(!O){let{xpub:q}=await U(),M=F.HDKey.fromExtendedKey(q).derive(`m/${K}/${B}`);if(!M.publicKey)throw new R.SwapKitError("wallet_ledger_get_address_error",{message:`Cannot derive leaf pubkey for ${G}`});O=M.publicKey}return O}return{connect:async()=>{await $()},getAddress:async()=>{let{app:q,policy:J}=await U(),M=await q.getWalletAddress(J,null,K,B,!1);if(!M)throw new R.SwapKitError("wallet_ledger_get_address_error",{message:`Cannot get ${G} address from ledger derivation path: ${j}`});return M},getExtendedPublicKey:async(q=`m/${N}`)=>{return(await $()).getExtendedPubkey(`m/${X(q)}`)},signTransaction:async(q)=>{let{app:J,policy:M,fpr:W}=await U(),A=Number.parseInt(W,16)>>>0,f=x(j),D=Array.from({length:q.inputsLength},(Z,_)=>_).filter((Z)=>!g(q,Z));if(D.length>0){let Z=await v();for(let _ of D)q.updateInput(_,{bip32Derivation:[[Z,{fingerprint:A,path:f}]]})}let y=C.base64.encode(q.toPSBT(0)),m=await J.signPsbt(y,M,null);for(let[Z,_]of m)q.updateInput(Z,{partialSig:[[new Uint8Array(_.pubkey),new Uint8Array(_.signature)]]});return q}}}},l=S({chain:"bitcoin"}),s=S({chain:"litecoin"});
2
+
3
+ //# debugId=2C91C97B5CF5D4DF64756E2164756E21
4
+ //# sourceMappingURL=chunk-3gajmdgz.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/ledger/clients/utxo-psbt.ts"],
4
+ "sourcesContent": [
5
+ "import type Transport from \"@ledgerhq/hw-transport\";\nimport { base64 } from \"@scure/base\";\nimport { HDKey } from \"@scure/bip32\";\nimport { type DerivationPathArray, derivationPathToString, getWalletFormatFor, SwapKitError } from \"@swapkit/helpers\";\nimport type { Transaction } from \"@swapkit/utxo-signer\";\n\nimport { getLedgerTransport } from \"../helpers/getLedgerTransport\";\n\ntype SupportedCoin = \"bitcoin\" | \"litecoin\";\n\ntype DefaultDescriptorTemplate = \"wpkh(@0/**)\" | \"tr(@0/**)\" | \"sh(wpkh(@0/**))\" | \"pkh(@0/**)\";\n\nfunction templateForFormat(format: ReturnType<typeof getWalletFormatFor>): DefaultDescriptorTemplate {\n switch (format) {\n case \"bech32\":\n return \"wpkh(@0/**)\";\n case \"p2sh\":\n return \"sh(wpkh(@0/**))\";\n case \"legacy\":\n return \"pkh(@0/**)\";\n default:\n return \"wpkh(@0/**)\";\n }\n}\n\nfunction pathToString(path: DerivationPathArray | string): string {\n return typeof path === \"string\" ? path : derivationPathToString(path);\n}\n\nfunction normalizeLedgerPath(path: string): string {\n return path.replace(/^m\\//, \"\").replace(/^\\/+/, \"\");\n}\n\nfunction pathToNumberArray(path: string): number[] {\n return path\n .replace(/^m\\//, \"\")\n .split(\"/\")\n .filter(Boolean)\n .map((p) => {\n const hardened = p.endsWith(\"'\");\n const num = Number.parseInt(hardened ? p.slice(0, -1) : p, 10);\n return hardened ? (num | 0x80000000) >>> 0 : num;\n });\n}\n\nfunction hasBip32Derivation(tx: Transaction, inputIndex: number) {\n const input = tx.getInput(inputIndex) as { bip32Derivation?: Array<unknown> };\n\n return Boolean(input.bip32Derivation?.length);\n}\n\nconst BaseLedgerPsbtUTXO = ({ chain }: { chain: SupportedCoin }) => {\n return (derivationPathArray?: DerivationPathArray | string, injectedTransport?: Transport) => {\n // Per-call state — each BitcoinPsbtLedger/LitecoinPsbtLedger invocation has its own\n // AppClient and master fingerprint so different consumers (e.g. concurrent MCP\n // sessions on different devices) cannot inherit each other's ledger bindings or xpub.\n let appClient: import(\"ledger-bitcoin\").AppClient | undefined;\n let masterFingerprint: string | undefined;\n\n async function getAppClient() {\n if (!appClient) {\n const transport = injectedTransport ?? (await getLedgerTransport());\n const { AppClient } = await import(\"ledger-bitcoin\");\n appClient = new AppClient(transport);\n }\n return appClient;\n }\n\n async function getFingerprint() {\n if (!masterFingerprint) {\n const app = await getAppClient();\n masterFingerprint = await app.getMasterFingerprint();\n }\n return masterFingerprint;\n }\n\n // Single-address account: change == index == 0 by default.\n const derivationPath = normalizeLedgerPath(\n derivationPathArray ? pathToString(derivationPathArray) : \"84'/0'/0'/0/0\",\n );\n const pathSegments = derivationPath.split(\"/\").filter(Boolean);\n const accountPath = pathSegments.slice(0, 3).join(\"/\");\n const leafSegments = pathSegments.slice(3);\n const change = Number(leafSegments[0] ?? 0);\n const addressIndex = Number(leafSegments[1] ?? 0);\n const format = getWalletFormatFor(derivationPath);\n const template = templateForFormat(format);\n\n let cachedAccountXpub: string | undefined;\n let cachedLeafPubkey: Uint8Array | undefined;\n\n async function buildPolicy() {\n const app = await getAppClient();\n const fpr = await getFingerprint();\n if (!cachedAccountXpub) {\n cachedAccountXpub = await app.getExtendedPubkey(`m/${accountPath}`);\n }\n const { DefaultWalletPolicy } = await import(\"ledger-bitcoin\");\n const policy = new DefaultWalletPolicy(template, `[${fpr}/${accountPath}]${cachedAccountXpub}`);\n return { app, fpr, policy, xpub: cachedAccountXpub };\n }\n\n async function getLeafPubkey() {\n if (!cachedLeafPubkey) {\n const { xpub } = await buildPolicy();\n const accountKey = HDKey.fromExtendedKey(xpub);\n const leaf = accountKey.derive(`m/${change}/${addressIndex}`);\n if (!leaf.publicKey) {\n throw new SwapKitError(\"wallet_ledger_get_address_error\", {\n message: `Cannot derive leaf pubkey for ${chain}`,\n });\n }\n cachedLeafPubkey = leaf.publicKey;\n }\n return cachedLeafPubkey;\n }\n\n return {\n connect: async () => {\n await getAppClient();\n },\n getAddress: async () => {\n const { app, policy } = await buildPolicy();\n const address = await app.getWalletAddress(policy, null, change, addressIndex, false);\n if (!address) {\n throw new SwapKitError(\"wallet_ledger_get_address_error\", {\n message: `Cannot get ${chain} address from ledger derivation path: ${derivationPath}`,\n });\n }\n return address;\n },\n getExtendedPublicKey: async (path = `m/${accountPath}`) => {\n const app = await getAppClient();\n return app.getExtendedPubkey(`m/${normalizeLedgerPath(path)}`);\n },\n signTransaction: async (tx: Transaction): Promise<Transaction> => {\n const { app, policy, fpr } = await buildPolicy();\n const fingerprintBE = Number.parseInt(fpr, 16) >>> 0;\n const pathNumbers = pathToNumberArray(derivationPath);\n const missingDerivationIndexes = Array.from({ length: tx.inputsLength }, (_, inputIndex) => inputIndex).filter(\n (inputIndex) => !hasBip32Derivation(tx, inputIndex),\n );\n\n if (missingDerivationIndexes.length > 0) {\n const leafPubkey = await getLeafPubkey();\n\n // Fallback for PSBTs that do not include per-input HD key origins.\n for (const inputIndex of missingDerivationIndexes) {\n tx.updateInput(inputIndex, {\n bip32Derivation: [[leafPubkey, { fingerprint: fingerprintBE, path: pathNumbers }]],\n });\n }\n }\n\n const psbtB64 = base64.encode(tx.toPSBT(0));\n const sigs = await app.signPsbt(psbtB64, policy, null);\n\n for (const [idx, partial] of sigs) {\n tx.updateInput(idx, { partialSig: [[new Uint8Array(partial.pubkey), new Uint8Array(partial.signature)]] });\n }\n\n return tx;\n },\n };\n };\n};\n\nexport const BitcoinPsbtLedger = BaseLedgerPsbtUTXO({ chain: \"bitcoin\" });\nexport const LitecoinPsbtLedger = BaseLedgerPsbtUTXO({ chain: \"litecoin\" });\n"
6
+ ],
7
+ "mappings": "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",
8
+ "debugId": "2C91C97B5CF5D4DF64756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,4 @@
1
+ import{c as C}from"./chunk-3yr76n9s.js";import{d as D}from"./chunk-n05bv2n5.js";import{base64 as m}from"@scure/base";import{HDKey as b}from"@scure/bip32";import{derivationPathToString as P,getWalletFormatFor as x,SwapKitError as X}from"@swapkit/helpers";function g(G){switch(G){case"bech32":return"wpkh(@0/**)";case"p2sh":return"sh(wpkh(@0/**))";case"legacy":return"pkh(@0/**)";default:return"wpkh(@0/**)"}}function u(G){return typeof G==="string"?G:P(G)}function k(G){return G.replace(/^m\//,"").replace(/^\/+/,"")}function l(G){return G.replace(/^m\//,"").split("/").filter(Boolean).map((Q)=>{let R=Q.endsWith("'"),V=Number.parseInt(R?Q.slice(0,-1):Q,10);return R?(V|2147483648)>>>0:V})}function s(G,Q){let R=G.getInput(Q);return Boolean(R.bip32Derivation?.length)}var F=({chain:G})=>{return(Q,R)=>{let V,z;async function _(){if(!V){let q=R??await C(),{AppClient:J}=await import("ledger-bitcoin");V=new J(q)}return V}async function S(){if(!z)z=await(await _()).getMasterFingerprint();return z}let $=k(Q?u(Q):"84'/0'/0'/0/0"),W=$.split("/").filter(Boolean),H=W.slice(0,3).join("/"),w=W.slice(3),E=Number(w[0]??0),K=Number(w[1]??0),L=x($),T=g(L),j,N;async function O(){let q=await _(),J=await S();if(!j)j=await q.getExtendedPubkey(`m/${H}`);let{DefaultWalletPolicy:M}=await import("ledger-bitcoin"),U=new M(T,`[${J}/${H}]${j}`);return{app:q,fpr:J,policy:U,xpub:j}}async function I(){if(!N){let{xpub:q}=await O(),M=b.fromExtendedKey(q).derive(`m/${E}/${K}`);if(!M.publicKey)throw new X("wallet_ledger_get_address_error",{message:`Cannot derive leaf pubkey for ${G}`});N=M.publicKey}return N}return{connect:async()=>{await _()},getAddress:async()=>{let{app:q,policy:J}=await O(),M=await q.getWalletAddress(J,null,E,K,!1);if(!M)throw new X("wallet_ledger_get_address_error",{message:`Cannot get ${G} address from ledger derivation path: ${$}`});return M},getExtendedPublicKey:async(q=`m/${H}`)=>{return(await _()).getExtendedPubkey(`m/${k(q)}`)},signTransaction:async(q)=>{let{app:J,policy:M,fpr:U}=await O(),v=Number.parseInt(U,16)>>>0,A=l($),B=Array.from({length:q.inputsLength},(Y,Z)=>Z).filter((Y)=>!s(q,Y));if(B.length>0){let Y=await I();for(let Z of B)q.updateInput(Z,{bip32Derivation:[[Y,{fingerprint:v,path:A}]]})}let f=m.encode(q.toPSBT(0)),y=await J.signPsbt(f,M,null);for(let[Y,Z]of y)q.updateInput(Y,{partialSig:[[new Uint8Array(Z.pubkey),new Uint8Array(Z.signature)]]});return q}}}},n=F({chain:"bitcoin"}),p=F({chain:"litecoin"});export{p as LitecoinPsbtLedger,n as BitcoinPsbtLedger};
2
+
3
+ //# debugId=891D5D7B8F0B7C8C64756E2164756E21
4
+ //# sourceMappingURL=chunk-jttnd211.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/ledger/clients/utxo-psbt.ts"],
4
+ "sourcesContent": [
5
+ "import type Transport from \"@ledgerhq/hw-transport\";\nimport { base64 } from \"@scure/base\";\nimport { HDKey } from \"@scure/bip32\";\nimport { type DerivationPathArray, derivationPathToString, getWalletFormatFor, SwapKitError } from \"@swapkit/helpers\";\nimport type { Transaction } from \"@swapkit/utxo-signer\";\n\nimport { getLedgerTransport } from \"../helpers/getLedgerTransport\";\n\ntype SupportedCoin = \"bitcoin\" | \"litecoin\";\n\ntype DefaultDescriptorTemplate = \"wpkh(@0/**)\" | \"tr(@0/**)\" | \"sh(wpkh(@0/**))\" | \"pkh(@0/**)\";\n\nfunction templateForFormat(format: ReturnType<typeof getWalletFormatFor>): DefaultDescriptorTemplate {\n switch (format) {\n case \"bech32\":\n return \"wpkh(@0/**)\";\n case \"p2sh\":\n return \"sh(wpkh(@0/**))\";\n case \"legacy\":\n return \"pkh(@0/**)\";\n default:\n return \"wpkh(@0/**)\";\n }\n}\n\nfunction pathToString(path: DerivationPathArray | string): string {\n return typeof path === \"string\" ? path : derivationPathToString(path);\n}\n\nfunction normalizeLedgerPath(path: string): string {\n return path.replace(/^m\\//, \"\").replace(/^\\/+/, \"\");\n}\n\nfunction pathToNumberArray(path: string): number[] {\n return path\n .replace(/^m\\//, \"\")\n .split(\"/\")\n .filter(Boolean)\n .map((p) => {\n const hardened = p.endsWith(\"'\");\n const num = Number.parseInt(hardened ? p.slice(0, -1) : p, 10);\n return hardened ? (num | 0x80000000) >>> 0 : num;\n });\n}\n\nfunction hasBip32Derivation(tx: Transaction, inputIndex: number) {\n const input = tx.getInput(inputIndex) as { bip32Derivation?: Array<unknown> };\n\n return Boolean(input.bip32Derivation?.length);\n}\n\nconst BaseLedgerPsbtUTXO = ({ chain }: { chain: SupportedCoin }) => {\n return (derivationPathArray?: DerivationPathArray | string, injectedTransport?: Transport) => {\n // Per-call state — each BitcoinPsbtLedger/LitecoinPsbtLedger invocation has its own\n // AppClient and master fingerprint so different consumers (e.g. concurrent MCP\n // sessions on different devices) cannot inherit each other's ledger bindings or xpub.\n let appClient: import(\"ledger-bitcoin\").AppClient | undefined;\n let masterFingerprint: string | undefined;\n\n async function getAppClient() {\n if (!appClient) {\n const transport = injectedTransport ?? (await getLedgerTransport());\n const { AppClient } = await import(\"ledger-bitcoin\");\n appClient = new AppClient(transport);\n }\n return appClient;\n }\n\n async function getFingerprint() {\n if (!masterFingerprint) {\n const app = await getAppClient();\n masterFingerprint = await app.getMasterFingerprint();\n }\n return masterFingerprint;\n }\n\n // Single-address account: change == index == 0 by default.\n const derivationPath = normalizeLedgerPath(\n derivationPathArray ? pathToString(derivationPathArray) : \"84'/0'/0'/0/0\",\n );\n const pathSegments = derivationPath.split(\"/\").filter(Boolean);\n const accountPath = pathSegments.slice(0, 3).join(\"/\");\n const leafSegments = pathSegments.slice(3);\n const change = Number(leafSegments[0] ?? 0);\n const addressIndex = Number(leafSegments[1] ?? 0);\n const format = getWalletFormatFor(derivationPath);\n const template = templateForFormat(format);\n\n let cachedAccountXpub: string | undefined;\n let cachedLeafPubkey: Uint8Array | undefined;\n\n async function buildPolicy() {\n const app = await getAppClient();\n const fpr = await getFingerprint();\n if (!cachedAccountXpub) {\n cachedAccountXpub = await app.getExtendedPubkey(`m/${accountPath}`);\n }\n const { DefaultWalletPolicy } = await import(\"ledger-bitcoin\");\n const policy = new DefaultWalletPolicy(template, `[${fpr}/${accountPath}]${cachedAccountXpub}`);\n return { app, fpr, policy, xpub: cachedAccountXpub };\n }\n\n async function getLeafPubkey() {\n if (!cachedLeafPubkey) {\n const { xpub } = await buildPolicy();\n const accountKey = HDKey.fromExtendedKey(xpub);\n const leaf = accountKey.derive(`m/${change}/${addressIndex}`);\n if (!leaf.publicKey) {\n throw new SwapKitError(\"wallet_ledger_get_address_error\", {\n message: `Cannot derive leaf pubkey for ${chain}`,\n });\n }\n cachedLeafPubkey = leaf.publicKey;\n }\n return cachedLeafPubkey;\n }\n\n return {\n connect: async () => {\n await getAppClient();\n },\n getAddress: async () => {\n const { app, policy } = await buildPolicy();\n const address = await app.getWalletAddress(policy, null, change, addressIndex, false);\n if (!address) {\n throw new SwapKitError(\"wallet_ledger_get_address_error\", {\n message: `Cannot get ${chain} address from ledger derivation path: ${derivationPath}`,\n });\n }\n return address;\n },\n getExtendedPublicKey: async (path = `m/${accountPath}`) => {\n const app = await getAppClient();\n return app.getExtendedPubkey(`m/${normalizeLedgerPath(path)}`);\n },\n signTransaction: async (tx: Transaction): Promise<Transaction> => {\n const { app, policy, fpr } = await buildPolicy();\n const fingerprintBE = Number.parseInt(fpr, 16) >>> 0;\n const pathNumbers = pathToNumberArray(derivationPath);\n const missingDerivationIndexes = Array.from({ length: tx.inputsLength }, (_, inputIndex) => inputIndex).filter(\n (inputIndex) => !hasBip32Derivation(tx, inputIndex),\n );\n\n if (missingDerivationIndexes.length > 0) {\n const leafPubkey = await getLeafPubkey();\n\n // Fallback for PSBTs that do not include per-input HD key origins.\n for (const inputIndex of missingDerivationIndexes) {\n tx.updateInput(inputIndex, {\n bip32Derivation: [[leafPubkey, { fingerprint: fingerprintBE, path: pathNumbers }]],\n });\n }\n }\n\n const psbtB64 = base64.encode(tx.toPSBT(0));\n const sigs = await app.signPsbt(psbtB64, policy, null);\n\n for (const [idx, partial] of sigs) {\n tx.updateInput(idx, { partialSig: [[new Uint8Array(partial.pubkey), new Uint8Array(partial.signature)]] });\n }\n\n return tx;\n },\n };\n };\n};\n\nexport const BitcoinPsbtLedger = BaseLedgerPsbtUTXO({ chain: \"bitcoin\" });\nexport const LitecoinPsbtLedger = BaseLedgerPsbtUTXO({ chain: \"litecoin\" });\n"
6
+ ],
7
+ "mappings": "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",
8
+ "debugId": "891D5D7B8F0B7C8C64756E2164756E21",
9
+ "names": []
10
+ }
@@ -1,5 +1,5 @@
1
1
  var P0={};Y0(P0,{ledgerWallet:()=>B0,LEDGER_SUPPORTED_CHAINS:()=>H0});module.exports=Q0(P0);var w=require("@swapkit/helpers"),Y=require("@swapkit/toolboxes/utxo"),WL=require("@swapkit/wallet-core");var J=require("@swapkit/helpers"),v=async({chain:L,ledgerClient:y})=>{if(!y)return"";switch(L){case J.Chain.Cosmos:case J.Chain.THORChain:return y.connect();case J.Chain.Ethereum:case J.Chain.BinanceSmartChain:case J.Chain.Avalanche:case J.Chain.Polygon:case J.Chain.Arbitrum:case J.Chain.Berachain:case J.Chain.Optimism:case J.Chain.Base:case J.Chain.Aurora:case J.Chain.Gnosis:case J.Chain.Monad:case J.Chain.XLayer:return y.getAddress();case J.Chain.Bitcoin:case J.Chain.BitcoinCash:case J.Chain.Dash:case J.Chain.Dogecoin:case J.Chain.Litecoin:case J.Chain.Zcash:{let _=y;await _.connect();let R=await _.getAddress();return L===J.Chain.BitcoinCash?R.replace("bitcoincash:",""):R}case J.Chain.Near:return await y.getAddress();case J.Chain.Ripple:return y.getAddress();case J.Chain.Tron:return y.getAddress();case J.Chain.Sui:return y.connect();default:throw new J.SwapKitError("wallet_chain_not_supported",{chain:L,wallet:J.WalletOption.LEDGER})}};var N=require("@swapkit/helpers");var h=require("@swapkit/helpers");var c=require("@swapkit/helpers");var ML=require("@swapkit/helpers");var n=85,UL=250;var x={GET_ADDR_SECP256K1:4,GET_VERSION:0,INS_PUBLIC_KEY_SECP256K1:1,SIGN_SECP256K1:2},jL={ADD:1,INIT:0,LAST:2},ZL={ONLY_RETRIEVE:0,SHOW_ADDRESS_IN_DEVICE:1},o={JSON:0},g={NoError:36864},AL={1:"U2F: Unknown",2:"U2F: Bad request",3:"U2F: Configuration unsupported",4:"U2F: Device Ineligible",5:"U2F: Timeout",14:"Timeout",25600:"Execution Error",26368:"Wrong Length",26626:"Error deriving keys",27010:"Empty Buffer",27011:"Output buffer too small",27012:"Data is invalid",27013:"Conditions not satisfied",27014:"Transaction rejected",27264:"Bad key handle",27392:"Invalid P1/P2",27904:"Instruction not supported",28160:"App does not seem to be open",28416:"Unknown error",28417:"Sign/verify error",36864:"No errors",36865:"Device is busy"};function k(L){if(L in AL)return AL[L];return`Unknown Status Code: ${L}`}function W0(L){return typeof L==="object"&&L!==null&&!Array.isArray(L)&&!(L instanceof Date)}function z(L){if(L){if(W0(L)){if(Object.hasOwn(L,"statusCode"))return{error_message:k(L.statusCode),return_code:L.statusCode};if(Object.hasOwn(L,"return_code")&&Object.hasOwn(L,"error_message"))return L}return{error_message:L.toString(),return_code:65535}}return{error_message:L.toString(),return_code:65535}}function $L(L){return L.send(85,x.GET_VERSION,0,0).then((y)=>{let _=y.slice(-2),R=_[0]*256+_[1],T=0;if(y.length>=9)T=(y[5]<<24)+(y[6]<<16)+(y[7]<<8)+(y[8]<<0);return{device_locked:y[4]===1,error_message:k(R),major:y[1],minor:y[2],patch:y[3],return_code:R,target_id:T.toString(16),test_mode:y[0]!==0}},z)}var _L=require("@swapkit/helpers");function PL(L){if(L==null||L.length<3)throw new _L.SwapKitError("wallet_ledger_invalid_params",{reason:"Path too short"});if(L.length>10)throw new _L.SwapKitError("wallet_ledger_invalid_params",{reason:"Path too long"});let y=Buffer.alloc(1+4*L.length);y.writeUInt8(L.length,0);for(let _=0;_<L.length;_+=1){let R=L[_]||0;if(_<3)R|=2147483648;y.writeInt32LE(R,1+_*4)}return y}function CL(L,y,_,R,T=o.JSON){return L.transport.send(n,x.SIGN_SECP256K1,y,T,R,[g.NoError,27012,27264]).then((m)=>{let G=m.slice(-2),O=G[0]*256+G[1],B=k(O);if(O===27264||O===27012)B=`${B} : ${m.slice(0,m.length-2).toString("ascii")}`;let F=null;if(m.length>2)F=m.slice(0,m.length-2);return{error_message:B,return_code:O,signature:F}},z)}function D0(L){if(L.length!==65)throw new _L.SwapKitError("wallet_ledger_invalid_params",{reason:"decompressed public key length should be 65 bytes"});let y=L.slice(33,65),_=Buffer.from([2+(y[y.length-1]&1)]);return Buffer.concat([_,L.slice(1,33)])}function SL(L,y){return L.transport.send(n,x.INS_PUBLIC_KEY_SECP256K1,0,0,y,[g.NoError]).then((_)=>{let R=_.slice(-2),T=R[0]*256+R[1],m=Buffer.from(_.slice(0,65));return{compressed_pk:D0(m),error_message:k(T),pk:m,return_code:T}},z)}function zL(L){if(!L||L.length!==5)throw new _L.SwapKitError("wallet_ledger_invalid_params",{reason:"Path must be exactly 5 elements"});let y=Buffer.alloc(20);return y.writeUInt32LE(2147483648+L[0],0),y.writeUInt32LE(2147483648+L[1],4),y.writeUInt32LE(2147483648+L[2],8),y.writeUInt32LE(L[3],12),y.writeUInt32LE(L[4],16),y}function KL(L,y,_,R,T=o.JSON){let m=jL.ADD;if(y===1)m=jL.INIT;if(y===_)m=jL.LAST;return CL(L,m,0,R,T)}function VL(L,y){return L.transport.send(n,x.GET_ADDR_SECP256K1,0,0,y,[g.NoError]).then((_)=>{let R=_.slice(-2),T=R[0]*256+R[1];return{compressed_pk:Buffer.from(_.slice(0,33)),error_message:k(T),pk:"OBSOLETE PROPERTY",return_code:T}},z)}class TL{transport;versionResponse;constructor(L){if(!L)throw new ML.SwapKitError("wallet_ledger_transport_not_defined");this.transport=L}static serializeHRP(L){if(L==null||L.length<3||L.length>83)throw new ML.SwapKitError("wallet_ledger_invalid_params",{reason:"Invalid HRP"});let y=Buffer.alloc(1+L.length);return y.writeUInt8(L.length,0),y.write(L,1),y}async serializePath(L){if(this.versionResponse=await $L(this.transport),this.versionResponse.return_code!==g.NoError)throw this.versionResponse;switch(this.versionResponse.major){case 1:return PL(L);case 2:return zL(L);default:return Buffer.alloc(0)}}async signGetChunks(L,y){let _=await this.serializePath(L),R=[];R.push(_);for(let T=0;T<y.length;T+=UL){let m=T+UL;if(T>y.length)m=y.length;R.push(y.slice(T,m))}return R}async getVersion(){try{return this.versionResponse=await $L(this.transport),this.versionResponse}catch(L){return z(L)}}appInfo(){return this.transport.send(176,1,0,0).then((L)=>{let y=L.readUInt16BE(L.length-2),_="",R="",T=0,m=0;if(L[0]!==1)return{error_message:"response format ID not recognized",return_code:36865};let G=L[1];_=L.slice(2,2+G).toString("ascii");let O=2+G,B=L[O];O+=1,R=L.slice(O,O+B).toString("ascii"),O+=B;let F=L[O];return O+=1,T=F,m=L[O],{appName:_,appVersion:R,error_message:k(y),flag_onboarded:(m&4)!==0,flag_pin_validated:(m&128)!==0,flag_recovery:(m&1)!==0,flag_signed_mcu_code:(m&2)!==0,flagLen:T,flagsValue:m,return_code:y}},z)}deviceInfo(){return this.transport.send(224,1,0,0,Buffer.from([]),[g.NoError,28160]).then((L)=>{let y=L.slice(-2),_=y[0]*256+y[1];if(_===28160)return{error_message:"This command is only available in the Dashboard",return_code:_};let R=L.slice(0,4).toString("hex"),T=4,m=L[T];T+=1;let G=L.slice(T,T+m).toString();T+=m;let O=L[T];T+=1;let B=L.slice(T,T+O).toString("hex");T+=O;let F=L[T];T+=1;let X=L.slice(T,T+F);if(X[F-1]===0)X=L.slice(T,T+F-1);let j=X.toString();return{error_message:k(_),flag:B,mcuVersion:j,return_code:_,seVersion:G,targetId:R}},z)}async publicKey(L){try{let y=await this.serializePath(L);switch(this.versionResponse.major){case 1:return SL(this,y);case 2:{let _=Buffer.concat([TL.serializeHRP("thor"),y]);return VL(this,_)}default:return{error_message:"App Version is not supported",return_code:25600}}}catch(y){return z(y)}}async getAddressAndPubKey(L,y,_=!1){try{let R=await this.serializePath(L),T=Buffer.concat([TL.serializeHRP(y),R]),m=await this.transport.send(n,x.GET_ADDR_SECP256K1,_?ZL.SHOW_ADDRESS_IN_DEVICE:ZL.ONLY_RETRIEVE,0,T,[g.NoError]),G=Buffer.from(m.slice(0,33)),O=Buffer.from(m.slice(33,-2)).toString(),B=m.readUInt16BE(m.length-2);return{bech32_address:O,compressed_pk:G,error_message:k(B),return_code:B}}catch(R){return z(R)}}showAddressAndPubKey(L,y){return this.getAddressAndPubKey(L,y,!0)}signSendChunk(L,y,_,R=o.JSON){switch(this.versionResponse.major){case 1:return CL(this,L,y,_,R);case 2:return KL(this,L,y,_,R);default:return{error_message:"App Version is not supported",return_code:25600}}}async sign(L,y,_=o.JSON){let R=Buffer.from(y),T=[],m;try{T=await this.signGetChunks(L,R),m=await this.signSendChunk(1,T.length,T[0],_)}catch(O){z(O)}let G={error_message:m.error_message,return_code:m.return_code,signature:null};for(let O=1;O<T.length;O+=1)if(G=await this.signSendChunk(1+O,T.length,T[O],_),G.return_code!==g.NoError)break;return{error_message:G.error_message,return_code:G.return_code,signature:G.signature}}}class wL{ledgerTimeout=50000;derivationPath=c.NetworkDerivationPath.GAIA;transport;ledgerApp;chain="thor";injectedTransport;constructor(L){if(this.injectedTransport=L,L)this.transport=L}checkOrCreateTransportAndLedger=async(L=!1)=>{if(!L&&this.transport&&this.ledgerApp)return;try{if(!this.transport||L&&!this.injectedTransport)this.transport=this.injectedTransport??await q();switch(this.chain){case"thor":{this.ledgerApp=L||!this.ledgerApp?new TL(this.transport):this.ledgerApp;break}case"cosmos":{let _=(await import("@ledgerhq/hw-app-cosmos")).default;this.ledgerApp=L||!this.ledgerApp?new _(this.transport):this.ledgerApp}}return this.ledgerApp}catch(y){throw new c.SwapKitError("wallet_ledger_connection_error",y)}};validateResponse=(L,y)=>{switch(L){case c.LedgerErrorCode.NoError:return;case c.LedgerErrorCode.LockedDevice:throw new c.SwapKitError("wallet_ledger_device_locked",{message:`Ledger is locked: ${y}`});case c.LedgerErrorCode.TC_NotFound:throw new c.SwapKitError("wallet_ledger_device_not_found");default:break}}}class QL extends wL{pubKey=null;derivationPath;constructor(L=h.NetworkDerivationPath.GAIA,y){super(y);this.chain="cosmos",this.derivationPath=h.derivationPathToString(L)}connect=async()=>{await this.checkOrCreateTransportAndLedger(!0);let{publicKey:L,address:y}=await this.getAddressAndPubKey();return this.pubKey=Buffer.from(L,"hex").toString("base64"),y};getAddressAndPubKey=async()=>{return await this.checkOrCreateTransportAndLedger(!0),await this.ledgerApp.getAddress(this.derivationPath,this.chain)};signTransaction=async(L,y="0")=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:_,error_message:R,signature:T}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new h.SwapKitError("wallet_ledger_pubkey_not_found");return this.validateResponse(_,R),[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:y,signature:T}]};signAmino=async(L,y)=>{await this.checkOrCreateTransportAndLedger(!0);let _=await this.getAccounts();if(_.findIndex((Z)=>Z.address===L)===-1)throw new h.SwapKitError("wallet_ledger_address_not_found",{address:L});let T=await import("@cosmjs/amino"),m=T.encodeSecp256k1Signature??T.default?.encodeSecp256k1Signature,G=T.serializeSignDoc??T.default?.serializeSignDoc,O=await import("@cosmjs/crypto"),B=O.Secp256k1Signature??O.default?.Secp256k1Signature,F=G(y),X=await this.ledgerApp.sign(this.derivationPath,F);this.validateResponse(X.return_code,X.error_message);let j=B.fromDer(X.signature).toFixedLength();return{signature:m(_[0].pubkey,j),signed:y}};getAccounts=async()=>{await this.checkOrCreateTransportAndLedger(!0);let L=await this.getAddressAndPubKey();return[{address:L.address,algo:"secp256k1",pubkey:Buffer.from(L.publicKey,"hex")}]}}var $=require("@swapkit/helpers"),kL=require("ethers");class S extends kL.AbstractSigner{chainId=$.ChainId.Ethereum;derivationPath="";ledgerApp=null;ledgerTimeout=50000;injectedTransport;constructor({provider:L,derivationPath:y=$.NetworkDerivationPath.OP,chainId:_=$.ChainId.Optimism,transport:R}){super(L);this.chainId=_||$.ChainId.Ethereum,this.derivationPath=typeof y==="string"?y:$.derivationPathToString(y),this.injectedTransport=R,Object.defineProperty(this,"provider",{enumerable:!0,value:L||null,writable:!1})}connect=(L)=>new S({chainId:this.chainId,derivationPath:this.derivationPath,provider:L,transport:this.injectedTransport});checkOrCreateTransportAndLedger=async()=>{if(this.ledgerApp)return;await this.createTransportAndLedger()};createTransportAndLedger=async()=>{let L=this.injectedTransport??await q(),y=(await import("@ledgerhq/hw-app-eth")).default;this.ledgerApp=new y(L)};getAddress=async()=>{let L=await this.getAddressAndPubKey();if(!L)throw new $.SwapKitError("wallet_ledger_failed_to_get_address");return L.address};getAddressAndPubKey=async()=>{return await this.createTransportAndLedger(),this.ledgerApp?.getAddress(this.derivationPath)};showAddressAndPubKey=async()=>{return await this.createTransportAndLedger(),this.ledgerApp?.getAddress(this.derivationPath,!0)};signMessage=async(L)=>{let{Signature:y}=await import("ethers");await this.createTransportAndLedger();let _=await this.ledgerApp?.signPersonalMessage(this.derivationPath,L);if(!_)throw new $.SwapKitError("wallet_ledger_signing_error");return _.r=`0x${_.r}`,_.s=`0x${_.s}`,y.from(_).serialized};sendTransaction=async(L)=>{if(!this.provider)throw new $.SwapKitError("wallet_ledger_no_provider");let y=await this.signTransaction(L);return await this.provider.broadcastTransaction(y)};signTypedData=async(L,y,_,R)=>{let{buildEIP712DomainType:T}=await import("@swapkit/toolboxes/evm"),{Signature:m,TypedDataEncoder:G}=await import("ethers");await this.createTransportAndLedger();let{EIP712Domain:O,...B}=y,F=R??G.from(B).primaryType,X;try{X=await this.ledgerApp?.signEIP712Message(this.derivationPath,{domain:L,message:_,primaryType:F,types:{EIP712Domain:T(L),...B}})}catch(j){let Z=j instanceof Error&&"statusCode"in j;if(!Z||Z&&j.statusCode===27013)throw j;let Q=G.hashDomain(L).slice(2),H=G.from(B).hash(_).slice(2);X=await this.ledgerApp?.signEIP712HashedMessage(this.derivationPath,Q,H)}if(!X)throw new $.SwapKitError("wallet_ledger_signing_error");return X.r=`0x${X.r}`,X.s=`0x${X.s}`,m.from(X).serialized};signTransaction=async(L)=>{let{Transaction:y}=await import("ethers");await this.createTransportAndLedger();let _=await this.provider?.getTransactionCount(L.from||await this.getAddress()),R={chainId:L.chainId||this.chainId,data:L.data,gasLimit:L.gasLimit,...L.gasPrice&&{gasPrice:L.gasPrice},...!L.gasPrice&&L.maxFeePerGas&&{maxFeePerGas:L.maxFeePerGas,maxPriorityFeePerGas:L.maxPriorityFeePerGas},nonce:L.nonce!==void 0?Number((L.nonce||_||0).toString()):_,to:L.to?.toString(),type:L.type&&!Number.isNaN(L.type)?L.type:L.maxFeePerGas?2:0,value:L.value},T=y.from(R).unsignedSerialized.slice(2),{ledgerService:m}=await import("@ledgerhq/hw-app-eth"),G=await m.resolveTransaction(T,{},{erc20:!0,externalPlugins:!0}),O=await this.ledgerApp?.signTransaction(this.derivationPath,T,G);if(!O)throw new $.SwapKitError("wallet_ledger_signing_error");let{r:B,s:F,v:X}=O;return y.from({...R,signature:{r:`0x${B}`,s:`0x${F}`,v:Number(BigInt(X))}}).serialized}}var cL=(L)=>new S({...L,chainId:$.ChainId.Arbitrum}),IL=(L)=>new S({...L,chainId:$.ChainId.Aurora}),EL=(L)=>new S({...L,chainId:$.ChainId.Avalanche}),vL=(L)=>new S({...L,chainId:$.ChainId.Base}),gL=(L)=>new S({...L,chainId:$.ChainId.Ethereum}),bL=(L)=>new S({...L,chainId:$.ChainId.Gnosis}),lL=(L)=>new S({...L,chainId:$.ChainId.Optimism}),xL=(L)=>new S({...L,chainId:$.ChainId.Polygon}),hL=(L)=>new S({...L,chainId:$.ChainId.BinanceSmartChain}),dL=(L)=>new S({...L,chainId:$.ChainId.Monad}),iL=(L)=>new S({...L,chainId:$.ChainId.XLayer}),uL=(L)=>new S({...L,chainId:$.ChainId.Berachain});async function nL(L,y){let _=(await import("@ledgerhq/hw-app-near")).default,{Chain:R,NetworkDerivationPath:T,SwapKitError:m}=await import("@swapkit/helpers"),G=y??await q(),O=new _(G),B=(L||T[R.Near]).join("'/").concat("'"),{address:F,publicKey:X}=await O.getAddress(B);return{getAddress(){return Promise.resolve(F)},async getPublicKey(){let{PublicKey:Z}=await import("@near-js/crypto");return Z.fromString(`ed25519:${X}`)},signDelegateAction(Z){return Promise.reject(new m("wallet_ledger_method_not_supported",{method:"signDelegateAction",wallet:"Ledger"}))},signNep413Message(Z,Q,H,f,W){return Promise.reject(new m("wallet_ledger_method_not_supported",{method:"signNep413Message",wallet:"Ledger"}))},async signTransaction(Z){let{Signature:Q,SignedTransaction:H}=await import("@near-js/transactions");try{let f=await O.signTransaction(Z.encode(),B);if(!f)throw Error("Signature undefined");let W=new Q({data:f,keyType:0}),C=new H({signature:W,transaction:Z});return[f,C]}catch(f){throw new m("wallet_ledger_signing_error",{error:f})}}}}var A=require("@swapkit/helpers");class oL{derivationPath;ledgerApp=null;address=null;publicKey=null;injectedTransport;constructor(L,y){this.derivationPath=typeof L==="string"?L:A.derivationPathToString(L||A.NetworkDerivationPath[A.Chain.Sui]),this.injectedTransport=y}getLedgerPath(){return this.derivationPath.replace(/^m\//,"").replace(/\/(\d+)\/(\d+)$/,"/$1'/$2'")}async createTransportAndLedger(){if(this.ledgerApp)return;let L=this.injectedTransport??await q(),y=(await import("@ledgerhq/hw-app-sui")).default;this.ledgerApp=new y(L)}async connect(){if(await this.createTransportAndLedger(),!this.ledgerApp)throw new A.SwapKitError("wallet_ledger_transport_error");let L=this.getLedgerPath(),y=await this.ledgerApp.getPublicKey(L);if(!y?.publicKey)throw new A.SwapKitError("wallet_ledger_failed_to_get_address");return this.publicKey=y.publicKey,this.address=`0x${Buffer.from(y.address).toString("hex")}`,this.address}toSuiAddress(){if(!this.address)throw new A.SwapKitError("wallet_ledger_failed_to_get_address");return this.address}async getAddress(){if(this.address)return this.address;return await this.connect()}async signTransaction(L){let y=L instanceof Uint8Array?L:L.transaction;if(await this.createTransportAndLedger(),!this.ledgerApp)throw new A.SwapKitError("wallet_ledger_transport_error");if(!this.publicKey)throw new A.SwapKitError("wallet_ledger_failed_to_get_address");try{let _=this.getLedgerPath(),R=new Uint8Array(3+y.length);R[0]=0,R[1]=0,R[2]=0,R.set(y,3);let T=await this.ledgerApp.signTransaction(_,R);if(!T?.signature)throw new A.SwapKitError("wallet_ledger_signing_error");let m=this.publicKey.length===33?this.publicKey.slice(1):this.publicKey;if(m.length!==32)throw new A.SwapKitError("wallet_ledger_signing_error",{error:"Invalid public key length"});let G=new Uint8Array(97);G[0]=0,G.set(T.signature,1),G.set(m,65);let O=Buffer.from(G).toString("base64");return{bytes:Buffer.from(y).toString("base64"),signature:O}}catch(_){throw new A.SwapKitError("wallet_ledger_signing_error",{error:_})}}}var tL=(L,y)=>new oL(L,y);var aL=require("@scure/base"),mL=require("@swapkit/helpers");var pL=require("@scure/base"),I=require("@swapkit/helpers"),YL=(L)=>{if(L.length<64)throw new I.SwapKitError("wallet_ledger_invalid_signature",{reason:"Too short"});if(L[0]!==48)throw new I.SwapKitError("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected first byte 0x30"});if(L[1]+2!==L.length)throw new I.SwapKitError("wallet_ledger_invalid_signature",{reason:"signature length does not match TLV"});if(L[2]!==2)throw new I.SwapKitError("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected length type 0x02"});let y=L[3],_=L.slice(4,y+4);if(_.length===33&&_[0]===0)_=_.slice(1,33);else if(_.length===33)throw new I.SwapKitError("wallet_ledger_invalid_signature",{reason:"r too long"});while(_.length<32)_.unshift(0);if(L[y+4]!==2)throw new I.SwapKitError("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected length type 0x02 for s"});let R=L[y+5];if(4+y+2+R!==L.length)throw new I.SwapKitError("wallet_ledger_invalid_signature",{reason:"TLV byte lengths do not match message length"});let T=L.slice(y+6,L.length);if(T.length===33&&T[0]===0)T=T.slice(1,33);else if(T.length===33)throw new I.SwapKitError("wallet_ledger_invalid_signature",{reason:"s too long"});while(T.length<32)T.unshift(0);if(_.length!==32||T.length!==32)throw new I.SwapKitError("wallet_ledger_invalid_signature",{reason:"must be 32 bytes each"});return pL.base64.encode(Buffer.concat([_,T]))};class HL extends wL{pubKey=null;derivationPath;constructor(L=mL.NetworkDerivationPath.THOR,y){super(y);this.chain="thor",this.derivationPath=L}get pubkey(){return this.pubKey}connect=async()=>{await this.checkOrCreateTransportAndLedger();let{compressed_pk:L,bech32_address:y}=await this.getAddressAndPubKey();return this.pubKey=aL.base64.encode(L),y};getAddressAndPubKey=async()=>{await this.checkOrCreateTransportAndLedger(!0);let L=await this.ledgerApp.getAddressAndPubKey(this.derivationPath,this.chain);return this.validateResponse(L.return_code,L.error_message),L};showAddressAndPubKey=async()=>{await this.checkOrCreateTransportAndLedger(!0);let L=await this.ledgerApp.showAddressAndPubKey(this.derivationPath,this.chain);return this.validateResponse(L.return_code,L.error_message),L};signTransaction=async(L,y="0")=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:_,error_message:R,signature:T}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new mL.SwapKitError("wallet_ledger_pubkey_not_found");return this.validateResponse(_,R),[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:y,signature:YL(T)}]};sign=async(L)=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:y,error_message:_,signature:R}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new mL.SwapKitError("wallet_ledger_pubkey_not_found");return this.validateResponse(y,_),YL(R)}}var E=require("@swapkit/helpers");class eL{derivationPath;ledgerApp=null;ledgerTimeout=50000;injectedTransport;constructor(L,y){this.derivationPath=typeof L==="string"?L:E.derivationPathToString(L||E.NetworkDerivationPath.TRON),this.injectedTransport=y}checkOrCreateTransportAndLedger=async()=>{if(this.ledgerApp)return;await this.createTransportAndLedger()};createTransportAndLedger=async()=>{let L=this.injectedTransport??await q(),y=(await import("@ledgerhq/hw-app-trx")).default;this.ledgerApp=new y(L)};getAddress=async()=>{let L=await this.getAddressAndPubKey();if(!L)throw new E.SwapKitError("wallet_ledger_failed_to_get_address");return L.address};getAddressAndPubKey=async()=>{await this.createTransportAndLedger();let L=await this.ledgerApp?.getAddress(this.derivationPath);if(!L)throw new E.SwapKitError("wallet_ledger_failed_to_get_address");return{address:L.address,publicKey:L.publicKey}};showAddressAndPubKey=async()=>{return await this.createTransportAndLedger(),this.ledgerApp?.getAddress(this.derivationPath,!0)};signTransaction=async(L)=>{if(await this.createTransportAndLedger(),!this.ledgerApp)throw new E.SwapKitError("wallet_ledger_transport_error");let y=JSON.stringify(L);try{let _=await this.ledgerApp.signTransaction(this.derivationPath,y,[]);if(!_)throw new E.SwapKitError("wallet_ledger_signing_error");return{...L,signature:[_]}}catch(_){throw new E.SwapKitError("wallet_ledger_signing_error",{error:_})}}}var sL=(L,y)=>new eL(L,y);var RL=require("@scure/base"),b=require("@swapkit/helpers");var L0=["bitcoin-cash","dash","dogecoin","zcash"],rL=({tx:L,inputUtxos:y,btcApp:_,derivationPath:R,chain:T},m)=>{let G=y.map((j)=>{return[_.splitTransaction(j.txHex||"",!L0.includes(T),T==="zcash"),j.index,void 0,void 0]}),O=RL.hex.encode(L.unsignedTx),B=_.splitTransaction(O,!0),F=_.serializeTransactionOutputs(B).toString("hex"),X={additionals:["bech32"],associatedKeysets:G.map(()=>R),inputs:G,outputScriptHex:F,segwit:!0,useTrustedInputForSegwit:!0};return _.createPaymentTransaction({...X,...m})},J0=({tx:L,inputUtxos:y,btcApp:_,derivationPaths:R,chain:T},m)=>{if(R.length!==y.length)throw new b.SwapKitError("wallet_ledger_invalid_params",{message:`Derivation paths count (${R.length}) must match inputs count (${y.length})`});let G=y.map((j)=>{return[_.splitTransaction(j.txHex||"",!L0.includes(T),T==="zcash"),j.index,void 0,void 0]}),O=RL.hex.encode(L.unsignedTx),B=_.splitTransaction(O,!0),F=_.serializeTransactionOutputs(B).toString("hex"),X={additionals:["bech32"],associatedKeysets:R,inputs:G,outputScriptHex:F,segwit:!0,useTrustedInputForSegwit:!0};return _.createPaymentTransaction({...X,...m})},t=({chain:L,additionalSignParams:y})=>{return(_,R)=>{let T,m=null;async function G(X=!0){if(X&&!T)new b.SwapKitError("wallet_ledger_connection_error",{message:`Ledger connection failed:
2
- ${JSON.stringify({btcApp:T,checkBtcApp:X})}`});m||=R??await q()}async function O(){m=R??await q(),T=new(await import("@ledgerhq/hw-app-btc")).default({currency:L,transport:m})}let B=typeof _==="string"?_:b.derivationPathToString(_),F=b.getWalletFormatFor(B);return{connect:async()=>{await G(!1),T=new(await import("@ledgerhq/hw-app-btc")).default({currency:L,transport:m})},getAddress:async()=>{let{toCashAddress:X}=await import("@swapkit/toolboxes/utxo");await G(!1);let{bitcoinAddress:j}=await T.getWalletPublicKey(B,{format:F});if(!j)throw new b.SwapKitError("wallet_ledger_get_address_error",{message:`Cannot get ${L} address from ledger derivation path: ${B}`});return L==="bitcoin-cash"&&F==="legacy"?X(j).replace(/(bchtest:|bitcoincash:)/,""):j},getExtendedPublicKey:async(X="84'/0'/0'",j=76067358)=>{return await G(!1),T.getWalletXpub({path:X,xpubVersion:j})},signPCZT:async(X)=>{if(L!=="zcash")throw new b.SwapKitError("wallet_ledger_chain_not_supported",{message:"PCZT signing is only supported for Zcash"});await O();let{ZcashTransaction:j,Script:Z}=await import("@swapkit/utxo-signer"),Q=X.getGlobal(),H=new j({consensusBranchId:Q.consensusBranchId,expiryHeight:Q.expiryHeight,lockTime:Q.lockTime,version:Q.txVersion,versionGroupId:Q.versionGroupId}),f=[];for(let D=0;D<X.inputsLength;D++){let U=X.getInput(D);H.addInput({index:U.index,script:new Uint8Array,sequence:U.sequence??4294967295,txid:U.txid,value:U.value}),f.push({hash:RL.hex.encode(new Uint8Array([...U.txid].reverse())),index:U.index,txHex:U0(U,Q),value:Number(U.value),witnessUtxo:{script:U.scriptPubkey,value:Number(U.value)}})}for(let D=0;D<X.outputsLength;D++){let U=X.getOutput(D);H.addOutput({amount:U.value,script:U.scriptPubkey})}let W=await rL({btcApp:T,chain:L,derivationPath:B,inputUtxos:f,tx:H},{...y,expiryHeight:(()=>{let D=Buffer.alloc(4);return D.writeUInt32LE(Q.expiryHeight),D})(),lockTime:Q.lockTime}),C=j.fromHex(W,{allowUnknownOutputs:!0}),M=X.clone();for(let D=0;D<C.inputsLength;D++){let U=C.getInput(D);if(U.script&&U.script.length>0){let P=Z.decode(U.script);if(P.length>=2)M.addSignature(D,P[1],P[0])}}return M},signTransaction:async(X,j)=>{return await O(),rL({btcApp:T,chain:L,derivationPath:B,inputUtxos:j,tx:X},y)},signTransactionWithMultiplePaths:async(X,j,Z)=>{return await O(),J0({btcApp:T,chain:L,derivationPaths:Z,inputUtxos:j,tx:X},y)}}}};function U0(L,y){let _=[],R=(y.txVersion|2147483648)>>>0;_.push(R&255,R>>8&255,R>>16&255,R>>24&255);let T=y.versionGroupId;_.push(T&255,T>>8&255,T>>16&255,T>>24&255),_.push(0);let m=L.index+1;if(m<253)_.push(m);else _.push(253,m&255,m>>8&255);for(let B=0;B<L.index;B++)_.push(0,0,0,0,0,0,0,0),_.push(0);let G=L.value;_.push(Number(G&0xffn),Number(G>>8n&0xffn),Number(G>>16n&0xffn),Number(G>>24n&0xffn),Number(G>>32n&0xffn),Number(G>>40n&0xffn),Number(G>>48n&0xffn),Number(G>>56n&0xffn));let O=L.scriptPubkey;if(O.length<253)_.push(O.length);else _.push(253,O.length&255,O.length>>8&255);for(let B of O)_.push(B);return _.push(y.lockTime&255,y.lockTime>>8&255,y.lockTime>>16&255,y.lockTime>>24&255),_.push(y.expiryHeight&255,y.expiryHeight>>8&255,y.expiryHeight>>16&255,y.expiryHeight>>24&255),_.push(0,0,0,0,0,0,0,0),_.push(0),_.push(0),_.push(0),RL.hex.encode(new Uint8Array(_))}var y0=t({chain:"bitcoin"}),_0=t({chain:"litecoin"}),T0=t({additionalSignParams:{additionals:["abc"],segwit:!1,sigHashType:65},chain:"bitcoin-cash"}),w0=t({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dogecoin"}),m0=t({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dash"}),R0=t({additionalSignParams:{additionals:["zcash","sapling"],expiryHeight:(()=>{let L=Buffer.alloc(4);return L.writeUInt32LE(0),L})(),lockTime:0,segwit:!1,useTrustedInputForSegwit:!1},chain:"zcash"});var O0=Z0(require("@ledgerhq/hw-app-xrp")),p=require("@swapkit/helpers"),fL=require("ripple-binary-codec");var $0=2147483648;function C0(L){let y={};for(let _ in L)if(L[_]!==null&&L[_]!==void 0)y[_]=L[_];return y}function M0(L){return new O0.default(L)}var G0=async(L,y)=>{let _=p.derivationPathToString(L||p.NetworkDerivationPath[p.Chain.Ripple]),R=y??await q(),T=M0(R),{address:m,publicKey:G}=await T.getAddress(_);async function O(B){let{hashes:F}=await import("@swapkit/toolboxes/ripple"),j={...C0(B),Flags:B.Flags||$0,SigningPubKey:G.toUpperCase()},Z=fL.encode(j),Q=await T.signTransaction(_,Z),H=fL.encode({...j,TxnSignature:Q});return{hash:F.hashSignedTx(H),tx_blob:H}}return{getAddress:()=>m,signTransaction:O}};var K=async({chain:L,derivationPath:y,transport:_})=>{let{match:R}=await import("ts-pattern");return R(L).returnType().with(N.Chain.THORChain,()=>Promise.resolve(new HL(y,_))).with(N.Chain.Cosmos,()=>Promise.resolve(new QL(y,_))).with(N.Chain.Bitcoin,()=>Promise.resolve(y0(y,_))).with(N.Chain.BitcoinCash,()=>Promise.resolve(T0(y,_))).with(N.Chain.Dash,()=>Promise.resolve(m0(y,_))).with(N.Chain.Dogecoin,()=>Promise.resolve(w0(y,_))).with(N.Chain.Litecoin,()=>Promise.resolve(_0(y,_))).with(N.Chain.Zcash,()=>Promise.resolve(R0(y,_))).with(N.Chain.Ripple,()=>Promise.resolve(G0(y,_))).with(N.Chain.Tron,()=>Promise.resolve(sL(y,_))).with(N.Chain.Sui,()=>Promise.resolve(tL(y,_))).with(N.Chain.Near,()=>{return Promise.resolve(nL(y,_))}).with(N.Chain.Arbitrum,N.Chain.Aurora,N.Chain.Avalanche,N.Chain.Berachain,N.Chain.BinanceSmartChain,N.Chain.Ethereum,N.Chain.Gnosis,N.Chain.Monad,N.Chain.Optimism,N.Chain.Polygon,N.Chain.Base,N.Chain.XLayer,async()=>{let{getProvider:T}=await import("@swapkit/toolboxes/evm"),m={derivationPath:y,provider:await T(L),transport:_};return R(L).with(N.Chain.BinanceSmartChain,()=>hL(m)).with(N.Chain.Avalanche,()=>EL(m)).with(N.Chain.Arbitrum,()=>cL(m)).with(N.Chain.Berachain,()=>uL(m)).with(N.Chain.Optimism,()=>lL(m)).with(N.Chain.Polygon,()=>xL(m)).with(N.Chain.Base,()=>vL(m)).with(N.Chain.Aurora,()=>IL(m)).with(N.Chain.Gnosis,()=>bL(m)).with(N.Chain.Monad,()=>dL(m)).with(N.Chain.XLayer,()=>iL(m)).otherwise(()=>gL(m))}).otherwise(()=>{throw new N.SwapKitError("wallet_chain_not_supported",{chain:L,wallet:N.WalletOption.LEDGER})})};var B0=WL.createWallet({connect:({addChain:L,supportedChains:y,walletType:_})=>async function(T,m,{transport:G}={}){let[O]=w.filterSupportedChains({chains:T,supportedChains:y,walletType:_});if(!O)return!1;let B=m??w.NetworkDerivationPath[O],F=await A0({chain:O,derivationPath:B,transport:G});return L({...F,chain:O,walletType:w.WalletOption.LEDGER}),!0},directSigningSupport:{[w.Chain.Arbitrum]:!0,[w.Chain.Aurora]:!0,[w.Chain.Avalanche]:!0,[w.Chain.Base]:!0,[w.Chain.Berachain]:!0,[w.Chain.BinanceSmartChain]:!0,[w.Chain.Ethereum]:!0,[w.Chain.Gnosis]:!0,[w.Chain.Monad]:!0,[w.Chain.Bitcoin]:!0,[w.Chain.BitcoinCash]:!0,[w.Chain.Cosmos]:!0,[w.Chain.Dash]:!0,[w.Chain.Dogecoin]:!0,[w.Chain.Litecoin]:!0,[w.Chain.Near]:!0,[w.Chain.Optimism]:!0,[w.Chain.Polygon]:!0,[w.Chain.Ripple]:!0,[w.Chain.Sui]:!0,[w.Chain.Tron]:!0,[w.Chain.XLayer]:!0},name:"connectLedger",supportedChains:[w.Chain.Arbitrum,w.Chain.Aurora,w.Chain.Avalanche,w.Chain.Base,w.Chain.Berachain,w.Chain.BinanceSmartChain,w.Chain.Bitcoin,w.Chain.BitcoinCash,w.Chain.Cosmos,w.Chain.Dash,w.Chain.Dogecoin,w.Chain.Ethereum,w.Chain.Gnosis,w.Chain.Litecoin,w.Chain.Monad,w.Chain.Near,w.Chain.Optimism,w.Chain.Polygon,w.Chain.Ripple,w.Chain.Sui,w.Chain.THORChain,w.Chain.XLayer,w.Chain.Tron,w.Chain.Zcash],walletType:w.WalletOption.LEDGER}),H0=WL.getWalletSupportedChains(B0);function f0(L,y="t"){if(!L?.includes("=:"))return L;let _=L.includes(`:${y}:`)?L.split(`:${y}:`)[0]:L;return _?.substring(0,_.lastIndexOf(":"))}function FL(L){if(Array.isArray(L))return L.forEach((R,T)=>{L[T]=FL(R)}),L;if(typeof L!=="object")return L;let y={},_=Object.keys(L).sort();for(let R of _)y[R]=FL(L[R]);return y}function q0(L){return JSON.stringify(FL(L))}async function A0({chain:L,derivationPath:y,transport:_}){switch(L){case w.Chain.BitcoinCash:case w.Chain.Bitcoin:case w.Chain.Dash:case w.Chain.Dogecoin:case w.Chain.Litecoin:case w.Chain.Zcash:{let j=function(){return X()},{getUtxoToolbox:R}=await import("@swapkit/toolboxes/utxo"),T=L,m=await K({chain:L,derivationPath:y,transport:_}),G=await v({chain:L,ledgerClient:m}),O;if(L===w.Chain.Bitcoin||L===w.Chain.Litecoin){let{BitcoinPsbtLedger:W,LitecoinPsbtLedger:C}=await import("../chunk-m08x6an5.js"),M=L===w.Chain.Bitcoin?W(y,_):C(y,_);O={getAddress:M.getAddress,signTransaction:M.signTransaction}}else if(L===w.Chain.BitcoinCash||L===w.Chain.Dogecoin||L===w.Chain.Dash){let{createLegacyPsbtSigner:W}=await import("../chunk-mrsfcest.js");O=W({address:G,chain:T,legacyClient:m})}let B=O?await R(T,{signer:O}):R(T),F=async(W)=>{let C=W.feeRate||(await B.getFeeRates())[w.FeeOption.Average],M=[w.Chain.Bitcoin].includes(L)?W.memo:f0(W.memo),{tx:D,inputs:U}=await B.createTransaction({...W,feeRate:C,fetchTxHex:!0,memo:M,sender:G}),P=await m.signTransaction(D,U);return await B.broadcastTx(P)};async function X({accountIndex:W}={}){if(!m.getExtendedPublicKey)return;let C=Y.getUTXOAccountPath({accountIndex:W,chain:T,derivationPath:y}),M=w.derivationPathToString(C),D=L===w.Chain.Bitcoin||L===w.Chain.Litecoin?M:M.replace(/^m\//,""),U=await m.getExtendedPublicKey(D);return{accountIndex:Y.getUTXOAccountIndexFromPath(C),path:M,xpub:U}}async function Z({accountIndex:W,index:C,change:M=!1}){try{let D=Y.getUTXOAddressPath({accountIndex:W,chain:T,change:M,derivationPath:y,index:C}),U=await K({chain:T,derivationPath:D,transport:_}),P=await v({chain:T,ledgerClient:U});return{accountIndex:Y.getUTXOAccountIndexFromPath(D),address:P,change:M,index:C,path:w.derivationPathToString(D),pubkey:""}}catch{return}}async function Q({accountIndex:W,count:C,startIndex:M=0,change:D=!1}){return Y.assertDerivationIndex("count",C),Y.assertDerivationIndex("startIndex",M),(await Promise.all(Array.from({length:C},(P,l)=>Z({accountIndex:W,change:D,index:M+l})))).filter((P)=>!!P)}let H=Y.createHDWalletHelpers({chain:T,deriveAddress:Z,getBalance:B.getBalance,getUtxos:(W)=>Y.getUtxoApi(T).getUtxos({address:W,fetchTxHex:!0})});async function f({utxos:W,recipient:C,assetValue:M,memo:D,feeRate:U,feeOptionKey:P,changeAddress:l}){if(!W.length)throw new w.SwapKitError("wallet_ledger_invalid_params",{message:"No UTXOs provided for multi-address transfer"});let qL=U||(await B.getFeeRates())[P||w.FeeOption.Fast],OL=D?Y.compileMemo(D):null,V=[{address:C,value:M.getBaseValue("number")}];if(OL)V.push({script:OL,value:0});let GL=W.map(({hash:i,index:u,value:r,txHex:LL,witnessUtxo:yL})=>({hash:i,index:u,txHex:LL,value:r,witnessUtxo:yL})),{inputs:d,outputs:a}=B.accumulative({chain:T,feeRate:qL,inputs:GL,outputs:V});if(!(d&&a))throw new w.SwapKitError("wallet_ledger_connection_error",{message:"Insufficient balance for multi-address transfer"});let{Transaction:DL}=await import("@swapkit/utxo-signer"),BL=new DL({allowLegacyWitnessUtxo:!0,version:1}),e=l||W[0]?.address||C;Y.addInputsAndOutputs({chain:T,compiledMemo:OL,inputs:d,outputs:a,sender:e,tx:BL});let XL=Y.getUTXOAccountPath({chain:T,derivationPath:y}),JL=d.map((i)=>{let u=W.find((NL)=>NL.hash===i.hash&&NL.index===i.index),r=u?.derivationIndex??0,LL=u?.isChange??!1,yL=[...XL,Number(LL),r];return w.derivationPathToString(yL)});if(!m.signTransactionWithMultiplePaths)throw new w.SwapKitError("wallet_ledger_method_not_supported",{method:"signTransactionWithMultiplePaths"});let s=await m.signTransactionWithMultiplePaths(BL,d,JL);return B.broadcastTx(s)}return{...B,...H,address:G,deriveAddressAtIndex:Z,deriveAddresses:Q,getExtendedPublicKey:j,getExtendedPublicKeyInfo:X,transfer:F,transferFromMultipleAddresses:f}}case w.Chain.Ethereum:case w.Chain.Avalanche:case w.Chain.Arbitrum:case w.Chain.Berachain:case w.Chain.Optimism:case w.Chain.Polygon:case w.Chain.BinanceSmartChain:case w.Chain.Base:case w.Chain.Aurora:case w.Chain.Gnosis:case w.Chain.Monad:case w.Chain.XLayer:{let{getEvmToolboxAsync:R}=await import("@swapkit/toolboxes/evm"),T=await K({chain:L,derivationPath:y,transport:_}),m=await v({chain:L,ledgerClient:T});return{...await R(L,{signer:T}),address:m}}case w.Chain.Cosmos:{let{createSigningStargateClient:R,getMsgSendDenom:T,getCosmosToolbox:m}=await import("@swapkit/toolboxes/cosmos"),G=await K({chain:L,derivationPath:y,transport:_}),O=await v({chain:L,ledgerClient:G});return{...await m(w.Chain.Cosmos,{signer:G}),address:O,transfer:async({assetValue:X,recipient:j,memo:Z})=>{if(!X)throw new w.SwapKitError("wallet_ledger_invalid_asset");let Q={amount:[{amount:X.getBaseValue("string"),denom:T(`u${X.symbol}`).toLowerCase()}],fromAddress:O,toAddress:j},H=await w.getRPCUrl(L),f=await R(H,G,"0.007uatom"),{transactionHash:W}=await f.signAndBroadcast(O,[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:Q}],2,Z);return W}}}case w.Chain.THORChain:{let{SignMode:R}=await import("cosmjs-types/cosmos/tx/signing/v1beta1/signing.js"),{TxRaw:T}=await import("cosmjs-types/cosmos/tx/v1beta1/tx.js"),m=await import("@cosmjs/proto-signing"),G=m.encodePubkey??m.default?.encodePubkey,O=m.makeAuthInfoBytes??m.default?.makeAuthInfoBytes,{createStargateClient:B,buildEncodedTxBody:F,getCosmosToolbox:X,buildAminoMsg:j,getDefaultChainFee:Z,fromBase64:Q,parseAminoMessageForDirectSigning:H}=await import("@swapkit/toolboxes/cosmos"),f=X(L),W=await K({chain:L,derivationPath:y,transport:_}),C=await v({chain:L,ledgerClient:W}),M=Z(L),{pubkey:D,signTransaction:U,sign:P}=W,l=async({memo:V="",assetValue:GL,...d})=>{let a=await f.getAccount(C);if(!a)throw new w.SwapKitError("wallet_ledger_invalid_account");if(!GL)throw new w.SwapKitError("wallet_ledger_invalid_asset");if(!D)throw new w.SwapKitError("wallet_ledger_pubkey_not_found");let{accountNumber:DL,sequence:BL}=a,e=(BL||0).toString(),XL=FL([j({assetValue:GL,memo:V,sender:C,...d})]),JL=q0({account_number:DL?.toString(),chain_id:w.THORConfig.chainId,fee:M,memo:V,msgs:XL,sequence:e}),s=await U(JL,e);if(!s)throw new w.SwapKitError("wallet_ledger_signing_error");let i=G({type:"tendermint/PubKeySecp256k1",value:D}),u=XL.map(H),r=await F({chain:L,memo:V,msgs:u}),LL=O([{pubkey:i,sequence:Number(e)}],M.amount,Number.parseInt(M.gas,10),void 0,void 0,R.SIGN_MODE_LEGACY_AMINO_JSON),yL=s?.[0]?.signature?Q(s[0].signature):Uint8Array.from([]),NL=T.fromPartial({authInfoBytes:LL,bodyBytes:r,signatures:[yL]}),X0=T.encode(NL).finish(),N0=await w.getRPCUrl(w.Chain.THORChain),j0=await B(N0),{transactionHash:F0}=await j0.broadcastTx(X0);return F0};return{...f,address:C,deposit:(V)=>l(V),signMessage:P,transfer:(V)=>l(V)}}case w.Chain.Near:{let{getNearToolbox:R}=await import("@swapkit/toolboxes/near"),T=await K({chain:L,derivationPath:y,transport:_}),m=await T.getAddress();return{...R({signer:T}),address:m}}case w.Chain.Ripple:{let{getRippleToolbox:R}=await import("@swapkit/toolboxes/ripple"),T=await K({chain:L,derivationPath:y,transport:_}),m=T.getAddress();return{...R({signer:T}),address:m}}case w.Chain.Tron:{let{getTronToolbox:R}=await import("@swapkit/toolboxes/tron"),T=await K({chain:L,derivationPath:y,transport:_}),m=await v({chain:L,ledgerClient:T});return{...R({signer:T}),address:m}}case w.Chain.Sui:{let{getSuiToolbox:R}=await import("@swapkit/toolboxes/sui"),T=await K({chain:L,derivationPath:y,transport:_}),m=await v({chain:L,ledgerClient:T});return{...R({signer:T}),address:m}}default:throw new w.SwapKitError("wallet_ledger_chain_not_supported",{chain:L})}}
2
+ ${JSON.stringify({btcApp:T,checkBtcApp:X})}`});m||=R??await q()}async function O(){m=R??await q(),T=new(await import("@ledgerhq/hw-app-btc")).default({currency:L,transport:m})}let B=typeof _==="string"?_:b.derivationPathToString(_),F=b.getWalletFormatFor(B);return{connect:async()=>{await G(!1),T=new(await import("@ledgerhq/hw-app-btc")).default({currency:L,transport:m})},getAddress:async()=>{let{toCashAddress:X}=await import("@swapkit/toolboxes/utxo");await G(!1);let{bitcoinAddress:j}=await T.getWalletPublicKey(B,{format:F});if(!j)throw new b.SwapKitError("wallet_ledger_get_address_error",{message:`Cannot get ${L} address from ledger derivation path: ${B}`});return L==="bitcoin-cash"&&F==="legacy"?X(j).replace(/(bchtest:|bitcoincash:)/,""):j},getExtendedPublicKey:async(X="84'/0'/0'",j=76067358)=>{return await G(!1),T.getWalletXpub({path:X,xpubVersion:j})},signPCZT:async(X)=>{if(L!=="zcash")throw new b.SwapKitError("wallet_ledger_chain_not_supported",{message:"PCZT signing is only supported for Zcash"});await O();let{ZcashTransaction:j,Script:Z}=await import("@swapkit/utxo-signer"),Q=X.getGlobal(),H=new j({consensusBranchId:Q.consensusBranchId,expiryHeight:Q.expiryHeight,lockTime:Q.lockTime,version:Q.txVersion,versionGroupId:Q.versionGroupId}),f=[];for(let D=0;D<X.inputsLength;D++){let U=X.getInput(D);H.addInput({index:U.index,script:new Uint8Array,sequence:U.sequence??4294967295,txid:U.txid,value:U.value}),f.push({hash:RL.hex.encode(new Uint8Array([...U.txid].reverse())),index:U.index,txHex:U0(U,Q),value:Number(U.value),witnessUtxo:{script:U.scriptPubkey,value:Number(U.value)}})}for(let D=0;D<X.outputsLength;D++){let U=X.getOutput(D);H.addOutput({amount:U.value,script:U.scriptPubkey})}let W=await rL({btcApp:T,chain:L,derivationPath:B,inputUtxos:f,tx:H},{...y,expiryHeight:(()=>{let D=Buffer.alloc(4);return D.writeUInt32LE(Q.expiryHeight),D})(),lockTime:Q.lockTime}),C=j.fromHex(W,{allowUnknownOutputs:!0}),M=X.clone();for(let D=0;D<C.inputsLength;D++){let U=C.getInput(D);if(U.script&&U.script.length>0){let P=Z.decode(U.script);if(P.length>=2)M.addSignature(D,P[1],P[0])}}return M},signTransaction:async(X,j)=>{return await O(),rL({btcApp:T,chain:L,derivationPath:B,inputUtxos:j,tx:X},y)},signTransactionWithMultiplePaths:async(X,j,Z)=>{return await O(),J0({btcApp:T,chain:L,derivationPaths:Z,inputUtxos:j,tx:X},y)}}}};function U0(L,y){let _=[],R=(y.txVersion|2147483648)>>>0;_.push(R&255,R>>8&255,R>>16&255,R>>24&255);let T=y.versionGroupId;_.push(T&255,T>>8&255,T>>16&255,T>>24&255),_.push(0);let m=L.index+1;if(m<253)_.push(m);else _.push(253,m&255,m>>8&255);for(let B=0;B<L.index;B++)_.push(0,0,0,0,0,0,0,0),_.push(0);let G=L.value;_.push(Number(G&0xffn),Number(G>>8n&0xffn),Number(G>>16n&0xffn),Number(G>>24n&0xffn),Number(G>>32n&0xffn),Number(G>>40n&0xffn),Number(G>>48n&0xffn),Number(G>>56n&0xffn));let O=L.scriptPubkey;if(O.length<253)_.push(O.length);else _.push(253,O.length&255,O.length>>8&255);for(let B of O)_.push(B);return _.push(y.lockTime&255,y.lockTime>>8&255,y.lockTime>>16&255,y.lockTime>>24&255),_.push(y.expiryHeight&255,y.expiryHeight>>8&255,y.expiryHeight>>16&255,y.expiryHeight>>24&255),_.push(0,0,0,0,0,0,0,0),_.push(0),_.push(0),_.push(0),RL.hex.encode(new Uint8Array(_))}var y0=t({chain:"bitcoin"}),_0=t({chain:"litecoin"}),T0=t({additionalSignParams:{additionals:["abc"],segwit:!1,sigHashType:65},chain:"bitcoin-cash"}),w0=t({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dogecoin"}),m0=t({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dash"}),R0=t({additionalSignParams:{additionals:["zcash","sapling"],expiryHeight:(()=>{let L=Buffer.alloc(4);return L.writeUInt32LE(0),L})(),lockTime:0,segwit:!1,useTrustedInputForSegwit:!1},chain:"zcash"});var O0=Z0(require("@ledgerhq/hw-app-xrp")),p=require("@swapkit/helpers"),fL=require("ripple-binary-codec");var $0=2147483648;function C0(L){let y={};for(let _ in L)if(L[_]!==null&&L[_]!==void 0)y[_]=L[_];return y}function M0(L){return new O0.default(L)}var G0=async(L,y)=>{let _=p.derivationPathToString(L||p.NetworkDerivationPath[p.Chain.Ripple]),R=y??await q(),T=M0(R),{address:m,publicKey:G}=await T.getAddress(_);async function O(B){let{hashes:F}=await import("@swapkit/toolboxes/ripple"),j={...C0(B),Flags:B.Flags||$0,SigningPubKey:G.toUpperCase()},Z=fL.encode(j),Q=await T.signTransaction(_,Z),H=fL.encode({...j,TxnSignature:Q});return{hash:F.hashSignedTx(H),tx_blob:H}}return{getAddress:()=>m,signTransaction:O}};var K=async({chain:L,derivationPath:y,transport:_})=>{let{match:R}=await import("ts-pattern");return R(L).returnType().with(N.Chain.THORChain,()=>Promise.resolve(new HL(y,_))).with(N.Chain.Cosmos,()=>Promise.resolve(new QL(y,_))).with(N.Chain.Bitcoin,()=>Promise.resolve(y0(y,_))).with(N.Chain.BitcoinCash,()=>Promise.resolve(T0(y,_))).with(N.Chain.Dash,()=>Promise.resolve(m0(y,_))).with(N.Chain.Dogecoin,()=>Promise.resolve(w0(y,_))).with(N.Chain.Litecoin,()=>Promise.resolve(_0(y,_))).with(N.Chain.Zcash,()=>Promise.resolve(R0(y,_))).with(N.Chain.Ripple,()=>Promise.resolve(G0(y,_))).with(N.Chain.Tron,()=>Promise.resolve(sL(y,_))).with(N.Chain.Sui,()=>Promise.resolve(tL(y,_))).with(N.Chain.Near,()=>{return Promise.resolve(nL(y,_))}).with(N.Chain.Arbitrum,N.Chain.Aurora,N.Chain.Avalanche,N.Chain.Berachain,N.Chain.BinanceSmartChain,N.Chain.Ethereum,N.Chain.Gnosis,N.Chain.Monad,N.Chain.Optimism,N.Chain.Polygon,N.Chain.Base,N.Chain.XLayer,async()=>{let{getProvider:T}=await import("@swapkit/toolboxes/evm"),m={derivationPath:y,provider:await T(L),transport:_};return R(L).with(N.Chain.BinanceSmartChain,()=>hL(m)).with(N.Chain.Avalanche,()=>EL(m)).with(N.Chain.Arbitrum,()=>cL(m)).with(N.Chain.Berachain,()=>uL(m)).with(N.Chain.Optimism,()=>lL(m)).with(N.Chain.Polygon,()=>xL(m)).with(N.Chain.Base,()=>vL(m)).with(N.Chain.Aurora,()=>IL(m)).with(N.Chain.Gnosis,()=>bL(m)).with(N.Chain.Monad,()=>dL(m)).with(N.Chain.XLayer,()=>iL(m)).otherwise(()=>gL(m))}).otherwise(()=>{throw new N.SwapKitError("wallet_chain_not_supported",{chain:L,wallet:N.WalletOption.LEDGER})})};var B0=WL.createWallet({connect:({addChain:L,supportedChains:y,walletType:_})=>async function(T,m,{transport:G}={}){let[O]=w.filterSupportedChains({chains:T,supportedChains:y,walletType:_});if(!O)return!1;let B=m??w.NetworkDerivationPath[O],F=await A0({chain:O,derivationPath:B,transport:G});return L({...F,chain:O,walletType:w.WalletOption.LEDGER}),!0},directSigningSupport:{[w.Chain.Arbitrum]:!0,[w.Chain.Aurora]:!0,[w.Chain.Avalanche]:!0,[w.Chain.Base]:!0,[w.Chain.Berachain]:!0,[w.Chain.BinanceSmartChain]:!0,[w.Chain.Ethereum]:!0,[w.Chain.Gnosis]:!0,[w.Chain.Monad]:!0,[w.Chain.Bitcoin]:!0,[w.Chain.BitcoinCash]:!0,[w.Chain.Cosmos]:!0,[w.Chain.Dash]:!0,[w.Chain.Dogecoin]:!0,[w.Chain.Litecoin]:!0,[w.Chain.Near]:!0,[w.Chain.Optimism]:!0,[w.Chain.Polygon]:!0,[w.Chain.Ripple]:!0,[w.Chain.Sui]:!0,[w.Chain.Tron]:!0,[w.Chain.XLayer]:!0},name:"connectLedger",supportedChains:[w.Chain.Arbitrum,w.Chain.Aurora,w.Chain.Avalanche,w.Chain.Base,w.Chain.Berachain,w.Chain.BinanceSmartChain,w.Chain.Bitcoin,w.Chain.BitcoinCash,w.Chain.Cosmos,w.Chain.Dash,w.Chain.Dogecoin,w.Chain.Ethereum,w.Chain.Gnosis,w.Chain.Litecoin,w.Chain.Monad,w.Chain.Near,w.Chain.Optimism,w.Chain.Polygon,w.Chain.Ripple,w.Chain.Sui,w.Chain.THORChain,w.Chain.XLayer,w.Chain.Tron,w.Chain.Zcash],walletType:w.WalletOption.LEDGER}),H0=WL.getWalletSupportedChains(B0);function f0(L,y="t"){if(!L?.includes("=:"))return L;let _=L.includes(`:${y}:`)?L.split(`:${y}:`)[0]:L;return _?.substring(0,_.lastIndexOf(":"))}function FL(L){if(Array.isArray(L))return L.forEach((R,T)=>{L[T]=FL(R)}),L;if(typeof L!=="object")return L;let y={},_=Object.keys(L).sort();for(let R of _)y[R]=FL(L[R]);return y}function q0(L){return JSON.stringify(FL(L))}async function A0({chain:L,derivationPath:y,transport:_}){switch(L){case w.Chain.BitcoinCash:case w.Chain.Bitcoin:case w.Chain.Dash:case w.Chain.Dogecoin:case w.Chain.Litecoin:case w.Chain.Zcash:{let j=function(){return X()},{getUtxoToolbox:R}=await import("@swapkit/toolboxes/utxo"),T=L,m=await K({chain:L,derivationPath:y,transport:_}),G=await v({chain:L,ledgerClient:m}),O;if(L===w.Chain.Bitcoin||L===w.Chain.Litecoin){let{BitcoinPsbtLedger:W,LitecoinPsbtLedger:C}=await import("../chunk-3gajmdgz.js"),M=L===w.Chain.Bitcoin?W(y,_):C(y,_);O={getAddress:M.getAddress,signTransaction:M.signTransaction}}else if(L===w.Chain.BitcoinCash||L===w.Chain.Dogecoin||L===w.Chain.Dash){let{createLegacyPsbtSigner:W}=await import("../chunk-mrsfcest.js");O=W({address:G,chain:T,legacyClient:m})}let B=O?await R(T,{signer:O}):R(T),F=async(W)=>{let C=W.feeRate||(await B.getFeeRates())[w.FeeOption.Average],M=[w.Chain.Bitcoin].includes(L)?W.memo:f0(W.memo),{tx:D,inputs:U}=await B.createTransaction({...W,feeRate:C,fetchTxHex:!0,memo:M,sender:G}),P=await m.signTransaction(D,U);return await B.broadcastTx(P)};async function X({accountIndex:W}={}){if(!m.getExtendedPublicKey)return;let C=Y.getUTXOAccountPath({accountIndex:W,chain:T,derivationPath:y}),M=w.derivationPathToString(C),D=L===w.Chain.Bitcoin||L===w.Chain.Litecoin?M:M.replace(/^m\//,""),U=await m.getExtendedPublicKey(D);return{accountIndex:Y.getUTXOAccountIndexFromPath(C),path:M,xpub:U}}async function Z({accountIndex:W,index:C,change:M=!1}){try{let D=Y.getUTXOAddressPath({accountIndex:W,chain:T,change:M,derivationPath:y,index:C}),U=await K({chain:T,derivationPath:D,transport:_}),P=await v({chain:T,ledgerClient:U});return{accountIndex:Y.getUTXOAccountIndexFromPath(D),address:P,change:M,index:C,path:w.derivationPathToString(D),pubkey:""}}catch{return}}async function Q({accountIndex:W,count:C,startIndex:M=0,change:D=!1}){return Y.assertDerivationIndex("count",C),Y.assertDerivationIndex("startIndex",M),(await Promise.all(Array.from({length:C},(P,l)=>Z({accountIndex:W,change:D,index:M+l})))).filter((P)=>!!P)}let H=Y.createHDWalletHelpers({chain:T,deriveAddress:Z,getBalance:B.getBalance,getUtxos:(W)=>Y.getUtxoApi(T).getUtxos({address:W,fetchTxHex:!0})});async function f({utxos:W,recipient:C,assetValue:M,memo:D,feeRate:U,feeOptionKey:P,changeAddress:l}){if(!W.length)throw new w.SwapKitError("wallet_ledger_invalid_params",{message:"No UTXOs provided for multi-address transfer"});let qL=U||(await B.getFeeRates())[P||w.FeeOption.Fast],OL=D?Y.compileMemo(D):null,V=[{address:C,value:M.getBaseValue("number")}];if(OL)V.push({script:OL,value:0});let GL=W.map(({hash:i,index:u,value:r,txHex:LL,witnessUtxo:yL})=>({hash:i,index:u,txHex:LL,value:r,witnessUtxo:yL})),{inputs:d,outputs:a}=B.accumulative({chain:T,feeRate:qL,inputs:GL,outputs:V});if(!(d&&a))throw new w.SwapKitError("wallet_ledger_connection_error",{message:"Insufficient balance for multi-address transfer"});let{Transaction:DL}=await import("@swapkit/utxo-signer"),BL=new DL({allowLegacyWitnessUtxo:!0,version:1}),e=l||W[0]?.address||C;Y.addInputsAndOutputs({chain:T,compiledMemo:OL,inputs:d,outputs:a,sender:e,tx:BL});let XL=Y.getUTXOAccountPath({chain:T,derivationPath:y}),JL=d.map((i)=>{let u=W.find((NL)=>NL.hash===i.hash&&NL.index===i.index),r=u?.derivationIndex??0,LL=u?.isChange??!1,yL=[...XL,Number(LL),r];return w.derivationPathToString(yL)});if(!m.signTransactionWithMultiplePaths)throw new w.SwapKitError("wallet_ledger_method_not_supported",{method:"signTransactionWithMultiplePaths"});let s=await m.signTransactionWithMultiplePaths(BL,d,JL);return B.broadcastTx(s)}return{...B,...H,address:G,deriveAddressAtIndex:Z,deriveAddresses:Q,getExtendedPublicKey:j,getExtendedPublicKeyInfo:X,transfer:F,transferFromMultipleAddresses:f}}case w.Chain.Ethereum:case w.Chain.Avalanche:case w.Chain.Arbitrum:case w.Chain.Berachain:case w.Chain.Optimism:case w.Chain.Polygon:case w.Chain.BinanceSmartChain:case w.Chain.Base:case w.Chain.Aurora:case w.Chain.Gnosis:case w.Chain.Monad:case w.Chain.XLayer:{let{getEvmToolboxAsync:R}=await import("@swapkit/toolboxes/evm"),T=await K({chain:L,derivationPath:y,transport:_}),m=await v({chain:L,ledgerClient:T});return{...await R(L,{signer:T}),address:m}}case w.Chain.Cosmos:{let{createSigningStargateClient:R,getMsgSendDenom:T,getCosmosToolbox:m}=await import("@swapkit/toolboxes/cosmos"),G=await K({chain:L,derivationPath:y,transport:_}),O=await v({chain:L,ledgerClient:G});return{...await m(w.Chain.Cosmos,{signer:G}),address:O,transfer:async({assetValue:X,recipient:j,memo:Z})=>{if(!X)throw new w.SwapKitError("wallet_ledger_invalid_asset");let Q={amount:[{amount:X.getBaseValue("string"),denom:T(`u${X.symbol}`).toLowerCase()}],fromAddress:O,toAddress:j},H=await w.getRPCUrl(L),f=await R(H,G,"0.007uatom"),{transactionHash:W}=await f.signAndBroadcast(O,[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:Q}],2,Z);return W}}}case w.Chain.THORChain:{let{SignMode:R}=await import("cosmjs-types/cosmos/tx/signing/v1beta1/signing.js"),{TxRaw:T}=await import("cosmjs-types/cosmos/tx/v1beta1/tx.js"),m=await import("@cosmjs/proto-signing"),G=m.encodePubkey??m.default?.encodePubkey,O=m.makeAuthInfoBytes??m.default?.makeAuthInfoBytes,{createStargateClient:B,buildEncodedTxBody:F,getCosmosToolbox:X,buildAminoMsg:j,getDefaultChainFee:Z,fromBase64:Q,parseAminoMessageForDirectSigning:H}=await import("@swapkit/toolboxes/cosmos"),f=X(L),W=await K({chain:L,derivationPath:y,transport:_}),C=await v({chain:L,ledgerClient:W}),M=Z(L),{pubkey:D,signTransaction:U,sign:P}=W,l=async({memo:V="",assetValue:GL,...d})=>{let a=await f.getAccount(C);if(!a)throw new w.SwapKitError("wallet_ledger_invalid_account");if(!GL)throw new w.SwapKitError("wallet_ledger_invalid_asset");if(!D)throw new w.SwapKitError("wallet_ledger_pubkey_not_found");let{accountNumber:DL,sequence:BL}=a,e=(BL||0).toString(),XL=FL([j({assetValue:GL,memo:V,sender:C,...d})]),JL=q0({account_number:DL?.toString(),chain_id:w.THORConfig.chainId,fee:M,memo:V,msgs:XL,sequence:e}),s=await U(JL,e);if(!s)throw new w.SwapKitError("wallet_ledger_signing_error");let i=G({type:"tendermint/PubKeySecp256k1",value:D}),u=XL.map(H),r=await F({chain:L,memo:V,msgs:u}),LL=O([{pubkey:i,sequence:Number(e)}],M.amount,Number.parseInt(M.gas,10),void 0,void 0,R.SIGN_MODE_LEGACY_AMINO_JSON),yL=s?.[0]?.signature?Q(s[0].signature):Uint8Array.from([]),NL=T.fromPartial({authInfoBytes:LL,bodyBytes:r,signatures:[yL]}),X0=T.encode(NL).finish(),N0=await w.getRPCUrl(w.Chain.THORChain),j0=await B(N0),{transactionHash:F0}=await j0.broadcastTx(X0);return F0};return{...f,address:C,deposit:(V)=>l(V),signMessage:P,transfer:(V)=>l(V)}}case w.Chain.Near:{let{getNearToolbox:R}=await import("@swapkit/toolboxes/near"),T=await K({chain:L,derivationPath:y,transport:_}),m=await T.getAddress();return{...R({signer:T}),address:m}}case w.Chain.Ripple:{let{getRippleToolbox:R}=await import("@swapkit/toolboxes/ripple"),T=await K({chain:L,derivationPath:y,transport:_}),m=T.getAddress();return{...R({signer:T}),address:m}}case w.Chain.Tron:{let{getTronToolbox:R}=await import("@swapkit/toolboxes/tron"),T=await K({chain:L,derivationPath:y,transport:_}),m=await v({chain:L,ledgerClient:T});return{...R({signer:T}),address:m}}case w.Chain.Sui:{let{getSuiToolbox:R}=await import("@swapkit/toolboxes/sui"),T=await K({chain:L,derivationPath:y,transport:_}),m=await v({chain:L,ledgerClient:T});return{...R({signer:T}),address:m}}default:throw new w.SwapKitError("wallet_ledger_chain_not_supported",{chain:L})}}
3
3
 
4
4
  //# debugId=A1939314CC5EB6BD64756E2164756E21
5
5
  //# sourceMappingURL=index.cjs.map
@@ -1,5 +1,5 @@
1
1
  import{c as f}from"../chunk-3yr76n9s.js";import{d as N}from"../chunk-n05bv2n5.js";import{Chain as R,derivationPathToString as YL,FeeOption as O0,filterSupportedChains as t0,getRPCUrl as G0,NetworkDerivationPath as p0,SwapKitError as E,THORConfig as a0,WalletOption as B0}from"@swapkit/helpers";import{addInputsAndOutputs as e0,assertDerivationIndex as X0,compileMemo as s0,createHDWalletHelpers as r0,getUTXOAccountIndexFromPath as N0,getUTXOAccountPath as j0,getUTXOAddressPath as Ly,getUtxoApi as yy}from"@swapkit/toolboxes/utxo";import{createWallet as _y,getWalletSupportedChains as Ty}from"@swapkit/wallet-core";import{Chain as $,SwapKitError as U0,WalletOption as Z0}from"@swapkit/helpers";var k=async({chain:L,ledgerClient:y})=>{if(!y)return"";switch(L){case $.Cosmos:case $.THORChain:return y.connect();case $.Ethereum:case $.BinanceSmartChain:case $.Avalanche:case $.Polygon:case $.Arbitrum:case $.Berachain:case $.Optimism:case $.Base:case $.Aurora:case $.Gnosis:case $.Monad:case $.XLayer:return y.getAddress();case $.Bitcoin:case $.BitcoinCash:case $.Dash:case $.Dogecoin:case $.Litecoin:case $.Zcash:{let _=y;await _.connect();let m=await _.getAddress();return L===$.BitcoinCash?m.replace("bitcoincash:",""):m}case $.Near:return await y.getAddress();case $.Ripple:return y.getAddress();case $.Tron:return y.getAddress();case $.Sui:return y.connect();default:throw new U0("wallet_chain_not_supported",{chain:L,wallet:Z0.LEDGER})}};import{Chain as F,SwapKitError as n0,WalletOption as o0}from"@swapkit/helpers";import{derivationPathToString as Q0,NetworkDerivationPath as Y0,SwapKitError as VL}from"@swapkit/helpers";import{LedgerErrorCode as ZL,NetworkDerivationPath as M0,SwapKitError as $L}from"@swapkit/helpers";import{SwapKitError as KL}from"@swapkit/helpers";var d=85,WL=250;var b={GET_ADDR_SECP256K1:4,GET_VERSION:0,INS_PUBLIC_KEY_SECP256K1:1,SIGN_SECP256K1:2},OL={ADD:1,INIT:0,LAST:2},DL={ONLY_RETRIEVE:0,SHOW_ADDRESS_IN_DEVICE:1},i={JSON:0},c={NoError:36864},fL={1:"U2F: Unknown",2:"U2F: Bad request",3:"U2F: Configuration unsupported",4:"U2F: Device Ineligible",5:"U2F: Timeout",14:"Timeout",25600:"Execution Error",26368:"Wrong Length",26626:"Error deriving keys",27010:"Empty Buffer",27011:"Output buffer too small",27012:"Data is invalid",27013:"Conditions not satisfied",27014:"Transaction rejected",27264:"Bad key handle",27392:"Invalid P1/P2",27904:"Instruction not supported",28160:"App does not seem to be open",28416:"Unknown error",28417:"Sign/verify error",36864:"No errors",36865:"Device is busy"};function V(L){if(L in fL)return fL[L];return`Unknown Status Code: ${L}`}function $0(L){return typeof L==="object"&&L!==null&&!Array.isArray(L)&&!(L instanceof Date)}function S(L){if(L){if($0(L)){if(Object.hasOwn(L,"statusCode"))return{error_message:V(L.statusCode),return_code:L.statusCode};if(Object.hasOwn(L,"return_code")&&Object.hasOwn(L,"error_message"))return L}return{error_message:L.toString(),return_code:65535}}return{error_message:L.toString(),return_code:65535}}function JL(L){return L.send(85,b.GET_VERSION,0,0).then((y)=>{let _=y.slice(-2),m=_[0]*256+_[1],T=0;if(y.length>=9)T=(y[5]<<24)+(y[6]<<16)+(y[7]<<8)+(y[8]<<0);return{device_locked:y[4]===1,error_message:V(m),major:y[1],minor:y[2],patch:y[3],return_code:m,target_id:T.toString(16),test_mode:y[0]!==0}},S)}import{SwapKitError as GL}from"@swapkit/helpers";function qL(L){if(L==null||L.length<3)throw new GL("wallet_ledger_invalid_params",{reason:"Path too short"});if(L.length>10)throw new GL("wallet_ledger_invalid_params",{reason:"Path too long"});let y=Buffer.alloc(1+4*L.length);y.writeUInt8(L.length,0);for(let _=0;_<L.length;_+=1){let m=L[_]||0;if(_<3)m|=2147483648;y.writeInt32LE(m,1+_*4)}return y}function UL(L,y,_,m,T=i.JSON){return L.transport.send(d,b.SIGN_SECP256K1,y,T,m,[c.NoError,27012,27264]).then((w)=>{let G=w.slice(-2),O=G[0]*256+G[1],B=V(O);if(O===27264||O===27012)B=`${B} : ${w.slice(0,w.length-2).toString("ascii")}`;let W=null;if(w.length>2)W=w.slice(0,w.length-2);return{error_message:B,return_code:O,signature:W}},S)}function C0(L){if(L.length!==65)throw new GL("wallet_ledger_invalid_params",{reason:"decompressed public key length should be 65 bytes"});let y=L.slice(33,65),_=Buffer.from([2+(y[y.length-1]&1)]);return Buffer.concat([_,L.slice(1,33)])}function AL(L,y){return L.transport.send(d,b.INS_PUBLIC_KEY_SECP256K1,0,0,y,[c.NoError]).then((_)=>{let m=_.slice(-2),T=m[0]*256+m[1],w=Buffer.from(_.slice(0,65));return{compressed_pk:C0(w),error_message:V(T),pk:w,return_code:T}},S)}function PL(L){if(!L||L.length!==5)throw new GL("wallet_ledger_invalid_params",{reason:"Path must be exactly 5 elements"});let y=Buffer.alloc(20);return y.writeUInt32LE(2147483648+L[0],0),y.writeUInt32LE(2147483648+L[1],4),y.writeUInt32LE(2147483648+L[2],8),y.writeUInt32LE(L[3],12),y.writeUInt32LE(L[4],16),y}function SL(L,y,_,m,T=i.JSON){let w=OL.ADD;if(y===1)w=OL.INIT;if(y===_)w=OL.LAST;return UL(L,w,0,m,T)}function zL(L,y){return L.transport.send(d,b.GET_ADDR_SECP256K1,0,0,y,[c.NoError]).then((_)=>{let m=_.slice(-2),T=m[0]*256+m[1];return{compressed_pk:Buffer.from(_.slice(0,33)),error_message:V(T),pk:"OBSOLETE PROPERTY",return_code:T}},S)}class s{transport;versionResponse;constructor(L){if(!L)throw new KL("wallet_ledger_transport_not_defined");this.transport=L}static serializeHRP(L){if(L==null||L.length<3||L.length>83)throw new KL("wallet_ledger_invalid_params",{reason:"Invalid HRP"});let y=Buffer.alloc(1+L.length);return y.writeUInt8(L.length,0),y.write(L,1),y}async serializePath(L){if(this.versionResponse=await JL(this.transport),this.versionResponse.return_code!==c.NoError)throw this.versionResponse;switch(this.versionResponse.major){case 1:return qL(L);case 2:return PL(L);default:return Buffer.alloc(0)}}async signGetChunks(L,y){let _=await this.serializePath(L),m=[];m.push(_);for(let T=0;T<y.length;T+=WL){let w=T+WL;if(T>y.length)w=y.length;m.push(y.slice(T,w))}return m}async getVersion(){try{return this.versionResponse=await JL(this.transport),this.versionResponse}catch(L){return S(L)}}appInfo(){return this.transport.send(176,1,0,0).then((L)=>{let y=L.readUInt16BE(L.length-2),_="",m="",T=0,w=0;if(L[0]!==1)return{error_message:"response format ID not recognized",return_code:36865};let G=L[1];_=L.slice(2,2+G).toString("ascii");let O=2+G,B=L[O];O+=1,m=L.slice(O,O+B).toString("ascii"),O+=B;let W=L[O];return O+=1,T=W,w=L[O],{appName:_,appVersion:m,error_message:V(y),flag_onboarded:(w&4)!==0,flag_pin_validated:(w&128)!==0,flag_recovery:(w&1)!==0,flag_signed_mcu_code:(w&2)!==0,flagLen:T,flagsValue:w,return_code:y}},S)}deviceInfo(){return this.transport.send(224,1,0,0,Buffer.from([]),[c.NoError,28160]).then((L)=>{let y=L.slice(-2),_=y[0]*256+y[1];if(_===28160)return{error_message:"This command is only available in the Dashboard",return_code:_};let m=L.slice(0,4).toString("hex"),T=4,w=L[T];T+=1;let G=L.slice(T,T+w).toString();T+=w;let O=L[T];T+=1;let B=L.slice(T,T+O).toString("hex");T+=O;let W=L[T];T+=1;let X=L.slice(T,T+W);if(X[W-1]===0)X=L.slice(T,T+W-1);let j=X.toString();return{error_message:V(_),flag:B,mcuVersion:j,return_code:_,seVersion:G,targetId:m}},S)}async publicKey(L){try{let y=await this.serializePath(L);switch(this.versionResponse.major){case 1:return AL(this,y);case 2:{let _=Buffer.concat([s.serializeHRP("thor"),y]);return zL(this,_)}default:return{error_message:"App Version is not supported",return_code:25600}}}catch(y){return S(y)}}async getAddressAndPubKey(L,y,_=!1){try{let m=await this.serializePath(L),T=Buffer.concat([s.serializeHRP(y),m]),w=await this.transport.send(d,b.GET_ADDR_SECP256K1,_?DL.SHOW_ADDRESS_IN_DEVICE:DL.ONLY_RETRIEVE,0,T,[c.NoError]),G=Buffer.from(w.slice(0,33)),O=Buffer.from(w.slice(33,-2)).toString(),B=w.readUInt16BE(w.length-2);return{bech32_address:O,compressed_pk:G,error_message:V(B),return_code:B}}catch(m){return S(m)}}showAddressAndPubKey(L,y){return this.getAddressAndPubKey(L,y,!0)}signSendChunk(L,y,_,m=i.JSON){switch(this.versionResponse.major){case 1:return UL(this,L,y,_,m);case 2:return SL(this,L,y,_,m);default:return{error_message:"App Version is not supported",return_code:25600}}}async sign(L,y,_=i.JSON){let m=Buffer.from(y),T=[],w;try{T=await this.signGetChunks(L,m),w=await this.signSendChunk(1,T.length,T[0],_)}catch(O){S(O)}let G={error_message:w.error_message,return_code:w.return_code,signature:null};for(let O=1;O<T.length;O+=1)if(G=await this.signSendChunk(1+O,T.length,T[O],_),G.return_code!==c.NoError)break;return{error_message:G.error_message,return_code:G.return_code,signature:G.signature}}}class r{ledgerTimeout=50000;derivationPath=M0.GAIA;transport;ledgerApp;chain="thor";injectedTransport;constructor(L){if(this.injectedTransport=L,L)this.transport=L}checkOrCreateTransportAndLedger=async(L=!1)=>{if(!L&&this.transport&&this.ledgerApp)return;try{if(!this.transport||L&&!this.injectedTransport)this.transport=this.injectedTransport??await f();switch(this.chain){case"thor":{this.ledgerApp=L||!this.ledgerApp?new s(this.transport):this.ledgerApp;break}case"cosmos":{let _=(await import("@ledgerhq/hw-app-cosmos")).default;this.ledgerApp=L||!this.ledgerApp?new _(this.transport):this.ledgerApp}}return this.ledgerApp}catch(y){throw new $L("wallet_ledger_connection_error",y)}};validateResponse=(L,y)=>{switch(L){case ZL.NoError:return;case ZL.LockedDevice:throw new $L("wallet_ledger_device_locked",{message:`Ledger is locked: ${y}`});case ZL.TC_NotFound:throw new $L("wallet_ledger_device_not_found");default:break}}}class CL extends r{pubKey=null;derivationPath;constructor(L=Y0.GAIA,y){super(y);this.chain="cosmos",this.derivationPath=Q0(L)}connect=async()=>{await this.checkOrCreateTransportAndLedger(!0);let{publicKey:L,address:y}=await this.getAddressAndPubKey();return this.pubKey=Buffer.from(L,"hex").toString("base64"),y};getAddressAndPubKey=async()=>{return await this.checkOrCreateTransportAndLedger(!0),await this.ledgerApp.getAddress(this.derivationPath,this.chain)};signTransaction=async(L,y="0")=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:_,error_message:m,signature:T}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new VL("wallet_ledger_pubkey_not_found");return this.validateResponse(_,m),[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:y,signature:T}]};signAmino=async(L,y)=>{await this.checkOrCreateTransportAndLedger(!0);let _=await this.getAccounts();if(_.findIndex((Z)=>Z.address===L)===-1)throw new VL("wallet_ledger_address_not_found",{address:L});let T=await import("@cosmjs/amino"),w=T.encodeSecp256k1Signature??T.default?.encodeSecp256k1Signature,G=T.serializeSignDoc??T.default?.serializeSignDoc,O=await import("@cosmjs/crypto"),B=O.Secp256k1Signature??O.default?.Secp256k1Signature,W=G(y),X=await this.ledgerApp.sign(this.derivationPath,W);this.validateResponse(X.return_code,X.error_message);let j=B.fromDer(X.signature).toFixedLength();return{signature:w(_[0].pubkey,j),signed:y}};getAccounts=async()=>{await this.checkOrCreateTransportAndLedger(!0);let L=await this.getAddressAndPubKey();return[{address:L.address,algo:"secp256k1",pubkey:Buffer.from(L.publicKey,"hex")}]}}import{ChainId as q,derivationPathToString as H0,NetworkDerivationPath as f0,SwapKitError as LL}from"@swapkit/helpers";import{AbstractSigner as q0}from"ethers";class P extends q0{chainId=q.Ethereum;derivationPath="";ledgerApp=null;ledgerTimeout=50000;injectedTransport;constructor({provider:L,derivationPath:y=f0.OP,chainId:_=q.Optimism,transport:m}){super(L);this.chainId=_||q.Ethereum,this.derivationPath=typeof y==="string"?y:H0(y),this.injectedTransport=m,Object.defineProperty(this,"provider",{enumerable:!0,value:L||null,writable:!1})}connect=(L)=>new P({chainId:this.chainId,derivationPath:this.derivationPath,provider:L,transport:this.injectedTransport});checkOrCreateTransportAndLedger=async()=>{if(this.ledgerApp)return;await this.createTransportAndLedger()};createTransportAndLedger=async()=>{let L=this.injectedTransport??await f(),y=(await import("@ledgerhq/hw-app-eth")).default;this.ledgerApp=new y(L)};getAddress=async()=>{let L=await this.getAddressAndPubKey();if(!L)throw new LL("wallet_ledger_failed_to_get_address");return L.address};getAddressAndPubKey=async()=>{return await this.createTransportAndLedger(),this.ledgerApp?.getAddress(this.derivationPath)};showAddressAndPubKey=async()=>{return await this.createTransportAndLedger(),this.ledgerApp?.getAddress(this.derivationPath,!0)};signMessage=async(L)=>{let{Signature:y}=await import("ethers");await this.createTransportAndLedger();let _=await this.ledgerApp?.signPersonalMessage(this.derivationPath,L);if(!_)throw new LL("wallet_ledger_signing_error");return _.r=`0x${_.r}`,_.s=`0x${_.s}`,y.from(_).serialized};sendTransaction=async(L)=>{if(!this.provider)throw new LL("wallet_ledger_no_provider");let y=await this.signTransaction(L);return await this.provider.broadcastTransaction(y)};signTypedData=async(L,y,_,m)=>{let{buildEIP712DomainType:T}=await import("@swapkit/toolboxes/evm"),{Signature:w,TypedDataEncoder:G}=await import("ethers");await this.createTransportAndLedger();let{EIP712Domain:O,...B}=y,W=m??G.from(B).primaryType,X;try{X=await this.ledgerApp?.signEIP712Message(this.derivationPath,{domain:L,message:_,primaryType:W,types:{EIP712Domain:T(L),...B}})}catch(j){let Z=j instanceof Error&&"statusCode"in j;if(!Z||Z&&j.statusCode===27013)throw j;let Q=G.hashDomain(L).slice(2),Y=G.from(B).hash(_).slice(2);X=await this.ledgerApp?.signEIP712HashedMessage(this.derivationPath,Q,Y)}if(!X)throw new LL("wallet_ledger_signing_error");return X.r=`0x${X.r}`,X.s=`0x${X.s}`,w.from(X).serialized};signTransaction=async(L)=>{let{Transaction:y}=await import("ethers");await this.createTransportAndLedger();let _=await this.provider?.getTransactionCount(L.from||await this.getAddress()),m={chainId:L.chainId||this.chainId,data:L.data,gasLimit:L.gasLimit,...L.gasPrice&&{gasPrice:L.gasPrice},...!L.gasPrice&&L.maxFeePerGas&&{maxFeePerGas:L.maxFeePerGas,maxPriorityFeePerGas:L.maxPriorityFeePerGas},nonce:L.nonce!==void 0?Number((L.nonce||_||0).toString()):_,to:L.to?.toString(),type:L.type&&!Number.isNaN(L.type)?L.type:L.maxFeePerGas?2:0,value:L.value},T=y.from(m).unsignedSerialized.slice(2),{ledgerService:w}=await import("@ledgerhq/hw-app-eth"),G=await w.resolveTransaction(T,{},{erc20:!0,externalPlugins:!0}),O=await this.ledgerApp?.signTransaction(this.derivationPath,T,G);if(!O)throw new LL("wallet_ledger_signing_error");let{r:B,s:W,v:X}=O;return y.from({...m,signature:{r:`0x${B}`,s:`0x${W}`,v:Number(BigInt(X))}}).serialized}}var kL=(L)=>new P({...L,chainId:q.Arbitrum}),cL=(L)=>new P({...L,chainId:q.Aurora}),IL=(L)=>new P({...L,chainId:q.Avalanche}),EL=(L)=>new P({...L,chainId:q.Base}),vL=(L)=>new P({...L,chainId:q.Ethereum}),gL=(L)=>new P({...L,chainId:q.Gnosis}),bL=(L)=>new P({...L,chainId:q.Optimism}),lL=(L)=>new P({...L,chainId:q.Polygon}),xL=(L)=>new P({...L,chainId:q.BinanceSmartChain}),hL=(L)=>new P({...L,chainId:q.Monad}),dL=(L)=>new P({...L,chainId:q.XLayer}),iL=(L)=>new P({...L,chainId:q.Berachain});async function uL(L,y){let _=(await import("@ledgerhq/hw-app-near")).default,{Chain:m,NetworkDerivationPath:T,SwapKitError:w}=await import("@swapkit/helpers"),G=y??await f(),O=new _(G),B=(L||T[m.Near]).join("'/").concat("'"),{address:W,publicKey:X}=await O.getAddress(B);return{getAddress(){return Promise.resolve(W)},async getPublicKey(){let{PublicKey:Z}=await import("@near-js/crypto");return Z.fromString(`ed25519:${X}`)},signDelegateAction(Z){return Promise.reject(new w("wallet_ledger_method_not_supported",{method:"signDelegateAction",wallet:"Ledger"}))},signNep413Message(Z,Q,Y,H,D){return Promise.reject(new w("wallet_ledger_method_not_supported",{method:"signNep413Message",wallet:"Ledger"}))},async signTransaction(Z){let{Signature:Q,SignedTransaction:Y}=await import("@near-js/transactions");try{let H=await O.signTransaction(Z.encode(),B);if(!H)throw Error("Signature undefined");let D=new Q({data:H,keyType:0}),C=new Y({signature:D,transaction:Z});return[H,C]}catch(H){throw new w("wallet_ledger_signing_error",{error:H})}}}}import{Chain as A0,derivationPathToString as P0,NetworkDerivationPath as S0,SwapKitError as v}from"@swapkit/helpers";class nL{derivationPath;ledgerApp=null;address=null;publicKey=null;injectedTransport;constructor(L,y){this.derivationPath=typeof L==="string"?L:P0(L||S0[A0.Sui]),this.injectedTransport=y}getLedgerPath(){return this.derivationPath.replace(/^m\//,"").replace(/\/(\d+)\/(\d+)$/,"/$1'/$2'")}async createTransportAndLedger(){if(this.ledgerApp)return;let L=this.injectedTransport??await f(),y=(await import("@ledgerhq/hw-app-sui")).default;this.ledgerApp=new y(L)}async connect(){if(await this.createTransportAndLedger(),!this.ledgerApp)throw new v("wallet_ledger_transport_error");let L=this.getLedgerPath(),y=await this.ledgerApp.getPublicKey(L);if(!y?.publicKey)throw new v("wallet_ledger_failed_to_get_address");return this.publicKey=y.publicKey,this.address=`0x${Buffer.from(y.address).toString("hex")}`,this.address}toSuiAddress(){if(!this.address)throw new v("wallet_ledger_failed_to_get_address");return this.address}async getAddress(){if(this.address)return this.address;return await this.connect()}async signTransaction(L){let y=L instanceof Uint8Array?L:L.transaction;if(await this.createTransportAndLedger(),!this.ledgerApp)throw new v("wallet_ledger_transport_error");if(!this.publicKey)throw new v("wallet_ledger_failed_to_get_address");try{let _=this.getLedgerPath(),m=new Uint8Array(3+y.length);m[0]=0,m[1]=0,m[2]=0,m.set(y,3);let T=await this.ledgerApp.signTransaction(_,m);if(!T?.signature)throw new v("wallet_ledger_signing_error");let w=this.publicKey.length===33?this.publicKey.slice(1):this.publicKey;if(w.length!==32)throw new v("wallet_ledger_signing_error",{error:"Invalid public key length"});let G=new Uint8Array(97);G[0]=0,G.set(T.signature,1),G.set(w,65);let O=Buffer.from(G).toString("base64");return{bytes:Buffer.from(y).toString("base64"),signature:O}}catch(_){throw new v("wallet_ledger_signing_error",{error:_})}}}var oL=(L,y)=>new nL(L,y);import{base64 as K0}from"@scure/base";import{NetworkDerivationPath as V0,SwapKitError as tL}from"@swapkit/helpers";import{base64 as z0}from"@scure/base";import{SwapKitError as I}from"@swapkit/helpers";var ML=(L)=>{if(L.length<64)throw new I("wallet_ledger_invalid_signature",{reason:"Too short"});if(L[0]!==48)throw new I("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected first byte 0x30"});if(L[1]+2!==L.length)throw new I("wallet_ledger_invalid_signature",{reason:"signature length does not match TLV"});if(L[2]!==2)throw new I("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected length type 0x02"});let y=L[3],_=L.slice(4,y+4);if(_.length===33&&_[0]===0)_=_.slice(1,33);else if(_.length===33)throw new I("wallet_ledger_invalid_signature",{reason:"r too long"});while(_.length<32)_.unshift(0);if(L[y+4]!==2)throw new I("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected length type 0x02 for s"});let m=L[y+5];if(4+y+2+m!==L.length)throw new I("wallet_ledger_invalid_signature",{reason:"TLV byte lengths do not match message length"});let T=L.slice(y+6,L.length);if(T.length===33&&T[0]===0)T=T.slice(1,33);else if(T.length===33)throw new I("wallet_ledger_invalid_signature",{reason:"s too long"});while(T.length<32)T.unshift(0);if(_.length!==32||T.length!==32)throw new I("wallet_ledger_invalid_signature",{reason:"must be 32 bytes each"});return z0.encode(Buffer.concat([_,T]))};class QL extends r{pubKey=null;derivationPath;constructor(L=V0.THOR,y){super(y);this.chain="thor",this.derivationPath=L}get pubkey(){return this.pubKey}connect=async()=>{await this.checkOrCreateTransportAndLedger();let{compressed_pk:L,bech32_address:y}=await this.getAddressAndPubKey();return this.pubKey=K0.encode(L),y};getAddressAndPubKey=async()=>{await this.checkOrCreateTransportAndLedger(!0);let L=await this.ledgerApp.getAddressAndPubKey(this.derivationPath,this.chain);return this.validateResponse(L.return_code,L.error_message),L};showAddressAndPubKey=async()=>{await this.checkOrCreateTransportAndLedger(!0);let L=await this.ledgerApp.showAddressAndPubKey(this.derivationPath,this.chain);return this.validateResponse(L.return_code,L.error_message),L};signTransaction=async(L,y="0")=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:_,error_message:m,signature:T}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new tL("wallet_ledger_pubkey_not_found");return this.validateResponse(_,m),[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:y,signature:ML(T)}]};sign=async(L)=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:y,error_message:_,signature:m}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new tL("wallet_ledger_pubkey_not_found");return this.validateResponse(y,_),ML(m)}}import{derivationPathToString as k0,NetworkDerivationPath as c0,SwapKitError as yL}from"@swapkit/helpers";class pL{derivationPath;ledgerApp=null;ledgerTimeout=50000;injectedTransport;constructor(L,y){this.derivationPath=typeof L==="string"?L:k0(L||c0.TRON),this.injectedTransport=y}checkOrCreateTransportAndLedger=async()=>{if(this.ledgerApp)return;await this.createTransportAndLedger()};createTransportAndLedger=async()=>{let L=this.injectedTransport??await f(),y=(await import("@ledgerhq/hw-app-trx")).default;this.ledgerApp=new y(L)};getAddress=async()=>{let L=await this.getAddressAndPubKey();if(!L)throw new yL("wallet_ledger_failed_to_get_address");return L.address};getAddressAndPubKey=async()=>{await this.createTransportAndLedger();let L=await this.ledgerApp?.getAddress(this.derivationPath);if(!L)throw new yL("wallet_ledger_failed_to_get_address");return{address:L.address,publicKey:L.publicKey}};showAddressAndPubKey=async()=>{return await this.createTransportAndLedger(),this.ledgerApp?.getAddress(this.derivationPath,!0)};signTransaction=async(L)=>{if(await this.createTransportAndLedger(),!this.ledgerApp)throw new yL("wallet_ledger_transport_error");let y=JSON.stringify(L);try{let _=await this.ledgerApp.signTransaction(this.derivationPath,y,[]);if(!_)throw new yL("wallet_ledger_signing_error");return{...L,signature:[_]}}catch(_){throw new yL("wallet_ledger_signing_error",{error:_})}}}var aL=(L,y)=>new pL(L,y);import{hex as XL}from"@scure/base";import{derivationPathToString as I0,getWalletFormatFor as E0,SwapKitError as BL}from"@swapkit/helpers";var sL=["bitcoin-cash","dash","dogecoin","zcash"],eL=({tx:L,inputUtxos:y,btcApp:_,derivationPath:m,chain:T},w)=>{let G=y.map((j)=>{return[_.splitTransaction(j.txHex||"",!sL.includes(T),T==="zcash"),j.index,void 0,void 0]}),O=XL.encode(L.unsignedTx),B=_.splitTransaction(O,!0),W=_.serializeTransactionOutputs(B).toString("hex"),X={additionals:["bech32"],associatedKeysets:G.map(()=>m),inputs:G,outputScriptHex:W,segwit:!0,useTrustedInputForSegwit:!0};return _.createPaymentTransaction({...X,...w})},v0=({tx:L,inputUtxos:y,btcApp:_,derivationPaths:m,chain:T},w)=>{if(m.length!==y.length)throw new BL("wallet_ledger_invalid_params",{message:`Derivation paths count (${m.length}) must match inputs count (${y.length})`});let G=y.map((j)=>{return[_.splitTransaction(j.txHex||"",!sL.includes(T),T==="zcash"),j.index,void 0,void 0]}),O=XL.encode(L.unsignedTx),B=_.splitTransaction(O,!0),W=_.serializeTransactionOutputs(B).toString("hex"),X={additionals:["bech32"],associatedKeysets:m,inputs:G,outputScriptHex:W,segwit:!0,useTrustedInputForSegwit:!0};return _.createPaymentTransaction({...X,...w})},u=({chain:L,additionalSignParams:y})=>{return(_,m)=>{let T,w=null;async function G(X=!0){if(X&&!T)new BL("wallet_ledger_connection_error",{message:`Ledger connection failed:
2
- ${JSON.stringify({btcApp:T,checkBtcApp:X})}`});w||=m??await f()}async function O(){w=m??await f(),T=new(await import("@ledgerhq/hw-app-btc")).default({currency:L,transport:w})}let B=typeof _==="string"?_:I0(_),W=E0(B);return{connect:async()=>{await G(!1),T=new(await import("@ledgerhq/hw-app-btc")).default({currency:L,transport:w})},getAddress:async()=>{let{toCashAddress:X}=await import("@swapkit/toolboxes/utxo");await G(!1);let{bitcoinAddress:j}=await T.getWalletPublicKey(B,{format:W});if(!j)throw new BL("wallet_ledger_get_address_error",{message:`Cannot get ${L} address from ledger derivation path: ${B}`});return L==="bitcoin-cash"&&W==="legacy"?X(j).replace(/(bchtest:|bitcoincash:)/,""):j},getExtendedPublicKey:async(X="84'/0'/0'",j=76067358)=>{return await G(!1),T.getWalletXpub({path:X,xpubVersion:j})},signPCZT:async(X)=>{if(L!=="zcash")throw new BL("wallet_ledger_chain_not_supported",{message:"PCZT signing is only supported for Zcash"});await O();let{ZcashTransaction:j,Script:Z}=await import("@swapkit/utxo-signer"),Q=X.getGlobal(),Y=new j({consensusBranchId:Q.consensusBranchId,expiryHeight:Q.expiryHeight,lockTime:Q.lockTime,version:Q.txVersion,versionGroupId:Q.versionGroupId}),H=[];for(let J=0;J<X.inputsLength;J++){let U=X.getInput(J);Y.addInput({index:U.index,script:new Uint8Array,sequence:U.sequence??4294967295,txid:U.txid,value:U.value}),H.push({hash:XL.encode(new Uint8Array([...U.txid].reverse())),index:U.index,txHex:g0(U,Q),value:Number(U.value),witnessUtxo:{script:U.scriptPubkey,value:Number(U.value)}})}for(let J=0;J<X.outputsLength;J++){let U=X.getOutput(J);Y.addOutput({amount:U.value,script:U.scriptPubkey})}let D=await eL({btcApp:T,chain:L,derivationPath:B,inputUtxos:H,tx:Y},{...y,expiryHeight:(()=>{let J=Buffer.alloc(4);return J.writeUInt32LE(Q.expiryHeight),J})(),lockTime:Q.lockTime}),C=j.fromHex(D,{allowUnknownOutputs:!0}),M=X.clone();for(let J=0;J<C.inputsLength;J++){let U=C.getInput(J);if(U.script&&U.script.length>0){let A=Z.decode(U.script);if(A.length>=2)M.addSignature(J,A[1],A[0])}}return M},signTransaction:async(X,j)=>{return await O(),eL({btcApp:T,chain:L,derivationPath:B,inputUtxos:j,tx:X},y)},signTransactionWithMultiplePaths:async(X,j,Z)=>{return await O(),v0({btcApp:T,chain:L,derivationPaths:Z,inputUtxos:j,tx:X},y)}}}};function g0(L,y){let _=[],m=(y.txVersion|2147483648)>>>0;_.push(m&255,m>>8&255,m>>16&255,m>>24&255);let T=y.versionGroupId;_.push(T&255,T>>8&255,T>>16&255,T>>24&255),_.push(0);let w=L.index+1;if(w<253)_.push(w);else _.push(253,w&255,w>>8&255);for(let B=0;B<L.index;B++)_.push(0,0,0,0,0,0,0,0),_.push(0);let G=L.value;_.push(Number(G&0xffn),Number(G>>8n&0xffn),Number(G>>16n&0xffn),Number(G>>24n&0xffn),Number(G>>32n&0xffn),Number(G>>40n&0xffn),Number(G>>48n&0xffn),Number(G>>56n&0xffn));let O=L.scriptPubkey;if(O.length<253)_.push(O.length);else _.push(253,O.length&255,O.length>>8&255);for(let B of O)_.push(B);return _.push(y.lockTime&255,y.lockTime>>8&255,y.lockTime>>16&255,y.lockTime>>24&255),_.push(y.expiryHeight&255,y.expiryHeight>>8&255,y.expiryHeight>>16&255,y.expiryHeight>>24&255),_.push(0,0,0,0,0,0,0,0),_.push(0),_.push(0),_.push(0),XL.encode(new Uint8Array(_))}var rL=u({chain:"bitcoin"}),L0=u({chain:"litecoin"}),y0=u({additionalSignParams:{additionals:["abc"],segwit:!1,sigHashType:65},chain:"bitcoin-cash"}),_0=u({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dogecoin"}),T0=u({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dash"}),w0=u({additionalSignParams:{additionals:["zcash","sapling"],expiryHeight:(()=>{let L=Buffer.alloc(4);return L.writeUInt32LE(0),L})(),lockTime:0,segwit:!1,useTrustedInputForSegwit:!1},chain:"zcash"});import b0 from"@ledgerhq/hw-app-xrp";import{Chain as l0,derivationPathToString as x0,NetworkDerivationPath as h0}from"@swapkit/helpers";import{encode as m0}from"ripple-binary-codec";var d0=2147483648;function i0(L){let y={};for(let _ in L)if(L[_]!==null&&L[_]!==void 0)y[_]=L[_];return y}function u0(L){return new b0(L)}var R0=async(L,y)=>{let _=x0(L||h0[l0.Ripple]),m=y??await f(),T=u0(m),{address:w,publicKey:G}=await T.getAddress(_);async function O(B){let{hashes:W}=await import("@swapkit/toolboxes/ripple"),j={...i0(B),Flags:B.Flags||d0,SigningPubKey:G.toUpperCase()},Z=m0(j),Q=await T.signTransaction(_,Z),Y=m0({...j,TxnSignature:Q});return{hash:W.hashSignedTx(Y),tx_blob:Y}}return{getAddress:()=>w,signTransaction:O}};var z=async({chain:L,derivationPath:y,transport:_})=>{let{match:m}=await import("ts-pattern");return m(L).returnType().with(F.THORChain,()=>Promise.resolve(new QL(y,_))).with(F.Cosmos,()=>Promise.resolve(new CL(y,_))).with(F.Bitcoin,()=>Promise.resolve(rL(y,_))).with(F.BitcoinCash,()=>Promise.resolve(y0(y,_))).with(F.Dash,()=>Promise.resolve(T0(y,_))).with(F.Dogecoin,()=>Promise.resolve(_0(y,_))).with(F.Litecoin,()=>Promise.resolve(L0(y,_))).with(F.Zcash,()=>Promise.resolve(w0(y,_))).with(F.Ripple,()=>Promise.resolve(R0(y,_))).with(F.Tron,()=>Promise.resolve(aL(y,_))).with(F.Sui,()=>Promise.resolve(oL(y,_))).with(F.Near,()=>{return Promise.resolve(uL(y,_))}).with(F.Arbitrum,F.Aurora,F.Avalanche,F.Berachain,F.BinanceSmartChain,F.Ethereum,F.Gnosis,F.Monad,F.Optimism,F.Polygon,F.Base,F.XLayer,async()=>{let{getProvider:T}=await import("@swapkit/toolboxes/evm"),w={derivationPath:y,provider:await T(L),transport:_};return m(L).with(F.BinanceSmartChain,()=>xL(w)).with(F.Avalanche,()=>IL(w)).with(F.Arbitrum,()=>kL(w)).with(F.Berachain,()=>iL(w)).with(F.Optimism,()=>bL(w)).with(F.Polygon,()=>lL(w)).with(F.Base,()=>EL(w)).with(F.Aurora,()=>cL(w)).with(F.Gnosis,()=>gL(w)).with(F.Monad,()=>hL(w)).with(F.XLayer,()=>dL(w)).otherwise(()=>vL(w))}).otherwise(()=>{throw new n0("wallet_chain_not_supported",{chain:L,wallet:o0.LEDGER})})};var wy=_y({connect:({addChain:L,supportedChains:y,walletType:_})=>async function(T,w,{transport:G}={}){let[O]=t0({chains:T,supportedChains:y,walletType:_});if(!O)return!1;let B=w??p0[O],W=await Oy({chain:O,derivationPath:B,transport:G});return L({...W,chain:O,walletType:B0.LEDGER}),!0},directSigningSupport:{[R.Arbitrum]:!0,[R.Aurora]:!0,[R.Avalanche]:!0,[R.Base]:!0,[R.Berachain]:!0,[R.BinanceSmartChain]:!0,[R.Ethereum]:!0,[R.Gnosis]:!0,[R.Monad]:!0,[R.Bitcoin]:!0,[R.BitcoinCash]:!0,[R.Cosmos]:!0,[R.Dash]:!0,[R.Dogecoin]:!0,[R.Litecoin]:!0,[R.Near]:!0,[R.Optimism]:!0,[R.Polygon]:!0,[R.Ripple]:!0,[R.Sui]:!0,[R.Tron]:!0,[R.XLayer]:!0},name:"connectLedger",supportedChains:[R.Arbitrum,R.Aurora,R.Avalanche,R.Base,R.Berachain,R.BinanceSmartChain,R.Bitcoin,R.BitcoinCash,R.Cosmos,R.Dash,R.Dogecoin,R.Ethereum,R.Gnosis,R.Litecoin,R.Monad,R.Near,R.Optimism,R.Polygon,R.Ripple,R.Sui,R.THORChain,R.XLayer,R.Tron,R.Zcash],walletType:B0.LEDGER}),Z_=Ty(wy);function my(L,y="t"){if(!L?.includes("=:"))return L;let _=L.includes(`:${y}:`)?L.split(`:${y}:`)[0]:L;return _?.substring(0,_.lastIndexOf(":"))}function NL(L){if(Array.isArray(L))return L.forEach((m,T)=>{L[T]=NL(m)}),L;if(typeof L!=="object")return L;let y={},_=Object.keys(L).sort();for(let m of _)y[m]=NL(L[m]);return y}function Ry(L){return JSON.stringify(NL(L))}async function Oy({chain:L,derivationPath:y,transport:_}){switch(L){case R.BitcoinCash:case R.Bitcoin:case R.Dash:case R.Dogecoin:case R.Litecoin:case R.Zcash:{let j=function(){return X()},{getUtxoToolbox:m}=await import("@swapkit/toolboxes/utxo"),T=L,w=await z({chain:L,derivationPath:y,transport:_}),G=await k({chain:L,ledgerClient:w}),O;if(L===R.Bitcoin||L===R.Litecoin){let{BitcoinPsbtLedger:D,LitecoinPsbtLedger:C}=await import("../chunk-9jd3dhjv.js"),M=L===R.Bitcoin?D(y,_):C(y,_);O={getAddress:M.getAddress,signTransaction:M.signTransaction}}else if(L===R.BitcoinCash||L===R.Dogecoin||L===R.Dash){let{createLegacyPsbtSigner:D}=await import("../chunk-px09mwnt.js");O=D({address:G,chain:T,legacyClient:w})}let B=O?await m(T,{signer:O}):m(T),W=async(D)=>{let C=D.feeRate||(await B.getFeeRates())[O0.Average],M=[R.Bitcoin].includes(L)?D.memo:my(D.memo),{tx:J,inputs:U}=await B.createTransaction({...D,feeRate:C,fetchTxHex:!0,memo:M,sender:G}),A=await w.signTransaction(J,U);return await B.broadcastTx(A)};async function X({accountIndex:D}={}){if(!w.getExtendedPublicKey)return;let C=j0({accountIndex:D,chain:T,derivationPath:y}),M=YL(C),J=L===R.Bitcoin||L===R.Litecoin?M:M.replace(/^m\//,""),U=await w.getExtendedPublicKey(J);return{accountIndex:N0(C),path:M,xpub:U}}async function Z({accountIndex:D,index:C,change:M=!1}){try{let J=Ly({accountIndex:D,chain:T,change:M,derivationPath:y,index:C}),U=await z({chain:T,derivationPath:J,transport:_}),A=await k({chain:T,ledgerClient:U});return{accountIndex:N0(J),address:A,change:M,index:C,path:YL(J),pubkey:""}}catch{return}}async function Q({accountIndex:D,count:C,startIndex:M=0,change:J=!1}){return X0("count",C),X0("startIndex",M),(await Promise.all(Array.from({length:C},(A,g)=>Z({accountIndex:D,change:J,index:M+g})))).filter((A)=>!!A)}let Y=r0({chain:T,deriveAddress:Z,getBalance:B.getBalance,getUtxos:(D)=>yy(T).getUtxos({address:D,fetchTxHex:!0})});async function H({utxos:D,recipient:C,assetValue:M,memo:J,feeRate:U,feeOptionKey:A,changeAddress:g}){if(!D.length)throw new E("wallet_ledger_invalid_params",{message:"No UTXOs provided for multi-address transfer"});let HL=U||(await B.getFeeRates())[A||O0.Fast],_L=J?s0(J):null,K=[{address:C,value:M.getBaseValue("number")}];if(_L)K.push({script:_L,value:0});let TL=D.map(({hash:x,index:h,value:p,txHex:a,witnessUtxo:e})=>({hash:x,index:h,txHex:a,value:p,witnessUtxo:e})),{inputs:l,outputs:n}=B.accumulative({chain:T,feeRate:HL,inputs:TL,outputs:K});if(!(l&&n))throw new E("wallet_ledger_connection_error",{message:"Insufficient balance for multi-address transfer"});let{Transaction:jL}=await import("@swapkit/utxo-signer"),wL=new jL({allowLegacyWitnessUtxo:!0,version:1}),o=g||D[0]?.address||C;e0({chain:T,compiledMemo:_L,inputs:l,outputs:n,sender:o,tx:wL});let mL=j0({chain:T,derivationPath:y}),FL=l.map((x)=>{let h=D.find((RL)=>RL.hash===x.hash&&RL.index===x.index),p=h?.derivationIndex??0,a=h?.isChange??!1,e=[...mL,Number(a),p];return YL(e)});if(!w.signTransactionWithMultiplePaths)throw new E("wallet_ledger_method_not_supported",{method:"signTransactionWithMultiplePaths"});let t=await w.signTransactionWithMultiplePaths(wL,l,FL);return B.broadcastTx(t)}return{...B,...Y,address:G,deriveAddressAtIndex:Z,deriveAddresses:Q,getExtendedPublicKey:j,getExtendedPublicKeyInfo:X,transfer:W,transferFromMultipleAddresses:H}}case R.Ethereum:case R.Avalanche:case R.Arbitrum:case R.Berachain:case R.Optimism:case R.Polygon:case R.BinanceSmartChain:case R.Base:case R.Aurora:case R.Gnosis:case R.Monad:case R.XLayer:{let{getEvmToolboxAsync:m}=await import("@swapkit/toolboxes/evm"),T=await z({chain:L,derivationPath:y,transport:_}),w=await k({chain:L,ledgerClient:T});return{...await m(L,{signer:T}),address:w}}case R.Cosmos:{let{createSigningStargateClient:m,getMsgSendDenom:T,getCosmosToolbox:w}=await import("@swapkit/toolboxes/cosmos"),G=await z({chain:L,derivationPath:y,transport:_}),O=await k({chain:L,ledgerClient:G});return{...await w(R.Cosmos,{signer:G}),address:O,transfer:async({assetValue:X,recipient:j,memo:Z})=>{if(!X)throw new E("wallet_ledger_invalid_asset");let Q={amount:[{amount:X.getBaseValue("string"),denom:T(`u${X.symbol}`).toLowerCase()}],fromAddress:O,toAddress:j},Y=await G0(L),H=await m(Y,G,"0.007uatom"),{transactionHash:D}=await H.signAndBroadcast(O,[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:Q}],2,Z);return D}}}case R.THORChain:{let{SignMode:m}=await import("cosmjs-types/cosmos/tx/signing/v1beta1/signing.js"),{TxRaw:T}=await import("cosmjs-types/cosmos/tx/v1beta1/tx.js"),w=await import("@cosmjs/proto-signing"),G=w.encodePubkey??w.default?.encodePubkey,O=w.makeAuthInfoBytes??w.default?.makeAuthInfoBytes,{createStargateClient:B,buildEncodedTxBody:W,getCosmosToolbox:X,buildAminoMsg:j,getDefaultChainFee:Z,fromBase64:Q,parseAminoMessageForDirectSigning:Y}=await import("@swapkit/toolboxes/cosmos"),H=X(L),D=await z({chain:L,derivationPath:y,transport:_}),C=await k({chain:L,ledgerClient:D}),M=Z(L),{pubkey:J,signTransaction:U,sign:A}=D,g=async({memo:K="",assetValue:TL,...l})=>{let n=await H.getAccount(C);if(!n)throw new E("wallet_ledger_invalid_account");if(!TL)throw new E("wallet_ledger_invalid_asset");if(!J)throw new E("wallet_ledger_pubkey_not_found");let{accountNumber:jL,sequence:wL}=n,o=(wL||0).toString(),mL=NL([j({assetValue:TL,memo:K,sender:C,...l})]),FL=Ry({account_number:jL?.toString(),chain_id:a0.chainId,fee:M,memo:K,msgs:mL,sequence:o}),t=await U(FL,o);if(!t)throw new E("wallet_ledger_signing_error");let x=G({type:"tendermint/PubKeySecp256k1",value:J}),h=mL.map(Y),p=await W({chain:L,memo:K,msgs:h}),a=O([{pubkey:x,sequence:Number(o)}],M.amount,Number.parseInt(M.gas,10),void 0,void 0,m.SIGN_MODE_LEGACY_AMINO_JSON),e=t?.[0]?.signature?Q(t[0].signature):Uint8Array.from([]),RL=T.fromPartial({authInfoBytes:a,bodyBytes:p,signatures:[e]}),F0=T.encode(RL).finish(),W0=await G0(R.THORChain),D0=await B(W0),{transactionHash:J0}=await D0.broadcastTx(F0);return J0};return{...H,address:C,deposit:(K)=>g(K),signMessage:A,transfer:(K)=>g(K)}}case R.Near:{let{getNearToolbox:m}=await import("@swapkit/toolboxes/near"),T=await z({chain:L,derivationPath:y,transport:_}),w=await T.getAddress();return{...m({signer:T}),address:w}}case R.Ripple:{let{getRippleToolbox:m}=await import("@swapkit/toolboxes/ripple"),T=await z({chain:L,derivationPath:y,transport:_}),w=T.getAddress();return{...m({signer:T}),address:w}}case R.Tron:{let{getTronToolbox:m}=await import("@swapkit/toolboxes/tron"),T=await z({chain:L,derivationPath:y,transport:_}),w=await k({chain:L,ledgerClient:T});return{...m({signer:T}),address:w}}case R.Sui:{let{getSuiToolbox:m}=await import("@swapkit/toolboxes/sui"),T=await z({chain:L,derivationPath:y,transport:_}),w=await k({chain:L,ledgerClient:T});return{...m({signer:T}),address:w}}default:throw new E("wallet_ledger_chain_not_supported",{chain:L})}}export{wy as ledgerWallet,Z_ as LEDGER_SUPPORTED_CHAINS};
2
+ ${JSON.stringify({btcApp:T,checkBtcApp:X})}`});w||=m??await f()}async function O(){w=m??await f(),T=new(await import("@ledgerhq/hw-app-btc")).default({currency:L,transport:w})}let B=typeof _==="string"?_:I0(_),W=E0(B);return{connect:async()=>{await G(!1),T=new(await import("@ledgerhq/hw-app-btc")).default({currency:L,transport:w})},getAddress:async()=>{let{toCashAddress:X}=await import("@swapkit/toolboxes/utxo");await G(!1);let{bitcoinAddress:j}=await T.getWalletPublicKey(B,{format:W});if(!j)throw new BL("wallet_ledger_get_address_error",{message:`Cannot get ${L} address from ledger derivation path: ${B}`});return L==="bitcoin-cash"&&W==="legacy"?X(j).replace(/(bchtest:|bitcoincash:)/,""):j},getExtendedPublicKey:async(X="84'/0'/0'",j=76067358)=>{return await G(!1),T.getWalletXpub({path:X,xpubVersion:j})},signPCZT:async(X)=>{if(L!=="zcash")throw new BL("wallet_ledger_chain_not_supported",{message:"PCZT signing is only supported for Zcash"});await O();let{ZcashTransaction:j,Script:Z}=await import("@swapkit/utxo-signer"),Q=X.getGlobal(),Y=new j({consensusBranchId:Q.consensusBranchId,expiryHeight:Q.expiryHeight,lockTime:Q.lockTime,version:Q.txVersion,versionGroupId:Q.versionGroupId}),H=[];for(let J=0;J<X.inputsLength;J++){let U=X.getInput(J);Y.addInput({index:U.index,script:new Uint8Array,sequence:U.sequence??4294967295,txid:U.txid,value:U.value}),H.push({hash:XL.encode(new Uint8Array([...U.txid].reverse())),index:U.index,txHex:g0(U,Q),value:Number(U.value),witnessUtxo:{script:U.scriptPubkey,value:Number(U.value)}})}for(let J=0;J<X.outputsLength;J++){let U=X.getOutput(J);Y.addOutput({amount:U.value,script:U.scriptPubkey})}let D=await eL({btcApp:T,chain:L,derivationPath:B,inputUtxos:H,tx:Y},{...y,expiryHeight:(()=>{let J=Buffer.alloc(4);return J.writeUInt32LE(Q.expiryHeight),J})(),lockTime:Q.lockTime}),C=j.fromHex(D,{allowUnknownOutputs:!0}),M=X.clone();for(let J=0;J<C.inputsLength;J++){let U=C.getInput(J);if(U.script&&U.script.length>0){let A=Z.decode(U.script);if(A.length>=2)M.addSignature(J,A[1],A[0])}}return M},signTransaction:async(X,j)=>{return await O(),eL({btcApp:T,chain:L,derivationPath:B,inputUtxos:j,tx:X},y)},signTransactionWithMultiplePaths:async(X,j,Z)=>{return await O(),v0({btcApp:T,chain:L,derivationPaths:Z,inputUtxos:j,tx:X},y)}}}};function g0(L,y){let _=[],m=(y.txVersion|2147483648)>>>0;_.push(m&255,m>>8&255,m>>16&255,m>>24&255);let T=y.versionGroupId;_.push(T&255,T>>8&255,T>>16&255,T>>24&255),_.push(0);let w=L.index+1;if(w<253)_.push(w);else _.push(253,w&255,w>>8&255);for(let B=0;B<L.index;B++)_.push(0,0,0,0,0,0,0,0),_.push(0);let G=L.value;_.push(Number(G&0xffn),Number(G>>8n&0xffn),Number(G>>16n&0xffn),Number(G>>24n&0xffn),Number(G>>32n&0xffn),Number(G>>40n&0xffn),Number(G>>48n&0xffn),Number(G>>56n&0xffn));let O=L.scriptPubkey;if(O.length<253)_.push(O.length);else _.push(253,O.length&255,O.length>>8&255);for(let B of O)_.push(B);return _.push(y.lockTime&255,y.lockTime>>8&255,y.lockTime>>16&255,y.lockTime>>24&255),_.push(y.expiryHeight&255,y.expiryHeight>>8&255,y.expiryHeight>>16&255,y.expiryHeight>>24&255),_.push(0,0,0,0,0,0,0,0),_.push(0),_.push(0),_.push(0),XL.encode(new Uint8Array(_))}var rL=u({chain:"bitcoin"}),L0=u({chain:"litecoin"}),y0=u({additionalSignParams:{additionals:["abc"],segwit:!1,sigHashType:65},chain:"bitcoin-cash"}),_0=u({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dogecoin"}),T0=u({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dash"}),w0=u({additionalSignParams:{additionals:["zcash","sapling"],expiryHeight:(()=>{let L=Buffer.alloc(4);return L.writeUInt32LE(0),L})(),lockTime:0,segwit:!1,useTrustedInputForSegwit:!1},chain:"zcash"});import b0 from"@ledgerhq/hw-app-xrp";import{Chain as l0,derivationPathToString as x0,NetworkDerivationPath as h0}from"@swapkit/helpers";import{encode as m0}from"ripple-binary-codec";var d0=2147483648;function i0(L){let y={};for(let _ in L)if(L[_]!==null&&L[_]!==void 0)y[_]=L[_];return y}function u0(L){return new b0(L)}var R0=async(L,y)=>{let _=x0(L||h0[l0.Ripple]),m=y??await f(),T=u0(m),{address:w,publicKey:G}=await T.getAddress(_);async function O(B){let{hashes:W}=await import("@swapkit/toolboxes/ripple"),j={...i0(B),Flags:B.Flags||d0,SigningPubKey:G.toUpperCase()},Z=m0(j),Q=await T.signTransaction(_,Z),Y=m0({...j,TxnSignature:Q});return{hash:W.hashSignedTx(Y),tx_blob:Y}}return{getAddress:()=>w,signTransaction:O}};var z=async({chain:L,derivationPath:y,transport:_})=>{let{match:m}=await import("ts-pattern");return m(L).returnType().with(F.THORChain,()=>Promise.resolve(new QL(y,_))).with(F.Cosmos,()=>Promise.resolve(new CL(y,_))).with(F.Bitcoin,()=>Promise.resolve(rL(y,_))).with(F.BitcoinCash,()=>Promise.resolve(y0(y,_))).with(F.Dash,()=>Promise.resolve(T0(y,_))).with(F.Dogecoin,()=>Promise.resolve(_0(y,_))).with(F.Litecoin,()=>Promise.resolve(L0(y,_))).with(F.Zcash,()=>Promise.resolve(w0(y,_))).with(F.Ripple,()=>Promise.resolve(R0(y,_))).with(F.Tron,()=>Promise.resolve(aL(y,_))).with(F.Sui,()=>Promise.resolve(oL(y,_))).with(F.Near,()=>{return Promise.resolve(uL(y,_))}).with(F.Arbitrum,F.Aurora,F.Avalanche,F.Berachain,F.BinanceSmartChain,F.Ethereum,F.Gnosis,F.Monad,F.Optimism,F.Polygon,F.Base,F.XLayer,async()=>{let{getProvider:T}=await import("@swapkit/toolboxes/evm"),w={derivationPath:y,provider:await T(L),transport:_};return m(L).with(F.BinanceSmartChain,()=>xL(w)).with(F.Avalanche,()=>IL(w)).with(F.Arbitrum,()=>kL(w)).with(F.Berachain,()=>iL(w)).with(F.Optimism,()=>bL(w)).with(F.Polygon,()=>lL(w)).with(F.Base,()=>EL(w)).with(F.Aurora,()=>cL(w)).with(F.Gnosis,()=>gL(w)).with(F.Monad,()=>hL(w)).with(F.XLayer,()=>dL(w)).otherwise(()=>vL(w))}).otherwise(()=>{throw new n0("wallet_chain_not_supported",{chain:L,wallet:o0.LEDGER})})};var wy=_y({connect:({addChain:L,supportedChains:y,walletType:_})=>async function(T,w,{transport:G}={}){let[O]=t0({chains:T,supportedChains:y,walletType:_});if(!O)return!1;let B=w??p0[O],W=await Oy({chain:O,derivationPath:B,transport:G});return L({...W,chain:O,walletType:B0.LEDGER}),!0},directSigningSupport:{[R.Arbitrum]:!0,[R.Aurora]:!0,[R.Avalanche]:!0,[R.Base]:!0,[R.Berachain]:!0,[R.BinanceSmartChain]:!0,[R.Ethereum]:!0,[R.Gnosis]:!0,[R.Monad]:!0,[R.Bitcoin]:!0,[R.BitcoinCash]:!0,[R.Cosmos]:!0,[R.Dash]:!0,[R.Dogecoin]:!0,[R.Litecoin]:!0,[R.Near]:!0,[R.Optimism]:!0,[R.Polygon]:!0,[R.Ripple]:!0,[R.Sui]:!0,[R.Tron]:!0,[R.XLayer]:!0},name:"connectLedger",supportedChains:[R.Arbitrum,R.Aurora,R.Avalanche,R.Base,R.Berachain,R.BinanceSmartChain,R.Bitcoin,R.BitcoinCash,R.Cosmos,R.Dash,R.Dogecoin,R.Ethereum,R.Gnosis,R.Litecoin,R.Monad,R.Near,R.Optimism,R.Polygon,R.Ripple,R.Sui,R.THORChain,R.XLayer,R.Tron,R.Zcash],walletType:B0.LEDGER}),Z_=Ty(wy);function my(L,y="t"){if(!L?.includes("=:"))return L;let _=L.includes(`:${y}:`)?L.split(`:${y}:`)[0]:L;return _?.substring(0,_.lastIndexOf(":"))}function NL(L){if(Array.isArray(L))return L.forEach((m,T)=>{L[T]=NL(m)}),L;if(typeof L!=="object")return L;let y={},_=Object.keys(L).sort();for(let m of _)y[m]=NL(L[m]);return y}function Ry(L){return JSON.stringify(NL(L))}async function Oy({chain:L,derivationPath:y,transport:_}){switch(L){case R.BitcoinCash:case R.Bitcoin:case R.Dash:case R.Dogecoin:case R.Litecoin:case R.Zcash:{let j=function(){return X()},{getUtxoToolbox:m}=await import("@swapkit/toolboxes/utxo"),T=L,w=await z({chain:L,derivationPath:y,transport:_}),G=await k({chain:L,ledgerClient:w}),O;if(L===R.Bitcoin||L===R.Litecoin){let{BitcoinPsbtLedger:D,LitecoinPsbtLedger:C}=await import("../chunk-jttnd211.js"),M=L===R.Bitcoin?D(y,_):C(y,_);O={getAddress:M.getAddress,signTransaction:M.signTransaction}}else if(L===R.BitcoinCash||L===R.Dogecoin||L===R.Dash){let{createLegacyPsbtSigner:D}=await import("../chunk-px09mwnt.js");O=D({address:G,chain:T,legacyClient:w})}let B=O?await m(T,{signer:O}):m(T),W=async(D)=>{let C=D.feeRate||(await B.getFeeRates())[O0.Average],M=[R.Bitcoin].includes(L)?D.memo:my(D.memo),{tx:J,inputs:U}=await B.createTransaction({...D,feeRate:C,fetchTxHex:!0,memo:M,sender:G}),A=await w.signTransaction(J,U);return await B.broadcastTx(A)};async function X({accountIndex:D}={}){if(!w.getExtendedPublicKey)return;let C=j0({accountIndex:D,chain:T,derivationPath:y}),M=YL(C),J=L===R.Bitcoin||L===R.Litecoin?M:M.replace(/^m\//,""),U=await w.getExtendedPublicKey(J);return{accountIndex:N0(C),path:M,xpub:U}}async function Z({accountIndex:D,index:C,change:M=!1}){try{let J=Ly({accountIndex:D,chain:T,change:M,derivationPath:y,index:C}),U=await z({chain:T,derivationPath:J,transport:_}),A=await k({chain:T,ledgerClient:U});return{accountIndex:N0(J),address:A,change:M,index:C,path:YL(J),pubkey:""}}catch{return}}async function Q({accountIndex:D,count:C,startIndex:M=0,change:J=!1}){return X0("count",C),X0("startIndex",M),(await Promise.all(Array.from({length:C},(A,g)=>Z({accountIndex:D,change:J,index:M+g})))).filter((A)=>!!A)}let Y=r0({chain:T,deriveAddress:Z,getBalance:B.getBalance,getUtxos:(D)=>yy(T).getUtxos({address:D,fetchTxHex:!0})});async function H({utxos:D,recipient:C,assetValue:M,memo:J,feeRate:U,feeOptionKey:A,changeAddress:g}){if(!D.length)throw new E("wallet_ledger_invalid_params",{message:"No UTXOs provided for multi-address transfer"});let HL=U||(await B.getFeeRates())[A||O0.Fast],_L=J?s0(J):null,K=[{address:C,value:M.getBaseValue("number")}];if(_L)K.push({script:_L,value:0});let TL=D.map(({hash:x,index:h,value:p,txHex:a,witnessUtxo:e})=>({hash:x,index:h,txHex:a,value:p,witnessUtxo:e})),{inputs:l,outputs:n}=B.accumulative({chain:T,feeRate:HL,inputs:TL,outputs:K});if(!(l&&n))throw new E("wallet_ledger_connection_error",{message:"Insufficient balance for multi-address transfer"});let{Transaction:jL}=await import("@swapkit/utxo-signer"),wL=new jL({allowLegacyWitnessUtxo:!0,version:1}),o=g||D[0]?.address||C;e0({chain:T,compiledMemo:_L,inputs:l,outputs:n,sender:o,tx:wL});let mL=j0({chain:T,derivationPath:y}),FL=l.map((x)=>{let h=D.find((RL)=>RL.hash===x.hash&&RL.index===x.index),p=h?.derivationIndex??0,a=h?.isChange??!1,e=[...mL,Number(a),p];return YL(e)});if(!w.signTransactionWithMultiplePaths)throw new E("wallet_ledger_method_not_supported",{method:"signTransactionWithMultiplePaths"});let t=await w.signTransactionWithMultiplePaths(wL,l,FL);return B.broadcastTx(t)}return{...B,...Y,address:G,deriveAddressAtIndex:Z,deriveAddresses:Q,getExtendedPublicKey:j,getExtendedPublicKeyInfo:X,transfer:W,transferFromMultipleAddresses:H}}case R.Ethereum:case R.Avalanche:case R.Arbitrum:case R.Berachain:case R.Optimism:case R.Polygon:case R.BinanceSmartChain:case R.Base:case R.Aurora:case R.Gnosis:case R.Monad:case R.XLayer:{let{getEvmToolboxAsync:m}=await import("@swapkit/toolboxes/evm"),T=await z({chain:L,derivationPath:y,transport:_}),w=await k({chain:L,ledgerClient:T});return{...await m(L,{signer:T}),address:w}}case R.Cosmos:{let{createSigningStargateClient:m,getMsgSendDenom:T,getCosmosToolbox:w}=await import("@swapkit/toolboxes/cosmos"),G=await z({chain:L,derivationPath:y,transport:_}),O=await k({chain:L,ledgerClient:G});return{...await w(R.Cosmos,{signer:G}),address:O,transfer:async({assetValue:X,recipient:j,memo:Z})=>{if(!X)throw new E("wallet_ledger_invalid_asset");let Q={amount:[{amount:X.getBaseValue("string"),denom:T(`u${X.symbol}`).toLowerCase()}],fromAddress:O,toAddress:j},Y=await G0(L),H=await m(Y,G,"0.007uatom"),{transactionHash:D}=await H.signAndBroadcast(O,[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:Q}],2,Z);return D}}}case R.THORChain:{let{SignMode:m}=await import("cosmjs-types/cosmos/tx/signing/v1beta1/signing.js"),{TxRaw:T}=await import("cosmjs-types/cosmos/tx/v1beta1/tx.js"),w=await import("@cosmjs/proto-signing"),G=w.encodePubkey??w.default?.encodePubkey,O=w.makeAuthInfoBytes??w.default?.makeAuthInfoBytes,{createStargateClient:B,buildEncodedTxBody:W,getCosmosToolbox:X,buildAminoMsg:j,getDefaultChainFee:Z,fromBase64:Q,parseAminoMessageForDirectSigning:Y}=await import("@swapkit/toolboxes/cosmos"),H=X(L),D=await z({chain:L,derivationPath:y,transport:_}),C=await k({chain:L,ledgerClient:D}),M=Z(L),{pubkey:J,signTransaction:U,sign:A}=D,g=async({memo:K="",assetValue:TL,...l})=>{let n=await H.getAccount(C);if(!n)throw new E("wallet_ledger_invalid_account");if(!TL)throw new E("wallet_ledger_invalid_asset");if(!J)throw new E("wallet_ledger_pubkey_not_found");let{accountNumber:jL,sequence:wL}=n,o=(wL||0).toString(),mL=NL([j({assetValue:TL,memo:K,sender:C,...l})]),FL=Ry({account_number:jL?.toString(),chain_id:a0.chainId,fee:M,memo:K,msgs:mL,sequence:o}),t=await U(FL,o);if(!t)throw new E("wallet_ledger_signing_error");let x=G({type:"tendermint/PubKeySecp256k1",value:J}),h=mL.map(Y),p=await W({chain:L,memo:K,msgs:h}),a=O([{pubkey:x,sequence:Number(o)}],M.amount,Number.parseInt(M.gas,10),void 0,void 0,m.SIGN_MODE_LEGACY_AMINO_JSON),e=t?.[0]?.signature?Q(t[0].signature):Uint8Array.from([]),RL=T.fromPartial({authInfoBytes:a,bodyBytes:p,signatures:[e]}),F0=T.encode(RL).finish(),W0=await G0(R.THORChain),D0=await B(W0),{transactionHash:J0}=await D0.broadcastTx(F0);return J0};return{...H,address:C,deposit:(K)=>g(K),signMessage:A,transfer:(K)=>g(K)}}case R.Near:{let{getNearToolbox:m}=await import("@swapkit/toolboxes/near"),T=await z({chain:L,derivationPath:y,transport:_}),w=await T.getAddress();return{...m({signer:T}),address:w}}case R.Ripple:{let{getRippleToolbox:m}=await import("@swapkit/toolboxes/ripple"),T=await z({chain:L,derivationPath:y,transport:_}),w=T.getAddress();return{...m({signer:T}),address:w}}case R.Tron:{let{getTronToolbox:m}=await import("@swapkit/toolboxes/tron"),T=await z({chain:L,derivationPath:y,transport:_}),w=await k({chain:L,ledgerClient:T});return{...m({signer:T}),address:w}}case R.Sui:{let{getSuiToolbox:m}=await import("@swapkit/toolboxes/sui"),T=await z({chain:L,derivationPath:y,transport:_}),w=await k({chain:L,ledgerClient:T});return{...m({signer:T}),address:w}}default:throw new E("wallet_ledger_chain_not_supported",{chain:L})}}export{wy as ledgerWallet,Z_ as LEDGER_SUPPORTED_CHAINS};
3
3
 
4
4
  //# debugId=135ADE5A0C3CEF1464756E2164756E21
5
5
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utxo-psbt.d.ts","sourceRoot":"","sources":["../../../../src/ledger/clients/utxo-psbt.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,MAAM,wBAAwB,CAAC;AAGpD,OAAO,EAAE,KAAK,mBAAmB,EAA4D,MAAM,kBAAkB,CAAC;AACtH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AA+IxD,eAAO,MAAM,iBAAiB,yBAzGE,mBAAmB,GAAG,MAAM,sBAAsB,SAAS;;;;0BAgFzD,WAAW,KAAG,OAAO,CAAC,WAAW,CAAC;CAyBK,CAAC;AAC1E,eAAO,MAAM,kBAAkB,yBA1GC,mBAAmB,GAAG,MAAM,sBAAsB,SAAS;;;;0BAgFzD,WAAW,KAAG,OAAO,CAAC,WAAW,CAAC;CA0BO,CAAC"}
1
+ {"version":3,"file":"utxo-psbt.d.ts","sourceRoot":"","sources":["../../../../src/ledger/clients/utxo-psbt.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,MAAM,wBAAwB,CAAC;AAGpD,OAAO,EAAE,KAAK,mBAAmB,EAA4D,MAAM,kBAAkB,CAAC;AACtH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAmKxD,eAAO,MAAM,iBAAiB,yBAnHE,mBAAmB,GAAG,MAAM,sBAAsB,SAAS;;;;0BAmFzD,WAAW,KAAG,OAAO,CAAC,WAAW,CAAC;CAgCK,CAAC;AAC1E,eAAO,MAAM,kBAAkB,yBApHC,mBAAmB,GAAG,MAAM,sBAAsB,SAAS;;;;0BAmFzD,WAAW,KAAG,OAAO,CAAC,WAAW,CAAC;CAiCO,CAAC"}
package/package.json CHANGED
@@ -107,5 +107,5 @@
107
107
  "type-check:go": "tsgo"
108
108
  },
109
109
  "type": "module",
110
- "version": "4.9.5"
110
+ "version": "4.9.6"
111
111
  }
@@ -27,6 +27,10 @@ function pathToString(path: DerivationPathArray | string): string {
27
27
  return typeof path === "string" ? path : derivationPathToString(path);
28
28
  }
29
29
 
30
+ function normalizeLedgerPath(path: string): string {
31
+ return path.replace(/^m\//, "").replace(/^\/+/, "");
32
+ }
33
+
30
34
  function pathToNumberArray(path: string): number[] {
31
35
  return path
32
36
  .replace(/^m\//, "")
@@ -39,6 +43,12 @@ function pathToNumberArray(path: string): number[] {
39
43
  });
40
44
  }
41
45
 
46
+ function hasBip32Derivation(tx: Transaction, inputIndex: number) {
47
+ const input = tx.getInput(inputIndex) as { bip32Derivation?: Array<unknown> };
48
+
49
+ return Boolean(input.bip32Derivation?.length);
50
+ }
51
+
42
52
  const BaseLedgerPsbtUTXO = ({ chain }: { chain: SupportedCoin }) => {
43
53
  return (derivationPathArray?: DerivationPathArray | string, injectedTransport?: Transport) => {
44
54
  // Per-call state — each BitcoinPsbtLedger/LitecoinPsbtLedger invocation has its own
@@ -65,9 +75,12 @@ const BaseLedgerPsbtUTXO = ({ chain }: { chain: SupportedCoin }) => {
65
75
  }
66
76
 
67
77
  // Single-address account: change == index == 0 by default.
68
- const derivationPath = derivationPathArray ? pathToString(derivationPathArray) : "84'/0'/0'/0/0";
69
- const accountPath = derivationPath.split("/").slice(0, 3).join("/");
70
- const leafSegments = derivationPath.split("/").slice(3);
78
+ const derivationPath = normalizeLedgerPath(
79
+ derivationPathArray ? pathToString(derivationPathArray) : "84'/0'/0'/0/0",
80
+ );
81
+ const pathSegments = derivationPath.split("/").filter(Boolean);
82
+ const accountPath = pathSegments.slice(0, 3).join("/");
83
+ const leafSegments = pathSegments.slice(3);
71
84
  const change = Number(leafSegments[0] ?? 0);
72
85
  const addressIndex = Number(leafSegments[1] ?? 0);
73
86
  const format = getWalletFormatFor(derivationPath);
@@ -118,17 +131,25 @@ const BaseLedgerPsbtUTXO = ({ chain }: { chain: SupportedCoin }) => {
118
131
  },
119
132
  getExtendedPublicKey: async (path = `m/${accountPath}`) => {
120
133
  const app = await getAppClient();
121
- return app.getExtendedPubkey(path);
134
+ return app.getExtendedPubkey(`m/${normalizeLedgerPath(path)}`);
122
135
  },
123
136
  signTransaction: async (tx: Transaction): Promise<Transaction> => {
124
137
  const { app, policy, fpr } = await buildPolicy();
125
138
  const fingerprintBE = Number.parseInt(fpr, 16) >>> 0;
126
139
  const pathNumbers = pathToNumberArray(derivationPath);
127
- const leafPubkey = await getLeafPubkey();
128
-
129
- // Single-address account: every input is owned by the same key + path.
130
- for (let i = 0; i < tx.inputsLength; i++) {
131
- tx.updateInput(i, { bip32Derivation: [[leafPubkey, { fingerprint: fingerprintBE, path: pathNumbers }]] });
140
+ const missingDerivationIndexes = Array.from({ length: tx.inputsLength }, (_, inputIndex) => inputIndex).filter(
141
+ (inputIndex) => !hasBip32Derivation(tx, inputIndex),
142
+ );
143
+
144
+ if (missingDerivationIndexes.length > 0) {
145
+ const leafPubkey = await getLeafPubkey();
146
+
147
+ // Fallback for PSBTs that do not include per-input HD key origins.
148
+ for (const inputIndex of missingDerivationIndexes) {
149
+ tx.updateInput(inputIndex, {
150
+ bip32Derivation: [[leafPubkey, { fingerprint: fingerprintBE, path: pathNumbers }]],
151
+ });
152
+ }
132
153
  }
133
154
 
134
155
  const psbtB64 = base64.encode(tx.toPSBT(0));
@@ -138,7 +159,6 @@ const BaseLedgerPsbtUTXO = ({ chain }: { chain: SupportedCoin }) => {
138
159
  tx.updateInput(idx, { partialSig: [[new Uint8Array(partial.pubkey), new Uint8Array(partial.signature)]] });
139
160
  }
140
161
 
141
- tx.finalize();
142
162
  return tx;
143
163
  },
144
164
  };
@@ -1,4 +0,0 @@
1
- import{c as w}from"./chunk-3yr76n9s.js";import{d as E}from"./chunk-n05bv2n5.js";import{base64 as x}from"@scure/base";import{HDKey as f}from"@scure/bip32";import{derivationPathToString as m,getWalletFormatFor as y,SwapKitError as K}from"@swapkit/helpers";function b(z){switch(z){case"bech32":return"wpkh(@0/**)";case"p2sh":return"sh(wpkh(@0/**))";case"legacy":return"pkh(@0/**)";default:return"wpkh(@0/**)"}}function P(z){return typeof z==="string"?z:m(z)}function g(z){return z.replace(/^m\//,"").split("/").filter(Boolean).map((M)=>{let Y=M.endsWith("'"),Q=Number.parseInt(Y?M.slice(0,-1):M,10);return Y?(Q|2147483648)>>>0:Q})}var B=({chain:z})=>{return(M,Y)=>{let Q,$;async function Z(){if(!Q){let q=Y??await w(),{AppClient:G}=await import("ledger-bitcoin");Q=new G(q)}return Q}async function X(){if(!$)$=await(await Z()).getMasterFingerprint();return $}let R=M?P(M):"84'/0'/0'/0/0",H=R.split("/").slice(0,3).join("/"),N=R.split("/").slice(3),O=Number(N[0]??0),U=Number(N[1]??0),k=y(R),S=b(k),_,j;async function D(){let q=await Z(),G=await X();if(!_)_=await q.getExtendedPubkey(`m/${H}`);let{DefaultWalletPolicy:J}=await import("ledger-bitcoin"),I=new J(S,`[${G}/${H}]${_}`);return{app:q,fpr:G,policy:I,xpub:_}}async function C(){if(!j){let{xpub:q}=await D(),J=f.fromExtendedKey(q).derive(`m/${O}/${U}`);if(!J.publicKey)throw new K("wallet_ledger_get_address_error",{message:`Cannot derive leaf pubkey for ${z}`});j=J.publicKey}return j}return{connect:async()=>{await Z()},getAddress:async()=>{let{app:q,policy:G}=await D(),J=await q.getWalletAddress(G,null,O,U,!1);if(!J)throw new K("wallet_ledger_get_address_error",{message:`Cannot get ${z} address from ledger derivation path: ${R}`});return J},getExtendedPublicKey:async(q=`m/${H}`)=>{return(await Z()).getExtendedPubkey(q)},signTransaction:async(q)=>{let{app:G,policy:J,fpr:I}=await D(),F=Number.parseInt(I,16)>>>0,L=g(R),T=await C();for(let V=0;V<q.inputsLength;V++)q.updateInput(V,{bip32Derivation:[[T,{fingerprint:F,path:L}]]});let v=x.encode(q.toPSBT(0)),A=await G.signPsbt(v,J,null);for(let[V,W]of A)q.updateInput(V,{partialSig:[[new Uint8Array(W.pubkey),new Uint8Array(W.signature)]]});return q.finalize(),q}}}},o=B({chain:"bitcoin"}),d=B({chain:"litecoin"});export{d as LitecoinPsbtLedger,o as BitcoinPsbtLedger};
2
-
3
- //# debugId=AE9B8E2F206F534564756E2164756E21
4
- //# sourceMappingURL=chunk-9jd3dhjv.js.map
@@ -1,10 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/ledger/clients/utxo-psbt.ts"],
4
- "sourcesContent": [
5
- "import type Transport from \"@ledgerhq/hw-transport\";\nimport { base64 } from \"@scure/base\";\nimport { HDKey } from \"@scure/bip32\";\nimport { type DerivationPathArray, derivationPathToString, getWalletFormatFor, SwapKitError } from \"@swapkit/helpers\";\nimport type { Transaction } from \"@swapkit/utxo-signer\";\n\nimport { getLedgerTransport } from \"../helpers/getLedgerTransport\";\n\ntype SupportedCoin = \"bitcoin\" | \"litecoin\";\n\ntype DefaultDescriptorTemplate = \"wpkh(@0/**)\" | \"tr(@0/**)\" | \"sh(wpkh(@0/**))\" | \"pkh(@0/**)\";\n\nfunction templateForFormat(format: ReturnType<typeof getWalletFormatFor>): DefaultDescriptorTemplate {\n switch (format) {\n case \"bech32\":\n return \"wpkh(@0/**)\";\n case \"p2sh\":\n return \"sh(wpkh(@0/**))\";\n case \"legacy\":\n return \"pkh(@0/**)\";\n default:\n return \"wpkh(@0/**)\";\n }\n}\n\nfunction pathToString(path: DerivationPathArray | string): string {\n return typeof path === \"string\" ? path : derivationPathToString(path);\n}\n\nfunction pathToNumberArray(path: string): number[] {\n return path\n .replace(/^m\\//, \"\")\n .split(\"/\")\n .filter(Boolean)\n .map((p) => {\n const hardened = p.endsWith(\"'\");\n const num = Number.parseInt(hardened ? p.slice(0, -1) : p, 10);\n return hardened ? (num | 0x80000000) >>> 0 : num;\n });\n}\n\nconst BaseLedgerPsbtUTXO = ({ chain }: { chain: SupportedCoin }) => {\n return (derivationPathArray?: DerivationPathArray | string, injectedTransport?: Transport) => {\n // Per-call state — each BitcoinPsbtLedger/LitecoinPsbtLedger invocation has its own\n // AppClient and master fingerprint so different consumers (e.g. concurrent MCP\n // sessions on different devices) cannot inherit each other's ledger bindings or xpub.\n let appClient: import(\"ledger-bitcoin\").AppClient | undefined;\n let masterFingerprint: string | undefined;\n\n async function getAppClient() {\n if (!appClient) {\n const transport = injectedTransport ?? (await getLedgerTransport());\n const { AppClient } = await import(\"ledger-bitcoin\");\n appClient = new AppClient(transport);\n }\n return appClient;\n }\n\n async function getFingerprint() {\n if (!masterFingerprint) {\n const app = await getAppClient();\n masterFingerprint = await app.getMasterFingerprint();\n }\n return masterFingerprint;\n }\n\n // Single-address account: change == index == 0 by default.\n const derivationPath = derivationPathArray ? pathToString(derivationPathArray) : \"84'/0'/0'/0/0\";\n const accountPath = derivationPath.split(\"/\").slice(0, 3).join(\"/\");\n const leafSegments = derivationPath.split(\"/\").slice(3);\n const change = Number(leafSegments[0] ?? 0);\n const addressIndex = Number(leafSegments[1] ?? 0);\n const format = getWalletFormatFor(derivationPath);\n const template = templateForFormat(format);\n\n let cachedAccountXpub: string | undefined;\n let cachedLeafPubkey: Uint8Array | undefined;\n\n async function buildPolicy() {\n const app = await getAppClient();\n const fpr = await getFingerprint();\n if (!cachedAccountXpub) {\n cachedAccountXpub = await app.getExtendedPubkey(`m/${accountPath}`);\n }\n const { DefaultWalletPolicy } = await import(\"ledger-bitcoin\");\n const policy = new DefaultWalletPolicy(template, `[${fpr}/${accountPath}]${cachedAccountXpub}`);\n return { app, fpr, policy, xpub: cachedAccountXpub };\n }\n\n async function getLeafPubkey() {\n if (!cachedLeafPubkey) {\n const { xpub } = await buildPolicy();\n const accountKey = HDKey.fromExtendedKey(xpub);\n const leaf = accountKey.derive(`m/${change}/${addressIndex}`);\n if (!leaf.publicKey) {\n throw new SwapKitError(\"wallet_ledger_get_address_error\", {\n message: `Cannot derive leaf pubkey for ${chain}`,\n });\n }\n cachedLeafPubkey = leaf.publicKey;\n }\n return cachedLeafPubkey;\n }\n\n return {\n connect: async () => {\n await getAppClient();\n },\n getAddress: async () => {\n const { app, policy } = await buildPolicy();\n const address = await app.getWalletAddress(policy, null, change, addressIndex, false);\n if (!address) {\n throw new SwapKitError(\"wallet_ledger_get_address_error\", {\n message: `Cannot get ${chain} address from ledger derivation path: ${derivationPath}`,\n });\n }\n return address;\n },\n getExtendedPublicKey: async (path = `m/${accountPath}`) => {\n const app = await getAppClient();\n return app.getExtendedPubkey(path);\n },\n signTransaction: async (tx: Transaction): Promise<Transaction> => {\n const { app, policy, fpr } = await buildPolicy();\n const fingerprintBE = Number.parseInt(fpr, 16) >>> 0;\n const pathNumbers = pathToNumberArray(derivationPath);\n const leafPubkey = await getLeafPubkey();\n\n // Single-address account: every input is owned by the same key + path.\n for (let i = 0; i < tx.inputsLength; i++) {\n tx.updateInput(i, { bip32Derivation: [[leafPubkey, { fingerprint: fingerprintBE, path: pathNumbers }]] });\n }\n\n const psbtB64 = base64.encode(tx.toPSBT(0));\n const sigs = await app.signPsbt(psbtB64, policy, null);\n\n for (const [idx, partial] of sigs) {\n tx.updateInput(idx, { partialSig: [[new Uint8Array(partial.pubkey), new Uint8Array(partial.signature)]] });\n }\n\n tx.finalize();\n return tx;\n },\n };\n };\n};\n\nexport const BitcoinPsbtLedger = BaseLedgerPsbtUTXO({ chain: \"bitcoin\" });\nexport const LitecoinPsbtLedger = BaseLedgerPsbtUTXO({ chain: \"litecoin\" });\n"
6
- ],
7
- "mappings": "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",
8
- "debugId": "AE9B8E2F206F534564756E2164756E21",
9
- "names": []
10
- }
@@ -1,4 +0,0 @@
1
- var w=require("@scure/base"),B=require("@scure/bip32"),M=require("@swapkit/helpers");function f(z){switch(z){case"bech32":return"wpkh(@0/**)";case"p2sh":return"sh(wpkh(@0/**))";case"legacy":return"pkh(@0/**)";default:return"wpkh(@0/**)"}}function m(z){return typeof z==="string"?z:M.derivationPathToString(z)}function y(z){return z.replace(/^m\//,"").split("/").filter(Boolean).map((Q)=>{let Z=Q.endsWith("'"),R=Number.parseInt(Z?Q.slice(0,-1):Q,10);return Z?(R|2147483648)>>>0:R})}var X=({chain:z})=>{return(Q,Z)=>{let R,H;async function _(){if(!R){let q=Z??await K(),{AppClient:G}=await import("ledger-bitcoin");R=new G(q)}return R}async function k(){if(!H)H=await(await _()).getMasterFingerprint();return H}let V=Q?m(Q):"84'/0'/0'/0/0",j=V.split("/").slice(0,3).join("/"),O=V.split("/").slice(3),U=Number(O[0]??0),W=Number(O[1]??0),S=M.getWalletFormatFor(V),C=f(S),$,D;async function I(){let q=await _(),G=await k();if(!$)$=await q.getExtendedPubkey(`m/${j}`);let{DefaultWalletPolicy:J}=await import("ledger-bitcoin"),N=new J(C,`[${G}/${j}]${$}`);return{app:q,fpr:G,policy:N,xpub:$}}async function F(){if(!D){let{xpub:q}=await I(),J=B.HDKey.fromExtendedKey(q).derive(`m/${U}/${W}`);if(!J.publicKey)throw new M.SwapKitError("wallet_ledger_get_address_error",{message:`Cannot derive leaf pubkey for ${z}`});D=J.publicKey}return D}return{connect:async()=>{await _()},getAddress:async()=>{let{app:q,policy:G}=await I(),J=await q.getWalletAddress(G,null,U,W,!1);if(!J)throw new M.SwapKitError("wallet_ledger_get_address_error",{message:`Cannot get ${z} address from ledger derivation path: ${V}`});return J},getExtendedPublicKey:async(q=`m/${j}`)=>{return(await _()).getExtendedPubkey(q)},signTransaction:async(q)=>{let{app:G,policy:J,fpr:N}=await I(),L=Number.parseInt(N,16)>>>0,T=y(V),v=await F();for(let Y=0;Y<q.inputsLength;Y++)q.updateInput(Y,{bip32Derivation:[[v,{fingerprint:L,path:T}]]});let A=w.base64.encode(q.toPSBT(0)),x=await G.signPsbt(A,J,null);for(let[Y,E]of x)q.updateInput(Y,{partialSig:[[new Uint8Array(E.pubkey),new Uint8Array(E.signature)]]});return q.finalize(),q}}}},P=X({chain:"bitcoin"}),g=X({chain:"litecoin"});
2
-
3
- //# debugId=EEF70E29FB42902064756E2164756E21
4
- //# sourceMappingURL=chunk-m08x6an5.js.map
@@ -1,10 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/ledger/clients/utxo-psbt.ts"],
4
- "sourcesContent": [
5
- "import type Transport from \"@ledgerhq/hw-transport\";\nimport { base64 } from \"@scure/base\";\nimport { HDKey } from \"@scure/bip32\";\nimport { type DerivationPathArray, derivationPathToString, getWalletFormatFor, SwapKitError } from \"@swapkit/helpers\";\nimport type { Transaction } from \"@swapkit/utxo-signer\";\n\nimport { getLedgerTransport } from \"../helpers/getLedgerTransport\";\n\ntype SupportedCoin = \"bitcoin\" | \"litecoin\";\n\ntype DefaultDescriptorTemplate = \"wpkh(@0/**)\" | \"tr(@0/**)\" | \"sh(wpkh(@0/**))\" | \"pkh(@0/**)\";\n\nfunction templateForFormat(format: ReturnType<typeof getWalletFormatFor>): DefaultDescriptorTemplate {\n switch (format) {\n case \"bech32\":\n return \"wpkh(@0/**)\";\n case \"p2sh\":\n return \"sh(wpkh(@0/**))\";\n case \"legacy\":\n return \"pkh(@0/**)\";\n default:\n return \"wpkh(@0/**)\";\n }\n}\n\nfunction pathToString(path: DerivationPathArray | string): string {\n return typeof path === \"string\" ? path : derivationPathToString(path);\n}\n\nfunction pathToNumberArray(path: string): number[] {\n return path\n .replace(/^m\\//, \"\")\n .split(\"/\")\n .filter(Boolean)\n .map((p) => {\n const hardened = p.endsWith(\"'\");\n const num = Number.parseInt(hardened ? p.slice(0, -1) : p, 10);\n return hardened ? (num | 0x80000000) >>> 0 : num;\n });\n}\n\nconst BaseLedgerPsbtUTXO = ({ chain }: { chain: SupportedCoin }) => {\n return (derivationPathArray?: DerivationPathArray | string, injectedTransport?: Transport) => {\n // Per-call state — each BitcoinPsbtLedger/LitecoinPsbtLedger invocation has its own\n // AppClient and master fingerprint so different consumers (e.g. concurrent MCP\n // sessions on different devices) cannot inherit each other's ledger bindings or xpub.\n let appClient: import(\"ledger-bitcoin\").AppClient | undefined;\n let masterFingerprint: string | undefined;\n\n async function getAppClient() {\n if (!appClient) {\n const transport = injectedTransport ?? (await getLedgerTransport());\n const { AppClient } = await import(\"ledger-bitcoin\");\n appClient = new AppClient(transport);\n }\n return appClient;\n }\n\n async function getFingerprint() {\n if (!masterFingerprint) {\n const app = await getAppClient();\n masterFingerprint = await app.getMasterFingerprint();\n }\n return masterFingerprint;\n }\n\n // Single-address account: change == index == 0 by default.\n const derivationPath = derivationPathArray ? pathToString(derivationPathArray) : \"84'/0'/0'/0/0\";\n const accountPath = derivationPath.split(\"/\").slice(0, 3).join(\"/\");\n const leafSegments = derivationPath.split(\"/\").slice(3);\n const change = Number(leafSegments[0] ?? 0);\n const addressIndex = Number(leafSegments[1] ?? 0);\n const format = getWalletFormatFor(derivationPath);\n const template = templateForFormat(format);\n\n let cachedAccountXpub: string | undefined;\n let cachedLeafPubkey: Uint8Array | undefined;\n\n async function buildPolicy() {\n const app = await getAppClient();\n const fpr = await getFingerprint();\n if (!cachedAccountXpub) {\n cachedAccountXpub = await app.getExtendedPubkey(`m/${accountPath}`);\n }\n const { DefaultWalletPolicy } = await import(\"ledger-bitcoin\");\n const policy = new DefaultWalletPolicy(template, `[${fpr}/${accountPath}]${cachedAccountXpub}`);\n return { app, fpr, policy, xpub: cachedAccountXpub };\n }\n\n async function getLeafPubkey() {\n if (!cachedLeafPubkey) {\n const { xpub } = await buildPolicy();\n const accountKey = HDKey.fromExtendedKey(xpub);\n const leaf = accountKey.derive(`m/${change}/${addressIndex}`);\n if (!leaf.publicKey) {\n throw new SwapKitError(\"wallet_ledger_get_address_error\", {\n message: `Cannot derive leaf pubkey for ${chain}`,\n });\n }\n cachedLeafPubkey = leaf.publicKey;\n }\n return cachedLeafPubkey;\n }\n\n return {\n connect: async () => {\n await getAppClient();\n },\n getAddress: async () => {\n const { app, policy } = await buildPolicy();\n const address = await app.getWalletAddress(policy, null, change, addressIndex, false);\n if (!address) {\n throw new SwapKitError(\"wallet_ledger_get_address_error\", {\n message: `Cannot get ${chain} address from ledger derivation path: ${derivationPath}`,\n });\n }\n return address;\n },\n getExtendedPublicKey: async (path = `m/${accountPath}`) => {\n const app = await getAppClient();\n return app.getExtendedPubkey(path);\n },\n signTransaction: async (tx: Transaction): Promise<Transaction> => {\n const { app, policy, fpr } = await buildPolicy();\n const fingerprintBE = Number.parseInt(fpr, 16) >>> 0;\n const pathNumbers = pathToNumberArray(derivationPath);\n const leafPubkey = await getLeafPubkey();\n\n // Single-address account: every input is owned by the same key + path.\n for (let i = 0; i < tx.inputsLength; i++) {\n tx.updateInput(i, { bip32Derivation: [[leafPubkey, { fingerprint: fingerprintBE, path: pathNumbers }]] });\n }\n\n const psbtB64 = base64.encode(tx.toPSBT(0));\n const sigs = await app.signPsbt(psbtB64, policy, null);\n\n for (const [idx, partial] of sigs) {\n tx.updateInput(idx, { partialSig: [[new Uint8Array(partial.pubkey), new Uint8Array(partial.signature)]] });\n }\n\n tx.finalize();\n return tx;\n },\n };\n };\n};\n\nexport const BitcoinPsbtLedger = BaseLedgerPsbtUTXO({ chain: \"bitcoin\" });\nexport const LitecoinPsbtLedger = BaseLedgerPsbtUTXO({ chain: \"litecoin\" });\n"
6
- ],
7
- "mappings": "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",
8
- "debugId": "EEF70E29FB42902064756E2164756E21",
9
- "names": []
10
- }