@antseed/gateway-console 0.1.9 → 0.1.11

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 (162) hide show
  1. package/dist/assets/Activity-UaQeZdKk.js +1 -0
  2. package/dist/assets/{Audit-tBcMBtG2.js → Audit-Cd26xOlL.js} +1 -1
  3. package/dist/assets/BrandIcon-dTKznfCA.js +1 -0
  4. package/dist/assets/{ChainGate-bxLjo_3b.js → ChainGate-DpChfDOP.js} +1 -1
  5. package/dist/assets/{ChannelClose-C0Y19KzJ.js → ChannelClose-DpNV5MqB.js} +1 -1
  6. package/dist/assets/{Charts-CHTi7z3n.js → Charts-C65ZE2xP.js} +1 -1
  7. package/dist/assets/Chat-BbM_y6mh.js +225 -0
  8. package/dist/assets/{ConnectWallet-fHEv854J.js → ConnectWallet-CLv0c-JB.js} +1 -1
  9. package/dist/assets/{DataTable-CCEZoIzX.js → DataTable-BkJdorEh.js} +1 -1
  10. package/dist/assets/{Disclosure-BitAjv2r.js → Disclosure-DMLE7rCw.js} +1 -1
  11. package/dist/assets/KeyHolder-Cjko0nrs.js +1 -0
  12. package/dist/assets/{Keys-C22oAYzQ.js → Keys-DLKN6Sna.js} +1 -1
  13. package/dist/assets/Logs-DIPNoSb8.js +1 -0
  14. package/dist/assets/{Members-ZyqdMsMd.js → Members-CgP9OTz9.js} +1 -1
  15. package/dist/assets/{Migrate-TGloMMad.js → Migrate-DDHZ-rux.js} +1 -1
  16. package/dist/assets/ModelDetails-CkDNU2Px.js +1 -0
  17. package/dist/assets/Models-DXbiNymT.js +1 -0
  18. package/dist/assets/{OperatorActions-DPQvd1zg.js → OperatorActions-BuEpaCiH.js} +1 -1
  19. package/dist/assets/{OperatorGateAlert-CEK2vyQ9.js → OperatorGateAlert-grMRoFdV.js} +1 -1
  20. package/dist/assets/{Overview-CPoqW_Mi.js → Overview-BU9HCltc.js} +1 -1
  21. package/dist/assets/{PeerPicker-w_ZaksUm.js → PeerPicker-CfsXTUyK.js} +1 -1
  22. package/dist/assets/{PolicyEditor-BOjadRE8.js → PolicyEditor-ptFDJhFh.js} +1 -1
  23. package/dist/assets/{PolicyField-BbDSVgcK.js → PolicyField-CHhm50jF.js} +1 -1
  24. package/dist/assets/{Presets-9x2m9R-f.js → Presets-szQETQLM.js} +1 -1
  25. package/dist/assets/Providers-B6xbFeNU.js +1 -0
  26. package/dist/assets/RequestLog-DJl6FJhq.js +1 -0
  27. package/dist/assets/{Rewards-D9omoUfP.js → Rewards-BOfJumNk.js} +2 -2
  28. package/dist/assets/{RewardsClaim-CWJBaJEv.js → RewardsClaim-DHvgMfZ4.js} +1 -1
  29. package/dist/assets/Routing-DFuhPfzU.js +1 -0
  30. package/dist/assets/{Segmented-D_Yun-tG.js → Segmented-D3e0aBDU.js} +1 -1
  31. package/dist/assets/{SelectField-D3qPiNQz.js → SelectField-Cl4acfcI.js} +1 -1
  32. package/dist/assets/{Settings-Bo654hg3.js → Settings--0bbw1dn.js} +2 -2
  33. package/dist/assets/SidePanel-D0rNElh3.js +1 -0
  34. package/dist/assets/{Staking-HKOLSr5r.js → Staking-1D2HNu5P.js} +1 -1
  35. package/dist/assets/{StakingDashboard-BHU6EJ_h.js → StakingDashboard-C5Ib_AUs.js} +1 -1
  36. package/dist/assets/{Switch-BmFsXcr8.js → Switch-B2AEvyu7.js} +1 -1
  37. package/dist/assets/{Tabs-DmkE9BPd.js → Tabs-Cv10NtDy.js} +1 -1
  38. package/dist/assets/{TextAreaField-RZPCzhKZ.js → TextAreaField-Dbr655cs.js} +1 -1
  39. package/dist/assets/{UsageByModel-nhGKdBi8.js → UsageByModel-BfvCLwo9.js} +1 -1
  40. package/dist/assets/VerificationLinks-CERoRvCR.js +1 -0
  41. package/dist/assets/{Wallet-jy4q5mLQ.js → Wallet-CVS_hzu0.js} +3 -3
  42. package/dist/assets/{WalletConfirm-dV_LWLAS.js → WalletConfirm-C8Kazsh7.js} +1 -1
  43. package/dist/assets/{WalletFunding-B3t7wm--.js → WalletFunding-BbhXB813.js} +1 -1
  44. package/dist/assets/{WalletSignIn-BTt56Pbi.js → WalletSignIn-Tzs38aME.js} +1 -1
  45. package/dist/assets/{Workspaces-mfw5erSQ.js → Workspaces-DGgrOEZk.js} +1 -1
  46. package/dist/assets/{add-BWOpvuwn.js → add-CdcnAnIQ.js} +1 -1
  47. package/dist/assets/{all-wallets-Dzo5pBZj.js → all-wallets-CaMIS0WH.js} +1 -1
  48. package/dist/assets/{app-store-D7NT8p3m.js → app-store-BJlWsf36.js} +1 -1
  49. package/dist/assets/{apple-DZKBu-O0.js → apple-sOU-w3fg.js} +1 -1
  50. package/dist/assets/{arrow-bottom-CL8pk1cz.js → arrow-bottom-CTOfZJ7E.js} +1 -1
  51. package/dist/assets/{arrow-bottom-circle-CfYYPCEB.js → arrow-bottom-circle-B6IrOSiK.js} +1 -1
  52. package/dist/assets/{arrow-left-DVKw3BfQ.js → arrow-left-D0Qm9EWX.js} +1 -1
  53. package/dist/assets/{arrow-right-LIBetaMw.js → arrow-right-XMSWQLiv.js} +1 -1
  54. package/dist/assets/{arrow-top-Bdq-JU1Z.js → arrow-top-Bym-ayRK.js} +1 -1
  55. package/dist/assets/{bank-BYRxGjPq.js → bank-NJF8WYDR.js} +1 -1
  56. package/dist/assets/{basic-CZ6XfWue.js → basic-bO70Xvle.js} +1 -1
  57. package/dist/assets/{browser-4mXAG82s.js → browser-ucjw1tpv.js} +1 -1
  58. package/dist/assets/{bundle-full-BIYMHvS6.js → bundle-full-idGWmtvy.js} +1 -1
  59. package/dist/assets/{card-CHQPd736.js → card-DcpyI2qX.js} +1 -1
  60. package/dist/assets/{ccip-CDMxOoDo.js → ccip-DBXxv0FH.js} +1 -1
  61. package/dist/assets/{checkmark-8o_U76Ey.js → checkmark-RFLSeCgj.js} +1 -1
  62. package/dist/assets/{checkmark-bold-DLi4Gcn_.js → checkmark-bold-Dl1q9Kby.js} +1 -1
  63. package/dist/assets/{chevron-bottom-DmX6fEDV.js → chevron-bottom-ilycsYd4.js} +1 -1
  64. package/dist/assets/{chevron-left-AyKJMTQa.js → chevron-left-DFK2Xbq1.js} +1 -1
  65. package/dist/assets/{chevron-right-DQ8e2bPT.js → chevron-right-Ew8XV9m9.js} +1 -1
  66. package/dist/assets/{chevron-top-B5o-6za5.js → chevron-top-CxoXH2-q.js} +1 -1
  67. package/dist/assets/{chrome-store-BSncx9O2.js → chrome-store-ClmhY3B0.js} +1 -1
  68. package/dist/assets/{clock-DBlIwqMs.js → clock-CCiukNBf.js} +1 -1
  69. package/dist/assets/{close-CGfPRgam.js → close-B0KBYbXe.js} +1 -1
  70. package/dist/assets/code-block-DxUcjw4S.js +3 -0
  71. package/dist/assets/{coinPlaceholder-BUSXHM7f.js → coinPlaceholder-D2ugxr3r.js} +1 -1
  72. package/dist/assets/{compass-WMx9aHQn.js → compass-CutyEYmW.js} +1 -1
  73. package/dist/assets/{copy-4QWyzVbB.js → copy-CJ0RBt1e.js} +1 -1
  74. package/dist/assets/{core-4C0uPyns.js → core-BCJdIbrO.js} +3 -3
  75. package/dist/assets/cursor-Bg_hT9DN.js +3 -0
  76. package/dist/assets/{cursor-transparent-BaithBa8.js → cursor-transparent-BQ_jwSfb.js} +1 -1
  77. package/dist/assets/{desktop-pj3LdQx_.js → desktop-CsfFLaEs.js} +1 -1
  78. package/dist/assets/{disconnect-cmEUajMk.js → disconnect-B62slDXp.js} +1 -1
  79. package/dist/assets/{discord-BYVJX-t1.js → discord-B8GwtWtL.js} +1 -1
  80. package/dist/assets/{en_US-Y4ZOVFV4-BZ-715IV.js → en_US-Y4ZOVFV4-sKQksBWU.js} +4 -4
  81. package/dist/assets/{etherscan-BdQaeBLV.js → etherscan-BT9zhNhd.js} +1 -1
  82. package/dist/assets/{exclamation-triangle-B5R8OH8o.js → exclamation-triangle-BSoPK6uq.js} +1 -1
  83. package/dist/assets/{extension-DrkCTDz1.js → extension-CQxJq6bp.js} +1 -1
  84. package/dist/assets/{external-link-CZIsXhQB.js → external-link-BnfAKGN2.js} +1 -1
  85. package/dist/assets/{facebook-B8mGiKom.js → facebook-DiAqdu4i.js} +1 -1
  86. package/dist/assets/{farcaster-BlEPprye.js → farcaster-B1y2in5M.js} +1 -1
  87. package/dist/assets/{filters-QpslZY8t.js → filters-BkVUp9NW.js} +1 -1
  88. package/dist/assets/{github-3U8av1u0.js → github-IRwi-GM-.js} +1 -1
  89. package/dist/assets/{google-DuIQFQyG.js → google-k2ysL2bi.js} +1 -1
  90. package/dist/assets/{help-circle-BKX8azWY.js → help-circle-DLj9trmu.js} +1 -1
  91. package/dist/assets/highlighted-body-KQOG7T2V-CJM-VU3I.js +1 -0
  92. package/dist/assets/{id-DoN-p9_h.js → id-BY4HWjv7.js} +1 -1
  93. package/dist/assets/{image-DnOVeCbR.js → image-BtUeZe1t.js} +1 -1
  94. package/dist/assets/{index-DeVTk1EB.js → index-BXwAwVaO.js} +1 -1
  95. package/dist/assets/{index-B25V3jQV.js → index-Cmb-H95F.js} +1 -1
  96. package/dist/assets/index-DYK1gWhP.css +1 -0
  97. package/dist/assets/{index-BPmBiG1M.js → index-DiB9Y59V.js} +3 -3
  98. package/dist/assets/{index-A9482YJO.js → index-DsRX2D_O.js} +1 -1
  99. package/dist/assets/index-cESr4Zze.js +91 -0
  100. package/dist/assets/{index.es-C1jtws71.js → index.es-DP9EmOYi.js} +3 -3
  101. package/dist/assets/{info-CdmGz8ET.js → info-BaKj81_D.js} +1 -1
  102. package/dist/assets/{info-circle-C6CmWEn4.js → info-circle-ecoA_B_t.js} +1 -1
  103. package/dist/assets/{lightbulb-BAyNXoa1.js → lightbulb-DGQG-WWk.js} +1 -1
  104. package/dist/assets/{limits-DjiKmaDB.js → limits-D2JvFgaN.js} +1 -1
  105. package/dist/assets/{mail-CiF1vNhi.js → mail-BvEbsX3q.js} +1 -1
  106. package/dist/assets/{mermaid-MCJ5UELQ-nKICVXNz.js → mermaid-MCJ5UELQ-B8uOykea.js} +3 -3
  107. package/dist/assets/{metamask-sdk-DkF2jP-o.js → metamask-sdk-BYmYI1f3.js} +1 -1
  108. package/dist/assets/{mobile-C1sek6EE.js → mobile-CwlM4JMX.js} +1 -1
  109. package/dist/assets/{more-Dg3gTue9.js → more-CT36TpLm.js} +1 -1
  110. package/dist/assets/{network-placeholder-DjgO487Z.js → network-placeholder-DG1Vvm-U.js} +1 -1
  111. package/dist/assets/{nftPlaceholder-CJQkl27U.js → nftPlaceholder-D6USOn7p.js} +1 -1
  112. package/dist/assets/{off-CH17X0ZN.js → off-BNSO7pY1.js} +1 -1
  113. package/dist/assets/{play-store-CQuK3mcO.js → play-store-PUfM0qU0.js} +1 -1
  114. package/dist/assets/{plus-pEvbyOXN.js → plus-C8fnGfp3.js} +1 -1
  115. package/dist/assets/{qr-code-Cl8u00kF.js → qr-code-CjdrQ0pR.js} +1 -1
  116. package/dist/assets/{recycle-horizontal-C2j4VihN.js → recycle-horizontal-BMxBgeB4.js} +1 -1
  117. package/dist/assets/{refresh-DiGzIXYL.js → refresh-C2D196Fq.js} +1 -1
  118. package/dist/assets/{reown-logo-lnPAI4aT.js → reown-logo-CLN2ORKJ.js} +1 -1
  119. package/dist/assets/{search-yadtJ599.js → search-C9voC8dq.js} +1 -1
  120. package/dist/assets/selection-HN8SZ52c.js +1 -0
  121. package/dist/assets/{send-C3NLDzpo.js → send-BAxcrGbA.js} +1 -1
  122. package/dist/assets/{sendTransaction-qrdT91Tm.js → sendTransaction-Cmz5eiPq.js} +1 -1
  123. package/dist/assets/stored-CETnaQtE.js +1 -0
  124. package/dist/assets/{swapHorizontal-C3NCkGQo.js → swapHorizontal-CHCTyoP7.js} +1 -1
  125. package/dist/assets/{swapHorizontalBold-BZwhavke.js → swapHorizontalBold-LQsONWBk.js} +1 -1
  126. package/dist/assets/{swapHorizontalMedium-Cmnd2nih.js → swapHorizontalMedium-BxrBEjrx.js} +1 -1
  127. package/dist/assets/{swapHorizontalRoundedBold-gSkn4e0W.js → swapHorizontalRoundedBold-CEHDoSv1.js} +1 -1
  128. package/dist/assets/{swapVertical-B3cp9dIz.js → swapVertical-DMylrYB1.js} +1 -1
  129. package/dist/assets/{telegram-CCcfHXb2.js → telegram-BhVfpln1.js} +1 -1
  130. package/dist/assets/{three-dots-Dn7VO-lq.js → three-dots-nkXRRS-E.js} +1 -1
  131. package/dist/assets/{twitch-C46oL1KF.js → twitch-CYroZH_7.js} +1 -1
  132. package/dist/assets/{twitterIcon-CAkiEmDS.js → twitterIcon-DpHUqlyA.js} +1 -1
  133. package/dist/assets/usage-8BBeTlF-.js +1 -0
  134. package/dist/assets/{useInfiniteQuery-Dwl-oWNd.js → useInfiniteQuery-zD1WIYBy.js} +1 -1
  135. package/dist/assets/{useTx-CT2tKEAI.js → useTx-DsLsc5bB.js} +1 -1
  136. package/dist/assets/{verify-jbEYtj7t.js → verify-DARDbLiQ.js} +1 -1
  137. package/dist/assets/{verify-filled-CtFkkLAN.js → verify-filled-EsNi41IB.js} +1 -1
  138. package/dist/assets/{w3m-modal-Drzo9R1s.js → w3m-modal-CIUN4uxE.js} +1 -1
  139. package/dist/assets/{waitForCallsStatus-CU9lZ8Vj.js → waitForCallsStatus-DlpsNYx1.js} +1 -1
  140. package/dist/assets/{wallet-B11Hl0Lf.js → wallet-B2vgeP1E.js} +1 -1
  141. package/dist/assets/{wallet-placeholder-DwLspbFR.js → wallet-placeholder-DQsissb3.js} +1 -1
  142. package/dist/assets/{walletconnect-3aC0SnNJ.js → walletconnect-DylNgC0Z.js} +1 -1
  143. package/dist/assets/{warning-circle-DuqXAhpW.js → warning-circle-CVEgsVb4.js} +1 -1
  144. package/dist/assets/{writeContract-m5SoBxcM.js → writeContract-Cqg_OlRQ.js} +1 -1
  145. package/dist/assets/{x-DTeu3B0J.js → x-DSURRh6S.js} +1 -1
  146. package/dist/index.html +2 -2
  147. package/package.json +1 -1
  148. package/dist/assets/Activity-DrhhsiYE.js +0 -1
  149. package/dist/assets/Chat-C1AfYZwW.js +0 -220
  150. package/dist/assets/KeyHolder-DSLJe1Wc.js +0 -1
  151. package/dist/assets/Logs-DHuR0CKc.js +0 -1
  152. package/dist/assets/Models-CM4ay6RE.js +0 -1
  153. package/dist/assets/Providers-CqYXx8xK.js +0 -1
  154. package/dist/assets/RequestLog-39L0RtJc.js +0 -1
  155. package/dist/assets/Routing-4gxa6VdE.js +0 -1
  156. package/dist/assets/code-block-B9znTLtr.js +0 -3
  157. package/dist/assets/cursor-C_vrGLpb.js +0 -3
  158. package/dist/assets/highlighted-body-KQOG7T2V-9-ocLujg.js +0 -1
  159. package/dist/assets/index-BpFwvYMF.js +0 -91
  160. package/dist/assets/index-C9evdHF9.css +0 -1
  161. package/dist/assets/models-CJU4tPJk.js +0 -1
  162. package/dist/assets/usage-yuqGLybi.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/core-4C0uPyns.js","assets/index-BpFwvYMF.js","assets/index-C9evdHF9.css","assets/en_US-Y4ZOVFV4-BZ-715IV.js","assets/clsx-B-dksMZM.js","assets/index-BhwNCc8y.js","assets/en_US-Y4ZOVFV4-CcVPgXVa.css"])))=>i.map(i=>d[i]);
2
- import{c5 as co,cq as Tl,c4 as vt,_ as Qu}from"./index-BpFwvYMF.js";import{r as Xu}from"./events-DQ172AOg.js";import{az as ed}from"./en_US-Y4ZOVFV4-BZ-715IV.js";function hr(r){return new Promise((e,t)=>{r.oncomplete=r.onsuccess=()=>e(r.result),r.onabort=r.onerror=()=>t(r.error)})}function Rl(r,e){let t;const i=()=>{if(t)return t;const s=indexedDB.open(r);return s.onupgradeneeded=()=>s.result.createObjectStore(e),t=hr(s),t.then(n=>{n.onclose=()=>t=void 0},()=>{}),t};return(s,n)=>i().then(o=>n(o.transaction(e,s).objectStore(e)))}let Rs;function _i(){return Rs||(Rs=Rl("keyval-store","keyval")),Rs}function Fo(r,e=_i()){return e("readonly",t=>hr(t.get(r)))}function td(r,e,t=_i()){return t("readwrite",i=>(i.put(e,r),hr(i.transaction)))}function rd(r,e=_i()){return e("readwrite",t=>(t.delete(r),hr(t.transaction)))}function id(r=_i()){return r("readwrite",e=>(e.clear(),hr(e.transaction)))}function sd(r,e){return r.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},hr(r.transaction)}function nd(r=_i()){return r("readonly",e=>{if(e.getAllKeys)return hr(e.getAllKeys());const t=[];return sd(e,i=>t.push(i.key)).then(()=>t)})}var Ye=Xu();const lo=co(Ye);var Lo=function(r,e,t){if(t||arguments.length===2)for(var i=0,s=e.length,n;i<s;i++)(n||!(i in e))&&(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return r.concat(n||Array.prototype.slice.call(e))},od=(function(){function r(e,t,i){this.name=e,this.version=t,this.os=i,this.type="browser"}return r})(),ad=(function(){function r(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return r})(),cd=(function(){function r(e,t,i,s){this.name=e,this.version=t,this.os=i,this.bot=s,this.type="bot-device"}return r})(),ld=(function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r})(),hd=(function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r})(),ud=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,dd=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Mo=3,pd=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",ud]],ko=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function fd(r){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new hd:typeof navigator<"u"?yd(navigator.userAgent):wd()}function gd(r){return r!==""&&pd.reduce(function(e,t){var i=t[0],s=t[1];if(e)return e;var n=s.exec(r);return!!n&&[i,n]},!1)}function yd(r){var e=gd(r);if(!e)return null;var t=e[0],i=e[1];if(t==="searchbot")return new ld;var s=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);s?s.length<Mo&&(s=Lo(Lo([],s,!0),bd(Mo-s.length),!0)):s=[];var n=s.join("."),o=md(r),a=dd.exec(r);return a&&a[1]?new cd(t,n,o,a[1]):new od(t,n,o)}function md(r){for(var e=0,t=ko.length;e<t;e++){var i=ko[e],s=i[0],n=i[1],o=n.exec(r);if(o)return s}return null}function wd(){var r=typeof process<"u"&&process.version;return r?new ad(process.version.slice(1)):null}function bd(r){for(var e=[],t=0;t<r;t++)e.push("0");return e}var Ns={};/*! *****************************************************************************
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/core-BCJdIbrO.js","assets/index-cESr4Zze.js","assets/index-DYK1gWhP.css","assets/en_US-Y4ZOVFV4-sKQksBWU.js","assets/clsx-B-dksMZM.js","assets/index-BhwNCc8y.js","assets/en_US-Y4ZOVFV4-CcVPgXVa.css"])))=>i.map(i=>d[i]);
2
+ import{c9 as co,cu as Tl,c8 as vt,_ as Qu}from"./index-cESr4Zze.js";import{r as Xu}from"./events-DQ172AOg.js";import{az as ed}from"./en_US-Y4ZOVFV4-sKQksBWU.js";function hr(r){return new Promise((e,t)=>{r.oncomplete=r.onsuccess=()=>e(r.result),r.onabort=r.onerror=()=>t(r.error)})}function Rl(r,e){let t;const i=()=>{if(t)return t;const s=indexedDB.open(r);return s.onupgradeneeded=()=>s.result.createObjectStore(e),t=hr(s),t.then(n=>{n.onclose=()=>t=void 0},()=>{}),t};return(s,n)=>i().then(o=>n(o.transaction(e,s).objectStore(e)))}let Rs;function _i(){return Rs||(Rs=Rl("keyval-store","keyval")),Rs}function Fo(r,e=_i()){return e("readonly",t=>hr(t.get(r)))}function td(r,e,t=_i()){return t("readwrite",i=>(i.put(e,r),hr(i.transaction)))}function rd(r,e=_i()){return e("readwrite",t=>(t.delete(r),hr(t.transaction)))}function id(r=_i()){return r("readwrite",e=>(e.clear(),hr(e.transaction)))}function sd(r,e){return r.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},hr(r.transaction)}function nd(r=_i()){return r("readonly",e=>{if(e.getAllKeys)return hr(e.getAllKeys());const t=[];return sd(e,i=>t.push(i.key)).then(()=>t)})}var Ye=Xu();const lo=co(Ye);var Lo=function(r,e,t){if(t||arguments.length===2)for(var i=0,s=e.length,n;i<s;i++)(n||!(i in e))&&(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return r.concat(n||Array.prototype.slice.call(e))},od=(function(){function r(e,t,i){this.name=e,this.version=t,this.os=i,this.type="browser"}return r})(),ad=(function(){function r(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return r})(),cd=(function(){function r(e,t,i,s){this.name=e,this.version=t,this.os=i,this.bot=s,this.type="bot-device"}return r})(),ld=(function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r})(),hd=(function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r})(),ud=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,dd=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Mo=3,pd=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",ud]],ko=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function fd(r){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new hd:typeof navigator<"u"?yd(navigator.userAgent):wd()}function gd(r){return r!==""&&pd.reduce(function(e,t){var i=t[0],s=t[1];if(e)return e;var n=s.exec(r);return!!n&&[i,n]},!1)}function yd(r){var e=gd(r);if(!e)return null;var t=e[0],i=e[1];if(t==="searchbot")return new ld;var s=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);s?s.length<Mo&&(s=Lo(Lo([],s,!0),bd(Mo-s.length),!0)):s=[];var n=s.join("."),o=md(r),a=dd.exec(r);return a&&a[1]?new cd(t,n,o,a[1]):new od(t,n,o)}function md(r){for(var e=0,t=ko.length;e<t;e++){var i=ko[e],s=i[0],n=i[1],o=n.exec(r);if(o)return s}return null}function wd(){var r=typeof process<"u"&&process.version;return r?new ad(process.version.slice(1)):null}function bd(r){for(var e=[],t=0;t<r;t++)e.push("0");return e}var Ns={};/*! *****************************************************************************
3
3
  Copyright (c) Microsoft Corporation.
4
4
 
5
5
  Permission to use, copy, modify, and/or distribute this software for any
@@ -35,4 +35,4 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
35
35
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
36
36
  PERFORMANCE OF THIS SOFTWARE.
37
37
  ***************************************************************************** */var zn=function(r,e){return zn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var s in i)i.hasOwnProperty(s)&&(t[s]=i[s])},zn(r,e)};function X0(r,e){zn(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var Hn=function(){return Hn=Object.assign||function(e){for(var t,i=1,s=arguments.length;i<s;i++){t=arguments[i];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},Hn.apply(this,arguments)};function eE(r,e){var t={};for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&e.indexOf(i)<0&&(t[i]=r[i]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(r);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(r,i[s])&&(t[i[s]]=r[i[s]]);return t}function tE(r,e,t,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(r,e,t,i);else for(var a=r.length-1;a>=0;a--)(o=r[a])&&(n=(s<3?o(n):s>3?o(e,t,n):o(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}function rE(r,e){return function(t,i){e(t,i,r)}}function iE(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function sE(r,e,t,i){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{l(i.next(h))}catch(u){o(u)}}function c(h){try{l(i.throw(h))}catch(u){o(u)}}function l(h){h.done?n(h.value):s(h.value).then(a,c)}l((i=i.apply(r,e||[])).next())})}function nE(r,e){var t={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},i,s,n,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(h){return c([l,h])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;t;)try{if(i=1,s&&(n=l[0]&2?s.return:l[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,l[1])).done)return n;switch(s=0,n&&(l=[l[0]&2,n.value]),l[0]){case 0:case 1:n=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,s=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(n=t.trys,!(n=n.length>0&&n[n.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!n||l[1]>n[0]&&l[1]<n[3])){t.label=l[1];break}if(l[0]===6&&t.label<n[1]){t.label=n[1],n=l;break}if(n&&t.label<n[2]){t.label=n[2],t.ops.push(l);break}n[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(h){l=[6,h],s=0}finally{i=n=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function oE(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]}function aE(r,e){for(var t in r)t!=="default"&&!e.hasOwnProperty(t)&&(e[t]=r[t])}function Vn(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],i=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&i>=r.length&&(r=void 0),{value:r&&r[i++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function cu(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i=t.call(r),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=i.next()).done;)n.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(t=i.return)&&t.call(i)}finally{if(o)throw o.error}}return n}function cE(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(cu(arguments[e]));return r}function lE(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var i=Array(r),s=0,e=0;e<t;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)i[s]=n[o];return i}function Ei(r){return this instanceof Ei?(this.v=r,this):new Ei(r)}function hE(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(r,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(d){i[d]&&(s[d]=function(f){return new Promise(function(p,g){n.push([d,f,p,g])>1||a(d,f)})})}function a(d,f){try{c(i[d](f))}catch(p){u(n[0][3],p)}}function c(d){d.value instanceof Ei?Promise.resolve(d.value.v).then(l,h):u(n[0][2],d)}function l(d){a("next",d)}function h(d){a("throw",d)}function u(d,f){d(f),n.shift(),n.length&&a(n[0][0],n[0][1])}}function uE(r){var e,t;return e={},i("next"),i("throw",function(s){throw s}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(s,n){e[s]=r[s]?function(o){return(t=!t)?{value:Ei(r[s](o)),done:s==="return"}:n?n(o):o}:n}}function dE(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof Vn=="function"?Vn(r):r[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(n){t[n]=r[n]&&function(o){return new Promise(function(a,c){o=r[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(l){n({value:l,done:a})},o)}}function pE(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function fE(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)Object.hasOwnProperty.call(r,t)&&(e[t]=r[t]);return e.default=r,e}function gE(r){return r&&r.__esModule?r:{default:r}}function yE(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function mE(r,e,t){if(!e.has(r))throw new TypeError("attempted to set private field on non-instance");return e.set(r,t),t}const wE=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Hn},__asyncDelegator:uE,__asyncGenerator:hE,__asyncValues:dE,__await:Ei,__awaiter:sE,__classPrivateFieldGet:yE,__classPrivateFieldSet:mE,__createBinding:oE,__decorate:tE,__exportStar:aE,__extends:X0,__generator:nE,__importDefault:gE,__importStar:fE,__makeTemplateObject:pE,__metadata:iE,__param:rE,__read:cu,__rest:eE,__spread:cE,__spreadArrays:lE,__values:Vn},Symbol.toStringTag,{value:"Module"})),bE=Tl(wE);var Pt={},Pc;function vE(){if(Pc)return Pt;Pc=1,Object.defineProperty(Pt,"__esModule",{value:!0}),Pt.isBrowserCryptoAvailable=Pt.getSubtleCrypto=Pt.getBrowerCrypto=void 0;function r(){return(vt===null||vt===void 0?void 0:vt.crypto)||(vt===null||vt===void 0?void 0:vt.msCrypto)||{}}Pt.getBrowerCrypto=r;function e(){const i=r();return i.subtle||i.webkitSubtle}Pt.getSubtleCrypto=e;function t(){return!!r()&&!!e()}return Pt.isBrowserCryptoAvailable=t,Pt}var $t={},$c;function EE(){if($c)return $t;$c=1,Object.defineProperty($t,"__esModule",{value:!0}),$t.isBrowser=$t.isNode=$t.isReactNative=void 0;function r(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}$t.isReactNative=r;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}$t.isNode=e;function t(){return!r()&&!e()}return $t.isBrowser=t,$t}var Ac;function _E(){return Ac||(Ac=1,(function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=bE;e.__exportStar(vE(),r),e.__exportStar(EE(),r)})(hn)),hn}var IE=_E();function wt(r=3){const e=Date.now()*Math.pow(10,r),t=Math.floor(Math.random()*Math.pow(10,r));return e+t}function sr(r=6){return BigInt(wt(r))}function zt(r,e,t){return{id:t||wt(),jsonrpc:"2.0",method:r,params:e}}function Os(r,e){return{id:r,jsonrpc:"2.0",result:e}}function Ps(r,e,t){return{id:r,jsonrpc:"2.0",error:DE(e)}}function DE(r,e){return typeof r>"u"?Oc(nu):(typeof r=="string"&&(r=Object.assign(Object.assign({},Oc(Po)),{message:r})),Z0(r.code)&&(r=Q0(r.code)),r)}class SE{}class OE extends SE{constructor(){super()}}class PE extends OE{constructor(e){super()}}const $E="^https?:",AE="^wss?:";function CE(r){const e=r.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function lu(r,e){const t=CE(r);return typeof t>"u"?!1:new RegExp(e).test(t)}function Cc(r){return lu(r,$E)}function xc(r){return lu(r,AE)}function xE(r){return new RegExp("wss?://localhost(:d{2,5})?").test(r)}function hu(r){return typeof r=="object"&&"id"in r&&"jsonrpc"in r&&r.jsonrpc==="2.0"}function $o(r){return hu(r)&&"method"in r}function $s(r){return hu(r)&&(bt(r)||tt(r))}function bt(r){return"result"in r}function tt(r){return"error"in r}let it=class extends PE{constructor(e){super(e),this.events=new Ye.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async request(e,t){return this.requestStrict(zt(e.method,e.params||[],e.id||sr().toString()),t)}async requestStrict(e,t){return new Promise(async(i,s)=>{if(!this.connection.connected)try{await this.open()}catch(n){s(n)}this.events.on(`${e.id}`,n=>{tt(n)?s(n.error):i(n.result)});try{await this.connection.send(e,t)}catch(n){s(n)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),$s(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}};const TE=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),RE=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Tc=r=>r.split("?")[0],Rc=10,NE=TE();let jE=class{constructor(e){if(this.url=e,this.events=new Ye.EventEmitter,this.registering=!1,!xc(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,t)=>{if(typeof this.socket>"u"){t(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(jt(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!xc(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return s(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((t,i)=>{const s=IE.isReactNative()?void 0:{rejectUnauthorized:!xE(e)},n=new NE(e,[],s);RE()?n.onerror=o=>{const a=o;i(this.emitError(a.error))}:n.on("error",o=>{i(this.emitError(o))}),n.onopen=()=>{this.onOpen(n),t(n)}})}onOpen(e){e.onmessage=t=>this.onPayload(t),e.onclose=t=>this.onClose(t),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const t=typeof e.data=="string"?or(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),s=i.message||i.toString(),n=Ps(e,s);this.events.emit("payload",n)}parseError(e,t=this.url){return au(e,Tc(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Rc&&this.events.setMaxListeners(Rc)}emitError(e){const t=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${Tc(this.url)}`));return this.events.emit("register_error",t),t}};var BE={};const uu="wc",du=2,Kn="core",It=`${uu}@2:${Kn}:`,UE={logger:"error"},qE={database:":memory:"},FE="crypto",Nc="client_ed25519_seed",LE=U.ONE_DAY,ME="keychain",kE="0.3",zE="messages",HE="0.3",jc=U.SIX_HOURS,VE="publisher",pu="irn",KE="error",fu="wss://relay.walletconnect.org",WE="relayer",we={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},GE="_subscription",Qe={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},YE=.1,Wn="2.21.1",ae={link_mode:"link_mode",relay:"relay"},ts={inbound:"inbound",outbound:"outbound"},JE="0.3",ZE="WALLETCONNECT_CLIENT_ID",Bc="WALLETCONNECT_LINK_MODE_APPS",He={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},QE="subscription",XE="0.3",e1="pairing",t1="0.3",ii={wc_pairingDelete:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:U.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:U.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:U.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:U.ONE_DAY,prompt:!1,tag:0},res:{ttl:U.ONE_DAY,prompt:!1,tag:0}}},tr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},ot={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},r1="history",i1="0.3",s1="expirer",et={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},n1="0.3",o1="verify-api",a1="https://verify.walletconnect.com",gu="https://verify.walletconnect.org",pi=gu,c1=`${pi}/v3`,l1=[a1,gu],h1="echo",u1="https://echo.walletconnect.com",mt={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},At={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},at={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},Yt={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},Jt={authenticated_session_approve_started:"authenticated_session_approve_started",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve"},si={no_internet_connection:"no_internet_connection",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},d1=.1,p1="event-client",f1=86400,g1="https://pulse.walletconnect.org/batch";function y1(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var s=0;s<r.length;s++){var n=r.charAt(s),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,w=0,E=0,b=p.length;E!==b&&p[E]===0;)E++,g++;for(var _=(b-E)*h+1>>>0,A=new Uint8Array(_);E!==b;){for(var T=p[E],v=0,I=_-1;(T!==0||v<w)&&I!==-1;I--,v++)T+=256*A[I]>>>0,A[I]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");w=v,E++}for(var P=_-w;P!==_&&A[P]===0;)P++;for(var S=c.repeat(g);P<_;++P)S+=r.charAt(A[P]);return S}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var w=0,E=0;p[g]===c;)w++,g++;for(var b=(p.length-g)*l+1>>>0,_=new Uint8Array(b);p[g];){var A=t[p.charCodeAt(g)];if(A===255)return;for(var T=0,v=b-1;(A!==0||T<E)&&v!==-1;v--,T++)A+=a*_[v]>>>0,_[v]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");E=T,g++}if(p[g]!==" "){for(var I=b-E;I!==b&&_[I]===0;)I++;for(var P=new Uint8Array(w+(b-I)),S=w;I!==b;)P[S++]=_[I++];return P}}}function f(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:d,decode:f}}var m1=y1,w1=m1;const yu=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},b1=r=>new TextEncoder().encode(r),v1=r=>new TextDecoder().decode(r);class E1{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class _1{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return mu(this,e)}}class I1{constructor(e){this.decoders=e}or(e){return mu(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const mu=(r,e)=>new I1({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});class D1{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new E1(e,t,i),this.decoder=new _1(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const As=({name:r,prefix:e,encode:t,decode:i})=>new D1(r,e,t,i),Ri=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:s}=w1(t,e);return As({prefix:r,name:e,encode:i,decode:n=>yu(s(n))})},S1=(r,e,t,i)=>{const s={};for(let h=0;h<e.length;++h)s[e[h]]=h;let n=r.length;for(;r[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,l=0;for(let h=0;h<n;++h){const u=s[r[h]];if(u===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<t|u,a+=t,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},O1=(r,e,t)=>{const i=e[e.length-1]==="=",s=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,n+=e[s&a>>o];if(o&&(n+=e[s&a<<t-o]),i)for(;n.length*t&7;)n+="=";return n},$e=({name:r,prefix:e,bitsPerChar:t,alphabet:i})=>As({prefix:e,name:r,encode(s){return O1(s,i,t)},decode(s){return S1(s,i,t,r)}}),P1=As({prefix:"\0",name:"identity",encode:r=>v1(r),decode:r=>b1(r)});var $1=Object.freeze({__proto__:null,identity:P1});const A1=$e({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var C1=Object.freeze({__proto__:null,base2:A1});const x1=$e({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var T1=Object.freeze({__proto__:null,base8:x1});const R1=Ri({prefix:"9",name:"base10",alphabet:"0123456789"});var N1=Object.freeze({__proto__:null,base10:R1});const j1=$e({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),B1=$e({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var U1=Object.freeze({__proto__:null,base16:j1,base16upper:B1});const q1=$e({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),F1=$e({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),L1=$e({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),M1=$e({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),k1=$e({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),z1=$e({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),H1=$e({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),V1=$e({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),K1=$e({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var W1=Object.freeze({__proto__:null,base32:q1,base32upper:F1,base32pad:L1,base32padupper:M1,base32hex:k1,base32hexupper:z1,base32hexpad:H1,base32hexpadupper:V1,base32z:K1});const G1=Ri({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Y1=Ri({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var J1=Object.freeze({__proto__:null,base36:G1,base36upper:Y1});const Z1=Ri({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Q1=Ri({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var X1=Object.freeze({__proto__:null,base58btc:Z1,base58flickr:Q1});const e_=$e({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),t_=$e({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),r_=$e({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),i_=$e({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var s_=Object.freeze({__proto__:null,base64:e_,base64pad:t_,base64url:r_,base64urlpad:i_});const wu=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),n_=wu.reduce((r,e,t)=>(r[t]=e,r),[]),o_=wu.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function a_(r){return r.reduce((e,t)=>(e+=n_[t],e),"")}function c_(r){const e=[];for(const t of r){const i=o_[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const l_=As({prefix:"🚀",name:"base256emoji",encode:a_,decode:c_});var h_=Object.freeze({__proto__:null,base256emoji:l_}),u_=bu,Uc=128,d_=-128,p_=Math.pow(2,31);function bu(r,e,t){e=e||[],t=t||0;for(var i=t;r>=p_;)e[t++]=r&255|Uc,r/=128;for(;r&d_;)e[t++]=r&255|Uc,r>>>=7;return e[t]=r|0,bu.bytes=t-i+1,e}var f_=Gn,g_=128,qc=127;function Gn(r,i){var t=0,i=i||0,s=0,n=i,o,a=r.length;do{if(n>=a)throw Gn.bytes=0,new RangeError("Could not decode varint");o=r[n++],t+=s<28?(o&qc)<<s:(o&qc)*Math.pow(2,s),s+=7}while(o>=g_);return Gn.bytes=n-i,t}var y_=Math.pow(2,7),m_=Math.pow(2,14),w_=Math.pow(2,21),b_=Math.pow(2,28),v_=Math.pow(2,35),E_=Math.pow(2,42),__=Math.pow(2,49),I_=Math.pow(2,56),D_=Math.pow(2,63),S_=function(r){return r<y_?1:r<m_?2:r<w_?3:r<b_?4:r<v_?5:r<E_?6:r<__?7:r<I_?8:r<D_?9:10},O_={encode:u_,decode:f_,encodingLength:S_},vu=O_;const Fc=(r,e,t=0)=>(vu.encode(r,e,t),e),Lc=r=>vu.encodingLength(r),Yn=(r,e)=>{const t=e.byteLength,i=Lc(r),s=i+Lc(t),n=new Uint8Array(s+t);return Fc(r,n,0),Fc(t,n,i),n.set(e,s),new P_(r,t,e,n)};class P_{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}}const Eu=({name:r,code:e,encode:t})=>new $_(r,e,t);class $_{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Yn(this.code,t):t.then(i=>Yn(this.code,i))}else throw Error("Unknown type, must be binary type")}}const _u=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),A_=Eu({name:"sha2-256",code:18,encode:_u("SHA-256")}),C_=Eu({name:"sha2-512",code:19,encode:_u("SHA-512")});var x_=Object.freeze({__proto__:null,sha256:A_,sha512:C_});const Iu=0,T_="identity",Du=yu,R_=r=>Yn(Iu,Du(r)),N_={code:Iu,name:T_,encode:Du,digest:R_};var j_=Object.freeze({__proto__:null,identity:N_});new TextEncoder,new TextDecoder;const Mc={...$1,...C1,...T1,...N1,...U1,...W1,...J1,...X1,...s_,...h_};({...x_,...j_});function B_(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}function Su(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const kc=Su("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),un=Su("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);const e=B_(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),U_={utf8:kc,"utf-8":kc,hex:Mc.base16,latin1:un,ascii:un,binary:un,...Mc};function q_(r,e="utf8"){const t=U_[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r,"utf8"):t.decoder.decode(`${t.prefix}${r}`)}var F_=Object.defineProperty,L_=(r,e,t)=>e in r?F_(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,gt=(r,e,t)=>L_(r,typeof e!="symbol"?e+"":e,t);class M_{constructor(e,t){this.core=e,this.logger=t,gt(this,"keychain",new Map),gt(this,"name",ME),gt(this,"version",kE),gt(this,"initialized",!1),gt(this,"storagePrefix",It),gt(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),gt(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),gt(this,"set",async(i,s)=>{this.isInitialized(),this.keychain.set(i,s),await this.persist()}),gt(this,"get",i=>{this.isInitialized();const s=this.keychain.get(i);if(typeof s>"u"){const{message:n}=q("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return s}),gt(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=Ne(t,this.name)}get context(){return Me(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Cn(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?xn(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var k_=Object.defineProperty,z_=(r,e,t)=>e in r?k_(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ie=(r,e,t)=>z_(r,typeof e!="symbol"?e+"":e,t);class H_{constructor(e,t,i){this.core=e,this.logger=t,Ie(this,"name",FE),Ie(this,"keychain"),Ie(this,"randomSessionIdentifier",Mn()),Ie(this,"initialized",!1),Ie(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ie(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),Ie(this,"getClientId",async()=>{this.isInitialized();const s=await this.getClientSeed(),n=ba(s);return uh(n.publicKey)}),Ie(this,"generateKeyPair",()=>{this.isInitialized();const s=Ab();return this.setPrivateKey(s.publicKey,s.privateKey)}),Ie(this,"signJWT",async s=>{this.isInitialized();const n=await this.getClientSeed(),o=ba(n),a=this.randomSessionIdentifier;return await Kg(a,s,LE,o)}),Ie(this,"generateSharedKey",(s,n,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=Cb(a,n);return this.setSymKey(c,o)}),Ie(this,"setSymKey",async(s,n)=>{this.isInitialized();const o=n||Qi(s);return await this.keychain.set(o,s),o}),Ie(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),Ie(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),Ie(this,"encode",async(s,n,o)=>{this.isInitialized();const a=eu(o),c=jt(n);if(ic(a))return Rb(c,o==null?void 0:o.encoding);if(rc(a)){const d=a.senderPublicKey,f=a.receiverPublicKey;s=await this.generateSharedKey(d,f)}const l=this.getSymKey(s),{type:h,senderPublicKey:u}=a;return xb({type:h,symKey:l,message:c,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),Ie(this,"decode",async(s,n,o)=>{this.isInitialized();const a=jb(n,o);if(ic(a)){const c=Nb(n,o==null?void 0:o.encoding);return or(c)}if(rc(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;s=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(s),l=Tb({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return or(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ie(this,"getPayloadType",(s,n=ht)=>{const o=vi({encoded:s,encoding:n});return lr(o.type)}),Ie(this,"getPayloadSenderPublicKey",(s,n=ht)=>{const o=vi({encoded:s,encoding:n});return o.senderPublicKey?Le(o.senderPublicKey,Re):void 0}),this.core=e,this.logger=Ne(t,this.name),this.keychain=i||new M_(this.core,this.logger)}get context(){return Me(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Nc)}catch{e=Mn(),await this.keychain.set(Nc,e)}return q_(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var V_=Object.defineProperty,K_=Object.defineProperties,W_=Object.getOwnPropertyDescriptors,zc=Object.getOwnPropertySymbols,G_=Object.prototype.hasOwnProperty,Y_=Object.prototype.propertyIsEnumerable,Jn=(r,e,t)=>e in r?V_(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,J_=(r,e)=>{for(var t in e||(e={}))G_.call(e,t)&&Jn(r,t,e[t]);if(zc)for(var t of zc(e))Y_.call(e,t)&&Jn(r,t,e[t]);return r},Z_=(r,e)=>K_(r,W_(e)),ke=(r,e,t)=>Jn(r,typeof e!="symbol"?e+"":e,t);class Q_ extends R0{constructor(e,t){super(e,t),this.logger=e,this.core=t,ke(this,"messages",new Map),ke(this,"messagesWithoutClientAck",new Map),ke(this,"name",zE),ke(this,"version",HE),ke(this,"initialized",!1),ke(this,"storagePrefix",It),ke(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const s=await this.getRelayerMessagesWithoutClientAck();typeof s<"u"&&(this.messagesWithoutClientAck=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),ke(this,"set",async(i,s,n)=>{this.isInitialized();const o=Et(s);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(i,a),n===ts.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,Z_(J_({},c),{[o]:s}))}return await this.persist(),o}),ke(this,"get",i=>{this.isInitialized();let s=this.messages.get(i);return typeof s>"u"&&(s={}),s}),ke(this,"getWithoutAck",i=>{this.isInitialized();const s={};for(const n of i){const o=this.messagesWithoutClientAck.get(n)||{};s[n]=Object.values(o)}return s}),ke(this,"has",(i,s)=>{this.isInitialized();const n=this.get(i),o=Et(s);return typeof n[o]<"u"}),ke(this,"ack",async(i,s)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(i);if(typeof n>"u")return;const o=Et(s);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,n),await this.persist()}),ke(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=Ne(e,this.name),this.core=t}get context(){return Me(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Cn(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Cn(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?xn(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?xn(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var X_=Object.defineProperty,eI=Object.defineProperties,tI=Object.getOwnPropertyDescriptors,Hc=Object.getOwnPropertySymbols,rI=Object.prototype.hasOwnProperty,iI=Object.prototype.propertyIsEnumerable,Zn=(r,e,t)=>e in r?X_(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,zi=(r,e)=>{for(var t in e||(e={}))rI.call(e,t)&&Zn(r,t,e[t]);if(Hc)for(var t of Hc(e))iI.call(e,t)&&Zn(r,t,e[t]);return r},dn=(r,e)=>eI(r,tI(e)),ct=(r,e,t)=>Zn(r,typeof e!="symbol"?e+"":e,t);class sI extends N0{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,ct(this,"events",new Ye.EventEmitter),ct(this,"name",VE),ct(this,"queue",new Map),ct(this,"publishTimeout",U.toMiliseconds(U.ONE_MINUTE)),ct(this,"initialPublishTimeout",U.toMiliseconds(U.ONE_SECOND*15)),ct(this,"needsTransportRestart",!1),ct(this,"publish",async(i,s,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:s,opts:n}});const a=(n==null?void 0:n.ttl)||jc,c=as(n),l=(n==null?void 0:n.prompt)||!1,h=(n==null?void 0:n.tag)||0,u=(n==null?void 0:n.id)||sr().toString(),d={topic:i,message:s,opts:{ttl:a,relay:c,prompt:l,tag:h,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},f=`Failed to publish payload, please try again. id:${u} tag:${h}`;try{const p=new Promise(async g=>{const w=({id:b})=>{d.opts.id===b&&(this.removeRequestFromQueue(b),this.relayer.events.removeListener(we.publish,w),g(d))};this.relayer.events.on(we.publish,w);const E=kt(new Promise((b,_)=>{this.rpcPublish({topic:i,message:s,ttl:a,prompt:l,tag:h,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(b).catch(A=>{this.logger.warn(A,A==null?void 0:A.message),_(A)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${h}`);try{await E,this.events.removeListener(we.publish,w)}catch(b){this.queue.set(u,dn(zi({},d),{attempt:1})),this.logger.warn(b,b==null?void 0:b.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:i,message:s,opts:n}}),await kt(p,this.publishTimeout,f)}catch(p){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(p),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw p}finally{this.queue.delete(u)}}),ct(this,"on",(i,s)=>{this.events.on(i,s)}),ct(this,"once",(i,s)=>{this.events.once(i,s)}),ct(this,"off",(i,s)=>{this.events.off(i,s)}),ct(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.relayer=e,this.logger=Ne(t,this.name),this.registerEventListeners()}get context(){return Me(this.logger)}async rpcPublish(e){var t,i,s,n;const{topic:o,message:a,ttl:c=jc,prompt:l,tag:h,id:u,attestation:d,tvf:f}=e,p={method:ci(as().protocol).publish,params:zi({topic:o,message:a,ttl:c,prompt:l,tag:h,attestation:d},f),id:u};Se((t=p.params)==null?void 0:t.prompt)&&((i=p.params)==null||delete i.prompt),Se((s=p.params)==null?void 0:s.tag)&&((n=p.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:p});const g=await this.relayer.request(p);return this.relayer.events.emit(we.publish,e),this.logger.debug("Successfully Published Payload"),g}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const i=e.attempt+1;this.queue.set(t,dn(zi({},e),{attempt:i}));const{topic:s,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish(dn(zi({},e),{topic:s,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(dr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(we.connection_stalled);return}this.checkQueue()}),this.relayer.on(we.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var nI=Object.defineProperty,oI=(r,e,t)=>e in r?nI(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,vr=(r,e,t)=>oI(r,typeof e!="symbol"?e+"":e,t);class aI{constructor(){vr(this,"map",new Map),vr(this,"set",(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),vr(this,"get",e=>this.map.get(e)||[]),vr(this,"exists",(e,t)=>this.get(e).includes(t)),vr(this,"delete",(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const s=i.filter(n=>n!==t);if(!s.length){this.map.delete(e);return}this.map.set(e,s)}),vr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var cI=Object.defineProperty,lI=Object.defineProperties,hI=Object.getOwnPropertyDescriptors,Vc=Object.getOwnPropertySymbols,uI=Object.prototype.hasOwnProperty,dI=Object.prototype.propertyIsEnumerable,Qn=(r,e,t)=>e in r?cI(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ni=(r,e)=>{for(var t in e||(e={}))uI.call(e,t)&&Qn(r,t,e[t]);if(Vc)for(var t of Vc(e))dI.call(e,t)&&Qn(r,t,e[t]);return r},pn=(r,e)=>lI(r,hI(e)),ie=(r,e,t)=>Qn(r,typeof e!="symbol"?e+"":e,t);class pI extends U0{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,ie(this,"subscriptions",new Map),ie(this,"topicMap",new aI),ie(this,"events",new Ye.EventEmitter),ie(this,"name",QE),ie(this,"version",XE),ie(this,"pending",new Map),ie(this,"cached",[]),ie(this,"initialized",!1),ie(this,"storagePrefix",It),ie(this,"subscribeTimeout",U.toMiliseconds(U.ONE_MINUTE)),ie(this,"initialSubscribeTimeout",U.toMiliseconds(U.ONE_SECOND*15)),ie(this,"clientId"),ie(this,"batchSubscribeTopicsLimit",500),ie(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ie(this,"subscribe",async(i,s)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}});try{const n=as(s),o={topic:i,relay:n,transportType:s==null?void 0:s.transportType};this.pending.set(i,o);const a=await this.rpcSubscribe(i,n,s);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),ie(this,"unsubscribe",async(i,s)=>{this.isInitialized(),typeof(s==null?void 0:s.id)<"u"?await this.unsubscribeById(i,s.id,s):await this.unsubscribeByTopic(i,s)}),ie(this,"isSubscribed",i=>new Promise(s=>{s(this.topicMap.topics.includes(i))})),ie(this,"isKnownTopic",i=>new Promise(s=>{s(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(n=>n.topic===i))})),ie(this,"on",(i,s)=>{this.events.on(i,s)}),ie(this,"once",(i,s)=>{this.events.once(i,s)}),ie(this,"off",(i,s)=>{this.events.off(i,s)}),ie(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),ie(this,"start",async()=>{await this.onConnect()}),ie(this,"stop",async()=>{await this.onDisconnect()}),ie(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ie(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(s=>{i.push(s)}),await this.batchSubscribe(i)}),ie(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(dr.pulse,async()=>{await this.checkPending()}),this.events.on(He.created,async i=>{const s=He.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()}),this.events.on(He.deleted,async i=>{const s=He.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()})}),this.relayer=e,this.logger=Ne(t,this.name),this.clientId=""}get context(){return Me(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map(async s=>await this.unsubscribeById(e,s,t)))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const s=as(i);await this.restartToComplete({topic:e,id:t,relay:s}),await this.rpcUnsubscribe(e,t,s);const n=te("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,t,i){var s;(!i||(i==null?void 0:i.transportType)===ae.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:ci(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(s=i==null?void 0:i.internal)==null?void 0:s.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((i==null?void 0:i.transportType)===ae.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(h=>this.logger.warn(h))},U.toMiliseconds(U.ONE_SECOND)),a;const c=new Promise(async h=>{const u=d=>{d.topic===e&&(this.events.removeListener(He.created,u),h(d.id))};this.events.on(He.created,u);try{const d=await kt(new Promise((f,p)=>{this.relayer.request(n).catch(g=>{this.logger.warn(g,g==null?void 0:g.message),p(g)}).then(f)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(He.created,u),h(d)}catch{}}),l=await kt(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return l?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(we.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:ci(t.protocol).batchSubscribe,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await kt(new Promise(s=>{this.relayer.request(i).catch(n=>this.logger.warn(n)).then(s)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(we.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:ci(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let s;try{s=await await kt(new Promise((n,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(we.connection_stalled)}return s}rpcUnsubscribe(e,t,i){const s={method:ci(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,t){this.setSubscription(e,pn(ni({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,ni({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,ni({},t)),this.topicMap.set(t.topic,e),this.events.emit(He.created,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:i}=q("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(He.deleted,pn(ni({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(He.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<t;i++){const s=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(He.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=q("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async t=>pn(ni({},t),{id:await this.getSubscriptionId(t.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(await ym(U.toMiliseconds(U.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return Et(e+await this.getClientId())}}var fI=Object.defineProperty,Kc=Object.getOwnPropertySymbols,gI=Object.prototype.hasOwnProperty,yI=Object.prototype.propertyIsEnumerable,Xn=(r,e,t)=>e in r?fI(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Wc=(r,e)=>{for(var t in e||(e={}))gI.call(e,t)&&Xn(r,t,e[t]);if(Kc)for(var t of Kc(e))yI.call(e,t)&&Xn(r,t,e[t]);return r},Z=(r,e,t)=>Xn(r,typeof e!="symbol"?e+"":e,t);class mI extends j0{constructor(e){super(e),Z(this,"protocol","wc"),Z(this,"version",2),Z(this,"core"),Z(this,"logger"),Z(this,"events",new Ye.EventEmitter),Z(this,"provider"),Z(this,"messages"),Z(this,"subscriber"),Z(this,"publisher"),Z(this,"name",WE),Z(this,"transportExplicitlyClosed",!1),Z(this,"initialized",!1),Z(this,"connectionAttemptInProgress",!1),Z(this,"relayUrl"),Z(this,"projectId"),Z(this,"packageName"),Z(this,"bundleId"),Z(this,"hasExperiencedNetworkDisruption",!1),Z(this,"pingTimeout"),Z(this,"heartBeatTimeout",U.toMiliseconds(U.THIRTY_SECONDS+U.FIVE_SECONDS)),Z(this,"reconnectTimeout"),Z(this,"connectPromise"),Z(this,"reconnectInProgress",!1),Z(this,"requestsInFlight",[]),Z(this,"connectTimeout",U.toMiliseconds(U.ONE_SECOND*15)),Z(this,"request",async t=>{var i,s;this.logger.debug("Publishing Request Payload");const n=t.id||sr().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(i=t.params)==null?void 0:i.topic},"relayer.request - publishing...");const o=`${n}:${((s=t.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(t);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),Z(this,"resetPingTimeout",()=>{ns()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,i,s,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(s=(i=(t=this.provider)==null?void 0:t.connection)==null?void 0:i.socket)==null?void 0:s.terminate)==null||n.call(s)}catch(o){this.logger.warn(o,o==null?void 0:o.message)}},this.heartBeatTimeout))}),Z(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),Z(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(we.connect)}),Z(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Z(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(we.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Z(this,"registerProviderListeners",()=>{this.provider.on(Qe.payload,this.onPayloadHandler),this.provider.on(Qe.connect,this.onConnectHandler),this.provider.on(Qe.disconnect,this.onDisconnectHandler),this.provider.on(Qe.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Ne(e.logger,this.name):xi(Ss({level:e.logger||KE})),this.messages=new Q_(this.logger,e.core),this.subscriber=new pI(this,this.logger),this.publisher=new sI(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||fu,this.projectId=e.projectId,em()?this.packageName=Oa():tm()&&(this.bundleId=Oa()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e==null?void 0:e.message)}}get context(){return Me(this.logger)}get connected(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:ae.relay},ts.outbound)}async subscribe(e,t){var i,s,n;this.isInitialized(),(!(t!=null&&t.transportType)||(t==null?void 0:t.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=t==null?void 0:t.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(s=t==null?void 0:t.internal)==null?void 0:s.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const l=h=>{h.topic===e&&(this.subscriber.off(He.created,l),c())};return await Promise.all([new Promise(h=>{c=h,this.subscriber.on(He.created,l)}),new Promise(async(h,u)=>{a=await this.subscriber.subscribe(e,Wc({internal:{throwOnFailedPublish:o}},t)).catch(d=>{o&&u(d)})||a,h()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await kt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(t,i)=>{await this.connect(e).then(t).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await fc())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((i,s)=>i.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const i of t)try{await this.onMessageEvent(i)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+(s==null?void 0:s.message))}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:i}=e;if(!t.sessionExists){const s=de(U.FIVE_MINUTES),n={topic:i,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(we.message,e),await this.recordMessageEvent(e,ts.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(i,s)=>{const n=()=>{s(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Qe.disconnect,n),await kt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{s(o)}).finally(()=>{this.provider.off(Qe.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Qe.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Qe.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const s=i;this.logger.warn({},s.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(i=>setTimeout(i,U.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,i,s,n;if(ns())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(s=(i=this.provider)==null?void 0:i.connection)==null?void 0:s.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new it(new jE(om({sdkVersion:Wn,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,t){const{topic:i,message:s}=e;await this.messages.set(i,s,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const s=this.messages.has(t,i);return s&&this.logger.warn(`Ignoring duplicate message: ${i}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),$o(e)){if(!e.method.endsWith(GE))return;const t=e.params,{topic:i,message:s,publishedAt:n,attestation:o}=t.data,a={topic:i,message:s,publishedAt:n,transportType:ae.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Wc({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else $s(e)&&this.events.emit(we.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,ts.inbound),this.events.emit(we.message,e))}async acknowledgePayload(e){const t=Os(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Qe.payload,this.onPayloadHandler),this.provider.off(Qe.connect,this.onConnectHandler),this.provider.off(Qe.disconnect,this.onDisconnectHandler),this.provider.off(Qe.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await fc();$v(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(dr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&xv())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(t){this.logger.warn(t,t==null?void 0:t.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(we.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},U.toMiliseconds(YE)))))}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function wI(){}function Gc(r){if(!r||typeof r!="object")return!1;const e=Object.getPrototypeOf(r);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(r)==="[object Object]":!1}function Yc(r){return Object.getOwnPropertySymbols(r).filter(e=>Object.prototype.propertyIsEnumerable.call(r,e))}function Jc(r){return r==null?r===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(r)}const bI="[object RegExp]",vI="[object String]",EI="[object Number]",_I="[object Boolean]",Zc="[object Arguments]",II="[object Symbol]",DI="[object Date]",SI="[object Map]",OI="[object Set]",PI="[object Array]",$I="[object Function]",AI="[object ArrayBuffer]",fn="[object Object]",CI="[object Error]",xI="[object DataView]",TI="[object Uint8Array]",RI="[object Uint8ClampedArray]",NI="[object Uint16Array]",jI="[object Uint32Array]",BI="[object BigUint64Array]",UI="[object Int8Array]",qI="[object Int16Array]",FI="[object Int32Array]",LI="[object BigInt64Array]",MI="[object Float32Array]",kI="[object Float64Array]";function zI(r,e){return r===e||Number.isNaN(r)&&Number.isNaN(e)}function HI(r,e,t){return li(r,e,void 0,void 0,void 0,void 0,t)}function li(r,e,t,i,s,n,o){const a=o(r,e,t,i,s,n);if(a!==void 0)return a;if(typeof r==typeof e)switch(typeof r){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return r===e;case"number":return r===e||Object.is(r,e);case"function":return r===e;case"object":return fi(r,e,n,o)}return fi(r,e,n,o)}function fi(r,e,t,i){if(Object.is(r,e))return!0;let s=Jc(r),n=Jc(e);if(s===Zc&&(s=fn),n===Zc&&(n=fn),s!==n)return!1;switch(s){case vI:return r.toString()===e.toString();case EI:{const c=r.valueOf(),l=e.valueOf();return zI(c,l)}case _I:case DI:case II:return Object.is(r.valueOf(),e.valueOf());case bI:return r.source===e.source&&r.flags===e.flags;case $I:return r===e}t=t??new Map;const o=t.get(r),a=t.get(e);if(o!=null&&a!=null)return o===e;t.set(r,e),t.set(e,r);try{switch(s){case SI:{if(r.size!==e.size)return!1;for(const[c,l]of r.entries())if(!e.has(c)||!li(l,e.get(c),c,r,e,t,i))return!1;return!0}case OI:{if(r.size!==e.size)return!1;const c=Array.from(r.values()),l=Array.from(e.values());for(let h=0;h<c.length;h++){const u=c[h],d=l.findIndex(f=>li(u,f,void 0,r,e,t,i));if(d===-1)return!1;l.splice(d,1)}return!0}case PI:case TI:case RI:case NI:case jI:case BI:case UI:case qI:case FI:case LI:case MI:case kI:{if(typeof Buffer<"u"&&Buffer.isBuffer(r)!==Buffer.isBuffer(e)||r.length!==e.length)return!1;for(let c=0;c<r.length;c++)if(!li(r[c],e[c],c,r,e,t,i))return!1;return!0}case AI:return r.byteLength!==e.byteLength?!1:fi(new Uint8Array(r),new Uint8Array(e),t,i);case xI:return r.byteLength!==e.byteLength||r.byteOffset!==e.byteOffset?!1:fi(new Uint8Array(r),new Uint8Array(e),t,i);case CI:return r.name===e.name&&r.message===e.message;case fn:{if(!(fi(r.constructor,e.constructor,t,i)||Gc(r)&&Gc(e)))return!1;const c=[...Object.keys(r),...Yc(r)],l=[...Object.keys(e),...Yc(e)];if(c.length!==l.length)return!1;for(let h=0;h<c.length;h++){const u=c[h],d=r[u];if(!Object.hasOwn(e,u))return!1;const f=e[u];if(!li(d,f,u,r,e,t,i))return!1}return!0}default:return!1}}finally{t.delete(r),t.delete(e)}}function VI(r,e){return HI(r,e,wI)}var KI=Object.defineProperty,Qc=Object.getOwnPropertySymbols,WI=Object.prototype.hasOwnProperty,GI=Object.prototype.propertyIsEnumerable,eo=(r,e,t)=>e in r?KI(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Xc=(r,e)=>{for(var t in e||(e={}))WI.call(e,t)&&eo(r,t,e[t]);if(Qc)for(var t of Qc(e))GI.call(e,t)&&eo(r,t,e[t]);return r},Be=(r,e,t)=>eo(r,typeof e!="symbol"?e+"":e,t);class pr extends B0{constructor(e,t,i,s=It,n=void 0){super(e,t,i,s),this.core=e,this.logger=t,this.name=i,Be(this,"map",new Map),Be(this,"version",JE),Be(this,"cached",[]),Be(this,"initialized",!1),Be(this,"getKey"),Be(this,"storagePrefix",It),Be(this,"recentlyDeleted",[]),Be(this,"recentlyDeletedLimit",200),Be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Se(o)?this.map.set(this.getKey(o),o):nv(o)?this.map.set(o.id,o):ov(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Be(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),Be(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Be(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>VI(a[c],o[c]))):this.values)),Be(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Xc(Xc({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Be(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=Ne(t,this.name),this.storagePrefix=s,this.getKey=n}get context(){return Me(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:s}=q("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}const{message:i}=q("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:t}=q("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var YI=Object.defineProperty,JI=(r,e,t)=>e in r?YI(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,W=(r,e,t)=>JI(r,typeof e!="symbol"?e+"":e,t);class ZI{constructor(e,t){this.core=e,this.logger=t,W(this,"name",e1),W(this,"version",t1),W(this,"events",new lo),W(this,"pairings"),W(this,"initialized",!1),W(this,"storagePrefix",It),W(this,"ignoredPayloadTypes",[Rt]),W(this,"registeredMethods",[]),W(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),W(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),W(this,"create",async i=>{this.isInitialized();const s=Mn(),n=await this.core.crypto.setSymKey(s),o=de(U.FIVE_MINUTES),a={protocol:pu},c={topic:n,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},l=nc({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:s,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(tr.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:i==null?void 0:i.transportType}),{topic:n,uri:l}}),W(this,"pair",async i=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[mt.pairing_started]}});this.isValidPair(i,s);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:l}=sc(i.uri);s.props.properties.topic=n,s.addTrace(mt.pairing_uri_validation_success),s.addTrace(mt.pairing_uri_not_expired);let h;if(this.pairings.keys.includes(n)){if(h=this.pairings.get(n),s.addTrace(mt.existing_pairing),h.active)throw s.setError(At.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);s.addTrace(mt.pairing_not_expired)}const u=c||de(U.FIVE_MINUTES),d={topic:n,relay:a,expiry:u,active:!1,methods:l};this.core.expirer.set(n,u),await this.pairings.set(n,d),s.addTrace(mt.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(tr.create,d),s.addTrace(mt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),s.addTrace(mt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(At.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(f){throw s.setError(At.subscribe_pairing_topic_failure),f}return s.addTrace(mt.subscribe_pairing_topic_success),d}),W(this,"activate",async({topic:i})=>{this.isInitialized();const s=de(U.FIVE_MINUTES);this.core.expirer.set(i,s),await this.pairings.update(i,{active:!0,expiry:s})}),W(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:s}=i;if(this.pairings.keys.includes(s)){const n=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Zt();this.events.once(X("pairing_ping",n),({error:l})=>{l?c(l):a()}),await o()}}),W(this,"updateExpiry",async({topic:i,expiry:s})=>{this.isInitialized(),await this.pairings.update(i,{expiry:s})}),W(this,"updateMetadata",async({topic:i,metadata:s})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:s})}),W(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),W(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:s}=i;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",te("USER_DISCONNECTED")),await this.deletePairing(s))}),W(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:s,relay:n,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(s);return nc({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),W(this,"sendRequest",async(i,s,n)=>{const o=zt(s,n),a=await this.core.crypto.encode(i,o),c=ii[s].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),W(this,"sendResult",async(i,s,n)=>{const o=Os(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,l=ii[c].res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)}),W(this,"sendError",async(i,s,n)=>{const o=Ps(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,l=ii[c]?ii[c].res:ii.unregistered_method.res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)}),W(this,"deletePairing",async(i,s)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,te("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),s?Promise.resolve():this.core.expirer.del(i)])}),W(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(s=>Lt(s.expiry));await Promise.all(i.map(s=>this.deletePairing(s.topic)))}),W(this,"onRelayEventRequest",async i=>{const{topic:s,payload:n}=i;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(s,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(s,n);default:return await this.onUnknownRpcMethodRequest(s,n)}}),W(this,"onRelayEventResponse",async i=>{const{topic:s,payload:n}=i,o=(await this.core.history.get(s,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(s,n);default:return this.onUnknownRpcMethodResponse(o)}}),W(this,"onPairingPingRequest",async(i,s)=>{const{id:n}=s;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(tr.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),W(this,"onPairingPingResponse",(i,s)=>{const{id:n}=s;setTimeout(()=>{bt(s)?this.events.emit(X("pairing_ping",n),{}):tt(s)&&this.events.emit(X("pairing_ping",n),{error:s.error})},500)}),W(this,"onPairingDeleteRequest",async(i,s)=>{const{id:n}=s;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(tr.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),W(this,"onUnknownRpcMethodRequest",async(i,s)=>{const{id:n,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=te("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,i,a),this.logger.error(a)}catch(a){await this.sendError(n,i,a),this.logger.error(a)}}),W(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(te("WC_METHOD_UNSUPPORTED",i))}),W(this,"isValidPair",(i,s)=>{var n;if(!qe(i)){const{message:a}=q("MISSING_OR_INVALID",`pair() params: ${i}`);throw s.setError(At.malformed_pairing_uri),new Error(a)}if(!sv(i.uri)){const{message:a}=q("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw s.setError(At.malformed_pairing_uri),new Error(a)}const o=sc(i==null?void 0:i.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=q("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(At.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=q("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(At.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&U.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){s.setError(At.pairing_expired);const{message:a}=q("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),W(this,"isValidPing",async i=>{if(!qe(i)){const{message:n}=q("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),W(this,"isValidDisconnect",async i=>{if(!qe(i)){const{message:n}=q("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),W(this,"isValidPairingTopic",async i=>{if(!ue(i,!1)){const{message:s}=q("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(s)}if(!this.pairings.keys.includes(i)){const{message:s}=q("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(s)}if(Lt(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:s}=q("EXPIRED",`pairing topic: ${i}`);throw new Error(s)}}),this.core=e,this.logger=Ne(t,this.name),this.pairings=new pr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Me(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(we.message,async e=>{const{topic:t,message:i,transportType:s}=e;if(this.pairings.keys.includes(t)&&s!==ae.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const n=await this.core.crypto.decode(t,i);$o(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):$s(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id)),await this.core.relayer.messages.ack(t,i)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(et.expired,async e=>{const{topic:t}=Eh(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(tr.expire,{topic:t}))})}}var QI=Object.defineProperty,XI=(r,e,t)=>e in r?QI(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,De=(r,e,t)=>XI(r,typeof e!="symbol"?e+"":e,t);class e2 extends T0{constructor(e,t){super(e,t),this.core=e,this.logger=t,De(this,"records",new Map),De(this,"events",new Ye.EventEmitter),De(this,"name",r1),De(this,"version",i1),De(this,"cached",[]),De(this,"initialized",!1),De(this,"storagePrefix",It),De(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),De(this,"set",(i,s,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:s,chainId:n}),this.records.has(s.id))return;const o={id:s.id,topic:i,request:{method:s.method,params:s.params||null},chainId:n,expiry:de(U.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(ot.created,o)}),De(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const s=await this.getRecord(i.id);typeof s.response>"u"&&(s.response=tt(i)?{error:i.error}:{result:i.result},this.records.set(s.id,s),this.persist(),this.events.emit(ot.updated,s))}),De(this,"get",async(i,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:s}),await this.getRecord(s))),De(this,"delete",(i,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(n=>{if(n.topic===i){if(typeof s<"u"&&n.id!==s)return;this.records.delete(n.id),this.events.emit(ot.deleted,n)}}),this.persist()}),De(this,"exists",async(i,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===i:!1)),De(this,"on",(i,s)=>{this.events.on(i,s)}),De(this,"once",(i,s)=>{this.events.once(i,s)}),De(this,"off",(i,s)=>{this.events.off(i,s)}),De(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=Ne(t,this.name)}get context(){return Me(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:zt(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:i}=q("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(ot.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=q("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(ot.created,e=>{const t=ot.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(ot.updated,e=>{const t=ot.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(ot.deleted,e=>{const t=ot.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(dr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{U.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(ot.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var t2=Object.defineProperty,r2=(r,e,t)=>e in r?t2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ce=(r,e,t)=>r2(r,typeof e!="symbol"?e+"":e,t);class i2 extends q0{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ce(this,"expirations",new Map),Ce(this,"events",new Ye.EventEmitter),Ce(this,"name",s1),Ce(this,"version",n1),Ce(this,"cached",[]),Ce(this,"initialized",!1),Ce(this,"storagePrefix",It),Ce(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ce(this,"has",i=>{try{const s=this.formatTarget(i);return typeof this.getExpiration(s)<"u"}catch{return!1}}),Ce(this,"set",(i,s)=>{this.isInitialized();const n=this.formatTarget(i),o={target:n,expiry:s};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(et.created,{target:n,expiration:o})}),Ce(this,"get",i=>{this.isInitialized();const s=this.formatTarget(i);return this.getExpiration(s)}),Ce(this,"del",i=>{if(this.isInitialized(),this.has(i)){const s=this.formatTarget(i),n=this.getExpiration(s);this.expirations.delete(s),this.events.emit(et.deleted,{target:s,expiration:n})}}),Ce(this,"on",(i,s)=>{this.events.on(i,s)}),Ce(this,"once",(i,s)=>{this.events.once(i,s)}),Ce(this,"off",(i,s)=>{this.events.off(i,s)}),Ce(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=Ne(t,this.name)}get context(){return Me(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return am(e);if(typeof e=="number")return cm(e);const{message:t}=q("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(et.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=q("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:i}=q("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;U.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(et.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(dr.pulse,()=>this.checkExpirations()),this.events.on(et.created,e=>{const t=et.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(et.expired,e=>{const t=et.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(et.deleted,e=>{const t=et.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var s2=Object.defineProperty,n2=(r,e,t)=>e in r?s2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,he=(r,e,t)=>n2(r,typeof e!="symbol"?e+"":e,t);class o2 extends F0{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,he(this,"name",o1),he(this,"abortController"),he(this,"isDevEnv"),he(this,"verifyUrlV3",c1),he(this,"storagePrefix",It),he(this,"version",du),he(this,"publicKey"),he(this,"fetchPromise"),he(this,"init",async()=>{var s;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&U.toMiliseconds((s=this.publicKey)==null?void 0:s.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),he(this,"register",async s=>{if(!Wr()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=s,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const l=Nt.getDocument(),h=this.startAbortTimer(U.ONE_SECOND*5),u=await new Promise((d,f)=>{const p=()=>{window.removeEventListener("message",w),l.body.removeChild(g),f("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=l.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const w=E=>{if(E.data&&typeof E.data=="string")try{const b=JSON.parse(E.data);if(b.type==="verify_attestation"){if(An(b.attestation).payload.id!==o)return;clearInterval(h),l.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",w),d(b.attestation===null?"":b.attestation)}}catch(b){this.logger.warn(b)}};l.body.appendChild(g),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(l){this.logger.warn(l)}return""}),he(this,"resolve",async s=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=s;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(An(n).payload.id!==a)return;const l=await this.isValidJwtAttestation(n);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(s==null?void 0:s.verifyUrl);return this.fetchAttestation(o,c)}),he(this,"fetchAttestation",async(s,n)=>{this.logger.debug(`resolving attestation: ${s} from url: ${n}`);const o=this.startAbortTimer(U.ONE_SECOND*5),a=await fetch(`${n}/attestation/${s}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),he(this,"getVerifyUrl",s=>{let n=s||pi;return l1.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${pi}`),n=pi),n}),he(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const s=this.startAbortTimer(U.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(s),await n.json()}catch(s){this.logger.warn(s)}}),he(this,"persistPublicKey",async s=>{this.logger.debug("persisting public key to local storage",s),await this.store.setItem(this.storeKey,s),this.publicKey=s}),he(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),he(this,"isValidJwtAttestation",async s=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(s,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(s,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),he(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),he(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const s=await this.fetchPromise;return this.fetchPromise=void 0,s}),he(this,"validateAttestation",(s,n)=>{const o=Ub(s,n.publicKey),a={hasExpired:U.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Ne(t,this.name),this.abortController=new AbortController,this.isDevEnv=wo(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Me(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),U.toMiliseconds(e))}}var a2=Object.defineProperty,c2=(r,e,t)=>e in r?a2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,el=(r,e,t)=>c2(r,typeof e!="symbol"?e+"":e,t);class l2 extends L0{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,el(this,"context",h1),el(this,"registerDeviceToken",async i=>{const{clientId:s,token:n,notificationType:o,enableEncrypted:a=!1}=i,c=`${u1}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:s,type:o,token:n,always_raw:a})})}),this.logger=Ne(t,this.context)}}var h2=Object.defineProperty,tl=Object.getOwnPropertySymbols,u2=Object.prototype.hasOwnProperty,d2=Object.prototype.propertyIsEnumerable,to=(r,e,t)=>e in r?h2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,oi=(r,e)=>{for(var t in e||(e={}))u2.call(e,t)&&to(r,t,e[t]);if(tl)for(var t of tl(e))d2.call(e,t)&&to(r,t,e[t]);return r},fe=(r,e,t)=>to(r,typeof e!="symbol"?e+"":e,t);class p2 extends M0{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,fe(this,"context",p1),fe(this,"storagePrefix",It),fe(this,"storageVersion",d1),fe(this,"events",new Map),fe(this,"shouldPersist",!1),fe(this,"init",async()=>{if(!wo())try{const s={eventId:$a(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:bh(this.core.relayer.protocol,this.core.relayer.version,Wn)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}}),fe(this,"createEvent",s=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=s,l=$a(),h=this.core.projectId||"",u=Date.now(),d=oi({eventId:l,timestamp:u,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:h,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,d),this.shouldPersist=!0),d}),fe(this,"getEvent",s=>{const{eventId:n,topic:o}=s;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return oi(oi({},a),this.setMethods(a.eventId))}),fe(this,"deleteEvent",s=>{const{eventId:n}=s;this.events.delete(n),this.shouldPersist=!0}),fe(this,"setEventListeners",()=>{this.core.heartbeat.on(dr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{U.fromMiliseconds(Date.now())-U.fromMiliseconds(s.timestamp)>f1&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})}),fe(this,"setMethods",s=>({addTrace:n=>this.addTrace(s,n),setError:n=>this.setError(s,n)})),fe(this,"addTrace",(s,n)=>{const o=this.events.get(s);o&&(o.props.properties.trace.push(n),this.events.set(s,o),this.shouldPersist=!0)}),fe(this,"setError",(s,n)=>{const o=this.events.get(s);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(s,o),this.shouldPersist=!0)}),fe(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),fe(this,"restore",async()=>{try{const s=await this.core.storage.getItem(this.storageKey)||[];if(!s.length)return;s.forEach(n=>{this.events.set(n.eventId,oi(oi({},n),this.setMethods(n.eventId)))})}catch(s){this.logger.warn(s)}}),fe(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const s=[];for(const[n,o]of this.events)o.props.type&&s.push(o);if(s.length!==0)try{if((await this.sendEvent(s)).ok)for(const n of s)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),fe(this,"sendEvent",async s=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${g1}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Wn}${n}`,{method:"POST",body:JSON.stringify(s)})}),fe(this,"getAppDomain",()=>wh().url),this.logger=Ne(t,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var f2=Object.defineProperty,rl=Object.getOwnPropertySymbols,g2=Object.prototype.hasOwnProperty,y2=Object.prototype.propertyIsEnumerable,ro=(r,e,t)=>e in r?f2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,il=(r,e)=>{for(var t in e||(e={}))g2.call(e,t)&&ro(r,t,e[t]);if(rl)for(var t of rl(e))y2.call(e,t)&&ro(r,t,e[t]);return r},oe=(r,e,t)=>ro(r,typeof e!="symbol"?e+"":e,t);let m2=class Ou extends $0{constructor(e){var t;super(e),oe(this,"protocol",uu),oe(this,"version",du),oe(this,"name",Kn),oe(this,"relayUrl"),oe(this,"projectId"),oe(this,"customStoragePrefix"),oe(this,"events",new Ye.EventEmitter),oe(this,"logger"),oe(this,"heartbeat"),oe(this,"relayer"),oe(this,"crypto"),oe(this,"storage"),oe(this,"history"),oe(this,"expirer"),oe(this,"pairing"),oe(this,"verify"),oe(this,"echoClient"),oe(this,"linkModeSupportedApps"),oe(this,"eventClient"),oe(this,"initialized",!1),oe(this,"logChunkController"),oe(this,"on",(a,c)=>this.events.on(a,c)),oe(this,"once",(a,c)=>this.events.once(a,c)),oe(this,"off",(a,c)=>this.events.off(a,c)),oe(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),oe(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const h={topic:a,message:c,publishedAt:Date.now(),transportType:ae.link_mode};this.relayer.onLinkMessageEvent(h,{sessionExists:l})});const i=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(i)try{return this.customStoragePrefix=i.customStoragePrefix,this.logger=i.logger,this.heartbeat=i.heartbeat,this.crypto=i.crypto,this.history=i.history,this.expirer=i.expirer,this.storage=i.storage,this.relayer=i.relayer,this.pairing=i.pairing,this.verify=i.verify,this.echoClient=i.echoClient,this.linkModeSupportedApps=i.linkModeSupportedApps,this.eventClient=i.eventClient,this.initialized=i.initialized,this.logChunkController=i.logChunkController,i}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||fu,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const s=Ss({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:UE.logger,name:Kn}),{logger:n,chunkLoggerController:o}=S0({opts:s,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Ne(n,this.name),this.heartbeat=new Rv,this.crypto=new H_(this,this.logger,e==null?void 0:e.keychain),this.history=new e2(this,this.logger),this.expirer=new i2(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new c0(il(il({},qE),e==null?void 0:e.storageOptions)),this.relayer=new mI({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new ZI(this,this.logger),this.verify=new o2(this,this.logger,this.storage),this.echoClient=new l2(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new p2(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new Ou(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(ZE,i),t}get context(){return Me(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Bc,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(Bc)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,i=`${t}_count`;return globalThis[i]=(globalThis[i]||0)+1,globalThis[i]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[i]} times.`),globalThis[t]}catch(t){console.warn("Failed to get global WalletConnect core",t);return}}setGlobalCore(e){var t;try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${((t=e.opts)==null?void 0:t.customStoragePrefix)||""}`;globalThis[i]=e}catch(i){console.warn("Failed to set global WalletConnect core",i)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&BE.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const w2=m2,Pu="wc",$u=2,Au="client",Ao=`${Pu}@${$u}:${Au}:`,gn={name:Au,logger:"error"},sl="WALLETCONNECT_DEEPLINK_CHOICE",b2="proposal",nl="Proposal expired",v2="session",Er=U.SEVEN_DAYS,E2="engine",ge={wc_sessionPropose:{req:{ttl:U.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1104},res:{ttl:U.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1106},res:{ttl:U.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:U.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:U.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1112},res:{ttl:U.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1114},res:{ttl:U.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:U.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:U.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1119}}},yn={min:U.FIVE_MINUTES,max:U.SEVEN_DAYS},yt={idle:"IDLE",active:"ACTIVE"},ol={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},_2="request",I2=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],D2="wc",S2="auth",O2="authKeys",P2="pairingTopics",$2="requests",Cs=`${D2}@${1.5}:${S2}:`,rs=`${Cs}:PUB_KEY`;var A2=Object.defineProperty,C2=Object.defineProperties,x2=Object.getOwnPropertyDescriptors,al=Object.getOwnPropertySymbols,T2=Object.prototype.hasOwnProperty,R2=Object.prototype.propertyIsEnumerable,io=(r,e,t)=>e in r?A2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,se=(r,e)=>{for(var t in e||(e={}))T2.call(e,t)&&io(r,t,e[t]);if(al)for(var t of al(e))R2.call(e,t)&&io(r,t,e[t]);return r},Te=(r,e)=>C2(r,x2(e)),R=(r,e,t)=>io(r,typeof e!="symbol"?e+"":e,t);class N2 extends V0{constructor(e){super(e),R(this,"name",E2),R(this,"events",new lo),R(this,"initialized",!1),R(this,"requestQueue",{state:yt.idle,queue:[]}),R(this,"sessionRequestQueue",{state:yt.idle,queue:[]}),R(this,"requestQueueDelay",U.ONE_SECOND),R(this,"expectedPairingMethodMap",new Map),R(this,"recentlyDeletedMap",new Map),R(this,"recentlyDeletedLimit",200),R(this,"relayMessageCache",[]),R(this,"pendingSessions",new Map),R(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(ge)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},U.toMiliseconds(this.requestQueueDelay)))}),R(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Te(se({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(i),i.optionalNamespaces=Xb(i.requiredNamespaces,i.optionalNamespaces),i.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=i;let h=s,u,d=!1;try{if(h){const v=this.client.core.pairing.pairings.get(h);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=v.active}}catch(v){throw this.client.logger.error(`connect() -> pairing.get(${h}) failed`),v}if(!h||!d){const{topic:v,uri:I}=await this.client.core.pairing.create();h=v,u=I}if(!h){const{message:v}=q("NO_MATCHING_KEY",`connect() pairing topic: ${h}`);throw new Error(v)}const f=await this.client.core.crypto.generateKeyPair(),p=ge.wc_sessionPropose.req.ttl||U.FIVE_MINUTES,g=de(p),w=Te(se(se({requiredNamespaces:n,optionalNamespaces:o,relays:l??[{protocol:pu}],proposer:{publicKey:f,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:h},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:wt()}),E=X("session_connect",w.id),{reject:b,resolve:_,done:A}=Zt(p,nl),T=({id:v})=>{v===w.id&&(this.client.events.off("proposal_expire",T),this.pendingSessions.delete(w.id),this.events.emit(E,{error:{message:nl,code:0}}))};return this.client.events.on("proposal_expire",T),this.events.once(E,({error:v,session:I})=>{this.client.events.off("proposal_expire",T),v?b(v):I&&_(I)}),await this.sendRequest({topic:h,method:"wc_sessionPropose",params:w,throwOnFailedPublish:!0,clientRpcId:w.id}),await this.setProposal(w.id,w),{uri:u,approval:A}}),R(this,"pair",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(i){throw this.client.logger.error("pair() failed"),i}}),R(this,"approve",async t=>{var i,s,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=t==null?void 0:t.id)==null?void 0:i.toString(),trace:[at.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(S){throw o.setError(Yt.no_internet_connection),S}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(S){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),o.setError(Yt.proposal_not_found),S}try{await this.isValidApprove(t)}catch(S){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Yt.session_approve_namespace_validation_failure),S}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:h,scopedProperties:u,sessionConfig:d}=t,f=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:p,proposer:g,requiredNamespaces:w,optionalNamespaces:E}=f;let b=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:p});b||(b=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:at.session_approve_started,properties:{topic:p,trace:[at.session_approve_started,at.session_namespaces_validation_success]}}));const _=await this.client.core.crypto.generateKeyPair(),A=g.publicKey,T=await this.client.core.crypto.generateSharedKey(_,A),v=se(se(se({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:_,metadata:this.client.metadata},expiry:de(Er)},h&&{sessionProperties:h}),u&&{scopedProperties:u}),d&&{sessionConfig:d}),I=ae.relay;b.addTrace(at.subscribing_session_topic);try{await this.client.core.relayer.subscribe(T,{transportType:I})}catch(S){throw b.setError(Yt.subscribe_session_topic_failure),S}b.addTrace(at.subscribe_session_topic_success);const P=Te(se({},v),{topic:T,requiredNamespaces:w,optionalNamespaces:E,pairingTopic:p,acknowledged:!1,self:v.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:_,transportType:ae.relay});await this.client.session.set(T,P),b.addTrace(at.store_session);try{b.addTrace(at.publishing_session_settle),await this.sendRequest({topic:T,method:"wc_sessionSettle",params:v,throwOnFailedPublish:!0}).catch(S=>{throw b==null||b.setError(Yt.session_settle_publish_failure),S}),b.addTrace(at.session_settle_publish_success),b.addTrace(at.publishing_session_approve),await this.sendResult({id:a,topic:p,result:{relay:{protocol:c??"irn"},responderPublicKey:_},throwOnFailedPublish:!0}).catch(S=>{throw b==null||b.setError(Yt.session_approve_publish_failure),S}),b.addTrace(at.session_approve_publish_success)}catch(S){throw this.client.logger.error(S),this.client.session.delete(T,te("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(T),S}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:g.metadata}),await this.client.proposal.delete(a,te("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:p}),await this.setExpiry(T,de(Er)),{topic:T,acknowledged:()=>Promise.resolve(this.client.session.get(T))}}),R(this,"reject",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(t)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:s}=t;let n;try{n=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}n&&(await this.sendError({id:i,topic:n,error:s,rpcOpts:ge.wc_sessionPropose.reject}),await this.client.proposal.delete(i,te("USER_DISCONNECTED")))}),R(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(u){throw this.client.logger.error("update() -> isValidUpdate() failed"),u}const{topic:i,namespaces:s}=t,{done:n,resolve:o,reject:a}=Zt(),c=wt(),l=sr().toString(),h=this.client.session.get(i).namespaces;return this.events.once(X("session_update",c),({error:u})=>{u?a(u):o()}),await this.client.session.update(i,{namespaces:s}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(u=>{this.client.logger.error(u),this.client.session.update(i,{namespaces:h}),a(u)}),{acknowledged:n}}),R(this,"extend",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=t,s=wt(),{done:n,resolve:o,reject:a}=Zt();return this.events.once(X("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,de(Er)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),R(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(E){throw this.client.logger.error("request() -> isValidRequest() failed"),E}const{chainId:i,request:s,topic:n,expiry:o=ge.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);(a==null?void 0:a.transportType)===ae.relay&&await this.confirmOnlineStateOrThrow();const c=wt(),l=sr().toString(),{done:h,resolve:u,reject:d}=Zt(o,"Request expired. Please try again.");this.events.once(X("session_request",c),({error:E,result:b})=>{E?d(E):u(b)});const f="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:n,method:f,params:{request:Te(se({},s),{expiryTimestamp:de(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(E=>d(E)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),await h();const g={request:Te(se({},s),{expiryTimestamp:de(o)}),chainId:i},w=this.shouldSetTVF(f,g);return await Promise.all([new Promise(async E=>{await this.sendRequest(se({clientRpcId:c,relayRpcId:l,topic:n,method:f,params:g,expiry:o,throwOnFailedPublish:!0},w&&{tvf:this.getTVFParams(c,g)})).catch(b=>d(b)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),E()}),new Promise(async E=>{var b;if(!((b=a.sessionConfig)!=null&&b.disableDeepLink)){const _=await dm(this.client.core.storage,sl);await lm({id:c,topic:n,wcDeepLink:_})}E()}),h()]).then(E=>E[2])}),R(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:i,response:s}=t,{id:n}=s,o=this.client.session.get(i);o.transportType===ae.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);bt(s)?await this.sendResult({id:n,topic:i,result:s.result,throwOnFailedPublish:!0,appLink:a}):tt(s)&&await this.sendError({id:n,topic:i,error:s.error,appLink:a}),this.cleanupAfterResponse(t)}),R(this,"ping",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:i}=t;if(this.client.session.keys.includes(i)){const s=wt(),n=sr().toString(),{done:o,resolve:a,reject:c}=Zt();this.events.once(X("session_ping",s),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),R(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:i,event:s,chainId:n}=t,o=sr().toString(),a=wt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:s,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),R(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:i}=t;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:te("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:s}=q("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(s)}}),R(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(i=>rv(i,t)))),R(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),R(this,"authenticate",async(t,i)=>{var s;this.isInitialized(),this.isValidAuthenticate(t);const n=i&&this.client.core.linkModeSupportedApps.includes(i)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),o=n?ae.link_mode:ae.relay;o===ae.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:h,nonce:u,type:d,exp:f,nbf:p,methods:g=[],expiry:w}=t,E=[...t.resources||[]],{topic:b,uri:_}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:b,uri:_}});const A=await this.client.core.crypto.generateKeyPair(),T=Qi(A);if(await Promise.all([this.client.auth.authKeys.set(rs,{responseTopic:T,publicKey:A}),this.client.auth.pairingTopics.set(T,{topic:T,pairingTopic:b})]),await this.client.core.relayer.subscribe(T,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${b}`),g.length>0){const{namespace:O}=qr(a[0]);let x=sw(O,"request",g);Zi(E)&&(x=ow(x,E.pop())),E.push(x)}const v=w&&w>ge.wc_sessionAuthenticate.req.ttl?w:ge.wc_sessionAuthenticate.req.ttl,I={authPayload:{type:d??"caip122",chains:a,statement:c,aud:l,domain:h,version:"1",nonce:u,iat:new Date().toISOString(),exp:f,nbf:p,resources:E},requester:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:de(v)},P={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},S={requiredNamespaces:{},optionalNamespaces:P,relays:[{protocol:"irn"}],pairingTopic:b,proposer:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:de(ge.wc_sessionPropose.req.ttl),id:wt()},{done:j,resolve:N,reject:B}=Zt(v,"Request expired"),k=wt(),$=X("session_connect",S.id),y=X("session_request",k),m=async({error:O,session:x})=>{this.events.off(y,D),O?B(O):x&&N({session:x})},D=async O=>{var x,F,M;if(await this.deletePendingAuthRequest(k,{message:"fulfilled",code:0}),O.error){const Y=te("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return O.error.code===Y.code?void 0:(this.events.off($,m),B(O.error.message))}await this.deleteProposal(S.id),this.events.off($,m);const{cacaos:z,responder:L}=O.result,H=[],V=[];for(const Y of z){await Ba({cacao:Y,projectId:this.client.core.projectId})||(this.client.logger.error(Y,"Signature verification failed"),B(te("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ae}=Y,Ee=Zi(Ae.resources),xe=[Tn(Ae.iss)],Je=os(Ae.iss);if(Ee){const Ze=Ua(Ee),gr=qa(Ee);H.push(...Ze),xe.push(...gr)}for(const Ze of xe)V.push(`${Ze}:${Je}`)}const ne=await this.client.core.crypto.generateSharedKey(A,L.publicKey);let ee;H.length>0&&(ee={topic:ne,acknowledged:!0,self:{publicKey:A,metadata:this.client.metadata},peer:L,controller:L.publicKey,expiry:de(Er),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:b,namespaces:lc([...new Set(H)],[...new Set(V)]),transportType:o},await this.client.core.relayer.subscribe(ne,{transportType:o}),await this.client.session.set(ne,ee),b&&await this.client.core.pairing.updateMetadata({topic:b,metadata:L.metadata}),ee=this.client.session.get(ne)),(x=this.client.metadata.redirect)!=null&&x.linkMode&&(F=L.metadata.redirect)!=null&&F.linkMode&&(M=L.metadata.redirect)!=null&&M.universal&&i&&(this.client.core.addLinkModeSupportedApp(L.metadata.redirect.universal),this.client.session.update(ne,{transportType:ae.link_mode})),N({auths:z,session:ee})};this.events.once($,m),this.events.once(y,D);let C;try{if(n){const O=zt("wc_sessionAuthenticate",I,k);this.client.core.history.set(b,O);const x=await this.client.core.crypto.encode("",O,{type:Ci,encoding:Mt});C=Li(i,b,x)}else await Promise.all([this.sendRequest({topic:b,method:"wc_sessionAuthenticate",params:I,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:k}),this.sendRequest({topic:b,method:"wc_sessionPropose",params:S,expiry:ge.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:S.id})])}catch(O){throw this.events.off($,m),this.events.off(y,D),O}return await this.setProposal(S.id,S),await this.setAuthRequest(k,{request:Te(se({},I),{verifyContext:{}}),pairingTopic:b,transportType:o}),{uri:C??_,response:j}}),R(this,"approveSessionAuthenticate",async t=>{const{id:i,auths:s}=t,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Jt.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw n.setError(si.no_internet_connection),w}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(si.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||ae.relay;a===ae.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),h=Qi(c),u={type:Rt,receiverPublicKey:c,senderPublicKey:l},d=[],f=[];for(const w of s){if(!await Ba({cacao:w,projectId:this.client.core.projectId})){n.setError(si.invalid_cacao);const T=te("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:h,error:T,encodeOpts:u}),new Error(T.message)}n.addTrace(Jt.cacaos_verified);const{p:E}=w,b=Zi(E.resources),_=[Tn(E.iss)],A=os(E.iss);if(b){const T=Ua(b),v=qa(b);d.push(...T),_.push(...v)}for(const T of _)f.push(`${T}:${A}`)}const p=await this.client.core.crypto.generateSharedKey(l,c);n.addTrace(Jt.create_authenticated_session_topic);let g;if((d==null?void 0:d.length)>0){g={topic:p,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:de(Er),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:lc([...new Set(d)],[...new Set(f)]),transportType:a},n.addTrace(Jt.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(w){throw n.setError(si.subscribe_authenticated_session_topic_failure),w}n.addTrace(Jt.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),n.addTrace(Jt.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Jt.publishing_authenticated_session_approve);try{await this.sendResult({topic:h,id:i,result:{cacaos:s,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw n.setError(si.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:g}}),R(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:i,reason:s}=t,n=this.getPendingAuthRequest(i);if(!n)throw new Error(`Could not find pending auth request with id ${i}`);n.transportType===ae.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Qi(o),l={type:Rt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:s,encodeOpts:l,rpcOpts:ge.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,te("USER_DISCONNECTED"))}),R(this,"formatAuthMessage",t=>{this.isInitialized();const{request:i,iss:s}=t;return Ch(i,s)}),R(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const t=this.relayMessageCache.shift();t&&await this.onRelayMessage(t)}catch(t){this.client.logger.error(t)}},50)}),R(this,"cleanupDuplicatePairings",async t=>{if(t.pairingTopic)try{const i=this.client.core.pairing.pairings.get(t.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===t.peer.metadata.url&&n.topic&&n.topic!==i.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),R(this,"deleteSession",async t=>{var i;const{topic:s,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=t,{self:c}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,te("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),n||this.client.core.expirer.del(s),this.client.core.storage.removeItem(sl).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===s&&this.deletePendingSessionRequest(l.id,te("USER_DISCONNECTED"))}),s===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=yt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:s})}),R(this,"deleteProposal",async(t,i)=>{if(i)try{const s=this.client.proposal.get(t),n=this.client.core.eventClient.getEvent({topic:s.pairingTopic});n==null||n.setError(Yt.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,te("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),R(this,"deletePendingSessionRequest",async(t,i,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,i),s?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==t),s&&(this.sessionRequestQueue.state=yt.idle,this.client.events.emit("session_request_expire",{id:t}))}),R(this,"deletePendingAuthRequest",async(t,i,s=!1)=>{await Promise.all([this.client.auth.requests.delete(t,i),s?Promise.resolve():this.client.core.expirer.del(t)])}),R(this,"setExpiry",async(t,i)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,i),await this.client.session.update(t,{expiry:i}))}),R(this,"setProposal",async(t,i)=>{this.client.core.expirer.set(t,de(ge.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,i)}),R(this,"setAuthRequest",async(t,i)=>{const{request:s,pairingTopic:n,transportType:o=ae.relay}=i;this.client.core.expirer.set(t,s.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:t,pairingTopic:n,verifyContext:s.verifyContext,transportType:o})}),R(this,"setPendingSessionRequest",async t=>{const{id:i,topic:s,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||de(ge.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:s,params:n,verifyContext:o})}),R(this,"sendRequest",async t=>{const{topic:i,method:s,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:h,tvf:u}=t,d=zt(s,n,c);let f;const p=!!h;try{const E=p?Mt:ht;f=await this.client.core.crypto.encode(i,d,{encoding:E})}catch(E){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),E}let g;if(I2.includes(s)){const E=Et(JSON.stringify(d)),b=Et(f);g=await this.client.core.verify.register({id:b,decryptedId:E})}const w=ge[s].req;if(w.attestation=g,o&&(w.ttl=o),a&&(w.id=a),this.client.core.history.set(i,d),p){const E=Li(h,i,f);await global.Linking.openURL(E,this.client.name)}else{const E=ge[s].req;o&&(E.ttl=o),a&&(E.id=a),E.tvf=Te(se({},u),{correlationId:d.id}),l?(E.internal=Te(se({},E.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,f,E)):this.client.core.relayer.publish(i,f,E).catch(b=>this.client.logger.error(b))}return d.id}),R(this,"sendResult",async t=>{const{id:i,topic:s,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,l=Os(i,n);let h;const u=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=u?Mt:ht;h=await this.client.core.crypto.encode(s,l,Te(se({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),p}let d,f;try{d=await this.client.core.history.get(s,i);const p=d.request;try{this.shouldSetTVF(p.method,p.params)&&(f=this.getTVFParams(i,p.params,n))}catch(g){this.client.logger.warn("sendResult() -> getTVFParams() failed",g)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${i}) failed`),p}if(u){const p=Li(c,s,h);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,g=ge[p].res;g.tvf=Te(se({},f),{correlationId:i}),o?(g.internal=Te(se({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,h,g)):this.client.core.relayer.publish(s,h,g).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(l)}),R(this,"sendError",async t=>{const{id:i,topic:s,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,l=Ps(i,n);let h;const u=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=u?Mt:ht;h=await this.client.core.crypto.encode(s,l,Te(se({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),f}let d;try{d=await this.client.core.history.get(s,i)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${s}, ${i}) failed`),f}if(u){const f=Li(c,s,h);await global.Linking.openURL(f,this.client.name)}else{const f=d.request.method,p=a||ge[f].res;this.client.core.relayer.publish(s,h,p)}await this.client.core.history.resolve(l)}),R(this,"cleanup",async()=>{const t=[],i=[];this.client.session.getAll().forEach(s=>{let n=!1;Lt(s.expiry)&&(n=!0),this.client.core.crypto.keychain.has(s.topic)||(n=!0),n&&t.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{Lt(s.expiryTimestamp)&&i.push(s.id)}),await Promise.all([...t.map(s=>this.deleteSession({topic:s})),...i.map(s=>this.deleteProposal(s))])}),R(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),R(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),R(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===yt.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=yt.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=yt.idle}),R(this,"processRequest",async t=>{const{topic:i,payload:s,attestation:n,transportType:o,encryptedId:a}=t,c=s.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:s,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,s);case"wc_sessionPing":return await this.onSessionPingRequest(i,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:s,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:s,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),R(this,"onRelayEventResponse",async t=>{const{topic:i,payload:s,transportType:n}=t,o=(await this.client.core.history.get(i,s.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,s,n);case"wc_sessionSettle":return this.onSessionSettleResponse(i,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,s);case"wc_sessionExtend":return this.onSessionExtendResponse(i,s);case"wc_sessionPing":return this.onSessionPingResponse(i,s);case"wc_sessionRequest":return this.onSessionRequestResponse(i,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,s);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),R(this,"onRelayEventUnknownPayload",t=>{const{topic:i}=t,{message:s}=q("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),R(this,"shouldIgnorePairingRequest",t=>{const{topic:i,requestMethod:s}=t,n=this.expectedPairingMethodMap.get(i);return!n||n.includes(s)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),R(this,"onSessionProposeRequest",async t=>{const{topic:i,payload:s,attestation:n,encryptedId:o}=t,{params:a,id:c}=s;try{const l=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(At.proposal_listener_not_found)),this.isValidConnect(se({},s.params));const h=a.expiryTimestamp||de(ge.wc_sessionPropose.req.ttl),u=se({id:c,pairingTopic:i,expiryTimestamp:h},a);await this.setProposal(c,u);const d=await this.getVerifyContext({attestationId:n,hash:Et(JSON.stringify(s)),encryptedId:o,metadata:u.proposer.metadata});l==null||l.addTrace(mt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:u,verifyContext:d})}catch(l){await this.sendError({id:c,topic:i,error:l,rpcOpts:ge.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),R(this,"onSessionProposeResponse",async(t,i,s)=>{const{id:n}=i;if(bt(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const h=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(n,{sessionTopic:h,pairingTopic:t,proposalId:n,publicKey:c});const u=await this.client.core.relayer.subscribe(h,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:t})}else if(tt(i)){await this.client.proposal.delete(n,te("USER_DISCONNECTED"));const o=X("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),R(this,"onSessionSettleRequest",async(t,i)=>{const{id:s,params:n}=i;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:h,scopedProperties:u,sessionConfig:d}=i.params,f=[...this.pendingSessions.values()].find(w=>w.sessionTopic===t);if(!f)return this.client.logger.error(`Pending session not found for topic ${t}`);const p=this.client.proposal.get(f.proposalId),g=Te(se(se(se({topic:t,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:f.pairingTopic,requiredNamespaces:p.requiredNamespaces,optionalNamespaces:p.optionalNamespaces,controller:a.publicKey,self:{publicKey:f.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},h&&{sessionProperties:h}),u&&{scopedProperties:u}),d&&{sessionConfig:d}),{transportType:ae.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:f.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(X("session_connect",f.proposalId),{session:g}),this.pendingSessions.delete(f.proposalId),this.deleteProposal(f.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:i.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:s,topic:t,error:o}),this.client.logger.error(o)}}),R(this,"onSessionSettleResponse",async(t,i)=>{const{id:s}=i;bt(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(X("session_approve",s),{})):tt(i)&&(await this.client.session.delete(t,te("USER_DISCONNECTED")),this.events.emit(X("session_approve",s),{error:i.error}))}),R(this,"onSessionUpdateRequest",async(t,i)=>{const{params:s,id:n}=i;try{const o=`${t}_session_update`,a=ri.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:t,error:te("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(se({topic:t},s));try{ri.set(o,n),await this.client.session.update(t,{namespaces:s.namespaces}),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0})}catch(c){throw ri.delete(o),c}this.client.events.emit("session_update",{id:n,topic:t,params:s})}catch(o){await this.sendError({id:n,topic:t,error:o}),this.client.logger.error(o)}}),R(this,"isRequestOutOfSync",(t,i)=>i.toString().slice(0,-3)<t.toString().slice(0,-3)),R(this,"onSessionUpdateResponse",(t,i)=>{const{id:s}=i,n=X("session_update",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);bt(i)?this.events.emit(X("session_update",s),{}):tt(i)&&this.events.emit(X("session_update",s),{error:i.error})}),R(this,"onSessionExtendRequest",async(t,i)=>{const{id:s}=i;try{this.isValidExtend({topic:t}),await this.setExpiry(t,de(Er)),await this.sendResult({id:s,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:s,topic:t})}catch(n){await this.sendError({id:s,topic:t,error:n}),this.client.logger.error(n)}}),R(this,"onSessionExtendResponse",(t,i)=>{const{id:s}=i,n=X("session_extend",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);bt(i)?this.events.emit(X("session_extend",s),{}):tt(i)&&this.events.emit(X("session_extend",s),{error:i.error})}),R(this,"onSessionPingRequest",async(t,i)=>{const{id:s}=i;try{this.isValidPing({topic:t}),await this.sendResult({id:s,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:t})}catch(n){await this.sendError({id:s,topic:t,error:n}),this.client.logger.error(n)}}),R(this,"onSessionPingResponse",(t,i)=>{const{id:s}=i,n=X("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);bt(i)?this.events.emit(X("session_ping",s),{}):tt(i)&&this.events.emit(X("session_ping",s),{error:i.error})},500)}),R(this,"onSessionDeleteRequest",async(t,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:t,reason:i.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(we.publish,async()=>{n(await this.deleteSession({topic:t,id:s}))})}),this.sendResult({id:s,topic:t,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:te("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),R(this,"onSessionRequest",async t=>{var i,s,n;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:h}=t,{id:u,params:d}=a;try{await this.isValidRequest(se({topic:o},d));const f=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:Et(JSON.stringify(zt("wc_sessionRequest",d,u))),encryptedId:l,metadata:f.peer.metadata,transportType:h}),g={id:u,topic:o,params:d,verifyContext:p};await this.setPendingSessionRequest(g),h===ae.link_mode&&(i=f.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((s=f.peer.metadata.redirect)==null?void 0:s.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(f){await this.sendError({id:u,topic:o,error:f}),this.client.logger.error(f)}}),R(this,"onSessionRequestResponse",(t,i)=>{const{id:s}=i,n=X("session_request",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);bt(i)?this.events.emit(X("session_request",s),{result:i.result}):tt(i)&&this.events.emit(X("session_request",s),{error:i.error})}),R(this,"onSessionEventRequest",async(t,i)=>{const{id:s,params:n}=i;try{const o=`${t}_session_event_${n.event.name}`,a=ri.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(se({topic:t},n)),this.client.events.emit("session_event",{id:s,topic:t,params:n}),ri.set(o,s)}catch(o){await this.sendError({id:s,topic:t,error:o}),this.client.logger.error(o)}}),R(this,"onSessionAuthenticateResponse",(t,i)=>{const{id:s}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:i}),bt(i)?this.events.emit(X("session_request",s),{result:i.result}):tt(i)&&this.events.emit(X("session_request",s),{error:i.error})}),R(this,"onSessionAuthenticateRequest",async t=>{var i;const{topic:s,payload:n,attestation:o,encryptedId:a,transportType:c}=t;try{const{requester:l,authPayload:h,expiryTimestamp:u}=n.params,d=await this.getVerifyContext({attestationId:o,hash:Et(JSON.stringify(n)),encryptedId:a,metadata:l.metadata,transportType:c}),f={requester:l,pairingTopic:s,id:n.id,authPayload:h,verifyContext:d,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:f,pairingTopic:s,transportType:c}),c===ae.link_mode&&(i=l.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:n.params,id:n.id,verifyContext:d})}catch(l){this.client.logger.error(l);const h=n.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,c),f={type:Rt,receiverPublicKey:h,senderPublicKey:u};await this.sendError({id:n.id,topic:s,error:l,encodeOpts:f,rpcOpts:ge.wc_sessionAuthenticate.autoReject,appLink:d})}}),R(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),R(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=yt.idle,this.processSessionRequestQueue()},U.toMiliseconds(this.requestQueueDelay))}),R(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:i})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(n=>n.topic===t&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=X("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(X("session_request",n.request.id),{error:i})})}),R(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===yt.active){this.client.logger.info("session request queue is already active.");return}const t=this.sessionRequestQueue.queue[0];if(!t){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=yt.active,this.emitSessionRequest(t)}catch(i){this.client.logger.error(i)}}),R(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),R(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const i=this.client.proposal.getAll().find(s=>s.pairingTopic===t.topic);i&&this.onSessionProposeRequest({topic:t.topic,payload:zt("wc_sessionPropose",Te(se({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id)})}),R(this,"isValidConnect",async t=>{if(!qe(t)){const{message:l}=q("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(l)}const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=t;if(Se(i)||await this.isValidPairingTopic(i),!fv(c)){const{message:l}=q("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!Se(s)&&Vt(s)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(s,"requiredNamespaces")}if(!Se(n)&&Vt(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Se(o)||this.validateSessionProps(o,"sessionProperties"),!Se(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(s||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(h=>l.includes(h)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),R(this,"validateNamespaces",(t,i)=>{const s=pv(t,"connect()",i);if(s)throw new Error(s.message)}),R(this,"isValidApprove",async t=>{if(!qe(t))throw new Error(q("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:i,namespaces:s,relayProtocol:n,sessionProperties:o,scopedProperties:a}=t;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),l=nn(s,"approve()");if(l)throw new Error(l.message);const h=dc(c.requiredNamespaces,s,"approve()");if(h)throw new Error(h.message);if(!ue(n,!0)){const{message:u}=q("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}if(Se(o)||this.validateSessionProps(o,"sessionProperties"),!Se(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(s));if(!Object.keys(a).every(d=>u.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),R(this,"isValidReject",async t=>{if(!qe(t)){const{message:n}=q("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:i,reason:s}=t;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!yv(s)){const{message:n}=q("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(n)}}),R(this,"isValidSessionSettleRequest",t=>{if(!qe(t)){const{message:l}=q("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(l)}const{relay:i,controller:s,namespaces:n,expiry:o}=t;if(!ru(i)){const{message:l}=q("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=av(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=nn(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Lt(o)){const{message:l}=q("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),R(this,"isValidUpdate",async t=>{if(!qe(t)){const{message:c}=q("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(c)}const{topic:i,namespaces:s}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const n=this.client.session.get(i),o=nn(s,"update()");if(o)throw new Error(o.message);const a=dc(n.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)}),R(this,"isValidExtend",async t=>{if(!qe(t)){const{message:s}=q("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(s)}const{topic:i}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),R(this,"isValidRequest",async t=>{if(!qe(t)){const{message:c}=q("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(c)}const{topic:i,request:s,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!uc(a,n)){const{message:c}=q("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!mv(s)){const{message:c}=q("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!vv(a,n,s.method)){const{message:c}=q("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}if(o&&!Dv(o,yn)){const{message:c}=q("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${yn.min} and ${yn.max}`);throw new Error(c)}}),R(this,"isValidRespond",async t=>{var i;if(!qe(t)){const{message:o}=q("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(o)}const{topic:s,response:n}=t;try{await this.isValidSessionTopic(s)}catch(o){throw(i=t==null?void 0:t.response)!=null&&i.id&&this.cleanupAfterResponse(t),o}if(!wv(n)){const{message:o}=q("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),R(this,"isValidPing",async t=>{if(!qe(t)){const{message:s}=q("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(s)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),R(this,"isValidEmit",async t=>{if(!qe(t)){const{message:a}=q("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:i,event:s,chainId:n}=t;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!uc(o,n)){const{message:a}=q("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!bv(s)){const{message:a}=q("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!Ev(o,n,s.name)){const{message:a}=q("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}}),R(this,"isValidDisconnect",async t=>{if(!qe(t)){const{message:s}=q("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(s)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),R(this,"isValidAuthenticate",t=>{const{chains:i,uri:s,domain:n,nonce:o}=t;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!ue(s,!1))throw new Error("uri is required parameter");if(!ue(n,!1))throw new Error("domain is required parameter");if(!ue(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>qr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=qr(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),R(this,"getVerifyContext",async t=>{const{attestationId:i,hash:s,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||pi,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ae.link_mode){const h=this.getAppLinkIfEnabled(o,a);return c.verified.validation=h&&new URL(h).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:i,hash:s,encryptedId:n,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),R(this,"validateSessionProps",(t,i)=>{Object.values(t).forEach((s,n)=>{if(s==null){const{message:o}=q("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${s} for key ${Object.keys(t)[n]}`);throw new Error(o)}})}),R(this,"getPendingAuthRequest",t=>{const i=this.client.auth.requests.get(t);return typeof i=="object"?i:void 0}),R(this,"addToRecentlyDeleted",(t,i)=>{if(this.recentlyDeletedMap.set(t,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(s++>=n)break;this.recentlyDeletedMap.delete(o)}}}),R(this,"checkRecentlyDeleted",t=>{const i=this.recentlyDeletedMap.get(t);if(i){const{message:s}=q("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${t}`);throw new Error(s)}}),R(this,"isLinkModeEnabled",(t,i)=>{var s,n,o,a,c,l,h,u,d;return!t||i!==ae.link_mode?!1:((n=(s=this.client.metadata)==null?void 0:s.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((h=t==null?void 0:t.redirect)==null?void 0:h.universal)!==void 0&&((u=t==null?void 0:t.redirect)==null?void 0:u.universal)!==""&&((d=t==null?void 0:t.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),R(this,"getAppLinkIfEnabled",(t,i)=>{var s;return this.isLinkModeEnabled(t,i)?(s=t==null?void 0:t.redirect)==null?void 0:s.universal:void 0}),R(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const i=Pa(t,"topic")||"",s=decodeURIComponent(Pa(t,"wc_ev")||""),n=this.client.session.keys.includes(i);n&&this.client.session.update(i,{transportType:ae.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:s,sessionExists:n})}),R(this,"registerLinkModeListeners",async()=>{var t;if(wo()||Kt()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const i=global==null?void 0:global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const s=await i.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}),R(this,"shouldSetTVF",(t,i)=>{if(!i||t!=="wc_sessionRequest")return!1;const{request:s}=i;return Object.keys(ol).includes(s.method)}),R(this,"getTVFParams",(t,i,s)=>{var n,o;try{const a=i.request.method,c=this.extractTxHashesFromResult(a,s);return Te(se({correlationId:t,rpcMethods:[a],chainId:i.chainId},this.isValidContractData(i.request.params)&&{contractAddresses:[(o=(n=i.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),R(this,"isValidContractData",t=>{var i;if(!t)return!1;try{const s=(t==null?void 0:t.data)||((i=t==null?void 0:t[0])==null?void 0:i.data);if(!s.startsWith("0x"))return!1;const n=s.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),R(this,"extractTxHashesFromResult",(t,i)=>{try{const s=ol[t];if(typeof i=="string")return[i];const n=i[s.key];if(ut(n))return t==="solana_signAllTransactions"?n.map(o=>Hm(o)):n;if(typeof n=="string")return[n]}catch(s){this.client.logger.warn("Error extracting tx hashes from result",s)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,s]of Object.entries(t))for(const n of s)try{await this.onProviderMessageEvent({topic:i,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(we.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:i,attestation:s,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(rs)?this.client.auth.authKeys.get(rs):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,i,{receiverPublicKey:o,encoding:n===ae.link_mode?Mt:ht});$o(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:s,transportType:n,encryptedId:Et(i)})):$s(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:n}),this.client.core.history.delete(t,a.id)):await this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(t,i)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(et.expired,async e=>{const{topic:t,id:i}=Eh(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,q("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,q("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(tr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(tr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ue(e,!1)){const{message:t}=q("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=q("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Lt(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=q("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!ue(e,!1)){const{message:t}=q("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=q("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Lt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=q("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=q("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ue(e,!1)){const{message:t}=q("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=q("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!gv(e)){const{message:t}=q("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=q("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Lt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=q("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class j2 extends pr{constructor(e,t){super(e,t,b2,Ao),this.core=e,this.logger=t}}let B2=class extends pr{constructor(e,t){super(e,t,v2,Ao),this.core=e,this.logger=t}};class U2 extends pr{constructor(e,t){super(e,t,_2,Ao,i=>i.id),this.core=e,this.logger=t}}class q2 extends pr{constructor(e,t){super(e,t,O2,Cs,()=>rs),this.core=e,this.logger=t}}class F2 extends pr{constructor(e,t){super(e,t,P2,Cs),this.core=e,this.logger=t}}class L2 extends pr{constructor(e,t){super(e,t,$2,Cs,i=>i.id),this.core=e,this.logger=t}}var M2=Object.defineProperty,k2=(r,e,t)=>e in r?M2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,mn=(r,e,t)=>k2(r,typeof e!="symbol"?e+"":e,t);class z2{constructor(e,t){this.core=e,this.logger=t,mn(this,"authKeys"),mn(this,"pairingTopics"),mn(this,"requests"),this.authKeys=new q2(this.core,this.logger),this.pairingTopics=new F2(this.core,this.logger),this.requests=new L2(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var H2=Object.defineProperty,V2=(r,e,t)=>e in r?H2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,G=(r,e,t)=>V2(r,typeof e!="symbol"?e+"":e,t);let K2=class Cu extends H0{constructor(e){super(e),G(this,"protocol",Pu),G(this,"version",$u),G(this,"name",gn.name),G(this,"metadata"),G(this,"core"),G(this,"logger"),G(this,"events",new Ye.EventEmitter),G(this,"engine"),G(this,"session"),G(this,"proposal"),G(this,"pendingRequest"),G(this,"auth"),G(this,"signConfig"),G(this,"on",(i,s)=>this.events.on(i,s)),G(this,"once",(i,s)=>this.events.once(i,s)),G(this,"off",(i,s)=>this.events.off(i,s)),G(this,"removeListener",(i,s)=>this.events.removeListener(i,s)),G(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),G(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"update",async i=>{try{return await this.engine.update(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"request",async i=>{try{return await this.engine.request(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"find",i=>{try{return this.engine.find(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),G(this,"authenticate",async(i,s)=>{try{return await this.engine.authenticate(i,s)}catch(n){throw this.logger.error(n.message),n}}),G(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),this.name=(e==null?void 0:e.name)||gn.name,this.metadata=im(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const t=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:xi(Ss({level:(e==null?void 0:e.logger)||gn.logger}));this.core=(e==null?void 0:e.core)||new w2(e),this.logger=Ne(t,this.name),this.session=new B2(this.core,this.logger),this.proposal=new j2(this.core,this.logger),this.pendingRequest=new U2(this.core,this.logger),this.engine=new N2(this),this.auth=new z2(this.core,this.logger)}static async init(e){const t=new Cu(e);return await t.initialize(),t}get context(){return Me(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},U.toMiliseconds(U.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};var Hi={exports:{}},cl;function W2(){return cl||(cl=1,(function(r,e){var t=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof vt<"u"&&vt,i=(function(){function n(){this.fetch=!1,this.DOMException=t.DOMException}return n.prototype=t,new n})();(function(n){(function(o){var a=typeof n<"u"&&n||typeof self<"u"&&self||typeof vt<"u"&&vt||{},c={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function l(y){return y&&DataView.prototype.isPrototypeOf(y)}if(c.arrayBuffer)var h=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],u=ArrayBuffer.isView||function(y){return y&&h.indexOf(Object.prototype.toString.call(y))>-1};function d(y){if(typeof y!="string"&&(y=String(y)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(y)||y==="")throw new TypeError('Invalid character in header field name: "'+y+'"');return y.toLowerCase()}function f(y){return typeof y!="string"&&(y=String(y)),y}function p(y){var m={next:function(){var D=y.shift();return{done:D===void 0,value:D}}};return c.iterable&&(m[Symbol.iterator]=function(){return m}),m}function g(y){this.map={},y instanceof g?y.forEach(function(m,D){this.append(D,m)},this):Array.isArray(y)?y.forEach(function(m){if(m.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+m.length);this.append(m[0],m[1])},this):y&&Object.getOwnPropertyNames(y).forEach(function(m){this.append(m,y[m])},this)}g.prototype.append=function(y,m){y=d(y),m=f(m);var D=this.map[y];this.map[y]=D?D+", "+m:m},g.prototype.delete=function(y){delete this.map[d(y)]},g.prototype.get=function(y){return y=d(y),this.has(y)?this.map[y]:null},g.prototype.has=function(y){return this.map.hasOwnProperty(d(y))},g.prototype.set=function(y,m){this.map[d(y)]=f(m)},g.prototype.forEach=function(y,m){for(var D in this.map)this.map.hasOwnProperty(D)&&y.call(m,this.map[D],D,this)},g.prototype.keys=function(){var y=[];return this.forEach(function(m,D){y.push(D)}),p(y)},g.prototype.values=function(){var y=[];return this.forEach(function(m){y.push(m)}),p(y)},g.prototype.entries=function(){var y=[];return this.forEach(function(m,D){y.push([D,m])}),p(y)},c.iterable&&(g.prototype[Symbol.iterator]=g.prototype.entries);function w(y){if(!y._noBody){if(y.bodyUsed)return Promise.reject(new TypeError("Already read"));y.bodyUsed=!0}}function E(y){return new Promise(function(m,D){y.onload=function(){m(y.result)},y.onerror=function(){D(y.error)}})}function b(y){var m=new FileReader,D=E(m);return m.readAsArrayBuffer(y),D}function _(y){var m=new FileReader,D=E(m),C=/charset=([A-Za-z0-9_-]+)/.exec(y.type),O=C?C[1]:"utf-8";return m.readAsText(y,O),D}function A(y){for(var m=new Uint8Array(y),D=new Array(m.length),C=0;C<m.length;C++)D[C]=String.fromCharCode(m[C]);return D.join("")}function T(y){if(y.slice)return y.slice(0);var m=new Uint8Array(y.byteLength);return m.set(new Uint8Array(y)),m.buffer}function v(){return this.bodyUsed=!1,this._initBody=function(y){this.bodyUsed=this.bodyUsed,this._bodyInit=y,y?typeof y=="string"?this._bodyText=y:c.blob&&Blob.prototype.isPrototypeOf(y)?this._bodyBlob=y:c.formData&&FormData.prototype.isPrototypeOf(y)?this._bodyFormData=y:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(y)?this._bodyText=y.toString():c.arrayBuffer&&c.blob&&l(y)?(this._bodyArrayBuffer=T(y.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(y)||u(y))?this._bodyArrayBuffer=T(y):this._bodyText=y=Object.prototype.toString.call(y):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof y=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(y)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var y=w(this);if(y)return y;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var y=w(this);return y||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(c.blob)return this.blob().then(b);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var y=w(this);if(y)return y;if(this._bodyBlob)return _(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(A(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},c.formData&&(this.formData=function(){return this.text().then(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var I=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function P(y){var m=y.toUpperCase();return I.indexOf(m)>-1?m:y}function S(y,m){if(!(this instanceof S))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');m=m||{};var D=m.body;if(y instanceof S){if(y.bodyUsed)throw new TypeError("Already read");this.url=y.url,this.credentials=y.credentials,m.headers||(this.headers=new g(y.headers)),this.method=y.method,this.mode=y.mode,this.signal=y.signal,!D&&y._bodyInit!=null&&(D=y._bodyInit,y.bodyUsed=!0)}else this.url=String(y);if(this.credentials=m.credentials||this.credentials||"same-origin",(m.headers||!this.headers)&&(this.headers=new g(m.headers)),this.method=P(m.method||this.method||"GET"),this.mode=m.mode||this.mode||null,this.signal=m.signal||this.signal||(function(){if("AbortController"in a){var x=new AbortController;return x.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&D)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(D),(this.method==="GET"||this.method==="HEAD")&&(m.cache==="no-store"||m.cache==="no-cache")){var C=/([?&])_=[^&]*/;if(C.test(this.url))this.url=this.url.replace(C,"$1_="+new Date().getTime());else{var O=/\?/;this.url+=(O.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}S.prototype.clone=function(){return new S(this,{body:this._bodyInit})};function j(y){var m=new FormData;return y.trim().split("&").forEach(function(D){if(D){var C=D.split("="),O=C.shift().replace(/\+/g," "),x=C.join("=").replace(/\+/g," ");m.append(decodeURIComponent(O),decodeURIComponent(x))}}),m}function N(y){var m=new g,D=y.replace(/\r?\n[\t ]+/g," ");return D.split("\r").map(function(C){return C.indexOf(`
38
- `)===0?C.substr(1,C.length):C}).forEach(function(C){var O=C.split(":"),x=O.shift().trim();if(x){var F=O.join(":").trim();try{m.append(x,F)}catch(M){console.warn("Response "+M.message)}}}),m}v.call(S.prototype);function B(y,m){if(!(this instanceof B))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(m||(m={}),this.type="default",this.status=m.status===void 0?200:m.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=m.statusText===void 0?"":""+m.statusText,this.headers=new g(m.headers),this.url=m.url||"",this._initBody(y)}v.call(B.prototype),B.prototype.clone=function(){return new B(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new g(this.headers),url:this.url})},B.error=function(){var y=new B(null,{status:200,statusText:""});return y.ok=!1,y.status=0,y.type="error",y};var k=[301,302,303,307,308];B.redirect=function(y,m){if(k.indexOf(m)===-1)throw new RangeError("Invalid status code");return new B(null,{status:m,headers:{location:y}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(m,D){this.message=m,this.name=D;var C=Error(m);this.stack=C.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function $(y,m){return new Promise(function(D,C){var O=new S(y,m);if(O.signal&&O.signal.aborted)return C(new o.DOMException("Aborted","AbortError"));var x=new XMLHttpRequest;function F(){x.abort()}x.onload=function(){var L={statusText:x.statusText,headers:N(x.getAllResponseHeaders()||"")};O.url.indexOf("file://")===0&&(x.status<200||x.status>599)?L.status=200:L.status=x.status,L.url="responseURL"in x?x.responseURL:L.headers.get("X-Request-URL");var H="response"in x?x.response:x.responseText;setTimeout(function(){D(new B(H,L))},0)},x.onerror=function(){setTimeout(function(){C(new TypeError("Network request failed"))},0)},x.ontimeout=function(){setTimeout(function(){C(new TypeError("Network request timed out"))},0)},x.onabort=function(){setTimeout(function(){C(new o.DOMException("Aborted","AbortError"))},0)};function M(L){try{return L===""&&a.location.href?a.location.href:L}catch{return L}}if(x.open(O.method,M(O.url),!0),O.credentials==="include"?x.withCredentials=!0:O.credentials==="omit"&&(x.withCredentials=!1),"responseType"in x&&(c.blob?x.responseType="blob":c.arrayBuffer&&(x.responseType="arraybuffer")),m&&typeof m.headers=="object"&&!(m.headers instanceof g||a.Headers&&m.headers instanceof a.Headers)){var z=[];Object.getOwnPropertyNames(m.headers).forEach(function(L){z.push(d(L)),x.setRequestHeader(L,f(m.headers[L]))}),O.headers.forEach(function(L,H){z.indexOf(H)===-1&&x.setRequestHeader(H,L)})}else O.headers.forEach(function(L,H){x.setRequestHeader(H,L)});O.signal&&(O.signal.addEventListener("abort",F),x.onreadystatechange=function(){x.readyState===4&&O.signal.removeEventListener("abort",F)}),x.send(typeof O._bodyInit>"u"?null:O._bodyInit)})}return $.polyfill=!0,a.fetch||(a.fetch=$,a.Headers=g,a.Request=S,a.Response=B),o.Headers=g,o.Request=S,o.Response=B,o.fetch=$,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=t.fetch?t:i;e=s.fetch,e.default=s.fetch,e.fetch=s.fetch,e.Headers=s.Headers,e.Request=s.Request,e.Response=s.Response,r.exports=e})(Hi,Hi.exports)),Hi.exports}var G2=W2();const ll=co(G2);var Y2=Object.defineProperty,J2=Object.defineProperties,Z2=Object.getOwnPropertyDescriptors,hl=Object.getOwnPropertySymbols,Q2=Object.prototype.hasOwnProperty,X2=Object.prototype.propertyIsEnumerable,ul=(r,e,t)=>e in r?Y2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,dl=(r,e)=>{for(var t in e||(e={}))Q2.call(e,t)&&ul(r,t,e[t]);if(hl)for(var t of hl(e))X2.call(e,t)&&ul(r,t,e[t]);return r},pl=(r,e)=>J2(r,Z2(e));const eD={Accept:"application/json","Content-Type":"application/json"},tD="POST",fl={headers:eD,method:tD},gl=10;let dt=class{constructor(e,t=!1){if(this.url=e,this.disableProviderPing=t,this.events=new Ye.EventEmitter,this.isAvailable=!1,this.registering=!1,!Cc(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=t}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const t=jt(e),i=await(await ll(this.url,pl(dl({},fl),{body:t}))).json();this.onPayload({data:i})}catch(t){this.onError(e.id,t)}}async register(e=this.url){if(!Cc(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return s(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const t=jt({id:1,jsonrpc:"2.0",method:"test",params:[]});await ll(e,pl(dl({},fl),{body:t}))}this.onOpen()}catch(t){const i=this.parseError(t);throw this.events.emit("register_error",i),this.onClose(),i}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const t=typeof e.data=="string"?or(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),s=i.message||i.toString(),n=Ps(e,s);this.events.emit("payload",n)}parseError(e,t=this.url){return au(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>gl&&this.events.setMaxListeners(gl)}};const yl="error",rD="wss://relay.walletconnect.org",iD="wc",sD="universal_provider",Vi=`${iD}@2:${sD}:`,xu="https://rpc.walletconnect.org/v1/",Nr="generic",nD=`${xu}bundler`,st={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function oD(){}function Co(r){return r==null||typeof r!="object"&&typeof r!="function"}function xo(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}function aD(r){if(Co(r))return r;if(Array.isArray(r)||xo(r)||r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer)return r.slice(0);const e=Object.getPrototypeOf(r),t=e.constructor;if(r instanceof Date||r instanceof Map||r instanceof Set)return new t(r);if(r instanceof RegExp){const i=new t(r);return i.lastIndex=r.lastIndex,i}if(r instanceof DataView)return new t(r.buffer.slice(0));if(r instanceof Error){const i=new t(r.message);return i.stack=r.stack,i.name=r.name,i.cause=r.cause,i}if(typeof File<"u"&&r instanceof File)return new t([r],r.name,{type:r.type,lastModified:r.lastModified});if(typeof r=="object"){const i=Object.create(e);return Object.assign(i,r)}return r}function ml(r){return typeof r=="object"&&r!==null}function Tu(r){return Object.getOwnPropertySymbols(r).filter(e=>Object.prototype.propertyIsEnumerable.call(r,e))}function Ru(r){return r==null?r===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(r)}const cD="[object RegExp]",Nu="[object String]",ju="[object Number]",Bu="[object Boolean]",Uu="[object Arguments]",lD="[object Symbol]",hD="[object Date]",uD="[object Map]",dD="[object Set]",pD="[object Array]",fD="[object ArrayBuffer]",gD="[object Object]",yD="[object DataView]",mD="[object Uint8Array]",wD="[object Uint8ClampedArray]",bD="[object Uint16Array]",vD="[object Uint32Array]",ED="[object Int8Array]",_D="[object Int16Array]",ID="[object Int32Array]",DD="[object Float32Array]",SD="[object Float64Array]";function OD(r,e){return Ur(r,void 0,r,new Map,e)}function Ur(r,e,t,i=new Map,s=void 0){const n=s==null?void 0:s(r,e,t,i);if(n!=null)return n;if(Co(r))return r;if(i.has(r))return i.get(r);if(Array.isArray(r)){const o=new Array(r.length);i.set(r,o);for(let a=0;a<r.length;a++)o[a]=Ur(r[a],a,t,i,s);return Object.hasOwn(r,"index")&&(o.index=r.index),Object.hasOwn(r,"input")&&(o.input=r.input),o}if(r instanceof Date)return new Date(r.getTime());if(r instanceof RegExp){const o=new RegExp(r.source,r.flags);return o.lastIndex=r.lastIndex,o}if(r instanceof Map){const o=new Map;i.set(r,o);for(const[a,c]of r)o.set(a,Ur(c,a,t,i,s));return o}if(r instanceof Set){const o=new Set;i.set(r,o);for(const a of r)o.add(Ur(a,void 0,t,i,s));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(r))return r.subarray();if(xo(r)){const o=new(Object.getPrototypeOf(r)).constructor(r.length);i.set(r,o);for(let a=0;a<r.length;a++)o[a]=Ur(r[a],a,t,i,s);return o}if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer)return r.slice(0);if(r instanceof DataView){const o=new DataView(r.buffer.slice(0),r.byteOffset,r.byteLength);return i.set(r,o),rr(o,r,t,i,s),o}if(typeof File<"u"&&r instanceof File){const o=new File([r],r.name,{type:r.type});return i.set(r,o),rr(o,r,t,i,s),o}if(r instanceof Blob){const o=new Blob([r],{type:r.type});return i.set(r,o),rr(o,r,t,i,s),o}if(r instanceof Error){const o=new r.constructor;return i.set(r,o),o.message=r.message,o.name=r.name,o.stack=r.stack,o.cause=r.cause,rr(o,r,t,i,s),o}if(typeof r=="object"&&PD(r)){const o=Object.create(Object.getPrototypeOf(r));return i.set(r,o),rr(o,r,t,i,s),o}return r}function rr(r,e,t=r,i,s){const n=[...Object.keys(e),...Tu(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(r,a);(c==null||c.writable)&&(r[a]=Ur(e[a],a,t,i,s))}}function PD(r){switch(Ru(r)){case Uu:case pD:case fD:case yD:case Bu:case hD:case DD:case SD:case ED:case _D:case ID:case uD:case ju:case gD:case cD:case dD:case Nu:case lD:case mD:case wD:case bD:case vD:return!0;default:return!1}}function $D(r,e){return OD(r,(t,i,s,n)=>{if(typeof r=="object")switch(Object.prototype.toString.call(r)){case ju:case Nu:case Bu:{const o=new r.constructor(r==null?void 0:r.valueOf());return rr(o,r),o}case Uu:{const o={};return rr(o,r),o.length=r.length,o[Symbol.iterator]=r[Symbol.iterator],o}default:return}})}function wl(r){return $D(r)}function bl(r){return r!==null&&typeof r=="object"&&Ru(r)==="[object Arguments]"}function AD(r){return xo(r)}function CD(r){var t;if(typeof r!="object"||r==null)return!1;if(Object.getPrototypeOf(r)===null)return!0;if(Object.prototype.toString.call(r)!=="[object Object]"){const i=r[Symbol.toStringTag];return i==null||!((t=Object.getOwnPropertyDescriptor(r,Symbol.toStringTag))!=null&&t.writable)?!1:r.toString()===`[object ${i}]`}let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}function xD(r,...e){const t=e.slice(0,-1),i=e[e.length-1];let s=r;for(let n=0;n<t.length;n++){const o=t[n];s=so(s,o,i,new Map)}return s}function so(r,e,t,i){if(Co(r)&&(r=Object(r)),e==null||typeof e!="object")return r;if(i.has(e))return aD(i.get(e));if(i.set(e,r),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const s=[...Object.keys(e),...Tu(e)];for(let n=0;n<s.length;n++){const o=s[n];let a=e[o],c=r[o];if(bl(a)&&(a={...a}),bl(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=wl(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const h=[],u=Reflect.ownKeys(c);for(let d=0;d<u.length;d++){const f=u[d];h[f]=c[f]}c=h}else c=[];const l=t(c,a,o,r,e,i);l!=null?r[o]=l:Array.isArray(a)||ml(c)&&ml(a)?r[o]=so(c,a,t,i):c==null&&CD(a)?r[o]=so({},a,t,i):c==null&&AD(a)?r[o]=wl(a):(c===void 0||a!==void 0)&&(r[o]=a)}return r}function TD(r,...e){return xD(r,...e,oD)}var RD=Object.defineProperty,ND=Object.defineProperties,jD=Object.getOwnPropertyDescriptors,vl=Object.getOwnPropertySymbols,BD=Object.prototype.hasOwnProperty,UD=Object.prototype.propertyIsEnumerable,El=(r,e,t)=>e in r?RD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ki=(r,e)=>{for(var t in e||(e={}))BD.call(e,t)&&El(r,t,e[t]);if(vl)for(var t of vl(e))UD.call(e,t)&&El(r,t,e[t]);return r},qD=(r,e)=>ND(r,jD(e));function Ge(r,e,t){var i;const s=qr(r);return((i=e.rpcMap)==null?void 0:i[s.reference])||`${xu}?chainId=${s.namespace}:${s.reference}&projectId=${t}`}function fr(r){return r.includes(":")?r.split(":")[1]:r}function qu(r){return r.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function FD(r,e){const t=Object.keys(e.namespaces).filter(s=>s.includes(r));if(!t.length)return[];const i=[];return t.forEach(s=>{const n=e.namespaces[s].accounts;i.push(...n)}),i}function Wi(r={},e={}){const t=_l(r),i=_l(e);return TD(t,i)}function _l(r){var e,t,i,s,n;const o={};if(!Vt(r))return o;for(const[a,c]of Object.entries(r)){const l=Ds(a)?[a]:c.chains,h=c.methods||[],u=c.events||[],d=c.rpcMap||{},f=Br(a);o[f]=qD(Ki(Ki({},o[f]),c),{chains:_t(l,(e=o[f])==null?void 0:e.chains),methods:_t(h,(t=o[f])==null?void 0:t.methods),events:_t(u,(i=o[f])==null?void 0:i.events)}),(Vt(d)||Vt(((s=o[f])==null?void 0:s.rpcMap)||{}))&&(o[f].rpcMap=Ki(Ki({},d),(n=o[f])==null?void 0:n.rpcMap))}return o}function Il(r){return r.includes(":")?r.split(":")[2]:r}function Dl(r){const e={};for(const[t,i]of Object.entries(r)){const s=i.methods||[],n=i.events||[],o=i.accounts||[],a=Ds(t)?[t]:i.chains?i.chains:qu(i.accounts);e[t]={chains:a,methods:s,events:n,accounts:o}}return e}function wn(r){return typeof r=="number"?r:r.includes("0x")?parseInt(r,16):(r=r.includes(":")?r.split(":")[1]:r,isNaN(Number(r))?r:Number(r))}const Fu={},Q=r=>Fu[r],bn=(r,e)=>{Fu[r]=e};var LD=Object.defineProperty,MD=(r,e,t)=>e in r?LD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,_r=(r,e,t)=>MD(r,typeof e!="symbol"?e+"":e,t);class kD{constructor(e){_r(this,"name","polkadot"),_r(this,"client"),_r(this,"httpProviders"),_r(this,"events"),_r(this,"namespace"),_r(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=fr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var zD=Object.defineProperty,HD=Object.defineProperties,VD=Object.getOwnPropertyDescriptors,Sl=Object.getOwnPropertySymbols,KD=Object.prototype.hasOwnProperty,WD=Object.prototype.propertyIsEnumerable,no=(r,e,t)=>e in r?zD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ol=(r,e)=>{for(var t in e||(e={}))KD.call(e,t)&&no(r,t,e[t]);if(Sl)for(var t of Sl(e))WD.call(e,t)&&no(r,t,e[t]);return r},Pl=(r,e)=>HD(r,VD(e)),Ir=(r,e,t)=>no(r,typeof e!="symbol"?e+"":e,t);class GD{constructor(e){Ir(this,"name","eip155"),Ir(this,"client"),Ir(this,"chainId"),Ir(this,"namespace"),Ir(this,"httpProviders"),Ir(this,"events"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){const i=t||Ge(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=parseInt(fr(t));e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,i;let s=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";s=s.startsWith("0x")?s:`0x${s}`;const n=parseInt(s,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:s}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,i,s,n,o;const a=(i=(t=e.request)==null?void 0:t.params)==null?void 0:i[0],c=((n=(s=e.request)==null?void 0:s.params)==null?void 0:n[1])||[],l=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const h=this.client.session.get(e.topic),u=((o=h==null?void 0:h.sessionProperties)==null?void 0:o.capabilities)||{};if(u!=null&&u[l])return u==null?void 0:u[l];const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Pl(Ol({},h.sessionProperties||{}),{capabilities:Pl(Ol({},u||{}),{[l]:d})})})}catch(f){console.warn("Failed to update session with capabilities",f)}return d}async getCallStatus(e){var t,i;const s=this.client.session.get(e.topic),n=(t=s.sessionProperties)==null?void 0:t.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(i=s.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var i;const s=new URL(e),n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(zt("eth_getUserOperationReceipt",[(i=t.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${nD}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var YD=Object.defineProperty,JD=(r,e,t)=>e in r?YD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Dr=(r,e,t)=>JD(r,typeof e!="symbol"?e+"":e,t);class ZD{constructor(e){Dr(this,"name","solana"),Dr(this,"client"),Dr(this,"httpProviders"),Dr(this,"events"),Dr(this,"namespace"),Dr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=fr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var QD=Object.defineProperty,XD=(r,e,t)=>e in r?QD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Sr=(r,e,t)=>XD(r,typeof e!="symbol"?e+"":e,t);class eS{constructor(e){Sr(this,"name","cosmos"),Sr(this,"client"),Sr(this,"httpProviders"),Sr(this,"events"),Sr(this,"namespace"),Sr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=fr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var tS=Object.defineProperty,rS=(r,e,t)=>e in r?tS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Or=(r,e,t)=>rS(r,typeof e!="symbol"?e+"":e,t);class iS{constructor(e){Or(this,"name","algorand"),Or(this,"client"),Or(this,"httpProviders"),Or(this,"events"),Or(this,"namespace"),Or(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const i=t||Ge(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new it(new dt(i,Q("disableProviderPing")))}}var sS=Object.defineProperty,nS=(r,e,t)=>e in r?sS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Pr=(r,e,t)=>nS(r,typeof e!="symbol"?e+"":e,t);class oS{constructor(e){Pr(this,"name","cip34"),Pr(this,"client"),Pr(this,"httpProviders"),Pr(this,"events"),Pr(this,"namespace"),Pr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const i=this.getCardanoRPCUrl(t),s=fr(t);e[s]=this.createHttpProvider(s,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var aS=Object.defineProperty,cS=(r,e,t)=>e in r?aS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,$r=(r,e,t)=>cS(r,typeof e!="symbol"?e+"":e,t);class lS{constructor(e){$r(this,"name","elrond"),$r(this,"client"),$r(this,"httpProviders"),$r(this,"events"),$r(this,"namespace"),$r(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=fr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var hS=Object.defineProperty,uS=(r,e,t)=>e in r?hS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ar=(r,e,t)=>uS(r,typeof e!="symbol"?e+"":e,t);class dS{constructor(e){Ar(this,"name","multiversx"),Ar(this,"client"),Ar(this,"httpProviders"),Ar(this,"events"),Ar(this,"namespace"),Ar(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=fr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var pS=Object.defineProperty,fS=(r,e,t)=>e in r?pS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Cr=(r,e,t)=>fS(r,typeof e!="symbol"?e+"":e,t);class gS{constructor(e){Cr(this,"name","near"),Cr(this,"client"),Cr(this,"httpProviders"),Cr(this,"events"),Cr(this,"namespace"),Cr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||Ge(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace);return typeof i>"u"?void 0:new it(new dt(i,Q("disableProviderPing")))}}var yS=Object.defineProperty,mS=(r,e,t)=>e in r?yS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,xr=(r,e,t)=>mS(r,typeof e!="symbol"?e+"":e,t);class wS{constructor(e){xr(this,"name","tezos"),xr(this,"client"),xr(this,"httpProviders"),xr(this,"events"),xr(this,"namespace"),xr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||Ge(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace);return typeof i>"u"?void 0:new it(new dt(i))}}var bS=Object.defineProperty,vS=(r,e,t)=>e in r?bS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Tr=(r,e,t)=>vS(r,typeof e!="symbol"?e+"":e,t);class ES{constructor(e){Tr(this,"name",Nr),Tr(this,"client"),Tr(this,"httpProviders"),Tr(this,"events"),Tr(this,"namespace"),Tr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const i={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(s=>{const n=qr(s);i[`${n.namespace}:${n.reference}`]=this.createHttpProvider(s)}),i}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var _S=Object.defineProperty,IS=Object.defineProperties,DS=Object.getOwnPropertyDescriptors,$l=Object.getOwnPropertySymbols,SS=Object.prototype.hasOwnProperty,OS=Object.prototype.propertyIsEnumerable,oo=(r,e,t)=>e in r?_S(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Gi=(r,e)=>{for(var t in e||(e={}))SS.call(e,t)&&oo(r,t,e[t]);if($l)for(var t of $l(e))OS.call(e,t)&&oo(r,t,e[t]);return r},vn=(r,e)=>IS(r,DS(e)),Xe=(r,e,t)=>oo(r,typeof e!="symbol"?e+"":e,t);let PS=class Lu{constructor(e){Xe(this,"client"),Xe(this,"namespaces"),Xe(this,"optionalNamespaces"),Xe(this,"sessionProperties"),Xe(this,"scopedProperties"),Xe(this,"events",new lo),Xe(this,"rpcProviders",{}),Xe(this,"session"),Xe(this,"providerOpts"),Xe(this,"logger"),Xe(this,"uri"),Xe(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:xi(Ss({level:(e==null?void 0:e.logger)||yl})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new Lu(e);return await t.initialize(),t}async request(e,t,i){const[s,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:Gi({},e),chainId:`${s}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,s){const n=new Date().getTime();this.request(e,i,s).then(o=>t(null,Os(n,o))).catch(o=>t(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:te("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:s}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await s();if(this.session=n.session,this.session){const o=Dl(this.session.namespaces);this.namespaces=Wi(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const s=await i();this.session=s;const n=Dl(s.namespaces);return this.namespaces=Wi(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,s]=this.validateChain(e),n=this.getProvider(i);n.name===Nr?n.setDefaultChain(`${i}:${s}`,t):n.setDefaultChain(s,t)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(ut(t)){for(const i of t)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,t;if(this.client=this.providerOpts.client||await K2.init({core:this.providerOpts.core,logger:this.providerOpts.logger||yl,relayUrl:this.providerOpts.relayUrl||rD,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(i){throw this.logger.error("Failed to get session",i),new Error(`The provided session: ${(t=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:t.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(t=>Br(t)))];bn("client",this.client),bn("events",this.events),bn("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=FD(t,this.session),s=qu(i),n=Wi(this.namespaces,this.optionalNamespaces),o=vn(Gi({},n[t]),{accounts:i,chains:s});switch(t){case"eip155":this.rpcProviders[t]=new GD({namespace:o});break;case"algorand":this.rpcProviders[t]=new iS({namespace:o});break;case"solana":this.rpcProviders[t]=new ZD({namespace:o});break;case"cosmos":this.rpcProviders[t]=new eS({namespace:o});break;case"polkadot":this.rpcProviders[t]=new kD({namespace:o});break;case"cip34":this.rpcProviders[t]=new oS({namespace:o});break;case"elrond":this.rpcProviders[t]=new lS({namespace:o});break;case"multiversx":this.rpcProviders[t]=new dS({namespace:o});break;case"near":this.rpcProviders[t]=new gS({namespace:o});break;case"tezos":this.rpcProviders[t]=new wS({namespace:o});break;default:this.rpcProviders[Nr]?this.rpcProviders[Nr].updateNamespace(o):this.rpcProviders[Nr]=new ES({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var t;const{topic:i}=e;i===((t=this.session)==null?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:i,topic:s}=e;if(s!==((t=this.session)==null?void 0:t.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&&ut(o)&&this.events.emit("accountsChanged",o.map(Il))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=Br(o),l=wn(o)!==wn(a)?`${c}:${wn(a)}`:o;this.onChainChanged(l)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i,s;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=t,o=(s=this.client)==null?void 0:s.session.get(e);this.session=vn(Gi({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===((t=this.session)==null?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",vn(Gi({},te("USER_DISCONNECTED")),{data:e.topic})))}),this.on(st.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Nr]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t={},optionalNamespaces:i={},sessionProperties:s,scopedProperties:n}=e;this.optionalNamespaces=Wi(t,i),this.sessionProperties=s,this.scopedProperties=n}validateChain(e){const[t,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(o=>Br(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const s=Br(Object.keys(this.namespaces)[0]),n=this.rpcProviders[s].getDefaultChain();return[s,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,t=!1){if(!this.namespaces)return;const[i,s]=this.validateChain(e);if(!s)return;this.updateNamespaceChain(i,s),this.events.emit("chainChanged",s);const n=this.getProvider(i).getDefaultChain();t||this.getProvider(i).setDefaultChain(s),this.emitAccountsChangedOnChainChange({namespace:i,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:t,newChainId:i}){var s,n;try{if(t===i)return;const o=(n=(s=this.session)==null?void 0:s.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${i}:`)).map(Il);if(!ut(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,t){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${t}`,s={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=t):this.namespaces[i]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){var i;const s=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${Vi}/${e}${s}`,t)}async getFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${Vi}/${e}${i}`)}async deleteFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${Vi}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const i of t)i.startsWith(Vi)&&await this.client.core.storage.removeItem(i)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const $S=PS,AS="wc",CS="ethereum_provider",xS=`${AS}@2:${CS}:`,TS="https://rpc.walletconnect.org/v1/",us=["eth_sendTransaction","personal_sign"],Mu=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],ds=["chainChanged","accountsChanged"],ku=["chainChanged","accountsChanged","message","disconnect","connect"],RS=async()=>{const{createAppKit:r}=await Qu(()=>import("./core-4C0uPyns.js").then(e=>e.G),__vite__mapDeps([0,1,2,3,4,5,6]));return r};var NS=Object.defineProperty,jS=Object.defineProperties,BS=Object.getOwnPropertyDescriptors,Al=Object.getOwnPropertySymbols,US=Object.prototype.hasOwnProperty,qS=Object.prototype.propertyIsEnumerable,ao=(r,e,t)=>e in r?NS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Qt=(r,e)=>{for(var t in e||(e={}))US.call(e,t)&&ao(r,t,e[t]);if(Al)for(var t of Al(e))qS.call(e,t)&&ao(r,t,e[t]);return r},ai=(r,e)=>jS(r,BS(e)),ze=(r,e,t)=>ao(r,typeof e!="symbol"?e+"":e,t);function ps(r){return Number(r[0].split(":")[1])}function Yi(r){return`0x${r.toString(16)}`}function FS(r){const{chains:e,optionalChains:t,methods:i,optionalMethods:s,events:n,optionalEvents:o,rpcMap:a}=r;if(!ut(e))throw new Error("Invalid chains");const c={chains:e,methods:i||us,events:n||ds,rpcMap:Qt({},e.length?{[ps(e)]:a[ps(e)]}:{})},l=n==null?void 0:n.filter(f=>!ds.includes(f)),h=i==null?void 0:i.filter(f=>!us.includes(f));if(!t&&!o&&!s&&!(l!=null&&l.length)&&!(h!=null&&h.length))return{required:e.length?c:void 0};const u=(l==null?void 0:l.length)&&(h==null?void 0:h.length)||!t,d={chains:[...new Set(u?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:Mu))],events:[...new Set(c.events.concat(o!=null&&o.length?o:ku))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?d:void 0}}class xs{constructor(){ze(this,"events",new Ye.EventEmitter),ze(this,"namespace","eip155"),ze(this,"accounts",[]),ze(this,"signer"),ze(this,"chainId",1),ze(this,"modal"),ze(this,"rpc"),ze(this,"STORAGE_KEY",xS),ze(this,"on",(e,t)=>(this.events.on(e,t),this)),ze(this,"once",(e,t)=>(this.events.once(e,t),this)),ze(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),ze(this,"off",(e,t)=>(this.events.off(e,t),this)),ze(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const t=new xs;return await t.initialize(e),t}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,i){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var t;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:s}=FS(this.rpc);try{const n=await new Promise(async(a,c)=>{var l,h;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(h=this.modal)==null||h.subscribeState(d=>{!d.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const u=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(ai(Qt({namespaces:Qt({},i&&{[this.namespace]:i})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:u})).then(d=>{a(d)}).catch(d=>{var f;(f=this.modal)==null||f.showErrorMessage("Unable to connect"),c(new Error(d.message))})});if(!n)return;const o=_a(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Yi(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(t=this.modal)==null||t.close()}}async authenticate(e,t){var i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const s=await new Promise(async(o,a)=>{var c,l;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(l=this.modal)==null||l.subscribeState(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(ai(Qt({},e),{chains:this.rpc.chains}),t).then(h=>{o(h)}).catch(h=>{var u;(u=this.modal)==null||u.showErrorMessage("Unable to connect"),a(new Error(h.message))})}),n=s.session;if(n){const o=_a(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Yi(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}finally{(i=this.modal)==null||i.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:t}=e,{event:i}=t;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",Yi(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",ai(Qt({},te("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",Yi(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){const[t,i,s]=e.split(":");return{chainId:`${t}:${i}`,address:s}}setAccounts(e){this.accounts=e.filter(t=>this.parseChainId(this.parseAccountId(t).chainId)===this.chainId).map(t=>this.parseAccountId(t).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var t,i;const s=(t=e==null?void 0:e.chains)!=null?t:[],n=(i=e==null?void 0:e.optionalChains)!=null?i:[],o=s.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=s.length?(e==null?void 0:e.methods)||us:[],c=s.length?(e==null?void 0:e.events)||ds:[],l=(e==null?void 0:e.optionalMethods)||[],h=(e==null?void 0:e.optionalEvents)||[],u=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),d=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:s==null?void 0:s.map(f=>this.formatChainId(f)),optionalChains:n.map(f=>this.formatChainId(f)),methods:a,events:c,optionalMethods:l,optionalEvents:h,rpcMap:u,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:d,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const i={};return e.forEach(s=>{i[s]=this.getRpcUrl(s,t)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?ps(this.rpc.chains):ps(this.rpc.optionalChains),this.signer=await $S.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let t;try{const i=await RS(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return JS}),n=s(ai(Qt({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");t=i(ai(Qt({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(i){throw console.warn(i),new Error("To use QR modal, please install @reown/appkit package")}if(t)try{this.modal=t}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:i,rpcMap:s}=e;t&&ut(t)&&(this.rpc.chains=t.map(n=>this.formatChainId(n)),t.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)})),i&&ut(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)}))}getRpcUrl(e,t){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${TS}?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),t=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:t==null?void 0:t.accounts),this.setAccounts(t==null?void 0:t.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(t=>this.signer.logger.warn(t))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(t=>this.parseAccount(t))}}const LS=xs;var MS=Object.defineProperty,kS=Object.defineProperties,zS=Object.getOwnPropertyDescriptors,Cl=Object.getOwnPropertySymbols,HS=Object.prototype.hasOwnProperty,VS=Object.prototype.propertyIsEnumerable,xl=(r,e,t)=>e in r?MS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,zu=(r,e)=>{for(var t in e||(e={}))HS.call(e,t)&&xl(r,t,e[t]);if(Cl)for(var t of Cl(e))VS.call(e,t)&&xl(r,t,e[t]);return r},KS=(r,e)=>kS(r,zS(e));function WS(r){if(r)return{"--w3m-font-family":r["--wcm-font-family"],"--w3m-accent":r["--wcm-accent-color"],"--w3m-color-mix":r["--wcm-background-color"],"--w3m-z-index":r["--wcm-z-index"]?Number(r["--wcm-z-index"]):void 0,"--w3m-qr-color":r["--wcm-accent-color"],"--w3m-font-size-master":r["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":r["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const GS=r=>{const[e,t]=r.split(":");return Hu({id:t,caipNetworkId:r,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function YS(r){var e,t,i,s,n,o,a;const c=(e=r.chains)==null?void 0:e.map(GS).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const l=c.find(u=>{var d;return u.id===((d=r.defaultChain)==null?void 0:d.id)}),h={projectId:r.projectId,networks:c,themeMode:r.themeMode,themeVariables:WS(r.themeVariables),chainImages:r.chainImages,connectorImages:r.walletImages,defaultNetwork:l,metadata:KS(zu({},r.metadata),{name:((t=r.metadata)==null?void 0:t.name)||"WalletConnect",description:((i=r.metadata)==null?void 0:i.description)||"Connect to WalletConnect-compatible wallets",url:((s=r.metadata)==null?void 0:s.url)||"https://walletconnect.org",icons:((n=r.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:r.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(r.explorerRecommendedWalletIds)?r.explorerRecommendedWalletIds:[],excludeWalletIds:r.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(r.explorerExcludedWalletIds)?r.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=r.mobileWallets)!=null&&o.length||(a=r.desktopWallets)!=null&&a.length){const u=[...(r.mobileWallets||[]).map(p=>({id:p.id,name:p.name,links:p.links})),...(r.desktopWallets||[]).map(p=>({id:p.id,name:p.name,links:{native:p.links.native,universal:p.links.universal}}))],d=[...h.featuredWalletIds||[],...h.excludeWalletIds||[]],f=u.filter(p=>!d.includes(p.id));f.length&&(h.customWallets=f)}return h}function Hu(r){return zu({formatters:void 0,fees:void 0,serializers:void 0},r)}var JS=Object.freeze({__proto__:null,convertWCMToAppKitOptions:YS,defineChain:Hu});const UO=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:LS,OPTIONAL_EVENTS:ku,OPTIONAL_METHODS:Mu,REQUIRED_EVENTS:ds,REQUIRED_METHODS:us,default:xs},Symbol.toStringTag,{value:"Module"}));export{S0 as A,tt as B,zy as C,Xd as D,Ne as E,wt as F,dt as G,UO as H,ur as I,lo as N,xi as O,ba as P,uh as Q,Nt as a,hi as b,U as c,fd as d,Jd as e,rt as f,Ye as g,c0 as h,Rv as i,zt as j,Ss as k,jE as l,$o as m,$s as n,it as o,Os as p,Kg as q,dr as r,An as s,Le as t,jt as u,or as v,sr as w,Ps as x,Me as y,bt as z};
38
+ `)===0?C.substr(1,C.length):C}).forEach(function(C){var O=C.split(":"),x=O.shift().trim();if(x){var F=O.join(":").trim();try{m.append(x,F)}catch(M){console.warn("Response "+M.message)}}}),m}v.call(S.prototype);function B(y,m){if(!(this instanceof B))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(m||(m={}),this.type="default",this.status=m.status===void 0?200:m.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=m.statusText===void 0?"":""+m.statusText,this.headers=new g(m.headers),this.url=m.url||"",this._initBody(y)}v.call(B.prototype),B.prototype.clone=function(){return new B(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new g(this.headers),url:this.url})},B.error=function(){var y=new B(null,{status:200,statusText:""});return y.ok=!1,y.status=0,y.type="error",y};var k=[301,302,303,307,308];B.redirect=function(y,m){if(k.indexOf(m)===-1)throw new RangeError("Invalid status code");return new B(null,{status:m,headers:{location:y}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(m,D){this.message=m,this.name=D;var C=Error(m);this.stack=C.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function $(y,m){return new Promise(function(D,C){var O=new S(y,m);if(O.signal&&O.signal.aborted)return C(new o.DOMException("Aborted","AbortError"));var x=new XMLHttpRequest;function F(){x.abort()}x.onload=function(){var L={statusText:x.statusText,headers:N(x.getAllResponseHeaders()||"")};O.url.indexOf("file://")===0&&(x.status<200||x.status>599)?L.status=200:L.status=x.status,L.url="responseURL"in x?x.responseURL:L.headers.get("X-Request-URL");var H="response"in x?x.response:x.responseText;setTimeout(function(){D(new B(H,L))},0)},x.onerror=function(){setTimeout(function(){C(new TypeError("Network request failed"))},0)},x.ontimeout=function(){setTimeout(function(){C(new TypeError("Network request timed out"))},0)},x.onabort=function(){setTimeout(function(){C(new o.DOMException("Aborted","AbortError"))},0)};function M(L){try{return L===""&&a.location.href?a.location.href:L}catch{return L}}if(x.open(O.method,M(O.url),!0),O.credentials==="include"?x.withCredentials=!0:O.credentials==="omit"&&(x.withCredentials=!1),"responseType"in x&&(c.blob?x.responseType="blob":c.arrayBuffer&&(x.responseType="arraybuffer")),m&&typeof m.headers=="object"&&!(m.headers instanceof g||a.Headers&&m.headers instanceof a.Headers)){var z=[];Object.getOwnPropertyNames(m.headers).forEach(function(L){z.push(d(L)),x.setRequestHeader(L,f(m.headers[L]))}),O.headers.forEach(function(L,H){z.indexOf(H)===-1&&x.setRequestHeader(H,L)})}else O.headers.forEach(function(L,H){x.setRequestHeader(H,L)});O.signal&&(O.signal.addEventListener("abort",F),x.onreadystatechange=function(){x.readyState===4&&O.signal.removeEventListener("abort",F)}),x.send(typeof O._bodyInit>"u"?null:O._bodyInit)})}return $.polyfill=!0,a.fetch||(a.fetch=$,a.Headers=g,a.Request=S,a.Response=B),o.Headers=g,o.Request=S,o.Response=B,o.fetch=$,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=t.fetch?t:i;e=s.fetch,e.default=s.fetch,e.fetch=s.fetch,e.Headers=s.Headers,e.Request=s.Request,e.Response=s.Response,r.exports=e})(Hi,Hi.exports)),Hi.exports}var G2=W2();const ll=co(G2);var Y2=Object.defineProperty,J2=Object.defineProperties,Z2=Object.getOwnPropertyDescriptors,hl=Object.getOwnPropertySymbols,Q2=Object.prototype.hasOwnProperty,X2=Object.prototype.propertyIsEnumerable,ul=(r,e,t)=>e in r?Y2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,dl=(r,e)=>{for(var t in e||(e={}))Q2.call(e,t)&&ul(r,t,e[t]);if(hl)for(var t of hl(e))X2.call(e,t)&&ul(r,t,e[t]);return r},pl=(r,e)=>J2(r,Z2(e));const eD={Accept:"application/json","Content-Type":"application/json"},tD="POST",fl={headers:eD,method:tD},gl=10;let dt=class{constructor(e,t=!1){if(this.url=e,this.disableProviderPing=t,this.events=new Ye.EventEmitter,this.isAvailable=!1,this.registering=!1,!Cc(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=t}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const t=jt(e),i=await(await ll(this.url,pl(dl({},fl),{body:t}))).json();this.onPayload({data:i})}catch(t){this.onError(e.id,t)}}async register(e=this.url){if(!Cc(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return s(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const t=jt({id:1,jsonrpc:"2.0",method:"test",params:[]});await ll(e,pl(dl({},fl),{body:t}))}this.onOpen()}catch(t){const i=this.parseError(t);throw this.events.emit("register_error",i),this.onClose(),i}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const t=typeof e.data=="string"?or(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),s=i.message||i.toString(),n=Ps(e,s);this.events.emit("payload",n)}parseError(e,t=this.url){return au(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>gl&&this.events.setMaxListeners(gl)}};const yl="error",rD="wss://relay.walletconnect.org",iD="wc",sD="universal_provider",Vi=`${iD}@2:${sD}:`,xu="https://rpc.walletconnect.org/v1/",Nr="generic",nD=`${xu}bundler`,st={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function oD(){}function Co(r){return r==null||typeof r!="object"&&typeof r!="function"}function xo(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}function aD(r){if(Co(r))return r;if(Array.isArray(r)||xo(r)||r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer)return r.slice(0);const e=Object.getPrototypeOf(r),t=e.constructor;if(r instanceof Date||r instanceof Map||r instanceof Set)return new t(r);if(r instanceof RegExp){const i=new t(r);return i.lastIndex=r.lastIndex,i}if(r instanceof DataView)return new t(r.buffer.slice(0));if(r instanceof Error){const i=new t(r.message);return i.stack=r.stack,i.name=r.name,i.cause=r.cause,i}if(typeof File<"u"&&r instanceof File)return new t([r],r.name,{type:r.type,lastModified:r.lastModified});if(typeof r=="object"){const i=Object.create(e);return Object.assign(i,r)}return r}function ml(r){return typeof r=="object"&&r!==null}function Tu(r){return Object.getOwnPropertySymbols(r).filter(e=>Object.prototype.propertyIsEnumerable.call(r,e))}function Ru(r){return r==null?r===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(r)}const cD="[object RegExp]",Nu="[object String]",ju="[object Number]",Bu="[object Boolean]",Uu="[object Arguments]",lD="[object Symbol]",hD="[object Date]",uD="[object Map]",dD="[object Set]",pD="[object Array]",fD="[object ArrayBuffer]",gD="[object Object]",yD="[object DataView]",mD="[object Uint8Array]",wD="[object Uint8ClampedArray]",bD="[object Uint16Array]",vD="[object Uint32Array]",ED="[object Int8Array]",_D="[object Int16Array]",ID="[object Int32Array]",DD="[object Float32Array]",SD="[object Float64Array]";function OD(r,e){return Ur(r,void 0,r,new Map,e)}function Ur(r,e,t,i=new Map,s=void 0){const n=s==null?void 0:s(r,e,t,i);if(n!=null)return n;if(Co(r))return r;if(i.has(r))return i.get(r);if(Array.isArray(r)){const o=new Array(r.length);i.set(r,o);for(let a=0;a<r.length;a++)o[a]=Ur(r[a],a,t,i,s);return Object.hasOwn(r,"index")&&(o.index=r.index),Object.hasOwn(r,"input")&&(o.input=r.input),o}if(r instanceof Date)return new Date(r.getTime());if(r instanceof RegExp){const o=new RegExp(r.source,r.flags);return o.lastIndex=r.lastIndex,o}if(r instanceof Map){const o=new Map;i.set(r,o);for(const[a,c]of r)o.set(a,Ur(c,a,t,i,s));return o}if(r instanceof Set){const o=new Set;i.set(r,o);for(const a of r)o.add(Ur(a,void 0,t,i,s));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(r))return r.subarray();if(xo(r)){const o=new(Object.getPrototypeOf(r)).constructor(r.length);i.set(r,o);for(let a=0;a<r.length;a++)o[a]=Ur(r[a],a,t,i,s);return o}if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer)return r.slice(0);if(r instanceof DataView){const o=new DataView(r.buffer.slice(0),r.byteOffset,r.byteLength);return i.set(r,o),rr(o,r,t,i,s),o}if(typeof File<"u"&&r instanceof File){const o=new File([r],r.name,{type:r.type});return i.set(r,o),rr(o,r,t,i,s),o}if(r instanceof Blob){const o=new Blob([r],{type:r.type});return i.set(r,o),rr(o,r,t,i,s),o}if(r instanceof Error){const o=new r.constructor;return i.set(r,o),o.message=r.message,o.name=r.name,o.stack=r.stack,o.cause=r.cause,rr(o,r,t,i,s),o}if(typeof r=="object"&&PD(r)){const o=Object.create(Object.getPrototypeOf(r));return i.set(r,o),rr(o,r,t,i,s),o}return r}function rr(r,e,t=r,i,s){const n=[...Object.keys(e),...Tu(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(r,a);(c==null||c.writable)&&(r[a]=Ur(e[a],a,t,i,s))}}function PD(r){switch(Ru(r)){case Uu:case pD:case fD:case yD:case Bu:case hD:case DD:case SD:case ED:case _D:case ID:case uD:case ju:case gD:case cD:case dD:case Nu:case lD:case mD:case wD:case bD:case vD:return!0;default:return!1}}function $D(r,e){return OD(r,(t,i,s,n)=>{if(typeof r=="object")switch(Object.prototype.toString.call(r)){case ju:case Nu:case Bu:{const o=new r.constructor(r==null?void 0:r.valueOf());return rr(o,r),o}case Uu:{const o={};return rr(o,r),o.length=r.length,o[Symbol.iterator]=r[Symbol.iterator],o}default:return}})}function wl(r){return $D(r)}function bl(r){return r!==null&&typeof r=="object"&&Ru(r)==="[object Arguments]"}function AD(r){return xo(r)}function CD(r){var t;if(typeof r!="object"||r==null)return!1;if(Object.getPrototypeOf(r)===null)return!0;if(Object.prototype.toString.call(r)!=="[object Object]"){const i=r[Symbol.toStringTag];return i==null||!((t=Object.getOwnPropertyDescriptor(r,Symbol.toStringTag))!=null&&t.writable)?!1:r.toString()===`[object ${i}]`}let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}function xD(r,...e){const t=e.slice(0,-1),i=e[e.length-1];let s=r;for(let n=0;n<t.length;n++){const o=t[n];s=so(s,o,i,new Map)}return s}function so(r,e,t,i){if(Co(r)&&(r=Object(r)),e==null||typeof e!="object")return r;if(i.has(e))return aD(i.get(e));if(i.set(e,r),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const s=[...Object.keys(e),...Tu(e)];for(let n=0;n<s.length;n++){const o=s[n];let a=e[o],c=r[o];if(bl(a)&&(a={...a}),bl(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=wl(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const h=[],u=Reflect.ownKeys(c);for(let d=0;d<u.length;d++){const f=u[d];h[f]=c[f]}c=h}else c=[];const l=t(c,a,o,r,e,i);l!=null?r[o]=l:Array.isArray(a)||ml(c)&&ml(a)?r[o]=so(c,a,t,i):c==null&&CD(a)?r[o]=so({},a,t,i):c==null&&AD(a)?r[o]=wl(a):(c===void 0||a!==void 0)&&(r[o]=a)}return r}function TD(r,...e){return xD(r,...e,oD)}var RD=Object.defineProperty,ND=Object.defineProperties,jD=Object.getOwnPropertyDescriptors,vl=Object.getOwnPropertySymbols,BD=Object.prototype.hasOwnProperty,UD=Object.prototype.propertyIsEnumerable,El=(r,e,t)=>e in r?RD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ki=(r,e)=>{for(var t in e||(e={}))BD.call(e,t)&&El(r,t,e[t]);if(vl)for(var t of vl(e))UD.call(e,t)&&El(r,t,e[t]);return r},qD=(r,e)=>ND(r,jD(e));function Ge(r,e,t){var i;const s=qr(r);return((i=e.rpcMap)==null?void 0:i[s.reference])||`${xu}?chainId=${s.namespace}:${s.reference}&projectId=${t}`}function fr(r){return r.includes(":")?r.split(":")[1]:r}function qu(r){return r.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function FD(r,e){const t=Object.keys(e.namespaces).filter(s=>s.includes(r));if(!t.length)return[];const i=[];return t.forEach(s=>{const n=e.namespaces[s].accounts;i.push(...n)}),i}function Wi(r={},e={}){const t=_l(r),i=_l(e);return TD(t,i)}function _l(r){var e,t,i,s,n;const o={};if(!Vt(r))return o;for(const[a,c]of Object.entries(r)){const l=Ds(a)?[a]:c.chains,h=c.methods||[],u=c.events||[],d=c.rpcMap||{},f=Br(a);o[f]=qD(Ki(Ki({},o[f]),c),{chains:_t(l,(e=o[f])==null?void 0:e.chains),methods:_t(h,(t=o[f])==null?void 0:t.methods),events:_t(u,(i=o[f])==null?void 0:i.events)}),(Vt(d)||Vt(((s=o[f])==null?void 0:s.rpcMap)||{}))&&(o[f].rpcMap=Ki(Ki({},d),(n=o[f])==null?void 0:n.rpcMap))}return o}function Il(r){return r.includes(":")?r.split(":")[2]:r}function Dl(r){const e={};for(const[t,i]of Object.entries(r)){const s=i.methods||[],n=i.events||[],o=i.accounts||[],a=Ds(t)?[t]:i.chains?i.chains:qu(i.accounts);e[t]={chains:a,methods:s,events:n,accounts:o}}return e}function wn(r){return typeof r=="number"?r:r.includes("0x")?parseInt(r,16):(r=r.includes(":")?r.split(":")[1]:r,isNaN(Number(r))?r:Number(r))}const Fu={},Q=r=>Fu[r],bn=(r,e)=>{Fu[r]=e};var LD=Object.defineProperty,MD=(r,e,t)=>e in r?LD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,_r=(r,e,t)=>MD(r,typeof e!="symbol"?e+"":e,t);class kD{constructor(e){_r(this,"name","polkadot"),_r(this,"client"),_r(this,"httpProviders"),_r(this,"events"),_r(this,"namespace"),_r(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=fr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var zD=Object.defineProperty,HD=Object.defineProperties,VD=Object.getOwnPropertyDescriptors,Sl=Object.getOwnPropertySymbols,KD=Object.prototype.hasOwnProperty,WD=Object.prototype.propertyIsEnumerable,no=(r,e,t)=>e in r?zD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ol=(r,e)=>{for(var t in e||(e={}))KD.call(e,t)&&no(r,t,e[t]);if(Sl)for(var t of Sl(e))WD.call(e,t)&&no(r,t,e[t]);return r},Pl=(r,e)=>HD(r,VD(e)),Ir=(r,e,t)=>no(r,typeof e!="symbol"?e+"":e,t);class GD{constructor(e){Ir(this,"name","eip155"),Ir(this,"client"),Ir(this,"chainId"),Ir(this,"namespace"),Ir(this,"httpProviders"),Ir(this,"events"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){const i=t||Ge(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=parseInt(fr(t));e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,i;let s=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";s=s.startsWith("0x")?s:`0x${s}`;const n=parseInt(s,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:s}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,i,s,n,o;const a=(i=(t=e.request)==null?void 0:t.params)==null?void 0:i[0],c=((n=(s=e.request)==null?void 0:s.params)==null?void 0:n[1])||[],l=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const h=this.client.session.get(e.topic),u=((o=h==null?void 0:h.sessionProperties)==null?void 0:o.capabilities)||{};if(u!=null&&u[l])return u==null?void 0:u[l];const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Pl(Ol({},h.sessionProperties||{}),{capabilities:Pl(Ol({},u||{}),{[l]:d})})})}catch(f){console.warn("Failed to update session with capabilities",f)}return d}async getCallStatus(e){var t,i;const s=this.client.session.get(e.topic),n=(t=s.sessionProperties)==null?void 0:t.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(i=s.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var i;const s=new URL(e),n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(zt("eth_getUserOperationReceipt",[(i=t.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${nD}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var YD=Object.defineProperty,JD=(r,e,t)=>e in r?YD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Dr=(r,e,t)=>JD(r,typeof e!="symbol"?e+"":e,t);class ZD{constructor(e){Dr(this,"name","solana"),Dr(this,"client"),Dr(this,"httpProviders"),Dr(this,"events"),Dr(this,"namespace"),Dr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=fr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var QD=Object.defineProperty,XD=(r,e,t)=>e in r?QD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Sr=(r,e,t)=>XD(r,typeof e!="symbol"?e+"":e,t);class eS{constructor(e){Sr(this,"name","cosmos"),Sr(this,"client"),Sr(this,"httpProviders"),Sr(this,"events"),Sr(this,"namespace"),Sr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=fr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var tS=Object.defineProperty,rS=(r,e,t)=>e in r?tS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Or=(r,e,t)=>rS(r,typeof e!="symbol"?e+"":e,t);class iS{constructor(e){Or(this,"name","algorand"),Or(this,"client"),Or(this,"httpProviders"),Or(this,"events"),Or(this,"namespace"),Or(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const i=t||Ge(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new it(new dt(i,Q("disableProviderPing")))}}var sS=Object.defineProperty,nS=(r,e,t)=>e in r?sS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Pr=(r,e,t)=>nS(r,typeof e!="symbol"?e+"":e,t);class oS{constructor(e){Pr(this,"name","cip34"),Pr(this,"client"),Pr(this,"httpProviders"),Pr(this,"events"),Pr(this,"namespace"),Pr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const i=this.getCardanoRPCUrl(t),s=fr(t);e[s]=this.createHttpProvider(s,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var aS=Object.defineProperty,cS=(r,e,t)=>e in r?aS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,$r=(r,e,t)=>cS(r,typeof e!="symbol"?e+"":e,t);class lS{constructor(e){$r(this,"name","elrond"),$r(this,"client"),$r(this,"httpProviders"),$r(this,"events"),$r(this,"namespace"),$r(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=fr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var hS=Object.defineProperty,uS=(r,e,t)=>e in r?hS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ar=(r,e,t)=>uS(r,typeof e!="symbol"?e+"":e,t);class dS{constructor(e){Ar(this,"name","multiversx"),Ar(this,"client"),Ar(this,"httpProviders"),Ar(this,"events"),Ar(this,"namespace"),Ar(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=fr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var pS=Object.defineProperty,fS=(r,e,t)=>e in r?pS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Cr=(r,e,t)=>fS(r,typeof e!="symbol"?e+"":e,t);class gS{constructor(e){Cr(this,"name","near"),Cr(this,"client"),Cr(this,"httpProviders"),Cr(this,"events"),Cr(this,"namespace"),Cr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||Ge(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace);return typeof i>"u"?void 0:new it(new dt(i,Q("disableProviderPing")))}}var yS=Object.defineProperty,mS=(r,e,t)=>e in r?yS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,xr=(r,e,t)=>mS(r,typeof e!="symbol"?e+"":e,t);class wS{constructor(e){xr(this,"name","tezos"),xr(this,"client"),xr(this,"httpProviders"),xr(this,"events"),xr(this,"namespace"),xr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||Ge(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace);return typeof i>"u"?void 0:new it(new dt(i))}}var bS=Object.defineProperty,vS=(r,e,t)=>e in r?bS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Tr=(r,e,t)=>vS(r,typeof e!="symbol"?e+"":e,t);class ES{constructor(e){Tr(this,"name",Nr),Tr(this,"client"),Tr(this,"httpProviders"),Tr(this,"events"),Tr(this,"namespace"),Tr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const i={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(s=>{const n=qr(s);i[`${n.namespace}:${n.reference}`]=this.createHttpProvider(s)}),i}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var _S=Object.defineProperty,IS=Object.defineProperties,DS=Object.getOwnPropertyDescriptors,$l=Object.getOwnPropertySymbols,SS=Object.prototype.hasOwnProperty,OS=Object.prototype.propertyIsEnumerable,oo=(r,e,t)=>e in r?_S(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Gi=(r,e)=>{for(var t in e||(e={}))SS.call(e,t)&&oo(r,t,e[t]);if($l)for(var t of $l(e))OS.call(e,t)&&oo(r,t,e[t]);return r},vn=(r,e)=>IS(r,DS(e)),Xe=(r,e,t)=>oo(r,typeof e!="symbol"?e+"":e,t);let PS=class Lu{constructor(e){Xe(this,"client"),Xe(this,"namespaces"),Xe(this,"optionalNamespaces"),Xe(this,"sessionProperties"),Xe(this,"scopedProperties"),Xe(this,"events",new lo),Xe(this,"rpcProviders",{}),Xe(this,"session"),Xe(this,"providerOpts"),Xe(this,"logger"),Xe(this,"uri"),Xe(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:xi(Ss({level:(e==null?void 0:e.logger)||yl})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new Lu(e);return await t.initialize(),t}async request(e,t,i){const[s,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:Gi({},e),chainId:`${s}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,s){const n=new Date().getTime();this.request(e,i,s).then(o=>t(null,Os(n,o))).catch(o=>t(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:te("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:s}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await s();if(this.session=n.session,this.session){const o=Dl(this.session.namespaces);this.namespaces=Wi(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const s=await i();this.session=s;const n=Dl(s.namespaces);return this.namespaces=Wi(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,s]=this.validateChain(e),n=this.getProvider(i);n.name===Nr?n.setDefaultChain(`${i}:${s}`,t):n.setDefaultChain(s,t)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(ut(t)){for(const i of t)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,t;if(this.client=this.providerOpts.client||await K2.init({core:this.providerOpts.core,logger:this.providerOpts.logger||yl,relayUrl:this.providerOpts.relayUrl||rD,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(i){throw this.logger.error("Failed to get session",i),new Error(`The provided session: ${(t=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:t.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(t=>Br(t)))];bn("client",this.client),bn("events",this.events),bn("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=FD(t,this.session),s=qu(i),n=Wi(this.namespaces,this.optionalNamespaces),o=vn(Gi({},n[t]),{accounts:i,chains:s});switch(t){case"eip155":this.rpcProviders[t]=new GD({namespace:o});break;case"algorand":this.rpcProviders[t]=new iS({namespace:o});break;case"solana":this.rpcProviders[t]=new ZD({namespace:o});break;case"cosmos":this.rpcProviders[t]=new eS({namespace:o});break;case"polkadot":this.rpcProviders[t]=new kD({namespace:o});break;case"cip34":this.rpcProviders[t]=new oS({namespace:o});break;case"elrond":this.rpcProviders[t]=new lS({namespace:o});break;case"multiversx":this.rpcProviders[t]=new dS({namespace:o});break;case"near":this.rpcProviders[t]=new gS({namespace:o});break;case"tezos":this.rpcProviders[t]=new wS({namespace:o});break;default:this.rpcProviders[Nr]?this.rpcProviders[Nr].updateNamespace(o):this.rpcProviders[Nr]=new ES({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var t;const{topic:i}=e;i===((t=this.session)==null?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:i,topic:s}=e;if(s!==((t=this.session)==null?void 0:t.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&&ut(o)&&this.events.emit("accountsChanged",o.map(Il))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=Br(o),l=wn(o)!==wn(a)?`${c}:${wn(a)}`:o;this.onChainChanged(l)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i,s;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=t,o=(s=this.client)==null?void 0:s.session.get(e);this.session=vn(Gi({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===((t=this.session)==null?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",vn(Gi({},te("USER_DISCONNECTED")),{data:e.topic})))}),this.on(st.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Nr]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t={},optionalNamespaces:i={},sessionProperties:s,scopedProperties:n}=e;this.optionalNamespaces=Wi(t,i),this.sessionProperties=s,this.scopedProperties=n}validateChain(e){const[t,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(o=>Br(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const s=Br(Object.keys(this.namespaces)[0]),n=this.rpcProviders[s].getDefaultChain();return[s,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,t=!1){if(!this.namespaces)return;const[i,s]=this.validateChain(e);if(!s)return;this.updateNamespaceChain(i,s),this.events.emit("chainChanged",s);const n=this.getProvider(i).getDefaultChain();t||this.getProvider(i).setDefaultChain(s),this.emitAccountsChangedOnChainChange({namespace:i,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:t,newChainId:i}){var s,n;try{if(t===i)return;const o=(n=(s=this.session)==null?void 0:s.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${i}:`)).map(Il);if(!ut(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,t){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${t}`,s={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=t):this.namespaces[i]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){var i;const s=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${Vi}/${e}${s}`,t)}async getFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${Vi}/${e}${i}`)}async deleteFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${Vi}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const i of t)i.startsWith(Vi)&&await this.client.core.storage.removeItem(i)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const $S=PS,AS="wc",CS="ethereum_provider",xS=`${AS}@2:${CS}:`,TS="https://rpc.walletconnect.org/v1/",us=["eth_sendTransaction","personal_sign"],Mu=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],ds=["chainChanged","accountsChanged"],ku=["chainChanged","accountsChanged","message","disconnect","connect"],RS=async()=>{const{createAppKit:r}=await Qu(()=>import("./core-BCJdIbrO.js").then(e=>e.G),__vite__mapDeps([0,1,2,3,4,5,6]));return r};var NS=Object.defineProperty,jS=Object.defineProperties,BS=Object.getOwnPropertyDescriptors,Al=Object.getOwnPropertySymbols,US=Object.prototype.hasOwnProperty,qS=Object.prototype.propertyIsEnumerable,ao=(r,e,t)=>e in r?NS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Qt=(r,e)=>{for(var t in e||(e={}))US.call(e,t)&&ao(r,t,e[t]);if(Al)for(var t of Al(e))qS.call(e,t)&&ao(r,t,e[t]);return r},ai=(r,e)=>jS(r,BS(e)),ze=(r,e,t)=>ao(r,typeof e!="symbol"?e+"":e,t);function ps(r){return Number(r[0].split(":")[1])}function Yi(r){return`0x${r.toString(16)}`}function FS(r){const{chains:e,optionalChains:t,methods:i,optionalMethods:s,events:n,optionalEvents:o,rpcMap:a}=r;if(!ut(e))throw new Error("Invalid chains");const c={chains:e,methods:i||us,events:n||ds,rpcMap:Qt({},e.length?{[ps(e)]:a[ps(e)]}:{})},l=n==null?void 0:n.filter(f=>!ds.includes(f)),h=i==null?void 0:i.filter(f=>!us.includes(f));if(!t&&!o&&!s&&!(l!=null&&l.length)&&!(h!=null&&h.length))return{required:e.length?c:void 0};const u=(l==null?void 0:l.length)&&(h==null?void 0:h.length)||!t,d={chains:[...new Set(u?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:Mu))],events:[...new Set(c.events.concat(o!=null&&o.length?o:ku))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?d:void 0}}class xs{constructor(){ze(this,"events",new Ye.EventEmitter),ze(this,"namespace","eip155"),ze(this,"accounts",[]),ze(this,"signer"),ze(this,"chainId",1),ze(this,"modal"),ze(this,"rpc"),ze(this,"STORAGE_KEY",xS),ze(this,"on",(e,t)=>(this.events.on(e,t),this)),ze(this,"once",(e,t)=>(this.events.once(e,t),this)),ze(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),ze(this,"off",(e,t)=>(this.events.off(e,t),this)),ze(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const t=new xs;return await t.initialize(e),t}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,i){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var t;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:s}=FS(this.rpc);try{const n=await new Promise(async(a,c)=>{var l,h;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(h=this.modal)==null||h.subscribeState(d=>{!d.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const u=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(ai(Qt({namespaces:Qt({},i&&{[this.namespace]:i})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:u})).then(d=>{a(d)}).catch(d=>{var f;(f=this.modal)==null||f.showErrorMessage("Unable to connect"),c(new Error(d.message))})});if(!n)return;const o=_a(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Yi(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(t=this.modal)==null||t.close()}}async authenticate(e,t){var i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const s=await new Promise(async(o,a)=>{var c,l;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(l=this.modal)==null||l.subscribeState(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(ai(Qt({},e),{chains:this.rpc.chains}),t).then(h=>{o(h)}).catch(h=>{var u;(u=this.modal)==null||u.showErrorMessage("Unable to connect"),a(new Error(h.message))})}),n=s.session;if(n){const o=_a(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Yi(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}finally{(i=this.modal)==null||i.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:t}=e,{event:i}=t;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",Yi(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",ai(Qt({},te("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",Yi(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){const[t,i,s]=e.split(":");return{chainId:`${t}:${i}`,address:s}}setAccounts(e){this.accounts=e.filter(t=>this.parseChainId(this.parseAccountId(t).chainId)===this.chainId).map(t=>this.parseAccountId(t).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var t,i;const s=(t=e==null?void 0:e.chains)!=null?t:[],n=(i=e==null?void 0:e.optionalChains)!=null?i:[],o=s.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=s.length?(e==null?void 0:e.methods)||us:[],c=s.length?(e==null?void 0:e.events)||ds:[],l=(e==null?void 0:e.optionalMethods)||[],h=(e==null?void 0:e.optionalEvents)||[],u=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),d=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:s==null?void 0:s.map(f=>this.formatChainId(f)),optionalChains:n.map(f=>this.formatChainId(f)),methods:a,events:c,optionalMethods:l,optionalEvents:h,rpcMap:u,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:d,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const i={};return e.forEach(s=>{i[s]=this.getRpcUrl(s,t)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?ps(this.rpc.chains):ps(this.rpc.optionalChains),this.signer=await $S.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let t;try{const i=await RS(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return JS}),n=s(ai(Qt({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");t=i(ai(Qt({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(i){throw console.warn(i),new Error("To use QR modal, please install @reown/appkit package")}if(t)try{this.modal=t}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:i,rpcMap:s}=e;t&&ut(t)&&(this.rpc.chains=t.map(n=>this.formatChainId(n)),t.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)})),i&&ut(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)}))}getRpcUrl(e,t){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${TS}?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),t=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:t==null?void 0:t.accounts),this.setAccounts(t==null?void 0:t.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(t=>this.signer.logger.warn(t))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(t=>this.parseAccount(t))}}const LS=xs;var MS=Object.defineProperty,kS=Object.defineProperties,zS=Object.getOwnPropertyDescriptors,Cl=Object.getOwnPropertySymbols,HS=Object.prototype.hasOwnProperty,VS=Object.prototype.propertyIsEnumerable,xl=(r,e,t)=>e in r?MS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,zu=(r,e)=>{for(var t in e||(e={}))HS.call(e,t)&&xl(r,t,e[t]);if(Cl)for(var t of Cl(e))VS.call(e,t)&&xl(r,t,e[t]);return r},KS=(r,e)=>kS(r,zS(e));function WS(r){if(r)return{"--w3m-font-family":r["--wcm-font-family"],"--w3m-accent":r["--wcm-accent-color"],"--w3m-color-mix":r["--wcm-background-color"],"--w3m-z-index":r["--wcm-z-index"]?Number(r["--wcm-z-index"]):void 0,"--w3m-qr-color":r["--wcm-accent-color"],"--w3m-font-size-master":r["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":r["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const GS=r=>{const[e,t]=r.split(":");return Hu({id:t,caipNetworkId:r,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function YS(r){var e,t,i,s,n,o,a;const c=(e=r.chains)==null?void 0:e.map(GS).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const l=c.find(u=>{var d;return u.id===((d=r.defaultChain)==null?void 0:d.id)}),h={projectId:r.projectId,networks:c,themeMode:r.themeMode,themeVariables:WS(r.themeVariables),chainImages:r.chainImages,connectorImages:r.walletImages,defaultNetwork:l,metadata:KS(zu({},r.metadata),{name:((t=r.metadata)==null?void 0:t.name)||"WalletConnect",description:((i=r.metadata)==null?void 0:i.description)||"Connect to WalletConnect-compatible wallets",url:((s=r.metadata)==null?void 0:s.url)||"https://walletconnect.org",icons:((n=r.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:r.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(r.explorerRecommendedWalletIds)?r.explorerRecommendedWalletIds:[],excludeWalletIds:r.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(r.explorerExcludedWalletIds)?r.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=r.mobileWallets)!=null&&o.length||(a=r.desktopWallets)!=null&&a.length){const u=[...(r.mobileWallets||[]).map(p=>({id:p.id,name:p.name,links:p.links})),...(r.desktopWallets||[]).map(p=>({id:p.id,name:p.name,links:{native:p.links.native,universal:p.links.universal}}))],d=[...h.featuredWalletIds||[],...h.excludeWalletIds||[]],f=u.filter(p=>!d.includes(p.id));f.length&&(h.customWallets=f)}return h}function Hu(r){return zu({formatters:void 0,fees:void 0,serializers:void 0},r)}var JS=Object.freeze({__proto__:null,convertWCMToAppKitOptions:YS,defineChain:Hu});const UO=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:LS,OPTIONAL_EVENTS:ku,OPTIONAL_METHODS:Mu,REQUIRED_EVENTS:ds,REQUIRED_METHODS:us,default:xs},Symbol.toStringTag,{value:"Module"}));export{S0 as A,tt as B,zy as C,Xd as D,Ne as E,wt as F,dt as G,UO as H,ur as I,lo as N,xi as O,ba as P,uh as Q,Nt as a,hi as b,U as c,fd as d,Jd as e,rt as f,Ye as g,c0 as h,Rv as i,zt as j,Ss as k,jE as l,$o as m,$s as n,it as o,Os as p,Kg as q,dr as r,An as s,Le as t,jt as u,or as v,sr as w,Ps as x,Me as y,bt as z};