@swapkit/wallet-hardware 4.6.3 → 4.8.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.
- package/dist/chunk-3yr76n9s.js +5 -0
- package/dist/chunk-3yr76n9s.js.map +10 -0
- package/dist/chunk-3zf2pqfd.js +4 -0
- package/dist/chunk-3zf2pqfd.js.map +10 -0
- package/dist/{chunk-1jexf7qt.js → chunk-7fsaymh4.js} +3 -3
- package/dist/{chunk-1jexf7qt.js.map → chunk-7fsaymh4.js.map} +1 -1
- package/dist/{chunk-skvfn1dg.js → chunk-9tg9jj9j.js} +3 -3
- package/dist/{chunk-skvfn1dg.js.map → chunk-9tg9jj9j.js.map} +1 -1
- package/dist/chunk-mrsfcest.js +4 -0
- package/dist/chunk-mrsfcest.js.map +10 -0
- package/dist/{chunk-1jpcb30j.js → chunk-n05bv2n5.js} +3 -3
- package/dist/{chunk-1jpcb30j.js.map → chunk-n05bv2n5.js.map} +1 -1
- package/dist/chunk-px09mwnt.js +4 -0
- package/dist/chunk-px09mwnt.js.map +10 -0
- package/dist/{chunk-ybje7f3s.js → chunk-vwv6z2mk.js} +3 -3
- package/dist/{chunk-ybje7f3s.js.map → chunk-vwv6z2mk.js.map} +1 -1
- package/dist/chunk-x85da57j.js +4 -0
- package/dist/chunk-x85da57j.js.map +10 -0
- package/dist/chunk-y3yvq1zt.js +4 -0
- package/dist/chunk-y3yvq1zt.js.map +10 -0
- package/dist/keepkey/index.cjs +2 -2
- package/dist/keepkey/index.cjs.map +4 -4
- package/dist/keepkey/index.js +2 -2
- package/dist/keepkey/index.js.map +4 -4
- package/dist/ledger/index.cjs +3 -3
- package/dist/ledger/index.cjs.map +5 -6
- package/dist/ledger/index.js +3 -3
- package/dist/ledger/index.js.map +5 -6
- package/dist/trezor/index.cjs +2 -2
- package/dist/trezor/index.cjs.map +3 -3
- package/dist/trezor/index.js +2 -2
- package/dist/trezor/index.js.map +3 -3
- package/dist/types/keepkey/chains/utxo.d.ts +52 -14
- package/dist/types/keepkey/chains/utxo.d.ts.map +1 -1
- package/dist/types/keepkey/index.d.ts +2 -1
- package/dist/types/keepkey/index.d.ts.map +1 -1
- package/dist/types/ledger/clients/thorchain/lib.d.ts.map +1 -1
- package/dist/types/ledger/clients/utxo-legacy-adapter.d.ts +31 -0
- package/dist/types/ledger/clients/utxo-legacy-adapter.d.ts.map +1 -0
- package/dist/types/ledger/clients/utxo-psbt.d.ts +15 -0
- package/dist/types/ledger/clients/utxo-psbt.d.ts.map +1 -0
- package/dist/types/ledger/index.d.ts +2 -1
- package/dist/types/ledger/index.d.ts.map +1 -1
- package/dist/types/trezor/index.d.ts +2 -1
- package/dist/types/trezor/index.d.ts.map +1 -1
- package/package.json +5 -4
- package/dist/chunk-4fapcrj9.js +0 -5
- package/dist/chunk-4fapcrj9.js.map +0 -10
- package/dist/chunk-jj2v7mke.js +0 -4
- package/dist/chunk-jj2v7mke.js.map +0 -10
- package/dist/types/core.d.ts +0 -18
- package/dist/types/core.d.ts.map +0 -1
package/dist/ledger/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{a as X0,b as B0}from"../chunk-4fapcrj9.js";import{e as j}from"../chunk-1jpcb30j.js";import{Chain as B,derivationPathToString as T0,FeeOption as R0,filterSupportedChains as e0,getRPCUrl as O0,NetworkDerivationPath as WL,SwapKitError as g,THORConfig as a0,WalletOption as G0}from"@swapkit/helpers";import{addInputsAndOutputs as s0,compileMemo as r0,createHDWalletHelpers as L_,getUtxoApi as __}from"@swapkit/toolboxes/utxo";import{Chain as J,SwapKitError as Z0,WalletOption as M0}from"@swapkit/helpers";var k=async({chain:L,ledgerClient:_})=>{if(!_)return"";switch(L){case J.Cosmos:case J.THORChain:return _.connect();case J.Ethereum:case J.BinanceSmartChain:case J.Avalanche:case J.Polygon:case J.Arbitrum:case J.Berachain:case J.Optimism:case J.Base:case J.Aurora:case J.Gnosis:case J.Monad:case J.XLayer:return _.getAddress();case J.Bitcoin:case J.BitcoinCash:case J.Dash:case J.Dogecoin:case J.Litecoin:case J.Zcash:{let y=_;await y.connect();let m=await y.getAddress();return L===J.BitcoinCash?m.replace("bitcoincash:",""):m}case J.Near:return await _.getAddress();case J.Ripple:return _.getAddress();case J.Tron:return _.getAddress();case J.Sui:return _.connect();default:throw new Z0("wallet_chain_not_supported",{chain:L,wallet:M0.LEDGER})}};import{Chain as C,SwapKitError as t0,WalletOption as p0}from"@swapkit/helpers";import{derivationPathToString as H0,NetworkDerivationPath as D0,SwapKitError as SL}from"@swapkit/helpers";import{LedgerErrorCode as $L,NetworkDerivationPath as U0,SwapKitError as JL}from"@swapkit/helpers";import{SwapKitError as zL}from"@swapkit/helpers";var v=85,NL=250;var h={GET_ADDR_SECP256K1:4,GET_VERSION:0,INS_PUBLIC_KEY_SECP256K1:1,SIGN_SECP256K1:2},mL={ADD:1,INIT:0,LAST:2},FL={ONLY_RETRIEVE:0,SHOW_ADDRESS_IN_DEVICE:1},x={JSON:0},c={NoError:36864},UL={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 S(L){if(L in UL)return UL[L];return`Unknown Status Code: ${L}`}function Q0(L){return typeof L==="object"&&L!==null&&!Array.isArray(L)&&!(L instanceof Date)}function f(L){if(L){if(Q0(L)){if(Object.hasOwn(L,"statusCode"))return{error_message:S(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,h.GET_VERSION,0,0).then((_)=>{let y=_.slice(-2),m=y[0]*256+y[1],w=0;if(_.length>=9)w=(_[5]<<24)+(_[6]<<16)+(_[7]<<8)+(_[8]<<0);return{device_locked:_[4]===1,error_message:S(m),major:_[1],minor:_[2],patch:_[3],return_code:m,target_id:w.toString(16),test_mode:_[0]!==0}},f)}import{SwapKitError as TL}from"@swapkit/helpers";function HL(L){if(L==null||L.length<3)throw new TL("wallet_ledger_invalid_params",{reason:"Path too short"});if(L.length>10)throw new TL("wallet_ledger_invalid_params",{reason:"Path too long"});let _=Buffer.alloc(1+4*L.length);_.writeUInt8(L.length,0);for(let y=0;y<L.length;y+=1){let m=L[y]||0;if(y<3)m|=2147483648;_.writeInt32LE(m,1+y*4)}return _}function AL(L,_,y,m,w=x.JSON){return L.transport.send(v,h.SIGN_SECP256K1,_,w,m,[c.NoError,27012,27264]).then((T)=>{let R=T.slice(-2),O=R[0]*256+R[1],N=S(O);if(O===27264||O===27012)N=`${N} : ${T.slice(0,T.length-2).toString("ascii")}`;let X=null;if(T.length>2)X=T.slice(0,T.length-2);return{error_message:N,return_code:O,signature:X}},f)}function W0(L){if(L.length!==65)throw new TL("wallet_ledger_invalid_params",{reason:"decompressed public key length should be 65 bytes"});let _=L.slice(33,65),y=Buffer.from([2+(_[_.length-1]&1)]);return Buffer.concat([y,L.slice(1,33)])}function DL(L,_){return L.transport.send(v,h.INS_PUBLIC_KEY_SECP256K1,0,0,_,[c.NoError]).then((y)=>{let m=y.slice(-2),w=m[0]*256+m[1],T=Buffer.from(y.slice(0,65));return{compressed_pk:W0(T),error_message:S(w),pk:T,return_code:w}},f)}function fL(L){if(!L||L.length!==5)throw new TL("wallet_ledger_invalid_params",{reason:"Path must be exactly 5 elements"});let _=Buffer.alloc(20);return _.writeUInt32LE(2147483648+L[0],0),_.writeUInt32LE(2147483648+L[1],4),_.writeUInt32LE(2147483648+L[2],8),_.writeUInt32LE(L[3],12),_.writeUInt32LE(L[4],16),_}function qL(L,_,y,m,w=x.JSON){let T=mL.ADD;if(_===1)T=mL.INIT;if(_===y)T=mL.LAST;return AL(L,T,0,m,w)}function PL(L,_){return L.transport.send(v,h.GET_ADDR_SECP256K1,0,0,_,[c.NoError]).then((y)=>{let m=y.slice(-2),w=m[0]*256+m[1];return{compressed_pk:Buffer.from(y.slice(0,33)),error_message:S(w),pk:"OBSOLETE PROPERTY",return_code:w}},f)}class p{transport;versionResponse;constructor(L){if(!L)throw new zL("wallet_ledger_transport_not_defined");this.transport=L}static serializeHRP(L){if(L==null||L.length<3||L.length>83)throw new zL("wallet_ledger_invalid_params",{reason:"Invalid HRP"});let _=Buffer.alloc(1+L.length);return _.writeUInt8(L.length,0),_.write(L,1),_}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 HL(L);case 2:return fL(L);default:return Buffer.alloc(0)}}async signGetChunks(L,_){let y=await this.serializePath(L),m=[];m.push(y);for(let w=0;w<_.length;w+=NL){let T=w+NL;if(w>_.length)T=_.length;m.push(_.slice(w,T))}return m}async getVersion(){try{return this.versionResponse=await jL(this.transport),this.versionResponse}catch(L){return f(L)}}appInfo(){return this.transport.send(176,1,0,0).then((L)=>{let _=L.slice(-2),y=_[0]*256+_[1],m="",w="",T=0,R=0;if(L[0]!==1)return{error_message:"response format ID not recognized",return_code:36865};let O=L[1];m=L.slice(2,2+O).toString("ascii");let N=2+O,X=L[N];N+=1,w=L.slice(N,N+X).toString("ascii"),N+=X;let G=L[N];return N+=1,T=G,R=L[N],{appName:m,appVersion:w,error_message:S(y),flag_onboarded:(R&4)!==0,flag_pin_validated:(R&128)!==0,flag_recovery:(R&1)!==0,flag_signed_mcu_code:(R&2)!==0,flagLen:T,flagsValue:R,return_code:y}},f)}deviceInfo(){return this.transport.send(224,1,0,0,Buffer.from([]),[c.NoError,28160]).then((L)=>{let _=L.slice(-2),y=_[0]*256+_[1];if(y===28160)return{error_message:"This command is only available in the Dashboard",return_code:y};let m=L.slice(0,4).toString("hex"),w=4,T=L[w];w+=1;let R=L.slice(w,w+T).toString();w+=T;let O=L[w];w+=1;let N=L.slice(w,w+O).toString("hex");w+=O;let X=L[w];w+=1;let G=L.slice(w,w+X);if(G[X-1]===0)G=L.slice(w,w+X-1);let A=G.toString();return{error_message:S(y),flag:N,mcuVersion:A,return_code:y,seVersion:R,targetId:m}},f)}async publicKey(L){try{let _=await this.serializePath(L);switch(this.versionResponse.major){case 1:return DL(this,_);case 2:{let y=Buffer.concat([p.serializeHRP("thor"),_]);return PL(this,y)}default:return{error_message:"App Version is not supported",return_code:25600}}}catch(_){return f(_)}}getAddressAndPubKey(L,_,y=!1){return this.serializePath(L).then((m)=>{let w=Buffer.concat([p.serializeHRP(_),m]);return this.transport.send(v,h.GET_ADDR_SECP256K1,y?FL.SHOW_ADDRESS_IN_DEVICE:FL.ONLY_RETRIEVE,0,w,[c.NoError]).then((T)=>{let R=T.slice(-2),O=R[0]*256+R[1],N=Buffer.from(T.slice(0,33));return{bech32_address:Buffer.from(T.slice(33,-2)).toString(),compressed_pk:N,error_message:S(O),return_code:O}},f)}).catch((m)=>f(m))}showAddressAndPubKey(L,_){return this.getAddressAndPubKey(L,_,!0)}signSendChunk(L,_,y,m=x.JSON){switch(this.versionResponse.major){case 1:return AL(this,L,_,y,m);case 2:return qL(this,L,_,y,m);default:return{error_message:"App Version is not supported",return_code:25600}}}async sign(L,_,y=x.JSON){let m=Buffer.from(_),w=[],T;try{w=await this.signGetChunks(L,m),T=await this.signSendChunk(1,w.length,w[0],y)}catch(O){f(O)}let R={error_message:T.error_message,return_code:T.return_code,signature:null};for(let O=1;O<w.length;O+=1)if(R=await this.signSendChunk(1+O,w.length,w[O],y),R.return_code!==c.NoError)break;return{error_message:R.error_message,return_code:R.return_code,signature:R.signature}}}import{SwapKitError as e}from"@swapkit/helpers";var CL=()=>navigator?.usb,Y0=async()=>{let L=CL();if(typeof L?.getDevices!=="function")return{};let{ledgerUSBVendorId:_}=await import("@ledgerhq/devices"),m=(await L?.getDevices()).filter((w)=>w.vendorId===_);if(m.length>0)return m[0];return L?.requestDevice({filters:[{vendorId:_}]})},Y=async()=>{let L=await Y0();if(!L)throw new e("wallet_ledger_device_not_found");if(L.opened||await L.open(),L.configuration===null)await L.selectConfiguration(1);try{await L.reset()}catch{}let _=L.configuration??L.configurations?.[0],y=_?.interfaces.find(({alternates:G})=>G.some(({interfaceClass:A})=>A===255))||_?.interfaces.find(({alternates:G})=>G.some(({interfaceClass:A})=>A===3));if(!y)throw await L.close(),new e("wallet_ledger_connection_error");let m=y.alternates?.find(({interfaceClass:G})=>G===3)?.interfaceClass,w=y.alternates?.find(({interfaceClass:G})=>G===255)?.interfaceClass;if(m&&!w){let G=(await import("@ledgerhq/hw-transport-webhid")).default;if(!await G.isSupported())throw await L.close(),new e("wallet_ledger_webhid_not_supported");return await G.create()}try{await L.claimInterface(y.interfaceNumber)}catch(G){throw await L.close(),new e("wallet_ledger_connection_claimed",G)}let T=(await import("@ledgerhq/hw-transport-webusb")).default;if(!await T.isSupported())throw new e("wallet_ledger_webusb_not_supported");let{DisconnectedDevice:O}=await import("@ledgerhq/errors"),N=new T(L,y.interfaceNumber),X=(G)=>{if(L===G.device)CL()?.removeEventListener("disconnect",X),N._emitDisconnect(new O)};return CL()?.addEventListener("disconnect",X),N};class a{ledgerTimeout=50000;derivationPath=U0.GAIA;transport;ledgerApp;chain="thor";checkOrCreateTransportAndLedger=async(L=!1)=>{if(!L&&this.transport&&this.ledgerApp)return;try{switch(this.transport=L||!this.transport?await Y():this.transport,this.chain){case"thor":{this.ledgerApp=L||!this.ledgerApp?new p(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(_){throw new JL("wallet_ledger_connection_error",_)}};validateResponse=(L,_)=>{switch(L){case $L.NoError:return;case $L.LockedDevice:throw new JL("wallet_ledger_device_locked",{message:`Ledger is locked: ${_}`});case $L.TC_NotFound:throw new JL("wallet_ledger_device_not_found");default:break}}}class ZL extends a{pubKey=null;derivationPath;constructor(L=D0.GAIA){super();this.chain="cosmos",this.derivationPath=H0(L)}connect=async()=>{await this.checkOrCreateTransportAndLedger(!0);let{publicKey:L,address:_}=await this.getAddressAndPubKey();return this.pubKey=Buffer.from(L,"hex").toString("base64"),_};getAddressAndPubKey=async()=>{return await this.checkOrCreateTransportAndLedger(!0),await this.ledgerApp.getAddress(this.derivationPath,this.chain)};signTransaction=async(L,_="0")=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:y,error_message:m,signature:w}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new SL("wallet_ledger_pubkey_not_found");return this.validateResponse(y,m),[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:_,signature:w}]};signAmino=async(L,_)=>{await this.checkOrCreateTransportAndLedger(!0);let y=await this.getAccounts();if(y.findIndex((F)=>F.address===L)===-1)throw new SL("wallet_ledger_address_not_found",{address:L});let w=await import("@cosmjs/amino"),T=w.encodeSecp256k1Signature??w.default?.encodeSecp256k1Signature,R=w.serializeSignDoc??w.default?.serializeSignDoc,O=await import("@cosmjs/crypto"),N=O.Secp256k1Signature??O.default?.Secp256k1Signature,X=R(_),G=await this.ledgerApp.sign(this.derivationPath,X);this.validateResponse(G.return_code,G.error_message);let A=N.fromDer(G.signature).toFixedLength();return{signature:T(y[0].pubkey,A),signed:_}};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 f0,NetworkDerivationPath as q0,SwapKitError as s}from"@swapkit/helpers";import{AbstractSigner as P0}from"ethers";class D extends P0{chainId=U.Ethereum;derivationPath="";ledgerApp=null;ledgerTimeout=50000;constructor({provider:L,derivationPath:_=q0.OP,chainId:y=U.Optimism}){super(L);this.chainId=y||U.Ethereum,this.derivationPath=typeof _==="string"?_:f0(_),Object.defineProperty(this,"provider",{enumerable:!0,value:L||null,writable:!1})}connect=(L)=>new D({chainId:this.chainId,derivationPath:this.derivationPath,provider:L});checkOrCreateTransportAndLedger=async()=>{if(this.ledgerApp)return;await this.createTransportAndLedger()};createTransportAndLedger=async()=>{let L=await Y(),_=(await import("@ledgerhq/hw-app-eth")).default;this.ledgerApp=new _(L)};getAddress=async()=>{let L=await this.getAddressAndPubKey();if(!L)throw new s("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:_}=await import("ethers");await this.createTransportAndLedger();let y=await this.ledgerApp?.signPersonalMessage(this.derivationPath,L);if(!y)throw new s("wallet_ledger_signing_error");return y.r=`0x${y.r}`,y.s=`0x${y.s}`,_.from(y).serialized};sendTransaction=async(L)=>{if(!this.provider)throw new s("wallet_ledger_no_provider");let _=await this.signTransaction(L);return await this.provider.broadcastTransaction(_)};signTypedData=async(L,_,y,m)=>{let{buildEIP712DomainType:w}=await import("@swapkit/toolboxes/evm"),{Signature:T,TypedDataEncoder:R}=await import("ethers");await this.createTransportAndLedger();let{EIP712Domain:O,...N}=_,X=m??R.from(N).primaryType,G;try{G=await this.ledgerApp?.signEIP712Message(this.derivationPath,{domain:L,message:y,primaryType:X,types:{EIP712Domain:w(L),...N}})}catch(A){let F=A instanceof Error&&"statusCode"in A;if(!F||F&&A.statusCode===27013)throw A;let $=R.hashDomain(L).slice(2),Z=R.from(N).hash(y).slice(2);G=await this.ledgerApp?.signEIP712HashedMessage(this.derivationPath,$,Z)}if(!G)throw new s("wallet_ledger_signing_error");return G.r=`0x${G.r}`,G.s=`0x${G.s}`,T.from(G).serialized};signTransaction=async(L)=>{let{Transaction:_}=await import("ethers");await this.createTransportAndLedger();let y=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||y||0).toString()):y,to:L.to?.toString(),type:L.type&&!Number.isNaN(L.type)?L.type:L.maxFeePerGas?2:0,value:L.value},w=_.from(m).unsignedSerialized.slice(2),{ledgerService:T}=await import("@ledgerhq/hw-app-eth"),R=await T.resolveTransaction(w,{},{erc20:!0,externalPlugins:!0}),O=await this.ledgerApp?.signTransaction(this.derivationPath,w,R);if(!O)throw new s("wallet_ledger_signing_error");let{r:N,s:X,v:G}=O;return _.from({...m,signature:{r:`0x${N}`,s:`0x${X}`,v:Number(BigInt(G))}}).serialized}}var KL=(L)=>new D({...L,chainId:U.Arbitrum}),kL=(L)=>new D({...L,chainId:U.Aurora}),cL=(L)=>new D({...L,chainId:U.Avalanche}),VL=(L)=>new D({...L,chainId:U.Base}),gL=(L)=>new D({...L,chainId:U.Ethereum}),IL=(L)=>new D({...L,chainId:U.Gnosis}),EL=(L)=>new D({...L,chainId:U.Optimism}),lL=(L)=>new D({...L,chainId:U.Polygon}),hL=(L)=>new D({...L,chainId:U.BinanceSmartChain}),bL=(L)=>new D({...L,chainId:U.Monad}),vL=(L)=>new D({...L,chainId:U.XLayer}),xL=(L)=>new D({...L,chainId:U.Berachain});async function dL(L){let _=(await import("@ledgerhq/hw-app-near")).default,{Chain:y,NetworkDerivationPath:m,SwapKitError:w}=await import("@swapkit/helpers"),T=await Y(),R=new _(T),O=(L||m[y.Near]).join("'/").concat("'"),{address:N,publicKey:X}=await R.getAddress(O);return{getAddress(){return Promise.resolve(N)},async getPublicKey(){let{PublicKey:A}=await import("@near-js/crypto");return A.fromString(`ed25519:${X}`)},signDelegateAction(A){return Promise.reject(new w("wallet_ledger_method_not_supported",{method:"signDelegateAction",wallet:"Ledger"}))},signNep413Message(A,F,$,Z,W){return Promise.reject(new w("wallet_ledger_method_not_supported",{method:"signNep413Message",wallet:"Ledger"}))},async signTransaction(A){let{Signature:F,SignedTransaction:$}=await import("@near-js/transactions");try{let Z=await R.signTransaction(A.encode(),O);if(!Z)throw Error("Signature undefined");let W=new F({data:Z,keyType:0}),H=new $({signature:W,transaction:A});return[Z,H]}catch(Z){throw new w("wallet_ledger_signing_error",{error:Z})}}}}import{Chain as z0,derivationPathToString as S0,NetworkDerivationPath as K0,SwapKitError as I}from"@swapkit/helpers";class oL{derivationPath;ledgerApp=null;address=null;publicKey=null;constructor(L){this.derivationPath=typeof L==="string"?L:S0(L||K0[z0.Sui])}getLedgerPath(){return this.derivationPath.replace(/^m\//,"").replace(/\/(\d+)\/(\d+)$/,"/$1'/$2'")}async createTransportAndLedger(){if(this.ledgerApp)return;let L=await Y(),_=(await import("@ledgerhq/hw-app-sui")).default;this.ledgerApp=new _(L)}async connect(){if(await this.createTransportAndLedger(),!this.ledgerApp)throw new I("wallet_ledger_transport_error");let L=this.getLedgerPath(),_=await this.ledgerApp.getPublicKey(L);if(!_?.publicKey)throw new I("wallet_ledger_failed_to_get_address");return this.publicKey=_.publicKey,this.address=`0x${Buffer.from(_.address).toString("hex")}`,this.address}toSuiAddress(){if(!this.address)throw new I("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 _=L instanceof Uint8Array?L:L.transaction;if(await this.createTransportAndLedger(),!this.ledgerApp)throw new I("wallet_ledger_transport_error");if(!this.publicKey)throw new I("wallet_ledger_failed_to_get_address");try{let y=this.getLedgerPath(),m=new Uint8Array(3+_.length);m[0]=0,m[1]=0,m[2]=0,m.set(_,3);let w=await this.ledgerApp.signTransaction(y,m);if(!w?.signature)throw new I("wallet_ledger_signing_error");let T=this.publicKey.length===33?this.publicKey.slice(1):this.publicKey;if(T.length!==32)throw new I("wallet_ledger_signing_error",{error:"Invalid public key length"});let R=new Uint8Array(97);R[0]=0,R.set(w.signature,1),R.set(T,65);let O=Buffer.from(R).toString("base64");return{bytes:Buffer.from(_).toString("base64"),signature:O}}catch(y){throw new I("wallet_ledger_signing_error",{error:y})}}}var nL=(L)=>new oL(L);import{base64 as c0}from"@scure/base";import{NetworkDerivationPath as V0,SwapKitError as iL}from"@swapkit/helpers";import{base64 as k0}from"@scure/base";import{SwapKitError as V}from"@swapkit/helpers";var ML=(L)=>{if(L.length<64)throw new V("wallet_ledger_invalid_signature",{reason:"Too short"});if(L[0]!==48)throw new V("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected first byte 0x30"});if(L[1]+2!==L.length)throw new V("wallet_ledger_invalid_signature",{reason:"signature length does not match TLV"});if(L[2]!==2)throw new V("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected length type 0x02"});let _=L[3],y=L.slice(4,_+4);if(y.length===33&&y[0]===0)y=y.slice(1,33);else if(y.length===33)throw new V("wallet_ledger_invalid_signature",{reason:"r too long"});while(y.length<32)y.unshift(0);if(L[_+4]!==2)throw new V("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected length type 0x02 for s"});let m=L[_+5];if(4+_+2+m!==L.length)throw new V("wallet_ledger_invalid_signature",{reason:"TLV byte lengths do not match message length"});let w=L.slice(_+6,L.length);if(w.length===33&&w[0]===0)w=w.slice(1,33);else if(w.length===33)throw new V("wallet_ledger_invalid_signature",{reason:"s too long"});while(w.length<32)w.unshift(0);if(y.length!==32||w.length!==32)throw new V("wallet_ledger_invalid_signature",{reason:"must be 32 bytes each"});return k0.encode(Buffer.concat([y,w]))};class QL extends a{pubKey=null;derivationPath;constructor(L=V0.THOR){super();this.chain="thor",this.derivationPath=L}get pubkey(){return this.pubKey}connect=async()=>{await this.checkOrCreateTransportAndLedger();let{compressed_pk:L,bech32_address:_}=await this.getAddressAndPubKey();return this.pubKey=c0.encode(L),_};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,_="0")=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:y,error_message:m,signature:w}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new iL("wallet_ledger_pubkey_not_found");return this.validateResponse(y,m),[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:_,signature:ML(w)}]};sign=async(L)=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:_,error_message:y,signature:m}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new iL("wallet_ledger_pubkey_not_found");return this.validateResponse(_,y),ML(m)}}import{derivationPathToString as g0,NetworkDerivationPath as I0,SwapKitError as r}from"@swapkit/helpers";class uL{derivationPath;ledgerApp=null;ledgerTimeout=50000;constructor(L){this.derivationPath=typeof L==="string"?L:g0(L||I0.TRON)}checkOrCreateTransportAndLedger=async()=>{if(this.ledgerApp)return;await this.createTransportAndLedger()};createTransportAndLedger=async()=>{let L=await Y(),_=(await import("@ledgerhq/hw-app-trx")).default;this.ledgerApp=new _(L)};getAddress=async()=>{let L=await this.getAddressAndPubKey();if(!L)throw new r("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 r("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 r("wallet_ledger_transport_error");let _=JSON.stringify(L);try{let y=await this.ledgerApp.signTransaction(this.derivationPath,_,[]);if(!y)throw new r("wallet_ledger_signing_error");return{...L,signature:[y]}}catch(y){throw new r("wallet_ledger_signing_error",{error:y})}}}var tL=(L)=>new uL(L);import{hex as OL}from"@scure/base";import{derivationPathToString as E0,getWalletFormatFor as l0,SwapKitError as RL}from"@swapkit/helpers";var eL=["bitcoin-cash","dash","dogecoin","zcash"],pL=({tx:L,inputUtxos:_,btcApp:y,derivationPath:m,chain:w},T)=>{let R=_.map((A)=>{return[y.splitTransaction(A.txHex||"",!eL.includes(w),w==="zcash"),A.index,void 0,void 0]}),O=OL.encode(L.unsignedTx),N=y.splitTransaction(O,!0),X=y.serializeTransactionOutputs(N).toString("hex"),G={additionals:["bech32"],associatedKeysets:R.map(()=>m),inputs:R,outputScriptHex:X,segwit:!0,useTrustedInputForSegwit:!0};return y.createPaymentTransaction({...G,...T})},h0=({tx:L,inputUtxos:_,btcApp:y,derivationPaths:m,chain:w},T)=>{if(m.length!==_.length)throw new RL("wallet_ledger_invalid_params",{message:`Derivation paths count (${m.length}) must match inputs count (${_.length})`});let R=_.map((A)=>{return[y.splitTransaction(A.txHex||"",!eL.includes(w),w==="zcash"),A.index,void 0,void 0]}),O=OL.encode(L.unsignedTx),N=y.splitTransaction(O,!0),X=y.serializeTransactionOutputs(N).toString("hex"),G={additionals:["bech32"],associatedKeysets:m,inputs:R,outputScriptHex:X,segwit:!0,useTrustedInputForSegwit:!0};return y.createPaymentTransaction({...G,...T})},d=({chain:L,additionalSignParams:_})=>{let y,m=null;async function w(R=!0){if(R&&!y)new RL("wallet_ledger_connection_error",{message:`Ledger connection failed:
|
|
2
|
-
${JSON.stringify({btcApp:y,checkBtcApp:R})}`});m||=await Y()}async function T(){m=await Y(),y=new(await import("@ledgerhq/hw-app-btc")).default({currency:L,transport:m})}return(R)=>{let O=typeof R==="string"?R:E0(R),N=l0(O);return{connect:async()=>{await w(!1),y=new(await import("@ledgerhq/hw-app-btc")).default({currency:L,transport:m})},getAddress:async()=>{let{toCashAddress:X}=await import("@swapkit/toolboxes/utxo");await w(!1);let{bitcoinAddress:G}=await y.getWalletPublicKey(O,{format:N});if(!G)throw new RL("wallet_ledger_get_address_error",{message:`Cannot get ${L} address from ledger derivation path: ${O}`});return L==="bitcoin-cash"&&N==="legacy"?X(G).replace(/(bchtest:|bitcoincash:)/,""):G},getExtendedPublicKey:async(X="84'/0'/0'",G=76067358)=>{return await w(!1),y.getWalletXpub({path:X,xpubVersion:G})},signPCZT:async(X)=>{if(L!=="zcash")throw new RL("wallet_ledger_chain_not_supported",{message:"PCZT signing is only supported for Zcash"});await T();let{ZcashTransaction:G,Script:A}=await import("@swapkit/utxo-signer"),F=X.getGlobal(),$=new G({consensusBranchId:F.consensusBranchId,expiryHeight:F.expiryHeight,lockTime:F.lockTime,version:F.txVersion,versionGroupId:F.versionGroupId}),Z=[];for(let M=0;M<X.inputsLength;M++){let Q=X.getInput(M);$.addInput({index:Q.index,script:new Uint8Array,sequence:Q.sequence??4294967295,txid:Q.txid,value:Q.value}),Z.push({hash:OL.encode(new Uint8Array([...Q.txid].reverse())),index:Q.index,txHex:b0(Q,F),value:Number(Q.value),witnessUtxo:{script:Q.scriptPubkey,value:Number(Q.value)}})}for(let M=0;M<X.outputsLength;M++){let Q=X.getOutput(M);$.addOutput({amount:Q.value,script:Q.scriptPubkey})}let W=await pL({btcApp:y,chain:L,derivationPath:O,inputUtxos:Z,tx:$},{..._,expiryHeight:(()=>{let M=Buffer.alloc(4);return M.writeUInt32LE(F.expiryHeight),M})(),lockTime:F.lockTime}),H=G.fromHex(W,{allowUnknownOutputs:!0}),q=X.clone();for(let M=0;M<H.inputsLength;M++){let Q=H.getInput(M);if(Q.script&&Q.script.length>0){let K=A.decode(Q.script);if(K.length>=2)q.addSignature(M,K[1],K[0])}}return q},signTransaction:async(X,G)=>{return await T(),pL({btcApp:y,chain:L,derivationPath:O,inputUtxos:G,tx:X},_)},signTransactionWithMultiplePaths:async(X,G,A)=>{return await T(),h0({btcApp:y,chain:L,derivationPaths:A,inputUtxos:G,tx:X},_)}}}};function b0(L,_){let y=[],m=(_.txVersion|2147483648)>>>0;y.push(m&255,m>>8&255,m>>16&255,m>>24&255);let w=_.versionGroupId;y.push(w&255,w>>8&255,w>>16&255,w>>24&255),y.push(0);let T=L.index+1;if(T<253)y.push(T);else y.push(253,T&255,T>>8&255);for(let N=0;N<L.index;N++)y.push(0,0,0,0,0,0,0,0),y.push(0);let R=L.value;y.push(Number(R&0xffn),Number(R>>8n&0xffn),Number(R>>16n&0xffn),Number(R>>24n&0xffn),Number(R>>32n&0xffn),Number(R>>40n&0xffn),Number(R>>48n&0xffn),Number(R>>56n&0xffn));let O=L.scriptPubkey;if(O.length<253)y.push(O.length);else y.push(253,O.length&255,O.length>>8&255);for(let N of O)y.push(N);return y.push(_.lockTime&255,_.lockTime>>8&255,_.lockTime>>16&255,_.lockTime>>24&255),y.push(_.expiryHeight&255,_.expiryHeight>>8&255,_.expiryHeight>>16&255,_.expiryHeight>>24&255),y.push(0,0,0,0,0,0,0,0),y.push(0),y.push(0),y.push(0),OL.encode(new Uint8Array(y))}var aL=d({chain:"bitcoin"}),sL=d({chain:"litecoin"}),rL=d({additionalSignParams:{additionals:["abc"],segwit:!1,sigHashType:65},chain:"bitcoin-cash"}),L0=d({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dogecoin"}),_0=d({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dash"}),y0=d({additionalSignParams:{additionals:["zcash","sapling"],expiryHeight:(()=>{let L=Buffer.alloc(4);return L.writeUInt32LE(0),L})(),lockTime:0,segwit:!1,useTrustedInputForSegwit:!1},chain:"zcash"});import v0 from"@ledgerhq/hw-app-xrp";import{Chain as x0,derivationPathToString as d0,NetworkDerivationPath as o0}from"@swapkit/helpers";import{encode as w0}from"ripple-binary-codec";var n0=2147483648;function i0(L){let _={};for(let y in L)if(L[y]!==null&&L[y]!==void 0)_[y]=L[y];return _}function u0(L){return new v0(L)}var m0=async(L)=>{let _=d0(L||o0[x0.Ripple]),y=await Y(),m=u0(y),{address:w,publicKey:T}=await m.getAddress(_);async function R(O){let{hashes:N}=await import("@swapkit/toolboxes/ripple"),G={...i0(O),Flags:O.Flags||n0,SigningPubKey:T.toUpperCase()},A=w0(G),F=await m.signTransaction(_,A),$=w0({...G,TxnSignature:F});return{hash:N.hashSignedTx($),tx_blob:$}}return{getAddress:()=>w,signTransaction:R}};var P=async({chain:L,derivationPath:_})=>{let{match:y}=await import("ts-pattern");return y(L).returnType().with(C.THORChain,()=>Promise.resolve(new QL(_))).with(C.Cosmos,()=>Promise.resolve(new ZL(_))).with(C.Bitcoin,()=>Promise.resolve(aL(_))).with(C.BitcoinCash,()=>Promise.resolve(rL(_))).with(C.Dash,()=>Promise.resolve(_0(_))).with(C.Dogecoin,()=>Promise.resolve(L0(_))).with(C.Litecoin,()=>Promise.resolve(sL(_))).with(C.Zcash,()=>Promise.resolve(y0(_))).with(C.Ripple,()=>Promise.resolve(m0(_))).with(C.Tron,()=>Promise.resolve(tL(_))).with(C.Sui,()=>Promise.resolve(nL(_))).with(C.Near,()=>{return Promise.resolve(dL(_))}).with(C.Arbitrum,C.Aurora,C.Avalanche,C.Berachain,C.BinanceSmartChain,C.Ethereum,C.Gnosis,C.Monad,C.Optimism,C.Polygon,C.Base,C.XLayer,async()=>{let{getProvider:m}=await import("@swapkit/toolboxes/evm"),w={derivationPath:_,provider:await m(L)};return y(L).with(C.BinanceSmartChain,()=>hL(w)).with(C.Avalanche,()=>cL(w)).with(C.Arbitrum,()=>KL(w)).with(C.Berachain,()=>xL(w)).with(C.Optimism,()=>EL(w)).with(C.Polygon,()=>lL(w)).with(C.Base,()=>VL(w)).with(C.Aurora,()=>kL(w)).with(C.Gnosis,()=>IL(w)).with(C.Monad,()=>bL(w)).with(C.XLayer,()=>vL(w)).otherwise(()=>gL(w))}).otherwise(()=>{throw new t0("wallet_chain_not_supported",{chain:L,wallet:p0.LEDGER})})};var y_=X0({connect:({addChain:L,supportedChains:_,walletType:y})=>async function(w,T){let[R]=e0({chains:w,supportedChains:_,walletType:y});if(!R)return!1;let O=await T_({chain:R,derivationPath:T});return L({...O,chain:R,walletType:G0.LEDGER}),!0},name:"connectLedger",supportedChains:[B.Arbitrum,B.Aurora,B.Avalanche,B.Base,B.Berachain,B.BinanceSmartChain,B.Bitcoin,B.BitcoinCash,B.Cosmos,B.Dash,B.Dogecoin,B.Ethereum,B.Gnosis,B.Litecoin,B.Monad,B.Near,B.Optimism,B.Polygon,B.Ripple,B.Sui,B.THORChain,B.XLayer,B.Tron,B.Zcash],walletType:G0.LEDGER}),Zy=B0(y_);function w_(L,_="t"){if(!L?.includes("=:"))return L;let y=L.includes(`:${_}:`)?L.split(`:${_}:`)[0]:L;return y?.substring(0,y.lastIndexOf(":"))}function GL(L){if(Array.isArray(L))return L.forEach((m,w)=>{L[w]=GL(m)}),L;if(typeof L!=="object")return L;let _={},y=Object.keys(L).sort();for(let m of y)_[m]=GL(L[m]);return _}function m_(L){return JSON.stringify(GL(L))}async function T_({chain:L,derivationPath:_}){switch(L){case B.BitcoinCash:case B.Bitcoin:case B.Dash:case B.Dogecoin:case B.Litecoin:case B.Zcash:{let{getUtxoToolbox:y}=await import("@swapkit/toolboxes/utxo"),m=L,w=y(m),T=await P({chain:L,derivationPath:_}),R=await k({chain:L,ledgerClient:T}),O=async(F)=>{let $=F.feeRate||(await w.getFeeRates())[R0.Average],Z=[B.Bitcoin].includes(L)?F.memo:w_(F.memo),{tx:W,inputs:H}=await w.createTransaction({...F,feeRate:$,fetchTxHex:!0,memo:Z,sender:R}),q=await T.signTransaction(W,H);return await w.broadcastTx(q)};async function N(){if(!T.getExtendedPublicKey)return;let F=await T.getExtendedPublicKey(),$=_?.slice(0,3)??WL[L].slice(0,3);return{path:T0($),xpub:F}}async function X({index:F,change:$=!1}){try{let W=[..._?.slice(0,3)??WL[L].slice(0,3),Number($),F],H=await P({chain:m,derivationPath:W});return{address:await k({chain:m,ledgerClient:H}),change:$,index:F,pubkey:""}}catch{return}}let G=L_({chain:m,deriveAddress:X,getBalance:w.getBalance,getUtxos:(F)=>__(m).getUtxos({address:F,fetchTxHex:!0})});async function A({utxos:F,recipient:$,assetValue:Z,memo:W,feeRate:H,feeOptionKey:q,changeAddress:M}){if(!F.length)throw new g("wallet_ledger_invalid_params",{message:"No UTXOs provided for multi-address transfer"});let Q=H||(await w.getFeeRates())[q||R0.Fast],K=W?r0(W):null,o=[{address:$,value:Z.getBaseValue("number")}];if(K)o.push({script:K,value:0});let YL=F.map(({hash:E,index:b,value:l,txHex:u,witnessUtxo:t})=>({hash:E,index:b,txHex:u,value:l,witnessUtxo:t})),{inputs:n,outputs:z}=w.accumulative({chain:m,feeRate:Q,inputs:YL,outputs:o});if(!(n&&z))throw new g("wallet_ledger_connection_error",{message:"Insufficient balance for multi-address transfer"});let{Transaction:LL}=await import("@swapkit/utxo-signer"),_L=new LL({allowLegacyWitnessUtxo:!0,version:1}),yL=M||F[0]?.address||$;s0({chain:m,compiledMemo:K,inputs:n,outputs:z,sender:yL,tx:_L});let XL=_?.slice(0,3)??WL[L].slice(0,3),BL=n.map((E)=>{let b=F.find((wL)=>wL.hash===E.hash&&wL.index===E.index),l=b?.derivationIndex??0,u=b?.isChange??!1,t=[...XL,Number(u),l];return T0(t)});if(!T.signTransactionWithMultiplePaths)throw new g("wallet_ledger_method_not_supported",{method:"signTransactionWithMultiplePaths"});let i=await T.signTransactionWithMultiplePaths(_L,n,BL);return w.broadcastTx(i)}return{...w,...G,address:R,deriveAddressAtIndex:X,getExtendedPublicKey:N,transfer:O,transferFromMultipleAddresses:A}}case B.Ethereum:case B.Avalanche:case B.Arbitrum:case B.Berachain:case B.Optimism:case B.Polygon:case B.BinanceSmartChain:case B.Base:case B.Aurora:case B.Gnosis:case B.Monad:case B.XLayer:{let{getEvmToolboxAsync:y}=await import("@swapkit/toolboxes/evm"),m=await P({chain:L,derivationPath:_}),w=await k({chain:L,ledgerClient:m});return{...await y(L,{signer:m}),address:w}}case B.Cosmos:{let{createSigningStargateClient:y,getMsgSendDenom:m,getCosmosToolbox:w}=await import("@swapkit/toolboxes/cosmos"),T=w(B.Cosmos),R=await P({chain:L,derivationPath:_}),O=await k({chain:L,ledgerClient:R});return{...T,address:O,transfer:async({assetValue:X,recipient:G,memo:A})=>{if(!X)throw new g("wallet_ledger_invalid_asset");let F={amount:[{amount:X.getBaseValue("string"),denom:m(`u${X.symbol}`).toLowerCase()}],fromAddress:O,toAddress:G},$=await O0(L),Z=await y($,R,"0.007uatom"),{transactionHash:W}=await Z.signAndBroadcast(O,[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:F}],2,A);return W}}}case B.THORChain:{let{SignMode:y}=await import("cosmjs-types/cosmos/tx/signing/v1beta1/signing.js"),{TxRaw:m}=await import("cosmjs-types/cosmos/tx/v1beta1/tx.js"),w=await import("@cosmjs/proto-signing"),T=w.encodePubkey??w.default?.encodePubkey,R=w.makeAuthInfoBytes??w.default?.makeAuthInfoBytes,{createStargateClient:O,buildEncodedTxBody:N,getCosmosToolbox:X,buildAminoMsg:G,getDefaultChainFee:A,fromBase64:F,parseAminoMessageForDirectSigning:$}=await import("@swapkit/toolboxes/cosmos"),Z=X(L),W=await P({chain:L,derivationPath:_}),H=await k({chain:L,ledgerClient:W}),q=A(L),{pubkey:M,signTransaction:Q,sign:K}=W,o=async({memo:z="",assetValue:LL,..._L})=>{let yL=await Z.getAccount(H);if(!yL)throw new g("wallet_ledger_invalid_account");if(!LL)throw new g("wallet_ledger_invalid_asset");if(!M)throw new g("wallet_ledger_pubkey_not_found");let{accountNumber:XL,sequence:BL}=yL,i=(BL||0).toString(),E=GL([G({assetValue:LL,memo:z,sender:H,..._L})]),b=m_({account_number:XL?.toString(),chain_id:a0.chainId,fee:q,memo:z,msgs:E,sequence:i}),l=await Q(b,i);if(!l)throw new g("wallet_ledger_signing_error");let u=T({type:"tendermint/PubKeySecp256k1",value:M}),t=E.map($),wL=await N({chain:L,memo:z,msgs:t}),N0=R([{pubkey:u,sequence:Number(i)}],q.amount,Number.parseInt(q.gas,10),void 0,void 0,y.SIGN_MODE_LEGACY_AMINO_JSON),F0=l?.[0]?.signature?F(l[0].signature):Uint8Array.from([]),j0=m.fromPartial({authInfoBytes:N0,bodyBytes:wL,signatures:[F0]}),A0=m.encode(j0).finish(),C0=await O0(B.THORChain),$0=await O(C0),{transactionHash:J0}=await $0.broadcastTx(A0);return J0};return{...Z,address:H,deposit:(z)=>o(z),signMessage:K,transfer:(z)=>o(z)}}case B.Near:{let{getNearToolbox:y}=await import("@swapkit/toolboxes/near"),m=await P({chain:L,derivationPath:_}),w=await m.getAddress();return{...y({signer:m}),address:w}}case B.Ripple:{let{getRippleToolbox:y}=await import("@swapkit/toolboxes/ripple"),m=await P({chain:L,derivationPath:_}),w=m.getAddress();return{...y({signer:m}),address:w}}case B.Tron:{let{getTronToolbox:y}=await import("@swapkit/toolboxes/tron"),m=await P({chain:L,derivationPath:_}),w=await k({chain:L,ledgerClient:m});return{...y({signer:m}),address:w}}case B.Sui:{let{getSuiToolbox:y}=await import("@swapkit/toolboxes/sui"),m=await P({chain:L,derivationPath:_}),w=await k({chain:L,ledgerClient:m});return{...y({signer:m}),address:w}}default:throw new g("wallet_ledger_chain_not_supported",{chain:L})}}export{y_ as ledgerWallet,Zy as LEDGER_SUPPORTED_CHAINS};
|
|
1
|
+
import{c as Q}from"../chunk-3yr76n9s.js";import{d as N}from"../chunk-n05bv2n5.js";import{Chain as m,derivationPathToString as ZL,FeeOption as R0,filterSupportedChains as t0,getRPCUrl as O0,NetworkDerivationPath as u0,SwapKitError as l,THORConfig as e0,WalletOption as G0}from"@swapkit/helpers";import{addInputsAndOutputs as p0,assertDerivationIndex as C0,compileMemo as a0,createHDWalletHelpers as r0,getUTXOAccountIndexFromPath as B0,getUTXOAccountPath as X0,getUTXOAddressPath as s0,getUtxoApi as L_}from"@swapkit/toolboxes/utxo";import{createWallet as __,getWalletSupportedChains as y_}from"@swapkit/wallet-core";import{Chain as $,SwapKitError as j0,WalletOption as A0}from"@swapkit/helpers";var K=async({chain:L,ledgerClient:_})=>{if(!_)return"";switch(L){case $.Cosmos:case $.THORChain:return _.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 _.getAddress();case $.Bitcoin:case $.BitcoinCash:case $.Dash:case $.Dogecoin:case $.Litecoin:case $.Zcash:{let y=_;await y.connect();let T=await y.getAddress();return L===$.BitcoinCash?T.replace("bitcoincash:",""):T}case $.Near:return await _.getAddress();case $.Ripple:return _.getAddress();case $.Tron:return _.getAddress();case $.Sui:return _.connect();default:throw new j0("wallet_chain_not_supported",{chain:L,wallet:A0.LEDGER})}};import{Chain as F,SwapKitError as i0,WalletOption as n0}from"@swapkit/helpers";import{derivationPathToString as U0,NetworkDerivationPath as Z0,SwapKitError as zL}from"@swapkit/helpers";import{LedgerErrorCode as AL,NetworkDerivationPath as J0,SwapKitError as WL}from"@swapkit/helpers";import{SwapKitError as PL}from"@swapkit/helpers";var d=85,DL=250;var I={GET_ADDR_SECP256K1:4,GET_VERSION:0,INS_PUBLIC_KEY_SECP256K1:1,SIGN_SECP256K1:2},RL={ADD:1,INIT:0,LAST:2},FL={ONLY_RETRIEVE:0,SHOW_ADDRESS_IN_DEVICE:1},b={JSON:0},g={NoError:36864},QL={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 z(L){if(L in QL)return QL[L];return`Unknown Status Code: ${L}`}function W0(L){return typeof L==="object"&&L!==null&&!Array.isArray(L)&&!(L instanceof Date)}function q(L){if(L){if(W0(L)){if(Object.hasOwn(L,"statusCode"))return{error_message:z(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 fL(L){return L.send(85,I.GET_VERSION,0,0).then((_)=>{let y=_.slice(-2),T=y[0]*256+y[1],w=0;if(_.length>=9)w=(_[5]<<24)+(_[6]<<16)+(_[7]<<8)+(_[8]<<0);return{device_locked:_[4]===1,error_message:z(T),major:_[1],minor:_[2],patch:_[3],return_code:T,target_id:w.toString(16),test_mode:_[0]!==0}},q)}import{SwapKitError as OL}from"@swapkit/helpers";function YL(L){if(L==null||L.length<3)throw new OL("wallet_ledger_invalid_params",{reason:"Path too short"});if(L.length>10)throw new OL("wallet_ledger_invalid_params",{reason:"Path too long"});let _=Buffer.alloc(1+4*L.length);_.writeUInt8(L.length,0);for(let y=0;y<L.length;y+=1){let T=L[y]||0;if(y<3)T|=2147483648;_.writeInt32LE(T,1+y*4)}return _}function jL(L,_,y,T,w=b.JSON){return L.transport.send(d,I.SIGN_SECP256K1,_,w,T,[g.NoError,27012,27264]).then((R)=>{let O=R.slice(-2),G=O[0]*256+O[1],X=z(G);if(G===27264||G===27012)X=`${X} : ${R.slice(0,R.length-2).toString("ascii")}`;let C=null;if(R.length>2)C=R.slice(0,R.length-2);return{error_message:X,return_code:G,signature:C}},q)}function $0(L){if(L.length!==65)throw new OL("wallet_ledger_invalid_params",{reason:"decompressed public key length should be 65 bytes"});let _=L.slice(33,65),y=Buffer.from([2+(_[_.length-1]&1)]);return Buffer.concat([y,L.slice(1,33)])}function HL(L,_){return L.transport.send(d,I.INS_PUBLIC_KEY_SECP256K1,0,0,_,[g.NoError]).then((y)=>{let T=y.slice(-2),w=T[0]*256+T[1],R=Buffer.from(y.slice(0,65));return{compressed_pk:$0(R),error_message:z(w),pk:R,return_code:w}},q)}function cL(L){if(!L||L.length!==5)throw new OL("wallet_ledger_invalid_params",{reason:"Path must be exactly 5 elements"});let _=Buffer.alloc(20);return _.writeUInt32LE(2147483648+L[0],0),_.writeUInt32LE(2147483648+L[1],4),_.writeUInt32LE(2147483648+L[2],8),_.writeUInt32LE(L[3],12),_.writeUInt32LE(L[4],16),_}function qL(L,_,y,T,w=b.JSON){let R=RL.ADD;if(_===1)R=RL.INIT;if(_===y)R=RL.LAST;return jL(L,R,0,T,w)}function SL(L,_){return L.transport.send(d,I.GET_ADDR_SECP256K1,0,0,_,[g.NoError]).then((y)=>{let T=y.slice(-2),w=T[0]*256+T[1];return{compressed_pk:Buffer.from(y.slice(0,33)),error_message:z(w),pk:"OBSOLETE PROPERTY",return_code:w}},q)}class a{transport;versionResponse;constructor(L){if(!L)throw new PL("wallet_ledger_transport_not_defined");this.transport=L}static serializeHRP(L){if(L==null||L.length<3||L.length>83)throw new PL("wallet_ledger_invalid_params",{reason:"Invalid HRP"});let _=Buffer.alloc(1+L.length);return _.writeUInt8(L.length,0),_.write(L,1),_}async serializePath(L){if(this.versionResponse=await fL(this.transport),this.versionResponse.return_code!==g.NoError)throw this.versionResponse;switch(this.versionResponse.major){case 1:return YL(L);case 2:return cL(L);default:return Buffer.alloc(0)}}async signGetChunks(L,_){let y=await this.serializePath(L),T=[];T.push(y);for(let w=0;w<_.length;w+=DL){let R=w+DL;if(w>_.length)R=_.length;T.push(_.slice(w,R))}return T}async getVersion(){try{return this.versionResponse=await fL(this.transport),this.versionResponse}catch(L){return q(L)}}appInfo(){return this.transport.send(176,1,0,0).then((L)=>{let _=L.readUInt16BE(L.length-2),y="",T="",w=0,R=0;if(L[0]!==1)return{error_message:"response format ID not recognized",return_code:36865};let O=L[1];y=L.slice(2,2+O).toString("ascii");let G=2+O,X=L[G];G+=1,T=L.slice(G,G+X).toString("ascii"),G+=X;let C=L[G];return G+=1,w=C,R=L[G],{appName:y,appVersion:T,error_message:z(_),flag_onboarded:(R&4)!==0,flag_pin_validated:(R&128)!==0,flag_recovery:(R&1)!==0,flag_signed_mcu_code:(R&2)!==0,flagLen:w,flagsValue:R,return_code:_}},q)}deviceInfo(){return this.transport.send(224,1,0,0,Buffer.from([]),[g.NoError,28160]).then((L)=>{let _=L.slice(-2),y=_[0]*256+_[1];if(y===28160)return{error_message:"This command is only available in the Dashboard",return_code:y};let T=L.slice(0,4).toString("hex"),w=4,R=L[w];w+=1;let O=L.slice(w,w+R).toString();w+=R;let G=L[w];w+=1;let X=L.slice(w,w+G).toString("hex");w+=G;let C=L[w];w+=1;let B=L.slice(w,w+C);if(B[C-1]===0)B=L.slice(w,w+C-1);let D=B.toString();return{error_message:z(y),flag:X,mcuVersion:D,return_code:y,seVersion:O,targetId:T}},q)}async publicKey(L){try{let _=await this.serializePath(L);switch(this.versionResponse.major){case 1:return HL(this,_);case 2:{let y=Buffer.concat([a.serializeHRP("thor"),_]);return SL(this,y)}default:return{error_message:"App Version is not supported",return_code:25600}}}catch(_){return q(_)}}async getAddressAndPubKey(L,_,y=!1){try{let T=await this.serializePath(L),w=Buffer.concat([a.serializeHRP(_),T]),R=await this.transport.send(d,I.GET_ADDR_SECP256K1,y?FL.SHOW_ADDRESS_IN_DEVICE:FL.ONLY_RETRIEVE,0,w,[g.NoError]),O=Buffer.from(R.slice(0,33)),G=Buffer.from(R.slice(33,-2)).toString(),X=R.readUInt16BE(R.length-2);return{bech32_address:G,compressed_pk:O,error_message:z(X),return_code:X}}catch(T){return q(T)}}showAddressAndPubKey(L,_){return this.getAddressAndPubKey(L,_,!0)}signSendChunk(L,_,y,T=b.JSON){switch(this.versionResponse.major){case 1:return jL(this,L,_,y,T);case 2:return qL(this,L,_,y,T);default:return{error_message:"App Version is not supported",return_code:25600}}}async sign(L,_,y=b.JSON){let T=Buffer.from(_),w=[],R;try{w=await this.signGetChunks(L,T),R=await this.signSendChunk(1,w.length,w[0],y)}catch(G){q(G)}let O={error_message:R.error_message,return_code:R.return_code,signature:null};for(let G=1;G<w.length;G+=1)if(O=await this.signSendChunk(1+G,w.length,w[G],y),O.return_code!==g.NoError)break;return{error_message:O.error_message,return_code:O.return_code,signature:O.signature}}}class r{ledgerTimeout=50000;derivationPath=J0.GAIA;transport;ledgerApp;chain="thor";checkOrCreateTransportAndLedger=async(L=!1)=>{if(!L&&this.transport&&this.ledgerApp)return;try{switch(this.transport=L||!this.transport?await Q():this.transport,this.chain){case"thor":{this.ledgerApp=L||!this.ledgerApp?new a(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(_){throw new WL("wallet_ledger_connection_error",_)}};validateResponse=(L,_)=>{switch(L){case AL.NoError:return;case AL.LockedDevice:throw new WL("wallet_ledger_device_locked",{message:`Ledger is locked: ${_}`});case AL.TC_NotFound:throw new WL("wallet_ledger_device_not_found");default:break}}}class $L extends r{pubKey=null;derivationPath;constructor(L=Z0.GAIA){super();this.chain="cosmos",this.derivationPath=U0(L)}connect=async()=>{await this.checkOrCreateTransportAndLedger(!0);let{publicKey:L,address:_}=await this.getAddressAndPubKey();return this.pubKey=Buffer.from(L,"hex").toString("base64"),_};getAddressAndPubKey=async()=>{return await this.checkOrCreateTransportAndLedger(!0),await this.ledgerApp.getAddress(this.derivationPath,this.chain)};signTransaction=async(L,_="0")=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:y,error_message:T,signature:w}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new zL("wallet_ledger_pubkey_not_found");return this.validateResponse(y,T),[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:_,signature:w}]};signAmino=async(L,_)=>{await this.checkOrCreateTransportAndLedger(!0);let y=await this.getAccounts();if(y.findIndex((W)=>W.address===L)===-1)throw new zL("wallet_ledger_address_not_found",{address:L});let w=await import("@cosmjs/amino"),R=w.encodeSecp256k1Signature??w.default?.encodeSecp256k1Signature,O=w.serializeSignDoc??w.default?.serializeSignDoc,G=await import("@cosmjs/crypto"),X=G.Secp256k1Signature??G.default?.Secp256k1Signature,C=O(_),B=await this.ledgerApp.sign(this.derivationPath,C);this.validateResponse(B.return_code,B.error_message);let D=X.fromDer(B.signature).toFixedLength();return{signature:R(y[0].pubkey,D),signed:_}};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 Y,derivationPathToString as M0,NetworkDerivationPath as Q0,SwapKitError as s}from"@swapkit/helpers";import{AbstractSigner as Y0}from"ethers";class c extends Y0{chainId=Y.Ethereum;derivationPath="";ledgerApp=null;ledgerTimeout=50000;constructor({provider:L,derivationPath:_=Q0.OP,chainId:y=Y.Optimism}){super(L);this.chainId=y||Y.Ethereum,this.derivationPath=typeof _==="string"?_:M0(_),Object.defineProperty(this,"provider",{enumerable:!0,value:L||null,writable:!1})}connect=(L)=>new c({chainId:this.chainId,derivationPath:this.derivationPath,provider:L});checkOrCreateTransportAndLedger=async()=>{if(this.ledgerApp)return;await this.createTransportAndLedger()};createTransportAndLedger=async()=>{let L=await Q(),_=(await import("@ledgerhq/hw-app-eth")).default;this.ledgerApp=new _(L)};getAddress=async()=>{let L=await this.getAddressAndPubKey();if(!L)throw new s("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:_}=await import("ethers");await this.createTransportAndLedger();let y=await this.ledgerApp?.signPersonalMessage(this.derivationPath,L);if(!y)throw new s("wallet_ledger_signing_error");return y.r=`0x${y.r}`,y.s=`0x${y.s}`,_.from(y).serialized};sendTransaction=async(L)=>{if(!this.provider)throw new s("wallet_ledger_no_provider");let _=await this.signTransaction(L);return await this.provider.broadcastTransaction(_)};signTypedData=async(L,_,y,T)=>{let{buildEIP712DomainType:w}=await import("@swapkit/toolboxes/evm"),{Signature:R,TypedDataEncoder:O}=await import("ethers");await this.createTransportAndLedger();let{EIP712Domain:G,...X}=_,C=T??O.from(X).primaryType,B;try{B=await this.ledgerApp?.signEIP712Message(this.derivationPath,{domain:L,message:y,primaryType:C,types:{EIP712Domain:w(L),...X}})}catch(D){let W=D instanceof Error&&"statusCode"in D;if(!W||W&&D.statusCode===27013)throw D;let M=O.hashDomain(L).slice(2),Z=O.from(X).hash(y).slice(2);B=await this.ledgerApp?.signEIP712HashedMessage(this.derivationPath,M,Z)}if(!B)throw new s("wallet_ledger_signing_error");return B.r=`0x${B.r}`,B.s=`0x${B.s}`,R.from(B).serialized};signTransaction=async(L)=>{let{Transaction:_}=await import("ethers");await this.createTransportAndLedger();let y=await this.provider?.getTransactionCount(L.from||await this.getAddress()),T={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||y||0).toString()):y,to:L.to?.toString(),type:L.type&&!Number.isNaN(L.type)?L.type:L.maxFeePerGas?2:0,value:L.value},w=_.from(T).unsignedSerialized.slice(2),{ledgerService:R}=await import("@ledgerhq/hw-app-eth"),O=await R.resolveTransaction(w,{},{erc20:!0,externalPlugins:!0}),G=await this.ledgerApp?.signTransaction(this.derivationPath,w,O);if(!G)throw new s("wallet_ledger_signing_error");let{r:X,s:C,v:B}=G;return _.from({...T,signature:{r:`0x${X}`,s:`0x${C}`,v:Number(BigInt(B))}}).serialized}}var KL=(L)=>new c({...L,chainId:Y.Arbitrum}),gL=(L)=>new c({...L,chainId:Y.Aurora}),kL=(L)=>new c({...L,chainId:Y.Avalanche}),lL=(L)=>new c({...L,chainId:Y.Base}),VL=(L)=>new c({...L,chainId:Y.Ethereum}),EL=(L)=>new c({...L,chainId:Y.Gnosis}),IL=(L)=>new c({...L,chainId:Y.Optimism}),vL=(L)=>new c({...L,chainId:Y.Polygon}),hL=(L)=>new c({...L,chainId:Y.BinanceSmartChain}),oL=(L)=>new c({...L,chainId:Y.Monad}),dL=(L)=>new c({...L,chainId:Y.XLayer}),bL=(L)=>new c({...L,chainId:Y.Berachain});async function xL(L){let _=(await import("@ledgerhq/hw-app-near")).default,{Chain:y,NetworkDerivationPath:T,SwapKitError:w}=await import("@swapkit/helpers"),R=await Q(),O=new _(R),G=(L||T[y.Near]).join("'/").concat("'"),{address:X,publicKey:C}=await O.getAddress(G);return{getAddress(){return Promise.resolve(X)},async getPublicKey(){let{PublicKey:D}=await import("@near-js/crypto");return D.fromString(`ed25519:${C}`)},signDelegateAction(D){return Promise.reject(new w("wallet_ledger_method_not_supported",{method:"signDelegateAction",wallet:"Ledger"}))},signNep413Message(D,W,M,Z,f){return Promise.reject(new w("wallet_ledger_method_not_supported",{method:"signNep413Message",wallet:"Ledger"}))},async signTransaction(D){let{Signature:W,SignedTransaction:M}=await import("@near-js/transactions");try{let Z=await O.signTransaction(D.encode(),G);if(!Z)throw Error("Signature undefined");let f=new W({data:Z,keyType:0}),J=new M({signature:f,transaction:D});return[Z,J]}catch(Z){throw new w("wallet_ledger_signing_error",{error:Z})}}}}import{Chain as H0,derivationPathToString as c0,NetworkDerivationPath as q0,SwapKitError as V}from"@swapkit/helpers";class iL{derivationPath;ledgerApp=null;address=null;publicKey=null;constructor(L){this.derivationPath=typeof L==="string"?L:c0(L||q0[H0.Sui])}getLedgerPath(){return this.derivationPath.replace(/^m\//,"").replace(/\/(\d+)\/(\d+)$/,"/$1'/$2'")}async createTransportAndLedger(){if(this.ledgerApp)return;let L=await Q(),_=(await import("@ledgerhq/hw-app-sui")).default;this.ledgerApp=new _(L)}async connect(){if(await this.createTransportAndLedger(),!this.ledgerApp)throw new V("wallet_ledger_transport_error");let L=this.getLedgerPath(),_=await this.ledgerApp.getPublicKey(L);if(!_?.publicKey)throw new V("wallet_ledger_failed_to_get_address");return this.publicKey=_.publicKey,this.address=`0x${Buffer.from(_.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 _=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 y=this.getLedgerPath(),T=new Uint8Array(3+_.length);T[0]=0,T[1]=0,T[2]=0,T.set(_,3);let w=await this.ledgerApp.signTransaction(y,T);if(!w?.signature)throw new V("wallet_ledger_signing_error");let R=this.publicKey.length===33?this.publicKey.slice(1):this.publicKey;if(R.length!==32)throw new V("wallet_ledger_signing_error",{error:"Invalid public key length"});let O=new Uint8Array(97);O[0]=0,O.set(w.signature,1),O.set(R,65);let G=Buffer.from(O).toString("base64");return{bytes:Buffer.from(_).toString("base64"),signature:G}}catch(y){throw new V("wallet_ledger_signing_error",{error:y})}}}var nL=(L)=>new iL(L);import{base64 as P0}from"@scure/base";import{NetworkDerivationPath as z0,SwapKitError as tL}from"@swapkit/helpers";import{base64 as S0}from"@scure/base";import{SwapKitError as k}from"@swapkit/helpers";var JL=(L)=>{if(L.length<64)throw new k("wallet_ledger_invalid_signature",{reason:"Too short"});if(L[0]!==48)throw new k("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected first byte 0x30"});if(L[1]+2!==L.length)throw new k("wallet_ledger_invalid_signature",{reason:"signature length does not match TLV"});if(L[2]!==2)throw new k("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected length type 0x02"});let _=L[3],y=L.slice(4,_+4);if(y.length===33&&y[0]===0)y=y.slice(1,33);else if(y.length===33)throw new k("wallet_ledger_invalid_signature",{reason:"r too long"});while(y.length<32)y.unshift(0);if(L[_+4]!==2)throw new k("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected length type 0x02 for s"});let T=L[_+5];if(4+_+2+T!==L.length)throw new k("wallet_ledger_invalid_signature",{reason:"TLV byte lengths do not match message length"});let w=L.slice(_+6,L.length);if(w.length===33&&w[0]===0)w=w.slice(1,33);else if(w.length===33)throw new k("wallet_ledger_invalid_signature",{reason:"s too long"});while(w.length<32)w.unshift(0);if(y.length!==32||w.length!==32)throw new k("wallet_ledger_invalid_signature",{reason:"must be 32 bytes each"});return S0.encode(Buffer.concat([y,w]))};class UL extends r{pubKey=null;derivationPath;constructor(L=z0.THOR){super();this.chain="thor",this.derivationPath=L}get pubkey(){return this.pubKey}connect=async()=>{await this.checkOrCreateTransportAndLedger();let{compressed_pk:L,bech32_address:_}=await this.getAddressAndPubKey();return this.pubKey=P0.encode(L),_};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,_="0")=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:y,error_message:T,signature:w}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new tL("wallet_ledger_pubkey_not_found");return this.validateResponse(y,T),[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:_,signature:JL(w)}]};sign=async(L)=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:_,error_message:y,signature:T}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new tL("wallet_ledger_pubkey_not_found");return this.validateResponse(_,y),JL(T)}}import{derivationPathToString as K0,NetworkDerivationPath as g0,SwapKitError as LL}from"@swapkit/helpers";class uL{derivationPath;ledgerApp=null;ledgerTimeout=50000;constructor(L){this.derivationPath=typeof L==="string"?L:K0(L||g0.TRON)}checkOrCreateTransportAndLedger=async()=>{if(this.ledgerApp)return;await this.createTransportAndLedger()};createTransportAndLedger=async()=>{let L=await Q(),_=(await import("@ledgerhq/hw-app-trx")).default;this.ledgerApp=new _(L)};getAddress=async()=>{let L=await this.getAddressAndPubKey();if(!L)throw new LL("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 LL("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 LL("wallet_ledger_transport_error");let _=JSON.stringify(L);try{let y=await this.ledgerApp.signTransaction(this.derivationPath,_,[]);if(!y)throw new LL("wallet_ledger_signing_error");return{...L,signature:[y]}}catch(y){throw new LL("wallet_ledger_signing_error",{error:y})}}}var eL=(L)=>new uL(L);import{hex as CL}from"@scure/base";import{derivationPathToString as k0,getWalletFormatFor as l0,SwapKitError as GL}from"@swapkit/helpers";var aL=["bitcoin-cash","dash","dogecoin","zcash"],pL=({tx:L,inputUtxos:_,btcApp:y,derivationPath:T,chain:w},R)=>{let O=_.map((D)=>{return[y.splitTransaction(D.txHex||"",!aL.includes(w),w==="zcash"),D.index,void 0,void 0]}),G=CL.encode(L.unsignedTx),X=y.splitTransaction(G,!0),C=y.serializeTransactionOutputs(X).toString("hex"),B={additionals:["bech32"],associatedKeysets:O.map(()=>T),inputs:O,outputScriptHex:C,segwit:!0,useTrustedInputForSegwit:!0};return y.createPaymentTransaction({...B,...R})},V0=({tx:L,inputUtxos:_,btcApp:y,derivationPaths:T,chain:w},R)=>{if(T.length!==_.length)throw new GL("wallet_ledger_invalid_params",{message:`Derivation paths count (${T.length}) must match inputs count (${_.length})`});let O=_.map((D)=>{return[y.splitTransaction(D.txHex||"",!aL.includes(w),w==="zcash"),D.index,void 0,void 0]}),G=CL.encode(L.unsignedTx),X=y.splitTransaction(G,!0),C=y.serializeTransactionOutputs(X).toString("hex"),B={additionals:["bech32"],associatedKeysets:T,inputs:O,outputScriptHex:C,segwit:!0,useTrustedInputForSegwit:!0};return y.createPaymentTransaction({...B,...R})},x=({chain:L,additionalSignParams:_})=>{let y,T=null;async function w(O=!0){if(O&&!y)new GL("wallet_ledger_connection_error",{message:`Ledger connection failed:
|
|
2
|
+
${JSON.stringify({btcApp:y,checkBtcApp:O})}`});T||=await Q()}async function R(){T=await Q(),y=new(await import("@ledgerhq/hw-app-btc")).default({currency:L,transport:T})}return(O)=>{let G=typeof O==="string"?O:k0(O),X=l0(G);return{connect:async()=>{await w(!1),y=new(await import("@ledgerhq/hw-app-btc")).default({currency:L,transport:T})},getAddress:async()=>{let{toCashAddress:C}=await import("@swapkit/toolboxes/utxo");await w(!1);let{bitcoinAddress:B}=await y.getWalletPublicKey(G,{format:X});if(!B)throw new GL("wallet_ledger_get_address_error",{message:`Cannot get ${L} address from ledger derivation path: ${G}`});return L==="bitcoin-cash"&&X==="legacy"?C(B).replace(/(bchtest:|bitcoincash:)/,""):B},getExtendedPublicKey:async(C="84'/0'/0'",B=76067358)=>{return await w(!1),y.getWalletXpub({path:C,xpubVersion:B})},signPCZT:async(C)=>{if(L!=="zcash")throw new GL("wallet_ledger_chain_not_supported",{message:"PCZT signing is only supported for Zcash"});await R();let{ZcashTransaction:B,Script:D}=await import("@swapkit/utxo-signer"),W=C.getGlobal(),M=new B({consensusBranchId:W.consensusBranchId,expiryHeight:W.expiryHeight,lockTime:W.lockTime,version:W.txVersion,versionGroupId:W.versionGroupId}),Z=[];for(let j=0;j<C.inputsLength;j++){let A=C.getInput(j);M.addInput({index:A.index,script:new Uint8Array,sequence:A.sequence??4294967295,txid:A.txid,value:A.value}),Z.push({hash:CL.encode(new Uint8Array([...A.txid].reverse())),index:A.index,txHex:E0(A,W),value:Number(A.value),witnessUtxo:{script:A.scriptPubkey,value:Number(A.value)}})}for(let j=0;j<C.outputsLength;j++){let A=C.getOutput(j);M.addOutput({amount:A.value,script:A.scriptPubkey})}let f=await pL({btcApp:y,chain:L,derivationPath:G,inputUtxos:Z,tx:M},{..._,expiryHeight:(()=>{let j=Buffer.alloc(4);return j.writeUInt32LE(W.expiryHeight),j})(),lockTime:W.lockTime}),J=B.fromHex(f,{allowUnknownOutputs:!0}),U=C.clone();for(let j=0;j<J.inputsLength;j++){let A=J.getInput(j);if(A.script&&A.script.length>0){let H=D.decode(A.script);if(H.length>=2)U.addSignature(j,H[1],H[0])}}return U},signTransaction:async(C,B)=>{return await R(),pL({btcApp:y,chain:L,derivationPath:G,inputUtxos:B,tx:C},_)},signTransactionWithMultiplePaths:async(C,B,D)=>{return await R(),V0({btcApp:y,chain:L,derivationPaths:D,inputUtxos:B,tx:C},_)}}}};function E0(L,_){let y=[],T=(_.txVersion|2147483648)>>>0;y.push(T&255,T>>8&255,T>>16&255,T>>24&255);let w=_.versionGroupId;y.push(w&255,w>>8&255,w>>16&255,w>>24&255),y.push(0);let R=L.index+1;if(R<253)y.push(R);else y.push(253,R&255,R>>8&255);for(let X=0;X<L.index;X++)y.push(0,0,0,0,0,0,0,0),y.push(0);let O=L.value;y.push(Number(O&0xffn),Number(O>>8n&0xffn),Number(O>>16n&0xffn),Number(O>>24n&0xffn),Number(O>>32n&0xffn),Number(O>>40n&0xffn),Number(O>>48n&0xffn),Number(O>>56n&0xffn));let G=L.scriptPubkey;if(G.length<253)y.push(G.length);else y.push(253,G.length&255,G.length>>8&255);for(let X of G)y.push(X);return y.push(_.lockTime&255,_.lockTime>>8&255,_.lockTime>>16&255,_.lockTime>>24&255),y.push(_.expiryHeight&255,_.expiryHeight>>8&255,_.expiryHeight>>16&255,_.expiryHeight>>24&255),y.push(0,0,0,0,0,0,0,0),y.push(0),y.push(0),y.push(0),CL.encode(new Uint8Array(y))}var rL=x({chain:"bitcoin"}),sL=x({chain:"litecoin"}),L0=x({additionalSignParams:{additionals:["abc"],segwit:!1,sigHashType:65},chain:"bitcoin-cash"}),_0=x({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dogecoin"}),y0=x({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dash"}),w0=x({additionalSignParams:{additionals:["zcash","sapling"],expiryHeight:(()=>{let L=Buffer.alloc(4);return L.writeUInt32LE(0),L})(),lockTime:0,segwit:!1,useTrustedInputForSegwit:!1},chain:"zcash"});import I0 from"@ledgerhq/hw-app-xrp";import{Chain as v0,derivationPathToString as h0,NetworkDerivationPath as o0}from"@swapkit/helpers";import{encode as T0}from"ripple-binary-codec";var d0=2147483648;function b0(L){let _={};for(let y in L)if(L[y]!==null&&L[y]!==void 0)_[y]=L[y];return _}function x0(L){return new I0(L)}var m0=async(L)=>{let _=h0(L||o0[v0.Ripple]),y=await Q(),T=x0(y),{address:w,publicKey:R}=await T.getAddress(_);async function O(G){let{hashes:X}=await import("@swapkit/toolboxes/ripple"),B={...b0(G),Flags:G.Flags||d0,SigningPubKey:R.toUpperCase()},D=T0(B),W=await T.signTransaction(_,D),M=T0({...B,TxnSignature:W});return{hash:X.hashSignedTx(M),tx_blob:M}}return{getAddress:()=>w,signTransaction:O}};var S=async({chain:L,derivationPath:_})=>{let{match:y}=await import("ts-pattern");return y(L).returnType().with(F.THORChain,()=>Promise.resolve(new UL(_))).with(F.Cosmos,()=>Promise.resolve(new $L(_))).with(F.Bitcoin,()=>Promise.resolve(rL(_))).with(F.BitcoinCash,()=>Promise.resolve(L0(_))).with(F.Dash,()=>Promise.resolve(y0(_))).with(F.Dogecoin,()=>Promise.resolve(_0(_))).with(F.Litecoin,()=>Promise.resolve(sL(_))).with(F.Zcash,()=>Promise.resolve(w0(_))).with(F.Ripple,()=>Promise.resolve(m0(_))).with(F.Tron,()=>Promise.resolve(eL(_))).with(F.Sui,()=>Promise.resolve(nL(_))).with(F.Near,()=>{return Promise.resolve(xL(_))}).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:_,provider:await T(L)};return y(L).with(F.BinanceSmartChain,()=>hL(w)).with(F.Avalanche,()=>kL(w)).with(F.Arbitrum,()=>KL(w)).with(F.Berachain,()=>bL(w)).with(F.Optimism,()=>IL(w)).with(F.Polygon,()=>vL(w)).with(F.Base,()=>lL(w)).with(F.Aurora,()=>gL(w)).with(F.Gnosis,()=>EL(w)).with(F.Monad,()=>oL(w)).with(F.XLayer,()=>dL(w)).otherwise(()=>VL(w))}).otherwise(()=>{throw new i0("wallet_chain_not_supported",{chain:L,wallet:n0.LEDGER})})};var w_=__({connect:({addChain:L,supportedChains:_,walletType:y})=>async function(w,R){let[O]=t0({chains:w,supportedChains:_,walletType:y});if(!O)return!1;let G=R??u0[O],X=await R_({chain:O,derivationPath:G});return L({...X,chain:O,walletType:G0.LEDGER}),!0},directSigningSupport:{[m.Arbitrum]:!0,[m.Aurora]:!0,[m.Avalanche]:!0,[m.Base]:!0,[m.Berachain]:!0,[m.BinanceSmartChain]:!0,[m.Ethereum]:!0,[m.Gnosis]:!0,[m.Monad]:!0,[m.Bitcoin]:!0,[m.BitcoinCash]:!0,[m.Cosmos]:!0,[m.Dash]:!0,[m.Dogecoin]:!0,[m.Litecoin]:!0,[m.Near]:!0,[m.Optimism]:!0,[m.Polygon]:!0,[m.Ripple]:!0,[m.Sui]:!0,[m.Tron]:!0,[m.XLayer]:!0},name:"connectLedger",supportedChains:[m.Arbitrum,m.Aurora,m.Avalanche,m.Base,m.Berachain,m.BinanceSmartChain,m.Bitcoin,m.BitcoinCash,m.Cosmos,m.Dash,m.Dogecoin,m.Ethereum,m.Gnosis,m.Litecoin,m.Monad,m.Near,m.Optimism,m.Polygon,m.Ripple,m.Sui,m.THORChain,m.XLayer,m.Tron,m.Zcash],walletType:G0.LEDGER}),Ay=y_(w_);function T_(L,_="t"){if(!L?.includes("=:"))return L;let y=L.includes(`:${_}:`)?L.split(`:${_}:`)[0]:L;return y?.substring(0,y.lastIndexOf(":"))}function BL(L){if(Array.isArray(L))return L.forEach((T,w)=>{L[w]=BL(T)}),L;if(typeof L!=="object")return L;let _={},y=Object.keys(L).sort();for(let T of y)_[T]=BL(L[T]);return _}function m_(L){return JSON.stringify(BL(L))}async function R_({chain:L,derivationPath:_}){switch(L){case m.BitcoinCash:case m.Bitcoin:case m.Dash:case m.Dogecoin:case m.Litecoin:case m.Zcash:{let B=function(){return C()},{getUtxoToolbox:y}=await import("@swapkit/toolboxes/utxo"),T=L,w=await S({chain:L,derivationPath:_}),R=await K({chain:L,ledgerClient:w}),O;if(L===m.Bitcoin||L===m.Litecoin){let{BitcoinPsbtLedger:f,LitecoinPsbtLedger:J}=await import("../chunk-3zf2pqfd.js"),U=L===m.Bitcoin?f(_):J(_);O={getAddress:U.getAddress,signTransaction:U.signTransaction}}else if(L===m.BitcoinCash||L===m.Dogecoin||L===m.Dash){let{createLegacyPsbtSigner:f}=await import("../chunk-px09mwnt.js");O=f({address:R,chain:T,legacyClient:w})}let G=O?await y(T,{signer:O}):y(T),X=async(f)=>{let J=f.feeRate||(await G.getFeeRates())[R0.Average],U=[m.Bitcoin].includes(L)?f.memo:T_(f.memo),{tx:j,inputs:A}=await G.createTransaction({...f,feeRate:J,fetchTxHex:!0,memo:U,sender:R}),H=await w.signTransaction(j,A);return await G.broadcastTx(H)};async function C({accountIndex:f}={}){if(!w.getExtendedPublicKey)return;let J=X0({accountIndex:f,chain:T,derivationPath:_}),U=ZL(J),j=L===m.Bitcoin||L===m.Litecoin?U:U.replace(/^m\//,""),A=await w.getExtendedPublicKey(j);return{accountIndex:B0(J),path:U,xpub:A}}async function D({accountIndex:f,index:J,change:U=!1}){try{let j=s0({accountIndex:f,chain:T,change:U,derivationPath:_,index:J}),A=await S({chain:T,derivationPath:j}),H=await K({chain:T,ledgerClient:A});return{accountIndex:B0(j),address:H,change:U,index:J,path:ZL(j),pubkey:""}}catch{return}}async function W({accountIndex:f,count:J,startIndex:U=0,change:j=!1}){return C0("count",J),C0("startIndex",U),(await Promise.all(Array.from({length:J},(H,E)=>D({accountIndex:f,change:j,index:U+E})))).filter((H)=>!!H)}let M=r0({chain:T,deriveAddress:D,getBalance:G.getBalance,getUtxos:(f)=>L_(T).getUtxos({address:f,fetchTxHex:!0})});async function Z({utxos:f,recipient:J,assetValue:U,memo:j,feeRate:A,feeOptionKey:H,changeAddress:E}){if(!f.length)throw new l("wallet_ledger_invalid_params",{message:"No UTXOs provided for multi-address transfer"});let ML=A||(await G.getFeeRates())[H||R0.Fast],_L=j?a0(j):null,P=[{address:J,value:U.getBaseValue("number")}];if(_L)P.push({script:_L,value:0});let yL=f.map(({hash:h,index:o,value:u,txHex:e,witnessUtxo:p})=>({hash:h,index:o,txHex:e,value:u,witnessUtxo:p})),{inputs:v,outputs:i}=G.accumulative({chain:T,feeRate:ML,inputs:yL,outputs:P});if(!(v&&i))throw new l("wallet_ledger_connection_error",{message:"Insufficient balance for multi-address transfer"});let{Transaction:XL}=await import("@swapkit/utxo-signer"),wL=new XL({allowLegacyWitnessUtxo:!0,version:1}),n=E||f[0]?.address||J;p0({chain:T,compiledMemo:_L,inputs:v,outputs:i,sender:n,tx:wL});let TL=X0({chain:T,derivationPath:_}),NL=v.map((h)=>{let o=f.find((mL)=>mL.hash===h.hash&&mL.index===h.index),u=o?.derivationIndex??0,e=o?.isChange??!1,p=[...TL,Number(e),u];return ZL(p)});if(!w.signTransactionWithMultiplePaths)throw new l("wallet_ledger_method_not_supported",{method:"signTransactionWithMultiplePaths"});let t=await w.signTransactionWithMultiplePaths(wL,v,NL);return G.broadcastTx(t)}return{...G,...M,address:R,deriveAddressAtIndex:D,deriveAddresses:W,getExtendedPublicKey:B,getExtendedPublicKeyInfo:C,transfer:X,transferFromMultipleAddresses:Z}}case m.Ethereum:case m.Avalanche:case m.Arbitrum:case m.Berachain:case m.Optimism:case m.Polygon:case m.BinanceSmartChain:case m.Base:case m.Aurora:case m.Gnosis:case m.Monad:case m.XLayer:{let{getEvmToolboxAsync:y}=await import("@swapkit/toolboxes/evm"),T=await S({chain:L,derivationPath:_}),w=await K({chain:L,ledgerClient:T});return{...await y(L,{signer:T}),address:w}}case m.Cosmos:{let{createSigningStargateClient:y,getMsgSendDenom:T,getCosmosToolbox:w}=await import("@swapkit/toolboxes/cosmos"),R=await S({chain:L,derivationPath:_}),O=await K({chain:L,ledgerClient:R});return{...await w(m.Cosmos,{signer:R}),address:O,transfer:async({assetValue:C,recipient:B,memo:D})=>{if(!C)throw new l("wallet_ledger_invalid_asset");let W={amount:[{amount:C.getBaseValue("string"),denom:T(`u${C.symbol}`).toLowerCase()}],fromAddress:O,toAddress:B},M=await O0(L),Z=await y(M,R,"0.007uatom"),{transactionHash:f}=await Z.signAndBroadcast(O,[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:W}],2,D);return f}}}case m.THORChain:{let{SignMode:y}=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"),R=w.encodePubkey??w.default?.encodePubkey,O=w.makeAuthInfoBytes??w.default?.makeAuthInfoBytes,{createStargateClient:G,buildEncodedTxBody:X,getCosmosToolbox:C,buildAminoMsg:B,getDefaultChainFee:D,fromBase64:W,parseAminoMessageForDirectSigning:M}=await import("@swapkit/toolboxes/cosmos"),Z=C(L),f=await S({chain:L,derivationPath:_}),J=await K({chain:L,ledgerClient:f}),U=D(L),{pubkey:j,signTransaction:A,sign:H}=f,E=async({memo:P="",assetValue:yL,...v})=>{let i=await Z.getAccount(J);if(!i)throw new l("wallet_ledger_invalid_account");if(!yL)throw new l("wallet_ledger_invalid_asset");if(!j)throw new l("wallet_ledger_pubkey_not_found");let{accountNumber:XL,sequence:wL}=i,n=(wL||0).toString(),TL=BL([B({assetValue:yL,memo:P,sender:J,...v})]),NL=m_({account_number:XL?.toString(),chain_id:e0.chainId,fee:U,memo:P,msgs:TL,sequence:n}),t=await A(NL,n);if(!t)throw new l("wallet_ledger_signing_error");let h=R({type:"tendermint/PubKeySecp256k1",value:j}),o=TL.map(M),u=await X({chain:L,memo:P,msgs:o}),e=O([{pubkey:h,sequence:Number(n)}],U.amount,Number.parseInt(U.gas,10),void 0,void 0,y.SIGN_MODE_LEGACY_AMINO_JSON),p=t?.[0]?.signature?W(t[0].signature):Uint8Array.from([]),mL=T.fromPartial({authInfoBytes:e,bodyBytes:u,signatures:[p]}),N0=T.encode(mL).finish(),D0=await O0(m.THORChain),F0=await G(D0),{transactionHash:f0}=await F0.broadcastTx(N0);return f0};return{...Z,address:J,deposit:(P)=>E(P),signMessage:H,transfer:(P)=>E(P)}}case m.Near:{let{getNearToolbox:y}=await import("@swapkit/toolboxes/near"),T=await S({chain:L,derivationPath:_}),w=await T.getAddress();return{...y({signer:T}),address:w}}case m.Ripple:{let{getRippleToolbox:y}=await import("@swapkit/toolboxes/ripple"),T=await S({chain:L,derivationPath:_}),w=T.getAddress();return{...y({signer:T}),address:w}}case m.Tron:{let{getTronToolbox:y}=await import("@swapkit/toolboxes/tron"),T=await S({chain:L,derivationPath:_}),w=await K({chain:L,ledgerClient:T});return{...y({signer:T}),address:w}}case m.Sui:{let{getSuiToolbox:y}=await import("@swapkit/toolboxes/sui"),T=await S({chain:L,derivationPath:_}),w=await K({chain:L,ledgerClient:T});return{...y({signer:T}),address:w}}default:throw new l("wallet_ledger_chain_not_supported",{chain:L})}}export{w_ as ledgerWallet,Ay as LEDGER_SUPPORTED_CHAINS};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=DD30327A4ECB812364756E2164756E21
|
|
5
5
|
//# sourceMappingURL=index.js.map
|