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