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