@swapkit/wallet-hardware 4.9.34 → 4.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{c as U}from"../chunk-3yr76n9s.js";import{d as W}from"../chunk-n05bv2n5.js";import{Chain as w,derivationPathToString as _0,FeeOption as NL,filterSupportedChains as aL,getRPCUrl as tL,NetworkDerivationPath as eL,SwapKitError as x,WalletOption as F0}from"@swapkit/helpers";import{addInputsAndOutputs as rL,assertDerivationIndex as XL,compileMemo as sL,createHDWalletHelpers as Ly,getNetworkForChain as TL,getUTXOAccountIndexFromPath as q0,getUTXOAccountPath as D0,getUTXOAddressPath as yy,getUtxoApi as _y}from"@swapkit/toolboxes/utxo";import{createWallet as Ry,getWalletSupportedChains as Gy}from"@swapkit/wallet-core";import{Chain as q,SwapKitError as QL,WalletOption as YL}from"@swapkit/helpers";var P=async({chain:L,ledgerClient:y})=>{if(!y)return"";switch(L){case q.Cosmos:case q.THORChain:return y.connect();case q.Ethereum:case q.BinanceSmartChain:case q.Avalanche:case q.Polygon:case q.Arbitrum:case q.Berachain:case q.Optimism:case q.Base:case q.Aurora:case q.Gnosis:case q.Monad:case q.XLayer:return y.getAddress();case q.Bitcoin:case q.BitcoinCash:case q.Dash:case q.Dogecoin:case q.Litecoin:case q.Zcash:{let _=y;await _.connect();let B=await _.getAddress();return L===q.BitcoinCash?B.replace("bitcoincash:",""):B}case q.Near:return await y.getAddress();case q.Ripple:return y.getAddress();case q.Tron:return y.getAddress();case q.Sui:return y.connect();default:throw new QL("wallet_chain_not_supported",{chain:L,wallet:YL.LEDGER})}};import{Chain as $,SwapKitError as nL,WalletOption as pL}from"@swapkit/helpers";import{derivationPathToString as HL,NetworkDerivationPath as CL,SwapKitError as P0}from"@swapkit/helpers";import{LedgerErrorCode as J0,NetworkDerivationPath as DL,SwapKitError as Z0}from"@swapkit/helpers";import{SwapKitError as A0}from"@swapkit/helpers";var c=85,N0=250;var l={GET_ADDR_SECP256K1:4,GET_VERSION:0,INS_PUBLIC_KEY_SECP256K1:1,SIGN_SECP256K1:2},r={ADD:1,INIT:0,LAST:2},X0={ONLY_RETRIEVE:0,SHOW_ADDRESS_IN_DEVICE:1},g={JSON:0},E={NoError:36864},z0={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 A(L){if(L in z0)return z0[L];return`Unknown Status Code: ${L}`}function FL(L){return typeof L==="object"&&L!==null&&!Array.isArray(L)&&!(L instanceof Date)}function K(L){if(L){if(FL(L)){if(Object.hasOwn(L,"statusCode"))return{error_message:A(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 T0(L){return L.send(85,l.GET_VERSION,0,0).then((y)=>{let _=y.slice(-2),B=_[0]*256+_[1],R=0;if(y.length>=9)R=(y[5]<<24)+(y[6]<<16)+(y[7]<<8)+(y[8]<<0);return{device_locked:y[4]===1,error_message:A(B),major:y[1],minor:y[2],patch:y[3],return_code:B,target_id:R.toString(16),test_mode:y[0]!==0}},K)}import{SwapKitError as s}from"@swapkit/helpers";function k0(L){if(L==null||L.length<3)throw new s("wallet_ledger_invalid_params",{reason:"Path too short"});if(L.length>10)throw new s("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 B=L[_]||0;if(_<3)B|=2147483648;y.writeInt32LE(B,1+_*4)}return y}function O0(L,y,_,B,R=g.JSON){return L.transport.send(c,l.SIGN_SECP256K1,y,R,B,[E.NoError,27012,27264]).then((G)=>{let N=G.slice(-2),X=N[0]*256+N[1],T=A(X);if(X===27264||X===27012)T=`${T} : ${G.slice(0,G.length-2).toString("ascii")}`;let J=null;if(G.length>2)J=G.slice(0,G.length-2);return{error_message:T,return_code:X,signature:J}},K)}function qL(L){if(L.length!==65)throw new s("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 K0(L,y){return L.transport.send(c,l.INS_PUBLIC_KEY_SECP256K1,0,0,y,[E.NoError]).then((_)=>{let B=_.slice(-2),R=B[0]*256+B[1],G=Buffer.from(_.slice(0,65));return{compressed_pk:qL(G),error_message:A(R),pk:G,return_code:R}},K)}function S0(L){if(!L||L.length!==5)throw new s("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 m0(L,y,_,B,R=g.JSON){let G=r.ADD;if(y===1)G=r.INIT;if(y===_)G=r.LAST;return O0(L,G,0,B,R)}function V0(L,y){return L.transport.send(c,l.GET_ADDR_SECP256K1,0,0,y,[E.NoError]).then((_)=>{let B=_.slice(-2),R=B[0]*256+B[1];return{compressed_pk:Buffer.from(_.slice(0,33)),error_message:A(R),pk:"OBSOLETE PROPERTY",return_code:R}},K)}class u{transport;versionResponse;constructor(L){if(!L)throw new A0("wallet_ledger_transport_not_defined");this.transport=L}static serializeHRP(L){if(L==null||L.length<3||L.length>83)throw new A0("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 T0(this.transport),this.versionResponse.return_code!==E.NoError)throw this.versionResponse;switch(this.versionResponse.major){case 1:return k0(L);case 2:return S0(L);default:return Buffer.alloc(0)}}async signGetChunks(L,y){let _=await this.serializePath(L),B=[];B.push(_);for(let R=0;R<y.length;R+=N0){let G=R+N0;if(R>y.length)G=y.length;B.push(y.slice(R,G))}return B}async getVersion(){try{return this.versionResponse=await T0(this.transport),this.versionResponse}catch(L){return K(L)}}appInfo(){return this.transport.send(176,1,0,0).then((L)=>{let y=L.readUInt16BE(L.length-2),_="",B="",R=0,G=0;if(L[0]!==1)return{error_message:"response format ID not recognized",return_code:36865};let N=L[1];_=L.slice(2,2+N).toString("ascii");let X=2+N,T=L[X];X+=1,B=L.slice(X,X+T).toString("ascii"),X+=T;let J=L[X];return X+=1,R=J,G=L[X],{appName:_,appVersion:B,error_message:A(y),flag_onboarded:(G&4)!==0,flag_pin_validated:(G&128)!==0,flag_recovery:(G&1)!==0,flag_signed_mcu_code:(G&2)!==0,flagLen:R,flagsValue:G,return_code:y}},K)}deviceInfo(){return this.transport.send(224,1,0,0,Buffer.from([]),[E.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 B=L.slice(0,4).toString("hex"),R=4,G=L[R];R+=1;let N=L.slice(R,R+G).toString();R+=G;let X=L[R];R+=1;let T=L.slice(R,R+X).toString("hex");R+=X;let J=L[R];R+=1;let O=L.slice(R,R+J);if(O[J-1]===0)O=L.slice(R,R+J-1);let Z=O.toString();return{error_message:A(_),flag:T,mcuVersion:Z,return_code:_,seVersion:N,targetId:B}},K)}async publicKey(L){try{let y=await this.serializePath(L);switch(this.versionResponse.major){case 1:return K0(this,y);case 2:{let _=Buffer.concat([u.serializeHRP("thor"),y]);return V0(this,_)}default:return{error_message:"App Version is not supported",return_code:25600}}}catch(y){return K(y)}}async getAddressAndPubKey(L,y,_=!1){try{let B=await this.serializePath(L),R=Buffer.concat([u.serializeHRP(y),B]),G=await this.transport.send(c,l.GET_ADDR_SECP256K1,_?X0.SHOW_ADDRESS_IN_DEVICE:X0.ONLY_RETRIEVE,0,R,[E.NoError]),N=Buffer.from(G.slice(0,33)),X=Buffer.from(G.slice(33,-2)).toString(),T=G.readUInt16BE(G.length-2);return{bech32_address:X,compressed_pk:N,error_message:A(T),return_code:T}}catch(B){return K(B)}}showAddressAndPubKey(L,y){return this.getAddressAndPubKey(L,y,!0)}signSendChunk(L,y,_,B=g.JSON){switch(this.versionResponse.major){case 1:return O0(this,L,y,_,B);case 2:return m0(this,L,y,_,B);default:return{error_message:"App Version is not supported",return_code:25600}}}async sign(L,y,_=g.JSON){let B=Buffer.from(y),R=[],G;try{R=await this.signGetChunks(L,B),G=await this.signSendChunk(1,R.length,R[0],_)}catch(X){K(X)}let N={error_message:G.error_message,return_code:G.return_code,signature:null};for(let X=1;X<R.length;X+=1)if(N=await this.signSendChunk(1+X,R.length,R[X],_),N.return_code!==E.NoError)break;return{error_message:N.error_message,return_code:N.return_code,signature:N.signature}}}class i{ledgerTimeout=50000;derivationPath=DL.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 U();switch(this.chain){case"thor":{this.ledgerApp=L||!this.ledgerApp?new u(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 Z0("wallet_ledger_connection_error",y)}};validateResponse=(L,y)=>{switch(L){case J0.NoError:return;case J0.LockedDevice:throw new Z0("wallet_ledger_device_locked",{message:`Ledger is locked: ${y}`});case J0.TC_NotFound:throw new Z0("wallet_ledger_device_not_found");default:break}}}class $0 extends i{pubKey=null;derivationPath;constructor(L=CL.GAIA,y){super(y);this.chain="cosmos",this.derivationPath=HL(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:B,signature:R}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new P0("wallet_ledger_pubkey_not_found");return this.validateResponse(_,B),[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:y,signature:R}]};signAmino=async(L,y)=>{await this.checkOrCreateTransportAndLedger(!0);let _=await this.getAccounts();if(_.findIndex((j)=>j.address===L)===-1)throw new P0("wallet_ledger_address_not_found",{address:L});let R=await import("@cosmjs/amino"),G=R.encodeSecp256k1Signature??R.default?.encodeSecp256k1Signature,N=R.serializeSignDoc??R.default?.serializeSignDoc,X=await import("@cosmjs/crypto"),T=X.Secp256k1Signature??X.default?.Secp256k1Signature,J=N(y),O=await this.ledgerApp.sign(this.derivationPath,J);this.validateResponse(O.return_code,O.error_message);let Z=T.fromDer(O.signature).toFixedLength();return{signature:G(_[0].pubkey,Z),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 f,derivationPathToString as UL,NetworkDerivationPath as fL,SwapKitError as o}from"@swapkit/helpers";import{AbstractSigner as zL}from"ethers";function kL(L){if(typeof L==="number")return L;let y=L.startsWith("0x")?L.slice(2):L;return Number.parseInt(y||"0",16)}class z extends zL{chainId=f.Ethereum;derivationPath="";ledgerApp=null;ledgerTimeout=50000;transport;injectedTransport;constructor({provider:L,derivationPath:y=fL.OP,chainId:_=f.Optimism,transport:B}){super(L);this.chainId=_||f.Ethereum,this.derivationPath=typeof y==="string"?y:UL(y),this.injectedTransport=B,Object.defineProperty(this,"provider",{enumerable:!0,value:L||null,writable:!1})}connect=(L)=>new z({chainId:this.chainId,derivationPath:this.derivationPath,provider:L,transport:this.transport??this.injectedTransport});checkOrCreateTransportAndLedger=async()=>{await this.createTransportAndLedger()};createTransportAndLedger=async()=>{if(this.ledgerApp)return;this.transport||=this.injectedTransport??await U();let L=(await import("@ledgerhq/hw-app-eth")).default;this.ledgerApp=new L(this.transport)};getAddress=async()=>{let L=await this.getAddressAndPubKey();if(!L)throw new o("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 o("wallet_ledger_signing_error");return _.r=`0x${_.r}`,_.s=`0x${_.s}`,y.from(_).serialized};sendTransaction=async(L)=>{if(!this.provider)throw new o("wallet_ledger_no_provider");let y=await this.signTransaction(L);return await this.provider.broadcastTransaction(y)};signTypedData=async(L,y,_,B)=>{let{buildEIP712DomainType:R}=await import("@swapkit/toolboxes/evm"),{Signature:G,TypedDataEncoder:N}=await import("ethers");await this.createTransportAndLedger();let{EIP712Domain:X,...T}=y,J=B??N.from(T).primaryType,O;try{O=await this.ledgerApp?.signEIP712Message(this.derivationPath,{domain:L,message:_,primaryType:J,types:{EIP712Domain:R(L),...T}})}catch(Z){let j=Z instanceof Error&&"statusCode"in Z;if(!j||j&&Z.statusCode===27013)throw Z;let Y=N.hashDomain(L).slice(2),C=N.from(T).hash(_).slice(2);O=await this.ledgerApp?.signEIP712HashedMessage(this.derivationPath,Y,C)}if(!O)throw new o("wallet_ledger_signing_error");return O.r=`0x${O.r}`,O.s=`0x${O.s}`,G.from(O).serialized};signTransaction=async(L)=>{let{Transaction:y}=await import("ethers");await this.createTransportAndLedger();let _=L.nonce??void 0,B=_===void 0?await this.provider?.getTransactionCount(L.from||await this.getAddress()):void 0,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:_!==void 0?Number(_.toString()):B,to:L.to?.toString(),type:L.type&&!Number.isNaN(L.type)?L.type:L.maxFeePerGas?2:0,value:L.value},G=y.from(R).unsignedSerialized.slice(2),{ledgerService:N}=await import("@ledgerhq/hw-app-eth"),X=await N.resolveTransaction(G,{},{erc20:!0,externalPlugins:!0}),T=await this.ledgerApp?.signTransaction(this.derivationPath,G,X);if(!T)throw new o("wallet_ledger_signing_error");let{r:J,s:O,v:Z}=T;return y.from({...R,signature:{r:`0x${J}`,s:`0x${O}`,v:kL(Z)}}).serialized}}var E0=(L)=>new z({...L,chainId:f.Arbitrum}),I0=(L)=>new z({...L,chainId:f.Aurora}),v0=(L)=>new z({...L,chainId:f.Avalanche}),b0=(L)=>new z({...L,chainId:f.Base}),l0=(L)=>new z({...L,chainId:f.Ethereum}),c0=(L)=>new z({...L,chainId:f.Gnosis}),g0=(L)=>new z({...L,chainId:f.Optimism}),h0=(L)=>new z({...L,chainId:f.Polygon}),x0=(L)=>new z({...L,chainId:f.BinanceSmartChain}),d0=(L)=>new z({...L,chainId:f.Monad}),u0=(L)=>new z({...L,chainId:f.XLayer}),i0=(L)=>new z({...L,chainId:f.Berachain});async function o0(L,y){let _=(await import("@ledgerhq/hw-app-near")).default,{Chain:B,NetworkDerivationPath:R,SwapKitError:G}=await import("@swapkit/helpers"),N=y??await U(),X=new _(N),T=(L||R[B.Near]).join("'/").concat("'"),{address:J,publicKey:O}=await X.getAddress(T);return{getAddress(){return Promise.resolve(J)},async getPublicKey(){let{PublicKey:j}=await import("@near-js/crypto");return j.fromString(`ed25519:${O}`)},signDelegateAction(j){return Promise.reject(new G("wallet_ledger_method_not_supported",{method:"signDelegateAction",wallet:"Ledger"}))},signNep413Message(j,Y,C,D,m){return Promise.reject(new G("wallet_ledger_method_not_supported",{method:"signNep413Message",wallet:"Ledger"}))},async signTransaction(j){let{Signature:Y,SignedTransaction:C}=await import("@near-js/transactions");try{let D=await X.signTransaction(j.encode(),T);if(!D)throw Error("Signature undefined");let m=new Y({data:D,keyType:0}),v=new C({signature:m,transaction:j});return[D,v]}catch(D){throw new G("wallet_ledger_signing_error",{error:D})}}}}import{Chain as KL,derivationPathToString as SL,NetworkDerivationPath as mL,SwapKitError as b}from"@swapkit/helpers";class n0{derivationPath;ledgerApp=null;address=null;publicKey=null;injectedTransport;constructor(L,y){this.derivationPath=typeof L==="string"?L:SL(L||mL[KL.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 U(),y=(await import("@ledgerhq/hw-app-sui")).default;this.ledgerApp=new y(L)}async connect(){if(await this.createTransportAndLedger(),!this.ledgerApp)throw new b("wallet_ledger_transport_error");let L=this.getLedgerPath(),y=await this.ledgerApp.getPublicKey(L);if(!y?.publicKey)throw new b("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 b("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 b("wallet_ledger_transport_error");if(!this.publicKey)throw new b("wallet_ledger_failed_to_get_address");try{let _=this.getLedgerPath(),B=new Uint8Array(3+y.length);B[0]=0,B[1]=0,B[2]=0,B.set(y,3);let R=await this.ledgerApp.signTransaction(_,B);if(!R?.signature)throw new b("wallet_ledger_signing_error");let G=this.publicKey.length===33?this.publicKey.slice(1):this.publicKey;if(G.length!==32)throw new b("wallet_ledger_signing_error",{error:"Invalid public key length"});let N=new Uint8Array(97);N[0]=0,N.set(R.signature,1),N.set(G,65);let X=Buffer.from(N).toString("base64");return{bytes:Buffer.from(y).toString("base64"),signature:X}}catch(_){throw new b("wallet_ledger_signing_error",{error:_})}}}var p0=(L,y)=>new n0(L,y);import{base64 as j0}from"@scure/base";import{NetworkDerivationPath as AL,SwapKitError as W0}from"@swapkit/helpers";import{base64 as VL}from"@scure/base";import{SwapKitError as I}from"@swapkit/helpers";var L0=(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 B=L[y+5];if(4+y+2+B!==L.length)throw new I("wallet_ledger_invalid_signature",{reason:"TLV byte lengths do not match message length"});let R=L.slice(y+6,L.length);if(R.length===33&&R[0]===0)R=R.slice(1,33);else if(R.length===33)throw new I("wallet_ledger_invalid_signature",{reason:"s too long"});while(R.length<32)R.unshift(0);if(_.length!==32||R.length!==32)throw new I("wallet_ledger_invalid_signature",{reason:"must be 32 bytes each"});return VL.encode(Buffer.concat([_,R]))};function PL(L){if(typeof L==="string")return L;let y=L.chain?.toUpperCase(),_=(L.symbol||L.ticker||"").toUpperCase();if(!(y&&_))return _||y||"";if(L.synth)return`${y}/${_}`;return`${y}.${_}`}function EL(L){return{...L,msgs:L.msgs.map((y)=>{if(!y.type.includes("MsgDeposit"))return y;let _=y.value.coins;if(!Array.isArray(_))return y;return{...y,value:{...y.value,coins:_.map((B)=>({...B,asset:PL(B.asset)}))}}})}}class M0 extends i{pubKey=null;derivationPath;constructor(L=AL.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=j0.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:B,signature:R}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new W0("wallet_ledger_pubkey_not_found");return this.validateResponse(_,B),[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:y,signature:L0(R)}]};signAmino=async(L,y)=>{await this.checkOrCreateTransportAndLedger(!0);let _=(await this.getAccounts()).find((O)=>O.address===L);if(!_)throw new W0("wallet_ledger_address_not_found",{address:L});let B=await import("@cosmjs/amino"),R=B.encodeSecp256k1Signature??B.default?.encodeSecp256k1Signature,G=B.serializeSignDoc??B.default?.serializeSignDoc,N=EL(y),{return_code:X,error_message:T,signature:J}=await this.ledgerApp.sign(this.derivationPath,G(N));return this.validateResponse(X,T),{signature:R(_.pubkey,j0.decode(L0(J))),signed:y}};getAccounts=async()=>{await this.checkOrCreateTransportAndLedger(!0);let{bech32_address:L,compressed_pk:y}=await this.getAddressAndPubKey();return this.pubKey=j0.encode(y),[{address:L,algo:"secp256k1",pubkey:y}]};sign=async(L)=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:y,error_message:_,signature:B}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new W0("wallet_ledger_pubkey_not_found");return this.validateResponse(y,_),L0(B)}}import{derivationPathToString as IL,NetworkDerivationPath as vL,SwapKitError as n}from"@swapkit/helpers";class a0{derivationPath;ledgerApp=null;ledgerTimeout=50000;injectedTransport;constructor(L,y){this.derivationPath=typeof L==="string"?L:IL(L||vL.TRON),this.injectedTransport=y}checkOrCreateTransportAndLedger=async()=>{if(this.ledgerApp)return;await this.createTransportAndLedger()};createTransportAndLedger=async()=>{let L=this.injectedTransport??await U(),y=(await import("@ledgerhq/hw-app-trx")).default;this.ledgerApp=new y(L)};getAddress=async()=>{let L=await this.getAddressAndPubKey();if(!L)throw new n("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 n("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 n("wallet_ledger_transport_error");try{let y=await this.ledgerApp.signTransaction(this.derivationPath,L.raw_data_hex,[]);if(!y)throw new n("wallet_ledger_signing_error");return{...L,signature:[y]}}catch(y){throw new n("wallet_ledger_signing_error",{error:y})}}}var t0=(L,y)=>new a0(L,y);import{hex as y0}from"@scure/base";import{derivationPathToString as bL,getWalletFormatFor as Y0,SwapKitError as Q0}from"@swapkit/helpers";var r0=["bitcoin-cash","dash","dogecoin","zcash"],e0=({tx:L,inputUtxos:y,btcApp:_,derivationPath:B,chain:R},G)=>{let N=y.map((Y)=>{return[_.splitTransaction(Y.txHex||"",!r0.includes(R),R==="zcash"),Y.index,void 0,void 0]}),X=y0.encode(L.unsignedTx),T=_.splitTransaction(X,!0),J=_.serializeTransactionOutputs(T).toString("hex"),O=Y0(B),Z=O!=="legacy",j={additionals:O==="bech32"?["bech32"]:[],associatedKeysets:N.map(()=>B),inputs:N,outputScriptHex:J,segwit:Z,useTrustedInputForSegwit:Z};return _.createPaymentTransaction({...j,...G})},lL=({tx:L,inputUtxos:y,btcApp:_,derivationPaths:B,chain:R},G)=>{if(B.length!==y.length)throw new Q0("wallet_ledger_invalid_params",{message:`Derivation paths count (${B.length}) must match inputs count (${y.length})`});let N=y.map((Y)=>{return[_.splitTransaction(Y.txHex||"",!r0.includes(R),R==="zcash"),Y.index,void 0,void 0]}),X=y0.encode(L.unsignedTx),T=_.splitTransaction(X,!0),J=_.serializeTransactionOutputs(T).toString("hex"),O=Y0(B[0]??""),Z=O!=="legacy",j={additionals:O==="bech32"?["bech32"]:[],associatedKeysets:B,inputs:N,outputScriptHex:J,segwit:Z,useTrustedInputForSegwit:Z};return _.createPaymentTransaction({...j,...G})},h=({chain:L,additionalSignParams:y})=>{return(_,B)=>{let R,G=null;async function N(){G||=B??await U();let Z=(await import("@ledgerhq/hw-app-btc")).default;return R||=new Z({currency:L,transport:G}),R}async function X(){return R||await N()}async function T(){if(!B)await G?.close?.();R=void 0,G=null}let J=typeof _==="string"?_:bL(_),O=Y0(J);return{connect:async()=>{await X()},disconnect:T,getAddress:async()=>{let{toCashAddress:Z}=await import("@swapkit/toolboxes/utxo"),j=await X(),{bitcoinAddress:Y}=await j.getWalletPublicKey(J,{format:O});if(!Y)throw new Q0("wallet_ledger_get_address_error",{message:`Cannot get ${L} address from ledger derivation path: ${J}`});return L==="bitcoin-cash"&&O==="legacy"?Z(Y).replace(/(bchtest:|bitcoincash:)/,""):Y},getExtendedPublicKey:async(Z="84'/0'/0'",j=76067358)=>{return(await X()).getWalletXpub({path:Z,xpubVersion:j})},signPCZT:async(Z)=>{if(L!=="zcash")throw new Q0("wallet_ledger_chain_not_supported",{message:"PCZT signing is only supported for Zcash"});let j=await X(),{ZcashTransaction:Y,Script:C}=await import("@swapkit/utxo-signer"),D=Z.getGlobal(),m=new Y({consensusBranchId:D.consensusBranchId,expiryHeight:D.expiryHeight,lockTime:D.lockTime,version:D.txVersion,versionGroupId:D.versionGroupId}),v=[];for(let Q=0;Q<Z.inputsLength;Q++){let M=Z.getInput(Q);m.addInput({index:M.index,script:new Uint8Array,sequence:M.sequence??4294967295,txid:M.txid,value:M.value}),v.push({hash:y0.encode(new Uint8Array([...M.txid].reverse())),index:M.index,txHex:cL(M,D),value:Number(M.value),witnessUtxo:{script:M.scriptPubkey,value:Number(M.value)}})}for(let Q=0;Q<Z.outputsLength;Q++){let M=Z.getOutput(Q);m.addOutput({amount:M.value,script:M.scriptPubkey})}let d=await e0({btcApp:j,chain:L,derivationPath:J,inputUtxos:v,tx:m},{...y,expiryHeight:(()=>{let Q=Buffer.alloc(4);return Q.writeUInt32LE(D.expiryHeight),Q})(),lockTime:D.lockTime}),F=Y.fromHex(d,{allowUnknownOutputs:!0}),H=Z.clone();for(let Q=0;Q<F.inputsLength;Q++){let M=F.getInput(Q);if(M.script&&M.script.length>0){let k=C.decode(M.script);if(k.length>=2)H.addSignature(Q,k[1],k[0])}}return H},signTransaction:async(Z,j)=>{let Y=await X();return e0({btcApp:Y,chain:L,derivationPath:J,inputUtxos:j,tx:Z},y)},signTransactionWithMultiplePaths:async(Z,j,Y)=>{let C=await X();return lL({btcApp:C,chain:L,derivationPaths:Y,inputUtxos:j,tx:Z},y)}}}};function cL(L,y){let _=[],B=(y.txVersion|2147483648)>>>0;_.push(B&255,B>>8&255,B>>16&255,B>>24&255);let R=y.versionGroupId;_.push(R&255,R>>8&255,R>>16&255,R>>24&255),_.push(0);let G=L.index+1;if(G<253)_.push(G);else _.push(253,G&255,G>>8&255);for(let T=0;T<L.index;T++)_.push(0,0,0,0,0,0,0,0),_.push(0);let N=L.value;_.push(Number(N&0xffn),Number(N>>8n&0xffn),Number(N>>16n&0xffn),Number(N>>24n&0xffn),Number(N>>32n&0xffn),Number(N>>40n&0xffn),Number(N>>48n&0xffn),Number(N>>56n&0xffn));let X=L.scriptPubkey;if(X.length<253)_.push(X.length);else _.push(253,X.length&255,X.length>>8&255);for(let T of X)_.push(T);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),y0.encode(new Uint8Array(_))}var s0=h({chain:"bitcoin"}),LL=h({chain:"litecoin"}),yL=h({additionalSignParams:{additionals:["abc"],segwit:!1,sigHashType:65},chain:"bitcoin-cash"}),_L=h({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dogecoin"}),RL=h({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dash"}),GL=h({additionalSignParams:{additionals:["zcash","sapling"],expiryHeight:(()=>{let L=Buffer.alloc(4);return L.writeUInt32LE(0),L})(),lockTime:0,segwit:!1,useTrustedInputForSegwit:!1},chain:"zcash"});import gL from"@ledgerhq/hw-app-xrp";import{Chain as hL,derivationPathToString as xL,NetworkDerivationPath as dL}from"@swapkit/helpers";import{encode as BL}from"ripple-binary-codec";var uL=2147483648;function iL(L){let y={};for(let _ in L)if(L[_]!==null&&L[_]!==void 0)y[_]=L[_];return y}function oL(L){return new gL(L)}var wL=async(L,y)=>{let _=xL(L||dL[hL.Ripple]),B=y??await U(),R=oL(B),{address:G,publicKey:N}=await R.getAddress(_);async function X(T){let{hashes:J}=await import("xrpl"),Z={...iL(T),Flags:T.Flags||uL,SigningPubKey:N.toUpperCase()},j=BL(Z),Y=await R.signTransaction(_,j),C=BL({...Z,TxnSignature:Y});return{hash:J.hashSignedTx(C),tx_blob:C}}return{getAddress:()=>G,signTransaction:X}};var S=async({chain:L,derivationPath:y,transport:_})=>{let{match:B}=await import("ts-pattern");return B(L).returnType().with($.THORChain,()=>Promise.resolve(new M0(y,_))).with($.Cosmos,()=>Promise.resolve(new $0(y,_))).with($.Bitcoin,()=>Promise.resolve(s0(y,_))).with($.BitcoinCash,()=>Promise.resolve(yL(y,_))).with($.Dash,()=>Promise.resolve(RL(y,_))).with($.Dogecoin,()=>Promise.resolve(_L(y,_))).with($.Litecoin,()=>Promise.resolve(LL(y,_))).with($.Zcash,()=>Promise.resolve(GL(y,_))).with($.Ripple,()=>Promise.resolve(wL(y,_))).with($.Tron,()=>Promise.resolve(t0(y,_))).with($.Sui,()=>Promise.resolve(p0(y,_))).with($.Near,()=>{return Promise.resolve(o0(y,_))}).with($.Arbitrum,$.Aurora,$.Avalanche,$.Berachain,$.BinanceSmartChain,$.Ethereum,$.Gnosis,$.Monad,$.Optimism,$.Polygon,$.Base,$.XLayer,async()=>{let{getProvider:R}=await import("@swapkit/toolboxes/evm"),G={derivationPath:y,provider:await R(L),transport:_};return B(L).with($.BinanceSmartChain,()=>x0(G)).with($.Avalanche,()=>v0(G)).with($.Arbitrum,()=>E0(G)).with($.Berachain,()=>i0(G)).with($.Optimism,()=>g0(G)).with($.Polygon,()=>h0(G)).with($.Base,()=>b0(G)).with($.Aurora,()=>I0(G)).with($.Gnosis,()=>c0(G)).with($.Monad,()=>d0(G)).with($.XLayer,()=>u0(G)).otherwise(()=>l0(G))}).otherwise(()=>{throw new nL("wallet_chain_not_supported",{chain:L,wallet:pL.LEDGER})})};var By=Ry({connect:({addChain:L,supportedChains:y,walletType:_})=>async function(R,G,{address:N,transport:X}={}){let[T]=aL({chains:R,supportedChains:y,walletType:_});if(!T)return!1;let J=G??eL[T],O=await Xy({address:N,chain:T,derivationPath:J,transport:X});return L({...O,chain:T,walletType:F0.LEDGER}),!0},directSigningSupport:{[w.Arbitrum]:!0,[w.Aurora]:!0,[w.Avalanche]:!0,[w.Base]:!0,[w.Berachain]:!0,[w.BinanceSmartChain]:!0,[w.Ethereum]:!0,[w.Gnosis]:!0,[w.Monad]:!0,[w.Bitcoin]:!0,[w.BitcoinCash]:!0,[w.Cosmos]:!0,[w.Dash]:!0,[w.Dogecoin]:!0,[w.Litecoin]:!0,[w.Near]:!0,[w.Optimism]:!0,[w.Polygon]:!0,[w.Ripple]:!0,[w.Sui]:!0,[w.THORChain]:!0,[w.Tron]:!0,[w.XLayer]:!0},getExtendedPublicKey:Ny,name:"connectLedger",supportedChains:[w.Arbitrum,w.Aurora,w.Avalanche,w.Base,w.Berachain,w.BinanceSmartChain,w.Bitcoin,w.BitcoinCash,w.Cosmos,w.Dash,w.Dogecoin,w.Ethereum,w.Gnosis,w.Litecoin,w.Monad,w.Near,w.Optimism,w.Polygon,w.Ripple,w.Sui,w.THORChain,w.XLayer,w.Tron,w.Zcash],walletType:F0.LEDGER}),F_=Gy(By);function wy(L,y="t"){if(!L?.includes("=:"))return L;let _=L.includes(`:${y}:`)?L.split(`:${y}:`)[0]:L;return _?.substring(0,_.lastIndexOf(":"))}async function Ny(L,y,{accountIndex:_}={}){if(![w.BitcoinCash,w.Bitcoin,w.Dash,w.Dogecoin,w.Litecoin,w.Zcash].includes(L))throw new x("wallet_chain_not_supported",{chain:L,wallet:F0.LEDGER});let B=L,R=await S({chain:B,derivationPath:y});if(!R.getExtendedPublicKey)return;let G=D0({accountIndex:_,chain:B,derivationPath:y}),N=_0(G),X=L===w.Bitcoin||L===w.Litecoin?N:N.replace(/^m\//,""),T=TL(B).bip32.public;try{let J=await R.getExtendedPublicKey(X,T);return{accountIndex:q0(G),path:N,xpub:J}}finally{await R.disconnect?.()}}async function Xy({address:L,chain:y,derivationPath:_,transport:B}){switch(y){case w.BitcoinCash:case w.Bitcoin:case w.Dash:case w.Dogecoin:case w.Litecoin:case w.Zcash:{let C=function(F={}){return Y(F)},{getUtxoToolbox:R}=await import("@swapkit/toolboxes/utxo"),G=y,N=await S({chain:y,derivationPath:_,transport:B}),X=L??await P({chain:y,ledgerClient:N}),T,J;if(y===w.Bitcoin){let{BitcoinPsbtLedger:F}=await import("../chunk-gwx23jdp.js"),H=F(_,B);T={getAddress:H.getAddress,signTransaction:H.signTransaction}}else if(y===w.BitcoinCash||y===w.Dogecoin||y===w.Dash||y===w.Litecoin){let{createLegacyPsbtSigner:F,signLegacyPsbtTransaction:H}=await import("../chunk-bwf31zxr.js");T=F({address:X,chain:G,legacyClient:N}),J=async(Q)=>{let M=await H({chain:G,legacyClient:N,tx:Q});return O.broadcastTx(M)}}let O=T?await R(G,{signer:T}):R(G),Z=J??O.signAndBroadcastTransaction,j=async(F)=>{let H=F.feeRate||(await O.getFeeRates())[NL.Average],Q=[w.Bitcoin].includes(y)?F.memo:wy(F.memo),{tx:M,inputs:k}=await O.createTransaction({...F,feeRate:H,fetchTxHex:!0,memo:Q,sender:X}),V=await N.signTransaction(M,k);return await O.broadcastTx(V)};async function Y({accountIndex:F}={}){if(!N.getExtendedPublicKey)return;let H=D0({accountIndex:F,chain:G,derivationPath:_}),Q=_0(H),M=y===w.Bitcoin||y===w.Litecoin?Q:Q.replace(/^m\//,""),k=TL(G).bip32.public,V=await N.getExtendedPublicKey(M,k);return{accountIndex:q0(H),path:Q,xpub:V}}async function D({accountIndex:F,index:H,change:Q=!1}){try{let M=yy({accountIndex:F,chain:G,change:Q,derivationPath:_,index:H}),k=await S({chain:G,derivationPath:M,transport:B}),V=await P({chain:G,ledgerClient:k});return{accountIndex:q0(M),address:V,change:Q,index:H,path:_0(M),pubkey:""}}catch{return}}async function m({accountIndex:F,count:H,startIndex:Q=0,change:M=!1}){return XL("count",H),XL("startIndex",Q),(await Promise.all(Array.from({length:H},(V,p)=>D({accountIndex:F,change:M,index:Q+p})))).filter((V)=>!!V)}let v=Ly({chain:G,deriveAddress:D,getBalance:O.getBalance,getUtxos:(F)=>_y(G).getUtxos({address:F,fetchTxHex:!0})});async function d({utxos:F,recipient:H,assetValue:Q,memo:M,feeRate:k,feeOptionKey:V,changeAddress:p}){if(!F.length)throw new x("wallet_ledger_invalid_params",{message:"No UTXOs provided for multi-address transfer"});let OL=k||(await O.getFeeRates())[V||NL.Fast],R0=M?sL(M):null,H0=[{address:H,value:Q.getBaseValue("number")}];if(R0)H0.push({script:R0,value:0});let JL=F.map(({hash:t,index:e,value:G0,txHex:B0,witnessUtxo:w0})=>({hash:t,index:e,txHex:B0,value:G0,witnessUtxo:w0})),{inputs:a,outputs:C0}=O.accumulative({chain:G,feeRate:OL,inputs:JL,outputs:H0});if(!(a&&C0))throw new x("wallet_ledger_connection_error",{message:"Insufficient balance for multi-address transfer"});let{Transaction:ZL}=await import("@swapkit/utxo-signer"),U0=new ZL({allowLegacyWitnessUtxo:!0,version:1}),$L=p||F[0]?.address||H;rL({chain:G,compiledMemo:R0,inputs:a,outputs:C0,sender:$L,tx:U0});let jL=D0({chain:G,derivationPath:_}),WL=a.map((t)=>{let e=F.find((f0)=>f0.hash===t.hash&&f0.index===t.index),G0=e?.derivationIndex??0,B0=e?.isChange??!1,w0=[...jL,Number(B0),G0];return _0(w0)});if(!N.signTransactionWithMultiplePaths)throw new x("wallet_ledger_method_not_supported",{method:"signTransactionWithMultiplePaths"});let ML=await N.signTransactionWithMultiplePaths(U0,a,WL);return O.broadcastTx(ML)}return{...O,...v,address:X,deriveAddressAtIndex:D,deriveAddresses:m,getExtendedPublicKey:C,getExtendedPublicKeyInfo:Y,signAndBroadcastTransaction:Z,transfer:j,transferFromMultipleAddresses:d}}case w.Ethereum:case w.Avalanche:case w.Arbitrum:case w.Berachain:case w.Optimism:case w.Polygon:case w.BinanceSmartChain:case w.Base:case w.Aurora:case w.Gnosis:case w.Monad:case w.XLayer:{let{getEvmToolboxAsync:R}=await import("@swapkit/toolboxes/evm"),G=await S({chain:y,derivationPath:_,transport:B}),N=await P({chain:y,ledgerClient:G});return{...await R(y,{signer:G}),address:N}}case w.Cosmos:{let{createSigningStargateClient:R,getDefaultChainFee:G,getMsgSendDenom:N,getCosmosToolbox:X}=await import("@swapkit/toolboxes/cosmos"),T=await S({chain:y,derivationPath:_,transport:B}),J=await P({chain:y,ledgerClient:T});return{...await X(w.Cosmos,{signer:T}),address:J,transfer:async({assetValue:j,recipient:Y,memo:C})=>{if(!j)throw new x("wallet_ledger_invalid_asset");let D={amount:[{amount:j.getBaseValue("string"),denom:N(`u${j.symbol}`).toLowerCase()}],fromAddress:J,toAddress:Y},m=await tL(y),v=await R(m,T,"0.007uatom"),{transactionHash:d}=await v.signAndBroadcast(J,[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:D}],G(w.Cosmos),C);return d}}}case w.THORChain:{let R=await S({chain:y,derivationPath:_,transport:B}),{getCosmosToolbox:G}=await import("@swapkit/toolboxes/cosmos"),N=G(y,{signer:R}),X=await P({chain:y,ledgerClient:R}),{sign:T}=R;return{...N,address:X,signMessage:T}}case w.Near:{let{getNearToolbox:R}=await import("@swapkit/toolboxes/near"),G=await S({chain:y,derivationPath:_,transport:B}),N=await G.getAddress();return{...R({signer:G}),address:N}}case w.Ripple:{let{getRippleToolbox:R}=await import("@swapkit/toolboxes/ripple"),G=await S({chain:y,derivationPath:_,transport:B}),N=G.getAddress();return{...R({signer:G}),address:N}}case w.Tron:{let{getTronToolbox:R}=await import("@swapkit/toolboxes/tron"),G=await S({chain:y,derivationPath:_,transport:B}),N=await P({chain:y,ledgerClient:G});return{...R({signer:G}),address:N}}case w.Sui:{let{getSuiToolbox:R}=await import("@swapkit/toolboxes/sui"),G=await S({chain:y,derivationPath:_,transport:B}),N=await P({chain:y,ledgerClient:G});return{...R({signer:G}),address:N}}default:throw new x("wallet_ledger_chain_not_supported",{chain:y})}}export{By as ledgerWallet,Ny as getLedgerExtendedPublicKey,F_ as LEDGER_SUPPORTED_CHAINS};
1
+ import{c as f}from"../chunk-3yr76n9s.js";import{d as W}from"../chunk-n05bv2n5.js";import{Chain as w,derivationPathToString as _0,FeeOption as TL,filterSupportedChains as tL,getRPCUrl as eL,NetworkDerivationPath as rL,SwapKitError as x,WalletOption as M0}from"@swapkit/helpers";import{addInputsAndOutputs as sL,assertDerivationIndex as XL,compileMemo as Ly,createHDWalletHelpers as yy,getNetworkForChain as OL,getUTXOAccountIndexFromPath as q0,getUTXOAccountPath as D0,getUTXOAddressPath as _y,getUtxoApi as Ry}from"@swapkit/toolboxes/utxo";import{createWallet as Gy,getWalletSupportedChains as By}from"@swapkit/wallet-core";import{Chain as q,SwapKitError as FL,WalletOption as ML}from"@swapkit/helpers";var P=async({chain:L,ledgerClient:y})=>{if(!y)return"";switch(L){case q.Cosmos:case q.THORChain:return y.connect();case q.Ethereum:case q.BinanceSmartChain:case q.Avalanche:case q.Polygon:case q.Arbitrum:case q.Arc:case q.Berachain:case q.Optimism:case q.Base:case q.Aurora:case q.Gnosis:case q.Monad:case q.XLayer:return y.getAddress();case q.Bitcoin:case q.BitcoinCash:case q.Dash:case q.Dogecoin:case q.Litecoin:case q.Zcash:{let _=y;await _.connect();let B=await _.getAddress();return L===q.BitcoinCash?B.replace("bitcoincash:",""):B}case q.Near:return await y.getAddress();case q.Ripple:return y.getAddress();case q.Tron:return y.getAddress();case q.Sui:return y.connect();default:throw new FL("wallet_chain_not_supported",{chain:L,wallet:ML.LEDGER})}};import{Chain as $,SwapKitError as pL,WalletOption as aL}from"@swapkit/helpers";import{derivationPathToString as CL,NetworkDerivationPath as UL,SwapKitError as P0}from"@swapkit/helpers";import{LedgerErrorCode as J0,NetworkDerivationPath as HL,SwapKitError as Z0}from"@swapkit/helpers";import{SwapKitError as V0}from"@swapkit/helpers";var c=85,N0=250;var l={GET_ADDR_SECP256K1:4,GET_VERSION:0,INS_PUBLIC_KEY_SECP256K1:1,SIGN_SECP256K1:2},r={ADD:1,INIT:0,LAST:2},T0={ONLY_RETRIEVE:0,SHOW_ADDRESS_IN_DEVICE:1},g={JSON:0},E={NoError:36864},z0={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 z0)return z0[L];return`Unknown Status Code: ${L}`}function qL(L){return typeof L==="object"&&L!==null&&!Array.isArray(L)&&!(L instanceof Date)}function K(L){if(L){if(qL(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 X0(L){return L.send(85,l.GET_VERSION,0,0).then((y)=>{let _=y.slice(-2),B=_[0]*256+_[1],R=0;if(y.length>=9)R=(y[5]<<24)+(y[6]<<16)+(y[7]<<8)+(y[8]<<0);return{device_locked:y[4]===1,error_message:V(B),major:y[1],minor:y[2],patch:y[3],return_code:B,target_id:R.toString(16),test_mode:y[0]!==0}},K)}import{SwapKitError as s}from"@swapkit/helpers";function k0(L){if(L==null||L.length<3)throw new s("wallet_ledger_invalid_params",{reason:"Path too short"});if(L.length>10)throw new s("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 B=L[_]||0;if(_<3)B|=2147483648;y.writeInt32LE(B,1+_*4)}return y}function O0(L,y,_,B,R=g.JSON){return L.transport.send(c,l.SIGN_SECP256K1,y,R,B,[E.NoError,27012,27264]).then((G)=>{let N=G.slice(-2),T=N[0]*256+N[1],X=V(T);if(T===27264||T===27012)X=`${X} : ${G.slice(0,G.length-2).toString("ascii")}`;let J=null;if(G.length>2)J=G.slice(0,G.length-2);return{error_message:X,return_code:T,signature:J}},K)}function DL(L){if(L.length!==65)throw new s("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 K0(L,y){return L.transport.send(c,l.INS_PUBLIC_KEY_SECP256K1,0,0,y,[E.NoError]).then((_)=>{let B=_.slice(-2),R=B[0]*256+B[1],G=Buffer.from(_.slice(0,65));return{compressed_pk:DL(G),error_message:V(R),pk:G,return_code:R}},K)}function S0(L){if(!L||L.length!==5)throw new s("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 A0(L,y,_,B,R=g.JSON){let G=r.ADD;if(y===1)G=r.INIT;if(y===_)G=r.LAST;return O0(L,G,0,B,R)}function m0(L,y){return L.transport.send(c,l.GET_ADDR_SECP256K1,0,0,y,[E.NoError]).then((_)=>{let B=_.slice(-2),R=B[0]*256+B[1];return{compressed_pk:Buffer.from(_.slice(0,33)),error_message:V(R),pk:"OBSOLETE PROPERTY",return_code:R}},K)}class u{transport;versionResponse;constructor(L){if(!L)throw new V0("wallet_ledger_transport_not_defined");this.transport=L}static serializeHRP(L){if(L==null||L.length<3||L.length>83)throw new V0("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 X0(this.transport),this.versionResponse.return_code!==E.NoError)throw this.versionResponse;switch(this.versionResponse.major){case 1:return k0(L);case 2:return S0(L);default:return Buffer.alloc(0)}}async signGetChunks(L,y){let _=await this.serializePath(L),B=[];B.push(_);for(let R=0;R<y.length;R+=N0){let G=R+N0;if(R>y.length)G=y.length;B.push(y.slice(R,G))}return B}async getVersion(){try{return this.versionResponse=await X0(this.transport),this.versionResponse}catch(L){return K(L)}}appInfo(){return this.transport.send(176,1,0,0).then((L)=>{let y=L.readUInt16BE(L.length-2),_="",B="",R=0,G=0;if(L[0]!==1)return{error_message:"response format ID not recognized",return_code:36865};let N=L[1];_=L.slice(2,2+N).toString("ascii");let T=2+N,X=L[T];T+=1,B=L.slice(T,T+X).toString("ascii"),T+=X;let J=L[T];return T+=1,R=J,G=L[T],{appName:_,appVersion:B,error_message:V(y),flag_onboarded:(G&4)!==0,flag_pin_validated:(G&128)!==0,flag_recovery:(G&1)!==0,flag_signed_mcu_code:(G&2)!==0,flagLen:R,flagsValue:G,return_code:y}},K)}deviceInfo(){return this.transport.send(224,1,0,0,Buffer.from([]),[E.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 B=L.slice(0,4).toString("hex"),R=4,G=L[R];R+=1;let N=L.slice(R,R+G).toString();R+=G;let T=L[R];R+=1;let X=L.slice(R,R+T).toString("hex");R+=T;let J=L[R];R+=1;let O=L.slice(R,R+J);if(O[J-1]===0)O=L.slice(R,R+J-1);let Z=O.toString();return{error_message:V(_),flag:X,mcuVersion:Z,return_code:_,seVersion:N,targetId:B}},K)}async publicKey(L){try{let y=await this.serializePath(L);switch(this.versionResponse.major){case 1:return K0(this,y);case 2:{let _=Buffer.concat([u.serializeHRP("thor"),y]);return m0(this,_)}default:return{error_message:"App Version is not supported",return_code:25600}}}catch(y){return K(y)}}async getAddressAndPubKey(L,y,_=!1){try{let B=await this.serializePath(L),R=Buffer.concat([u.serializeHRP(y),B]),G=await this.transport.send(c,l.GET_ADDR_SECP256K1,_?T0.SHOW_ADDRESS_IN_DEVICE:T0.ONLY_RETRIEVE,0,R,[E.NoError]),N=Buffer.from(G.slice(0,33)),T=Buffer.from(G.slice(33,-2)).toString(),X=G.readUInt16BE(G.length-2);return{bech32_address:T,compressed_pk:N,error_message:V(X),return_code:X}}catch(B){return K(B)}}showAddressAndPubKey(L,y){return this.getAddressAndPubKey(L,y,!0)}signSendChunk(L,y,_,B=g.JSON){switch(this.versionResponse.major){case 1:return O0(this,L,y,_,B);case 2:return A0(this,L,y,_,B);default:return{error_message:"App Version is not supported",return_code:25600}}}async sign(L,y,_=g.JSON){let B=Buffer.from(y),R=[],G;try{R=await this.signGetChunks(L,B),G=await this.signSendChunk(1,R.length,R[0],_)}catch(T){K(T)}let N={error_message:G.error_message,return_code:G.return_code,signature:null};for(let T=1;T<R.length;T+=1)if(N=await this.signSendChunk(1+T,R.length,R[T],_),N.return_code!==E.NoError)break;return{error_message:N.error_message,return_code:N.return_code,signature:N.signature}}}class i{ledgerTimeout=50000;derivationPath=HL.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 u(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 Z0("wallet_ledger_connection_error",y)}};validateResponse=(L,y)=>{switch(L){case J0.NoError:return;case J0.LockedDevice:throw new Z0("wallet_ledger_device_locked",{message:`Ledger is locked: ${y}`});case J0.TC_NotFound:throw new Z0("wallet_ledger_device_not_found");default:break}}}class $0 extends i{pubKey=null;derivationPath;constructor(L=UL.GAIA,y){super(y);this.chain="cosmos",this.derivationPath=CL(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:B,signature:R}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new P0("wallet_ledger_pubkey_not_found");return this.validateResponse(_,B),[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:y,signature:R}]};signAmino=async(L,y)=>{await this.checkOrCreateTransportAndLedger(!0);let _=await this.getAccounts();if(_.findIndex((j)=>j.address===L)===-1)throw new P0("wallet_ledger_address_not_found",{address:L});let R=await import("@cosmjs/amino"),G=R.encodeSecp256k1Signature??R.default?.encodeSecp256k1Signature,N=R.serializeSignDoc??R.default?.serializeSignDoc,T=await import("@cosmjs/crypto"),X=T.Secp256k1Signature??T.default?.Secp256k1Signature,J=N(y),O=await this.ledgerApp.sign(this.derivationPath,J);this.validateResponse(O.return_code,O.error_message);let Z=X.fromDer(O.signature).toFixedLength();return{signature:G(_[0].pubkey,Z),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 U,derivationPathToString as fL,NetworkDerivationPath as zL,SwapKitError as o}from"@swapkit/helpers";import{AbstractSigner as kL}from"ethers";function KL(L){if(typeof L==="number")return L;let y=L.startsWith("0x")?L.slice(2):L;return Number.parseInt(y||"0",16)}class z extends kL{chainId=U.Ethereum;derivationPath="";ledgerApp=null;ledgerTimeout=50000;transport;injectedTransport;constructor({provider:L,derivationPath:y=zL.OP,chainId:_=U.Optimism,transport:B}){super(L);this.chainId=_||U.Ethereum,this.derivationPath=typeof y==="string"?y:fL(y),this.injectedTransport=B,Object.defineProperty(this,"provider",{enumerable:!0,value:L||null,writable:!1})}connect=(L)=>new z({chainId:this.chainId,derivationPath:this.derivationPath,provider:L,transport:this.transport??this.injectedTransport});checkOrCreateTransportAndLedger=async()=>{await this.createTransportAndLedger()};createTransportAndLedger=async()=>{if(this.ledgerApp)return;this.transport||=this.injectedTransport??await f();let L=(await import("@ledgerhq/hw-app-eth")).default;this.ledgerApp=new L(this.transport)};getAddress=async()=>{let L=await this.getAddressAndPubKey();if(!L)throw new o("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 o("wallet_ledger_signing_error");return _.r=`0x${_.r}`,_.s=`0x${_.s}`,y.from(_).serialized};sendTransaction=async(L)=>{if(!this.provider)throw new o("wallet_ledger_no_provider");let y=await this.signTransaction(L);return await this.provider.broadcastTransaction(y)};signTypedData=async(L,y,_,B)=>{let{buildEIP712DomainType:R}=await import("@swapkit/toolboxes/evm"),{Signature:G,TypedDataEncoder:N}=await import("ethers");await this.createTransportAndLedger();let{EIP712Domain:T,...X}=y,J=B??N.from(X).primaryType,O;try{O=await this.ledgerApp?.signEIP712Message(this.derivationPath,{domain:L,message:_,primaryType:J,types:{EIP712Domain:R(L),...X}})}catch(Z){let j=Z instanceof Error&&"statusCode"in Z;if(!j||j&&Z.statusCode===27013)throw Z;let F=N.hashDomain(L).slice(2),C=N.from(X).hash(_).slice(2);O=await this.ledgerApp?.signEIP712HashedMessage(this.derivationPath,F,C)}if(!O)throw new o("wallet_ledger_signing_error");return O.r=`0x${O.r}`,O.s=`0x${O.s}`,G.from(O).serialized};signTransaction=async(L)=>{let{Transaction:y}=await import("ethers");await this.createTransportAndLedger();let _=L.nonce??void 0,B=_===void 0?await this.provider?.getTransactionCount(L.from||await this.getAddress()):void 0,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:_!==void 0?Number(_.toString()):B,to:L.to?.toString(),type:L.type&&!Number.isNaN(L.type)?L.type:L.maxFeePerGas?2:0,value:L.value},G=y.from(R).unsignedSerialized.slice(2),{ledgerService:N}=await import("@ledgerhq/hw-app-eth"),T=await N.resolveTransaction(G,{},{erc20:!0,externalPlugins:!0}),X=await this.ledgerApp?.signTransaction(this.derivationPath,G,T);if(!X)throw new o("wallet_ledger_signing_error");let{r:J,s:O,v:Z}=X;return y.from({...R,signature:{r:`0x${J}`,s:`0x${O}`,v:KL(Z)}}).serialized}}var E0=(L)=>new z({...L,chainId:U.Arbitrum}),I0=(L)=>new z({...L,chainId:U.Arc}),v0=(L)=>new z({...L,chainId:U.Aurora}),b0=(L)=>new z({...L,chainId:U.Avalanche}),l0=(L)=>new z({...L,chainId:U.Base}),c0=(L)=>new z({...L,chainId:U.Ethereum}),g0=(L)=>new z({...L,chainId:U.Gnosis}),h0=(L)=>new z({...L,chainId:U.Optimism}),x0=(L)=>new z({...L,chainId:U.Polygon}),d0=(L)=>new z({...L,chainId:U.BinanceSmartChain}),u0=(L)=>new z({...L,chainId:U.Monad}),i0=(L)=>new z({...L,chainId:U.XLayer}),o0=(L)=>new z({...L,chainId:U.Berachain});async function n0(L,y){let _=(await import("@ledgerhq/hw-app-near")).default,{Chain:B,NetworkDerivationPath:R,SwapKitError:G}=await import("@swapkit/helpers"),N=y??await f(),T=new _(N),X=(L||R[B.Near]).join("'/").concat("'"),{address:J,publicKey:O}=await T.getAddress(X);return{getAddress(){return Promise.resolve(J)},async getPublicKey(){let{PublicKey:j}=await import("@near-js/crypto");return j.fromString(`ed25519:${O}`)},signDelegateAction(j){return Promise.reject(new G("wallet_ledger_method_not_supported",{method:"signDelegateAction",wallet:"Ledger"}))},signNep413Message(j,F,C,D,A){return Promise.reject(new G("wallet_ledger_method_not_supported",{method:"signNep413Message",wallet:"Ledger"}))},async signTransaction(j){let{Signature:F,SignedTransaction:C}=await import("@near-js/transactions");try{let D=await T.signTransaction(j.encode(),X);if(!D)throw Error("Signature undefined");let A=new F({data:D,keyType:0}),v=new C({signature:A,transaction:j});return[D,v]}catch(D){throw new G("wallet_ledger_signing_error",{error:D})}}}}import{Chain as SL,derivationPathToString as AL,NetworkDerivationPath as mL,SwapKitError as b}from"@swapkit/helpers";class p0{derivationPath;ledgerApp=null;address=null;publicKey=null;injectedTransport;constructor(L,y){this.derivationPath=typeof L==="string"?L:AL(L||mL[SL.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 b("wallet_ledger_transport_error");let L=this.getLedgerPath(),y=await this.ledgerApp.getPublicKey(L);if(!y?.publicKey)throw new b("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 b("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 b("wallet_ledger_transport_error");if(!this.publicKey)throw new b("wallet_ledger_failed_to_get_address");try{let _=this.getLedgerPath(),B=new Uint8Array(3+y.length);B[0]=0,B[1]=0,B[2]=0,B.set(y,3);let R=await this.ledgerApp.signTransaction(_,B);if(!R?.signature)throw new b("wallet_ledger_signing_error");let G=this.publicKey.length===33?this.publicKey.slice(1):this.publicKey;if(G.length!==32)throw new b("wallet_ledger_signing_error",{error:"Invalid public key length"});let N=new Uint8Array(97);N[0]=0,N.set(R.signature,1),N.set(G,65);let T=Buffer.from(N).toString("base64");return{bytes:Buffer.from(y).toString("base64"),signature:T}}catch(_){throw new b("wallet_ledger_signing_error",{error:_})}}}var a0=(L,y)=>new p0(L,y);import{base64 as j0}from"@scure/base";import{NetworkDerivationPath as PL,SwapKitError as W0}from"@swapkit/helpers";import{base64 as VL}from"@scure/base";import{SwapKitError as I}from"@swapkit/helpers";var L0=(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 B=L[y+5];if(4+y+2+B!==L.length)throw new I("wallet_ledger_invalid_signature",{reason:"TLV byte lengths do not match message length"});let R=L.slice(y+6,L.length);if(R.length===33&&R[0]===0)R=R.slice(1,33);else if(R.length===33)throw new I("wallet_ledger_invalid_signature",{reason:"s too long"});while(R.length<32)R.unshift(0);if(_.length!==32||R.length!==32)throw new I("wallet_ledger_invalid_signature",{reason:"must be 32 bytes each"});return VL.encode(Buffer.concat([_,R]))};function EL(L){if(typeof L==="string")return L;let y=L.chain?.toUpperCase(),_=(L.symbol||L.ticker||"").toUpperCase();if(!(y&&_))return _||y||"";if(L.synth)return`${y}/${_}`;return`${y}.${_}`}function IL(L){return{...L,msgs:L.msgs.map((y)=>{if(!y.type.includes("MsgDeposit"))return y;let _=y.value.coins;if(!Array.isArray(_))return y;return{...y,value:{...y.value,coins:_.map((B)=>({...B,asset:EL(B.asset)}))}}})}}class Q0 extends i{pubKey=null;derivationPath;constructor(L=PL.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=j0.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:B,signature:R}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new W0("wallet_ledger_pubkey_not_found");return this.validateResponse(_,B),[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:y,signature:L0(R)}]};signAmino=async(L,y)=>{await this.checkOrCreateTransportAndLedger(!0);let _=(await this.getAccounts()).find((O)=>O.address===L);if(!_)throw new W0("wallet_ledger_address_not_found",{address:L});let B=await import("@cosmjs/amino"),R=B.encodeSecp256k1Signature??B.default?.encodeSecp256k1Signature,G=B.serializeSignDoc??B.default?.serializeSignDoc,N=IL(y),{return_code:T,error_message:X,signature:J}=await this.ledgerApp.sign(this.derivationPath,G(N));return this.validateResponse(T,X),{signature:R(_.pubkey,j0.decode(L0(J))),signed:y}};getAccounts=async()=>{await this.checkOrCreateTransportAndLedger(!0);let{bech32_address:L,compressed_pk:y}=await this.getAddressAndPubKey();return this.pubKey=j0.encode(y),[{address:L,algo:"secp256k1",pubkey:y}]};sign=async(L)=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:y,error_message:_,signature:B}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new W0("wallet_ledger_pubkey_not_found");return this.validateResponse(y,_),L0(B)}}import{derivationPathToString as vL,NetworkDerivationPath as bL,SwapKitError as n}from"@swapkit/helpers";class t0{derivationPath;ledgerApp=null;ledgerTimeout=50000;injectedTransport;constructor(L,y){this.derivationPath=typeof L==="string"?L:vL(L||bL.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 n("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 n("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 n("wallet_ledger_transport_error");try{let y=await this.ledgerApp.signTransaction(this.derivationPath,L.raw_data_hex,[]);if(!y)throw new n("wallet_ledger_signing_error");return{...L,signature:[y]}}catch(y){throw new n("wallet_ledger_signing_error",{error:y})}}}var e0=(L,y)=>new t0(L,y);import{hex as y0}from"@scure/base";import{derivationPathToString as lL,getWalletFormatFor as F0,SwapKitError as Y0}from"@swapkit/helpers";var s0=["bitcoin-cash","dash","dogecoin","zcash"],r0=({tx:L,inputUtxos:y,btcApp:_,derivationPath:B,chain:R},G)=>{let N=y.map((F)=>{return[_.splitTransaction(F.txHex||"",!s0.includes(R),R==="zcash"),F.index,void 0,void 0]}),T=y0.encode(L.unsignedTx),X=_.splitTransaction(T,!0),J=_.serializeTransactionOutputs(X).toString("hex"),O=F0(B),Z=O!=="legacy",j={additionals:O==="bech32"?["bech32"]:[],associatedKeysets:N.map(()=>B),inputs:N,outputScriptHex:J,segwit:Z,useTrustedInputForSegwit:Z};return _.createPaymentTransaction({...j,...G})},cL=({tx:L,inputUtxos:y,btcApp:_,derivationPaths:B,chain:R},G)=>{if(B.length!==y.length)throw new Y0("wallet_ledger_invalid_params",{message:`Derivation paths count (${B.length}) must match inputs count (${y.length})`});let N=y.map((F)=>{return[_.splitTransaction(F.txHex||"",!s0.includes(R),R==="zcash"),F.index,void 0,void 0]}),T=y0.encode(L.unsignedTx),X=_.splitTransaction(T,!0),J=_.serializeTransactionOutputs(X).toString("hex"),O=F0(B[0]??""),Z=O!=="legacy",j={additionals:O==="bech32"?["bech32"]:[],associatedKeysets:B,inputs:N,outputScriptHex:J,segwit:Z,useTrustedInputForSegwit:Z};return _.createPaymentTransaction({...j,...G})},h=({chain:L,additionalSignParams:y})=>{return(_,B)=>{let R,G=null;async function N(){G||=B??await f();let Z=(await import("@ledgerhq/hw-app-btc")).default;return R||=new Z({currency:L,transport:G}),R}async function T(){return R||await N()}async function X(){if(!B)await G?.close?.();R=void 0,G=null}let J=typeof _==="string"?_:lL(_),O=F0(J);return{connect:async()=>{await T()},disconnect:X,getAddress:async()=>{let{toCashAddress:Z}=await import("@swapkit/toolboxes/utxo"),j=await T(),{bitcoinAddress:F}=await j.getWalletPublicKey(J,{format:O});if(!F)throw new Y0("wallet_ledger_get_address_error",{message:`Cannot get ${L} address from ledger derivation path: ${J}`});return L==="bitcoin-cash"&&O==="legacy"?Z(F).replace(/(bchtest:|bitcoincash:)/,""):F},getExtendedPublicKey:async(Z="84'/0'/0'",j=76067358)=>{return(await T()).getWalletXpub({path:Z,xpubVersion:j})},signPCZT:async(Z)=>{if(L!=="zcash")throw new Y0("wallet_ledger_chain_not_supported",{message:"PCZT signing is only supported for Zcash"});let j=await T(),{ZcashTransaction:F,Script:C}=await import("@swapkit/utxo-signer"),D=Z.getGlobal(),A=new F({consensusBranchId:D.consensusBranchId,expiryHeight:D.expiryHeight,lockTime:D.lockTime,version:D.txVersion,versionGroupId:D.versionGroupId}),v=[];for(let Y=0;Y<Z.inputsLength;Y++){let Q=Z.getInput(Y);A.addInput({index:Q.index,script:new Uint8Array,sequence:Q.sequence??4294967295,txid:Q.txid,value:Q.value}),v.push({hash:y0.encode(new Uint8Array([...Q.txid].reverse())),index:Q.index,txHex:gL(Q,D),value:Number(Q.value),witnessUtxo:{script:Q.scriptPubkey,value:Number(Q.value)}})}for(let Y=0;Y<Z.outputsLength;Y++){let Q=Z.getOutput(Y);A.addOutput({amount:Q.value,script:Q.scriptPubkey})}let d=await r0({btcApp:j,chain:L,derivationPath:J,inputUtxos:v,tx:A},{...y,expiryHeight:(()=>{let Y=Buffer.alloc(4);return Y.writeUInt32LE(D.expiryHeight),Y})(),lockTime:D.lockTime}),M=F.fromHex(d,{allowUnknownOutputs:!0}),H=Z.clone();for(let Y=0;Y<M.inputsLength;Y++){let Q=M.getInput(Y);if(Q.script&&Q.script.length>0){let k=C.decode(Q.script);if(k.length>=2)H.addSignature(Y,k[1],k[0])}}return H},signTransaction:async(Z,j)=>{let F=await T();return r0({btcApp:F,chain:L,derivationPath:J,inputUtxos:j,tx:Z},y)},signTransactionWithMultiplePaths:async(Z,j,F)=>{let C=await T();return cL({btcApp:C,chain:L,derivationPaths:F,inputUtxos:j,tx:Z},y)}}}};function gL(L,y){let _=[],B=(y.txVersion|2147483648)>>>0;_.push(B&255,B>>8&255,B>>16&255,B>>24&255);let R=y.versionGroupId;_.push(R&255,R>>8&255,R>>16&255,R>>24&255),_.push(0);let G=L.index+1;if(G<253)_.push(G);else _.push(253,G&255,G>>8&255);for(let X=0;X<L.index;X++)_.push(0,0,0,0,0,0,0,0),_.push(0);let N=L.value;_.push(Number(N&0xffn),Number(N>>8n&0xffn),Number(N>>16n&0xffn),Number(N>>24n&0xffn),Number(N>>32n&0xffn),Number(N>>40n&0xffn),Number(N>>48n&0xffn),Number(N>>56n&0xffn));let T=L.scriptPubkey;if(T.length<253)_.push(T.length);else _.push(253,T.length&255,T.length>>8&255);for(let X of T)_.push(X);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),y0.encode(new Uint8Array(_))}var LL=h({chain:"bitcoin"}),yL=h({chain:"litecoin"}),_L=h({additionalSignParams:{additionals:["abc"],segwit:!1,sigHashType:65},chain:"bitcoin-cash"}),RL=h({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dogecoin"}),GL=h({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dash"}),BL=h({additionalSignParams:{additionals:["zcash","sapling"],expiryHeight:(()=>{let L=Buffer.alloc(4);return L.writeUInt32LE(0),L})(),lockTime:0,segwit:!1,useTrustedInputForSegwit:!1},chain:"zcash"});import hL from"@ledgerhq/hw-app-xrp";import{Chain as xL,derivationPathToString as dL,NetworkDerivationPath as uL}from"@swapkit/helpers";import{encode as wL}from"ripple-binary-codec";var iL=2147483648;function oL(L){let y={};for(let _ in L)if(L[_]!==null&&L[_]!==void 0)y[_]=L[_];return y}function nL(L){return new hL(L)}var NL=async(L,y)=>{let _=dL(L||uL[xL.Ripple]),B=y??await f(),R=nL(B),{address:G,publicKey:N}=await R.getAddress(_);async function T(X){let{hashes:J}=await import("xrpl"),Z={...oL(X),Flags:X.Flags||iL,SigningPubKey:N.toUpperCase()},j=wL(Z),F=await R.signTransaction(_,j),C=wL({...Z,TxnSignature:F});return{hash:J.hashSignedTx(C),tx_blob:C}}return{getAddress:()=>G,signTransaction:T}};var S=async({chain:L,derivationPath:y,transport:_})=>{let{match:B}=await import("ts-pattern");return B(L).returnType().with($.THORChain,()=>Promise.resolve(new Q0(y,_))).with($.Cosmos,()=>Promise.resolve(new $0(y,_))).with($.Bitcoin,()=>Promise.resolve(LL(y,_))).with($.BitcoinCash,()=>Promise.resolve(_L(y,_))).with($.Dash,()=>Promise.resolve(GL(y,_))).with($.Dogecoin,()=>Promise.resolve(RL(y,_))).with($.Litecoin,()=>Promise.resolve(yL(y,_))).with($.Zcash,()=>Promise.resolve(BL(y,_))).with($.Ripple,()=>Promise.resolve(NL(y,_))).with($.Tron,()=>Promise.resolve(e0(y,_))).with($.Sui,()=>Promise.resolve(a0(y,_))).with($.Near,()=>{return Promise.resolve(n0(y,_))}).with($.Arbitrum,$.Arc,$.Aurora,$.Avalanche,$.Berachain,$.BinanceSmartChain,$.Ethereum,$.Gnosis,$.Monad,$.Optimism,$.Polygon,$.Base,$.XLayer,async()=>{let{getProvider:R}=await import("@swapkit/toolboxes/evm"),G={derivationPath:y,provider:await R(L),transport:_};return B(L).with($.BinanceSmartChain,()=>d0(G)).with($.Avalanche,()=>b0(G)).with($.Arbitrum,()=>E0(G)).with($.Arc,()=>I0(G)).with($.Berachain,()=>o0(G)).with($.Optimism,()=>h0(G)).with($.Polygon,()=>x0(G)).with($.Base,()=>l0(G)).with($.Aurora,()=>v0(G)).with($.Gnosis,()=>g0(G)).with($.Monad,()=>u0(G)).with($.XLayer,()=>i0(G)).otherwise(()=>c0(G))}).otherwise(()=>{throw new pL("wallet_chain_not_supported",{chain:L,wallet:aL.LEDGER})})};var wy=Gy({connect:({addChain:L,supportedChains:y,walletType:_})=>async function(R,G,{address:N,transport:T}={}){let[X]=tL({chains:R,supportedChains:y,walletType:_});if(!X)return!1;let J=G??rL[X],O=await Xy({address:N,chain:X,derivationPath:J,transport:T});return L({...O,chain:X,walletType:M0.LEDGER}),!0},directSigningSupport:{[w.Arbitrum]:!0,[w.Arc]:!0,[w.Aurora]:!0,[w.Avalanche]:!0,[w.Base]:!0,[w.Berachain]:!0,[w.BinanceSmartChain]:!0,[w.Ethereum]:!0,[w.Gnosis]:!0,[w.Monad]:!0,[w.Bitcoin]:!0,[w.BitcoinCash]:!0,[w.Cosmos]:!0,[w.Dash]:!0,[w.Dogecoin]:!0,[w.Litecoin]:!0,[w.Near]:!0,[w.Optimism]:!0,[w.Polygon]:!0,[w.Ripple]:!0,[w.Sui]:!0,[w.THORChain]:!0,[w.Tron]:!0,[w.XLayer]:!0},getExtendedPublicKey:Ty,name:"connectLedger",supportedChains:[w.Arbitrum,w.Arc,w.Aurora,w.Avalanche,w.Base,w.Berachain,w.BinanceSmartChain,w.Bitcoin,w.BitcoinCash,w.Cosmos,w.Dash,w.Dogecoin,w.Ethereum,w.Gnosis,w.Litecoin,w.Monad,w.Near,w.Optimism,w.Polygon,w.Ripple,w.Sui,w.THORChain,w.XLayer,w.Tron,w.Zcash],walletType:M0.LEDGER}),q_=By(wy);function Ny(L,y="t"){if(!L?.includes("=:"))return L;let _=L.includes(`:${y}:`)?L.split(`:${y}:`)[0]:L;return _?.substring(0,_.lastIndexOf(":"))}async function Ty(L,y,{accountIndex:_}={}){if(![w.BitcoinCash,w.Bitcoin,w.Dash,w.Dogecoin,w.Litecoin,w.Zcash].includes(L))throw new x("wallet_chain_not_supported",{chain:L,wallet:M0.LEDGER});let B=L,R=await S({chain:B,derivationPath:y});if(!R.getExtendedPublicKey)return;let G=D0({accountIndex:_,chain:B,derivationPath:y}),N=_0(G),T=L===w.Bitcoin||L===w.Litecoin?N:N.replace(/^m\//,""),X=OL(B).bip32.public;try{let J=await R.getExtendedPublicKey(T,X);return{accountIndex:q0(G),path:N,xpub:J}}finally{await R.disconnect?.()}}async function Xy({address:L,chain:y,derivationPath:_,transport:B}){switch(y){case w.BitcoinCash:case w.Bitcoin:case w.Dash:case w.Dogecoin:case w.Litecoin:case w.Zcash:{let C=function(M={}){return F(M)},{getUtxoToolbox:R}=await import("@swapkit/toolboxes/utxo"),G=y,N=await S({chain:y,derivationPath:_,transport:B}),T=L??await P({chain:y,ledgerClient:N}),X,J;if(y===w.Bitcoin){let{BitcoinPsbtLedger:M}=await import("../chunk-gwx23jdp.js"),H=M(_,B);X={getAddress:H.getAddress,signTransaction:H.signTransaction}}else if(y===w.BitcoinCash||y===w.Dogecoin||y===w.Dash||y===w.Litecoin){let{createLegacyPsbtSigner:M,signLegacyPsbtTransaction:H}=await import("../chunk-bwf31zxr.js");X=M({address:T,chain:G,legacyClient:N}),J=async(Y)=>{let Q=await H({chain:G,legacyClient:N,tx:Y});return O.broadcastTx(Q)}}let O=X?await R(G,{signer:X}):R(G),Z=J??O.signAndBroadcastTransaction,j=async(M)=>{let H=M.feeRate||(await O.getFeeRates())[TL.Average],Y=[w.Bitcoin].includes(y)?M.memo:Ny(M.memo),{tx:Q,inputs:k}=await O.createTransaction({...M,feeRate:H,fetchTxHex:!0,memo:Y,sender:T}),m=await N.signTransaction(Q,k);return await O.broadcastTx(m)};async function F({accountIndex:M}={}){if(!N.getExtendedPublicKey)return;let H=D0({accountIndex:M,chain:G,derivationPath:_}),Y=_0(H),Q=y===w.Bitcoin||y===w.Litecoin?Y:Y.replace(/^m\//,""),k=OL(G).bip32.public,m=await N.getExtendedPublicKey(Q,k);return{accountIndex:q0(H),path:Y,xpub:m}}async function D({accountIndex:M,index:H,change:Y=!1}){try{let Q=_y({accountIndex:M,chain:G,change:Y,derivationPath:_,index:H}),k=await S({chain:G,derivationPath:Q,transport:B}),m=await P({chain:G,ledgerClient:k});return{accountIndex:q0(Q),address:m,change:Y,index:H,path:_0(Q),pubkey:""}}catch{return}}async function A({accountIndex:M,count:H,startIndex:Y=0,change:Q=!1}){return XL("count",H),XL("startIndex",Y),(await Promise.all(Array.from({length:H},(m,p)=>D({accountIndex:M,change:Q,index:Y+p})))).filter((m)=>!!m)}let v=yy({chain:G,deriveAddress:D,getBalance:O.getBalance,getUtxos:(M)=>Ry(G).getUtxos({address:M,fetchTxHex:!0})});async function d({utxos:M,recipient:H,assetValue:Y,memo:Q,feeRate:k,feeOptionKey:m,changeAddress:p}){if(!M.length)throw new x("wallet_ledger_invalid_params",{message:"No UTXOs provided for multi-address transfer"});let JL=k||(await O.getFeeRates())[m||TL.Fast],R0=Q?Ly(Q):null,H0=[{address:H,value:Y.getBaseValue("number")}];if(R0)H0.push({script:R0,value:0});let ZL=M.map(({hash:t,index:e,value:G0,txHex:B0,witnessUtxo:w0})=>({hash:t,index:e,txHex:B0,value:G0,witnessUtxo:w0})),{inputs:a,outputs:C0}=O.accumulative({chain:G,feeRate:JL,inputs:ZL,outputs:H0});if(!(a&&C0))throw new x("wallet_ledger_connection_error",{message:"Insufficient balance for multi-address transfer"});let{Transaction:$L}=await import("@swapkit/utxo-signer"),U0=new $L({allowLegacyWitnessUtxo:!0,version:1}),jL=p||M[0]?.address||H;sL({chain:G,compiledMemo:R0,inputs:a,outputs:C0,sender:jL,tx:U0});let WL=D0({chain:G,derivationPath:_}),QL=a.map((t)=>{let e=M.find((f0)=>f0.hash===t.hash&&f0.index===t.index),G0=e?.derivationIndex??0,B0=e?.isChange??!1,w0=[...WL,Number(B0),G0];return _0(w0)});if(!N.signTransactionWithMultiplePaths)throw new x("wallet_ledger_method_not_supported",{method:"signTransactionWithMultiplePaths"});let YL=await N.signTransactionWithMultiplePaths(U0,a,QL);return O.broadcastTx(YL)}return{...O,...v,address:T,deriveAddressAtIndex:D,deriveAddresses:A,getExtendedPublicKey:C,getExtendedPublicKeyInfo:F,signAndBroadcastTransaction:Z,transfer:j,transferFromMultipleAddresses:d}}case w.Ethereum:case w.Avalanche:case w.Arbitrum:case w.Arc:case w.Berachain:case w.Optimism:case w.Polygon:case w.BinanceSmartChain:case w.Base:case w.Aurora:case w.Gnosis:case w.Monad:case w.XLayer:{let{getEvmToolboxAsync:R}=await import("@swapkit/toolboxes/evm"),G=await S({chain:y,derivationPath:_,transport:B}),N=await P({chain:y,ledgerClient:G});return{...await R(y,{signer:G}),address:N}}case w.Cosmos:{let{createSigningStargateClient:R,getDefaultChainFee:G,getMsgSendDenom:N,getCosmosToolbox:T}=await import("@swapkit/toolboxes/cosmos"),X=await S({chain:y,derivationPath:_,transport:B}),J=await P({chain:y,ledgerClient:X});return{...await T(w.Cosmos,{signer:X}),address:J,transfer:async({assetValue:j,recipient:F,memo:C})=>{if(!j)throw new x("wallet_ledger_invalid_asset");let D={amount:[{amount:j.getBaseValue("string"),denom:N(`u${j.symbol}`).toLowerCase()}],fromAddress:J,toAddress:F},A=await eL(y),v=await R(A,X,"0.007uatom"),{transactionHash:d}=await v.signAndBroadcast(J,[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:D}],G(w.Cosmos),C);return d}}}case w.THORChain:{let R=await S({chain:y,derivationPath:_,transport:B}),{getCosmosToolbox:G}=await import("@swapkit/toolboxes/cosmos"),N=G(y,{signer:R}),T=await P({chain:y,ledgerClient:R}),{sign:X}=R;return{...N,address:T,signMessage:X}}case w.Near:{let{getNearToolbox:R}=await import("@swapkit/toolboxes/near"),G=await S({chain:y,derivationPath:_,transport:B}),N=await G.getAddress();return{...R({signer:G}),address:N}}case w.Ripple:{let{getRippleToolbox:R}=await import("@swapkit/toolboxes/ripple"),G=await S({chain:y,derivationPath:_,transport:B}),N=G.getAddress();return{...R({signer:G}),address:N}}case w.Tron:{let{getTronToolbox:R}=await import("@swapkit/toolboxes/tron"),G=await S({chain:y,derivationPath:_,transport:B}),N=await P({chain:y,ledgerClient:G});return{...R({signer:G}),address:N}}case w.Sui:{let{getSuiToolbox:R}=await import("@swapkit/toolboxes/sui"),G=await S({chain:y,derivationPath:_,transport:B}),N=await P({chain:y,ledgerClient:G});return{...R({signer:G}),address:N}}default:throw new x("wallet_ledger_chain_not_supported",{chain:y})}}export{wy as ledgerWallet,Ty as getLedgerExtendedPublicKey,q_ as LEDGER_SUPPORTED_CHAINS};
2
2
 
3
- //# debugId=F6ECE6B7368A4F1064756E2164756E21
3
+ //# debugId=7712C9A2CFB7E89664756E2164756E21
4
4
  //# sourceMappingURL=index.js.map