@swapkit/wallet-hardware 4.2.11 → 4.6.1

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