@swapkit/wallet-hardware 6.1.1 → 6.2.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 (101) hide show
  1. package/dist/chunk-035dayv6.js +4 -0
  2. package/dist/chunk-035dayv6.js.map +10 -0
  3. package/dist/{chunk-yrxe491r.js → chunk-2jddegc1.js} +3 -3
  4. package/dist/{chunk-yrxe491r.js.map → chunk-2jddegc1.js.map} +1 -1
  5. package/dist/{chunk-gr3eswf1.js → chunk-42xrtarj.js} +3 -3
  6. package/dist/{chunk-gr3eswf1.js.map → chunk-42xrtarj.js.map} +1 -1
  7. package/dist/{chunk-3t17wpjg.js → chunk-545s1tsc.js} +3 -3
  8. package/dist/{chunk-3t17wpjg.js.map → chunk-545s1tsc.js.map} +1 -1
  9. package/dist/{chunk-1amf58aq.js → chunk-5xg0xc0g.js} +3 -3
  10. package/dist/{chunk-1amf58aq.js.map → chunk-5xg0xc0g.js.map} +1 -1
  11. package/dist/{chunk-xn0fnag5.js → chunk-71kfnwdp.js} +3 -3
  12. package/dist/{chunk-xn0fnag5.js.map → chunk-71kfnwdp.js.map} +1 -1
  13. package/dist/{chunk-xmvg4cds.js → chunk-7kwtpk70.js} +3 -3
  14. package/dist/{chunk-xmvg4cds.js.map → chunk-7kwtpk70.js.map} +1 -1
  15. package/dist/{chunk-0arpsm5f.js → chunk-7rbvcts9.js} +3 -3
  16. package/dist/{chunk-0arpsm5f.js.map → chunk-7rbvcts9.js.map} +1 -1
  17. package/dist/{chunk-k3thje6a.js → chunk-a47dwwv6.js} +3 -3
  18. package/dist/{chunk-k3thje6a.js.map → chunk-a47dwwv6.js.map} +1 -1
  19. package/dist/{chunk-5c7b7z2d.js → chunk-a6vcbcyd.js} +3 -3
  20. package/dist/{chunk-5c7b7z2d.js.map → chunk-a6vcbcyd.js.map} +1 -1
  21. package/dist/{chunk-wfbg89d3.js → chunk-b093ajcq.js} +3 -3
  22. package/dist/{chunk-wfbg89d3.js.map → chunk-b093ajcq.js.map} +1 -1
  23. package/dist/{chunk-ds2m83jp.js → chunk-b7htg03t.js} +3 -3
  24. package/dist/{chunk-ds2m83jp.js.map → chunk-b7htg03t.js.map} +1 -1
  25. package/dist/chunk-g6rrzxcx.js +5 -0
  26. package/dist/chunk-g6rrzxcx.js.map +10 -0
  27. package/dist/{chunk-jewm2ag3.js → chunk-j3n6fbqh.js} +4 -4
  28. package/dist/{chunk-jewm2ag3.js.map → chunk-j3n6fbqh.js.map} +1 -1
  29. package/dist/{chunk-nhva847d.js → chunk-kaw35ae2.js} +3 -3
  30. package/dist/{chunk-nhva847d.js.map → chunk-kaw35ae2.js.map} +1 -1
  31. package/dist/{chunk-dptbnkzm.js → chunk-mzan0m09.js} +4 -4
  32. package/dist/{chunk-dptbnkzm.js.map → chunk-mzan0m09.js.map} +1 -1
  33. package/dist/{chunk-jzrytcrf.js → chunk-rydhx4se.js} +3 -3
  34. package/dist/{chunk-jzrytcrf.js.map → chunk-rydhx4se.js.map} +1 -1
  35. package/dist/{chunk-09e51wma.js → chunk-s2akss77.js} +3 -3
  36. package/dist/{chunk-09e51wma.js.map → chunk-s2akss77.js.map} +1 -1
  37. package/dist/{chunk-tm47brht.js → chunk-s5a5v0m1.js} +3 -3
  38. package/dist/{chunk-tm47brht.js.map → chunk-s5a5v0m1.js.map} +1 -1
  39. package/dist/{chunk-8m2sn76p.js → chunk-sbebfr50.js} +3 -3
  40. package/dist/{chunk-8m2sn76p.js.map → chunk-sbebfr50.js.map} +1 -1
  41. package/dist/{chunk-xx7cwpzq.js → chunk-sp3dq5hr.js} +2 -2
  42. package/dist/{chunk-hg71hp4m.js → chunk-tecse0bj.js} +3 -3
  43. package/dist/{chunk-hg71hp4m.js.map → chunk-tecse0bj.js.map} +1 -1
  44. package/dist/chunk-tm5gk51g.js +4 -0
  45. package/dist/{chunk-eenx3cv6.js → chunk-x28a37pz.js} +3 -3
  46. package/dist/{chunk-eenx3cv6.js.map → chunk-x28a37pz.js.map} +1 -1
  47. package/dist/{chunk-3h1f3hyp.js → chunk-ys51wj1c.js} +3 -3
  48. package/dist/{chunk-3h1f3hyp.js.map → chunk-ys51wj1c.js.map} +1 -1
  49. package/dist/keepkey/index.cjs +2 -2
  50. package/dist/keepkey/index.cjs.map +3 -3
  51. package/dist/keepkey/index.js +2 -2
  52. package/dist/keepkey/index.js.map +3 -3
  53. package/dist/ledger/index.cjs +30 -30
  54. package/dist/ledger/index.cjs.map +11 -7
  55. package/dist/ledger/index.js +2 -2
  56. package/dist/ledger/index.js.map +10 -7
  57. package/dist/trezor/index.cjs +2 -2
  58. package/dist/trezor/index.cjs.map +6 -5
  59. package/dist/trezor/index.js +2 -2
  60. package/dist/trezor/index.js.map +3 -3
  61. package/dist/types/helpers/cardano.d.ts +35 -0
  62. package/dist/types/helpers/cardano.d.ts.map +1 -0
  63. package/dist/types/keepkey/index.d.ts +1 -0
  64. package/dist/types/keepkey/index.d.ts.map +1 -1
  65. package/dist/types/ledger/clients/cardano.d.ts +24 -0
  66. package/dist/types/ledger/clients/cardano.d.ts.map +1 -0
  67. package/dist/types/ledger/clients/evm.d.ts +1 -0
  68. package/dist/types/ledger/clients/evm.d.ts.map +1 -1
  69. package/dist/types/ledger/clients/stellar.d.ts +13 -0
  70. package/dist/types/ledger/clients/stellar.d.ts.map +1 -0
  71. package/dist/types/ledger/clients/ton.d.ts +13 -0
  72. package/dist/types/ledger/clients/ton.d.ts.map +1 -0
  73. package/dist/types/ledger/helpers/getLedgerAddress.d.ts.map +1 -1
  74. package/dist/types/ledger/helpers/getLedgerClient.d.ts +8 -1
  75. package/dist/types/ledger/helpers/getLedgerClient.d.ts.map +1 -1
  76. package/dist/types/ledger/index.d.ts +3 -2
  77. package/dist/types/ledger/index.d.ts.map +1 -1
  78. package/dist/types/ledger/types.d.ts +2 -2
  79. package/dist/types/ledger/types.d.ts.map +1 -1
  80. package/dist/types/trezor/cardanoSigner.d.ts.map +1 -1
  81. package/dist/types/trezor/index.d.ts +1 -0
  82. package/dist/types/trezor/index.d.ts.map +1 -1
  83. package/dist/types/trezor/stellarSigner.d.ts +1 -1
  84. package/package.json +16 -4
  85. package/src/helpers/cardano.ts +112 -0
  86. package/src/keepkey/index.ts +14 -14
  87. package/src/ledger/clients/cardano.ts +204 -0
  88. package/src/ledger/clients/evm.ts +4 -0
  89. package/src/ledger/clients/stellar.ts +83 -0
  90. package/src/ledger/clients/ton.ts +282 -0
  91. package/src/ledger/helpers/getLedgerAddress.ts +16 -0
  92. package/src/ledger/helpers/getLedgerClient.ts +13 -0
  93. package/src/ledger/index.ts +100 -28
  94. package/src/ledger/types.ts +2 -0
  95. package/src/trezor/cardanoSigner.ts +24 -80
  96. package/src/trezor/index.ts +86 -64
  97. package/dist/chunk-5p3ttw6y.js +0 -4
  98. package/dist/chunk-qjq7gvyx.js +0 -4
  99. package/dist/chunk-qjq7gvyx.js.map +0 -10
  100. /package/dist/{chunk-xx7cwpzq.js.map → chunk-sp3dq5hr.js.map} +0 -0
  101. /package/dist/{chunk-5p3ttw6y.js.map → chunk-tm5gk51g.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{Ea as U0,Fa as w$,Ga as m0}from"../chunk-ds2m83jp.js";import{Ia as L$}from"../chunk-jewm2ag3.js";import{$d as W}from"../chunk-nhva847d.js";import{hex as j5}from"@scure/base";import{Chain as z,derivationPathToString as D0,FeeOption as Q5,filterSupportedChains as e8,getUTXOScriptTypeForPath as $9,NetworkDerivationPath as Y9,SwapKitError as j0,UTXOScriptType as A0,WalletOption as N0}from"@swapkit/helpers";import{addInputsAndOutputs as J9,assertDerivationIndex as Z5,compileMemo as j9,createHDWalletHelpers as Q9,getNetworkForChain as X5,getScriptTypeForAddress as Z9,getUTXOAccountIndexFromPath as s0,getUTXOAccountPath as z5,getUTXOAddressPath as G5,getUtxoApi as q5}from"@swapkit/toolboxes/utxo";import{createWallet as G9,getWalletSupportedChains as B9}from"@swapkit/wallet-core";import{match as L0,P as B5}from"ts-pattern";import{SwapKitError as Z0}from"@swapkit/helpers";import{filter as y5,firstValueFrom as r0,map as b5,timeout as A5}from"rxjs";import{SwapKitError as O0}from"@swapkit/helpers";import{match as n0}from"ts-pattern";var E0={Completed:"completed",Error:"error",Stopped:"stopped"},C={None:"none",SignTransaction:"sign-transaction",VerifyAddress:"verify-address"},N5=new Set(["6985","5501"]),e=["6986"],L5=new Set(["5515"]),w5=new Set(["6511","6807","6d00","6e00"]),K5=new Set(["DeviceDisconnectedBeforeSendingApdu","DeviceDisconnectedWhileSendingError","DeviceNotRecognizedError","DeviceSessionNotFound","NoAccessibleDeviceError","ReconnectionFailedError"]),_5=new Set(["DisconnectedDevice","DisconnectedDeviceDuringOperation"]),R5=new Set(["UserRefusedOnDevice"]),O5=4,U5=/^(?:0x)?([0-9a-f]{4})$/i;function k5($){let Y=[],J=$;while(Y.length<O5&&typeof J==="object"&&J!==null){let j=J;Y.push(j),J=j.originalError}return Y}function f5({errorCode:$,statusCode:Y}){let J=typeof $==="string"?U5.exec($)?.[1]:void 0;if(J)return J.toLowerCase();return typeof Y==="number"?Y.toString(16).padStart(4,"0"):void 0}function d($,{userRefusedStatusWords:Y=[]}={}){let J=k5($),j=J.find((X)=>X instanceof O0);if(j)return j;let Q=J.flatMap(({_tag:X})=>typeof X==="string"?[X]:[]),Z=J.flatMap(({name:X})=>typeof X==="string"?[X]:[]),B=J.map(f5).find((X)=>X!==void 0),G=J.map((X)=>X.message).filter((X)=>typeof X==="string"&&X.length>0).at(-1),V=new Set([...N5,...Y]),q=n0({errorNames:Z,errorTags:Q,statusWord:B}).when(({errorNames:X,errorTags:F,statusWord:H})=>F.includes("RefusedByUserDAError")||X.some((M)=>R5.has(M))||!!H&&V.has(H),()=>"wallet_connection_rejected_by_user").when(({errorTags:X,statusWord:F})=>X.includes("DeviceLockedError")||!!F&&L5.has(F),()=>"wallet_ledger_device_locked").when(({errorTags:X,statusWord:F})=>X.includes("UnsupportedApplicationDAError")||!!F&&w5.has(F),()=>"wallet_ledger_app_not_open").when(({errorNames:X,errorTags:F})=>F.some((H)=>K5.has(H))||X.some((H)=>_5.has(H)),()=>"wallet_ledger_connection_error").otherwise(()=>"wallet_ledger_transport_error");return new O0({errorKey:q,info:{errorTag:Q[0],message:G,statusWord:B}},$)}function A({action:$,onDeviceActionState:Y,userRefusedStatusWords:J}){return new Promise((j,Q)=>{let Z;try{Z=$().observable}catch(q){Q(d(q,{userRefusedStatusWords:J}));return}let B=!1,G;function V(q){if(B)return;B=!0,G?.unsubscribe(),q()}if(G=Z.subscribe({complete:()=>{V(()=>Q(new O0("wallet_ledger_invalid_response")))},error:(q)=>{V(()=>Q(d(q,{userRefusedStatusWords:J})))},next:(q)=>{try{Y?.(q)}catch(X){}n0(q).with({status:E0.Completed},({output:X})=>V(()=>j(X))).with({status:E0.Error},({error:X})=>V(()=>Q(d(X,{userRefusedStatusWords:J})))).with({status:E0.Stopped},()=>V(()=>Q(new O0("wallet_ledger_connection_error")))).otherwise(()=>{return})}}),B)G.unsubscribe()})}var D5=1000,C0,x;function T5(){if(typeof navigator>"u"||!("hid"in navigator))return Promise.reject(new Z0("wallet_ledger_webhid_not_supported"));return Promise.all([import("../chunk-k3thje6a.js"),import("../chunk-3t17wpjg.js")]).then(([{DeviceManagementKitBuilder:$},{webHidTransportFactory:Y}])=>new $().addTransport(Y).build()).catch(($)=>{if(C0=void 0,$ instanceof Z0)throw $;throw new Z0("wallet_ledger_connection_error",$)})}function a0(){return C0??=T5(),C0}function P0(){return a0().then(($)=>t0({dmk:$}))}function I5($){return typeof $==="object"&&$!==null&&"_tag"in $&&$._tag==="DeviceSessionNotFound"}function E5({dmk:$,sessionId:Y}){try{return $.getConnectedDevice({sessionId:Y}),!0}catch(J){return!1}}async function C5({sessionPromise:$}){let Y=$;try{let J=await Y;if(E5(J))return J;if(x===Y)x=P0();return x??=P0(),Y=x,await Y}catch(J){if(x===Y)x=void 0;if(J instanceof Z0)throw J;throw new Z0("wallet_ledger_connection_error",J)}}async function P5(){let $=typeof navigator>"u"?void 0:navigator.hid;if(typeof $?.getDevices!=="function")return!1;try{let[Y,{LEDGER_VENDOR_ID:J}]=await Promise.all([$.getDevices(),import("../chunk-k3thje6a.js")]);return Y.some(({vendorId:j})=>j===J)}catch(Y){return!1}}async function v5({dmk:$}){if(!await P5())return;try{return await r0($.listenToAvailableDevices({}).pipe(b5(([Y])=>Y),y5((Y)=>Y!==void 0),A5({first:D5})))}catch(Y){return}}async function t0({dmk:$}){let Y=!1;try{let J=await v5({dmk:$});if(J)return{dmk:$,sessionId:await $.connect({device:J})};let j=$.startDiscovering({});Y=!0;let Q=await r0(j),Z=await $.connect({device:Q});return{dmk:$,sessionId:Z}}catch(J){if(J instanceof Z0)throw J;throw new Z0("wallet_ledger_connection_error",J)}finally{if(Y)try{await $.stopDiscovering()}catch(J){}}}function n({dmk:$}={}){if($)return t0({dmk:$});return x??=P0(),C5({sessionPromise:x})}function $0({build:$,dmkSession:Y}){let J;return async function(){let Q=Y??await n();if(J?.session.dmk!==Q.dmk||J.session.sessionId!==Q.sessionId){let Z=Promise.resolve().then(()=>$(Q));J={session:Q,signer:Z};let B=J;Z.catch(()=>{if(J===B)J=void 0})}return J.signer}}function e0(){let $=a0();return $.catch(()=>{return}),$}async function $$({dmkSession:$}={}){let Y=x,J=$;if(!J){if(!Y)return;if(x===Y)x=void 0;try{J=await Y}catch{return}}if(Y)try{let j=await Y;if(x===Y&&j.dmk===J.dmk&&j.sessionId===J.sessionId)x=void 0}catch(j){if(x===Y)x=void 0}try{await J.dmk.disconnect({sessionId:J.sessionId})}catch(j){if(I5(j))return;throw d(j)}}import{Chain as b,SwapKitError as S5,WalletOption as x5}from"@swapkit/helpers";var r=async({chain:$,ledgerClient:Y})=>{if(!Y)return"";switch($){case b.Cosmos:case b.THORChain:return Y.connect();case b.Ethereum:case b.BinanceSmartChain:case b.Avalanche:case b.Polygon:case b.Arbitrum:case b.Arc:case b.Berachain:case b.Optimism:case b.Base:case b.Aurora:case b.Gnosis:case b.Monad:case b.XLayer:return Y.getAddress();case b.Bitcoin:case b.BitcoinCash:case b.Dash:case b.Dogecoin:case b.Litecoin:case b.Zcash:{let J=Y;await J.connect();let j=await J.getAddress();return $===b.BitcoinCash?j.replace("bitcoincash:",""):j}case b.Near:return await Y.getAddress();case b.Ripple:return Y.getAddress();case b.Tron:return Y.getAddress();case b.Sui:return Y.connect();default:throw new S5("wallet_chain_not_supported",{chain:$,wallet:x5.LEDGER})}};import{Chain as _,EVMChains as r8,NetworkDerivationPath as a8,SwapKitError as o0,WalletOption as t8}from"@swapkit/helpers";import{hex as p}from"@scure/base";import{HARDENED_OFFSET as W$,HDKey as M$}from"@scure/bip32";import{Chain as H0,derivationPathToString as i5,NetworkDerivationPath as n5,SwapKitError as g}from"@swapkit/helpers";import{match as K$}from"ts-pattern";import{hex as u5}from"@scure/base";import{derivationPathToString as c5,getWalletFormatFor as x0,SwapKitError as G$}from"@swapkit/helpers";import{SwapKitError as m5}from"@swapkit/helpers";function l5($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function s({paramsOrPath:$,transport:Y}){if(l5($))return $;return{derivationPath:$,transport:Y}}async function u({appName:$,connection:Y,createApp:J,operation:j,requiredUserInteraction:Q=C.None}){let{dmkSession:Z,onDeviceActionState:B,transport:G}=Y;if(Z&&G)throw new m5("wallet_ledger_invalid_params",{message:"Provide either a Ledger DMK session or a LedgerJS transport, not both"});if(G)try{return await j(J(G))}catch(O){throw d(O)}let V=Z??await n(),[{CallTaskInAppDeviceAction:q,DmkResultFactory:X,UnknownDeviceExchangeError:F},{LedgerJsDmkTransport:H}]=await Promise.all([import("../chunk-k3thje6a.js"),import("../chunk-0arpsm5f.js")]),M=new q({input:{appName:$,requiredUserInteraction:Q,skipOpenApp:!1,task:async(O)=>{try{let y=await j(J(new H(O)));return X({data:{output:y}})}catch(y){return X({error:new F(y)})}}}});return(await A({action:()=>V.dmk.executeDeviceAction({deviceAction:M,sessionId:V.sessionId}),onDeviceActionState:B})).output}import{SwapKitError as g5}from"@swapkit/helpers";var Y$=100,J$={cla:224,ins:74},v0=0,j$=128,h5=[0,144,0];function Q$($,Y){let J=$[Y];if(J===void 0||J===255)return;if(J<253)return{size:1,value:J};let j=J===253?2:4;if(Y+1+j>$.length)return;let Q=new DataView($.buffer,$.byteOffset+Y+1,j);return{size:1+j,value:j===2?Q.getUint16(0,!0):Q.getUint32(0,!0)}}function S0($,Y){let J=(B,G={})=>new g5({errorKey:"wallet_ledger_invalid_params",info:{chain:Y,maxLength:Y$,operation:"splitOutputsForLegacyApp",outputsLength:$.length,reason:B,...G}}),j=Q$($,0);if(!j?.value)throw J("Transaction outputs do not start with a readable non-zero output count");let Q=[],Z=j.size;for(let B=0;B<j.value;B+=1){let G=B===0?0:Z,V=Q$($,Z+8),q=V?Z+8+V.size+V.value:void 0;if(!q||q>$.length)throw J("Transaction output is truncated",{outputIndex:B});let X=q-G;if(X>Y$)throw J("Output is longer than the Ledger app can check; shorten the memo",{outputIndex:B,pieceLength:X});Q.push($.subarray(G,q)),Z=q}if(Z!==$.length)throw J("Transaction outputs are followed by trailing bytes",{trailingBytes:$.length-Z});return Q}function Z$($,Y){let J=[],j=async(Q,Z,B,G,V=Buffer.alloc(0),...q)=>{if(!(Q===J$.cla&&Z===J$.ins&&(B===v0||B===j$)))return $.send(Q,Z,B,G,V,...q);if(J.push(V),B===v0)return Buffer.from(h5);let F=Buffer.concat(J);J=[];let H=S0(F,Y),M=Buffer.alloc(0);for(let[N,O]of H.entries()){let y=N===H.length-1?j$:v0;M=await $.send(Q,Z,y,G,Buffer.from(O),...q)}return M};return new Proxy($,{get:(Q,Z,B)=>Z==="send"?j:Reflect.get(Q,Z,B)})}var B$=["bitcoin-cash","dash","dogecoin","zcash"],d5=["bitcoin-cash","dash","dogecoin","litecoin"],p5={bitcoin:"Bitcoin","bitcoin-cash":"Bitcoin Cash",dash:"Dash",dogecoin:"Dogecoin",litecoin:"Litecoin",zcash:"Zcash"},o5=({outputScriptHex:$,inputUtxos:Y,btcApp:J,derivationPath:j,chain:Q},Z)=>{let B=Y.map((X)=>{return[J.splitTransaction(X.txHex||"",!B$.includes(Q),Q==="zcash"),X.index,void 0,void 0]}),G=x0(j),V=G!=="legacy",q={additionals:G==="bech32"?["bech32"]:[],associatedKeysets:B.map(()=>j),inputs:B,outputScriptHex:$,segwit:V,useTrustedInputForSegwit:V};return J.createPaymentTransaction({...q,...Z})},s5=({outputScriptHex:$,inputUtxos:Y,btcApp:J,derivationPaths:j,chain:Q},Z)=>{if(j.length!==Y.length)throw new G$("wallet_ledger_invalid_params",{message:`Derivation paths count (${j.length}) must match inputs count (${Y.length})`});let B=Y.map((X)=>{return[J.splitTransaction(X.txHex||"",!B$.includes(Q),Q==="zcash"),X.index,void 0,void 0]}),G=x0(j[0]??""),V=G!=="legacy",q={additionals:G==="bech32"?["bech32"]:[],associatedKeysets:j,inputs:B,outputScriptHex:$,segwit:V,useTrustedInputForSegwit:V};return J.createPaymentTransaction({...q,...Z})},X0=({chain:$,additionalSignParams:Y})=>{let J=d5.includes($);return(j,Q)=>{let{derivationPath:Z,...B}=s({paramsOrPath:j,transport:Q}),G=typeof Z==="string"?Z:c5(Z),V=x0(G);async function q({operation:F,requiredUserInteraction:H}){let M=(await import("@ledgerhq/hw-app-btc")).default;return u({appName:p5[$],connection:B,createApp:(N)=>new M({currency:$,transport:J?Z$(N,$):N}),operation:F,requiredUserInteraction:H})}async function X(F){let[{splitTransaction:H},{serializeTransactionOutputs:M}]=await Promise.all([import("@ledgerhq/hw-app-btc/splitTransaction"),import("@ledgerhq/hw-app-btc/serializeTransaction")]),N=M(H(u5.encode(F.unsignedTx),!0));if(J)S0(N,$);return N.toString("hex")}return{connect:async()=>{await q({operation:async()=>!0})},disconnect:async()=>{},getAddress:async()=>{let{toCashAddress:F}=await import("@swapkit/toolboxes/utxo"),{bitcoinAddress:H}=await q({operation:(M)=>M.getWalletPublicKey(G,{format:V})});if(!H)throw new G$("wallet_ledger_get_address_error",{message:`Cannot get ${$} address from ledger derivation path: ${G}`});return $==="bitcoin-cash"&&V==="legacy"?F(H).replace(/(bchtest:|bitcoincash:)/,""):H},getExtendedPublicKey:async(F="84'/0'/0'",H=76067358)=>{return await q({operation:(M)=>M.getWalletXpub({path:F,xpubVersion:H})})},signTransaction:async(F,H)=>{let M=await X(F);return await q({operation:(N)=>o5({btcApp:N,chain:$,derivationPath:G,inputUtxos:H,outputScriptHex:M},Y),requiredUserInteraction:C.SignTransaction})},signTransactionWithMultiplePaths:async(F,H,M)=>{let N=await X(F);return await q({operation:(O)=>s5({btcApp:O,chain:$,derivationPaths:M,inputUtxos:H,outputScriptHex:N},Y),requiredUserInteraction:C.SignTransaction})}}}},X$=X0({chain:"bitcoin"}),z$=X0({chain:"litecoin"}),q$=X0({additionalSignParams:{additionals:["abc","cashaddr"],segwit:!1,sigHashType:65,useTrustedInputForSegwit:!0},chain:"bitcoin-cash"}),V$=X0({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dogecoin"}),H$=X0({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dash"}),F$=X0({additionalSignParams:{additionals:["zcash","sapling"],expiryHeight:(()=>{let $=Buffer.alloc(4);return $.writeUInt32LE(0),$})(),lockTime:0,segwit:!1,useTrustedInputForSegwit:!1},chain:"zcash"});function _$($){return(typeof $==="string"?$:i5($)).replace(/^m\//,"").replace(/^\/+/,"")}function N$({path:$,reason:Y}){return new g("wallet_ledger_invalid_params",{path:$,reason:Y})}function R$($){let Y=_$($),J=/^(44|49|84|86)'\/0'\/(\d+)'(?:\/(0|1)\/(\d+))?$/.exec(Y);if(!J)throw N$({path:Y,reason:"Expected a Bitcoin path with purpose 44, 49, 84, or 86 and coin type 0"});let j=Number(J[1]),Q=Number(J[2]),Z=Number(J[3]??0),B=Number(J[4]??0);if(Q>=W$||B>=W$)throw N$({path:Y,reason:"Account and address index must be below 2^31"});let G=`${j}'/0'/${Q}'`;return{accountPath:G,addressIndex:B,change:Z,fullPath:`${G}/${Z}/${B}`,purpose:j}}function r5($){if($.length!==4)throw new g("wallet_ledger_invalid_response",{reason:`Expected a 4-byte master fingerprint, received ${$.length}`});return new DataView($.buffer,$.byteOffset,$.byteLength).getUint32(0,!1)}function l0({count:$,tx:Y}){if($!==Y.inputsLength)throw new g("wallet_ledger_invalid_params",{reason:`Input metadata count (${$}) must match transaction inputs count (${Y.inputsLength})`})}function a5({accountPath:$,derivationPaths:Y,tx:J}){l0({count:Y.length,tx:J});let j=Y.map(R$),Q=j.find((Z)=>Z.accountPath!==$);if(Q)throw new g("wallet_ledger_invalid_params",{accountPath:$,path:Q.fullPath,reason:"All input derivation paths must belong to the configured Bitcoin account"});return j}function t5($){return import("../chunk-xmvg4cds.js").then(({DefaultDescriptorTemplate:Y})=>K$($).with(44,()=>Y.LEGACY).with(49,()=>Y.NESTED_SEGWIT).with(84,()=>Y.NATIVE_SEGWIT).with(86,()=>Y.TAPROOT).exhaustive())}function e5($){return"signature"in $&&"pubkey"in $}function Y0({inputIndex:$,reason:Y}){return new g("wallet_ledger_invalid_response",{inputIndex:$,reason:Y})}async function $8({input:$,inputIndex:Y,previousTransaction:J}){if(!(J&&$.txid&&$.index!==void 0))throw Y0({inputIndex:Y,reason:"PSBT input is missing its previous output"});let{RawTx:j,utils:Q}=await import("@swapkit/utxo-signer"),Z=j.encode({...J,segwitFlag:!1,witnesses:void 0}),B=Q.sha256x2(Z).reverse();if(p.encode(B)!==p.encode($.txid))throw new g("wallet_ledger_invalid_params",{inputIndex:Y,reason:"Previous transaction does not match the input txid"});let G=J.outputs[$.index];if(!G)throw Y0({inputIndex:Y,reason:"Previous transaction has no spent output"});let{witnessUtxo:V}=$;if(V&&(V.amount!==G.amount||p.encode(V.script)!==p.encode(G.script)))throw new g("wallet_ledger_invalid_params",{inputIndex:Y,reason:"Input witnessUtxo does not match the previous transaction output"});return G}async function Y8({inputIndex:$,path:Y,publicKey:J,spentOutput:j}){let{p2pkh:Q,p2sh:Z,p2tr:B,p2wpkh:G}=await import("@swapkit/utxo-signer"),V=K$(Y.purpose).with(44,()=>Q(J).script).with(49,()=>Z(G(J)).script).with(84,()=>G(J).script).with(86,()=>B(J.slice(1)).script).exhaustive();if(p.encode(V)===p.encode(j.script))return;throw new g("wallet_ledger_invalid_params",{inputIndex:$,path:Y.fullPath,reason:"Input does not spend the script derived from its derivation path"})}function O$({derivationPath:$=n5.BTC,dmkSession:Y,onDeviceActionState:J,transport:j}={}){let Q=R$($),Z=j?X$($,j):void 0,B=$0({build:async(L)=>{let{SignerBtcBuilder:w}=await import("../chunk-xmvg4cds.js");return new w(L).build()},dmkSession:Y}),G,V;function q(){if(Z)throw new g("wallet_ledger_invalid_params",{reason:"A Device Signer Kit operation is unavailable when a legacy transport is supplied"});return B()}function X(){if(!G){G=q().then(async(w)=>{let{extendedPublicKey:k}=await A({action:()=>w.getExtendedPublicKey(Q.accountPath),onDeviceActionState:J});return k});let L=G;L.catch(()=>{if(G===L)G=void 0})}return G}function F(){if(!V){V=q().then(async(w)=>{let{masterFingerprint:k}=await A({action:()=>w.getMasterFingerprint(),onDeviceActionState:J});return r5(k)});let L=V;L.catch(()=>{if(V===L)V=void 0})}return V}async function H(){let L=Z?await Z.getExtendedPublicKey(Q.accountPath):await X(),{publicKey:w}=M$.fromExtendedKey(L).derive(`m/${Q.change}/${Q.addressIndex}`);if(!w)throw new g("wallet_ledger_invalid_response",{path:Q.fullPath,reason:"Could not derive a public key from the Ledger account xpub"});return w}async function M(){let[{DefaultWallet:L},w]=await Promise.all([import("../chunk-xmvg4cds.js"),t5(Q.purpose)]);return new L(Q.accountPath,w)}async function N({inputUtxos:L,tx:w}){let{RawTx:k}=await import("@swapkit/utxo-signer"),K=Array.from({length:w.inputsLength},(R,U)=>U).some((R)=>!(w.getInput(R).nonWitnessUtxo||L?.[R]?.txHex))?await import("@swapkit/toolboxes/utxo").then(({getUtxoApi:R})=>{let U=R(H0.Bitcoin);return U0((f)=>U.getRawTx(f))}):void 0;return Promise.all(Array.from({length:w.inputsLength},async(R,U)=>{let f=w.getInput(U);if(f.nonWitnessUtxo)return f.nonWitnessUtxo;if(!f.txid)throw Y0({inputIndex:U,reason:"PSBT input is missing its previous txid"});let D=L?.[U]?.txHex??await K?.(p.encode(f.txid));if(!D)throw new g("wallet_ledger_invalid_params",{inputIndex:U,reason:"Unable to resolve the previous transaction for Ledger signing"});return k.decode(p.decode(D))}))}async function O({inputUtxos:L,paths:w,tx:k}){let[P,K,R]=await Promise.all([X(),F(),N({inputUtxos:L,tx:k})]),{bip32Path:U}=await import("@swapkit/utxo-signer"),f=M$.fromExtendedKey(P),D=k.clone(),S=[];for(let[T,E]of w.entries()){let l=f.derive(`m/${E.change}/${E.addressIndex}`).publicKey;if(!l)throw new g("wallet_ledger_invalid_response",{inputIndex:T,reason:"Could not derive a public key from the Ledger account xpub"});S[T]=l;let Q0=D.getInput(T),t=R[T],i=await $8({input:Q0,inputIndex:T,previousTransaction:t});await Y8({inputIndex:T,path:E,publicKey:l,spentOutput:i});let V0={fingerprint:K,path:U(`m/${E.fullPath}`)};if(E.purpose===86){let w0=l.slice(1);D.updateInput(T,{tapBip32Derivation:[[w0,{der:V0,hashes:[]}]],tapInternalKey:w0,witnessUtxo:i})}else D.updateInput(T,{bip32Derivation:[[l,V0]],nonWitnessUtxo:t,witnessUtxo:E.purpose===44?void 0:i});await L$({chain:H0.Bitcoin,indexes:[T],publicKey:l,tx:D})}return{psbt:D,publicKeys:S}}async function y({inputUtxos:L,paths:w,tx:k}){let[P,K,{psbt:R,publicKeys:U}]=await Promise.all([q(),M(),O({inputUtxos:L,paths:w,tx:k})]),f=R.toPSBT(0),D=await A({action:()=>P.signPsbt(K,f),onDeviceActionState:J}),S=new Set;for(let T of D){if(!e5(T))throw Y0({reason:"Unexpected MuSig2 signature"});let{inputIndex:E,pubkey:l}=T,Q0=w[E],t=U[E];if(!(Q0&&t)||S.has(E))throw Y0({inputIndex:E,reason:"Unexpected or duplicate input signature"});if(S.add(E),Q0.purpose===86){if(T.tapleafHash)throw Y0({inputIndex:E,reason:"Unexpected taproot script signature"});R.updateInput(E,{tapKeySig:T.signature});continue}if(p.encode(l)!==p.encode(t))throw Y0({inputIndex:E,reason:"Signature public key does not match the input derivation"});R.updateInput(E,{partialSig:[[t,T.signature]]})}if(S.size!==R.inputsLength)throw Y0({reason:`Ledger signed ${S.size} of ${R.inputsLength} inputs`});return R}function I(L){return L.finalize(),L.hex}function h({tx:L,inputUtxos:w}){if(w)l0({count:w.length,tx:L});if(Z)return w?Z.signTransaction(L,w):m0({chain:H0.Bitcoin,legacyClient:Z,tx:L});let k=Array.from({length:L.inputsLength},()=>Q);return y({inputUtxos:w,paths:k,tx:L}).then(I)}return{connect:async()=>{if(Z)return Z.connect();await q()},disconnect:async()=>Z?.disconnect(),getAddress:async()=>{if(Z)return Z.getAddress();let L=await q(),w=await M(),{address:k}=await A({action:()=>L.getWalletAddress(w,Q.addressIndex,{change:Q.change===1}),onDeviceActionState:J});if(!k)throw new g("wallet_ledger_get_address_error",{path:Q.fullPath});return k},getExtendedPublicKey:async({checkOnDevice:L=!1,path:w=Q.accountPath}={})=>{if(Z)return Z.getExtendedPublicKey(w);let k=await q(),P=_$(w),{extendedPublicKey:K}=await A({action:()=>k.getExtendedPublicKey(P,{checkOnDevice:L}),onDeviceActionState:J});return K},getPublicKey:H,showAddressAndPubKey:async()=>{if(Z)return{address:await Z.getAddress()};let L=await q(),w=await M();return A({action:()=>L.getWalletAddress(w,Q.addressIndex,{change:Q.change===1,checkOnDevice:!0}),onDeviceActionState:J})},signTransaction:async(L)=>{if(Z){let k=await m0({chain:H0.Bitcoin,legacyClient:Z,tx:L}),{Transaction:P}=await import("@swapkit/utxo-signer");return P.fromRaw(p.decode(k),{allowUnknownOutputs:!0})}let w=Array.from({length:L.inputsLength},()=>Q);return await y({paths:w,tx:L})},signTransactionHex:h,signTransactionWithMultiplePaths:async({derivationPaths:L,inputUtxos:w,tx:k})=>{if(w)l0({count:w.length,tx:k});let P=a5({accountPath:Q.accountPath,derivationPaths:L,tx:k});if(Z){let K=w??await w$(k,H0.Bitcoin);return Z.signTransactionWithMultiplePaths(k,K,P.map((R)=>`m/${R.fullPath}`))}return y({inputUtxos:w,paths:P,tx:k}).then(I)}}}import{hex as g0}from"@scure/base";import{derivationPathToString as Z8,NetworkDerivationPath as G8,SwapKitError as z0}from"@swapkit/helpers";var U$=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,J8=U$>>1n;function j8($){return $.reduce((Y,J)=>Y<<8n|BigInt(J),0n)}function Q8($){let Y=new Uint8Array(32),J=$;for(let j=31;j>=0;j-=1)Y[j]=Number(J&0xffn),J>>=8n;return Y}function k0($){let Y=j8($.subarray(32,64));if(Y<=J8)return $;let J=new Uint8Array(64);return J.set($.subarray(0,32),0),J.set(Q8(U$-Y),32),J}function B8($){let Y=(typeof $==="string"?$:Z8($)).replace(/^m\//,"").replace(/^\/+/,"");if(!/^44'\/118'\/\d+'\/(0|1)\/\d+$/.test(Y))throw new z0("wallet_ledger_invalid_params",{path:Y,reason:"Expected a five-level Cosmos derivation path with coin type 118"});return Y}async function k$($){let{Secp256k1Signature:Y}=await import("@cosmjs/crypto");try{return k0($.length===64?Y.fromFixedLength($).toFixedLength():Y.fromDer($).toFixedLength())}catch(J){throw new z0("wallet_ledger_invalid_response",J)}}class h0{chain="cosmos";derivationPath;onDeviceActionState;transport;legacyAppPromise;pubKey=null;getSessionSigner;constructor({derivationPath:$=G8.GAIA,dmkSession:Y,onDeviceActionState:J,transport:j}={}){this.derivationPath=B8($),this.getSessionSigner=$0({build:async(Q)=>{let{SignerCosmosBuilder:Z}=await import("../chunk-eenx3cv6.js");return new Z(Q).build()},dmkSession:Y}),this.onDeviceActionState=J,this.transport=j}getSigner(){if(this.transport)throw new z0("wallet_ledger_invalid_params",{reason:"A Device Signer Kit operation is unavailable when a legacy transport is supplied"});return this.getSessionSigner()}getLegacyApp(){if(!this.transport)throw new z0("wallet_ledger_invalid_params",{reason:"Legacy Cosmos transport is unavailable"});return this.legacyAppPromise??=import("@ledgerhq/hw-app-cosmos").then(({default:$})=>new $(this.transport)),this.legacyAppPromise}async runLegacyOperation($){let Y=await this.getLegacyApp();try{return await $(Y)}catch(J){throw d(J,{userRefusedStatusWords:e})}}async signBytes($){if(this.transport){let j=await this.runLegacyOperation((Q)=>Q.sign(this.derivationPath,new TextDecoder().decode($)));if(j.return_code!==36864||!j.signature)throw new z0("wallet_ledger_invalid_response",{returnCode:j.return_code});return k$(j.signature)}let Y=await this.getSigner(),J=await A({action:()=>Y.signTransaction(this.derivationPath,this.chain,$),onDeviceActionState:this.onDeviceActionState,userRefusedStatusWords:e});return k$(J)}async connect(){if(this.transport)await this.getLegacyApp();else await this.getSigner();let{address:$,publicKey:Y}=await this.getAddressAndPubKey();return this.pubKey=Buffer.from(Y,"hex").toString("base64"),$}async disconnect(){}async getAddressAndPubKey(){if(this.transport)return this.runLegacyOperation((j)=>j.getAddress(this.derivationPath,this.chain));let $=await this.getSigner(),{address:Y,publicKey:J}=await A({action:()=>$.getAddress(this.derivationPath,this.chain),onDeviceActionState:this.onDeviceActionState,userRefusedStatusWords:e});return{address:Y,publicKey:g0.encode(J)}}async showAddressAndPubKey(){if(this.transport)return this.runLegacyOperation((j)=>j.getAddress(this.derivationPath,this.chain,!0));let $=await this.getSigner(),{address:Y,publicKey:J}=await A({action:()=>$.getAddress(this.derivationPath,this.chain,{checkOnDevice:!0}),onDeviceActionState:this.onDeviceActionState,userRefusedStatusWords:e});return{address:Y,publicKey:g0.encode(J)}}async signTransaction($,Y="0"){let J=await this.signBytes(typeof $==="string"?new TextEncoder().encode($):$);if(!this.pubKey){let{publicKey:j}=await this.getAddressAndPubKey();this.pubKey=Buffer.from(j,"hex").toString("base64")}return[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:Y,signature:J}]}async signAmino($,Y){let j=(await this.getAccounts()).find(({address:G})=>G===$);if(!j)throw new z0("wallet_ledger_address_not_found",{address:$});let{encodeSecp256k1Signature:Q,serializeSignDoc:Z}=await import("@cosmjs/amino"),B=await this.signBytes(Z(Y));return{signature:Q(j.pubkey,B),signed:Y}}async getAccounts(){let{address:$,publicKey:Y}=await this.getAddressAndPubKey();return[{address:$,algo:"secp256k1",pubkey:g0.decode(Y)}]}}import{ChainId as v,derivationPathToString as X8,NetworkDerivationPath as z8,SwapKitError as G0}from"@swapkit/helpers";import{AbstractSigner as q8}from"ethers";function V8({primaryType:$,types:Y}){let J={};function j(Q){if(Object.hasOwn(J,Q)||!Object.hasOwn(Y,Q))return;let Z=Y[Q];if(!Z)return;J[Q]=Z;for(let B of Z)j(B.type.replace(/\[[0-9]*\]/g,""))}if(j($),!Object.hasOwn(J,$))throw new G0("wallet_ledger_invalid_params",{primaryType:$,reason:"The EIP-712 primary type is not defined"});return J}var H8={report:()=>Promise.resolve(void 0)};class m extends q8{chainId=v.Ethereum;derivationPath="";dmkSession;getLedgerSigner;onDeviceActionState;originToken;constructor({provider:$,dmkSession:Y,derivationPath:J=z8.OP,chainId:j=v.Optimism,onDeviceActionState:Q,originToken:Z}){super($);this.chainId=j||v.Ethereum,this.derivationPath=(typeof J==="string"?J:X8(J)).replace(/^m\//,""),this.dmkSession=Y,this.onDeviceActionState=Q,this.originToken=Z,this.getLedgerSigner=$0({build:async(B)=>{let[{ContextModuleBuilder:G,ContextModuleChainID:V},{SignerEthBuilder:q}]=await Promise.all([import("../chunk-xx7cwpzq.js"),import("../chunk-tm47brht.js")]),X=new G({loggerFactory:(F)=>B.dmk.getLoggerFactory()(["ContextModule",F]),originToken:Z}).setChain(V.Ethereum).setBlindSigningReporter(H8).build();return X.signReport=()=>Promise.resolve(),new q({...B,originToken:Z}).withContextModule(X).build()},dmkSession:Y}),Object.defineProperty(this,"provider",{enumerable:!0,value:$||null,writable:!1})}connect=($)=>new m({chainId:this.chainId,derivationPath:this.derivationPath,dmkSession:this.dmkSession,onDeviceActionState:this.onDeviceActionState,originToken:this.originToken,provider:$});getAddress=async()=>{let{address:$}=await this.getAddressAndPubKey();if(!$)throw new G0("wallet_ledger_failed_to_get_address");return $};getAddressAndPubKey=async()=>{let $=await this.getLedgerSigner();return A({action:()=>$.getAddress(this.derivationPath,{chainId:Number(this.chainId)}),onDeviceActionState:this.onDeviceActionState})};showAddressAndPubKey=async()=>{let $=await this.getLedgerSigner();return A({action:()=>$.getAddress(this.derivationPath,{chainId:Number(this.chainId),checkOnDevice:!0}),onDeviceActionState:this.onDeviceActionState})};signMessage=async($)=>{let{Signature:Y,toUtf8Bytes:J}=await import("ethers"),j=typeof $==="string"?J($):$,Q=await this.getLedgerSigner(),Z=await A({action:()=>Q.signMessage(this.derivationPath,j),onDeviceActionState:this.onDeviceActionState});return Y.from(Z).serialized};signTypedData=async($,Y,J,j)=>{let{buildEIP712DomainType:Q}=await import("@swapkit/toolboxes/evm"),{hexlify:Z,Signature:B,TypedDataEncoder:G}=await import("ethers"),{EIP712Domain:V,...q}=Y,X=j??G.from(q).primaryType,F=V8({primaryType:X,types:q}),H=await G.resolveNames($,F,J,async(h)=>{let L=await this.resolveName(h);if(!L)throw new G0("wallet_ledger_invalid_params",{name:h});return L}),M=H.domain.chainId==null?void 0:Number(H.domain.chainId);if(M!==void 0&&!Number.isSafeInteger(M))throw new G0("wallet_ledger_invalid_params",{chainId:H.domain.chainId});let O={domain:{...H.domain.chainId!=null&&{chainId:M},...H.domain.name!=null&&{name:H.domain.name},...H.domain.salt!=null&&{salt:Z(H.domain.salt)},...H.domain.verifyingContract!=null&&{verifyingContract:H.domain.verifyingContract},...H.domain.version!=null&&{version:H.domain.version}},message:H.value,primaryType:X,types:{EIP712Domain:Q(H.domain),...F}},y=await this.getLedgerSigner(),I=await A({action:()=>y.signTypedData(this.derivationPath,O),onDeviceActionState:this.onDeviceActionState});return B.from(I).serialized};signTransaction=async($)=>{let{copyRequest:Y,getAddress:J,getBytes:j,resolveAddress:Q,resolveProperties:Z,Transaction:B}=await import("ethers"),G=Y($);if(G.type===4||G.authorizationList?.length)throw new G0("wallet_ledger_invalid_params",{message:"Ledger Ethereum DSK does not support EIP-7702 transactions"});let V=BigInt(this.chainId);if(G.chainId!=null&&G.chainId!==V)throw new G0("wallet_ledger_invalid_params",{chainId:G.chainId,expectedChainId:V,message:"Transaction chainId does not match the Ledger client chain"});let{from:q,to:X}=await Z({from:G.from?Q(G.from,this):void 0,to:G.to?Q(G.to,this):void 0}),F=q||G.nonce==null?await this.getAddress():void 0;if(q&&F&&J(q)!==J(F))throw new G0("wallet_ledger_invalid_params",{message:"Transaction from address does not match the Ledger account"});if(X)G.to=X;if(delete G.from,delete G.authorizationList,G.chainId=V,G.type==null&&G.gasPrice!=null&&G.accessList==null&&G.maxFeePerGas==null&&G.maxPriorityFeePerGas==null)G.type=0;G.nonce??=await this.provider?.getTransactionCount(F??await this.getAddress());let M=B.from(G),N=j(M.unsignedSerialized),O=await this.getLedgerSigner(),y=await A({action:()=>O.signTransaction(this.derivationPath,N),onDeviceActionState:this.onDeviceActionState});return M.signature=y,M.serialized}}function f$($){return new m({...$,chainId:v.Arbitrum})}function y$($){return new m({...$,chainId:v.Arc})}function b$($){return new m({...$,chainId:v.Aurora})}function A$($){return new m({...$,chainId:v.Avalanche})}function D$($){return new m({...$,chainId:v.Base})}function T$($){return new m({...$,chainId:v.Ethereum})}function I$($){return new m({...$,chainId:v.Gnosis})}function E$($){return new m({...$,chainId:v.Optimism})}function C$($){return new m({...$,chainId:v.Polygon})}function P$($){return new m({...$,chainId:v.BinanceSmartChain})}function v$($){return new m({...$,chainId:v.Monad})}function S$($){return new m({...$,chainId:v.XLayer})}function x$($){return new m({...$,chainId:v.Berachain})}import{Chain as F8,NetworkDerivationPath as W8,SwapKitError as F0}from"@swapkit/helpers";async function m$($,Y){let{derivationPath:J,...j}=s({paramsOrPath:$,transport:Y}),Q=(J||W8[F8.Near]).join("'/").concat("'");async function Z({operation:q,requiredUserInteraction:X}){let F=(await import("@ledgerhq/hw-app-near")).default;return u({appName:"NEAR",connection:j,createApp:(H)=>new F(H),operation:q,requiredUserInteraction:X})}let{address:B,publicKey:G}=await Z({operation:(q)=>q.getAddress(Q)});return{getAddress(){return Promise.resolve(B)},async getPublicKey(){let{PublicKey:q}=await import("@near-js/crypto"),X=G.startsWith("ed25519:")?G:`ed25519:${G}`;return q.fromString(X)},signDelegateAction(q){return Promise.reject(new F0("wallet_ledger_method_not_supported",{method:"signDelegateAction",wallet:"Ledger"}))},signNep413Message(q,X,F,H,M){return Promise.reject(new F0("wallet_ledger_method_not_supported",{method:"signNep413Message",wallet:"Ledger"}))},async signTransaction(q){let{Signature:X,SignedTransaction:F}=await import("@near-js/transactions");try{let H=await Z({operation:(O)=>O.signTransaction(q.encode(),Q),requiredUserInteraction:C.SignTransaction});if(!H)throw new F0("wallet_ledger_signing_error",{reason:"Ledger returned no NEAR signature"});let M=new X({data:H,keyType:0}),N=new F({signature:M,transaction:q});return[H,N]}catch(H){if(H instanceof F0)throw H;throw new F0("wallet_ledger_signing_error",{error:H})}}}}import{Chain as M8,derivationPathToString as N8,NetworkDerivationPath as L8,SwapKitError as B0}from"@swapkit/helpers";class l${derivationPath;address=null;publicKey=null;connection;constructor($,Y){let{derivationPath:J,...j}=s({paramsOrPath:$,transport:Y});this.derivationPath=typeof J==="string"?J:N8(J||L8[M8.Sui]),this.connection=j}getLedgerPath(){return this.derivationPath.replace(/^m\//,"").replace(/\/(\d+)\/(\d+)$/,"/$1'/$2'")}async runSuiOperation({operation:$,requiredUserInteraction:Y}){let J=(await import("@ledgerhq/hw-app-sui")).default;return u({appName:"Sui",connection:this.connection,createApp:(j)=>new J(j),operation:$,requiredUserInteraction:Y})}async connect(){let $=this.getLedgerPath(),Y=await this.runSuiOperation({operation:(J)=>J.getPublicKey($)});if(!Y?.publicKey)throw new B0("wallet_ledger_failed_to_get_address");return this.publicKey=Y.publicKey,this.address=`0x${Buffer.from(Y.address).toString("hex")}`,this.address}toSuiAddress(){if(!this.address)throw new B0("wallet_ledger_failed_to_get_address");return this.address}async getAddress(){if(this.address)return this.address;return await this.connect()}async signTransaction($){let Y=$ instanceof Uint8Array?$:$.transaction;if(!this.publicKey)throw new B0("wallet_ledger_failed_to_get_address");try{let J=this.getLedgerPath(),j=new Uint8Array(3+Y.length);j.set(Y,3);let Q=await this.runSuiOperation({operation:(G)=>G.signTransaction(J,j),requiredUserInteraction:C.SignTransaction});if(!Q?.signature)throw new B0("wallet_ledger_signing_error");let Z=this.publicKey.length===33?this.publicKey.slice(1):this.publicKey;if(Z.length!==32)throw new B0("wallet_ledger_signing_error",{error:"Invalid public key length"});let B=new Uint8Array(97);return B.set(Q.signature,1),B.set(Z,65),{bytes:Buffer.from(Y).toString("base64"),signature:Buffer.from(B).toString("base64")}}catch(J){if(J instanceof B0)throw J;throw new B0("wallet_ledger_signing_error",{error:J})}}}function g$($,Y){return new l$($,Y)}import{base64 as f0,hex as U8}from"@scure/base";import{NetworkDerivationPath as k8,SwapKitError as y0}from"@swapkit/helpers";import{SwapKitError as J0}from"@swapkit/helpers";var c$=85,w8=4,K8=0,u0=2,_8=0,R8=1,h$=2,c0=36864,u$=250;class W0{name="THORChainCommand";params;constructor($){this.params=$}getApdu(){let{data:$=new Uint8Array,ins:Y,p1:J=0,p2:j=0}=this.params;return{cla:c$,data:$,ins:Y,p1:J,p2:j}}parseResponse($){let Y=($.statusCode[0]??0)*256+($.statusCode[1]??0);if(Y!==c0)throw Error(`THORChain app returned status 0x${Y.toString(16).padStart(4,"0")}`);return $.data}}function d$({path:$}){if($.length!==5)throw new J0("wallet_ledger_invalid_params",{reason:"THORChain path must contain five elements"});let Y=new Uint8Array(20),J=new DataView(Y.buffer);return $.forEach((j,Q)=>{if(typeof j!=="number"||!Number.isInteger(j)||j<0||j>4294967295)throw new J0("wallet_ledger_invalid_params",{reason:`Invalid THORChain path segment ${Q}`});if(Q>=3&&j>=2147483648)throw new J0("wallet_ledger_invalid_params",{reason:`THORChain path segment ${Q} must not be hardened`});let Z=j&2147483647,B=Q<3?(Z|2147483648)>>>0:Z;J.setUint32(Q*4,B,!0)}),Y}function O8({hrp:$,path:Y}){let J=new TextEncoder().encode($);if(J.length<1||J.length>83)throw new J0("wallet_ledger_invalid_params",{reason:"Invalid THORChain address prefix"});let j=d$({path:Y});return Uint8Array.from([J.length,...J,...j])}function p$({checkOnDevice:$,hrp:Y,path:J}){return new W0({data:O8({hrp:Y,path:J}),ins:w8,p1:$?1:0})}function o$({message:$,path:Y}){let J=[new W0({data:d$({path:Y}),ins:u0,p1:_8})];if($.length===0)return J.push(new W0({data:new Uint8Array,ins:u0,p1:h$})),J;for(let j=0;j<$.length;j+=u$){let Q=Math.min(j+u$,$.length);J.push(new W0({data:$.slice(j,Q),ins:u0,p1:Q===$.length?h$:R8}))}return J}function s$({response:$}){if($.length<2)throw new J0("wallet_ledger_invalid_response",{reason:"THORChain response is missing status bytes"});return $.slice(0,-2)}async function i$({transport:$}){let Y=await $.send(c$,K8,0,0,Buffer.alloc(0),[c0]),J=s$({response:Y});if(J.length<4)throw new J0("wallet_ledger_invalid_response",{reason:"Invalid THORChain version response"});return`${J[1]}.${J[2]}.${J[3]}`}async function n$({command:$,transport:Y}){let J=$.getApdu(),j=await Y.send(J.cla,J.ins,J.p1,J.p2,Buffer.from(J.data),[c0]);return s$({response:j})}function r$({response:$}){if($.length<34)throw new J0("wallet_ledger_invalid_response",{reason:"Invalid THORChain address response"});let Y=$.slice(0,33),J=new TextDecoder().decode($.slice(33));if(!J)throw new J0("wallet_ledger_invalid_response",{reason:"THORChain address is empty"});return{address:J,publicKey:Y}}function d0({version:$}){return`THORChain Ledger app major 2 is required, received ${$||"unknown"}`}var f8="THORChain";function y8($){if(typeof $==="string")return $;let Y=$.chain?.toUpperCase(),J=($.symbol||$.ticker||"").toUpperCase();if(!(Y&&J))return J||Y||"";return`${Y}${$.synth?"/":"."}${J}`}function b8($){return{...$,msgs:$.msgs.map((Y)=>{if(!Y.type.includes("MsgDeposit"))return Y;let J=Y.value.coins;if(!Array.isArray(J))return Y;return{...Y,value:{...Y.value,coins:J.map((j)=>({...j,asset:y8(j.asset)}))}}})}}async function A8({signature:$}){let{Secp256k1Signature:Y}=await import("@cosmjs/crypto");try{return k0(Y.fromDer($).toFixedLength())}catch(J){throw new y0("wallet_ledger_invalid_signature",J)}}async function D8({commands:$,transport:Y}){let J=await i$({transport:Y});if(!J.startsWith("2.")){let{InvalidResponseFormatError:Q}=await import("../chunk-k3thje6a.js");throw new Q(d0({version:J}))}let j=new Uint8Array;for(let Q of $)j=await n$({command:Q,transport:Y});return j}class p0{derivationPath;dmkSession;onDeviceActionState;pubKey;transport;constructor({derivationPath:$=k8.THOR,dmkSession:Y,onDeviceActionState:J,transport:j}={}){if(Y&&j)throw new y0("wallet_ledger_invalid_params",{message:"Provide either a Ledger DMK session or a LedgerJS transport, not both"});this.derivationPath=$,this.dmkSession=Y,this.onDeviceActionState=J,this.transport=j}get pubkey(){return this.pubKey?f0.encode(this.pubKey):null}executeCommands=async({commands:$,requiredUserInteraction:Y})=>{if(this.transport)try{return await D8({commands:$,transport:this.transport})}catch(N){throw d(N,{userRefusedStatusWords:e})}let J=this.dmkSession??await n(),{Apdu:j,CallTaskInAppDeviceAction:Q,CommandResultFactory:Z,DmkResultFactory:B,InvalidResponseFormatError:G,InvalidStatusWordError:V,isSuccessCommandResult:q,UnknownDeviceExchangeError:X}=await import("../chunk-k3thje6a.js"),F=(N)=>{let O=N.getApdu();return{getApdu:()=>new j(O.cla,O.ins,O.p1,O.p2,O.data),name:N.name,parseResponse:(y)=>{try{return Z({data:N.parseResponse(y)})}catch(I){let h=U8.encode(y.statusCode);return Z({error:Object.assign(new V(I instanceof Error?I.message:String(I)),{errorCode:h})})}}}},H=new Q({input:{appName:f8,requiredUserInteraction:Y,skipOpenApp:!1,task:async(N)=>{try{let O=N.getDeviceSessionState(),y="currentApp"in O?O.currentApp.version:void 0;if(!y?.startsWith("2."))return B({error:new G(d0({version:y}))});let I=new Uint8Array;for(let h of $){let L=await N.sendCommand(F(h));if(!q(L))return B({error:L.error});I=L.data}return B({data:{response:I}})}catch(O){return B({error:new X(O)})}}}});return(await A({action:()=>J.dmk.executeDeviceAction({deviceAction:H,sessionId:J.sessionId}),onDeviceActionState:this.onDeviceActionState,userRefusedStatusWords:e})).response};getAddressData=async({checkOnDevice:$})=>{let Y=await this.executeCommands({commands:[p$({checkOnDevice:$,hrp:"thor",path:this.derivationPath})],requiredUserInteraction:$?C.VerifyAddress:C.None});return r$({response:Y})};signBytes=async({message:$})=>{let Y=await this.executeCommands({commands:o$({message:$,path:this.derivationPath}),requiredUserInteraction:C.SignTransaction});return A8({signature:Y})};connect=async()=>{let{address:$,publicKey:Y}=await this.getAddressData({checkOnDevice:!1});return this.pubKey=Y,$};getAddressAndPubKey=async()=>{let{address:$,publicKey:Y}=await this.getAddressData({checkOnDevice:!1});return this.pubKey=Y,{bech32_address:$,compressed_pk:Y,error_message:"No errors",return_code:36864}};showAddressAndPubKey=async()=>{let{address:$,publicKey:Y}=await this.getAddressData({checkOnDevice:!0});return this.pubKey=Y,{bech32_address:$,compressed_pk:Y,error_message:"No errors",return_code:36864}};signTransaction=async({rawTx:$,sequence:Y="0"})=>{if(!this.pubKey)await this.connect();let J=this.pubKey;if(!J)throw new y0("wallet_ledger_pubkey_not_found");let j=await this.signBytes({message:new TextEncoder().encode($)});return[{pub_key:{type:"tendermint/PubKeySecp256k1",value:f0.encode(J)},sequence:Y,signature:f0.encode(j)}]};signAmino=async($,Y)=>{let J=(await this.getAccounts()).find(({address:B})=>B===$);if(!J)throw new y0("wallet_ledger_address_not_found",{address:$});let{encodeSecp256k1Signature:j,serializeSignDoc:Q}=await import("@cosmjs/amino"),Z=await this.signBytes({message:Q(b8(Y))});return{signature:j(J.pubkey,Z),signed:Y}};getAccounts=async()=>{let{address:$,publicKey:Y}=await this.getAddressData({checkOnDevice:!1});return this.pubKey=Y,[{address:$,algo:"secp256k1",pubkey:Y}]};sign=async($)=>f0.encode(await this.signBytes({message:new TextEncoder().encode($)}))}import{derivationPathToString as T8,NetworkDerivationPath as I8,SwapKitError as M0}from"@swapkit/helpers";class a${derivationPath;ledgerTimeout=50000;connection;constructor($,Y){let{derivationPath:J,...j}=s({paramsOrPath:$,transport:Y});this.derivationPath=typeof J==="string"?J:T8(J||I8.TRON),this.connection=j}async runTronOperation({operation:$,requiredUserInteraction:Y}){let J=(await import("@ledgerhq/hw-app-trx")).default;return u({appName:"Tron",connection:this.connection,createApp:(j)=>new J(j),operation:$,requiredUserInteraction:Y})}checkOrCreateTransportAndLedger=async()=>{await this.runTronOperation({operation:async()=>!0})};createTransportAndLedger=async()=>{await this.runTronOperation({operation:async()=>!0})};getAddress=async()=>{let $=await this.getAddressAndPubKey();if(!$)throw new M0("wallet_ledger_failed_to_get_address");return $.address};getAddressAndPubKey=async()=>{let $=await this.runTronOperation({operation:(Y)=>Y.getAddress(this.derivationPath)});if(!$)throw new M0("wallet_ledger_failed_to_get_address");return{address:$.address,publicKey:$.publicKey}};showAddressAndPubKey=async()=>{return await this.runTronOperation({operation:($)=>$.getAddress(this.derivationPath,!0),requiredUserInteraction:C.VerifyAddress})};signTransaction=async($)=>{try{let Y=await this.runTronOperation({operation:(J)=>J.signTransaction(this.derivationPath,$.raw_data_hex,[]),requiredUserInteraction:C.SignTransaction});if(!Y)throw new M0("wallet_ledger_signing_error");return{...$,signature:[Y]}}catch(Y){if(Y instanceof M0)throw Y;throw new M0("wallet_ledger_signing_error",{error:Y})}}}function t$($,Y){return new a$($,Y)}import{Chain as E8,derivationPathToString as C8,NetworkDerivationPath as P8}from"@swapkit/helpers";var v8=2147483648;function S8($){return Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==null&&Y!==void 0))}async function e$($,Y){let{derivationPath:J,...j}=s({paramsOrPath:$,transport:Y}),Q=C8(J||P8[E8.Ripple]);async function Z({operation:q,requiredUserInteraction:X}){let F=(await import("@ledgerhq/hw-app-xrp")).default;return u({appName:"XRP",connection:j,createApp:(H)=>new F(H),operation:q,requiredUserInteraction:X})}let{address:B,publicKey:G}=await Z({operation:(q)=>q.getAddress(Q)});async function V(q){let[{encode:X},{hashes:F}]=await Promise.all([import("ripple-binary-codec"),import("xrpl")]),H={...S8(q),Flags:q.Flags||v8,SigningPubKey:G.toUpperCase()},M=X(H),N=await Z({operation:(I)=>I.signTransaction(Q,M),requiredUserInteraction:C.SignTransaction}),O=X({...H,TxnSignature:N});return{hash:F.hashSignedTx(O),tx_blob:O}}return{getAddress:()=>B,signTransaction:V}}import{hex as o}from"@scure/base";import{derivationPathToString as x8,NetworkDerivationPath as m8,SwapKitError as a}from"@swapkit/helpers";var l8=3364600;function $5($){return(typeof $==="string"?$:x8($)).replace(/^m\//,"").replace(/^\/+/,"")}function b0($){let Y=$5($),J=/^44'\/133'\/(\d+)'(?:\/(0|1)\/(\d+))?$/.exec(Y);if(!J)throw new a("wallet_ledger_invalid_params",{path:Y,reason:"Expected a Zcash BIP44 path with coin type 133"});let j=Number(J[1]),Q=`44'/133'/${j}'`;return{account:j,accountPath:Q,fullPath:`${Q}/${J[2]??0}/${J[3]??0}`}}function g8($){let Y=new Uint8Array(4);return new DataView(Y.buffer).setUint32(0,$>>>0,!0),Y}function h8($){let Y=new Uint8Array(8);return new DataView(Y.buffer).setBigUint64(0,$,!0),Y}function q0($,Y){return new a({errorKey:"wallet_ledger_invalid_params",info:$},Y)}function u8({bytes:$,offset:Y}){if(Y+4>$.length)throw Error("Unexpected end of previous transaction");return new DataView($.buffer,$.byteOffset+Y,4).getUint32(0,!0)}function c8($){let Y=0;function J(Q){if(Y+Q>$.length)throw Error(`Previous transaction ends before byte ${Y+Q}`);return Y+=Q,$.slice(Y-Q,Y)}function j(){let Q=J(1)[0]??0;if(Q<253)return Q;let Z=new DataView(J(Q===253?2:Q===254?4:8).buffer),B=Z.byteLength===2?Z.getUint16(0,!0):Z.byteLength===4?Z.getUint32(0,!0):Number(Z.getBigUint64(0,!0));if(!Number.isSafeInteger(B))throw Error("Previous transaction compact-size value exceeds safe range");return B}return{compactSize:j,rest:()=>J($.length-Y),take:J,varBytes:()=>J(j())}}function d8({bytes:$,version:Y}){let J=c8($),j=J.take(Y===4?8:20),Q=[];for(let q=J.compactSize();Q.length<q;){let X=J.take(36),F=J.varBytes(),H=J.take(4);Q.push({prevout:X,script:F,sequence:H})}let Z=[];for(let q=J.compactSize();Z.length<q;){let X=J.take(8),F=J.varBytes();Z.push({amount:X,script:F})}let B={inputs:Q,nVersionGroupId:j.slice(4,8),outputs:Z,version:j.slice(0,4)};if(Y>=5)return{...B,consensusBranchId:j.slice(8,12),locktime:j.slice(12,16),nExpiryHeight:j.slice(16,20)};let G=J.take(4),V=J.take(4);return{...B,extraData:J.rest(),locktime:G,nExpiryHeight:V}}function Y5({hash:$,txid:Y}){let J=$.toLowerCase();return J===o.encode(Y)||J===o.encode(Y.slice().reverse())}async function p8($){let{CompactSize:Y,utils:J}=await import("@swapkit/utxo-signer"),j=Array.from({length:$.outputsLength},(Q,Z)=>$.getOutput(Z));return J.concatBytes(Y.encode(BigInt(j.length)),...j.flatMap(({amount:Q,script:Z})=>[h8(Q),Y.encode(BigInt(Z.length)),Z]))}async function o8($){let{ZCASH_IRONWOOD_ACTIVATION_HEIGHT:Y,ZcashConsensusBranchId:J}=await import("@swapkit/utxo-signer");switch($){case J.NU6_2:return l8;case J.IRONWOOD:return Y;default:throw new a("wallet_ledger_invalid_params",{consensusBranchId:$,reason:"Ledger Zcash DSK signing supports NU6.2 and Ironwood target branches"})}}async function s8({inputIndex:$,utxo:Y}){let{hash:J,index:j,txHex:Q}=Y,Z={inputIndex:$,outputIndex:j,txid:J};if(!Q)throw q0({...Z,reason:"Zcash Ledger signing requires the full previous transaction txHex for every input"});function B(M){try{return M()}catch(N){throw q0({...Z,reason:N instanceof Error?N.message:String(N)},N)}}let G=B(()=>o.decode(Q.replace(/^0x/i,""))),V=B(()=>u8({bytes:G,offset:0})),q=V&2147483647;if((V&2147483648)===0||q<4||q>6)throw q0({...Z,reason:"Ledger Zcash signing supports only overwintered v4, v5 and v6 previous transactions",version:q});let X=B(()=>d8({bytes:G,version:q}));if(j<0||j>=X.outputs.length)throw q0({...Z,outputCount:X.outputs.length,reason:"Zcash input references an output outside its previous transaction"});if(q>=5)return{...X,serializedPreviousTransactionOverride:G};let{utils:F}=await import("@swapkit/utxo-signer"),H=F.sha256x2(G);if(!Y5({hash:J,txid:H}))throw q0({...Z,previousTxid:o.encode(H.reverse()),reason:"Previous transaction does not hash to the input txid"});return X}function i8({accountPath:$,derivationPaths:Y,inputUtxos:J,tx:j}){if(J.length!==j.inputsLength||Y.length!==j.inputsLength)throw new a("wallet_ledger_invalid_params",{derivationPathCount:Y.length,inputCount:j.inputsLength,inputUtxoCount:J.length,reason:"Zcash input UTXOs and derivation paths must match the transaction input count"});return J.forEach((Q,Z)=>{let B=j.getInput(Z);if(!Y5({hash:Q.hash,txid:B.txid})||Q.index!==B.index)throw q0({inputIndex:Z,reason:"Zcash input UTXO does not match the transaction input",transactionInput:{index:B.index,txid:o.encode(B.txid)},utxo:{hash:Q.hash,index:Q.index}})}),Y.map((Q)=>{let Z=b0(Q);if(Z.accountPath!==$)throw new a("wallet_ledger_invalid_params",{accountPath:$,path:Z.fullPath,reason:"All Zcash input derivation paths must belong to the configured account"});return Z.fullPath})}function n8($){let Y=$.replace(/^0x/i,""),J=o.decode(Y);if(J.length<4||(new DataView(J.buffer,J.byteOffset,4).getUint32(0,!0)&2147483647)!==5)throw new a("wallet_ledger_invalid_response",{reason:"Ledger Zcash signer did not return a version 5 transaction"});return Y}function J5({derivationPath:$=m8.ZEC,dmkSession:Y,onDeviceActionState:J,transport:j}={}){let Q=b0($),Z=j?F$($,j):void 0,B=$0({build:async(F)=>{let{SignerZcashBuilder:H}=await import("../chunk-gr3eswf1.js");return new H(F).build()},dmkSession:Y});function G(){if(Z)throw new a("wallet_ledger_invalid_params",{reason:"A Device Signer Kit operation is unavailable when a legacy transport is supplied"});return B()}async function V({checkOnDevice:F=!1,path:H=Q.fullPath}={}){let M=await G();return A({action:()=>M.getAddress(H,{checkOnDevice:F}),onDeviceActionState:J})}async function q({path:F=Q.accountPath,xpubVersion:H=76067358}={}){let M=b0(F);if(M.fullPath!==`${M.accountPath}/0/0`||$5(F).split("/").length!==3)throw new a("wallet_ledger_invalid_params",{path:F,reason:"Zcash extended public keys are exported at account level"});let N={dmkSession:j?void 0:Y??await n(),onDeviceActionState:J,transport:j},{default:O}=await import("@ledgerhq/hw-app-btc");return u({appName:"Zcash",connection:N,createApp:(y)=>new O({currency:"zcash",transport:y}),operation:(y)=>y.getWalletXpub({path:M.accountPath,xpubVersion:H})})}async function X({changePath:F,derivationPaths:H,inputUtxos:M,tx:N}){let O=i8({accountPath:Q.accountPath,derivationPaths:H??Array.from({length:N.inputsLength},()=>Q.fullPath),inputUtxos:M,tx:N});if(Z)throw new a("wallet_ledger_invalid_params",{reason:"Zcash signing requires a Ledger DMK session instead of a legacy transport"});let y=await o8(N.consensusBranchId),I=await Promise.all(M.map(async(k,P)=>[await s8({inputIndex:P,utxo:k}),k.index,null,N.getInput(P).sequence??4294967295])),h={additionals:["zcash","sapling"],associatedKeysets:O,blockHeight:y,changePath:F?b0(F).fullPath:Q.fullPath,expiryHeight:g8(N.expiryHeight),inputs:I,lockTime:N.lockTime,outputScriptHex:o.encode(await p8(N))},L=await G(),w=await A({action:()=>L.signTransaction(h),onDeviceActionState:J});return n8(w)}return{connect:async()=>{if(Z)return Z.connect();await G()},disconnect:async()=>Z?.disconnect(),getAddress:async()=>{if(Z)return Z.getAddress();return(await V()).address},getAddressAndPubKey:async()=>{if(Z)return{address:await Z.getAddress()};let{address:F,chainCode:H,publicKey:M}=await V();return{address:F,chainCode:o.encode(H),publicKey:o.encode(M)}},getExtendedPublicKey:q,showAddressAndPubKey:async()=>{if(Z)return{address:await Z.getAddress()};let{address:F,chainCode:H,publicKey:M}=await V({checkOnDevice:!0});return{address:F,chainCode:o.encode(H),publicKey:o.encode(M)}},signTransaction:X,signTransactionWithMultiplePaths:async(F)=>X(F)}}async function c({chain:$,dmkSession:Y,derivationPath:J,onDeviceActionState:j,originToken:Q,transport:Z}){let B=r8.includes($);if(Y&&Z)throw new o0("wallet_ledger_invalid_params",{message:"Provide either a Ledger DMK session or a LedgerJS transport, not both"});if(B&&Z)throw new o0("wallet_ledger_invalid_params",{message:"Ledger EVM clients require a DMK session instead of a LedgerJS transport"});let G={derivationPath:J??a8[$],dmkSession:Y,onDeviceActionState:j,transport:Z},{match:V}=await import("ts-pattern");return V($).returnType().with(_.THORChain,()=>Promise.resolve(new p0(G))).with(_.Cosmos,()=>Promise.resolve(new h0(G))).with(_.Bitcoin,()=>Promise.resolve(O$(G))).with(_.BitcoinCash,()=>Promise.resolve(q$(G))).with(_.Dash,()=>Promise.resolve(H$(G))).with(_.Dogecoin,()=>Promise.resolve(V$(G))).with(_.Litecoin,()=>Promise.resolve(z$(G))).with(_.Zcash,()=>Promise.resolve(J5(G))).with(_.Ripple,()=>Promise.resolve(e$(G))).with(_.Tron,()=>Promise.resolve(t$(G))).with(_.Sui,()=>Promise.resolve(g$(G))).with(_.Near,()=>Promise.resolve(m$(G))).with(_.Arbitrum,_.Arc,_.Aurora,_.Avalanche,_.Berachain,_.BinanceSmartChain,_.Ethereum,_.Gnosis,_.Monad,_.Optimism,_.Polygon,_.Base,_.XLayer,async()=>{let{getProvider:q}=await import("@swapkit/toolboxes/evm"),X={derivationPath:J,dmkSession:Y,onDeviceActionState:j,originToken:Q,provider:await q($)};return V($).with(_.BinanceSmartChain,()=>P$(X)).with(_.Avalanche,()=>A$(X)).with(_.Arbitrum,()=>f$(X)).with(_.Arc,()=>y$(X)).with(_.Berachain,()=>x$(X)).with(_.Optimism,()=>E$(X)).with(_.Polygon,()=>C$(X)).with(_.Base,()=>D$(X)).with(_.Aurora,()=>b$(X)).with(_.Gnosis,()=>I$(X)).with(_.Monad,()=>v$(X)).with(_.XLayer,()=>S$(X)).otherwise(()=>T$(X))}).otherwise(()=>{throw new o0("wallet_chain_not_supported",{chain:$,wallet:t8.LEDGER})})}var V5=[z.Arbitrum,z.Arc,z.Aurora,z.Avalanche,z.Base,z.Berachain,z.BinanceSmartChain,z.Bitcoin,z.BitcoinCash,z.Cosmos,z.Dash,z.Dogecoin,z.Ethereum,z.Gnosis,z.Litecoin,z.Monad,z.Near,z.Optimism,z.Polygon,z.Ripple,z.Sui,z.THORChain,z.XLayer,z.Tron,z.Zcash],X9=[z.BitcoinCash,z.Bitcoin,z.Dash,z.Dogecoin,z.Litecoin,z.Zcash],z9=[z.Ethereum,z.Avalanche,z.Arbitrum,z.Arc,z.Berachain,z.Optimism,z.Polygon,z.BinanceSmartChain,z.Base,z.Aurora,z.Gnosis,z.Monad,z.XLayer];function q9($){return V5.includes($)}var V9=G9({connect:({addChain:$,supportedChains:Y,walletType:J})=>async function(Q,Z,{address:B,dmkSession:G,onDeviceActionState:V,originToken:q,transport:X}={}){let[F]=e8({chains:Q,supportedChains:Y,walletType:J});if(!F)return!1;let H=Z??Y9[F],M=await O9({address:B,chain:F,derivationPath:H,dmkSession:G,onDeviceActionState:V,originToken:q,transport:X});return $({...M,chain:F,walletType:N0.LEDGER}),!0},directSigningSupport:{[z.Arbitrum]:!0,[z.Arc]:!0,[z.Aurora]:!0,[z.Avalanche]:!0,[z.Base]:!0,[z.Berachain]:!0,[z.BinanceSmartChain]:!0,[z.Ethereum]:!0,[z.Gnosis]:!0,[z.Monad]:!0,[z.Bitcoin]:!0,[z.BitcoinCash]:!0,[z.Cosmos]:!0,[z.Dash]:!0,[z.Dogecoin]:!0,[z.Litecoin]:!0,[z.Near]:!0,[z.Optimism]:!0,[z.Polygon]:!0,[z.Ripple]:!0,[z.Sui]:!0,[z.THORChain]:!0,[z.Tron]:!0,[z.XLayer]:!0},getExtendedPublicKey:F9,name:"connectLedger",supportedChains:[...V5],walletType:N0.LEDGER}),q1=B9(V9);function H5({chain:$,path:Y,signer:J,xpubVersion:j}){let Q=L0($).with(z.Bitcoin,z.Litecoin,()=>Y).with(z.BitcoinCash,z.Dash,z.Dogecoin,z.Zcash,()=>Y.replace(/^m\//,"")).exhaustive();return L0($).with(z.Bitcoin,()=>J.getExtendedPublicKey({path:Q})).with(z.Zcash,()=>J.getExtendedPublicKey({path:Q,xpubVersion:j})).with(z.BitcoinCash,z.Dash,z.Dogecoin,z.Litecoin,()=>J.getExtendedPublicKey(Q,j)).exhaustive()}function H9($){let Y=q5(z.Zcash),J=U0((j)=>Y.getRawTx(j));return Promise.all(Array.from({length:$.inputsLength},async(j,Q)=>{let Z=$.getInput(Q),B=j5.encode(Z.txid),G=j5.encode(Z.txid.slice().reverse()),V=await J(B),[q,X]=V?[B,V]:[G,await J(G)];if(!X)throw new j0("wallet_ledger_invalid_params",{inputIndex:Q,outputIndex:Z.index,reason:"Unable to resolve previous transaction hex for Ledger signing in either txid byte order",reversedTxid:G,txid:B});return{hash:q,index:Z.index,txHex:X,value:Number(Z.value)}}))}async function F9($,Y,{accountIndex:J,dmkSession:j,onDeviceActionState:Q,transport:Z}={}){if(![z.BitcoinCash,z.Bitcoin,z.Dash,z.Dogecoin,z.Litecoin,z.Zcash].includes($))throw new j0("wallet_chain_not_supported",{chain:$,wallet:N0.LEDGER});let B=$,G=await c({chain:B,derivationPath:Y,dmkSession:j,onDeviceActionState:Q,transport:Z});if(!G.getExtendedPublicKey)return;let V=z5({accountIndex:J,chain:B,derivationPath:Y}),q=D0(V),X=X5(B).bip32.public;try{let F=await H5({chain:B,path:q,signer:G,xpubVersion:X});return{accountIndex:s0(V),path:q,xpub:F}}finally{await G.disconnect?.()}}async function W9({address:$,chain:Y,dmkSession:J,derivationPath:j,onDeviceActionState:Q,transport:Z}){let{getUtxoToolbox:B}=await import("@swapkit/toolboxes/utxo"),G=Y,V=await c({chain:Y,derivationPath:j,dmkSession:J,onDeviceActionState:Q,transport:Z}),q=$??await r({chain:Y,ledgerClient:V}),X=(Y===z.Bitcoin?$9(j):void 0)??Z9(q,G),{publicKey:F,signLedgerTransaction:H,toolboxSigner:M}=await L0(Y).with(z.Bitcoin,async()=>{let K=V,U=X===A0.P2SH_P2WPKH||X===A0.P2TR?await K.getPublicKey():void 0;return{publicKey:U,signLedgerTransaction:({inputUtxos:f,transaction:D})=>K.signTransactionHex({inputUtxos:f,tx:D}),toolboxSigner:{getAddress:K.getAddress,publicKey:U,signTransaction:K.signTransaction}}}).with(z.BitcoinCash,z.Dogecoin,z.Dash,z.Litecoin,async()=>{let{createLegacyPsbtSigner:K,signLegacyPsbtTransaction:R}=await import("../chunk-5p3ttw6y.js"),U=V;return{publicKey:void 0,signLedgerTransaction:({inputUtxos:f,transaction:D})=>R({chain:G,inputUtxos:f,legacyClient:U,tx:D}),toolboxSigner:K({address:q,chain:G,legacyClient:U})}}).with(z.Zcash,()=>{let K=V;return{publicKey:void 0,signLedgerTransaction:async({inputUtxos:R,transaction:U})=>{if(!("consensusBranchId"in U))throw new j0("wallet_ledger_method_not_supported",{method:"signPCZT",wallet:N0.LEDGER});let f=R??await H9(U);return K.signTransaction({inputUtxos:f,tx:U})},toolboxSigner:void 0}}).exhaustive(),N=M?await B(G,{scriptType:X,signer:M}):B(G,{scriptType:X}),O=async(K)=>N.broadcastTx(await H({transaction:K})),y=async(K)=>{let R=K.feeRate||(await N.getFeeRates())[K.feeOptionKey||Q5.Fast],{tx:U,inputs:f}=await N.createTransaction({...K,feeRate:R,fetchTxHex:!0,publicKey:K.publicKey??F,sender:q}),D=await H({inputUtxos:f,transaction:U});return await N.broadcastTx(D)};async function I({accountIndex:K}={}){if(!V.getExtendedPublicKey)return;let R=z5({accountIndex:K,chain:G,derivationPath:j}),U=D0(R),f=X5(G).bip32.public,D=await H5({chain:Y,path:U,signer:V,xpubVersion:f});return{accountIndex:s0(R),path:U,xpub:D}}function h(K={}){return I(K)}async function L({accountIndex:K,index:R,change:U=!1}){try{let f=G5({accountIndex:K,chain:G,change:U,derivationPath:j,index:R}),D=await c({chain:G,derivationPath:f,dmkSession:J,onDeviceActionState:Q,transport:Z}),S=await r({chain:G,ledgerClient:D});return{accountIndex:s0(f),address:S,change:U,index:R,path:D0(f),pubkey:""}}catch{return}}async function w({accountIndex:K,count:R,startIndex:U=0,change:f=!1}){return Z5("count",R),Z5("startIndex",U),(await Promise.all(Array.from({length:R},(S,T)=>L({accountIndex:K,change:f,index:U+T})))).filter((S)=>!!S)}let k=Q9({chain:G,deriveAddress:L,getBalance:N.getBalance,getUtxos:(K)=>q5(G).getUtxos({address:K,fetchTxHex:!0})});async function P({utxos:K,recipient:R,assetValue:U,memo:f,feeRate:D,feeOptionKey:S,changeAddress:T}){if(Y===z.Zcash)throw new j0("wallet_ledger_method_not_supported",{method:"transferFromMultipleAddresses",wallet:N0.LEDGER});if(!K.length)throw new j0("wallet_ledger_invalid_params",{message:"No UTXOs provided for multi-address transfer"});let E=D||(await N.getFeeRates())[S||Q5.Fast],l=f?j9(f):null,Q0=[{address:R,value:U.getBaseValue("number")}];if(l)Q0.push({script:l,value:0});let t=K.map(({hash:K0,index:_0,value:I0,txHex:R0,witnessUtxo:M5})=>({hash:K0,index:_0,txHex:R0,value:I0,witnessUtxo:M5})),{inputs:i,outputs:V0}=N.accumulative({chain:G,feeRate:E,inputs:t,outputs:Q0});if(!(i&&V0))throw new j0("wallet_ledger_connection_error",{message:"Insufficient balance for multi-address transfer"});let{Transaction:w0}=await import("@swapkit/utxo-signer"),T0=new w0({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!l,version:1}),F5=T||K[0]?.address||R;J9({chain:G,compiledMemo:l,inputs:i,outputs:V0,sender:F5,tx:T0});let i0=i.map((K0)=>{let _0=K.find((R0)=>R0.hash===K0.hash&&R0.index===K0.index),I0=G5({chain:G,change:_0?.isChange??!1,derivationPath:j,index:_0?.derivationIndex??0});return D0(I0)});if(!V.signTransactionWithMultiplePaths)throw new j0("wallet_ledger_method_not_supported",{method:"signTransactionWithMultiplePaths"});let W5=await L0(Y).with(z.Bitcoin,()=>V.signTransactionWithMultiplePaths({derivationPaths:i0,inputUtxos:i,tx:T0})).with(z.BitcoinCash,z.Dash,z.Dogecoin,z.Litecoin,()=>V.signTransactionWithMultiplePaths(T0,i,i0)).exhaustive();return N.broadcastTx(W5)}return{...N,...k,address:q,deriveAddressAtIndex:L,deriveAddresses:w,getExtendedPublicKey:h,getExtendedPublicKeyInfo:I,signAndBroadcastTransaction:O,transfer:y,transferFromMultipleAddresses:P}}async function M9({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,originToken:Q,transport:Z}){let B=await c({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,originToken:Q,transport:Z}),{getEvmToolboxAsync:G}=await import("@swapkit/toolboxes/evm"),V=await r({chain:$,ledgerClient:B});return{...await G($,{signer:B}),address:V}}async function N9({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}){let Z=await c({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}),{getCosmosToolbox:B}=await import("@swapkit/toolboxes/cosmos"),G=B($,{signer:Z}),V=await r({chain:$,ledgerClient:Z});return{...G,address:V}}async function L9({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}){let Z=await c({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}),{getCosmosToolbox:B}=await import("@swapkit/toolboxes/cosmos"),G=B($,{signer:Z}),V=await r({chain:$,ledgerClient:Z}),{sign:q}=Z;return{...G,address:V,signMessage:q}}async function w9({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}){let{getNearToolbox:Z}=await import("@swapkit/toolboxes/near"),B=await c({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}),G=await B.getAddress();return{...Z({signer:B}),address:G}}async function K9({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}){let{getRippleToolbox:Z}=await import("@swapkit/toolboxes/ripple"),B=await c({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}),G=B.getAddress();return{...Z({signer:B}),address:G}}async function _9({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}){let{getTronToolbox:Z}=await import("@swapkit/toolboxes/tron"),B=await c({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}),G=await r({chain:$,ledgerClient:B});return{...Z({signer:B}),address:G}}async function R9({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}){let{getSuiToolbox:Z}=await import("@swapkit/toolboxes/sui"),B=await c({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}),G=await r({chain:$,ledgerClient:B});return{...Z({signer:B}),address:G}}function O9($){if(!q9($.chain))throw new j0("wallet_ledger_chain_not_supported",{chain:$.chain});return L0($.chain).with(B5.union(...X9),(Y)=>W9({...$,chain:Y})).with(B5.union(...z9),(Y)=>M9({...$,chain:Y})).with(z.Cosmos,(Y)=>N9({...$,chain:Y})).with(z.THORChain,(Y)=>L9({...$,chain:Y})).with(z.Near,(Y)=>w9({...$,chain:Y})).with(z.Ripple,(Y)=>K9({...$,chain:Y})).with(z.Tron,(Y)=>_9({...$,chain:Y})).with(z.Sui,(Y)=>R9({...$,chain:Y})).exhaustive()}export{e0 as preloadLedgerDMK,V9 as ledgerWallet,F9 as getLedgerExtendedPublicKey,n as getLedgerDMKSession,$$ as disconnectLedgerDMKSession,q1 as LEDGER_SUPPORTED_CHAINS};
1
+ import{Ea as D0,Fa as f$,Ga as c0}from"../chunk-b7htg03t.js";import{Ia as y$}from"../chunk-g6rrzxcx.js";import{Ja as O$}from"../chunk-j3n6fbqh.js";import{ae as H}from"../chunk-kaw35ae2.js";import{hex as K8}from"@scure/base";import{AssetValue as CY,Chain as q,derivationPathToString as v0,FeeOption as R8,filterSupportedChains as vY,getUTXOScriptTypeForPath as PY,NetworkDerivationPath as SY,SwapKitError as t,UTXOScriptType as C0,WalletOption as N0}from"@swapkit/helpers";import{addInputsAndOutputs as xY,assertDerivationIndex as w8,compileMemo as mY,createHDWalletHelpers as lY,getNetworkForChain as f8,getScriptTypeForAddress as gY,getUTXOAccountIndexFromPath as e0,getUTXOAccountPath as k8,getUTXOAddressPath as U8,getUtxoApi as b8}from"@swapkit/toolboxes/utxo";import{createWallet as hY,getWalletSupportedChains as uY}from"@swapkit/wallet-core";import{match as U0,P as O8}from"ts-pattern";import{SwapKitError as Z0}from"@swapkit/helpers";import{filter as c8,firstValueFrom as J$,map as d8,timeout as p8}from"rxjs";import{SwapKitError as A0}from"@swapkit/helpers";import{match as Y$}from"ts-pattern";var x0={Completed:"completed",Error:"error",Stopped:"stopped"},T={None:"none",SignTransaction:"sign-transaction",VerifyAddress:"verify-address"},C8=new Set(["6985","5501"]),$0=["6986"],v8=new Set(["5515"]),P8=new Set(["6511","6807","6d00","6e00"]),S8=new Set(["DeviceDisconnectedBeforeSendingApdu","DeviceDisconnectedWhileSendingError","DeviceNotRecognizedError","DeviceSessionNotFound","NoAccessibleDeviceError","ReconnectionFailedError"]),x8=new Set(["DisconnectedDevice","DisconnectedDeviceDuringOperation"]),m8=new Set(["UserRefusedOnDevice"]),l8=4,g8=/^(?:0x)?([0-9a-f]{4})$/i;function h8($){let Y=[],J=$;while(Y.length<l8&&typeof J==="object"&&J!==null){let j=J;Y.push(j),J=j.originalError}return Y}function u8({errorCode:$,statusCode:Y}){let J=typeof $==="string"?g8.exec($)?.[1]:void 0;if(J)return J.toLowerCase();return typeof Y==="number"?Y.toString(16).padStart(4,"0"):void 0}function p($,{userRefusedStatusWords:Y=[]}={}){let J=h8($),j=J.find((z)=>z instanceof A0);if(j)return j;let Q=J.flatMap(({_tag:z})=>typeof z==="string"?[z]:[]),Z=J.flatMap(({name:z})=>typeof z==="string"?[z]:[]),G=J.map(u8).find((z)=>z!==void 0),X=J.map((z)=>z.message).filter((z)=>typeof z==="string"&&z.length>0).at(-1),F=new Set([...C8,...Y]),B=Y$({errorNames:Z,errorTags:Q,statusWord:G}).when(({errorNames:z,errorTags:W,statusWord:V})=>W.includes("RefusedByUserDAError")||z.some((M)=>m8.has(M))||!!V&&F.has(V),()=>"wallet_connection_rejected_by_user").when(({errorTags:z,statusWord:W})=>z.includes("DeviceLockedError")||!!W&&v8.has(W),()=>"wallet_ledger_device_locked").when(({errorTags:z,statusWord:W})=>z.includes("UnsupportedApplicationDAError")||!!W&&P8.has(W),()=>"wallet_ledger_app_not_open").when(({errorNames:z,errorTags:W})=>W.some((V)=>S8.has(V))||z.some((V)=>x8.has(V)),()=>"wallet_ledger_connection_error").otherwise(()=>"wallet_ledger_transport_error");return new A0({errorKey:B,info:{errorTag:Q[0],message:X,statusWord:G}},$)}function E({action:$,onDeviceActionState:Y,userRefusedStatusWords:J}){return new Promise((j,Q)=>{let Z;try{Z=$().observable}catch(B){Q(p(B,{userRefusedStatusWords:J}));return}let G=!1,X;function F(B){if(G)return;G=!0,X?.unsubscribe(),B()}if(X=Z.subscribe({complete:()=>{F(()=>Q(new A0("wallet_ledger_invalid_response")))},error:(B)=>{F(()=>Q(p(B,{userRefusedStatusWords:J})))},next:(B)=>{try{Y?.(B)}catch(z){}Y$(B).with({status:x0.Completed},({output:z})=>F(()=>j(z))).with({status:x0.Error},({error:z})=>F(()=>Q(p(z,{userRefusedStatusWords:J})))).with({status:x0.Stopped},()=>F(()=>Q(new A0("wallet_ledger_connection_error")))).otherwise(()=>{return})}}),G)X.unsubscribe()})}var o8=1000,m0,h;function s8(){if(typeof navigator>"u"||!("hid"in navigator))return Promise.reject(new Z0("wallet_ledger_webhid_not_supported"));return Promise.all([import("../chunk-a47dwwv6.js"),import("../chunk-545s1tsc.js")]).then(([{DeviceManagementKitBuilder:$},{webHidTransportFactory:Y}])=>new $().addTransport(Y).build()).catch(($)=>{if(m0=void 0,$ instanceof Z0)throw $;throw new Z0("wallet_ledger_connection_error",$)})}function j$(){return m0??=s8(),m0}function l0(){return j$().then(($)=>Q$({dmk:$}))}function i8($){return typeof $==="object"&&$!==null&&"_tag"in $&&$._tag==="DeviceSessionNotFound"}function n8({dmk:$,sessionId:Y}){try{return $.getConnectedDevice({sessionId:Y}),!0}catch(J){return!1}}async function r8({sessionPromise:$}){let Y=$;try{let J=await Y;if(n8(J))return J;if(h===Y)h=l0();return h??=l0(),Y=h,await Y}catch(J){if(h===Y)h=void 0;if(J instanceof Z0)throw J;throw new Z0("wallet_ledger_connection_error",J)}}async function a8(){let $=typeof navigator>"u"?void 0:navigator.hid;if(typeof $?.getDevices!=="function")return!1;try{let[Y,{LEDGER_VENDOR_ID:J}]=await Promise.all([$.getDevices(),import("../chunk-a47dwwv6.js")]);return Y.some(({vendorId:j})=>j===J)}catch(Y){return!1}}async function t8({dmk:$}){if(!await a8())return;try{return await J$($.listenToAvailableDevices({}).pipe(d8(([Y])=>Y),c8((Y)=>Y!==void 0),p8({first:o8})))}catch(Y){return}}async function Q$({dmk:$}){let Y=!1;try{let J=await t8({dmk:$});if(J)return{dmk:$,sessionId:await $.connect({device:J})};let j=$.startDiscovering({});Y=!0;let Q=await J$(j),Z=await $.connect({device:Q});return{dmk:$,sessionId:Z}}catch(J){if(J instanceof Z0)throw J;throw new Z0("wallet_ledger_connection_error",J)}finally{if(Y)try{await $.stopDiscovering()}catch(J){}}}function r({dmk:$}={}){if($)return Q$({dmk:$});return h??=l0(),r8({sessionPromise:h})}function Y0({build:$,dmkSession:Y}){let J;return async function(){let Q=Y??await r();if(J?.session.dmk!==Q.dmk||J.session.sessionId!==Q.sessionId){let Z=Promise.resolve().then(()=>$(Q));J={session:Q,signer:Z};let G=J;Z.catch(()=>{if(J===G)J=void 0})}return J.signer}}function Z$(){let $=j$();return $.catch(()=>{return}),$}async function X$({dmkSession:$}={}){let Y=h,J=$;if(!J){if(!Y)return;if(h===Y)h=void 0;try{J=await Y}catch{return}}if(Y)try{let j=await Y;if(h===Y&&j.dmk===J.dmk&&j.sessionId===J.sessionId)h=void 0}catch(j){if(h===Y)h=void 0}try{await J.dmk.disconnect({sessionId:J.sessionId})}catch(j){if(i8(j))return;throw p(j)}}import{Chain as D,SwapKitError as e8,WalletOption as $9}from"@swapkit/helpers";var o=async({chain:$,ledgerClient:Y})=>{if(!Y)return"";switch($){case D.Cosmos:case D.THORChain:return Y.connect();case D.Ethereum:case D.BinanceSmartChain:case D.Avalanche:case D.Polygon:case D.Arbitrum:case D.Arc:case D.Berachain:case D.Optimism:case D.Base:case D.Aurora:case D.Gnosis:case D.Monad:case D.Robinhood:case D.XLayer:return Y.getAddress();case D.Bitcoin:case D.BitcoinCash:case D.Dash:case D.Dogecoin:case D.Litecoin:case D.Zcash:{let J=Y;await J.connect();let j=await J.getAddress();return $===D.BitcoinCash?j.replace("bitcoincash:",""):j}case D.Near:return await Y.getAddress();case D.Ripple:return Y.getAddress();case D.Stellar:return Y.getAddress();case D.Cardano:return Y.getAddress();case D.Tron:return Y.getAddress();case D.Sui:return Y.connect();case D.Ton:return Y.getAddress();default:throw new e8("wallet_chain_not_supported",{chain:$,wallet:$9.LEDGER})}};import{Chain as U,EVMChains as IY,NetworkDerivationPath as EY,SwapKitError as t0,WalletOption as TY}from"@swapkit/helpers";import{hex as s}from"@scure/base";import{HARDENED_OFFSET as R$,HDKey as w$}from"@scure/bip32";import{Chain as _0,derivationPathToString as V9,NetworkDerivationPath as q9,SwapKitError as d}from"@swapkit/helpers";import{match as k$}from"ts-pattern";import{hex as Z9}from"@scure/base";import{derivationPathToString as X9,getWalletFormatFor as u0,SwapKitError as q$}from"@swapkit/helpers";import{SwapKitError as Y9}from"@swapkit/helpers";function J9($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function l({paramsOrPath:$,transport:Y}){if(J9($))return $;return{derivationPath:$,transport:Y}}async function x({appName:$,connection:Y,createApp:J,operation:j,requiredUserInteraction:Q=T.None}){let{dmkSession:Z,onDeviceActionState:G,transport:X}=Y;if(Z&&X)throw new Y9("wallet_ledger_invalid_params",{message:"Provide either a Ledger DMK session or a LedgerJS transport, not both"});if(X)try{return await j(J(X))}catch(_){throw p(_)}let F=Z??await r(),[{CallTaskInAppDeviceAction:B,DmkResultFactory:z,UnknownDeviceExchangeError:W},{LedgerJsDmkTransport:V}]=await Promise.all([import("../chunk-a47dwwv6.js"),import("../chunk-7rbvcts9.js")]),M=new B({input:{appName:$,requiredUserInteraction:Q,skipOpenApp:!1,task:async(_)=>{try{let w=await j(J(new V(_)));return z({data:{output:w}})}catch(w){return z({error:new W(w)})}}}});return(await E({action:()=>F.dmk.executeDeviceAction({deviceAction:M,sessionId:F.sessionId}),onDeviceActionState:G})).output}import{SwapKitError as j9}from"@swapkit/helpers";var G$=100,z$={cla:224,ins:74},g0=0,B$=128,Q9=[0,144,0];function F$($,Y){let J=$[Y];if(J===void 0||J===255)return;if(J<253)return{size:1,value:J};let j=J===253?2:4;if(Y+1+j>$.length)return;let Q=new DataView($.buffer,$.byteOffset+Y+1,j);return{size:1+j,value:j===2?Q.getUint16(0,!0):Q.getUint32(0,!0)}}function h0($,Y){let J=(G,X={})=>new j9({errorKey:"wallet_ledger_invalid_params",info:{chain:Y,maxLength:G$,operation:"splitOutputsForLegacyApp",outputsLength:$.length,reason:G,...X}}),j=F$($,0);if(!j?.value)throw J("Transaction outputs do not start with a readable non-zero output count");let Q=[],Z=j.size;for(let G=0;G<j.value;G+=1){let X=G===0?0:Z,F=F$($,Z+8),B=F?Z+8+F.size+F.value:void 0;if(!B||B>$.length)throw J("Transaction output is truncated",{outputIndex:G});let z=B-X;if(z>G$)throw J("Output is longer than the Ledger app can check; shorten the memo",{outputIndex:G,pieceLength:z});Q.push($.subarray(X,B)),Z=B}if(Z!==$.length)throw J("Transaction outputs are followed by trailing bytes",{trailingBytes:$.length-Z});return Q}function V$($,Y){let J=[],j=async(Q,Z,G,X,F=Buffer.alloc(0),...B)=>{if(!(Q===z$.cla&&Z===z$.ins&&(G===g0||G===B$)))return $.send(Q,Z,G,X,F,...B);if(J.push(F),G===g0)return Buffer.from(Q9);let W=Buffer.concat(J);J=[];let V=h0(W,Y),M=Buffer.alloc(0);for(let[N,_]of V.entries()){let w=N===V.length-1?B$:g0;M=await $.send(Q,Z,w,X,Buffer.from(_),...B)}return M};return new Proxy($,{get:(Q,Z,G)=>Z==="send"?j:Reflect.get(Q,Z,G)})}var W$=["bitcoin-cash","dash","dogecoin","zcash"],G9=["bitcoin-cash","dash","dogecoin","litecoin"],z9={bitcoin:"Bitcoin","bitcoin-cash":"Bitcoin Cash",dash:"Dash",dogecoin:"Dogecoin",litecoin:"Litecoin",zcash:"Zcash"},B9=({outputScriptHex:$,inputUtxos:Y,btcApp:J,derivationPath:j,chain:Q},Z)=>{let G=Y.map((z)=>{return[J.splitTransaction(z.txHex||"",!W$.includes(Q),Q==="zcash"),z.index,void 0,void 0]}),X=u0(j),F=X!=="legacy",B={additionals:X==="bech32"?["bech32"]:[],associatedKeysets:G.map(()=>j),inputs:G,outputScriptHex:$,segwit:F,useTrustedInputForSegwit:F};return J.createPaymentTransaction({...B,...Z})},F9=({outputScriptHex:$,inputUtxos:Y,btcApp:J,derivationPaths:j,chain:Q},Z)=>{if(j.length!==Y.length)throw new q$("wallet_ledger_invalid_params",{message:`Derivation paths count (${j.length}) must match inputs count (${Y.length})`});let G=Y.map((z)=>{return[J.splitTransaction(z.txHex||"",!W$.includes(Q),Q==="zcash"),z.index,void 0,void 0]}),X=u0(j[0]??""),F=X!=="legacy",B={additionals:X==="bech32"?["bech32"]:[],associatedKeysets:j,inputs:G,outputScriptHex:$,segwit:F,useTrustedInputForSegwit:F};return J.createPaymentTransaction({...B,...Z})},V0=({chain:$,additionalSignParams:Y})=>{let J=G9.includes($);return(j,Q)=>{let{derivationPath:Z,...G}=l({paramsOrPath:j,transport:Q}),X=typeof Z==="string"?Z:X9(Z),F=u0(X);async function B({operation:W,requiredUserInteraction:V}){let M=(await import("@ledgerhq/hw-app-btc")).default;return x({appName:z9[$],connection:G,createApp:(N)=>new M({currency:$,transport:J?V$(N,$):N}),operation:W,requiredUserInteraction:V})}async function z(W){let[{splitTransaction:V},{serializeTransactionOutputs:M}]=await Promise.all([import("@ledgerhq/hw-app-btc/splitTransaction"),import("@ledgerhq/hw-app-btc/serializeTransaction")]),N=M(V(Z9.encode(W.unsignedTx),!0));if(J)h0(N,$);return N.toString("hex")}return{connect:async()=>{await B({operation:async()=>!0})},disconnect:async()=>{},getAddress:async()=>{let{toCashAddress:W}=await import("@swapkit/toolboxes/utxo"),{bitcoinAddress:V}=await B({operation:(M)=>M.getWalletPublicKey(X,{format:F})});if(!V)throw new q$("wallet_ledger_get_address_error",{message:`Cannot get ${$} address from ledger derivation path: ${X}`});return $==="bitcoin-cash"&&F==="legacy"?W(V).replace(/(bchtest:|bitcoincash:)/,""):V},getExtendedPublicKey:async(W="84'/0'/0'",V=76067358)=>{return await B({operation:(M)=>M.getWalletXpub({path:W,xpubVersion:V})})},signTransaction:async(W,V)=>{let M=await z(W);return await B({operation:(N)=>B9({btcApp:N,chain:$,derivationPath:X,inputUtxos:V,outputScriptHex:M},Y),requiredUserInteraction:T.SignTransaction})},signTransactionWithMultiplePaths:async(W,V,M)=>{let N=await z(W);return await B({operation:(_)=>F9({btcApp:_,chain:$,derivationPaths:M,inputUtxos:V,outputScriptHex:N},Y),requiredUserInteraction:T.SignTransaction})}}}},H$=V0({chain:"bitcoin"}),M$=V0({chain:"litecoin"}),N$=V0({additionalSignParams:{additionals:["abc","cashaddr"],segwit:!1,sigHashType:65,useTrustedInputForSegwit:!0},chain:"bitcoin-cash"}),L$=V0({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dogecoin"}),_$=V0({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dash"}),K$=V0({additionalSignParams:{additionals:["zcash","sapling"],expiryHeight:(()=>{let $=Buffer.alloc(4);return $.writeUInt32LE(0),$})(),lockTime:0,segwit:!1,useTrustedInputForSegwit:!1},chain:"zcash"});function b$($){return(typeof $==="string"?$:V9($)).replace(/^m\//,"").replace(/^\/+/,"")}function U$({path:$,reason:Y}){return new d("wallet_ledger_invalid_params",{path:$,reason:Y})}function A$($){let Y=b$($),J=/^(44|49|84|86)'\/0'\/(\d+)'(?:\/(0|1)\/(\d+))?$/.exec(Y);if(!J)throw U$({path:Y,reason:"Expected a Bitcoin path with purpose 44, 49, 84, or 86 and coin type 0"});let j=Number(J[1]),Q=Number(J[2]),Z=Number(J[3]??0),G=Number(J[4]??0);if(Q>=R$||G>=R$)throw U$({path:Y,reason:"Account and address index must be below 2^31"});let X=`${j}'/0'/${Q}'`;return{accountPath:X,addressIndex:G,change:Z,fullPath:`${X}/${Z}/${G}`,purpose:j}}function W9($){if($.length!==4)throw new d("wallet_ledger_invalid_response",{reason:`Expected a 4-byte master fingerprint, received ${$.length}`});return new DataView($.buffer,$.byteOffset,$.byteLength).getUint32(0,!1)}function d0({count:$,tx:Y}){if($!==Y.inputsLength)throw new d("wallet_ledger_invalid_params",{reason:`Input metadata count (${$}) must match transaction inputs count (${Y.inputsLength})`})}function H9({accountPath:$,derivationPaths:Y,tx:J}){d0({count:Y.length,tx:J});let j=Y.map(A$),Q=j.find((Z)=>Z.accountPath!==$);if(Q)throw new d("wallet_ledger_invalid_params",{accountPath:$,path:Q.fullPath,reason:"All input derivation paths must belong to the configured Bitcoin account"});return j}function M9($){return import("../chunk-7kwtpk70.js").then(({DefaultDescriptorTemplate:Y})=>k$($).with(44,()=>Y.LEGACY).with(49,()=>Y.NESTED_SEGWIT).with(84,()=>Y.NATIVE_SEGWIT).with(86,()=>Y.TAPROOT).exhaustive())}function N9($){return"signature"in $&&"pubkey"in $}function J0({inputIndex:$,reason:Y}){return new d("wallet_ledger_invalid_response",{inputIndex:$,reason:Y})}async function L9({input:$,inputIndex:Y,previousTransaction:J}){if(!(J&&$.txid&&$.index!==void 0))throw J0({inputIndex:Y,reason:"PSBT input is missing its previous output"});let{RawTx:j,utils:Q}=await import("@swapkit/utxo-signer"),Z=j.encode({...J,segwitFlag:!1,witnesses:void 0}),G=Q.sha256x2(Z).reverse();if(s.encode(G)!==s.encode($.txid))throw new d("wallet_ledger_invalid_params",{inputIndex:Y,reason:"Previous transaction does not match the input txid"});let X=J.outputs[$.index];if(!X)throw J0({inputIndex:Y,reason:"Previous transaction has no spent output"});let{witnessUtxo:F}=$;if(F&&(F.amount!==X.amount||s.encode(F.script)!==s.encode(X.script)))throw new d("wallet_ledger_invalid_params",{inputIndex:Y,reason:"Input witnessUtxo does not match the previous transaction output"});return X}async function _9({inputIndex:$,path:Y,publicKey:J,spentOutput:j}){let{p2pkh:Q,p2sh:Z,p2tr:G,p2wpkh:X}=await import("@swapkit/utxo-signer"),F=k$(Y.purpose).with(44,()=>Q(J).script).with(49,()=>Z(X(J)).script).with(84,()=>X(J).script).with(86,()=>G(J.slice(1)).script).exhaustive();if(s.encode(F)===s.encode(j.script))return;throw new d("wallet_ledger_invalid_params",{inputIndex:$,path:Y.fullPath,reason:"Input does not spend the script derived from its derivation path"})}function D$({derivationPath:$=q9.BTC,dmkSession:Y,onDeviceActionState:J,transport:j}={}){let Q=A$($),Z=j?H$($,j):void 0,G=Y0({build:async(L)=>{let{SignerBtcBuilder:K}=await import("../chunk-7kwtpk70.js");return new K(L).build()},dmkSession:Y}),X,F;function B(){if(Z)throw new d("wallet_ledger_invalid_params",{reason:"A Device Signer Kit operation is unavailable when a legacy transport is supplied"});return G()}function z(){if(!X){X=B().then(async(K)=>{let{extendedPublicKey:b}=await E({action:()=>K.getExtendedPublicKey(Q.accountPath),onDeviceActionState:J});return b});let L=X;L.catch(()=>{if(X===L)X=void 0})}return X}function W(){if(!F){F=B().then(async(K)=>{let{masterFingerprint:b}=await E({action:()=>K.getMasterFingerprint(),onDeviceActionState:J});return W9(b)});let L=F;L.catch(()=>{if(F===L)F=void 0})}return F}async function V(){let L=Z?await Z.getExtendedPublicKey(Q.accountPath):await z(),{publicKey:K}=w$.fromExtendedKey(L).derive(`m/${Q.change}/${Q.addressIndex}`);if(!K)throw new d("wallet_ledger_invalid_response",{path:Q.fullPath,reason:"Could not derive a public key from the Ledger account xpub"});return K}async function M(){let[{DefaultWallet:L},K]=await Promise.all([import("../chunk-7kwtpk70.js"),M9(Q.purpose)]);return new L(Q.accountPath,K)}async function N({inputUtxos:L,tx:K}){let{RawTx:b}=await import("@swapkit/utxo-signer"),R=Array.from({length:K.inputsLength},(O,k)=>k).some((O)=>!(K.getInput(O).nonWitnessUtxo||L?.[O]?.txHex))?await import("@swapkit/toolboxes/utxo").then(({getUtxoApi:O})=>{let k=O(_0.Bitcoin);return D0((f)=>k.getRawTx(f))}):void 0;return Promise.all(Array.from({length:K.inputsLength},async(O,k)=>{let f=K.getInput(k);if(f.nonWitnessUtxo)return f.nonWitnessUtxo;if(!f.txid)throw J0({inputIndex:k,reason:"PSBT input is missing its previous txid"});let A=L?.[k]?.txHex??await R?.(s.encode(f.txid));if(!A)throw new d("wallet_ledger_invalid_params",{inputIndex:k,reason:"Unable to resolve the previous transaction for Ledger signing"});return b.decode(s.decode(A))}))}async function _({inputUtxos:L,paths:K,tx:b}){let[C,R,O]=await Promise.all([z(),W(),N({inputUtxos:L,tx:b})]),{bip32Path:k}=await import("@swapkit/utxo-signer"),f=w$.fromExtendedKey(C),A=b.clone(),P=[];for(let[v,S]of K.entries()){let c=f.derive(`m/${S.change}/${S.addressIndex}`).publicKey;if(!c)throw new d("wallet_ledger_invalid_response",{inputIndex:v,reason:"Could not derive a public key from the Ledger account xpub"});P[v]=c;let Q0=A.getInput(v),e=O[v],n=await L9({input:Q0,inputIndex:v,previousTransaction:e});await _9({inputIndex:v,path:S,publicKey:c,spentOutput:n});let L0={fingerprint:R,path:k(`m/${S.fullPath}`)};if(S.purpose===86){let O0=c.slice(1);A.updateInput(v,{tapBip32Derivation:[[O0,{der:L0,hashes:[]}]],tapInternalKey:O0,witnessUtxo:n})}else A.updateInput(v,{bip32Derivation:[[c,L0]],nonWitnessUtxo:e,witnessUtxo:S.purpose===44?void 0:n});await O$({chain:_0.Bitcoin,indexes:[v],publicKey:c,tx:A})}return{psbt:A,publicKeys:P}}async function w({inputUtxos:L,paths:K,tx:b}){let[C,R,{psbt:O,publicKeys:k}]=await Promise.all([B(),M(),_({inputUtxos:L,paths:K,tx:b})]),f=O.toPSBT(0),A=await E({action:()=>C.signPsbt(R,f),onDeviceActionState:J}),P=new Set;for(let v of A){if(!N9(v))throw J0({reason:"Unexpected MuSig2 signature"});let{inputIndex:S,pubkey:c}=v,Q0=K[S],e=k[S];if(!(Q0&&e)||P.has(S))throw J0({inputIndex:S,reason:"Unexpected or duplicate input signature"});if(P.add(S),Q0.purpose===86){if(v.tapleafHash)throw J0({inputIndex:S,reason:"Unexpected taproot script signature"});O.updateInput(S,{tapKeySig:v.signature});continue}if(s.encode(c)!==s.encode(e))throw J0({inputIndex:S,reason:"Signature public key does not match the input derivation"});O.updateInput(S,{partialSig:[[e,v.signature]]})}if(P.size!==O.inputsLength)throw J0({reason:`Ledger signed ${P.size} of ${O.inputsLength} inputs`});return O}function y(L){return L.finalize(),L.hex}function I({tx:L,inputUtxos:K}){if(K)d0({count:K.length,tx:L});if(Z)return K?Z.signTransaction(L,K):c0({chain:_0.Bitcoin,legacyClient:Z,tx:L});let b=Array.from({length:L.inputsLength},()=>Q);return w({inputUtxos:K,paths:b,tx:L}).then(y)}return{connect:async()=>{if(Z)return Z.connect();await B()},disconnect:async()=>Z?.disconnect(),getAddress:async()=>{if(Z)return Z.getAddress();let L=await B(),K=await M(),{address:b}=await E({action:()=>L.getWalletAddress(K,Q.addressIndex,{change:Q.change===1}),onDeviceActionState:J});if(!b)throw new d("wallet_ledger_get_address_error",{path:Q.fullPath});return b},getExtendedPublicKey:async({checkOnDevice:L=!1,path:K=Q.accountPath}={})=>{if(Z)return Z.getExtendedPublicKey(K);let b=await B(),C=b$(K),{extendedPublicKey:R}=await E({action:()=>b.getExtendedPublicKey(C,{checkOnDevice:L}),onDeviceActionState:J});return R},getPublicKey:V,showAddressAndPubKey:async()=>{if(Z)return{address:await Z.getAddress()};let L=await B(),K=await M();return E({action:()=>L.getWalletAddress(K,Q.addressIndex,{change:Q.change===1,checkOnDevice:!0}),onDeviceActionState:J})},signTransaction:async(L)=>{if(Z){let b=await c0({chain:_0.Bitcoin,legacyClient:Z,tx:L}),{Transaction:C}=await import("@swapkit/utxo-signer");return C.fromRaw(s.decode(b),{allowUnknownOutputs:!0})}let K=Array.from({length:L.inputsLength},()=>Q);return await w({paths:K,tx:L})},signTransactionHex:I,signTransactionWithMultiplePaths:async({derivationPaths:L,inputUtxos:K,tx:b})=>{if(K)d0({count:K.length,tx:b});let C=H9({accountPath:Q.accountPath,derivationPaths:L,tx:b});if(Z){let R=K??await f$(b,_0.Bitcoin);return Z.signTransactionWithMultiplePaths(b,R,C.map((O)=>`m/${O.fullPath}`))}return w({inputUtxos:K,paths:C,tx:b}).then(y)}}}import{hex as X0}from"@scure/base";import{Chain as G0,NetworkDerivationPath as K9,SwapKitError as q0}from"@swapkit/helpers";function R9($){return new q0("wallet_ledger_method_not_supported",{chain:G0.Cardano,reason:$})}async function w9({address:$,amount:Y,format:J,tokenGroups:j},Q,{AddressType:Z,TxOutputDestinationType:G,TxOutputFormat:X}){let{getCardanoAddressFromBytes:F}=await import("@swapkit/toolboxes/cardano"),z=await F($)===Q.address?{params:{params:{spendingPath:Q.paymentPath,stakingPath:Q.stakingPath},type:Z.BASE_PAYMENT_KEY_STAKE_KEY},type:G.DEVICE_OWNED}:{params:{addressHex:X0.encode($)},type:G.THIRD_PARTY},W=j?.map(({policyId:V,tokens:M})=>({policyIdHex:X0.encode(V),tokens:M.map(({amount:N,assetName:_})=>({amount:N,assetNameHex:X0.encode(_)}))}));return{amount:Y,destination:z,format:J==="legacy"?X.ARRAY_LEGACY:X.MAP_BABBAGE,...W===void 0?{}:{tokenBundle:W}}}async function U9($,Y,J){let{decodeCardanoTransaction:j}=await import("@swapkit/toolboxes/cardano"),{Networks:Q,TransactionSigningMode:Z,TxAuxiliaryDataType:G}=J,{body:X}=await j($),{auxiliaryDataHash:F,fee:B,inputs:z,outputs:W,tagCborSets:V,ttl:M,validityIntervalStart:N}=y$(X,"Ledger",R9);return{additionalWitnessPaths:[],options:{tagCborSets:V},signingMode:Z.ORDINARY_TRANSACTION,tx:{fee:B,inputs:z.map(({index:_,txHash:w})=>({outputIndex:_,path:Y.paymentPath,txHashHex:X0.encode(w)})),network:Q.Mainnet,outputs:await Promise.all(W.map((_)=>w9(_,Y,J))),...F?{auxiliaryData:{params:{hashHex:X0.encode(F)},type:G.ARBITRARY_HASH}}:{},...M===void 0?{}:{ttl:M},...N===void 0?{}:{validityIntervalStart:N}}}}async function O9($,{txHashHex:Y,witnesses:J},{paymentPath:j,publicKey:Q}){let{addCardanoVkeyWitnesses:Z,decodeCardanoTransaction:G}=await import("@swapkit/toolboxes/cardano"),{bodyHash:X}=await G($);if(Y.toLowerCase()!==X)throw new q0("wallet_ledger_invalid_signature",{chain:G0.Cardano,error:"Ledger signed a different transaction body"});if(J.length===0)throw new q0("wallet_ledger_signing_error",{chain:G0.Cardano,error:"Ledger returned no witness"});let F=J.map(({path:B,witnessSignatureHex:z})=>{if(B.length!==j.length||B.some((W,V)=>W!==j[V]))throw new q0("wallet_ledger_signing_error",{chain:G0.Cardano,error:"Ledger returned a witness for an unexpected key"});return{publicKey:Q,signature:X0.decode(z)}});return Z($,F)}async function I$($,Y){let{derivationPath:J,...j}=l({paramsOrPath:$,transport:Y}),Q=J||K9[G0.Cardano],[Z,G,X,F,B]=Q;if(Q.length!==5||F!==0||B===void 0)throw new q0("wallet_ledger_derivation_path_error",{chain:G0.Cardano,derivationPath:Q});let z=await import("@cardano-foundation/ledgerjs-hw-app-cardano"),{getCardanoAddressFromBytes:W,getCardanoPublicKeyHash:V}=await import("@swapkit/toolboxes/cardano"),{HARDENED:M,Networks:N}=z,_=[Z+M,G+M,X+M],w=[..._,0,B],y=[..._,2,0];function I({operation:f,requiredUserInteraction:A}){return x({appName:"Cardano ADA",connection:j,createApp:(P)=>new z.Ada(P),operation:f,requiredUserInteraction:A})}function L(f){let A=Buffer.from(f?.publicKeyHex??"","hex");if(A.length!==32)throw new q0("wallet_ledger_failed_to_get_address",{chain:G0.Cardano,derivationPath:Q});return A}let K=await I({operation:(f)=>f.getExtendedPublicKeys({paths:[w,y]})}),b=L(K[0]),C=L(K[1]),R=await V(b),O=await W(Buffer.concat([Buffer.from([N.Mainnet.networkId]),R,await V(C)]));async function k(f){let A=await U9(f,{address:O,paymentPath:w,stakingPath:y},z),P=await I({operation:(v)=>v.signTransaction(A),requiredUserInteraction:T.SignTransaction});return O9(f,P,{paymentPath:w,publicKey:b})}return{getAddress:()=>O,publicKey:b,publicKeyHash:R,signTransaction:k}}import{hex as p0}from"@scure/base";import{derivationPathToString as A9,NetworkDerivationPath as D9,SwapKitError as W0}from"@swapkit/helpers";var E$=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,f9=E$>>1n;function k9($){return $.reduce((Y,J)=>Y<<8n|BigInt(J),0n)}function b9($){let Y=new Uint8Array(32),J=$;for(let j=31;j>=0;j-=1)Y[j]=Number(J&0xffn),J>>=8n;return Y}function y0($){let Y=k9($.subarray(32,64));if(Y<=f9)return $;let J=new Uint8Array(64);return J.set($.subarray(0,32),0),J.set(b9(E$-Y),32),J}function y9($){let Y=(typeof $==="string"?$:A9($)).replace(/^m\//,"").replace(/^\/+/,"");if(!/^44'\/118'\/\d+'\/(0|1)\/\d+$/.test(Y))throw new W0("wallet_ledger_invalid_params",{path:Y,reason:"Expected a five-level Cosmos derivation path with coin type 118"});return Y}async function T$($){let{Secp256k1Signature:Y}=await import("@cosmjs/crypto");try{return y0($.length===64?Y.fromFixedLength($).toFixedLength():Y.fromDer($).toFixedLength())}catch(J){throw new W0("wallet_ledger_invalid_response",J)}}class o0{chain="cosmos";derivationPath;onDeviceActionState;transport;legacyAppPromise;pubKey=null;getSessionSigner;constructor({derivationPath:$=D9.GAIA,dmkSession:Y,onDeviceActionState:J,transport:j}={}){this.derivationPath=y9($),this.getSessionSigner=Y0({build:async(Q)=>{let{SignerCosmosBuilder:Z}=await import("../chunk-x28a37pz.js");return new Z(Q).build()},dmkSession:Y}),this.onDeviceActionState=J,this.transport=j}getSigner(){if(this.transport)throw new W0("wallet_ledger_invalid_params",{reason:"A Device Signer Kit operation is unavailable when a legacy transport is supplied"});return this.getSessionSigner()}getLegacyApp(){if(!this.transport)throw new W0("wallet_ledger_invalid_params",{reason:"Legacy Cosmos transport is unavailable"});return this.legacyAppPromise??=import("@ledgerhq/hw-app-cosmos").then(({default:$})=>new $(this.transport)),this.legacyAppPromise}async runLegacyOperation($){let Y=await this.getLegacyApp();try{return await $(Y)}catch(J){throw p(J,{userRefusedStatusWords:$0})}}async signBytes($){if(this.transport){let j=await this.runLegacyOperation((Q)=>Q.sign(this.derivationPath,new TextDecoder().decode($)));if(j.return_code!==36864||!j.signature)throw new W0("wallet_ledger_invalid_response",{returnCode:j.return_code});return T$(j.signature)}let Y=await this.getSigner(),J=await E({action:()=>Y.signTransaction(this.derivationPath,this.chain,$),onDeviceActionState:this.onDeviceActionState,userRefusedStatusWords:$0});return T$(J)}async connect(){if(this.transport)await this.getLegacyApp();else await this.getSigner();let{address:$,publicKey:Y}=await this.getAddressAndPubKey();return this.pubKey=Buffer.from(Y,"hex").toString("base64"),$}async disconnect(){}async getAddressAndPubKey(){if(this.transport)return this.runLegacyOperation((j)=>j.getAddress(this.derivationPath,this.chain));let $=await this.getSigner(),{address:Y,publicKey:J}=await E({action:()=>$.getAddress(this.derivationPath,this.chain),onDeviceActionState:this.onDeviceActionState,userRefusedStatusWords:$0});return{address:Y,publicKey:p0.encode(J)}}async showAddressAndPubKey(){if(this.transport)return this.runLegacyOperation((j)=>j.getAddress(this.derivationPath,this.chain,!0));let $=await this.getSigner(),{address:Y,publicKey:J}=await E({action:()=>$.getAddress(this.derivationPath,this.chain,{checkOnDevice:!0}),onDeviceActionState:this.onDeviceActionState,userRefusedStatusWords:$0});return{address:Y,publicKey:p0.encode(J)}}async signTransaction($,Y="0"){let J=await this.signBytes(typeof $==="string"?new TextEncoder().encode($):$);if(!this.pubKey){let{publicKey:j}=await this.getAddressAndPubKey();this.pubKey=Buffer.from(j,"hex").toString("base64")}return[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:Y,signature:J}]}async signAmino($,Y){let j=(await this.getAccounts()).find(({address:X})=>X===$);if(!j)throw new W0("wallet_ledger_address_not_found",{address:$});let{encodeSecp256k1Signature:Q,serializeSignDoc:Z}=await import("@cosmjs/amino"),G=await this.signBytes(Z(Y));return{signature:Q(j.pubkey,G),signed:Y}}async getAccounts(){let{address:$,publicKey:Y}=await this.getAddressAndPubKey();return[{address:$,algo:"secp256k1",pubkey:p0.decode(Y)}]}}import{ChainId as m,derivationPathToString as I9,NetworkDerivationPath as E9,SwapKitError as z0}from"@swapkit/helpers";import{AbstractSigner as T9}from"ethers";function C9({primaryType:$,types:Y}){let J={};function j(Q){if(Object.hasOwn(J,Q)||!Object.hasOwn(Y,Q))return;let Z=Y[Q];if(!Z)return;J[Q]=Z;for(let G of Z)j(G.type.replace(/\[[0-9]*\]/g,""))}if(j($),!Object.hasOwn(J,$))throw new z0("wallet_ledger_invalid_params",{primaryType:$,reason:"The EIP-712 primary type is not defined"});return J}var v9={report:()=>Promise.resolve(void 0)};class g extends T9{chainId=m.Ethereum;derivationPath="";dmkSession;getLedgerSigner;onDeviceActionState;originToken;constructor({provider:$,dmkSession:Y,derivationPath:J=E9.OP,chainId:j=m.Optimism,onDeviceActionState:Q,originToken:Z}){super($);this.chainId=j||m.Ethereum,this.derivationPath=(typeof J==="string"?J:I9(J)).replace(/^m\//,""),this.dmkSession=Y,this.onDeviceActionState=Q,this.originToken=Z,this.getLedgerSigner=Y0({build:async(G)=>{let[{ContextModuleBuilder:X,ContextModuleChainID:F},{SignerEthBuilder:B}]=await Promise.all([import("../chunk-sp3dq5hr.js"),import("../chunk-s5a5v0m1.js")]),z=new X({loggerFactory:(W)=>G.dmk.getLoggerFactory()(["ContextModule",W]),originToken:Z}).setChain(F.Ethereum).setBlindSigningReporter(v9).build();return z.signReport=()=>Promise.resolve(),new B({...G,originToken:Z}).withContextModule(z).build()},dmkSession:Y}),Object.defineProperty(this,"provider",{enumerable:!0,value:$||null,writable:!1})}connect=($)=>new g({chainId:this.chainId,derivationPath:this.derivationPath,dmkSession:this.dmkSession,onDeviceActionState:this.onDeviceActionState,originToken:this.originToken,provider:$});getAddress=async()=>{let{address:$}=await this.getAddressAndPubKey();if(!$)throw new z0("wallet_ledger_failed_to_get_address");return $};getAddressAndPubKey=async()=>{let $=await this.getLedgerSigner();return E({action:()=>$.getAddress(this.derivationPath,{chainId:Number(this.chainId)}),onDeviceActionState:this.onDeviceActionState})};showAddressAndPubKey=async()=>{let $=await this.getLedgerSigner();return E({action:()=>$.getAddress(this.derivationPath,{chainId:Number(this.chainId),checkOnDevice:!0}),onDeviceActionState:this.onDeviceActionState})};signMessage=async($)=>{let{Signature:Y,toUtf8Bytes:J}=await import("ethers"),j=typeof $==="string"?J($):$,Q=await this.getLedgerSigner(),Z=await E({action:()=>Q.signMessage(this.derivationPath,j),onDeviceActionState:this.onDeviceActionState});return Y.from(Z).serialized};signTypedData=async($,Y,J,j)=>{let{buildEIP712DomainType:Q}=await import("@swapkit/toolboxes/evm"),{hexlify:Z,Signature:G,TypedDataEncoder:X}=await import("ethers"),{EIP712Domain:F,...B}=Y,z=j??X.from(B).primaryType,W=C9({primaryType:z,types:B}),V=await X.resolveNames($,W,J,async(I)=>{let L=await this.resolveName(I);if(!L)throw new z0("wallet_ledger_invalid_params",{name:I});return L}),M=V.domain.chainId==null?void 0:Number(V.domain.chainId);if(M!==void 0&&!Number.isSafeInteger(M))throw new z0("wallet_ledger_invalid_params",{chainId:V.domain.chainId});let _={domain:{...V.domain.chainId!=null&&{chainId:M},...V.domain.name!=null&&{name:V.domain.name},...V.domain.salt!=null&&{salt:Z(V.domain.salt)},...V.domain.verifyingContract!=null&&{verifyingContract:V.domain.verifyingContract},...V.domain.version!=null&&{version:V.domain.version}},message:V.value,primaryType:z,types:{EIP712Domain:Q(V.domain),...W}},w=await this.getLedgerSigner(),y=await E({action:()=>w.signTypedData(this.derivationPath,_),onDeviceActionState:this.onDeviceActionState});return G.from(y).serialized};signTransaction=async($)=>{let{copyRequest:Y,getAddress:J,getBytes:j,resolveAddress:Q,resolveProperties:Z,Transaction:G}=await import("ethers"),X=Y($);if(X.type===4||X.authorizationList?.length)throw new z0("wallet_ledger_invalid_params",{message:"Ledger Ethereum DSK does not support EIP-7702 transactions"});let F=BigInt(this.chainId);if(X.chainId!=null&&X.chainId!==F)throw new z0("wallet_ledger_invalid_params",{chainId:X.chainId,expectedChainId:F,message:"Transaction chainId does not match the Ledger client chain"});let{from:B,to:z}=await Z({from:X.from?Q(X.from,this):void 0,to:X.to?Q(X.to,this):void 0}),W=B||X.nonce==null?await this.getAddress():void 0;if(B&&W&&J(B)!==J(W))throw new z0("wallet_ledger_invalid_params",{message:"Transaction from address does not match the Ledger account"});if(z)X.to=z;if(delete X.from,delete X.authorizationList,X.chainId=F,X.type==null&&X.gasPrice!=null&&X.accessList==null&&X.maxFeePerGas==null&&X.maxPriorityFeePerGas==null)X.type=0;X.nonce??=await this.provider?.getTransactionCount(W??await this.getAddress());let M=G.from(X),N=j(M.unsignedSerialized),_=await this.getLedgerSigner(),w=await E({action:()=>_.signTransaction(this.derivationPath,N),onDeviceActionState:this.onDeviceActionState});return M.signature=w,M.serialized}}function C$($){return new g({...$,chainId:m.Arbitrum})}function v$($){return new g({...$,chainId:m.Arc})}function P$($){return new g({...$,chainId:m.Aurora})}function S$($){return new g({...$,chainId:m.Avalanche})}function x$($){return new g({...$,chainId:m.Base})}function m$($){return new g({...$,chainId:m.Ethereum})}function l$($){return new g({...$,chainId:m.Gnosis})}function g$($){return new g({...$,chainId:m.Optimism})}function h$($){return new g({...$,chainId:m.Polygon})}function u$($){return new g({...$,chainId:m.Robinhood})}function c$($){return new g({...$,chainId:m.BinanceSmartChain})}function d$($){return new g({...$,chainId:m.Monad})}function p$($){return new g({...$,chainId:m.XLayer})}function o$($){return new g({...$,chainId:m.Berachain})}import{Chain as P9,NetworkDerivationPath as S9,SwapKitError as K0}from"@swapkit/helpers";async function s$($,Y){let{derivationPath:J,...j}=l({paramsOrPath:$,transport:Y}),Q=(J||S9[P9.Near]).join("'/").concat("'");async function Z({operation:B,requiredUserInteraction:z}){let W=(await import("@ledgerhq/hw-app-near")).default;return x({appName:"NEAR",connection:j,createApp:(V)=>new W(V),operation:B,requiredUserInteraction:z})}let{address:G,publicKey:X}=await Z({operation:(B)=>B.getAddress(Q)});return{getAddress(){return Promise.resolve(G)},async getPublicKey(){let{PublicKey:B}=await import("@near-js/crypto"),z=X.startsWith("ed25519:")?X:`ed25519:${X}`;return B.fromString(z)},signDelegateAction(B){return Promise.reject(new K0("wallet_ledger_method_not_supported",{method:"signDelegateAction",wallet:"Ledger"}))},signNep413Message(B,z,W,V,M){return Promise.reject(new K0("wallet_ledger_method_not_supported",{method:"signNep413Message",wallet:"Ledger"}))},async signTransaction(B){let{Signature:z,SignedTransaction:W}=await import("@near-js/transactions");try{let V=await Z({operation:(_)=>_.signTransaction(B.encode(),Q),requiredUserInteraction:T.SignTransaction});if(!V)throw new K0("wallet_ledger_signing_error",{reason:"Ledger returned no NEAR signature"});let M=new z({data:V,keyType:0}),N=new W({signature:M,transaction:B});return[V,N]}catch(V){if(V instanceof K0)throw V;throw new K0("wallet_ledger_signing_error",{error:V})}}}}import{Chain as s0,derivationPathToString as x9,NetworkDerivationPath as m9,SwapKitError as i$}from"@swapkit/helpers";function l9($){let[Y,J,j,Q,Z]=$;if(Y!==44||J!==148||j===void 0||Q||Z)throw new i$("wallet_ledger_derivation_path_error",{chain:s0.Stellar,derivationPath:$,reason:"Stellar only uses m/44'/148'/x'"});return x9([Y,J,j]).replace(/^m\//,"")}async function n$($,Y){let{derivationPath:J,...j}=l({paramsOrPath:$,transport:Y}),Q=l9(J||m9[s0.Stellar]);async function Z({operation:z,requiredUserInteraction:W}){let V=(await import("@ledgerhq/hw-app-str")).default;return x({appName:"Stellar",connection:j,createApp:(M)=>new V(M),operation:z,requiredUserInteraction:W})}let[{rawPublicKey:G},{StrKey:X}]=await Promise.all([Z({operation:(z)=>z.getPublicKey(Q)}),import("@stellar/stellar-sdk")]),F=X.encodeEd25519PublicKey(G);async function B(z){let{signature:W}=await Z({operation:(V)=>V.signTransaction(Q,z.signatureBase()),requiredUserInteraction:T.SignTransaction});try{z.addSignature(F,W.toString("base64"))}catch(V){throw new i$("wallet_ledger_invalid_signature",{chain:s0.Stellar,error:V})}return z}return{getAddress:()=>F,publicKey:G,signTransaction:B}}import{Chain as g9,derivationPathToString as h9,NetworkDerivationPath as u9,SwapKitError as B0}from"@swapkit/helpers";class r${derivationPath;address=null;publicKey=null;connection;constructor($,Y){let{derivationPath:J,...j}=l({paramsOrPath:$,transport:Y});this.derivationPath=typeof J==="string"?J:h9(J||u9[g9.Sui]),this.connection=j}getLedgerPath(){return this.derivationPath.replace(/^m\//,"").replace(/\/(\d+)\/(\d+)$/,"/$1'/$2'")}async runSuiOperation({operation:$,requiredUserInteraction:Y}){let J=(await import("@ledgerhq/hw-app-sui")).default;return x({appName:"Sui",connection:this.connection,createApp:(j)=>new J(j),operation:$,requiredUserInteraction:Y})}async connect(){let $=this.getLedgerPath(),Y=await this.runSuiOperation({operation:(J)=>J.getPublicKey($)});if(!Y?.publicKey)throw new B0("wallet_ledger_failed_to_get_address");return this.publicKey=Y.publicKey,this.address=`0x${Buffer.from(Y.address).toString("hex")}`,this.address}toSuiAddress(){if(!this.address)throw new B0("wallet_ledger_failed_to_get_address");return this.address}async getAddress(){if(this.address)return this.address;return await this.connect()}async signTransaction($){let Y=$ instanceof Uint8Array?$:$.transaction;if(!this.publicKey)throw new B0("wallet_ledger_failed_to_get_address");try{let J=this.getLedgerPath(),j=new Uint8Array(3+Y.length);j.set(Y,3);let Q=await this.runSuiOperation({operation:(X)=>X.signTransaction(J,j),requiredUserInteraction:T.SignTransaction});if(!Q?.signature)throw new B0("wallet_ledger_signing_error");let Z=this.publicKey.length===33?this.publicKey.slice(1):this.publicKey;if(Z.length!==32)throw new B0("wallet_ledger_signing_error",{error:"Invalid public key length"});let G=new Uint8Array(97);return G.set(Q.signature,1),G.set(Z,65),{bytes:Buffer.from(Y).toString("base64"),signature:Buffer.from(G).toString("base64")}}catch(J){if(J instanceof B0)throw J;throw new B0("wallet_ledger_signing_error",{error:J})}}}function a$($,Y){return new r$($,Y)}import{base64 as I0,hex as i9}from"@scure/base";import{NetworkDerivationPath as n9,SwapKitError as E0}from"@swapkit/helpers";import{SwapKitError as j0}from"@swapkit/helpers";var $8=85,c9=4,d9=0,i0=2,p9=0,o9=1,t$=2,n0=36864,e$=250;class R0{name="THORChainCommand";params;constructor($){this.params=$}getApdu(){let{data:$=new Uint8Array,ins:Y,p1:J=0,p2:j=0}=this.params;return{cla:$8,data:$,ins:Y,p1:J,p2:j}}parseResponse($){let Y=($.statusCode[0]??0)*256+($.statusCode[1]??0);if(Y!==n0)throw Error(`THORChain app returned status 0x${Y.toString(16).padStart(4,"0")}`);return $.data}}function Y8({path:$}){if($.length!==5)throw new j0("wallet_ledger_invalid_params",{reason:"THORChain path must contain five elements"});let Y=new Uint8Array(20),J=new DataView(Y.buffer);return $.forEach((j,Q)=>{if(typeof j!=="number"||!Number.isInteger(j)||j<0||j>4294967295)throw new j0("wallet_ledger_invalid_params",{reason:`Invalid THORChain path segment ${Q}`});if(Q>=3&&j>=2147483648)throw new j0("wallet_ledger_invalid_params",{reason:`THORChain path segment ${Q} must not be hardened`});let Z=j&2147483647,G=Q<3?(Z|2147483648)>>>0:Z;J.setUint32(Q*4,G,!0)}),Y}function s9({hrp:$,path:Y}){let J=new TextEncoder().encode($);if(J.length<1||J.length>83)throw new j0("wallet_ledger_invalid_params",{reason:"Invalid THORChain address prefix"});let j=Y8({path:Y});return Uint8Array.from([J.length,...J,...j])}function J8({checkOnDevice:$,hrp:Y,path:J}){return new R0({data:s9({hrp:Y,path:J}),ins:c9,p1:$?1:0})}function j8({message:$,path:Y}){let J=[new R0({data:Y8({path:Y}),ins:i0,p1:p9})];if($.length===0)return J.push(new R0({data:new Uint8Array,ins:i0,p1:t$})),J;for(let j=0;j<$.length;j+=e$){let Q=Math.min(j+e$,$.length);J.push(new R0({data:$.slice(j,Q),ins:i0,p1:Q===$.length?t$:o9}))}return J}function Q8({response:$}){if($.length<2)throw new j0("wallet_ledger_invalid_response",{reason:"THORChain response is missing status bytes"});return $.slice(0,-2)}async function Z8({transport:$}){let Y=await $.send($8,d9,0,0,Buffer.alloc(0),[n0]),J=Q8({response:Y});if(J.length<4)throw new j0("wallet_ledger_invalid_response",{reason:"Invalid THORChain version response"});return`${J[1]}.${J[2]}.${J[3]}`}async function X8({command:$,transport:Y}){let J=$.getApdu(),j=await Y.send(J.cla,J.ins,J.p1,J.p2,Buffer.from(J.data),[n0]);return Q8({response:j})}function G8({response:$}){if($.length<34)throw new j0("wallet_ledger_invalid_response",{reason:"Invalid THORChain address response"});let Y=$.slice(0,33),J=new TextDecoder().decode($.slice(33));if(!J)throw new j0("wallet_ledger_invalid_response",{reason:"THORChain address is empty"});return{address:J,publicKey:Y}}function r0({version:$}){return`THORChain Ledger app major 2 is required, received ${$||"unknown"}`}var r9="THORChain";function a9($){if(typeof $==="string")return $;let Y=$.chain?.toUpperCase(),J=($.symbol||$.ticker||"").toUpperCase();if(!(Y&&J))return J||Y||"";return`${Y}${$.synth?"/":"."}${J}`}function t9($){return{...$,msgs:$.msgs.map((Y)=>{if(!Y.type.includes("MsgDeposit"))return Y;let J=Y.value.coins;if(!Array.isArray(J))return Y;return{...Y,value:{...Y.value,coins:J.map((j)=>({...j,asset:a9(j.asset)}))}}})}}async function e9({signature:$}){let{Secp256k1Signature:Y}=await import("@cosmjs/crypto");try{return y0(Y.fromDer($).toFixedLength())}catch(J){throw new E0("wallet_ledger_invalid_signature",J)}}async function $Y({commands:$,transport:Y}){let J=await Z8({transport:Y});if(!J.startsWith("2.")){let{InvalidResponseFormatError:Q}=await import("../chunk-a47dwwv6.js");throw new Q(r0({version:J}))}let j=new Uint8Array;for(let Q of $)j=await X8({command:Q,transport:Y});return j}class a0{derivationPath;dmkSession;onDeviceActionState;pubKey;transport;constructor({derivationPath:$=n9.THOR,dmkSession:Y,onDeviceActionState:J,transport:j}={}){if(Y&&j)throw new E0("wallet_ledger_invalid_params",{message:"Provide either a Ledger DMK session or a LedgerJS transport, not both"});this.derivationPath=$,this.dmkSession=Y,this.onDeviceActionState=J,this.transport=j}get pubkey(){return this.pubKey?I0.encode(this.pubKey):null}executeCommands=async({commands:$,requiredUserInteraction:Y})=>{if(this.transport)try{return await $Y({commands:$,transport:this.transport})}catch(N){throw p(N,{userRefusedStatusWords:$0})}let J=this.dmkSession??await r(),{Apdu:j,CallTaskInAppDeviceAction:Q,CommandResultFactory:Z,DmkResultFactory:G,InvalidResponseFormatError:X,InvalidStatusWordError:F,isSuccessCommandResult:B,UnknownDeviceExchangeError:z}=await import("../chunk-a47dwwv6.js"),W=(N)=>{let _=N.getApdu();return{getApdu:()=>new j(_.cla,_.ins,_.p1,_.p2,_.data),name:N.name,parseResponse:(w)=>{try{return Z({data:N.parseResponse(w)})}catch(y){let I=i9.encode(w.statusCode);return Z({error:Object.assign(new F(y instanceof Error?y.message:String(y)),{errorCode:I})})}}}},V=new Q({input:{appName:r9,requiredUserInteraction:Y,skipOpenApp:!1,task:async(N)=>{try{let _=N.getDeviceSessionState(),w="currentApp"in _?_.currentApp.version:void 0;if(!w?.startsWith("2."))return G({error:new X(r0({version:w}))});let y=new Uint8Array;for(let I of $){let L=await N.sendCommand(W(I));if(!B(L))return G({error:L.error});y=L.data}return G({data:{response:y}})}catch(_){return G({error:new z(_)})}}}});return(await E({action:()=>J.dmk.executeDeviceAction({deviceAction:V,sessionId:J.sessionId}),onDeviceActionState:this.onDeviceActionState,userRefusedStatusWords:$0})).response};getAddressData=async({checkOnDevice:$})=>{let Y=await this.executeCommands({commands:[J8({checkOnDevice:$,hrp:"thor",path:this.derivationPath})],requiredUserInteraction:$?T.VerifyAddress:T.None});return G8({response:Y})};signBytes=async({message:$})=>{let Y=await this.executeCommands({commands:j8({message:$,path:this.derivationPath}),requiredUserInteraction:T.SignTransaction});return e9({signature:Y})};connect=async()=>{let{address:$,publicKey:Y}=await this.getAddressData({checkOnDevice:!1});return this.pubKey=Y,$};getAddressAndPubKey=async()=>{let{address:$,publicKey:Y}=await this.getAddressData({checkOnDevice:!1});return this.pubKey=Y,{bech32_address:$,compressed_pk:Y,error_message:"No errors",return_code:36864}};showAddressAndPubKey=async()=>{let{address:$,publicKey:Y}=await this.getAddressData({checkOnDevice:!0});return this.pubKey=Y,{bech32_address:$,compressed_pk:Y,error_message:"No errors",return_code:36864}};signTransaction=async({rawTx:$,sequence:Y="0"})=>{if(!this.pubKey)await this.connect();let J=this.pubKey;if(!J)throw new E0("wallet_ledger_pubkey_not_found");let j=await this.signBytes({message:new TextEncoder().encode($)});return[{pub_key:{type:"tendermint/PubKeySecp256k1",value:I0.encode(J)},sequence:Y,signature:I0.encode(j)}]};signAmino=async($,Y)=>{let J=(await this.getAccounts()).find(({address:G})=>G===$);if(!J)throw new E0("wallet_ledger_address_not_found",{address:$});let{encodeSecp256k1Signature:j,serializeSignDoc:Q}=await import("@cosmjs/amino"),Z=await this.signBytes({message:Q(t9(Y))});return{signature:j(J.pubkey,Z),signed:Y}};getAccounts=async()=>{let{address:$,publicKey:Y}=await this.getAddressData({checkOnDevice:!1});return this.pubKey=Y,[{address:$,algo:"secp256k1",pubkey:Y}]};sign=async($)=>I0.encode(await this.signBytes({message:new TextEncoder().encode($)}))}import{Chain as z8,getRPCUrl as YY,NetworkDerivationPath as JY,SwapKitError as H0,WalletOption as V8}from"@swapkit/helpers";var jY=3,QY=300,B8=0;function ZY($){let[Y,J,j,Q,Z,...G]=$;if(!(Y===44&&J===607&&j===0&&Q===0&&typeof Z==="number"&&Number.isInteger(Z)&&Z>=0&&G.length===0))throw new H0({errorKey:"wallet_ledger_derivation_path_error",info:{derivationPath:$,reason:"Ledger TON accounts derive from m/44'/607'/0'/0'/{account}'"}});return[44,607,0,0,Z,0]}function F0($,Y={}){return new H0({errorKey:"wallet_ledger_invalid_params",info:{...Y,reason:$,wallet:V8.LEDGER}})}function XY($){let Y=Array.isArray($)?$:$.messages,[J]=Y;if(!J)throw F0("A TON transaction needs one message");if(Y.length>1)throw new H0({errorKey:"wallet_ledger_method_not_supported",info:{messageCount:Y.length,method:"signTransaction",reason:"Ledger signs one TON message per transaction",wallet:V8.LEDGER}});let j=(Array.isArray($)?J.sendMode:$.sendMode??J.sendMode)??jY;if(!Array.isArray($)&&J.sendMode!==void 0&&J.sendMode!==j)throw F0("The message send mode differs from the transaction send mode",{messageSendMode:J.sendMode,sendMode:j});if(!Number.isInteger(j)||j<0||j>255)throw F0("The TON send mode must be an integer between 0 and 255",{sendMode:j});return{message:J,sendMode:j}}async function GY($){let[{Address:Y,Cell:J,loadStateInit:j},{parseMessage:Q}]=await Promise.all([import("@ton/core"),import("@ton-community/ton-ledger")]);if(!/^\d+$/.test($.amount))throw F0("The TON amount must be an integer number of nanotons",{amount:$.amount});let Z=BigInt($.amount),G;try{G=Y.parse($.address)}catch{throw F0("Invalid TON destination address",{address:$.address})}let X=Y.isFriendly($.address)?Y.parseFriendly($.address).isBounceable:!0,F;if($.stateInit!==void 0)try{F=j(J.fromBase64($.stateInit).beginParse())}catch{throw F0("The TON state init is not a valid BOC",{stateInit:$.stateInit})}let B;if($.payload!==void 0)try{B=J.fromBase64($.payload)}catch{throw F0("The TON payload is not a valid BOC",{payload:$.payload})}let z=B?Q(B,{disallowModification:!0}):void 0;return{amount:Z,bounce:X,payload:B,payloadFormat:z,stateInit:F,to:G}}function F8($,Y){return $&&Y?$.hash().equals(Y.hash()):$==null&&Y==null}function zY($,Y){if(!($&&Y))return $==null&&Y==null;return F8($.code,Y.code)&&F8($.data,Y.data)}async function BY($,Y){let{Cell:J,loadMessageRelaxed:j}=await import("@ton/core"),Q;try{let X=$.beginParse().skip(512),F=X.loadUint(32),B=X.loadUint(32),z=X.loadUint(32);X.skip(8);let W=X.loadUint(8),V=j(X.loadRef().beginParse());X.endParse(),Q={order:V,sendMode:W,seqno:z,timeout:B,walletId:F}}catch(X){throw new H0({errorKey:"wallet_ledger_signing_error",info:{reason:"Unreadable signed TON transfer"}},X)}let{order:Z}=Q;if(!(Q.walletId===Y.walletId&&Q.timeout===Y.timeout&&Q.seqno===Y.seqno&&Q.sendMode===Y.sendMode&&Z.info.type==="internal"&&Z.info.dest.equals(Y.to)&&Z.info.value.coins===Y.amount&&Z.info.bounce===Y.bounce&&Z.body.hash().equals((Y.payload??J.EMPTY).hash())&&zY(Z.init,Y.stateInit)))throw new H0({errorKey:"wallet_ledger_signing_error",info:{reason:"The signed TON transfer does not match the requested message"}})}async function q8($,Y){let{derivationPath:J,...j}=l({paramsOrPath:$,transport:Y}),Q=ZY(J||JY[z8.Ton]);async function Z({operation:_,requiredUserInteraction:w}){let{TonTransport:y}=await import("@ton-community/ton-ledger");return x({appName:"TON",connection:j,createApp:(I)=>new y(I),operation:_,requiredUserInteraction:w})}let[{Address:G},{WalletContractV4:X}]=await Promise.all([import("@ton/core"),import("@ton/ton")]),{address:F,publicKey:B}=await Z({operation:(_)=>_.getAddress(Q,{bounceable:!1,chain:B8,testOnly:!1,walletVersion:"v4"})}),z=X.create({publicKey:B,workchain:B8});if(!z.address.equals(G.parse(F)))throw new H0({errorKey:"wallet_ledger_failed_to_get_address",info:{deviceAddress:F,reason:"The Ledger TON address is not the wallet v4 address of its public key"}});let W=z.address.toString({bounceable:!1,urlSafe:!0}),V;async function M(){if(!V){let{TonClient:I}=await import("@ton/ton");V=new I({endpoint:await YY(z8.Ton)})}let{state:_}=await V.getContractState(z.address),w=_==="active",y=w?await V.open(z).getSeqno():0;return{deployed:w,seqno:y}}async function N(_){let{message:w,sendMode:y}=XY(_),I=await GY(w),{deployed:L,seqno:K}=await M(),b=Math.floor(Date.now()/1000)+QY,C=await Z({operation:(f)=>f.signTransaction(Q,{amount:I.amount,bounce:I.bounce,payload:I.payloadFormat,sendMode:y,seqno:K,stateInit:I.stateInit,timeout:b,to:I.to}),requiredUserInteraction:T.SignTransaction});await BY(C,{...I,sendMode:y,seqno:K,timeout:b,walletId:z.walletId});let{beginCell:R,external:O,storeMessage:k}=await import("@ton/core");return R().store(k(O({body:C,init:L?void 0:z.init,to:z.address}))).endCell()}return{getAddress:()=>W,publicKey:B,signTransaction:N}}import{derivationPathToString as FY,NetworkDerivationPath as VY,SwapKitError as w0}from"@swapkit/helpers";class W8{derivationPath;ledgerTimeout=50000;connection;constructor($,Y){let{derivationPath:J,...j}=l({paramsOrPath:$,transport:Y});this.derivationPath=typeof J==="string"?J:FY(J||VY.TRON),this.connection=j}async runTronOperation({operation:$,requiredUserInteraction:Y}){let J=(await import("@ledgerhq/hw-app-trx")).default;return x({appName:"Tron",connection:this.connection,createApp:(j)=>new J(j),operation:$,requiredUserInteraction:Y})}checkOrCreateTransportAndLedger=async()=>{await this.runTronOperation({operation:async()=>!0})};createTransportAndLedger=async()=>{await this.runTronOperation({operation:async()=>!0})};getAddress=async()=>{let $=await this.getAddressAndPubKey();if(!$)throw new w0("wallet_ledger_failed_to_get_address");return $.address};getAddressAndPubKey=async()=>{let $=await this.runTronOperation({operation:(Y)=>Y.getAddress(this.derivationPath)});if(!$)throw new w0("wallet_ledger_failed_to_get_address");return{address:$.address,publicKey:$.publicKey}};showAddressAndPubKey=async()=>{return await this.runTronOperation({operation:($)=>$.getAddress(this.derivationPath,!0),requiredUserInteraction:T.VerifyAddress})};signTransaction=async($)=>{try{let Y=await this.runTronOperation({operation:(J)=>J.signTransaction(this.derivationPath,$.raw_data_hex,[]),requiredUserInteraction:T.SignTransaction});if(!Y)throw new w0("wallet_ledger_signing_error");return{...$,signature:[Y]}}catch(Y){if(Y instanceof w0)throw Y;throw new w0("wallet_ledger_signing_error",{error:Y})}}}function H8($,Y){return new W8($,Y)}import{Chain as qY,derivationPathToString as WY,NetworkDerivationPath as HY}from"@swapkit/helpers";var MY=2147483648;function NY($){return Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==null&&Y!==void 0))}async function M8($,Y){let{derivationPath:J,...j}=l({paramsOrPath:$,transport:Y}),Q=WY(J||HY[qY.Ripple]);async function Z({operation:B,requiredUserInteraction:z}){let W=(await import("@ledgerhq/hw-app-xrp")).default;return x({appName:"XRP",connection:j,createApp:(V)=>new W(V),operation:B,requiredUserInteraction:z})}let{address:G,publicKey:X}=await Z({operation:(B)=>B.getAddress(Q)});async function F(B){let[{encode:z},{hashes:W}]=await Promise.all([import("ripple-binary-codec"),import("xrpl")]),V={...NY(B),Flags:B.Flags||MY,SigningPubKey:X.toUpperCase()},M=z(V),N=await Z({operation:(y)=>y.signTransaction(Q,M),requiredUserInteraction:T.SignTransaction}),_=z({...V,TxnSignature:N});return{hash:W.hashSignedTx(_),tx_blob:_}}return{getAddress:()=>G,signTransaction:F}}import{hex as i}from"@scure/base";import{derivationPathToString as LY,NetworkDerivationPath as _Y,SwapKitError as a}from"@swapkit/helpers";var KY=3364600;function N8($){return(typeof $==="string"?$:LY($)).replace(/^m\//,"").replace(/^\/+/,"")}function T0($){let Y=N8($),J=/^44'\/133'\/(\d+)'(?:\/(0|1)\/(\d+))?$/.exec(Y);if(!J)throw new a("wallet_ledger_invalid_params",{path:Y,reason:"Expected a Zcash BIP44 path with coin type 133"});let j=Number(J[1]),Q=`44'/133'/${j}'`;return{account:j,accountPath:Q,fullPath:`${Q}/${J[2]??0}/${J[3]??0}`}}function RY($){let Y=new Uint8Array(4);return new DataView(Y.buffer).setUint32(0,$>>>0,!0),Y}function wY($){let Y=new Uint8Array(8);return new DataView(Y.buffer).setBigUint64(0,$,!0),Y}function M0($,Y){return new a({errorKey:"wallet_ledger_invalid_params",info:$},Y)}function UY({bytes:$,offset:Y}){if(Y+4>$.length)throw Error("Unexpected end of previous transaction");return new DataView($.buffer,$.byteOffset+Y,4).getUint32(0,!0)}function OY($){let Y=0;function J(Q){if(Y+Q>$.length)throw Error(`Previous transaction ends before byte ${Y+Q}`);return Y+=Q,$.slice(Y-Q,Y)}function j(){let Q=J(1)[0]??0;if(Q<253)return Q;let Z=new DataView(J(Q===253?2:Q===254?4:8).buffer),G=Z.byteLength===2?Z.getUint16(0,!0):Z.byteLength===4?Z.getUint32(0,!0):Number(Z.getBigUint64(0,!0));if(!Number.isSafeInteger(G))throw Error("Previous transaction compact-size value exceeds safe range");return G}return{compactSize:j,rest:()=>J($.length-Y),take:J,varBytes:()=>J(j())}}function fY({bytes:$,version:Y}){let J=OY($),j=J.take(Y===4?8:20),Q=[];for(let B=J.compactSize();Q.length<B;){let z=J.take(36),W=J.varBytes(),V=J.take(4);Q.push({prevout:z,script:W,sequence:V})}let Z=[];for(let B=J.compactSize();Z.length<B;){let z=J.take(8),W=J.varBytes();Z.push({amount:z,script:W})}let G={inputs:Q,nVersionGroupId:j.slice(4,8),outputs:Z,version:j.slice(0,4)};if(Y>=5)return{...G,consensusBranchId:j.slice(8,12),locktime:j.slice(12,16),nExpiryHeight:j.slice(16,20)};let X=J.take(4),F=J.take(4);return{...G,extraData:J.rest(),locktime:X,nExpiryHeight:F}}function L8({hash:$,txid:Y}){let J=$.toLowerCase();return J===i.encode(Y)||J===i.encode(Y.slice().reverse())}async function kY($){let{CompactSize:Y,utils:J}=await import("@swapkit/utxo-signer"),j=Array.from({length:$.outputsLength},(Q,Z)=>$.getOutput(Z));return J.concatBytes(Y.encode(BigInt(j.length)),...j.flatMap(({amount:Q,script:Z})=>[wY(Q),Y.encode(BigInt(Z.length)),Z]))}async function bY($){let{ZCASH_IRONWOOD_ACTIVATION_HEIGHT:Y,ZcashConsensusBranchId:J}=await import("@swapkit/utxo-signer");switch($){case J.NU6_2:return KY;case J.IRONWOOD:return Y;default:throw new a("wallet_ledger_invalid_params",{consensusBranchId:$,reason:"Ledger Zcash DSK signing supports NU6.2 and Ironwood target branches"})}}async function AY({inputIndex:$,utxo:Y}){let{hash:J,index:j,txHex:Q}=Y,Z={inputIndex:$,outputIndex:j,txid:J};if(!Q)throw M0({...Z,reason:"Zcash Ledger signing requires the full previous transaction txHex for every input"});function G(M){try{return M()}catch(N){throw M0({...Z,reason:N instanceof Error?N.message:String(N)},N)}}let X=G(()=>i.decode(Q.replace(/^0x/i,""))),F=G(()=>UY({bytes:X,offset:0})),B=F&2147483647;if((F&2147483648)===0||B<4||B>6)throw M0({...Z,reason:"Ledger Zcash signing supports only overwintered v4, v5 and v6 previous transactions",version:B});let z=G(()=>fY({bytes:X,version:B}));if(j<0||j>=z.outputs.length)throw M0({...Z,outputCount:z.outputs.length,reason:"Zcash input references an output outside its previous transaction"});if(B>=5)return{...z,serializedPreviousTransactionOverride:X};let{utils:W}=await import("@swapkit/utxo-signer"),V=W.sha256x2(X);if(!L8({hash:J,txid:V}))throw M0({...Z,previousTxid:i.encode(V.reverse()),reason:"Previous transaction does not hash to the input txid"});return z}function DY({accountPath:$,derivationPaths:Y,inputUtxos:J,tx:j}){if(J.length!==j.inputsLength||Y.length!==j.inputsLength)throw new a("wallet_ledger_invalid_params",{derivationPathCount:Y.length,inputCount:j.inputsLength,inputUtxoCount:J.length,reason:"Zcash input UTXOs and derivation paths must match the transaction input count"});return J.forEach((Q,Z)=>{let G=j.getInput(Z);if(!L8({hash:Q.hash,txid:G.txid})||Q.index!==G.index)throw M0({inputIndex:Z,reason:"Zcash input UTXO does not match the transaction input",transactionInput:{index:G.index,txid:i.encode(G.txid)},utxo:{hash:Q.hash,index:Q.index}})}),Y.map((Q)=>{let Z=T0(Q);if(Z.accountPath!==$)throw new a("wallet_ledger_invalid_params",{accountPath:$,path:Z.fullPath,reason:"All Zcash input derivation paths must belong to the configured account"});return Z.fullPath})}function yY($){let Y=$.replace(/^0x/i,""),J=i.decode(Y);if(J.length<4||(new DataView(J.buffer,J.byteOffset,4).getUint32(0,!0)&2147483647)!==5)throw new a("wallet_ledger_invalid_response",{reason:"Ledger Zcash signer did not return a version 5 transaction"});return Y}function _8({derivationPath:$=_Y.ZEC,dmkSession:Y,onDeviceActionState:J,transport:j}={}){let Q=T0($),Z=j?K$($,j):void 0,G=Y0({build:async(W)=>{let{SignerZcashBuilder:V}=await import("../chunk-42xrtarj.js");return new V(W).build()},dmkSession:Y});function X(){if(Z)throw new a("wallet_ledger_invalid_params",{reason:"A Device Signer Kit operation is unavailable when a legacy transport is supplied"});return G()}async function F({checkOnDevice:W=!1,path:V=Q.fullPath}={}){let M=await X();return E({action:()=>M.getAddress(V,{checkOnDevice:W}),onDeviceActionState:J})}async function B({path:W=Q.accountPath,xpubVersion:V=76067358}={}){let M=T0(W);if(M.fullPath!==`${M.accountPath}/0/0`||N8(W).split("/").length!==3)throw new a("wallet_ledger_invalid_params",{path:W,reason:"Zcash extended public keys are exported at account level"});let N={dmkSession:j?void 0:Y??await r(),onDeviceActionState:J,transport:j},{default:_}=await import("@ledgerhq/hw-app-btc");return x({appName:"Zcash",connection:N,createApp:(w)=>new _({currency:"zcash",transport:w}),operation:(w)=>w.getWalletXpub({path:M.accountPath,xpubVersion:V})})}async function z({changePath:W,derivationPaths:V,inputUtxos:M,tx:N}){let _=DY({accountPath:Q.accountPath,derivationPaths:V??Array.from({length:N.inputsLength},()=>Q.fullPath),inputUtxos:M,tx:N});if(Z)throw new a("wallet_ledger_invalid_params",{reason:"Zcash signing requires a Ledger DMK session instead of a legacy transport"});let w=await bY(N.consensusBranchId),y=await Promise.all(M.map(async(b,C)=>[await AY({inputIndex:C,utxo:b}),b.index,null,N.getInput(C).sequence??4294967295])),I={additionals:["zcash","sapling"],associatedKeysets:_,blockHeight:w,changePath:W?T0(W).fullPath:Q.fullPath,expiryHeight:RY(N.expiryHeight),inputs:y,lockTime:N.lockTime,outputScriptHex:i.encode(await kY(N))},L=await X(),K=await E({action:()=>L.signTransaction(I),onDeviceActionState:J});return yY(K)}return{connect:async()=>{if(Z)return Z.connect();await X()},disconnect:async()=>Z?.disconnect(),getAddress:async()=>{if(Z)return Z.getAddress();return(await F()).address},getAddressAndPubKey:async()=>{if(Z)return{address:await Z.getAddress()};let{address:W,chainCode:V,publicKey:M}=await F();return{address:W,chainCode:i.encode(V),publicKey:i.encode(M)}},getExtendedPublicKey:B,showAddressAndPubKey:async()=>{if(Z)return{address:await Z.getAddress()};let{address:W,chainCode:V,publicKey:M}=await F({checkOnDevice:!0});return{address:W,chainCode:i.encode(V),publicKey:i.encode(M)}},signTransaction:z,signTransactionWithMultiplePaths:async(W)=>z(W)}}async function u({chain:$,dmkSession:Y,derivationPath:J,onDeviceActionState:j,originToken:Q,transport:Z}){let G=IY.includes($);if(Y&&Z)throw new t0("wallet_ledger_invalid_params",{message:"Provide either a Ledger DMK session or a LedgerJS transport, not both"});if(G&&Z)throw new t0("wallet_ledger_invalid_params",{message:"Ledger EVM clients require a DMK session instead of a LedgerJS transport"});let X={derivationPath:J??EY[$],dmkSession:Y,onDeviceActionState:j,transport:Z},{match:F}=await import("ts-pattern");return F($).returnType().with(U.THORChain,()=>Promise.resolve(new a0(X))).with(U.Cosmos,()=>Promise.resolve(new o0(X))).with(U.Bitcoin,()=>Promise.resolve(D$(X))).with(U.BitcoinCash,()=>Promise.resolve(N$(X))).with(U.Dash,()=>Promise.resolve(_$(X))).with(U.Dogecoin,()=>Promise.resolve(L$(X))).with(U.Litecoin,()=>Promise.resolve(M$(X))).with(U.Zcash,()=>Promise.resolve(_8(X))).with(U.Ripple,()=>Promise.resolve(M8(X))).with(U.Stellar,()=>Promise.resolve(n$(X))).with(U.Cardano,()=>Promise.resolve(I$(X))).with(U.Tron,()=>Promise.resolve(H8(X))).with(U.Sui,()=>Promise.resolve(a$(X))).with(U.Ton,()=>Promise.resolve(q8(X))).with(U.Near,()=>Promise.resolve(s$(X))).with(U.Arbitrum,U.Arc,U.Aurora,U.Avalanche,U.Berachain,U.BinanceSmartChain,U.Ethereum,U.Gnosis,U.Monad,U.Optimism,U.Polygon,U.Base,U.Robinhood,U.XLayer,async()=>{let{getProvider:B}=await import("@swapkit/toolboxes/evm"),z={derivationPath:J,dmkSession:Y,onDeviceActionState:j,originToken:Q,provider:await B($)};return F($).with(U.BinanceSmartChain,()=>c$(z)).with(U.Avalanche,()=>S$(z)).with(U.Arbitrum,()=>C$(z)).with(U.Arc,()=>v$(z)).with(U.Berachain,()=>o$(z)).with(U.Optimism,()=>g$(z)).with(U.Polygon,()=>h$(z)).with(U.Base,()=>x$(z)).with(U.Aurora,()=>P$(z)).with(U.Gnosis,()=>l$(z)).with(U.Monad,()=>d$(z)).with(U.Robinhood,()=>u$(z)).with(U.XLayer,()=>p$(z)).otherwise(()=>m$(z))}).otherwise(()=>{throw new t0("wallet_chain_not_supported",{chain:$,wallet:TY.LEDGER})})}var A8=[q.Arbitrum,q.Arc,q.Aurora,q.Avalanche,q.Base,q.Berachain,q.BinanceSmartChain,q.Bitcoin,q.BitcoinCash,q.Cardano,q.Cosmos,q.Dash,q.Dogecoin,q.Ethereum,q.Gnosis,q.Litecoin,q.Monad,q.Near,q.Optimism,q.Polygon,q.Ripple,q.Robinhood,q.Stellar,q.Sui,q.THORChain,q.Ton,q.XLayer,q.Tron,q.Zcash],cY=[q.BitcoinCash,q.Bitcoin,q.Dash,q.Dogecoin,q.Litecoin,q.Zcash],D8=[q.Ethereum,q.Avalanche,q.Arbitrum,q.Arc,q.Berachain,q.Optimism,q.Polygon,q.BinanceSmartChain,q.Base,q.Aurora,q.Gnosis,q.Monad,q.Robinhood,q.XLayer];function dY($){return A8.includes($)}var pY=hY({connect:({addChain:$,supportedChains:Y,walletType:J})=>async function(Q,Z,{address:G,dmkSession:X,onDeviceActionState:F,originToken:B,transport:z}={}){let[W]=vY({chains:Q,supportedChains:Y,walletType:J});if(!W)return!1;let V=Z??SY[W],M=await Z1({address:G,chain:W,derivationPath:V,dmkSession:X,onDeviceActionState:F,originToken:B,transport:z});return $({...M,chain:W,walletType:N0.LEDGER}),!0},getExtendedPublicKey:sY,name:"connectLedger",signingSupport:{...Object.fromEntries(D8.map(($)=>[$,{direct:!0,typedData:!0}])),[q.Bitcoin]:{direct:!0},[q.BitcoinCash]:{direct:!0},[q.Cardano]:{direct:!0},[q.Cosmos]:{direct:!0},[q.Dash]:{direct:!0},[q.Dogecoin]:{direct:!0},[q.Litecoin]:{direct:!0},[q.Near]:{direct:!0},[q.Ripple]:{direct:!0},[q.Stellar]:{direct:!0},[q.Sui]:{direct:!0},[q.THORChain]:{direct:!0},[q.Ton]:{direct:!0},[q.Tron]:{direct:!0}},supportedChains:[...A8],walletType:N0.LEDGER}),G5=uY(pY);function y8({chain:$,path:Y,signer:J,xpubVersion:j}){let Q=U0($).with(q.Bitcoin,q.Litecoin,()=>Y).with(q.BitcoinCash,q.Dash,q.Dogecoin,q.Zcash,()=>Y.replace(/^m\//,"")).exhaustive();return U0($).with(q.Bitcoin,()=>J.getExtendedPublicKey({path:Q})).with(q.Zcash,()=>J.getExtendedPublicKey({path:Q,xpubVersion:j})).with(q.BitcoinCash,q.Dash,q.Dogecoin,q.Litecoin,()=>J.getExtendedPublicKey(Q,j)).exhaustive()}function oY($){let Y=b8(q.Zcash),J=D0((j)=>Y.getRawTx(j));return Promise.all(Array.from({length:$.inputsLength},async(j,Q)=>{let Z=$.getInput(Q),G=K8.encode(Z.txid),X=K8.encode(Z.txid.slice().reverse()),F=await J(G),[B,z]=F?[G,F]:[X,await J(X)];if(!z)throw new t("wallet_ledger_invalid_params",{inputIndex:Q,outputIndex:Z.index,reason:"Unable to resolve previous transaction hex for Ledger signing in either txid byte order",reversedTxid:X,txid:G});return{hash:B,index:Z.index,txHex:z,value:Number(Z.value)}}))}async function sY($,Y,{accountIndex:J,dmkSession:j,onDeviceActionState:Q,transport:Z}={}){if(![q.BitcoinCash,q.Bitcoin,q.Dash,q.Dogecoin,q.Litecoin,q.Zcash].includes($))throw new t("wallet_chain_not_supported",{chain:$,wallet:N0.LEDGER});let G=$,X=await u({chain:G,derivationPath:Y,dmkSession:j,onDeviceActionState:Q,transport:Z});if(!X.getExtendedPublicKey)return;let F=k8({accountIndex:J,chain:G,derivationPath:Y}),B=v0(F),z=f8(G).bip32.public;try{let W=await y8({chain:G,path:B,signer:X,xpubVersion:z});return{accountIndex:e0(F),path:B,xpub:W}}finally{await X.disconnect?.()}}async function iY({address:$,chain:Y,dmkSession:J,derivationPath:j,onDeviceActionState:Q,transport:Z}){let{getUtxoToolbox:G}=await import("@swapkit/toolboxes/utxo"),X=Y,F=await u({chain:Y,derivationPath:j,dmkSession:J,onDeviceActionState:Q,transport:Z}),B=$??await o({chain:Y,ledgerClient:F}),z=(Y===q.Bitcoin?PY(j):void 0)??gY(B,X),{publicKey:W,signLedgerTransaction:V,toolboxSigner:M}=await U0(Y).with(q.Bitcoin,async()=>{let R=F,k=z===C0.P2SH_P2WPKH||z===C0.P2TR?await R.getPublicKey():void 0;return{publicKey:k,signLedgerTransaction:({inputUtxos:f,transaction:A})=>R.signTransactionHex({inputUtxos:f,tx:A}),toolboxSigner:{getAddress:R.getAddress,publicKey:k,signTransaction:R.signTransaction}}}).with(q.BitcoinCash,q.Dogecoin,q.Dash,q.Litecoin,async()=>{let{createLegacyPsbtSigner:R,signLegacyPsbtTransaction:O}=await import("../chunk-tm5gk51g.js"),k=F;return{publicKey:void 0,signLedgerTransaction:({inputUtxos:f,transaction:A})=>O({chain:X,inputUtxos:f,legacyClient:k,tx:A}),toolboxSigner:R({address:B,chain:X,legacyClient:k})}}).with(q.Zcash,()=>{let R=F;return{publicKey:void 0,signLedgerTransaction:async({inputUtxos:O,transaction:k})=>{if(!("consensusBranchId"in k))throw new t("wallet_ledger_method_not_supported",{method:"signPCZT",wallet:N0.LEDGER});let f=O??await oY(k);return R.signTransaction({inputUtxos:f,tx:k})},toolboxSigner:void 0}}).exhaustive(),N=M?await G(X,{scriptType:z,signer:M}):G(X,{scriptType:z}),_=async(R)=>N.broadcastTx(await V({transaction:R})),w=async(R)=>{let O=R.feeRate||(await N.getFeeRates())[R.feeOptionKey||R8.Fast],{tx:k,inputs:f}=await N.createTransaction({...R,feeRate:O,fetchTxHex:!0,publicKey:R.publicKey??W,sender:B}),A=await V({inputUtxos:f,transaction:k});return await N.broadcastTx(A)};async function y({accountIndex:R}={}){if(!F.getExtendedPublicKey)return;let O=k8({accountIndex:R,chain:X,derivationPath:j}),k=v0(O),f=f8(X).bip32.public,A=await y8({chain:Y,path:k,signer:F,xpubVersion:f});return{accountIndex:e0(O),path:k,xpub:A}}function I(R={}){return y(R)}async function L({accountIndex:R,index:O,change:k=!1}){try{let f=U8({accountIndex:R,chain:X,change:k,derivationPath:j,index:O}),A=await u({chain:X,derivationPath:f,dmkSession:J,onDeviceActionState:Q,transport:Z}),P=await o({chain:X,ledgerClient:A});return{accountIndex:e0(f),address:P,change:k,index:O,path:v0(f),pubkey:""}}catch{return}}async function K({accountIndex:R,count:O,startIndex:k=0,change:f=!1}){return w8("count",O),w8("startIndex",k),(await Promise.all(Array.from({length:O},(P,v)=>L({accountIndex:R,change:f,index:k+v})))).filter((P)=>!!P)}let b=lY({chain:X,deriveAddress:L,getBalance:N.getBalance,getUtxos:(R)=>b8(X).getUtxos({address:R,fetchTxHex:!0})});async function C({utxos:R,recipient:O,assetValue:k,memo:f,feeRate:A,feeOptionKey:P,changeAddress:v}){if(Y===q.Zcash)throw new t("wallet_ledger_method_not_supported",{method:"transferFromMultipleAddresses",wallet:N0.LEDGER});if(!R.length)throw new t("wallet_ledger_invalid_params",{message:"No UTXOs provided for multi-address transfer"});let S=A||(await N.getFeeRates())[P||R8.Fast],c=f?mY(f):null,Q0=[{address:O,value:k.getBaseValue("number")}];if(c)Q0.push({script:c,value:0});let e=R.map(({hash:f0,index:k0,value:S0,txHex:b0,witnessUtxo:T8})=>({hash:f0,index:k0,txHex:b0,value:S0,witnessUtxo:T8})),{inputs:n,outputs:L0}=N.accumulative({chain:X,feeRate:S,inputs:e,outputs:Q0});if(!(n&&L0))throw new t("wallet_ledger_connection_error",{message:"Insufficient balance for multi-address transfer"});let{Transaction:O0}=await import("@swapkit/utxo-signer"),P0=new O0({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!c,version:1}),I8=v||R[0]?.address||O;xY({chain:X,compiledMemo:c,inputs:n,outputs:L0,sender:I8,tx:P0});let $$=n.map((f0)=>{let k0=R.find((b0)=>b0.hash===f0.hash&&b0.index===f0.index),S0=U8({chain:X,change:k0?.isChange??!1,derivationPath:j,index:k0?.derivationIndex??0});return v0(S0)});if(!F.signTransactionWithMultiplePaths)throw new t("wallet_ledger_method_not_supported",{method:"signTransactionWithMultiplePaths"});let E8=await U0(Y).with(q.Bitcoin,()=>F.signTransactionWithMultiplePaths({derivationPaths:$$,inputUtxos:n,tx:P0})).with(q.BitcoinCash,q.Dash,q.Dogecoin,q.Litecoin,()=>F.signTransactionWithMultiplePaths(P0,n,$$)).exhaustive();return N.broadcastTx(E8)}return{...N,...b,address:B,deriveAddressAtIndex:L,deriveAddresses:K,getExtendedPublicKey:I,getExtendedPublicKeyInfo:y,signAndBroadcastTransaction:_,transfer:w,transferFromMultipleAddresses:C}}async function nY({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,originToken:Q,transport:Z}){let G=await u({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,originToken:Q,transport:Z}),{getEvmToolboxAsync:X}=await import("@swapkit/toolboxes/evm"),F=await o({chain:$,ledgerClient:G});return{...await X($,{signer:G}),address:F}}async function rY({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}){let Z=await u({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}),{getCosmosToolbox:G}=await import("@swapkit/toolboxes/cosmos"),X=G($,{signer:Z}),F=await o({chain:$,ledgerClient:Z});return{...X,address:F}}async function aY({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}){let Z=await u({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}),{getCosmosToolbox:G}=await import("@swapkit/toolboxes/cosmos"),X=G($,{signer:Z}),F=await o({chain:$,ledgerClient:Z}),{sign:B}=Z;return{...X,address:F,signMessage:B}}async function tY({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}){let{getNearToolbox:Z}=await import("@swapkit/toolboxes/near"),G=await u({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}),X=await G.getAddress();return{...Z({signer:G}),address:X}}async function eY({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}){let{getCardanoToolbox:Z}=await import("@swapkit/toolboxes/cardano"),G=await u({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}),X=G.getAddress();return{...Z({signer:G}),address:X}}async function $1({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}){let{getRippleToolbox:Z}=await import("@swapkit/toolboxes/ripple"),G=await u({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}),X=G.getAddress();return{...Z({signer:G}),address:X}}async function Y1({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}){let{getStellarToolbox:Z}=await import("@swapkit/toolboxes/stellar"),G=await u({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}),X=await o({chain:$,ledgerClient:G});return{...Z({signer:G}),address:X}}async function J1({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}){let{getTronToolbox:Z}=await import("@swapkit/toolboxes/tron"),G=await u({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}),X=await o({chain:$,ledgerClient:G});return{...Z({signer:G}),address:X}}async function j1({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}){let{getSuiToolbox:Z}=await import("@swapkit/toolboxes/sui"),G=await u({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}),X=await o({chain:$,ledgerClient:G});return{...Z({signer:G}),address:X}}async function Q1({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}){let{getTONToolbox:Z}=await import("@swapkit/toolboxes/ton"),G=await u({chain:$,derivationPath:Y,dmkSession:J,onDeviceActionState:j,transport:Q}),X=await o({chain:$,ledgerClient:G}),F=Z(),B=async(M)=>F.broadcastTransaction(await G.signTransaction(M));return{...F,address:X,estimateTransactionFee:({assetValue:M})=>Promise.resolve(CY.from({chain:q.Ton,value:M.isGasAsset?"0.01":"0.06"})),getAddress:()=>X,getBalance:()=>F.getBalance(X),sign:()=>{throw new t("wallet_ledger_method_not_supported",{method:"sign",wallet:N0.LEDGER})},signAndBroadcastTransaction:B,transfer:async({assetValue:M,memo:N,recipient:_,sweep:w})=>B(await F.createTransaction({assetValue:M,memo:N,recipient:_,sender:X,sweep:w}))}}function Z1($){if(!dY($.chain))throw new t("wallet_ledger_chain_not_supported",{chain:$.chain});return U0($.chain).with(O8.union(...cY),(Y)=>iY({...$,chain:Y})).with(O8.union(...D8),(Y)=>nY({...$,chain:Y})).with(q.Cosmos,(Y)=>rY({...$,chain:Y})).with(q.THORChain,(Y)=>aY({...$,chain:Y})).with(q.Near,(Y)=>tY({...$,chain:Y})).with(q.Ripple,(Y)=>$1({...$,chain:Y})).with(q.Stellar,(Y)=>Y1({...$,chain:Y})).with(q.Cardano,(Y)=>eY({...$,chain:Y})).with(q.Tron,(Y)=>J1({...$,chain:Y})).with(q.Sui,(Y)=>j1({...$,chain:Y})).with(q.Ton,(Y)=>Q1({...$,chain:Y})).exhaustive()}export{Z$ as preloadLedgerDMK,pY as ledgerWallet,sY as getLedgerExtendedPublicKey,r as getLedgerDMKSession,X$ as disconnectLedgerDMKSession,G5 as LEDGER_SUPPORTED_CHAINS};
2
2
 
3
- //# debugId=42A8EA57BF63933D64756E2164756E21
3
+ //# debugId=7C6193C95BBAA7BE64756E2164756E21
4
4
  //# sourceMappingURL=index.js.map