@swapkit/wallet-hardware 4.2.10 → 4.6.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.
Files changed (96) hide show
  1. package/dist/LICENSE +246 -0
  2. package/dist/{chunk-7fsaymh4.js → chunk-1jexf7qt.js} +3 -3
  3. package/dist/{chunk-7fsaymh4.js.map → chunk-1jexf7qt.js.map} +1 -1
  4. package/dist/chunk-1jpcb30j.js +5 -0
  5. package/dist/{chunk-fazw0jvt.js.map → chunk-1jpcb30j.js.map} +1 -1
  6. package/dist/chunk-4fapcrj9.js +5 -0
  7. package/dist/chunk-4fapcrj9.js.map +10 -0
  8. package/dist/chunk-d54qkn5p.js +4 -0
  9. package/dist/chunk-d54qkn5p.js.map +10 -0
  10. package/dist/chunk-jj2v7mke.js +4 -0
  11. package/dist/chunk-jj2v7mke.js.map +10 -0
  12. package/dist/chunk-p94hfx8x.js +4 -0
  13. package/dist/{chunk-zzfbcc7e.js.map → chunk-p94hfx8x.js.map} +1 -1
  14. package/dist/chunk-skvfn1dg.js +4 -0
  15. package/dist/chunk-skvfn1dg.js.map +10 -0
  16. package/dist/{chunk-37bgpz1y.js → chunk-ybje7f3s.js} +3 -3
  17. package/dist/{chunk-37bgpz1y.js.map → chunk-ybje7f3s.js.map} +1 -1
  18. package/dist/keepkey/index.cjs +2 -2
  19. package/dist/keepkey/index.cjs.map +5 -5
  20. package/dist/keepkey/index.js +2 -2
  21. package/dist/keepkey/index.js.map +5 -5
  22. package/dist/ledger/index.cjs +3 -3
  23. package/dist/ledger/index.cjs.map +11 -10
  24. package/dist/ledger/index.js +3 -3
  25. package/dist/ledger/index.js.map +11 -10
  26. package/dist/trezor/index.cjs +2 -2
  27. package/dist/trezor/index.cjs.map +3 -3
  28. package/dist/trezor/index.js +2 -2
  29. package/dist/trezor/index.js.map +3 -3
  30. package/dist/types/core.d.ts +18 -0
  31. package/dist/types/core.d.ts.map +1 -0
  32. package/dist/types/keepkey/chains/evm.d.ts +2 -2
  33. package/dist/types/keepkey/chains/evm.d.ts.map +1 -1
  34. package/dist/types/keepkey/chains/ripple.d.ts +15 -8
  35. package/dist/types/keepkey/chains/ripple.d.ts.map +1 -1
  36. package/dist/types/keepkey/chains/utxo.d.ts +331 -5
  37. package/dist/types/keepkey/chains/utxo.d.ts.map +1 -1
  38. package/dist/types/keepkey/index.d.ts +3 -3
  39. package/dist/types/keepkey/index.d.ts.map +1 -1
  40. package/dist/types/ledger/clients/evm.d.ts +3 -2
  41. package/dist/types/ledger/clients/evm.d.ts.map +1 -1
  42. package/dist/types/ledger/clients/sui.d.ts +27 -0
  43. package/dist/types/ledger/clients/sui.d.ts.map +1 -0
  44. package/dist/types/ledger/clients/thorchain/lib.d.ts.map +1 -1
  45. package/dist/types/ledger/clients/utxo.d.ts +43 -7
  46. package/dist/types/ledger/clients/utxo.d.ts.map +1 -1
  47. package/dist/types/ledger/clients/xrp.d.ts +2 -2
  48. package/dist/types/ledger/clients/xrp.d.ts.map +1 -1
  49. package/dist/types/ledger/helpers/getLedgerAddress.d.ts.map +1 -1
  50. package/dist/types/ledger/helpers/getLedgerClient.d.ts +4 -1
  51. package/dist/types/ledger/helpers/getLedgerClient.d.ts.map +1 -1
  52. package/dist/types/ledger/index.d.ts +3 -3
  53. package/dist/types/ledger/index.d.ts.map +1 -1
  54. package/dist/types/ledger/types.d.ts +2 -0
  55. package/dist/types/ledger/types.d.ts.map +1 -1
  56. package/dist/types/trezor/evmSigner.d.ts +2 -2
  57. package/dist/types/trezor/evmSigner.d.ts.map +1 -1
  58. package/dist/types/trezor/index.d.ts +3 -3
  59. package/dist/types/trezor/index.d.ts.map +1 -1
  60. package/package.json +51 -40
  61. package/dist/chunk-4k7gb7ss.js +0 -4
  62. package/dist/chunk-4k7gb7ss.js.map +0 -10
  63. package/dist/chunk-93cj7bky.js +0 -4
  64. package/dist/chunk-93cj7bky.js.map +0 -10
  65. package/dist/chunk-fazw0jvt.js +0 -4
  66. package/dist/chunk-zzfbcc7e.js +0 -5
  67. package/src/index.ts +0 -1
  68. package/src/keepkey/chains/cosmos.ts +0 -69
  69. package/src/keepkey/chains/evm.ts +0 -114
  70. package/src/keepkey/chains/mayachain.ts +0 -98
  71. package/src/keepkey/chains/ripple.ts +0 -88
  72. package/src/keepkey/chains/thorchain.ts +0 -93
  73. package/src/keepkey/chains/utxo.ts +0 -137
  74. package/src/keepkey/coins.ts +0 -67
  75. package/src/keepkey/index.ts +0 -155
  76. package/src/ledger/clients/cosmos.ts +0 -84
  77. package/src/ledger/clients/evm.ts +0 -141
  78. package/src/ledger/clients/near.ts +0 -63
  79. package/src/ledger/clients/thorchain/common.ts +0 -93
  80. package/src/ledger/clients/thorchain/helpers.ts +0 -120
  81. package/src/ledger/clients/thorchain/index.ts +0 -87
  82. package/src/ledger/clients/thorchain/lib.ts +0 -278
  83. package/src/ledger/clients/thorchain/utils.ts +0 -69
  84. package/src/ledger/clients/tron.ts +0 -85
  85. package/src/ledger/clients/utxo.ts +0 -154
  86. package/src/ledger/clients/xrp.ts +0 -50
  87. package/src/ledger/cosmosTypes.ts +0 -98
  88. package/src/ledger/helpers/getLedgerAddress.ts +0 -69
  89. package/src/ledger/helpers/getLedgerClient.ts +0 -117
  90. package/src/ledger/helpers/getLedgerTransport.ts +0 -102
  91. package/src/ledger/helpers/index.ts +0 -3
  92. package/src/ledger/index.ts +0 -299
  93. package/src/ledger/interfaces/CosmosLedgerInterface.ts +0 -54
  94. package/src/ledger/types.ts +0 -40
  95. package/src/trezor/evmSigner.ts +0 -177
  96. package/src/trezor/index.ts +0 -349
@@ -1,5 +1,5 @@
1
- import{c as B,d as N}from"../chunk-zzfbcc7e.js";import{Chain as O,FeeOption as cy,filterSupportedChains as Sy,getRPCUrl as bL,SwapKitError as S,THORConfig as oy,WalletOption as dL}from"@swapkit/helpers";import{createWallet as Ky,getWalletSupportedChains as ny}from"@swapkit/wallet-core";import{Chain as j,SwapKitError as wy,WalletOption as ly}from"@swapkit/helpers";var H=async({chain:L,ledgerClient:y})=>{if(!y)return"";switch(L){case j.Cosmos:case j.THORChain:return y.connect();case j.Ethereum:case j.BinanceSmartChain:case j.Avalanche:case j.Polygon:case j.Arbitrum:case j.Optimism:case j.Base:case j.Aurora:case j.Gnosis:case j.XLayer:return y.getAddress();case j.Bitcoin:case j.BitcoinCash:case j.Dash:case j.Dogecoin:case j.Litecoin:case j.Zcash:{let _=y;await _.connect();let T=await _.getAddress();return L===j.BitcoinCash?T.replace("bitcoincash:",""):T}case j.Near:return await y.getAddress();case j.Ripple:return y.getAddress();case j.Tron:return y.getAddress();default:throw new wy("wallet_chain_not_supported",{chain:L,wallet:ly.LEDGER})}};import{Chain as C,SwapKitError as zy,WalletOption as qy}from"@swapkit/helpers";import{derivationPathToString as Xy,NetworkDerivationPath as By,SwapKitError as jL}from"@swapkit/helpers";import{LedgerErrorCode as s,NetworkDerivationPath as Gy,SwapKitError as LL}from"@swapkit/helpers";import{SwapKitError as FL}from"@swapkit/helpers";var z=85,u=250;var P={GET_ADDR_SECP256K1:4,GET_VERSION:0,INS_PUBLIC_KEY_SECP256K1:1,SIGN_SECP256K1:2},d={ADD:1,INIT:0,LAST:2},p={ONLY_RETRIEVE:0,SHOW_ADDRESS_IN_DEVICE:1},q={JSON:0},Y={NoError:36864},RL={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 W(L){if(L in RL)return RL[L];return`Unknown Status Code: ${L}`}function gy(L){return typeof L==="object"&&L!==null&&!Array.isArray(L)&&!(L instanceof Date)}function A(L){if(L){if(gy(L)){if(Object.hasOwn(L,"statusCode"))return{error_message:W(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 a(L){return L.send(85,P.GET_VERSION,0,0).then((y)=>{let _=y.slice(-2),T=_[0]*256+_[1],m=0;if(y.length>=9)m=(y[5]<<24)+(y[6]<<16)+(y[7]<<8)+(y[8]<<0);return{device_locked:y[4]===1,error_message:W(T),major:y[1],minor:y[2],patch:y[3],return_code:T,target_id:m.toString(16),test_mode:y[0]!==0}},A)}import{SwapKitError as V}from"@swapkit/helpers";function GL(L){if(L==null||L.length<3)throw new V("wallet_ledger_invalid_params",{reason:"Path too short"});if(L.length>10)throw new V("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 T=L[_]||0;if(_<3)T|=2147483648;y.writeInt32LE(T,1+_*4)}return y}function e(L,y,_,T,m=q.JSON){return L.transport.send(z,P.SIGN_SECP256K1,y,m,T,[Y.NoError,27012,27264]).then((w)=>{let g=w.slice(-2),l=g[0]*256+g[1],G=W(l);if(l===27264||l===27012)G=`${G} : ${w.slice(0,w.length-2).toString("ascii")}`;let X=null;if(w.length>2)X=w.slice(0,w.length-2);return{error_message:G,return_code:l,signature:X}},A)}function Oy(L){if(L.length!==65)throw new V("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 XL(L,y){return L.transport.send(z,P.INS_PUBLIC_KEY_SECP256K1,0,0,y,[Y.NoError]).then((_)=>{let T=_.slice(-2),m=T[0]*256+T[1],w=Buffer.from(_.slice(0,65));return{compressed_pk:Oy(w),error_message:W(m),pk:w,return_code:m}},A)}function BL(L){if(!L||L.length!==5)throw new V("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 NL(L,y,_,T,m=q.JSON){let w=d.ADD;if(y===1)w=d.INIT;if(y===_)w=d.LAST;return e(L,w,0,T,m)}function CL(L,y){return L.transport.send(z,P.GET_ADDR_SECP256K1,0,0,y,[Y.NoError]).then((_)=>{let T=_.slice(-2),m=T[0]*256+T[1];return{compressed_pk:Buffer.from(_.slice(0,33)),error_message:W(m),pk:"OBSOLETE PROPERTY",return_code:m}},A)}class K{transport;versionResponse;constructor(L){if(!L)throw new FL("wallet_ledger_transport_not_defined");this.transport=L}static serializeHRP(L){if(L==null||L.length<3||L.length>83)throw new FL("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 a(this.transport),this.versionResponse.return_code!==Y.NoError)throw this.versionResponse;switch(this.versionResponse.major){case 1:return GL(L);case 2:return BL(L);default:return Buffer.alloc(0)}}async signGetChunks(L,y){let _=await this.serializePath(L),T=[];T.push(_);for(let m=0;m<y.length;m+=u){let w=m+u;if(m>y.length)w=y.length;T.push(y.slice(m,w))}return T}async getVersion(){try{return this.versionResponse=await a(this.transport),this.versionResponse}catch(L){return A(L)}}appInfo(){return this.transport.send(176,1,0,0).then((L)=>{let y=L.slice(-2),_=y[0]*256+y[1],T="",m="",w=0,g=0;if(L[0]!==1)return{error_message:"response format ID not recognized",return_code:36865};let l=L[1];T=L.slice(2,2+l).toString("ascii");let G=2+l,X=L[G];G+=1,m=L.slice(G,G+X).toString("ascii"),G+=X;let R=L[G];return G+=1,w=R,g=L[G],{appName:T,appVersion:m,error_message:W(_),flag_onboarded:(g&4)!==0,flag_pin_validated:(g&128)!==0,flag_recovery:(g&1)!==0,flag_signed_mcu_code:(g&2)!==0,flagLen:w,flagsValue:g,return_code:_}},A)}deviceInfo(){return this.transport.send(224,1,0,0,Buffer.from([]),[Y.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 T=L.slice(0,4).toString("hex"),m=4,w=L[m];m+=1;let g=L.slice(m,m+w).toString();m+=w;let l=L[m];m+=1;let G=L.slice(m,m+l).toString("hex");m+=l;let X=L[m];m+=1;let R=L.slice(m,m+X);if(R[X-1]===0)R=L.slice(m,m+X-1);let F=R.toString();return{error_message:W(_),flag:G,mcuVersion:F,return_code:_,seVersion:g,targetId:T}},A)}async publicKey(L){try{let y=await this.serializePath(L);switch(this.versionResponse.major){case 1:return XL(this,y);case 2:{let _=Buffer.concat([K.serializeHRP("thor"),y]);return CL(this,_)}default:return{error_message:"App Version is not supported",return_code:25600}}}catch(y){return A(y)}}getAddressAndPubKey(L,y,_=!1){return this.serializePath(L).then((T)=>{let m=Buffer.concat([K.serializeHRP(y),T]);return this.transport.send(z,P.GET_ADDR_SECP256K1,_?p.SHOW_ADDRESS_IN_DEVICE:p.ONLY_RETRIEVE,0,m,[Y.NoError]).then((w)=>{let g=w.slice(-2),l=g[0]*256+g[1],G=Buffer.from(w.slice(0,33));return{bech32_address:Buffer.from(w.slice(33,-2)).toString(),compressed_pk:G,error_message:W(l),return_code:l}},A)}).catch((T)=>A(T))}showAddressAndPubKey(L,y){return this.getAddressAndPubKey(L,y,!0)}signSendChunk(L,y,_,T=q.JSON){switch(this.versionResponse.major){case 1:return e(this,L,y,_,T);case 2:return NL(this,L,y,_,T);default:return{error_message:"App Version is not supported",return_code:25600}}}async sign(L,y,_=q.JSON){let T=Buffer.from(y),m=[],w;try{m=await this.signGetChunks(L,T),w=await this.signSendChunk(1,m.length,m[0],_)}catch(l){A(l)}let g={error_message:w.error_message,return_code:w.return_code,signature:null};for(let l=1;l<m.length;l+=1)if(g=await this.signSendChunk(1+l,m.length,m[l],_),g.return_code!==Y.NoError)break;return{error_message:g.error_message,return_code:g.return_code,signature:g.signature}}}import{SwapKitError as n}from"@swapkit/helpers";var r=()=>navigator?.usb,Ry=async()=>{let L=r();if(typeof L?.getDevices!=="function")return{};let{ledgerUSBVendorId:y}=await import("@ledgerhq/devices"),T=(await L?.getDevices()).filter((m)=>m.vendorId===y);if(T.length>0)return T[0];return L?.requestDevice({filters:[{vendorId:y}]})},M=async()=>{let L=await Ry();if(!L)throw new n("wallet_ledger_device_not_found");if(L.opened||await L.open(),L.configuration===null)await L.selectConfiguration(1);try{await L.reset()}catch{}let y=L.configuration??L.configurations?.[0],_=y?.interfaces.find(({alternates:R})=>R.some(({interfaceClass:F})=>F===255))||y?.interfaces.find(({alternates:R})=>R.some(({interfaceClass:F})=>F===3));if(!_)throw await L.close(),new n("wallet_ledger_connection_error");let T=_.alternates?.find(({interfaceClass:R})=>R===3)?.interfaceClass,m=_.alternates?.find(({interfaceClass:R})=>R===255)?.interfaceClass;if(T&&!m){let R=(await import("@ledgerhq/hw-transport-webhid")).default;if(!await R.isSupported())throw await L.close(),new n("wallet_ledger_webhid_not_supported");return await R.create()}try{await L.claimInterface(_.interfaceNumber)}catch(R){throw await L.close(),new n("wallet_ledger_connection_claimed",R)}let w=(await import("@ledgerhq/hw-transport-webusb")).default;if(!await w.isSupported())throw new n("wallet_ledger_webusb_not_supported");let{DisconnectedDevice:l}=await import("@ledgerhq/errors"),G=new w(L,_.interfaceNumber),X=(R)=>{if(L===R.device)r()?.removeEventListener("disconnect",X),G._emitDisconnect(new l)};return r()?.addEventListener("disconnect",X),G};class k{ledgerTimeout=50000;derivationPath=Gy.GAIA;transport;ledgerApp;chain="thor";checkOrCreateTransportAndLedger=async(L=!1)=>{if(!L&&this.transport&&this.ledgerApp)return;try{switch(this.transport=L||!this.transport?await M():this.transport,this.chain){case"thor":{this.ledgerApp=L||!this.ledgerApp?new K(this.transport):this.ledgerApp;break}case"cosmos":{let y=(await import("@ledgerhq/hw-app-cosmos")).default;this.ledgerApp=L||!this.ledgerApp?new y(this.transport):this.ledgerApp}}return this.ledgerApp}catch(y){throw new LL("wallet_ledger_connection_error",y)}};validateResponse=(L,y)=>{switch(L){case s.NoError:return;case s.LockedDevice:throw new LL("wallet_ledger_device_locked",{message:`Ledger is locked: ${y}`});case s.TC_NotFound:throw new LL("wallet_ledger_device_not_found");default:break}}}class yL extends k{pubKey=null;derivationPath;constructor(L=By.GAIA){super();this.chain="cosmos",this.derivationPath=Xy(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:T,signature:m}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new jL("wallet_ledger_pubkey_not_found");return this.validateResponse(_,T),[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:y,signature:m}]};signAmino=async(L,y)=>{await this.checkOrCreateTransportAndLedger(!0);let _=await this.getAccounts();if(_.findIndex((i)=>i.address===L)===-1)throw new jL("wallet_ledger_address_not_found",{address:L});let m=await import("@cosmjs/amino"),w=m.encodeSecp256k1Signature??m.default?.encodeSecp256k1Signature,g=m.serializeSignDoc??m.default?.serializeSignDoc,l=await import("@cosmjs/crypto"),G=l.Secp256k1Signature??l.default?.Secp256k1Signature,X=g(y),R=await this.ledgerApp.sign(this.derivationPath,X);this.validateResponse(R.return_code,R.error_message);let F=G.fromDer(R.signature).toFixedLength();return{signature:w(_[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 Z,derivationPathToString as Ny,NetworkDerivationPath as Cy,SwapKitError as E}from"@swapkit/helpers";import{AbstractSigner as Fy}from"ethers";class $ extends Fy{chainId=Z.Ethereum;derivationPath="";ledgerApp=null;ledgerTimeout=50000;constructor({provider:L,derivationPath:y=Cy.OP,chainId:_=Z.Optimism}){super(L);this.chainId=_||Z.Ethereum,this.derivationPath=typeof y==="string"?y:Ny(y),Object.defineProperty(this,"provider",{enumerable:!0,value:L||null,writable:!1})}connect=(L)=>new $({chainId:this.chainId,derivationPath:this.derivationPath,provider:L});checkOrCreateTransportAndLedger=async()=>{if(this.ledgerApp)return;await this.createTransportAndLedger()};createTransportAndLedger=async()=>{let L=await M(),y=(await import("@ledgerhq/hw-app-eth")).default;this.ledgerApp=new y(L)};getAddress=async()=>{let L=await this.getAddressAndPubKey();if(!L)throw new E("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 E("wallet_ledger_signing_error");return _.r=`0x${_.r}`,_.s=`0x${_.s}`,y.from(_).serialized};sendTransaction=async(L)=>{if(!this.provider)throw new E("wallet_ledger_no_provider");let y=await this.signTransaction(L);return await this.provider.broadcastTransaction(y)};signTypedData(){throw new E("wallet_ledger_method_not_supported",{method:"signTypedData"})}signTransaction=async(L)=>{let{Transaction:y}=await import("ethers");await this.createTransportAndLedger();let _=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||_||0).toString()):_,to:L.to?.toString(),type:L.type&&!Number.isNaN(L.type)?L.type:L.maxFeePerGas?2:0,value:L.value},m=y.from(T).unsignedSerialized.slice(2),{ledgerService:w}=await import("@ledgerhq/hw-app-eth"),g=await w.resolveTransaction(m,{},{erc20:!0,externalPlugins:!0}),l=await this.ledgerApp?.signTransaction(this.derivationPath,m,g);if(!l)throw new E("wallet_ledger_signing_error");let{r:G,s:X,v:R}=l;return y.from({...T,signature:{r:`0x${G}`,s:`0x${X}`,v:Number(BigInt(R))}}).serialized}}var iL=(L)=>new $({...L,chainId:Z.Arbitrum}),ML=(L)=>new $({...L,chainId:Z.Aurora}),ZL=(L)=>new $({...L,chainId:Z.Avalanche}),AL=(L)=>new $({...L,chainId:Z.Base}),$L=(L)=>new $({...L,chainId:Z.Ethereum}),JL=(L)=>new $({...L,chainId:Z.Gnosis}),QL=(L)=>new $({...L,chainId:Z.Optimism}),WL=(L)=>new $({...L,chainId:Z.Polygon}),YL=(L)=>new $({...L,chainId:Z.BinanceSmartChain}),DL=(L)=>new $({...L,chainId:Z.Monad}),UL=(L)=>new $({...L,chainId:Z.XLayer});async function fL(L){let y=(await import("@ledgerhq/hw-app-near")).default,{Chain:_,NetworkDerivationPath:T,SwapKitError:m}=await import("@swapkit/helpers"),w=await M(),g=new y(w),l=(L||T[_.Near]).join("'/").concat("'"),{address:G,publicKey:X}=await g.getAddress(l);return{getAddress(){return Promise.resolve(G)},async getPublicKey(){let{PublicKey:F}=await import("@near-js/crypto");return F.fromString(`ed25519:${X}`)},signDelegateAction(F){return Promise.reject(new m("wallet_ledger_method_not_supported",{method:"signDelegateAction",wallet:"Ledger"}))},signNep413Message(F,i,Q,J,f){return Promise.reject(new m("wallet_ledger_method_not_supported",{method:"signNep413Message",wallet:"Ledger"}))},async signTransaction(F){let{Signature:i,SignedTransaction:Q}=await import("@near-js/transactions");try{let J=await g.signTransaction(F.encode(),l);if(!J)throw Error("Signature undefined");let f=new i({data:J,keyType:0}),o=new Q({signature:f,transaction:F});return[J,o]}catch(J){throw new m("wallet_ledger_signing_error",{error:J})}}}}import{base64 as iy}from"@scure/base";import{NetworkDerivationPath as My,SwapKitError as tL}from"@swapkit/helpers";import{base64 as jy}from"@scure/base";import{SwapKitError as D}from"@swapkit/helpers";var _L=(L)=>{if(L.length<64)throw new D("wallet_ledger_invalid_signature",{reason:"Too short"});if(L[0]!==48)throw new D("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected first byte 0x30"});if(L[1]+2!==L.length)throw new D("wallet_ledger_invalid_signature",{reason:"signature length does not match TLV"});if(L[2]!==2)throw new D("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 D("wallet_ledger_invalid_signature",{reason:"r too long"});while(_.length<32)_.unshift(0);if(L[y+4]!==2)throw new D("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected length type 0x02 for s"});let T=L[y+5];if(4+y+2+T!==L.length)throw new D("wallet_ledger_invalid_signature",{reason:"TLV byte lengths do not match message length"});let m=L.slice(y+6,L.length);if(m.length===33&&m[0]===0)m=m.slice(1,33);else if(m.length===33)throw new D("wallet_ledger_invalid_signature",{reason:"s too long"});while(m.length<32)m.unshift(0);if(_.length!==32||m.length!==32)throw new D("wallet_ledger_invalid_signature",{reason:"must be 32 bytes each"});return jy.encode(Buffer.concat([_,m]))};class mL extends k{pubKey=null;derivationPath;constructor(L=My.THOR){super();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=iy.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:T,signature:m}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new tL("wallet_ledger_pubkey_not_found");return this.validateResponse(_,T),[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:y,signature:_L(m)}]};sign=async(L)=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:y,error_message:_,signature:T}=await this.ledgerApp.sign(this.derivationPath,L);if(!this.pubKey)throw new tL("wallet_ledger_pubkey_not_found");return this.validateResponse(y,_),_L(T)}}import{derivationPathToString as Zy,NetworkDerivationPath as Ay,SwapKitError as b}from"@swapkit/helpers";class HL{derivationPath;ledgerApp=null;ledgerTimeout=50000;constructor(L){this.derivationPath=typeof L==="string"?L:Zy(L||Ay.TRON)}checkOrCreateTransportAndLedger=async()=>{if(this.ledgerApp)return;await this.createTransportAndLedger()};createTransportAndLedger=async()=>{let L=await M(),y=(await import("@ledgerhq/hw-app-trx")).default;this.ledgerApp=new y(L)};getAddress=async()=>{let L=await this.getAddressAndPubKey();if(!L)throw new b("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 b("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 b("wallet_ledger_transport_error");let y=JSON.stringify(L);try{let _=await this.ledgerApp.signTransaction(this.derivationPath,y,[]);if(!_)throw new b("wallet_ledger_signing_error");return{...L,signature:[_]}}catch(_){throw new b("wallet_ledger_signing_error",{error:_})}}}var PL=(L)=>new HL(L);import{derivationPathToString as $y,getWalletFormatFor as Jy,SwapKitError as zL}from"@swapkit/helpers";var Qy=["bitcoin-cash","dash","dogecoin","zcash"],Wy=({psbt:L,inputUtxos:y,btcApp:_,derivationPath:T,chain:m},w)=>{let g=y.map((F)=>{return[_.splitTransaction(F.txHex||"",!Qy.includes(m),m==="zcash"),F.index,void 0,void 0]}),l=L.data.globalMap.unsignedTx.toBuffer().toString("hex"),G=_.splitTransaction(l,!0),X=_.serializeTransactionOutputs(G).toString("hex"),R={additionals:["bech32"],associatedKeysets:g.map(()=>T),inputs:g,outputScriptHex:X,segwit:!0,useTrustedInputForSegwit:!0};return _.createPaymentTransaction({...R,...w})},c=({chain:L,additionalSignParams:y})=>{let _,T=null;async function m(g=!0){if(g&&!_)new zL("wallet_ledger_connection_error",{message:`Ledger connection failed:
2
- ${JSON.stringify({btcApp:_,checkBtcApp:g})}`});T||=await M()}async function w(){T=await M(),_=new(await import("@ledgerhq/hw-app-btc")).default({currency:L,transport:T})}return(g)=>{let l=typeof g==="string"?g:$y(g),G=Jy(l);return{connect:async()=>{await m(!1),_=new(await import("@ledgerhq/hw-app-btc")).default({currency:L,transport:T})},getAddress:async()=>{let{toCashAddress:X}=await import("@swapkit/toolboxes/utxo");await m(!1);let{bitcoinAddress:R}=await _.getWalletPublicKey(l,{format:G});if(!R)throw new zL("wallet_ledger_get_address_error",{message:`Cannot get ${L} address from ledger derivation path: ${l}`});return L==="bitcoin-cash"&&G==="legacy"?X(R).replace(/(bchtest:|bitcoincash:)/,""):R},getExtendedPublicKey:async(X="84'/0'/0'",R=76067358)=>{return await m(!1),_.getWalletXpub({path:X,xpubVersion:R})},signTransaction:async(X,R)=>{return await w(),Wy({btcApp:_,chain:L,derivationPath:l,inputUtxos:R,psbt:X},y)}}}},qL=c({chain:"bitcoin"}),cL=c({chain:"litecoin"}),SL=c({additionalSignParams:{additionals:["abc"],segwit:!1,sigHashType:65},chain:"bitcoin-cash"}),oL=c({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dogecoin"}),KL=c({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dash"}),nL=c({additionalSignParams:{additionals:["zcash","sapling"],expiryHeight:(()=>{let L=Buffer.allocUnsafe(4);return L.writeUInt32LE(0),L})(),lockTime:0,segwit:!1,useTrustedInputForSegwit:!1},chain:"zcash"});import Yy from"@ledgerhq/hw-app-xrp";import{Chain as Dy,derivationPathToString as Uy,NetworkDerivationPath as fy}from"@swapkit/helpers";import{encode as kL}from"ripple-binary-codec";var ty=2147483648;function Hy(L){let y={};for(let _ in L)if(L[_]!==null&&L[_]!==void 0)y[_]=L[_];return y}function Py(L){return new Yy(L)}var EL=async(L)=>{let y=Uy(L||fy[Dy.Ripple]),_=await M(),T=Py(_),{address:m,publicKey:w}=await T.getAddress(y);async function g(l){let{hashes:G}=await import("@swapkit/toolboxes/ripple"),R={...Hy(l),Flags:l.Flags||ty,SigningPubKey:w.toUpperCase()},F=kL(R),i=await T.signTransaction(y,F),Q=kL({...R,TxnSignature:i});return{hash:G.hashSignedTx(Q),tx_blob:Q}}return{getAddress:()=>m,signTransaction:g}};var U=async({chain:L,derivationPath:y})=>{let{match:_}=await import("ts-pattern");return _(L).returnType().with(C.THORChain,()=>Promise.resolve(new mL(y))).with(C.Cosmos,()=>Promise.resolve(new yL(y))).with(C.Bitcoin,()=>Promise.resolve(qL(y))).with(C.BitcoinCash,()=>Promise.resolve(SL(y))).with(C.Dash,()=>Promise.resolve(KL(y))).with(C.Dogecoin,()=>Promise.resolve(oL(y))).with(C.Litecoin,()=>Promise.resolve(cL(y))).with(C.Zcash,()=>Promise.resolve(nL(y))).with(C.Ripple,()=>Promise.resolve(EL(y))).with(C.Tron,()=>Promise.resolve(PL(y))).with(C.Near,()=>{return Promise.resolve(fL(y))}).with(C.Arbitrum,C.Aurora,C.Avalanche,C.BinanceSmartChain,C.Ethereum,C.Gnosis,C.Monad,C.Optimism,C.Polygon,C.Base,C.XLayer,async()=>{let{getProvider:T}=await import("@swapkit/toolboxes/evm"),m={derivationPath:y,provider:await T(L)};return _(L).with(C.BinanceSmartChain,()=>YL(m)).with(C.Avalanche,()=>ZL(m)).with(C.Arbitrum,()=>iL(m)).with(C.Optimism,()=>QL(m)).with(C.Polygon,()=>WL(m)).with(C.Base,()=>AL(m)).with(C.Aurora,()=>ML(m)).with(C.Gnosis,()=>JL(m)).with(C.Monad,()=>DL(m)).with(C.XLayer,()=>UL(m)).otherwise(()=>$L(m))}).otherwise(()=>{throw new zy("wallet_chain_not_supported",{chain:L,wallet:qy.LEDGER})})};var ky=Ky({connect:({addChain:L,supportedChains:y,walletType:_})=>async function(m,w){let[g]=Sy({chains:m,supportedChains:y,walletType:_});if(!g)return!1;let l=await dy({chain:g,derivationPath:w});return L({...l,chain:g,walletType:dL.LEDGER}),!0},name:"connectLedger",supportedChains:[O.Arbitrum,O.Aurora,O.Avalanche,O.Base,O.BinanceSmartChain,O.Bitcoin,O.BitcoinCash,O.Cosmos,O.Dash,O.Dogecoin,O.Ethereum,O.Gnosis,O.Litecoin,O.Monad,O.Near,O.Optimism,O.Polygon,O.Ripple,O.THORChain,O.XLayer,O.Tron,O.Zcash],walletType:dL.LEDGER}),e0=ny(ky);function Ey(L,y="t"){if(!L?.includes("=:"))return L;let _=L.includes(`:${y}:`)?L.split(`:${y}:`)[0]:L;return _?.substring(0,_.lastIndexOf(":"))}function v(L){if(Array.isArray(L))return L.forEach((T,m)=>{L[m]=v(T)}),L;if(typeof L!=="object")return L;let y={},_=Object.keys(L).sort();for(let T of _)y[T]=v(L[T]);return y}function by(L){return JSON.stringify(v(L))}async function dy({chain:L,derivationPath:y}){switch(L){case O.BitcoinCash:case O.Bitcoin:case O.Dash:case O.Dogecoin:case O.Litecoin:case O.Zcash:{let{getUtxoToolbox:_}=await import("@swapkit/toolboxes/utxo"),T=await _(L),m=await U({chain:L,derivationPath:y}),w=await H({chain:L,ledgerClient:m});return{...T,address:w,transfer:async(l)=>{let G=l.feeRate||(await T.getFeeRates())[cy.Average],X=[O.Bitcoin].includes(L)?l.memo:Ey(l.memo),{psbt:R,inputs:F}=await T.createTransaction({...l,feeRate:G,fetchTxHex:!0,memo:X,sender:w}),i=await m.signTransaction(R,F);return await T.broadcastTx(i)}}}case O.Ethereum:case O.Avalanche:case O.Arbitrum:case O.Optimism:case O.Polygon:case O.BinanceSmartChain:case O.Base:case O.Aurora:case O.Gnosis:case O.Monad:case O.XLayer:{let{getEvmToolbox:_}=await import("@swapkit/toolboxes/evm"),T=await U({chain:L,derivationPath:y}),m=await H({chain:L,ledgerClient:T});return{...await _(L,{signer:T}),address:m}}case O.Cosmos:{let{createSigningStargateClient:_,getMsgSendDenom:T,getCosmosToolbox:m}=await import("@swapkit/toolboxes/cosmos"),w=await m(O.Cosmos),g=await U({chain:L,derivationPath:y}),l=await H({chain:L,ledgerClient:g});return{...w,address:l,transfer:async({assetValue:X,recipient:R,memo:F})=>{if(!X)throw new S("wallet_ledger_invalid_asset");let i={amount:[{amount:X.getBaseValue("string"),denom:T(`u${X.symbol}`).toLowerCase()}],fromAddress:l,toAddress:R},Q=await bL(L),J=await _(Q,g,"0.007uatom"),{transactionHash:f}=await J.signAndBroadcast(l,[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:i}],2,F);return f}}}case O.THORChain:{let{SignMode:_}=await import("cosmjs-types/cosmos/tx/signing/v1beta1/signing.js"),{TxRaw:T}=await import("cosmjs-types/cosmos/tx/v1beta1/tx.js"),m=await import("@cosmjs/proto-signing"),w=m.encodePubkey??m.default?.encodePubkey,g=m.makeAuthInfoBytes??m.default?.makeAuthInfoBytes,{createStargateClient:l,buildEncodedTxBody:G,getCosmosToolbox:X,buildAminoMsg:R,getDefaultChainFee:F,fromBase64:i,parseAminoMessageForDirectSigning:Q}=await import("@swapkit/toolboxes/cosmos"),J=await X(L),f=await U({chain:L,derivationPath:y}),o=await H({chain:L,ledgerClient:f}),I=F(L),{pubkey:TL,signTransaction:VL,sign:vL}=f,wL=async({memo:t="",assetValue:lL,...IL})=>{let gL=await J.getAccount(o);if(!gL)throw new S("wallet_ledger_invalid_account");if(!lL)throw new S("wallet_ledger_invalid_asset");if(!TL)throw new S("wallet_ledger_pubkey_not_found");let{accountNumber:hL,sequence:xL}=gL,h=(xL||0).toString(),OL=v([R({assetValue:lL,memo:t,sender:o,...IL})]),uL=by({account_number:hL?.toString(),chain_id:oy.chainId,fee:I,memo:t,msgs:OL,sequence:h}),x=await VL(uL,h);if(!x)throw new S("wallet_ledger_signing_error");let pL=w({type:"tendermint/PubKeySecp256k1",value:TL}),aL=OL.map(Q),eL=await G({chain:L,memo:t,msgs:aL}),rL=g([{pubkey:pL,sequence:Number(h)}],I.amount,Number.parseInt(I.gas,10),void 0,void 0,_.SIGN_MODE_LEGACY_AMINO_JSON),sL=x?.[0]?.signature?i(x[0].signature):Uint8Array.from([]),Ly=T.fromPartial({authInfoBytes:rL,bodyBytes:eL,signatures:[sL]}),yy=T.encode(Ly).finish(),_y=await bL(O.THORChain),my=await l(_y),{transactionHash:Ty}=await my.broadcastTx(yy);return Ty};return{...J,address:o,deposit:(t)=>wL(t),signMessage:vL,transfer:(t)=>wL(t)}}case O.Near:{let{getNearToolbox:_}=await import("@swapkit/toolboxes/near"),T=await U({chain:L,derivationPath:y}),m=await T.getAddress();return{...await _({signer:T}),address:m}}case O.Ripple:{let{getRippleToolbox:_}=await import("@swapkit/toolboxes/ripple"),T=await U({chain:L,derivationPath:y}),m=T.getAddress();return{...await _({signer:T}),address:m}}case O.Tron:{let{createTronToolbox:_}=await import("@swapkit/toolboxes/tron"),T=await U({chain:L,derivationPath:y}),m=await H({chain:L,ledgerClient:T});return{...await _({signer:T}),address:m}}default:throw new S("wallet_ledger_chain_not_supported",{chain:L})}}export{ky as ledgerWallet,e0 as LEDGER_SUPPORTED_CHAINS};
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};
3
3
 
4
- //# debugId=9E1693A7A9B5B06664756E2164756E21
4
+ //# debugId=83C9AD2CDE49309B64756E2164756E21
5
5
  //# sourceMappingURL=index.js.map