@dcl/landing-site 0.0.1-23620719480.commit-7d049a4 → 0.0.1-23627664864.commit-ab90df9

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 (125) hide show
  1. package/assets/{AnimatedBackground-DX3pYC8p.js → AnimatedBackground-CYoTqbYg.js} +2 -2
  2. package/assets/{CardMedia-BbWfJnV6.js → CardMedia-7CC9xG-u.js} +1 -1
  3. package/assets/{FooterLanding-B-J0C7o7.js → FooterLanding-DcARO3Qd.js} +1 -1
  4. package/assets/{WearablePreview-5a_PGNGB.js → WearablePreview-DeJtYMuc.js} +2 -2
  5. package/assets/{add-DpCWcXle.js → add-DHbFaW3u.js} +1 -1
  6. package/assets/{all-wallets-DYP41Blj.js → all-wallets-CRly5QXg.js} +1 -1
  7. package/assets/{app-store-BIJURF6-.js → app-store-Dd6WCT_k.js} +1 -1
  8. package/assets/{apple-D_uhLxZR.js → apple-DUMWFgUn.js} +1 -1
  9. package/assets/{arrow-bottom-BW6Wv-sI.js → arrow-bottom-D3mF_xvx.js} +1 -1
  10. package/assets/{arrow-bottom-circle-DqG729cm.js → arrow-bottom-circle-BIh_3DJg.js} +1 -1
  11. package/assets/{arrow-left-DKYDNC-4.js → arrow-left-D129VRuQ.js} +1 -1
  12. package/assets/{arrow-right-CUusNHsj.js → arrow-right-CXxg1hwz.js} +1 -1
  13. package/assets/{arrow-top-D-Mz_CFK.js → arrow-top-CPxziWPU.js} +1 -1
  14. package/assets/{auto-track-E6PeBcrf.js → auto-track-kunbWvCr.js} +1 -1
  15. package/assets/{bank-MJMbfg0_.js → bank-OmJu75uV.js} +1 -1
  16. package/assets/{basic-0JGqszRD.js → basic-BkHRDOzY.js} +1 -1
  17. package/assets/{browser-COSkSQBs.js → browser-vfxSWYQN.js} +1 -1
  18. package/assets/{card-DSHncbWU.js → card-BDW1ypMm.js} +1 -1
  19. package/assets/{ccip-C4IsyTPG.js → ccip-BZrSGEeq.js} +1 -1
  20. package/assets/{checkmark-DI59iwl2.js → checkmark-BBE4n-LU.js} +1 -1
  21. package/assets/{checkmark-bold-B5b_aVMV.js → checkmark-bold-BI1-8q12.js} +1 -1
  22. package/assets/{chevron-bottom-CY0ZrVMi.js → chevron-bottom-DN3JXHJC.js} +1 -1
  23. package/assets/{chevron-left-D9UeLaSu.js → chevron-left-b3Pd_sSP.js} +1 -1
  24. package/assets/{chevron-right-DYngCl4M.js → chevron-right-BHMui_hT.js} +1 -1
  25. package/assets/{chevron-top-B1oJ3Ys-.js → chevron-top-DAoSxHfQ.js} +1 -1
  26. package/assets/{chrome-store-NOx8tFXN.js → chrome-store-vh4wdNcj.js} +1 -1
  27. package/assets/{clock-Bgb07TMb.js → clock-D6IIqrof.js} +1 -1
  28. package/assets/{close-KCBaR1NE.js → close-DX8Omd0u.js} +1 -1
  29. package/assets/{coinPlaceholder-Boyy4C0R.js → coinPlaceholder-DMz1-DUJ.js} +1 -1
  30. package/assets/{compass-B9h18XpL.js → compass-K7XMUTsh.js} +1 -1
  31. package/assets/{copy-D53IumqM.js → copy-xJPvxon3.js} +1 -1
  32. package/assets/{core-R9E8jRfz.js → core-CIPjJeZT.js} +5 -5
  33. package/assets/cursor-Y1mGDx8f.js +3 -0
  34. package/assets/{cursor-transparent-DTeFmaoS.js → cursor-transparent-Bn0f80xB.js} +1 -1
  35. package/assets/{desktop-C_-SbpNe.js → desktop-C0oeOcVN.js} +1 -1
  36. package/assets/{disconnect-PiZpxCb1.js → disconnect-C7oxmOI7.js} +1 -1
  37. package/assets/{discord-Ddxf1KxO.js → discord-QAC3dvdX.js} +1 -1
  38. package/assets/{etherscan-DLwVtVtu.js → etherscan-C71BGLju.js} +1 -1
  39. package/assets/{exclamation-triangle-QRWeaoZe.js → exclamation-triangle-Ccp39NK2.js} +1 -1
  40. package/assets/{extension-DvbWY6Gw.js → extension-ySj6wMNZ.js} +1 -1
  41. package/assets/{external-link-DMiMWTiv.js → external-link-CpqJR5mf.js} +1 -1
  42. package/assets/{facebook-SSsHPp9C.js → facebook-BJcG2KPn.js} +1 -1
  43. package/assets/{farcaster-BTLGHT3x.js → farcaster-C2lHmWA5.js} +1 -1
  44. package/assets/{filters-DZsYIsNJ.js → filters-CvFDZAoQ.js} +1 -1
  45. package/assets/{github-Dcyo6j15.js → github-ClQDba3c.js} +1 -1
  46. package/assets/{google-DYxpzCSX.js → google-BQs8Rk4q.js} +1 -1
  47. package/assets/{help-circle-DNcCzixn.js → help-circle-CSU6qgLf.js} +1 -1
  48. package/assets/{id-lWMRvKeR.js → id-BgOjKVbr.js} +1 -1
  49. package/assets/{image-Dkv4odMi.js → image-DVgOnGHZ.js} +1 -1
  50. package/assets/{index-DkCEfHSR.js → index--jRmApcn.js} +1 -1
  51. package/assets/{index-Bht5LsEk.js → index-1MG74k2x.js} +1 -1
  52. package/assets/{index-RAUtC1cy.js → index-BEVc5yj4.js} +2 -2
  53. package/assets/{index-3HiQP60Y.js → index-BIS8mSuJ.js} +2 -2
  54. package/assets/{index-IP4riM96.js → index-BdRPmqMp.js} +5 -5
  55. package/assets/index-BmgO0S1h.js +1 -0
  56. package/assets/{index-UCPBu_lb.js → index-BzT5QXLw.js} +1 -1
  57. package/assets/{index-B74VE1YN.js → index-CB1axRGZ.js} +1 -1
  58. package/assets/index-CLTwTOg8.js +1 -0
  59. package/assets/{index-D3FZgr7d.js → index-CRW6kDvu.js} +49 -57
  60. package/assets/{index-DY64NG3j.js → index-CUOepIcQ.js} +3 -3
  61. package/assets/{index-CZIwBdGf.js → index-CfKUcRzX.js} +1 -1
  62. package/assets/{index-B1E2WS85.js → index-Cgt5PImj.js} +1 -1
  63. package/assets/{index-C2r3Z22e.js → index-D12flkjB.js} +1 -1
  64. package/assets/{index-CLRaSgqZ.js → index-DOLqCalu.js} +1 -1
  65. package/assets/{index-DjQ6ERI-.js → index-Dc_-7sQ8.js} +1 -1
  66. package/assets/{index-BPb2uPKM.js → index-DnXzWIMx.js} +2 -2
  67. package/assets/{index-B6eeSsO_.js → index-DxEoaOaL.js} +3 -3
  68. package/assets/{index-CiW7T_au.js → index-xE9YG-kq.js} +1 -1
  69. package/assets/{index.es--N24oLp1.js → index.es-CNLJXA6D.js} +5 -5
  70. package/assets/{index.umd-Dgcb5DdO.js → index.umd-D6-8qxXT.js} +1 -1
  71. package/assets/{info-D9Dnp2wV.js → info-BNIDDLth.js} +1 -1
  72. package/assets/{info-circle-CoOUPZNE.js → info-circle-CsWPNO91.js} +1 -1
  73. package/assets/{lightbulb-BI3j8u3m.js → lightbulb-Duth4M59.js} +1 -1
  74. package/assets/{mail-ORINOCWr.js → mail-DJJZb-md.js} +1 -1
  75. package/assets/{mobile-CeHPXPkA.js → mobile-sjZU_tg1.js} +1 -1
  76. package/assets/{more-BHYLEFMC.js → more-tWWeUqAy.js} +1 -1
  77. package/assets/{network-placeholder-Co5Aa3yr.js → network-placeholder-XvXxHqaP.js} +1 -1
  78. package/assets/{nftPlaceholder-CxGQvhMT.js → nftPlaceholder-D1dWnvdR.js} +1 -1
  79. package/assets/{node-s4RJ8AH_.js → node-DFGkk7NE.js} +1 -1
  80. package/assets/{off-0iXyYdfj.js → off-DVkbkpk2.js} +1 -1
  81. package/assets/{play-store-DTDi2JaH.js → play-store-DgORnqvy.js} +1 -1
  82. package/assets/{plus-Cy_-oevD.js → plus-Cvls8mIu.js} +1 -1
  83. package/assets/{qr-code-B6dfioLK.js → qr-code-DPgdeDca.js} +1 -1
  84. package/assets/{recycle-horizontal-pLpXl48q.js → recycle-horizontal-D-MV8FWd.js} +1 -1
  85. package/assets/{refresh-CTkry1V3.js → refresh-BVoeIx4h.js} +1 -1
  86. package/assets/{reown-logo-CQXrQocw.js → reown-logo-CWRDYcC9.js} +1 -1
  87. package/assets/{search-DcUtq8nY.js → search-BiP3_S4O.js} +1 -1
  88. package/assets/{secp256k1-DOK1Amgu.js → secp256k1-BZSFMt4U.js} +1 -1
  89. package/assets/{secp256k1-DJPw0Lkb.js → secp256k1-DKEf8DdA.js} +1 -1
  90. package/assets/{send-CsUMCf__.js → send-DzazWRTv.js} +1 -1
  91. package/assets/{swapHorizontal-DajxR-U8.js → swapHorizontal-BZxIcX5m.js} +1 -1
  92. package/assets/{swapHorizontalBold-D2-VHGIC.js → swapHorizontalBold-Dnj1e45L.js} +1 -1
  93. package/assets/{swapHorizontalMedium-BrH7SgNo.js → swapHorizontalMedium-CmGoR7Dc.js} +1 -1
  94. package/assets/{swapHorizontalRoundedBold-BNx29FQu.js → swapHorizontalRoundedBold-DRp6Ef-S.js} +1 -1
  95. package/assets/{swapVertical-Bn92nmT-.js → swapVertical-B-pC42YJ.js} +1 -1
  96. package/assets/{swiper-react-Cgkj8mB9.js → swiper-react-DDkHRCfb.js} +1 -1
  97. package/assets/{telegram-Bd7lhcuu.js → telegram-C_DslCVk.js} +1 -1
  98. package/assets/{three-dots-D4kB_6oe.js → three-dots-BGgmJEK8.js} +1 -1
  99. package/assets/{twitch-ERVkAQ9g.js → twitch-CE1S5plA.js} +1 -1
  100. package/assets/{twitterIcon-DFWSkf23.js → twitterIcon-BsFQC6I1.js} +1 -1
  101. package/assets/{verify-CFOj0EIL.js → verify-BtLzRT13.js} +1 -1
  102. package/assets/{verify-filled-8hbZ53qu.js → verify-filled-DxRG2sXM.js} +1 -1
  103. package/assets/{w3m-modal-Q-diaHtC.js → w3m-modal-Dp7eNSEb.js} +1 -1
  104. package/assets/{wallet-CJTAh7zl.js → wallet--DLCzePz.js} +1 -1
  105. package/assets/{wallet-placeholder-Dgu0MUjk.js → wallet-placeholder-CmiN70Y2.js} +1 -1
  106. package/assets/{walletconnect-SwR0ilZs.js → walletconnect-ZTHdxaJg.js} +1 -1
  107. package/assets/{warning-circle-DqGA6JWs.js → warning-circle-DyXukdsn.js} +1 -1
  108. package/assets/{x-Bhp20IfI.js → x-BQ8elQCH.js} +1 -1
  109. package/avatar_face.webp +0 -0
  110. package/catch_the_vibe/alan.webp +0 -0
  111. package/catch_the_vibe/roustan.webp +0 -0
  112. package/come_hang_out_background.webp +0 -0
  113. package/index.html +4 -3
  114. package/jump_into_background.webp +0 -0
  115. package/landing_hero.webp +0 -0
  116. package/package.json +3 -3
  117. package/persona.webp +0 -0
  118. package/assets/cursor-CV1p_vON.js +0 -3
  119. package/assets/index-B9flaZuC.js +0 -1
  120. package/assets/index-D12nVzQv.js +0 -1
  121. package/avatar_face.png +0 -0
  122. package/come_hang_out_background.png +0 -0
  123. package/jump_into_background.png +0 -0
  124. package/landing_hero.png +0 -0
  125. package/persona.png +0 -0
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/secp256k1-DOK1Amgu.js","assets/index-D3FZgr7d.js","assets/index-nibyPLVP.js","assets/core-R9E8jRfz.js","assets/node-s4RJ8AH_.js"])))=>i.map(i=>d[i]);
2
- import{N as fh,P as ri,p as ft,f as At,g as H,h as dh,Q as Ce}from"./index-D3FZgr7d.js";import{c as gg,g as Za,s as yg,d as mg,k as wg,a as vg}from"./index-nibyPLVP.js";var fa={exports:{}},rn=typeof Reflect=="object"?Reflect:null,Qa=rn&&typeof rn.apply=="function"?rn.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Ci;rn&&typeof rn.ownKeys=="function"?Ci=rn.ownKeys:Object.getOwnPropertySymbols?Ci=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Ci=function(e){return Object.getOwnPropertyNames(e)};function bg(t){console&&console.warn&&console.warn(t)}var ph=Number.isNaN||function(e){return e!==e};function ne(){ne.init.call(this)}fa.exports=ne;fa.exports.once=Og;ne.EventEmitter=ne;ne.prototype._events=void 0;ne.prototype._eventsCount=0;ne.prototype._maxListeners=void 0;var Xa=10;function os(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ne,"defaultMaxListeners",{enumerable:!0,get:function(){return Xa},set:function(t){if(typeof t!="number"||t<0||ph(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Xa=t}});ne.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};ne.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||ph(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function gh(t){return t._maxListeners===void 0?ne.defaultMaxListeners:t._maxListeners}ne.prototype.getMaxListeners=function(){return gh(this)};ne.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")Qa(c,this,r);else for(var u=c.length,l=bh(c,u),n=0;n<u;++n)Qa(l[n],this,r);return!0};function yh(t,e,r,n){var i,s,o;if(os(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=gh(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,bg(a)}return t}ne.prototype.addListener=function(e,r){return yh(this,e,r,!1)};ne.prototype.on=ne.prototype.addListener;ne.prototype.prependListener=function(e,r){return yh(this,e,r,!0)};function Eg(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function mh(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=Eg.bind(n);return i.listener=r,n.wrapFn=i,i}ne.prototype.once=function(e,r){return os(r),this.on(e,mh(this,e,r)),this};ne.prototype.prependOnceListener=function(e,r){return os(r),this.prependListener(e,mh(this,e,r)),this};ne.prototype.removeListener=function(e,r){var n,i,s,o,a;if(os(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():_g(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};ne.prototype.off=ne.prototype.removeListener;ne.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function wh(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?$g(i):bh(i,i.length)}ne.prototype.listeners=function(e){return wh(this,e,!0)};ne.prototype.rawListeners=function(e){return wh(this,e,!1)};ne.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):vh.call(t,e)};ne.prototype.listenerCount=vh;function vh(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}ne.prototype.eventNames=function(){return this._eventsCount>0?Ci(this._events):[]};function bh(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function _g(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function $g(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function Og(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Eh(t,e,s,{once:!0}),e!=="error"&&Ig(t,i,{once:!0})})}function Ig(t,e,r){typeof t.on=="function"&&Eh(t,"error",e,r)}function Eh(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var Pg=fa.exports,T={};/*! *****************************************************************************
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/secp256k1-BZSFMt4U.js","assets/index-CRW6kDvu.js","assets/index-nibyPLVP.js","assets/core-CIPjJeZT.js","assets/node-DFGkk7NE.js"])))=>i.map(i=>d[i]);
2
+ import{N as fh,P as ri,p as ft,f as At,g as H,h as dh,Q as Ce}from"./index-CRW6kDvu.js";import{c as gg,g as Za,s as yg,d as mg,k as wg,a as vg}from"./index-nibyPLVP.js";var fa={exports:{}},rn=typeof Reflect=="object"?Reflect:null,Qa=rn&&typeof rn.apply=="function"?rn.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Ci;rn&&typeof rn.ownKeys=="function"?Ci=rn.ownKeys:Object.getOwnPropertySymbols?Ci=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Ci=function(e){return Object.getOwnPropertyNames(e)};function bg(t){console&&console.warn&&console.warn(t)}var ph=Number.isNaN||function(e){return e!==e};function ne(){ne.init.call(this)}fa.exports=ne;fa.exports.once=Og;ne.EventEmitter=ne;ne.prototype._events=void 0;ne.prototype._eventsCount=0;ne.prototype._maxListeners=void 0;var Xa=10;function os(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ne,"defaultMaxListeners",{enumerable:!0,get:function(){return Xa},set:function(t){if(typeof t!="number"||t<0||ph(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Xa=t}});ne.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};ne.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||ph(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function gh(t){return t._maxListeners===void 0?ne.defaultMaxListeners:t._maxListeners}ne.prototype.getMaxListeners=function(){return gh(this)};ne.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")Qa(c,this,r);else for(var u=c.length,l=bh(c,u),n=0;n<u;++n)Qa(l[n],this,r);return!0};function yh(t,e,r,n){var i,s,o;if(os(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=gh(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,bg(a)}return t}ne.prototype.addListener=function(e,r){return yh(this,e,r,!1)};ne.prototype.on=ne.prototype.addListener;ne.prototype.prependListener=function(e,r){return yh(this,e,r,!0)};function Eg(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function mh(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=Eg.bind(n);return i.listener=r,n.wrapFn=i,i}ne.prototype.once=function(e,r){return os(r),this.on(e,mh(this,e,r)),this};ne.prototype.prependOnceListener=function(e,r){return os(r),this.prependListener(e,mh(this,e,r)),this};ne.prototype.removeListener=function(e,r){var n,i,s,o,a;if(os(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():_g(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};ne.prototype.off=ne.prototype.removeListener;ne.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function wh(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?$g(i):bh(i,i.length)}ne.prototype.listeners=function(e){return wh(this,e,!0)};ne.prototype.rawListeners=function(e){return wh(this,e,!1)};ne.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):vh.call(t,e)};ne.prototype.listenerCount=vh;function vh(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}ne.prototype.eventNames=function(){return this._eventsCount>0?Ci(this._events):[]};function bh(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function _g(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function $g(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function Og(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Eh(t,e,s,{once:!0}),e!=="error"&&Ig(t,i,{once:!0})})}function Ig(t,e,r){typeof t.on=="function"&&Eh(t,"error",e,r)}function Eh(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var Pg=fa.exports,T={};/*! *****************************************************************************
3
3
  Copyright (c) Microsoft Corporation.
4
4
 
5
5
  Permission to use, copy, modify, and/or distribute this software for any
@@ -26,7 +26,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
26
26
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
27
27
  PERFORMANCE OF THIS SOFTWARE.
28
28
  ***************************************************************************** */var Lo=function(t,e){return Lo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},Lo(t,e)};function h0(t,e){Lo(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Ro=function(){return Ro=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},Ro.apply(this,arguments)};function f0(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function d0(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function p0(t,e){return function(r,n){e(r,n,t)}}function g0(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function y0(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(l){try{u(n.next(l))}catch(h){o(h)}}function c(l){try{u(n.throw(l))}catch(h){o(h)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((n=n.apply(t,e||[])).next())})}function m0(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,i=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],i=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function w0(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function v0(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function To(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function bf(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function b0(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(bf(arguments[e]));return t}function E0(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function Yn(t){return this instanceof Yn?(this.v=t,this):new Yn(t)}function _0(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(f){n[f]&&(i[f]=function(p){return new Promise(function(d,y){s.push([f,p,d,y])>1||a(f,p)})})}function a(f,p){try{c(n[f](p))}catch(d){h(s[0][3],d)}}function c(f){f.value instanceof Yn?Promise.resolve(f.value.v).then(u,l):h(s[0][2],f)}function u(f){a("next",f)}function l(f){a("throw",f)}function h(f,p){f(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function $0(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:Yn(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function O0(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof To=="function"?To(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function I0(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function P0(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function S0(t){return t&&t.__esModule?t:{default:t}}function D0(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function x0(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}const A0=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Ro},__asyncDelegator:$0,__asyncGenerator:_0,__asyncValues:O0,__await:Yn,__awaiter:y0,__classPrivateFieldGet:D0,__classPrivateFieldSet:x0,__createBinding:w0,__decorate:d0,__exportStar:v0,__extends:h0,__generator:m0,__importDefault:S0,__importStar:P0,__makeTemplateObject:I0,__metadata:g0,__param:p0,__read:bf,__rest:f0,__spread:b0,__spreadArrays:E0,__values:To},Symbol.toStringTag,{value:"Module"})),C0=fh(A0);var Bt={},kc;function L0(){if(kc)return Bt;kc=1,Object.defineProperty(Bt,"__esModule",{value:!0}),Bt.isBrowserCryptoAvailable=Bt.getSubtleCrypto=Bt.getBrowerCrypto=void 0;function t(){return(At===null||At===void 0?void 0:At.crypto)||(At===null||At===void 0?void 0:At.msCrypto)||{}}Bt.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}Bt.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Bt.isBrowserCryptoAvailable=r,Bt}var Ut={},qc;function R0(){if(qc)return Ut;qc=1,Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.isBrowser=Ut.isNode=Ut.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ut.isReactNative=t;function e(){return typeof ft<"u"&&typeof ft.versions<"u"&&typeof ft.versions.node<"u"}Ut.isNode=e;function r(){return!t()&&!e()}return Ut.isBrowser=r,Ut}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=C0;e.__exportStar(L0(),t),e.__exportStar(R0(),t)})(vf);function Dt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function gr(t=6){return BigInt(Dt(t))}function er(t,e,r){return{id:r||Dt(),jsonrpc:"2.0",method:t,params:e}}function gs(t,e){return{id:t,jsonrpc:"2.0",result:e}}function ys(t,e,r){return{id:t,jsonrpc:"2.0",error:T0(e)}}function T0(t,e){return typeof t>"u"?Fc(yf):(typeof t=="string"&&(t=Object.assign(Object.assign({},Fc(Oa)),{message:t})),u0(t.code)&&(t=l0(t.code)),t)}class N0{}class j0 extends N0{constructor(){super()}}class M0 extends j0{constructor(e){super()}}const B0="^https?:",U0="^wss?:";function F0(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Ef(t,e){const r=F0(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function zc(t){return Ef(t,B0)}function Hc(t){return Ef(t,U0)}function k0(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function _f(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Ia(t){return _f(t)&&"method"in t}function ms(t){return _f(t)&&(xt(t)||lt(t))}function xt(t){return"result"in t}function lt(t){return"error"in t}let dt=class extends M0{constructor(e){super(e),this.events=new n0.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,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(er(e.method,e.params||[],e.id||gr().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{lt(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ms(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)}};var Pa={exports:{}},sn=typeof Reflect=="object"?Reflect:null,Kc=sn&&typeof sn.apply=="function"?sn.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Ti;sn&&typeof sn.ownKeys=="function"?Ti=sn.ownKeys:Object.getOwnPropertySymbols?Ti=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Ti=function(e){return Object.getOwnPropertyNames(e)};function q0(t){console&&console.warn&&console.warn(t)}var $f=Number.isNaN||function(e){return e!==e};function se(){se.init.call(this)}Pa.exports=se;Pa.exports.once=V0;se.EventEmitter=se;se.prototype._events=void 0;se.prototype._eventsCount=0;se.prototype._maxListeners=void 0;var Vc=10;function ws(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(se,"defaultMaxListeners",{enumerable:!0,get:function(){return Vc},set:function(t){if(typeof t!="number"||t<0||$f(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Vc=t}});se.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};se.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||$f(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Of(t){return t._maxListeners===void 0?se.defaultMaxListeners:t._maxListeners}se.prototype.getMaxListeners=function(){return Of(this)};se.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")Kc(c,this,r);else for(var u=c.length,l=xf(c,u),n=0;n<u;++n)Kc(l[n],this,r);return!0};function If(t,e,r,n){var i,s,o;if(ws(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=Of(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,q0(a)}return t}se.prototype.addListener=function(e,r){return If(this,e,r,!1)};se.prototype.on=se.prototype.addListener;se.prototype.prependListener=function(e,r){return If(this,e,r,!0)};function z0(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Pf(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=z0.bind(n);return i.listener=r,n.wrapFn=i,i}se.prototype.once=function(e,r){return ws(r),this.on(e,Pf(this,e,r)),this};se.prototype.prependOnceListener=function(e,r){return ws(r),this.prependListener(e,Pf(this,e,r)),this};se.prototype.removeListener=function(e,r){var n,i,s,o,a;if(ws(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():H0(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};se.prototype.off=se.prototype.removeListener;se.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function Sf(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?K0(i):xf(i,i.length)}se.prototype.listeners=function(e){return Sf(this,e,!0)};se.prototype.rawListeners=function(e){return Sf(this,e,!1)};se.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Df.call(t,e)};se.prototype.listenerCount=Df;function Df(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}se.prototype.eventNames=function(){return this._eventsCount>0?Ti(this._events):[]};function xf(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function H0(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function K0(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function V0(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Af(t,e,s,{once:!0}),e!=="error"&&W0(t,i,{once:!0})})}function W0(t,e,r){typeof t.on=="function"&&Af(t,"error",e,r)}function Af(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var G0=Pa.exports;const Y0=()=>typeof WebSocket<"u"?WebSocket:typeof H<"u"&&typeof H.WebSocket<"u"?H.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),J0=()=>typeof WebSocket<"u"||typeof H<"u"&&typeof H.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Wc=t=>t.split("?")[0],Gc=10,Z0=Y0();let Q0=class{constructor(e){if(this.url=e,this.events=new G0.EventEmitter,this.registering=!1,!Hc(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,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Wt(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Hc(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=vf.isReactNative()?void 0:{rejectUnauthorized:!k0(e)},s=new Z0(e,[],i);J0()?s.onerror=o=>{const a=o;n(this.emitError(a.error))}:s.on("error",o=>{n(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),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 r=typeof e.data=="string"?wr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=ys(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return wf(e,Wc(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Gc&&this.events.setMaxListeners(Gc)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Wc(this.url)}`));return this.events.emit("register_error",r),r}};var Sa={exports:{}},on=typeof Reflect=="object"?Reflect:null,Yc=on&&typeof on.apply=="function"?on.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Ni;on&&typeof on.ownKeys=="function"?Ni=on.ownKeys:Object.getOwnPropertySymbols?Ni=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Ni=function(e){return Object.getOwnPropertyNames(e)};function X0(t){console&&console.warn&&console.warn(t)}var Cf=Number.isNaN||function(e){return e!==e};function oe(){oe.init.call(this)}Sa.exports=oe;Sa.exports.once=nE;oe.EventEmitter=oe;oe.prototype._events=void 0;oe.prototype._eventsCount=0;oe.prototype._maxListeners=void 0;var Jc=10;function vs(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(oe,"defaultMaxListeners",{enumerable:!0,get:function(){return Jc},set:function(t){if(typeof t!="number"||t<0||Cf(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Jc=t}});oe.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};oe.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Cf(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Lf(t){return t._maxListeners===void 0?oe.defaultMaxListeners:t._maxListeners}oe.prototype.getMaxListeners=function(){return Lf(this)};oe.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")Yc(c,this,r);else for(var u=c.length,l=Mf(c,u),n=0;n<u;++n)Yc(l[n],this,r);return!0};function Rf(t,e,r,n){var i,s,o;if(vs(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=Lf(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,X0(a)}return t}oe.prototype.addListener=function(e,r){return Rf(this,e,r,!1)};oe.prototype.on=oe.prototype.addListener;oe.prototype.prependListener=function(e,r){return Rf(this,e,r,!0)};function eE(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Tf(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=eE.bind(n);return i.listener=r,n.wrapFn=i,i}oe.prototype.once=function(e,r){return vs(r),this.on(e,Tf(this,e,r)),this};oe.prototype.prependOnceListener=function(e,r){return vs(r),this.prependListener(e,Tf(this,e,r)),this};oe.prototype.removeListener=function(e,r){var n,i,s,o,a;if(vs(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():tE(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};oe.prototype.off=oe.prototype.removeListener;oe.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function Nf(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?rE(i):Mf(i,i.length)}oe.prototype.listeners=function(e){return Nf(this,e,!0)};oe.prototype.rawListeners=function(e){return Nf(this,e,!1)};oe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):jf.call(t,e)};oe.prototype.listenerCount=jf;function jf(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}oe.prototype.eventNames=function(){return this._eventsCount>0?Ni(this._events):[]};function Mf(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function tE(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function rE(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function nE(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Bf(t,e,s,{once:!0}),e!=="error"&&iE(t,i,{once:!0})})}function iE(t,e,r){typeof t.on=="function"&&Bf(t,"error",e,r)}function Bf(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var sE=Sa.exports;function Jn(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function Zc(t){return Jn(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const Uf="2.23.2";let Ys={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:r})=>e?`${t??"https://viem.sh"}${e}${r?`#${r}`:""}`:void 0,version:`viem@${Uf}`};class br extends Error{constructor(e,r={}){const n=r.cause instanceof br?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof br&&r.cause.docsPath||r.docsPath,s=Ys.getDocsUrl?.({...r,docsPath:i}),o=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...Ys.version?[`Version: ${Ys.version}`]:[]].join(`
29
- `);super(o,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=e,this.version=Uf}walk(e){return Ff(this,e)}}function Ff(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Ff(t.cause,e):e?null:t}class kf extends br{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}}function _n(t,{dir:e,size:r=32}={}){return typeof t=="string"?oE(t,{dir:e,size:r}):aE(t,{dir:e,size:r})}function oE(t,{dir:e,size:r=32}={}){if(r===null)return t;const n=t.replace("0x","");if(n.length>r*2)throw new kf({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function aE(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new kf({size:t.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let i=0;i<r;i++){const s=e==="right";n[s?i:r-i-1]=t[s?i:t.length-i-1]}return n}class cE extends br{constructor({max:e,min:r,signed:n,size:i,value:s}){super(`Number "${s}" is not in safe ${i?`${i*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${r} to ${e})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}}class uE extends br{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function $n(t,{size:e}){if(Zc(t)>e)throw new uE({givenSize:Zc(t),maxSize:e})}function No(t,e={}){const{signed:r}=e;e.size&&$n(t,{size:e.size});const n=BigInt(t);if(!r)return n;const i=(t.length-2)/2,s=(1n<<BigInt(i)*8n-1n)-1n;return n<=s?n:n-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function lE(t,e={}){return Number(No(t,e))}const hE=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function jo(t,e={}){return typeof t=="number"||typeof t=="bigint"?zf(t,e):typeof t=="string"?pE(t,e):typeof t=="boolean"?fE(t,e):qf(t,e)}function fE(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?($n(r,{size:e.size}),_n(r,{size:e.size})):r}function qf(t,e={}){let r="";for(let i=0;i<t.length;i++)r+=hE[t[i]];const n=`0x${r}`;return typeof e.size=="number"?($n(n,{size:e.size}),_n(n,{dir:"right",size:e.size})):n}function zf(t,e={}){const{signed:r,size:n}=e,i=BigInt(t);let s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&r?-s-1n:0;if(s&&i>s||i<o){const c=typeof t=="bigint"?"n":"";throw new cE({max:s?`${s}${c}`:void 0,min:`${o}${c}`,signed:r,size:n,value:`${t}${c}`})}const a=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?_n(a,{size:n}):a}const dE=new TextEncoder;function pE(t,e={}){const r=dE.encode(t);return qf(r,e)}const gE=new TextEncoder;function yE(t,e={}){return typeof t=="number"||typeof t=="bigint"?wE(t,e):typeof t=="boolean"?mE(t,e):Jn(t)?Hf(t,e):Kf(t,e)}function mE(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?($n(r,{size:e.size}),_n(r,{size:e.size})):r}const Ft={zero:48,nine:57,A:65,F:70,a:97,f:102};function Qc(t){if(t>=Ft.zero&&t<=Ft.nine)return t-Ft.zero;if(t>=Ft.A&&t<=Ft.F)return t-(Ft.A-10);if(t>=Ft.a&&t<=Ft.f)return t-(Ft.a-10)}function Hf(t,e={}){let r=t;e.size&&($n(r,{size:e.size}),r=_n(r,{dir:"right",size:e.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const i=n.length/2,s=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const c=Qc(n.charCodeAt(a++)),u=Qc(n.charCodeAt(a++));if(c===void 0||u===void 0)throw new br(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);s[o]=c*16+u}return s}function wE(t,e){const r=zf(t,e);return Hf(r)}function Kf(t,e={}){const r=gE.encode(t);return typeof e.size=="number"?($n(r,{size:e.size}),_n(r,{dir:"right",size:e.size})):r}function Zi(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function vE(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function bs(t,...e){if(!vE(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function zC(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Zi(t.outputLen),Zi(t.blockLen)}function Xc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function bE(t,e){bs(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const vi=BigInt(2**32-1),eu=BigInt(32);function EE(t,e=!1){return e?{h:Number(t&vi),l:Number(t>>eu&vi)}:{h:Number(t>>eu&vi)|0,l:Number(t&vi)|0}}function _E(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:s,l:o}=EE(t[i],e);[r[i],n[i]]=[s,o]}return[r,n]}const $E=(t,e,r)=>t<<r|e>>>32-r,OE=(t,e,r)=>e<<r|t>>>32-r,IE=(t,e,r)=>e<<r-32|t>>>64-r,PE=(t,e,r)=>t<<r-32|e>>>64-r,Nr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function SE(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function HC(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function KC(t,e){return t<<32-e|t>>>e}const tu=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function DE(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function ru(t){for(let e=0;e<t.length;e++)t[e]=DE(t[e])}function xE(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Vf(t){return typeof t=="string"&&(t=xE(t)),bs(t),t}function VC(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];bs(i),e+=i.length}const r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){const s=t[n];r.set(s,i),i+=s.length}return r}class AE{clone(){return this._cloneInto()}}function CE(t){const e=n=>t().update(Vf(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function WC(t=32){if(Nr&&typeof Nr.getRandomValues=="function")return Nr.getRandomValues(new Uint8Array(t));if(Nr&&typeof Nr.randomBytes=="function")return Nr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const Wf=[],Gf=[],Yf=[],LE=BigInt(0),Cn=BigInt(1),RE=BigInt(2),TE=BigInt(7),NE=BigInt(256),jE=BigInt(113);for(let t=0,e=Cn,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],Wf.push(2*(5*n+r)),Gf.push((t+1)*(t+2)/2%64);let i=LE;for(let s=0;s<7;s++)e=(e<<Cn^(e>>TE)*jE)%NE,e&RE&&(i^=Cn<<(Cn<<BigInt(s))-Cn);Yf.push(i)}const[ME,BE]=_E(Yf,!0),nu=(t,e,r)=>r>32?IE(t,e,r):$E(t,e,r),iu=(t,e,r)=>r>32?PE(t,e,r):OE(t,e,r);function UE(t,e=24){const r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=r[c],l=r[c+1],h=nu(u,l,1)^r[a],f=iu(u,l,1)^r[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=f}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=Gf[o],c=nu(i,s,a),u=iu(i,s,a),l=Wf[o];i=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=ME[n],t[1]^=BE[n]}r.fill(0)}class Da extends AE{constructor(e,r,n,i=!1,s=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Zi(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=SE(this.state)}keccak(){tu||ru(this.state32),UE(this.state32,this.rounds),tu||ru(this.state32),this.posOut=0,this.pos=0}update(e){Xc(this);const{blockLen:r,state:n}=this;e=Vf(e);const i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);for(let a=0;a<o;a++)n[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:n,blockLen:i}=this;e[n]^=r,r&128&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){Xc(this,!1),bs(e),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,s=e.length;i<s;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,s-i);e.set(r.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Zi(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(bE(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new Da(r,n,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const FE=(t,e,r)=>CE(()=>new Da(e,t,r)),kE=FE(1,136,256/8);function Jf(t,e){const r=e||"hex",n=kE(Jn(t,{strict:!1})?yE(t):t);return r==="bytes"?n:jo(n)}class qE extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const Js=new qE(8192);function zE(t,e){if(Js.has(`${t}.${e}`))return Js.get(`${t}.${e}`);const r=t.substring(2).toLowerCase(),n=Jf(Kf(r),"bytes"),i=r.split("");for(let o=0;o<40;o+=2)n[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(n[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const s=`0x${i.join("")}`;return Js.set(`${t}.${e}`,s),s}function HE(t){const e=Jf(`0x${t.substring(4)}`).substring(26);return zE(`0x${e}`)}async function KE({hash:t,signature:e}){const r=Jn(t)?t:jo(t),{secp256k1:n}=await dh(async()=>{const{secp256k1:o}=await import("./secp256k1-DOK1Amgu.js");return{secp256k1:o}},__vite__mapDeps([0,1,2]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:h,yParity:f}=e,p=Number(f??h),d=su(p);return new n.Signature(No(u),No(l)).addRecoveryBit(d)}const o=Jn(e)?e:jo(e),a=lE(`0x${o.slice(130)}`),c=su(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function su(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function VE({hash:t,signature:e}){return HE(await KE({hash:t,signature:e}))}function WE(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let u=0;u<e.length;u++)e[u]=255;for(let u=0;u<t.length;u++){const l=t.charAt(u),h=l.charCodeAt(0);if(e[h]!==255)throw new TypeError(l+" is ambiguous");e[h]=u}const r=t.length,n=t.charAt(0),i=Math.log(r)/Math.log(256),s=Math.log(256)/Math.log(r);function o(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";let l=0,h=0,f=0;const p=u.length;for(;f!==p&&u[f]===0;)f++,l++;const d=(p-f)*s+1>>>0,y=new Uint8Array(d);for(;f!==p;){let v=u[f],E=0;for(let O=d-1;(v!==0||E<h)&&O!==-1;O--,E++)v+=256*y[O]>>>0,y[O]=v%r>>>0,v=v/r>>>0;if(v!==0)throw new Error("Non-zero carry");h=E,f++}let w=d-h;for(;w!==d&&y[w]===0;)w++;let b=n.repeat(l);for(;w<d;++w)b+=t.charAt(y[w]);return b}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,h=0,f=0;for(;u[l]===n;)h++,l++;const p=(u.length-l)*i+1>>>0,d=new Uint8Array(p);for(;l<u.length;){const v=u.charCodeAt(l);if(v>255)return;let E=e[v];if(E===255)return;let O=0;for(let x=p-1;(E!==0||O<f)&&x!==-1;x--,O++)E+=r*d[x]>>>0,d[x]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");f=O,l++}let y=p-f;for(;y!==p&&d[y]===0;)y++;const w=new Uint8Array(h+(p-y));let b=h;for(;y!==p;)w[b++]=d[y++];return w}function c(u){const l=a(u);if(l)return l;throw new Error("Non-base"+r+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var GE="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const YE=WE(GE);function Zf(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function qn(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const r=Zf(e);let n=0;for(const i of t)r.set(i,n),n+=i.length;return r}function Qf(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const ou=Qf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Zs=Qf("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=Zf(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Xf={utf8:ou,"utf-8":ou,hex:Mc.base16,latin1:Zs,ascii:Zs,binary:Zs,...Mc};function ht(t,e="utf8"){const r=Xf[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}function Ze(t,e="utf8"){const r=Xf[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}var JE={VITE_BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23620719480.commit-7d049a4"};const ZE=":";function an(t){const[e,r]=t.split(ZE);return{namespace:e,reference:r}}function au(t,e=[]){const r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;const i=t[n];r.push(...i.accounts)}),r}function ed(t,e){return t.includes(":")?[t]:e.chains||[]}var QE=Object.defineProperty,XE=Object.defineProperties,e1=Object.getOwnPropertyDescriptors,cu=Object.getOwnPropertySymbols,t1=Object.prototype.hasOwnProperty,r1=Object.prototype.propertyIsEnumerable,uu=(t,e,r)=>e in t?QE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,lu=(t,e)=>{for(var r in e||(e={}))t1.call(e,r)&&uu(t,r,e[r]);if(cu)for(var r of cu(e))r1.call(e,r)&&uu(t,r,e[r]);return t},n1=(t,e)=>XE(t,e1(e));const i1="ReactNative",it={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},s1="js";function Qi(){return typeof ft<"u"&&typeof ft.versions<"u"&&typeof ft.versions.node<"u"}function ir(){return!vr()&&!!Ea()&&navigator.product===i1}function o1(){return ir()&&typeof H<"u"&&typeof(H==null?void 0:H.Platform)<"u"&&(H==null?void 0:H.Platform.OS)==="android"}function a1(){return ir()&&typeof H<"u"&&typeof(H==null?void 0:H.Platform)<"u"&&(H==null?void 0:H.Platform.OS)==="ios"}function On(){return!Qi()&&!!Ea()&&!!vr()}function ai(){return ir()?it.reactNative:Qi()?it.node:On()?it.browser:it.unknown}function hu(){var t;try{return ir()&&typeof H<"u"&&typeof(H==null?void 0:H.Application)<"u"?(t=H.Application)==null?void 0:t.applicationId:void 0}catch{return}}function c1(t,e){const r=new URLSearchParams(t);for(const n of Object.keys(e).sort())if(e.hasOwnProperty(n)){const i=e[n];i!==void 0&&r.set(n,i)}return r.toString()}function u1(t){var e,r;const n=td();try{return t!=null&&t.url&&n.url&&new URL(t.url).host!==new URL(n.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${n.url}. This is probably unintended and can lead to issues.`),t.url=n.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(i=>i!=="")),n1(lu(lu({},n),t),{url:t?.url||n.url,name:t?.name||n.name,description:t?.description||n.description,icons:(r=t?.icons)!=null&&r.length&&t.icons.length>0?t.icons:n.icons})}catch(i){return console.warn("Error populating app metadata",i),t||n}}function td(){return sf()||{name:"",description:"",url:"",icons:[""]}}function l1(){if(ai()===it.reactNative&&typeof H<"u"&&typeof(H==null?void 0:H.Platform)<"u"){const{OS:r,Version:n}=H.Platform;return[r,n].join("-")}const t=Mv();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function h1(){var t;const e=ai();return e===it.browser?[e,((t=nf())==null?void 0:t.host)||"unknown"].join(":"):e}function rd(t,e,r){const n=l1(),i=h1();return[[t,e].join("-"),[s1,r].join("-"),n,i].join("/")}function f1({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=r.split("?"),l=rd(t,e,n),h={auth:i,ua:l,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},f=c1(u[1]||"",h);return u[0]+"?"+f}function yr(t,e){return t.filter(r=>e.includes(r)).length===t.length}function Mo(t){return Object.fromEntries(t.entries())}function Bo(t){return new Map(Object.entries(t))}function ur(t=T.FIVE_MINUTES,e){const r=T.toMiliseconds(t||T.FIVE_MINUTES);let n,i,s,o;return{resolve:a=>{s&&n&&(clearTimeout(s),n(a),o=Promise.resolve(a))},reject:a=>{s&&i&&(clearTimeout(s),i(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);s=setTimeout(()=>{const u=new Error(e);o=Promise.reject(u),c(u)},r),n=a,i=c})}}function tr(t,e,r){return new Promise(async(n,i)=>{const s=setTimeout(()=>i(new Error(r)),e);try{const o=await t;n(o)}catch(o){i(o)}clearTimeout(s)})}function nd(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function d1(t){return nd("topic",t)}function p1(t){return nd("id",t)}function id(t){const[e,r]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")n.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return n}function _e(t,e){return T.fromMiliseconds(Date.now()+T.toMiliseconds(t))}function Qt(t){return Date.now()>=T.toMiliseconds(t)}function ee(t,e){return`${t}${e?`:${e}`:""}`}function Rt(t=[],e=[]){return[...new Set([...t,...e])]}async function g1({id:t,topic:e,wcDeepLink:r}){var n;try{if(!r)return;const i=typeof r=="string"?JSON.parse(r):r,s=i?.href;if(typeof s!="string")return;const o=y1(s,t,e),a=ai();if(a===it.browser){if(!((n=vr())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}m1(o)}else a===it.reactNative&&typeof(H==null?void 0:H.Linking)<"u"&&await H.Linking.openURL(o)}catch(i){console.error(i)}}function y1(t,e,r){const n=`requestId=${e}&sessionTopic=${r}`;t.endsWith("/")&&(t=t.slice(0,-1));let i=`${t}`;if(t.startsWith("https://t.me")){const s=t.includes("?")?"&startapp=":"?startapp=";i=`${i}${s}${E1(n,!0)}`}else i=`${i}/wc?${n}`;return i}function m1(t){let e="_self";b1()?e="_top":(v1()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function w1(t,e){let r="";try{if(On()&&(r=localStorage.getItem(e),r))return r;r=await t.getItem(e)}catch(n){console.error(n)}return r}function fu(t,e){if(!t.includes(e))return null;const r=t.split(/([&,?,=])/),n=r.indexOf(e);return r[n+2]}function du(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function xa(){return typeof ft<"u"&&JE.IS_VITEST==="true"}function v1(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function b1(){try{return window.self!==window.top}catch{return!1}}function E1(t,e=!1){const r=Ce.from(t).toString("base64");return e?r.replace(/[=]/g,""):r}function sd(t){return Ce.from(t,"base64").toString("utf-8")}function _1(t){return new Promise(e=>setTimeout(e,t))}function Zn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function $1(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ci(t,...e){if(!$1(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Aa(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Zn(t.outputLen),Zn(t.blockLen)}function dn(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function od(t,e){ci(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const bi=BigInt(2**32-1),pu=BigInt(32);function O1(t,e=!1){return e?{h:Number(t&bi),l:Number(t>>pu&bi)}:{h:Number(t>>pu&bi)|0,l:Number(t&bi)|0}}function I1(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:s,l:o}=O1(t[i],e);[r[i],n[i]]=[s,o]}return[r,n]}const P1=(t,e,r)=>t<<r|e>>>32-r,S1=(t,e,r)=>e<<r|t>>>32-r,D1=(t,e,r)=>e<<r-32|t>>>64-r,x1=(t,e,r)=>t<<r-32|e>>>64-r,jr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function A1(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Qs(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Ot(t,e){return t<<32-e|t>>>e}const gu=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function C1(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function yu(t){for(let e=0;e<t.length;e++)t[e]=C1(t[e])}function L1(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function pn(t){return typeof t=="string"&&(t=L1(t)),ci(t),t}function R1(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];ci(i),e+=i.length}const r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){const s=t[n];r.set(s,i),i+=s.length}return r}let Ca=class{clone(){return this._cloneInto()}};function ad(t){const e=n=>t().update(pn(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function In(t=32){if(jr&&typeof jr.getRandomValues=="function")return jr.getRandomValues(new Uint8Array(t));if(jr&&typeof jr.randomBytes=="function")return jr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const cd=[],ud=[],ld=[],T1=BigInt(0),Ln=BigInt(1),N1=BigInt(2),j1=BigInt(7),M1=BigInt(256),B1=BigInt(113);for(let t=0,e=Ln,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],cd.push(2*(5*n+r)),ud.push((t+1)*(t+2)/2%64);let i=T1;for(let s=0;s<7;s++)e=(e<<Ln^(e>>j1)*B1)%M1,e&N1&&(i^=Ln<<(Ln<<BigInt(s))-Ln);ld.push(i)}const[U1,F1]=I1(ld,!0),mu=(t,e,r)=>r>32?D1(t,e,r):P1(t,e,r),wu=(t,e,r)=>r>32?x1(t,e,r):S1(t,e,r);function k1(t,e=24){const r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=r[c],l=r[c+1],h=mu(u,l,1)^r[a],f=wu(u,l,1)^r[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=f}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=ud[o],c=mu(i,s,a),u=wu(i,s,a),l=cd[o];i=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=U1[n],t[1]^=F1[n]}r.fill(0)}let q1=class hd extends Ca{constructor(e,r,n,i=!1,s=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Zn(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=A1(this.state)}keccak(){gu||yu(this.state32),k1(this.state32,this.rounds),gu||yu(this.state32),this.posOut=0,this.pos=0}update(e){dn(this);const{blockLen:r,state:n}=this;e=pn(e);const i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);for(let a=0;a<o;a++)n[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:n,blockLen:i}=this;e[n]^=r,r&128&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){dn(this,!1),ci(e),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,s=e.length;i<s;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,s-i);e.set(r.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Zn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(od(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new hd(r,n,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}};const z1=(t,e,r)=>ad(()=>new q1(e,t,r)),H1=z1(1,136,256/8),K1="https://rpc.walletconnect.org/v1";function fd(t){const e=`Ethereum Signed Message:
29
+ `);super(o,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=e,this.version=Uf}walk(e){return Ff(this,e)}}function Ff(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Ff(t.cause,e):e?null:t}class kf extends br{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}}function _n(t,{dir:e,size:r=32}={}){return typeof t=="string"?oE(t,{dir:e,size:r}):aE(t,{dir:e,size:r})}function oE(t,{dir:e,size:r=32}={}){if(r===null)return t;const n=t.replace("0x","");if(n.length>r*2)throw new kf({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function aE(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new kf({size:t.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let i=0;i<r;i++){const s=e==="right";n[s?i:r-i-1]=t[s?i:t.length-i-1]}return n}class cE extends br{constructor({max:e,min:r,signed:n,size:i,value:s}){super(`Number "${s}" is not in safe ${i?`${i*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${r} to ${e})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}}class uE extends br{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function $n(t,{size:e}){if(Zc(t)>e)throw new uE({givenSize:Zc(t),maxSize:e})}function No(t,e={}){const{signed:r}=e;e.size&&$n(t,{size:e.size});const n=BigInt(t);if(!r)return n;const i=(t.length-2)/2,s=(1n<<BigInt(i)*8n-1n)-1n;return n<=s?n:n-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function lE(t,e={}){return Number(No(t,e))}const hE=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function jo(t,e={}){return typeof t=="number"||typeof t=="bigint"?zf(t,e):typeof t=="string"?pE(t,e):typeof t=="boolean"?fE(t,e):qf(t,e)}function fE(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?($n(r,{size:e.size}),_n(r,{size:e.size})):r}function qf(t,e={}){let r="";for(let i=0;i<t.length;i++)r+=hE[t[i]];const n=`0x${r}`;return typeof e.size=="number"?($n(n,{size:e.size}),_n(n,{dir:"right",size:e.size})):n}function zf(t,e={}){const{signed:r,size:n}=e,i=BigInt(t);let s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&r?-s-1n:0;if(s&&i>s||i<o){const c=typeof t=="bigint"?"n":"";throw new cE({max:s?`${s}${c}`:void 0,min:`${o}${c}`,signed:r,size:n,value:`${t}${c}`})}const a=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?_n(a,{size:n}):a}const dE=new TextEncoder;function pE(t,e={}){const r=dE.encode(t);return qf(r,e)}const gE=new TextEncoder;function yE(t,e={}){return typeof t=="number"||typeof t=="bigint"?wE(t,e):typeof t=="boolean"?mE(t,e):Jn(t)?Hf(t,e):Kf(t,e)}function mE(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?($n(r,{size:e.size}),_n(r,{size:e.size})):r}const Ft={zero:48,nine:57,A:65,F:70,a:97,f:102};function Qc(t){if(t>=Ft.zero&&t<=Ft.nine)return t-Ft.zero;if(t>=Ft.A&&t<=Ft.F)return t-(Ft.A-10);if(t>=Ft.a&&t<=Ft.f)return t-(Ft.a-10)}function Hf(t,e={}){let r=t;e.size&&($n(r,{size:e.size}),r=_n(r,{dir:"right",size:e.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const i=n.length/2,s=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const c=Qc(n.charCodeAt(a++)),u=Qc(n.charCodeAt(a++));if(c===void 0||u===void 0)throw new br(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);s[o]=c*16+u}return s}function wE(t,e){const r=zf(t,e);return Hf(r)}function Kf(t,e={}){const r=gE.encode(t);return typeof e.size=="number"?($n(r,{size:e.size}),_n(r,{dir:"right",size:e.size})):r}function Zi(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function vE(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function bs(t,...e){if(!vE(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function zC(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Zi(t.outputLen),Zi(t.blockLen)}function Xc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function bE(t,e){bs(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const vi=BigInt(2**32-1),eu=BigInt(32);function EE(t,e=!1){return e?{h:Number(t&vi),l:Number(t>>eu&vi)}:{h:Number(t>>eu&vi)|0,l:Number(t&vi)|0}}function _E(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:s,l:o}=EE(t[i],e);[r[i],n[i]]=[s,o]}return[r,n]}const $E=(t,e,r)=>t<<r|e>>>32-r,OE=(t,e,r)=>e<<r|t>>>32-r,IE=(t,e,r)=>e<<r-32|t>>>64-r,PE=(t,e,r)=>t<<r-32|e>>>64-r,Nr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function SE(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function HC(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function KC(t,e){return t<<32-e|t>>>e}const tu=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function DE(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function ru(t){for(let e=0;e<t.length;e++)t[e]=DE(t[e])}function xE(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Vf(t){return typeof t=="string"&&(t=xE(t)),bs(t),t}function VC(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];bs(i),e+=i.length}const r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){const s=t[n];r.set(s,i),i+=s.length}return r}class AE{clone(){return this._cloneInto()}}function CE(t){const e=n=>t().update(Vf(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function WC(t=32){if(Nr&&typeof Nr.getRandomValues=="function")return Nr.getRandomValues(new Uint8Array(t));if(Nr&&typeof Nr.randomBytes=="function")return Nr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const Wf=[],Gf=[],Yf=[],LE=BigInt(0),Cn=BigInt(1),RE=BigInt(2),TE=BigInt(7),NE=BigInt(256),jE=BigInt(113);for(let t=0,e=Cn,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],Wf.push(2*(5*n+r)),Gf.push((t+1)*(t+2)/2%64);let i=LE;for(let s=0;s<7;s++)e=(e<<Cn^(e>>TE)*jE)%NE,e&RE&&(i^=Cn<<(Cn<<BigInt(s))-Cn);Yf.push(i)}const[ME,BE]=_E(Yf,!0),nu=(t,e,r)=>r>32?IE(t,e,r):$E(t,e,r),iu=(t,e,r)=>r>32?PE(t,e,r):OE(t,e,r);function UE(t,e=24){const r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=r[c],l=r[c+1],h=nu(u,l,1)^r[a],f=iu(u,l,1)^r[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=f}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=Gf[o],c=nu(i,s,a),u=iu(i,s,a),l=Wf[o];i=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=ME[n],t[1]^=BE[n]}r.fill(0)}class Da extends AE{constructor(e,r,n,i=!1,s=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Zi(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=SE(this.state)}keccak(){tu||ru(this.state32),UE(this.state32,this.rounds),tu||ru(this.state32),this.posOut=0,this.pos=0}update(e){Xc(this);const{blockLen:r,state:n}=this;e=Vf(e);const i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);for(let a=0;a<o;a++)n[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:n,blockLen:i}=this;e[n]^=r,r&128&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){Xc(this,!1),bs(e),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,s=e.length;i<s;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,s-i);e.set(r.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Zi(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(bE(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new Da(r,n,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const FE=(t,e,r)=>CE(()=>new Da(e,t,r)),kE=FE(1,136,256/8);function Jf(t,e){const r=e||"hex",n=kE(Jn(t,{strict:!1})?yE(t):t);return r==="bytes"?n:jo(n)}class qE extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const Js=new qE(8192);function zE(t,e){if(Js.has(`${t}.${e}`))return Js.get(`${t}.${e}`);const r=t.substring(2).toLowerCase(),n=Jf(Kf(r),"bytes"),i=r.split("");for(let o=0;o<40;o+=2)n[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(n[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const s=`0x${i.join("")}`;return Js.set(`${t}.${e}`,s),s}function HE(t){const e=Jf(`0x${t.substring(4)}`).substring(26);return zE(`0x${e}`)}async function KE({hash:t,signature:e}){const r=Jn(t)?t:jo(t),{secp256k1:n}=await dh(async()=>{const{secp256k1:o}=await import("./secp256k1-BZSFMt4U.js");return{secp256k1:o}},__vite__mapDeps([0,1,2]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:h,yParity:f}=e,p=Number(f??h),d=su(p);return new n.Signature(No(u),No(l)).addRecoveryBit(d)}const o=Jn(e)?e:jo(e),a=lE(`0x${o.slice(130)}`),c=su(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function su(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function VE({hash:t,signature:e}){return HE(await KE({hash:t,signature:e}))}function WE(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let u=0;u<e.length;u++)e[u]=255;for(let u=0;u<t.length;u++){const l=t.charAt(u),h=l.charCodeAt(0);if(e[h]!==255)throw new TypeError(l+" is ambiguous");e[h]=u}const r=t.length,n=t.charAt(0),i=Math.log(r)/Math.log(256),s=Math.log(256)/Math.log(r);function o(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";let l=0,h=0,f=0;const p=u.length;for(;f!==p&&u[f]===0;)f++,l++;const d=(p-f)*s+1>>>0,y=new Uint8Array(d);for(;f!==p;){let v=u[f],E=0;for(let O=d-1;(v!==0||E<h)&&O!==-1;O--,E++)v+=256*y[O]>>>0,y[O]=v%r>>>0,v=v/r>>>0;if(v!==0)throw new Error("Non-zero carry");h=E,f++}let w=d-h;for(;w!==d&&y[w]===0;)w++;let b=n.repeat(l);for(;w<d;++w)b+=t.charAt(y[w]);return b}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,h=0,f=0;for(;u[l]===n;)h++,l++;const p=(u.length-l)*i+1>>>0,d=new Uint8Array(p);for(;l<u.length;){const v=u.charCodeAt(l);if(v>255)return;let E=e[v];if(E===255)return;let O=0;for(let x=p-1;(E!==0||O<f)&&x!==-1;x--,O++)E+=r*d[x]>>>0,d[x]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");f=O,l++}let y=p-f;for(;y!==p&&d[y]===0;)y++;const w=new Uint8Array(h+(p-y));let b=h;for(;y!==p;)w[b++]=d[y++];return w}function c(u){const l=a(u);if(l)return l;throw new Error("Non-base"+r+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var GE="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const YE=WE(GE);function Zf(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function qn(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const r=Zf(e);let n=0;for(const i of t)r.set(i,n),n+=i.length;return r}function Qf(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const ou=Qf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Zs=Qf("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=Zf(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Xf={utf8:ou,"utf-8":ou,hex:Mc.base16,latin1:Zs,ascii:Zs,binary:Zs,...Mc};function ht(t,e="utf8"){const r=Xf[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}function Ze(t,e="utf8"){const r=Xf[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}var JE={VITE_BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23627664864.commit-ab90df9"};const ZE=":";function an(t){const[e,r]=t.split(ZE);return{namespace:e,reference:r}}function au(t,e=[]){const r=[];return Object.keys(t).forEach(n=>{if(e.length&&!e.includes(n))return;const i=t[n];r.push(...i.accounts)}),r}function ed(t,e){return t.includes(":")?[t]:e.chains||[]}var QE=Object.defineProperty,XE=Object.defineProperties,e1=Object.getOwnPropertyDescriptors,cu=Object.getOwnPropertySymbols,t1=Object.prototype.hasOwnProperty,r1=Object.prototype.propertyIsEnumerable,uu=(t,e,r)=>e in t?QE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,lu=(t,e)=>{for(var r in e||(e={}))t1.call(e,r)&&uu(t,r,e[r]);if(cu)for(var r of cu(e))r1.call(e,r)&&uu(t,r,e[r]);return t},n1=(t,e)=>XE(t,e1(e));const i1="ReactNative",it={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},s1="js";function Qi(){return typeof ft<"u"&&typeof ft.versions<"u"&&typeof ft.versions.node<"u"}function ir(){return!vr()&&!!Ea()&&navigator.product===i1}function o1(){return ir()&&typeof H<"u"&&typeof(H==null?void 0:H.Platform)<"u"&&(H==null?void 0:H.Platform.OS)==="android"}function a1(){return ir()&&typeof H<"u"&&typeof(H==null?void 0:H.Platform)<"u"&&(H==null?void 0:H.Platform.OS)==="ios"}function On(){return!Qi()&&!!Ea()&&!!vr()}function ai(){return ir()?it.reactNative:Qi()?it.node:On()?it.browser:it.unknown}function hu(){var t;try{return ir()&&typeof H<"u"&&typeof(H==null?void 0:H.Application)<"u"?(t=H.Application)==null?void 0:t.applicationId:void 0}catch{return}}function c1(t,e){const r=new URLSearchParams(t);for(const n of Object.keys(e).sort())if(e.hasOwnProperty(n)){const i=e[n];i!==void 0&&r.set(n,i)}return r.toString()}function u1(t){var e,r;const n=td();try{return t!=null&&t.url&&n.url&&new URL(t.url).host!==new URL(n.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${n.url}. This is probably unintended and can lead to issues.`),t.url=n.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(i=>i!=="")),n1(lu(lu({},n),t),{url:t?.url||n.url,name:t?.name||n.name,description:t?.description||n.description,icons:(r=t?.icons)!=null&&r.length&&t.icons.length>0?t.icons:n.icons})}catch(i){return console.warn("Error populating app metadata",i),t||n}}function td(){return sf()||{name:"",description:"",url:"",icons:[""]}}function l1(){if(ai()===it.reactNative&&typeof H<"u"&&typeof(H==null?void 0:H.Platform)<"u"){const{OS:r,Version:n}=H.Platform;return[r,n].join("-")}const t=Mv();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function h1(){var t;const e=ai();return e===it.browser?[e,((t=nf())==null?void 0:t.host)||"unknown"].join(":"):e}function rd(t,e,r){const n=l1(),i=h1();return[[t,e].join("-"),[s1,r].join("-"),n,i].join("/")}function f1({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=r.split("?"),l=rd(t,e,n),h={auth:i,ua:l,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},f=c1(u[1]||"",h);return u[0]+"?"+f}function yr(t,e){return t.filter(r=>e.includes(r)).length===t.length}function Mo(t){return Object.fromEntries(t.entries())}function Bo(t){return new Map(Object.entries(t))}function ur(t=T.FIVE_MINUTES,e){const r=T.toMiliseconds(t||T.FIVE_MINUTES);let n,i,s,o;return{resolve:a=>{s&&n&&(clearTimeout(s),n(a),o=Promise.resolve(a))},reject:a=>{s&&i&&(clearTimeout(s),i(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);s=setTimeout(()=>{const u=new Error(e);o=Promise.reject(u),c(u)},r),n=a,i=c})}}function tr(t,e,r){return new Promise(async(n,i)=>{const s=setTimeout(()=>i(new Error(r)),e);try{const o=await t;n(o)}catch(o){i(o)}clearTimeout(s)})}function nd(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function d1(t){return nd("topic",t)}function p1(t){return nd("id",t)}function id(t){const[e,r]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")n.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return n}function _e(t,e){return T.fromMiliseconds(Date.now()+T.toMiliseconds(t))}function Qt(t){return Date.now()>=T.toMiliseconds(t)}function ee(t,e){return`${t}${e?`:${e}`:""}`}function Rt(t=[],e=[]){return[...new Set([...t,...e])]}async function g1({id:t,topic:e,wcDeepLink:r}){var n;try{if(!r)return;const i=typeof r=="string"?JSON.parse(r):r,s=i?.href;if(typeof s!="string")return;const o=y1(s,t,e),a=ai();if(a===it.browser){if(!((n=vr())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}m1(o)}else a===it.reactNative&&typeof(H==null?void 0:H.Linking)<"u"&&await H.Linking.openURL(o)}catch(i){console.error(i)}}function y1(t,e,r){const n=`requestId=${e}&sessionTopic=${r}`;t.endsWith("/")&&(t=t.slice(0,-1));let i=`${t}`;if(t.startsWith("https://t.me")){const s=t.includes("?")?"&startapp=":"?startapp=";i=`${i}${s}${E1(n,!0)}`}else i=`${i}/wc?${n}`;return i}function m1(t){let e="_self";b1()?e="_top":(v1()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function w1(t,e){let r="";try{if(On()&&(r=localStorage.getItem(e),r))return r;r=await t.getItem(e)}catch(n){console.error(n)}return r}function fu(t,e){if(!t.includes(e))return null;const r=t.split(/([&,?,=])/),n=r.indexOf(e);return r[n+2]}function du(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function xa(){return typeof ft<"u"&&JE.IS_VITEST==="true"}function v1(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function b1(){try{return window.self!==window.top}catch{return!1}}function E1(t,e=!1){const r=Ce.from(t).toString("base64");return e?r.replace(/[=]/g,""):r}function sd(t){return Ce.from(t,"base64").toString("utf-8")}function _1(t){return new Promise(e=>setTimeout(e,t))}function Zn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function $1(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ci(t,...e){if(!$1(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Aa(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Zn(t.outputLen),Zn(t.blockLen)}function dn(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function od(t,e){ci(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const bi=BigInt(2**32-1),pu=BigInt(32);function O1(t,e=!1){return e?{h:Number(t&bi),l:Number(t>>pu&bi)}:{h:Number(t>>pu&bi)|0,l:Number(t&bi)|0}}function I1(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:s,l:o}=O1(t[i],e);[r[i],n[i]]=[s,o]}return[r,n]}const P1=(t,e,r)=>t<<r|e>>>32-r,S1=(t,e,r)=>e<<r|t>>>32-r,D1=(t,e,r)=>e<<r-32|t>>>64-r,x1=(t,e,r)=>t<<r-32|e>>>64-r,jr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function A1(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Qs(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Ot(t,e){return t<<32-e|t>>>e}const gu=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function C1(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function yu(t){for(let e=0;e<t.length;e++)t[e]=C1(t[e])}function L1(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function pn(t){return typeof t=="string"&&(t=L1(t)),ci(t),t}function R1(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];ci(i),e+=i.length}const r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){const s=t[n];r.set(s,i),i+=s.length}return r}let Ca=class{clone(){return this._cloneInto()}};function ad(t){const e=n=>t().update(pn(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function In(t=32){if(jr&&typeof jr.getRandomValues=="function")return jr.getRandomValues(new Uint8Array(t));if(jr&&typeof jr.randomBytes=="function")return jr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const cd=[],ud=[],ld=[],T1=BigInt(0),Ln=BigInt(1),N1=BigInt(2),j1=BigInt(7),M1=BigInt(256),B1=BigInt(113);for(let t=0,e=Ln,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],cd.push(2*(5*n+r)),ud.push((t+1)*(t+2)/2%64);let i=T1;for(let s=0;s<7;s++)e=(e<<Ln^(e>>j1)*B1)%M1,e&N1&&(i^=Ln<<(Ln<<BigInt(s))-Ln);ld.push(i)}const[U1,F1]=I1(ld,!0),mu=(t,e,r)=>r>32?D1(t,e,r):P1(t,e,r),wu=(t,e,r)=>r>32?x1(t,e,r):S1(t,e,r);function k1(t,e=24){const r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=r[c],l=r[c+1],h=mu(u,l,1)^r[a],f=wu(u,l,1)^r[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=f}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=ud[o],c=mu(i,s,a),u=wu(i,s,a),l=cd[o];i=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=U1[n],t[1]^=F1[n]}r.fill(0)}let q1=class hd extends Ca{constructor(e,r,n,i=!1,s=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Zn(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=A1(this.state)}keccak(){gu||yu(this.state32),k1(this.state32,this.rounds),gu||yu(this.state32),this.posOut=0,this.pos=0}update(e){dn(this);const{blockLen:r,state:n}=this;e=pn(e);const i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);for(let a=0;a<o;a++)n[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:n,blockLen:i}=this;e[n]^=r,r&128&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){dn(this,!1),ci(e),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,s=e.length;i<s;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,s-i);e.set(r.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Zn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(od(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new hd(r,n,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}};const z1=(t,e,r)=>ad(()=>new q1(e,t,r)),H1=z1(1,136,256/8),K1="https://rpc.walletconnect.org/v1";function fd(t){const e=`Ethereum Signed Message:
30
30
  ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Ce.from(H1(r)).toString("hex")}async function V1(t,e,r,n,i,s){switch(r.t){case"eip191":return await W1(t,e,r.s);case"eip1271":return await G1(t,e,r.s,n,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}async function W1(t,e,r){return(await VE({hash:fd(e),signature:r})).toLowerCase()===t.toLowerCase()}async function G1(t,e,r,n,i,s){const o=an(n);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${n}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u="0000000000000000000000000000000000000000000000000000000000000041",l=r.substring(2),h=fd(e).substring(2),f=a+h+c+u+l,p=await fetch(`${s||K1}/?chainId=${n}&projectId=${i}`,{method:"POST",body:JSON.stringify({id:Y1(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:f},"latest"]})}),{result:d}=await p.json();return d?d.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Y1(){return Date.now()+Math.floor(Math.random()*1e3)}function J1(t){const e=atob(t),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);const n=r[0];if(n===0)throw new Error("No signatures found");const i=1+n*64;if(r.length<i)throw new Error("Transaction data too short for claimed signature count");if(r.length<100)throw new Error("Transaction too short");const s=Ce.from(t,"base64").slice(1,65);return YE.encode(s)}var Z1=Object.defineProperty,Q1=Object.defineProperties,X1=Object.getOwnPropertyDescriptors,vu=Object.getOwnPropertySymbols,e_=Object.prototype.hasOwnProperty,t_=Object.prototype.propertyIsEnumerable,bu=(t,e,r)=>e in t?Z1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,r_=(t,e)=>{for(var r in e||(e={}))e_.call(e,r)&&bu(t,r,e[r]);if(vu)for(var r of vu(e))t_.call(e,r)&&bu(t,r,e[r]);return t},n_=(t,e)=>Q1(t,X1(e));const i_="did:pkh:",La=t=>t?.split(":"),s_=t=>{const e=t&&La(t);if(e)return t.includes(i_)?e[3]:e[1]},Uo=t=>{const e=t&&La(t);if(e)return e[2]+":"+e[3]},Xi=t=>{const e=t&&La(t);if(e)return e.pop()};async function Eu(t){const{cacao:e,projectId:r}=t,{s:n,p:i}=e,s=dd(i,i.iss),o=Xi(i.iss);return await V1(o,s,n,Uo(i.iss),r)}const dd=(t,e)=>{const r=`${t.domain} wants you to sign in with your Ethereum account:`,n=Xi(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let i=t.statement||void 0;const s=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${s_(e)}`,c=`Nonce: ${t.nonce}`,u=`Issued At: ${t.iat}`,l=t.exp?`Expiration Time: ${t.exp}`:void 0,h=t.nbf?`Not Before: ${t.nbf}`:void 0,f=t.requestId?`Request ID: ${t.requestId}`:void 0,p=t.resources?`Resources:${t.resources.map(y=>`
31
31
  - ${y}`).join("")}`:void 0,d=ji(t.resources);if(d){const y=Qn(d);i=p_(i,y)}return[r,n,"",i,"",s,o,a,c,u,l,h,f,p].filter(y=>y!=null).join(`
32
32
  `)};function o_(t){return Ce.from(JSON.stringify(t)).toString("base64")}function a_(t){return JSON.parse(Ce.from(t,"base64").toString("utf-8"))}function Er(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(r=>{const n=t.att[r];if(Array.isArray(n))throw new Error(`Resource must be an object: ${r}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(n).forEach(i=>{const s=n[i];if(!Array.isArray(s))throw new Error(`Ability limits ${i} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function c_(t,e,r,n={}){return r?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:u_(e,r,n)}}}function u_(t,e,r={}){e=e?.sort((i,s)=>i.localeCompare(s));const n=e.map(i=>({[`${t}/${i}`]:[r]}));return Object.assign({},...n)}function pd(t){return Er(t),`urn:recap:${o_(t).replace(/=/g,"")}`}function Qn(t){const e=a_(t.replace("urn:recap:",""));return Er(e),e}function l_(t,e,r){const n=c_(t,e,r);return pd(n)}function h_(t){return t&&t.includes("urn:recap:")}function f_(t,e){const r=Qn(t),n=Qn(e),i=d_(r,n);return pd(i)}function d_(t,e){Er(t),Er(e);const r=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,s)=>i.localeCompare(s)),n={att:{}};return r.forEach(i=>{var s,o;Object.keys(((s=t.att)==null?void 0:s[i])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[i])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,u;n.att[i]=n_(r_({},n.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((u=e.att[i])==null?void 0:u[a])})})}),n}function p_(t="",e){Er(e);const r="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(r))return t;const n=[];let i=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(h=>({ability:h.split("/")[0],action:h.split("/")[1]}));c.sort((h,f)=>h.action.localeCompare(f.action));const u={};c.forEach(h=>{u[h.ability]||(u[h.ability]=[]),u[h.ability].push(h.action)});const l=Object.keys(u).map(h=>(i++,`(${i}) '${h}': '${u[h].join("', '")}' for '${a}'.`));n.push(l.join(", ").replace(".,","."))});const s=n.join(" "),o=`${r}${s}`;return`${t?t+" ":""}${o}`}function _u(t){var e;const r=Qn(t);Er(r);const n=(e=r.att)==null?void 0:e.eip155;return n?Object.keys(n).map(i=>i.split("/")[1]):[]}function $u(t){const e=Qn(t);Er(e);const r=[];return Object.values(e.att).forEach(n=>{Object.values(n).forEach(i=>{var s;(s=i?.[0])!=null&&s.chains&&r.push(i[0].chains)})}),[...new Set(r.flat())]}function ji(t){if(!t)return;const e=t?.[t.length-1];return h_(e)?e:void 0}function Xs(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function gd(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function nt(t,...e){if(!gd(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Ou(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function g_(t,e){nt(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Iu(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}const rr=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),y_=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),m_=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!m_)throw new Error("Non little-endian hardware is not supported");function w_(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Fo(t){if(typeof t=="string")t=w_(t);else if(gd(t))t=ko(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function v_(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function b_(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}const E_=(t,e)=>{function r(n,...i){if(nt(n),t.nonceLength!==void 0){const u=i[0];if(!u)throw new Error("nonce / iv required");t.varSizeNonce?nt(u):nt(u,t.nonceLength)}const s=t.tagLength;s&&i[1]!==void 0&&nt(i[1]);const o=e(n,...i),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");nt(l)}};let c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,nt(u),a(o.encrypt.length,l),o.encrypt(u,l)},decrypt(u,l){if(nt(u),s&&u.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(o.decrypt.length,l),o.decrypt(u,l)}}}return Object.assign(r,t),r};function Pu(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(r&&!__(e))throw new Error("invalid output, must be aligned");return e}function Su(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s);t.setUint32(e+4,o,n),t.setUint32(e+0,a,n)}function __(t){return t.byteOffset%4===0}function ko(t){return Uint8Array.from(t)}function gn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}const yd=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),$_=yd("expand 16-byte k"),O_=yd("expand 32-byte k"),I_=rr($_),P_=rr(O_);function Z(t,e){return t<<e|t>>>32-e}function qo(t){return t.byteOffset%4===0}const Ei=64,S_=16,md=2**32-1,Du=new Uint32Array;function D_(t,e,r,n,i,s,o,a){const c=i.length,u=new Uint8Array(Ei),l=rr(u),h=qo(i)&&qo(s),f=h?rr(i):Du,p=h?rr(s):Du;for(let d=0;d<c;o++){if(t(e,r,n,l,o,a),o>=md)throw new Error("arx: counter overflow");const y=Math.min(Ei,c-d);if(h&&y===Ei){const w=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let b=0,v;b<S_;b++)v=w+b,p[v]=f[v]^l[b];d+=Ei;continue}for(let w=0,b;w<y;w++)b=d+w,s[b]=i[b]^u[w];d+=y}}function x_(t,e){const{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=v_({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Xs(i),Xs(o),Iu(s),Iu(r),(a,c,u,l,h=0)=>{nt(a),nt(c),nt(u);const f=u.length;if(l===void 0&&(l=new Uint8Array(f)),nt(l),Xs(h),h<0||h>=md)throw new Error("arx: counter overflow");if(l.length<f)throw new Error(`arx: output (${l.length}) is shorter than data (${f})`);const p=[];let d=a.length,y,w;if(d===32)p.push(y=ko(a)),w=P_;else if(d===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),w=I_,p.push(y);else throw new Error(`arx: invalid 32-byte key, got length=${d}`);qo(c)||p.push(c=ko(c));const b=rr(y);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(w,b,rr(c.subarray(0,16)),b),c=c.subarray(16)}const v=16-i;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){const O=new Uint8Array(12);O.set(c,s?0:12-c.length),c=O,p.push(c)}const E=rr(c);return D_(t,w,b,E,u,l,h,o),gn(...p),l}}const Re=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class A_{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=Fo(e),nt(e,32);const r=Re(e,0),n=Re(e,2),i=Re(e,4),s=Re(e,6),o=Re(e,8),a=Re(e,10),c=Re(e,12),u=Re(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let l=0;l<8;l++)this.pad[l]=Re(e,16+2*l)}process(e,r,n=!1){const i=n?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],u=o[2],l=o[3],h=o[4],f=o[5],p=o[6],d=o[7],y=o[8],w=o[9],b=Re(e,r+0),v=Re(e,r+2),E=Re(e,r+4),O=Re(e,r+6),x=Re(e,r+8),D=Re(e,r+10),S=Re(e,r+12),C=Re(e,r+14);let I=s[0]+(b&8191),k=s[1]+((b>>>13|v<<3)&8191),M=s[2]+((v>>>10|E<<6)&8191),j=s[3]+((E>>>7|O<<9)&8191),q=s[4]+((O>>>4|x<<12)&8191),L=s[5]+(x>>>1&8191),g=s[6]+((x>>>14|D<<2)&8191),m=s[7]+((D>>>11|S<<5)&8191),_=s[8]+((S>>>8|C<<8)&8191),P=s[9]+(C>>>5|i),$=0,A=$+I*a+k*(5*w)+M*(5*y)+j*(5*d)+q*(5*p);$=A>>>13,A&=8191,A+=L*(5*f)+g*(5*h)+m*(5*l)+_*(5*u)+P*(5*c),$+=A>>>13,A&=8191;let B=$+I*c+k*a+M*(5*w)+j*(5*y)+q*(5*d);$=B>>>13,B&=8191,B+=L*(5*p)+g*(5*f)+m*(5*h)+_*(5*l)+P*(5*u),$+=B>>>13,B&=8191;let F=$+I*u+k*c+M*a+j*(5*w)+q*(5*y);$=F>>>13,F&=8191,F+=L*(5*d)+g*(5*p)+m*(5*f)+_*(5*h)+P*(5*l),$+=F>>>13,F&=8191;let z=$+I*l+k*u+M*c+j*a+q*(5*w);$=z>>>13,z&=8191,z+=L*(5*y)+g*(5*d)+m*(5*p)+_*(5*f)+P*(5*h),$+=z>>>13,z&=8191;let U=$+I*h+k*l+M*u+j*c+q*a;$=U>>>13,U&=8191,U+=L*(5*w)+g*(5*y)+m*(5*d)+_*(5*p)+P*(5*f),$+=U>>>13,U&=8191;let K=$+I*f+k*h+M*l+j*u+q*c;$=K>>>13,K&=8191,K+=L*a+g*(5*w)+m*(5*y)+_*(5*d)+P*(5*p),$+=K>>>13,K&=8191;let Y=$+I*p+k*f+M*h+j*l+q*u;$=Y>>>13,Y&=8191,Y+=L*c+g*a+m*(5*w)+_*(5*y)+P*(5*d),$+=Y>>>13,Y&=8191;let pe=$+I*d+k*p+M*f+j*h+q*l;$=pe>>>13,pe&=8191,pe+=L*u+g*c+m*a+_*(5*w)+P*(5*y),$+=pe>>>13,pe&=8191;let te=$+I*y+k*d+M*p+j*f+q*h;$=te>>>13,te&=8191,te+=L*l+g*u+m*c+_*a+P*(5*w),$+=te>>>13,te&=8191;let J=$+I*w+k*y+M*d+j*p+q*f;$=J>>>13,J&=8191,J+=L*h+g*l+m*u+_*c+P*a,$+=J>>>13,J&=8191,$=($<<2)+$|0,$=$+A|0,A=$&8191,$=$>>>13,B+=$,s[0]=A,s[1]=B,s[2]=F,s[3]=z,s[4]=U,s[5]=K,s[6]=Y,s[7]=pe,s[8]=te,s[9]=J}finalize(){const{h:e,pad:r}=this,n=new Uint16Array(10);let i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,n[0]=e[0]+5,i=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+i,i=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+r[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+r[a]|0)+(o>>>16)|0,e[a]=o&65535;gn(n)}update(e){Ou(this);const{buffer:r,blockLen:n}=this;e=Fo(e);const i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);if(o===n){for(;n<=i-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){gn(this.h,this.r,this.buffer,this.pad)}digestInto(e){Ou(this),g_(e,this),this.finished=!0;const{buffer:r,h:n}=this;let{pos:i}=this;if(i){for(r[i++]=1;i<16;i++)r[i]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=n[o]>>>0,e[s++]=n[o]>>>8;return e}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}}function C_(t){const e=(n,i)=>t(i).update(Fo(n)).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}const L_=C_(t=>new A_(t));function R_(t,e,r,n,i,s=20){let o=t[0],a=t[1],c=t[2],u=t[3],l=e[0],h=e[1],f=e[2],p=e[3],d=e[4],y=e[5],w=e[6],b=e[7],v=i,E=r[0],O=r[1],x=r[2],D=o,S=a,C=c,I=u,k=l,M=h,j=f,q=p,L=d,g=y,m=w,_=b,P=v,$=E,A=O,B=x;for(let z=0;z<s;z+=2)D=D+k|0,P=Z(P^D,16),L=L+P|0,k=Z(k^L,12),D=D+k|0,P=Z(P^D,8),L=L+P|0,k=Z(k^L,7),S=S+M|0,$=Z($^S,16),g=g+$|0,M=Z(M^g,12),S=S+M|0,$=Z($^S,8),g=g+$|0,M=Z(M^g,7),C=C+j|0,A=Z(A^C,16),m=m+A|0,j=Z(j^m,12),C=C+j|0,A=Z(A^C,8),m=m+A|0,j=Z(j^m,7),I=I+q|0,B=Z(B^I,16),_=_+B|0,q=Z(q^_,12),I=I+q|0,B=Z(B^I,8),_=_+B|0,q=Z(q^_,7),D=D+M|0,B=Z(B^D,16),m=m+B|0,M=Z(M^m,12),D=D+M|0,B=Z(B^D,8),m=m+B|0,M=Z(M^m,7),S=S+j|0,P=Z(P^S,16),_=_+P|0,j=Z(j^_,12),S=S+j|0,P=Z(P^S,8),_=_+P|0,j=Z(j^_,7),C=C+q|0,$=Z($^C,16),L=L+$|0,q=Z(q^L,12),C=C+q|0,$=Z($^C,8),L=L+$|0,q=Z(q^L,7),I=I+k|0,A=Z(A^I,16),g=g+A|0,k=Z(k^g,12),I=I+k|0,A=Z(A^I,8),g=g+A|0,k=Z(k^g,7);let F=0;n[F++]=o+D|0,n[F++]=a+S|0,n[F++]=c+C|0,n[F++]=u+I|0,n[F++]=l+k|0,n[F++]=h+M|0,n[F++]=f+j|0,n[F++]=p+q|0,n[F++]=d+L|0,n[F++]=y+g|0,n[F++]=w+m|0,n[F++]=b+_|0,n[F++]=v+P|0,n[F++]=E+$|0,n[F++]=O+A|0,n[F++]=x+B|0}const T_=x_(R_,{counterRight:!1,counterLength:4,allowShortKeys:!1}),N_=new Uint8Array(16),xu=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(N_.subarray(r))},j_=new Uint8Array(32);function Au(t,e,r,n,i){const s=t(e,r,j_),o=L_.create(s);i&&xu(o,i),xu(o,n);const a=new Uint8Array(16),c=y_(a);Su(c,0,BigInt(i?i.length:0),!0),Su(c,8,BigInt(n.length),!0),o.update(a);const u=o.digest();return gn(s,a),u}const M_=t=>(e,r,n)=>({encrypt(i,s){const o=i.length;s=Pu(o+16,s,!1),s.set(i);const a=s.subarray(0,-16);t(e,r,a,a,1);const c=Au(t,e,r,a,n);return s.set(c,o),gn(c),s},decrypt(i,s){s=Pu(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=Au(t,e,r,o,n);if(!b_(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,r,s,s,1),gn(c),s}}),wd=E_({blockSize:64,nonceLength:12,tagLength:16},M_(T_));let vd=class extends Ca{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Aa(e);const n=pn(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(n.length>i?e.create().update(n).digest():n);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),s.fill(0)}update(e){return dn(this),this.iHash.update(e),this}digestInto(e){dn(this),ci(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:n,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Es=(t,e,r)=>new vd(t,e).update(r).digest();Es.create=(t,e)=>new vd(t,e);function B_(t,e,r){return Aa(t),r===void 0&&(r=new Uint8Array(t.outputLen)),Es(t,pn(r),pn(e))}const eo=new Uint8Array([0]),Cu=new Uint8Array;function U_(t,e,r,n=32){if(Aa(t),Zn(n),n>255*t.outputLen)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(n/t.outputLen);r===void 0&&(r=Cu);const s=new Uint8Array(i*t.outputLen),o=Es.create(t,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let u=0;u<i;u++)eo[0]=u+1,a.update(u===0?Cu:c).update(r).update(eo).digestInto(c),s.set(c,t.outputLen*u),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),eo.fill(0),s.slice(0,n)}const F_=(t,e,r,n,i)=>U_(t,B_(t,e,r),n,i);function k_(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}function q_(t,e,r){return t&e^~t&r}function z_(t,e,r){return t&e^t&r^e&r}let H_=class extends Ca{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Qs(this.buffer)}update(e){dn(this);const{view:r,buffer:n,blockLen:i}=this;e=pn(e);const s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=Qs(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){dn(this),od(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(n,0),o=0);for(let h=o;h<i;h++)r[h]=0;k_(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=Qs(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return e.length=i,e.pos=a,e.finished=s,e.destroyed=o,i%r&&e.buffer.set(n),e}};const K_=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Jt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Zt=new Uint32Array(64);class V_ extends H_{constructor(){super(64,32,8,!1),this.A=Jt[0]|0,this.B=Jt[1]|0,this.C=Jt[2]|0,this.D=Jt[3]|0,this.E=Jt[4]|0,this.F=Jt[5]|0,this.G=Jt[6]|0,this.H=Jt[7]|0}get(){const{A:e,B:r,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[e,r,n,i,s,o,a,c]}set(e,r,n,i,s,o,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)Zt[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const f=Zt[h-15],p=Zt[h-2],d=Ot(f,7)^Ot(f,18)^f>>>3,y=Ot(p,17)^Ot(p,19)^p>>>10;Zt[h]=y+Zt[h-7]+d+Zt[h-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){const f=Ot(a,6)^Ot(a,11)^Ot(a,25),p=l+f+q_(a,c,u)+K_[h]+Zt[h]|0,d=(Ot(n,2)^Ot(n,13)^Ot(n,22))+z_(n,i,s)|0;l=u,u=c,c=a,a=o+p|0,o=s,s=i,i=n,n=p+d|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,i,s,o,a,c,u,l)}roundClean(){Zt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const ui=ad(()=>new V_);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _s=BigInt(0),$s=BigInt(1),W_=BigInt(2);function _r(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function li(t){if(!_r(t))throw new Error("Uint8Array expected")}function yn(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const G_=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function mn(t){li(t);let e="";for(let r=0;r<t.length;r++)e+=G_[t[r]];return e}function Xr(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Ra(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?_s:BigInt("0x"+t)}const kt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Lu(t){if(t>=kt._0&&t<=kt._9)return t-kt._0;if(t>=kt.A&&t<=kt.F)return t-(kt.A-10);if(t>=kt.a&&t<=kt.f)return t-(kt.a-10)}function wn(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){const o=Lu(t.charCodeAt(s)),a=Lu(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=o*16+a}return n}function mr(t){return Ra(mn(t))}function Xn(t){return li(t),Ra(mn(Uint8Array.from(t).reverse()))}function vn(t,e){return wn(t.toString(16).padStart(e*2,"0"))}function Os(t,e){return vn(t,e).reverse()}function Y_(t){return wn(Xr(t))}function rt(t,e,r){let n;if(typeof e=="string")try{n=wn(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(_r(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=n.length;if(typeof r=="number"&&i!==r)throw new Error(t+" of length "+r+" expected, got "+i);return n}function ei(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];li(i),e+=i.length}const r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){const s=t[n];r.set(s,i),i+=s.length}return r}function J_(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Z_(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const to=t=>typeof t=="bigint"&&_s<=t;function Is(t,e,r){return to(t)&&to(e)&&to(r)&&e<=t&&t<r}function Kt(t,e,r,n){if(!Is(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function bd(t){let e;for(e=0;t>_s;t>>=$s,e+=1);return e}function Q_(t,e){return t>>BigInt(e)&$s}function X_(t,e,r){return t|(r?$s:_s)<<BigInt(e)}const Ta=t=>(W_<<BigInt(t-1))-$s,ro=t=>new Uint8Array(t),Ru=t=>Uint8Array.from(t);function Ed(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=ro(t),i=ro(t),s=0;const o=()=>{n.fill(1),i.fill(0),s=0},a=(...l)=>r(i,n,...l),c=(l=ro())=>{i=a(Ru([0]),l),n=a(),l.length!==0&&(i=a(Ru([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const h=[];for(;l<e;){n=a();const f=n.slice();h.push(f),l+=n.length}return ei(...h)};return(l,h)=>{o(),c(l);let f;for(;!(f=h(u()));)c();return o(),f}}const e$={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||_r(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function Pn(t,e,r={}){const n=(i,s,o)=>{const a=e$[s];if(typeof a!="function")throw new Error("invalid validator function");const c=t[i];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(i)+" is invalid. Expected "+s+", got "+c)};for(const[i,s]of Object.entries(e))n(i,s,!1);for(const[i,s]of Object.entries(r))n(i,s,!0);return t}const t$=()=>{throw new Error("not implemented")};function zo(t){const e=new WeakMap;return(r,...n)=>{const i=e.get(r);if(i!==void 0)return i;const s=t(r,...n);return e.set(r,s),s}}var r$=Object.freeze({__proto__:null,isBytes:_r,abytes:li,abool:yn,bytesToHex:mn,numberToHexUnpadded:Xr,hexToNumber:Ra,hexToBytes:wn,bytesToNumberBE:mr,bytesToNumberLE:Xn,numberToBytesBE:vn,numberToBytesLE:Os,numberToVarBytesBE:Y_,ensureBytes:rt,concatBytes:ei,equalBytes:J_,utf8ToBytes:Z_,inRange:Is,aInRange:Kt,bitLen:bd,bitGet:Q_,bitSet:X_,bitMask:Ta,createHmacDrbg:Ed,validateObject:Pn,notImplemented:t$,memoized:zo});const Ae=BigInt(0),ve=BigInt(1),fr=BigInt(2),n$=BigInt(3),Ho=BigInt(4),Tu=BigInt(5),Nu=BigInt(8);function Je(t,e){const r=t%e;return r>=Ae?r:e+r}function _d(t,e,r){if(e<Ae)throw new Error("invalid exponent, negatives unsupported");if(r<=Ae)throw new Error("invalid modulus");if(r===ve)return Ae;let n=ve;for(;e>Ae;)e&ve&&(n=n*t%r),t=t*t%r,e>>=ve;return n}function vt(t,e,r){let n=t;for(;e-- >Ae;)n*=n,n%=r;return n}function Ko(t,e){if(t===Ae)throw new Error("invert: expected non-zero number");if(e<=Ae)throw new Error("invert: expected positive modulus, got "+e);let r=Je(t,e),n=e,i=Ae,s=ve;for(;r!==Ae;){const o=n/r,a=n%r,c=i-s*o;n=r,r=a,i=s,s=c}if(n!==ve)throw new Error("invert: does not exist");return Je(i,e)}function i$(t){const e=(t-ve)/fr;let r,n,i;for(r=t-ve,n=0;r%fr===Ae;r/=fr,n++);for(i=fr;i<t&&_d(i,e,t)!==t-ve;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){const o=(t+ve)/Ho;return function(a,c){const u=a.pow(c,o);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}const s=(r+ve)/fr;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=n,u=o.pow(o.mul(o.ONE,i),r),l=o.pow(a,s),h=o.pow(a,r);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let f=1;for(let d=o.sqr(h);f<c&&!o.eql(d,o.ONE);f++)d=o.sqr(d);const p=o.pow(u,ve<<BigInt(c-f-1));u=o.sqr(p),l=o.mul(l,p),h=o.mul(h,u),c=f}return l}}function s$(t){if(t%Ho===n$){const e=(t+ve)/Ho;return function(r,n){const i=r.pow(n,e);if(!r.eql(r.sqr(i),n))throw new Error("Cannot find square root");return i}}if(t%Nu===Tu){const e=(t-Tu)/Nu;return function(r,n){const i=r.mul(n,fr),s=r.pow(i,e),o=r.mul(n,s),a=r.mul(r.mul(o,fr),s),c=r.mul(o,r.sub(a,r.ONE));if(!r.eql(r.sqr(c),n))throw new Error("Cannot find square root");return c}}return i$(t)}const o$=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function a$(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=o$.reduce((n,i)=>(n[i]="function",n),e);return Pn(t,r)}function c$(t,e,r){if(r<Ae)throw new Error("invalid exponent, negatives unsupported");if(r===Ae)return t.ONE;if(r===ve)return e;let n=t.ONE,i=e;for(;r>Ae;)r&ve&&(n=t.mul(n,i)),i=t.sqr(i),r>>=ve;return n}function u$(t,e){const r=new Array(e.length),n=e.reduce((s,o,a)=>t.is0(o)?s:(r[a]=s,t.mul(s,o)),t.ONE),i=t.inv(n);return e.reduceRight((s,o,a)=>t.is0(o)?s:(r[a]=t.mul(s,r[a]),t.mul(s,o)),i),r}function $d(t,e){const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Od(t,e,r=!1,n={}){if(t<=Ae)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=$d(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:i,BYTES:s,MASK:Ta(i),ZERO:Ae,ONE:ve,create:c=>Je(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ae<=c&&c<t},is0:c=>c===Ae,isOdd:c=>(c&ve)===ve,neg:c=>Je(-c,t),eql:(c,u)=>c===u,sqr:c=>Je(c*c,t),add:(c,u)=>Je(c+u,t),sub:(c,u)=>Je(c-u,t),mul:(c,u)=>Je(c*u,t),pow:(c,u)=>c$(a,c,u),div:(c,u)=>Je(c*Ko(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Ko(c,t),sqrt:n.sqrt||(c=>(o||(o=s$(t)),o(a,c))),invertBatch:c=>u$(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?Os(c,s):vn(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?Xn(c):mr(c)}});return Object.freeze(a)}function Id(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function Pd(t){const e=Id(t);return e+Math.ceil(e/2)}function l$(t,e,r=!1){const n=t.length,i=Id(e),s=Pd(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const o=r?Xn(t):mr(t),a=Je(o,e-ve)+ve;return r?Os(a,i):vn(a,i)}const ju=BigInt(0),_i=BigInt(1);function no(t,e){const r=e.negate();return t?r:e}function Sd(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function io(t,e){Sd(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1);return{windows:r,windowSize:n}}function h$(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function f$(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const so=new WeakMap,Dd=new WeakMap;function oo(t){return Dd.get(t)||1}function d$(t,e){return{constTimeNegate:no,hasPrecomputes(r){return oo(r)!==1},unsafeLadder(r,n,i=t.ZERO){let s=r;for(;n>ju;)n&_i&&(i=i.add(s)),s=s.double(),n>>=_i;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=io(n,e),o=[];let a=r,c=a;for(let u=0;u<i;u++){c=a,o.push(c);for(let l=1;l<s;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,n,i){const{windows:s,windowSize:o}=io(r,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**r-1),l=2**r,h=BigInt(r);for(let f=0;f<s;f++){const p=f*o;let d=Number(i&u);i>>=h,d>o&&(d-=l,i+=_i);const y=p,w=p+Math.abs(d)-1,b=f%2!==0,v=d<0;d===0?c=c.add(no(b,n[y])):a=a.add(no(v,n[w]))}return{p:a,f:c}},wNAFUnsafe(r,n,i,s=t.ZERO){const{windows:o,windowSize:a}=io(r,e),c=BigInt(2**r-1),u=2**r,l=BigInt(r);for(let h=0;h<o;h++){const f=h*a;if(i===ju)break;let p=Number(i&c);if(i>>=l,p>a&&(p-=u,i+=_i),p===0)continue;let d=n[f+Math.abs(p)-1];p<0&&(d=d.negate()),s=s.add(d)}return s},getPrecomputes(r,n,i){let s=so.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&so.set(n,i(s))),s},wNAFCached(r,n,i){const s=oo(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=oo(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){Sd(n,e),Dd.set(r,n),so.delete(r)}}}function p$(t,e,r,n){if(h$(r,t),f$(n,e),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=bd(BigInt(r.length)),o=s>12?s-3:s>4?s-2:s?2:1,a=(1<<o)-1,c=new Array(a+1).fill(i),u=Math.floor((e.BITS-1)/o)*o;let l=i;for(let h=u;h>=0;h-=o){c.fill(i);for(let p=0;p<n.length;p++){const d=n[p],y=Number(d>>BigInt(h)&BigInt(a));c[y]=c[y].add(r[p])}let f=i;for(let p=c.length-1,d=i;p>0;p--)d=d.add(c[p]),f=f.add(d);if(l=l.add(f),h!==0)for(let p=0;p<o;p++)l=l.double()}return l}function xd(t){return a$(t.Fp),Pn(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...$d(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Mr=BigInt(0),ao=BigInt(1);function g$(t){return Pn(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function y$(t){const e=g$(t),{P:r}=e,n=v=>Je(v,r),i=e.montgomeryBits,s=Math.ceil(i/8),o=e.nByteLength,a=e.adjustScalarBytes||(v=>v),c=e.powPminus2||(v=>_d(v,r-BigInt(2),r));function u(v,E,O){const x=n(v*(E-O));return E=n(E-x),O=n(O+x),[E,O]}const l=(e.a-BigInt(2))/BigInt(4);function h(v,E){Kt("u",v,Mr,r),Kt("scalar",E,Mr,r);const O=E,x=v;let D=ao,S=Mr,C=v,I=ao,k=Mr,M;for(let q=BigInt(i-1);q>=Mr;q--){const L=O>>q&ao;k^=L,M=u(k,D,C),D=M[0],C=M[1],M=u(k,S,I),S=M[0],I=M[1],k=L;const g=D+S,m=n(g*g),_=D-S,P=n(_*_),$=m-P,A=C+I,B=C-I,F=n(B*g),z=n(A*_),U=F+z,K=F-z;C=n(U*U),I=n(x*n(K*K)),D=n(m*P),S=n($*(m+n(l*$)))}M=u(k,D,C),D=M[0],C=M[1],M=u(k,S,I),S=M[0],I=M[1];const j=c(S);return n(D*j)}function f(v){return Os(n(v),s)}function p(v){const E=rt("u coordinate",v,s);return o===32&&(E[31]&=127),Xn(E)}function d(v){const E=rt("scalar",v),O=E.length;if(O!==s&&O!==o){let x=""+s+" or "+o;throw new Error("invalid scalar, expected "+x+" bytes, got "+O)}return Xn(a(E))}function y(v,E){const O=p(E),x=d(v),D=h(O,x);if(D===Mr)throw new Error("invalid private or public key received");return f(D)}const w=f(e.Gu);function b(v){return y(v,w)}return{scalarMult:y,scalarMultBase:b,getSharedSecret:(v,E)=>y(v,E),getPublicKey:v=>b(v),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:w}}const Vo=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const m$=BigInt(1),Mu=BigInt(2),w$=BigInt(3),v$=BigInt(5);BigInt(8);function b$(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=Vo,o=t*t%s*t%s,a=vt(o,Mu,s)*o%s,c=vt(a,m$,s)*t%s,u=vt(c,v$,s)*c%s,l=vt(u,e,s)*u%s,h=vt(l,r,s)*l%s,f=vt(h,n,s)*h%s,p=vt(f,i,s)*f%s,d=vt(p,i,s)*f%s,y=vt(d,e,s)*u%s;return{pow_p_5_8:vt(y,Mu,s)*t%s,b2:o}}function E$(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Wo=y$({P:Vo,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{const e=Vo,{pow_p_5_8:r,b2:n}=b$(t);return Je(vt(r,w$,e)*n,e)},adjustScalarBytes:E$,randomBytes:In});function Bu(t){t.lowS!==void 0&&yn("lowS",t.lowS),t.prehash!==void 0&&yn("prehash",t.prehash)}function _$(t){const e=xd(t);Pn(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:n,a:i}=e;if(r){if(!n.eql(i,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:$$,hexToBytes:O$}=r$;class I$ extends Error{constructor(e=""){super(e)}}const zt={Err:I$,_tlv:{encode:(t,e)=>{const{Err:r}=zt;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,i=Xr(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?Xr(i.length/2|128):"";return Xr(t)+s+i+e},decode(t,e){const{Err:r}=zt;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const i=e[n++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const u=e.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(n+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=zt;if(t<Ht)throw new e("integer: negative integers are not allowed");let r=Xr(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=zt;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return $$(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=zt,i=typeof t=="string"?O$(t):t;li(i);const{v:s,l:o}=n.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,s),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=zt,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),s=n+i;return e.encode(48,s)}},Ht=BigInt(0),Se=BigInt(1);BigInt(2);const Uu=BigInt(3);BigInt(4);function P$(t){const e=_$(t),{Fp:r}=e,n=Od(e.n,e.nBitLength),i=e.toBytes||((y,w,b)=>{const v=w.toAffine();return ei(Uint8Array.from([4]),r.toBytes(v.x),r.toBytes(v.y))}),s=e.fromBytes||(y=>{const w=y.subarray(1),b=r.fromBytes(w.subarray(0,r.BYTES)),v=r.fromBytes(w.subarray(r.BYTES,2*r.BYTES));return{x:b,y:v}});function o(y){const{a:w,b}=e,v=r.sqr(y),E=r.mul(v,y);return r.add(r.add(E,r.mul(y,w)),b)}if(!r.eql(r.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return Is(y,Se,e.n)}function c(y){const{allowedPrivateKeyLengths:w,nByteLength:b,wrapPrivateKey:v,n:E}=e;if(w&&typeof y!="bigint"){if(_r(y)&&(y=mn(y)),typeof y!="string"||!w.includes(y.length))throw new Error("invalid private key");y=y.padStart(b*2,"0")}let O;try{O=typeof y=="bigint"?y:mr(rt("private key",y,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof y)}return v&&(O=Je(O,E)),Kt("private key",O,Se,E),O}function u(y){if(!(y instanceof f))throw new Error("ProjectivePoint expected")}const l=zo((y,w)=>{const{px:b,py:v,pz:E}=y;if(r.eql(E,r.ONE))return{x:b,y:v};const O=y.is0();w==null&&(w=O?r.ONE:r.inv(E));const x=r.mul(b,w),D=r.mul(v,w),S=r.mul(E,w);if(O)return{x:r.ZERO,y:r.ZERO};if(!r.eql(S,r.ONE))throw new Error("invZ was invalid");return{x,y:D}}),h=zo(y=>{if(y.is0()){if(e.allowInfinityPoint&&!r.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:w,y:b}=y.toAffine();if(!r.isValid(w)||!r.isValid(b))throw new Error("bad point: x or y not FE");const v=r.sqr(b),E=o(w);if(!r.eql(v,E))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class f{constructor(w,b,v){if(this.px=w,this.py=b,this.pz=v,w==null||!r.isValid(w))throw new Error("x required");if(b==null||!r.isValid(b))throw new Error("y required");if(v==null||!r.isValid(v))throw new Error("z required");Object.freeze(this)}static fromAffine(w){const{x:b,y:v}=w||{};if(!w||!r.isValid(b)||!r.isValid(v))throw new Error("invalid affine point");if(w instanceof f)throw new Error("projective point not allowed");const E=O=>r.eql(O,r.ZERO);return E(b)&&E(v)?f.ZERO:new f(b,v,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(w){const b=r.invertBatch(w.map(v=>v.pz));return w.map((v,E)=>v.toAffine(b[E])).map(f.fromAffine)}static fromHex(w){const b=f.fromAffine(s(rt("pointHex",w)));return b.assertValidity(),b}static fromPrivateKey(w){return f.BASE.multiply(c(w))}static msm(w,b){return p$(f,n,w,b)}_setWindowSize(w){d.setWindowSize(this,w)}assertValidity(){h(this)}hasEvenY(){const{y:w}=this.toAffine();if(r.isOdd)return!r.isOdd(w);throw new Error("Field doesn't support isOdd")}equals(w){u(w);const{px:b,py:v,pz:E}=this,{px:O,py:x,pz:D}=w,S=r.eql(r.mul(b,D),r.mul(O,E)),C=r.eql(r.mul(v,D),r.mul(x,E));return S&&C}negate(){return new f(this.px,r.neg(this.py),this.pz)}double(){const{a:w,b}=e,v=r.mul(b,Uu),{px:E,py:O,pz:x}=this;let D=r.ZERO,S=r.ZERO,C=r.ZERO,I=r.mul(E,E),k=r.mul(O,O),M=r.mul(x,x),j=r.mul(E,O);return j=r.add(j,j),C=r.mul(E,x),C=r.add(C,C),D=r.mul(w,C),S=r.mul(v,M),S=r.add(D,S),D=r.sub(k,S),S=r.add(k,S),S=r.mul(D,S),D=r.mul(j,D),C=r.mul(v,C),M=r.mul(w,M),j=r.sub(I,M),j=r.mul(w,j),j=r.add(j,C),C=r.add(I,I),I=r.add(C,I),I=r.add(I,M),I=r.mul(I,j),S=r.add(S,I),M=r.mul(O,x),M=r.add(M,M),I=r.mul(M,j),D=r.sub(D,I),C=r.mul(M,k),C=r.add(C,C),C=r.add(C,C),new f(D,S,C)}add(w){u(w);const{px:b,py:v,pz:E}=this,{px:O,py:x,pz:D}=w;let S=r.ZERO,C=r.ZERO,I=r.ZERO;const k=e.a,M=r.mul(e.b,Uu);let j=r.mul(b,O),q=r.mul(v,x),L=r.mul(E,D),g=r.add(b,v),m=r.add(O,x);g=r.mul(g,m),m=r.add(j,q),g=r.sub(g,m),m=r.add(b,E);let _=r.add(O,D);return m=r.mul(m,_),_=r.add(j,L),m=r.sub(m,_),_=r.add(v,E),S=r.add(x,D),_=r.mul(_,S),S=r.add(q,L),_=r.sub(_,S),I=r.mul(k,m),S=r.mul(M,L),I=r.add(S,I),S=r.sub(q,I),I=r.add(q,I),C=r.mul(S,I),q=r.add(j,j),q=r.add(q,j),L=r.mul(k,L),m=r.mul(M,m),q=r.add(q,L),L=r.sub(j,L),L=r.mul(k,L),m=r.add(m,L),j=r.mul(q,m),C=r.add(C,j),j=r.mul(_,m),S=r.mul(g,S),S=r.sub(S,j),j=r.mul(g,q),I=r.mul(_,I),I=r.add(I,j),new f(S,C,I)}subtract(w){return this.add(w.negate())}is0(){return this.equals(f.ZERO)}wNAF(w){return d.wNAFCached(this,w,f.normalizeZ)}multiplyUnsafe(w){const{endo:b,n:v}=e;Kt("scalar",w,Ht,v);const E=f.ZERO;if(w===Ht)return E;if(this.is0()||w===Se)return this;if(!b||d.hasPrecomputes(this))return d.wNAFCachedUnsafe(this,w,f.normalizeZ);let{k1neg:O,k1:x,k2neg:D,k2:S}=b.splitScalar(w),C=E,I=E,k=this;for(;x>Ht||S>Ht;)x&Se&&(C=C.add(k)),S&Se&&(I=I.add(k)),k=k.double(),x>>=Se,S>>=Se;return O&&(C=C.negate()),D&&(I=I.negate()),I=new f(r.mul(I.px,b.beta),I.py,I.pz),C.add(I)}multiply(w){const{endo:b,n:v}=e;Kt("scalar",w,Se,v);let E,O;if(b){const{k1neg:x,k1:D,k2neg:S,k2:C}=b.splitScalar(w);let{p:I,f:k}=this.wNAF(D),{p:M,f:j}=this.wNAF(C);I=d.constTimeNegate(x,I),M=d.constTimeNegate(S,M),M=new f(r.mul(M.px,b.beta),M.py,M.pz),E=I.add(M),O=k.add(j)}else{const{p:x,f:D}=this.wNAF(w);E=x,O=D}return f.normalizeZ([E,O])[0]}multiplyAndAddUnsafe(w,b,v){const E=f.BASE,O=(D,S)=>S===Ht||S===Se||!D.equals(E)?D.multiplyUnsafe(S):D.multiply(S),x=O(this,b).add(O(w,v));return x.is0()?void 0:x}toAffine(w){return l(this,w)}isTorsionFree(){const{h:w,isTorsionFree:b}=e;if(w===Se)return!0;if(b)return b(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:w,clearCofactor:b}=e;return w===Se?this:b?b(f,this):this.multiplyUnsafe(e.h)}toRawBytes(w=!0){return yn("isCompressed",w),this.assertValidity(),i(f,this,w)}toHex(w=!0){return yn("isCompressed",w),mn(this.toRawBytes(w))}}f.BASE=new f(e.Gx,e.Gy,r.ONE),f.ZERO=new f(r.ZERO,r.ONE,r.ZERO);const p=e.nBitLength,d=d$(f,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function S$(t){const e=xd(t);return Pn(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function D$(t){const e=S$(t),{Fp:r,n}=e,i=r.BYTES+1,s=2*r.BYTES+1;function o(L){return Je(L,n)}function a(L){return Ko(L,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:h}=P$({...e,toBytes(L,g,m){const _=g.toAffine(),P=r.toBytes(_.x),$=ei;return yn("isCompressed",m),m?$(Uint8Array.from([g.hasEvenY()?2:3]),P):$(Uint8Array.from([4]),P,r.toBytes(_.y))},fromBytes(L){const g=L.length,m=L[0],_=L.subarray(1);if(g===i&&(m===2||m===3)){const P=mr(_);if(!Is(P,Se,r.ORDER))throw new Error("Point is not on curve");const $=l(P);let A;try{A=r.sqrt($)}catch(F){const z=F instanceof Error?": "+F.message:"";throw new Error("Point is not on curve"+z)}const B=(A&Se)===Se;return(m&1)===1!==B&&(A=r.neg(A)),{x:P,y:A}}else if(g===s&&m===4){const P=r.fromBytes(_.subarray(0,r.BYTES)),$=r.fromBytes(_.subarray(r.BYTES,2*r.BYTES));return{x:P,y:$}}else{const P=i,$=s;throw new Error("invalid Point, expected length of "+P+", or uncompressed "+$+", got "+g)}}}),f=L=>mn(vn(L,e.nByteLength));function p(L){const g=n>>Se;return L>g}function d(L){return p(L)?o(-L):L}const y=(L,g,m)=>mr(L.slice(g,m));class w{constructor(g,m,_){this.r=g,this.s=m,this.recovery=_,this.assertValidity()}static fromCompact(g){const m=e.nByteLength;return g=rt("compactSignature",g,m*2),new w(y(g,0,m),y(g,m,2*m))}static fromDER(g){const{r:m,s:_}=zt.toSig(rt("DER",g));return new w(m,_)}assertValidity(){Kt("r",this.r,Se,n),Kt("s",this.s,Se,n)}addRecoveryBit(g){return new w(this.r,this.s,g)}recoverPublicKey(g){const{r:m,s:_,recovery:P}=this,$=D(rt("msgHash",g));if(P==null||![0,1,2,3].includes(P))throw new Error("recovery id invalid");const A=P===2||P===3?m+e.n:m;if(A>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const B=P&1?"03":"02",F=c.fromHex(B+f(A)),z=a(A),U=o(-$*z),K=o(_*z),Y=c.BASE.multiplyAndAddUnsafe(F,U,K);if(!Y)throw new Error("point at infinify");return Y.assertValidity(),Y}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return wn(this.toDERHex())}toDERHex(){return zt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return wn(this.toCompactHex())}toCompactHex(){return f(this.r)+f(this.s)}}const b={isValidPrivateKey(L){try{return u(L),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const L=Pd(e.n);return l$(e.randomBytes(L),e.n)},precompute(L=8,g=c.BASE){return g._setWindowSize(L),g.multiply(BigInt(3)),g}};function v(L,g=!0){return c.fromPrivateKey(L).toRawBytes(g)}function E(L){const g=_r(L),m=typeof L=="string",_=(g||m)&&L.length;return g?_===i||_===s:m?_===2*i||_===2*s:L instanceof c}function O(L,g,m=!0){if(E(L))throw new Error("first arg must be private key");if(!E(g))throw new Error("second arg must be public key");return c.fromHex(g).multiply(u(L)).toRawBytes(m)}const x=e.bits2int||function(L){if(L.length>8192)throw new Error("input is too large");const g=mr(L),m=L.length*8-e.nBitLength;return m>0?g>>BigInt(m):g},D=e.bits2int_modN||function(L){return o(x(L))},S=Ta(e.nBitLength);function C(L){return Kt("num < 2^"+e.nBitLength,L,Ht,S),vn(L,e.nByteLength)}function I(L,g,m=k){if(["recovered","canonical"].some(te=>te in m))throw new Error("sign() legacy options not supported");const{hash:_,randomBytes:P}=e;let{lowS:$,prehash:A,extraEntropy:B}=m;$==null&&($=!0),L=rt("msgHash",L),Bu(m),A&&(L=rt("prehashed msgHash",_(L)));const F=D(L),z=u(g),U=[C(z),C(F)];if(B!=null&&B!==!1){const te=B===!0?P(r.BYTES):B;U.push(rt("extraEntropy",te))}const K=ei(...U),Y=F;function pe(te){const J=x(te);if(!h(J))return;const Ue=a(J),Le=c.BASE.multiply(J).toAffine(),qe=o(Le.x);if(qe===Ht)return;const ot=o(Ue*o(Y+qe*z));if(ot===Ht)return;let Nt=(Le.x===qe?0:2)|Number(Le.y&Se),Ar=ot;return $&&p(ot)&&(Ar=d(ot),Nt^=1),new w(qe,Ar,Nt)}return{seed:K,k2sig:pe}}const k={lowS:e.lowS,prehash:!1},M={lowS:e.lowS,prehash:!1};function j(L,g,m=k){const{seed:_,k2sig:P}=I(L,g,m),$=e;return Ed($.hash.outputLen,$.nByteLength,$.hmac)(_,P)}c.BASE._setWindowSize(8);function q(L,g,m,_=M){const P=L;g=rt("msgHash",g),m=rt("publicKey",m);const{lowS:$,prehash:A,format:B}=_;if(Bu(_),"strict"in _)throw new Error("options.strict was renamed to lowS");if(B!==void 0&&B!=="compact"&&B!=="der")throw new Error("format must be compact or der");const F=typeof P=="string"||_r(P),z=!F&&!B&&typeof P=="object"&&P!==null&&typeof P.r=="bigint"&&typeof P.s=="bigint";if(!F&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let U,K;try{if(z&&(U=new w(P.r,P.s)),F){try{B!=="compact"&&(U=w.fromDER(P))}catch(ot){if(!(ot instanceof zt.Err))throw ot}!U&&B!=="der"&&(U=w.fromCompact(P))}K=c.fromHex(m)}catch{return!1}if(!U||$&&U.hasHighS())return!1;A&&(g=e.hash(g));const{r:Y,s:pe}=U,te=D(g),J=a(pe),Ue=o(te*J),Le=o(Y*J),qe=c.BASE.multiplyAndAddUnsafe(K,Ue,Le)?.toAffine();return qe?o(qe.x)===Y:!1}return{CURVE:e,getPublicKey:v,getSharedSecret:O,sign:j,verify:q,ProjectivePoint:c,Signature:w,utils:b}}function x$(t){return{hash:t,hmac:(e,...r)=>Es(t,e,R1(...r)),randomBytes:In}}function A$(t,e){const r=n=>D$({...t,...x$(n)});return{...r(e),create:r}}const Ad=Od(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),C$=Ad.create(BigInt("-3")),L$=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),R$=A$({a:C$,b:L$,Fp:Ad,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},ui),Cd="base10",He="base16",bt="base64pad",Xt="base64url",hi="utf8",Ld=0,Vt=1,fi=2,T$=0,Fu=1,zn=12,Na=32;function N$(){const t=Wo.utils.randomPrivateKey(),e=Wo.getPublicKey(t);return{privateKey:Ze(t,He),publicKey:Ze(e,He)}}function Go(){const t=In(Na);return Ze(t,He)}function j$(t,e){const r=Wo.getSharedSecret(ht(t,He),ht(e,He)),n=F_(ui,r,void 0,void 0,Na);return Ze(n,He)}function Mi(t){const e=ui(ht(t,He));return Ze(e,He)}function Ct(t){const e=ui(ht(t,hi));return Ze(e,He)}function Rd(t){return ht(`${t}`,Cd)}function $r(t){return Number(Ze(t,Cd))}function Td(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Nd(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4;return e+"=".repeat(r)}function M$(t){const e=Rd(typeof t.type<"u"?t.type:Ld);if($r(e)===Vt&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof t.senderPublicKey<"u"?ht(t.senderPublicKey,He):void 0,n=typeof t.iv<"u"?ht(t.iv,He):In(zn),i=ht(t.symKey,He),s=wd(i,n).encrypt(ht(t.message,hi)),o=jd({type:e,sealed:s,iv:n,senderPublicKey:r});return t.encoding===Xt?Td(o):o}function B$(t){const e=ht(t.symKey,He),{sealed:r,iv:n}=ti({encoded:t.encoded,encoding:t.encoding}),i=wd(e,n).decrypt(r);if(i===null)throw new Error("Failed to decrypt");return Ze(i,hi)}function U$(t,e){const r=Rd(fi),n=In(zn),i=ht(t,hi),s=jd({type:r,sealed:i,iv:n});return e===Xt?Td(s):s}function F$(t,e){const{sealed:r}=ti({encoded:t,encoding:e});return Ze(r,hi)}function jd(t){if($r(t.type)===fi)return Ze(qn([t.type,t.sealed]),bt);if($r(t.type)===Vt){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ze(qn([t.type,t.senderPublicKey,t.iv,t.sealed]),bt)}return Ze(qn([t.type,t.iv,t.sealed]),bt)}function ti(t){const e=(t.encoding||bt)===Xt?Nd(t.encoded):t.encoded,r=ht(e,bt),n=r.slice(T$,Fu),i=Fu;if($r(n)===Vt){const c=i+Na,u=c+zn,l=r.slice(i,c),h=r.slice(c,u),f=r.slice(u);return{type:n,sealed:f,iv:h,senderPublicKey:l}}if($r(n)===fi){const c=r.slice(i),u=In(zn);return{type:n,sealed:c,iv:u}}const s=i+zn,o=r.slice(i,s),a=r.slice(s);return{type:n,sealed:a,iv:o}}function k$(t,e){const r=ti({encoded:t,encoding:e?.encoding});return Md({type:$r(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Ze(r.senderPublicKey,He):void 0,receiverPublicKey:e?.receiverPublicKey})}function Md(t){const e=t?.type||Ld;if(e===Vt){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function ku(t){return t.type===Vt&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function qu(t){return t.type===fi}function q$(t){const e=Ce.from(t.x,"base64"),r=Ce.from(t.y,"base64");return qn([new Uint8Array([4]),e,r])}function z$(t,e){const[r,n,i]=t.split("."),s=Ce.from(Nd(i),"base64");if(s.length!==64)throw new Error("Invalid signature length");const o=s.slice(0,32),a=s.slice(32,64),c=`${r}.${n}`,u=ui(c),l=q$(e);if(!R$.verify(qn([o,a]),u,l))throw new Error("Invalid signature");return Co(t).payload}const H$="irn";function es(t){return t?.relay||{protocol:H$}}function Un(t){const e=Jb[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function K$(t,e="-"){const r={},n="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(n)){const s=i.replace(n,""),o=t[i];r[s]=o}}),r}function zu(t){if(!t.includes("wc:")){const u=sd(t);u!=null&&u.includes("wc:")&&(t=u)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),i=t.substring(e+1,r).split("@"),s=typeof r<"u"?t.substring(r):"",o=new URLSearchParams(s),a={};o.forEach((u,l)=>{a[l]=u});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:n,topic:V$(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:K$(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function V$(t){return t.startsWith("//")?t.substring(2):t}function W$(t,e="-"){const r="relay",n={};return Object.keys(t).forEach(i=>{const s=i,o=r+e+s;t[s]&&(n[o]=t[s])}),n}function Hu(t){const e=new URLSearchParams,r=W$(t.relay);Object.keys(r).sort().forEach(i=>{e.set(i,r[i])}),e.set("symKey",t.symKey),t.expiryTimestamp&&e.set("expiryTimestamp",t.expiryTimestamp.toString()),t.methods&&e.set("methods",t.methods.join(","));const n=e.toString();return`${t.protocol}:${t.topic}@${t.version}?${n}`}function $i(t,e,r){return`${t}?wc_ev=${r}&topic=${e}`}var G$=Object.defineProperty,Y$=Object.defineProperties,J$=Object.getOwnPropertyDescriptors,Ku=Object.getOwnPropertySymbols,Z$=Object.prototype.hasOwnProperty,Q$=Object.prototype.propertyIsEnumerable,Vu=(t,e,r)=>e in t?G$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,X$=(t,e)=>{for(var r in e||(e={}))Z$.call(e,r)&&Vu(t,r,e[r]);if(Ku)for(var r of Ku(e))Q$.call(e,r)&&Vu(t,r,e[r]);return t},eO=(t,e)=>Y$(t,J$(e));function Sn(t){const e=[];return t.forEach(r=>{const[n,i]=r.split(":");e.push(`${n}:${i}`)}),e}function tO(t){const e=[];return Object.values(t).forEach(r=>{e.push(...Sn(r.accounts))}),e}function rO(t,e){const r=[];return Object.values(t).forEach(n=>{Sn(n.accounts).includes(e)&&r.push(...n.methods)}),r}function nO(t,e){const r=[];return Object.values(t).forEach(n=>{Sn(n.accounts).includes(e)&&r.push(...n.events)}),r}function Ps(t){return t.includes(":")}function en(t){return Ps(t)?t.split(":")[0]:t}function Wu(t){var e,r,n;const i={};if(!nr(t))return i;for(const[s,o]of Object.entries(t)){const a=Ps(s)?[s]:o.chains,c=o.methods||[],u=o.events||[],l=en(s);i[l]=eO(X$({},i[l]),{chains:Rt(a,(e=i[l])==null?void 0:e.chains),methods:Rt(c,(r=i[l])==null?void 0:r.methods),events:Rt(u,(n=i[l])==null?void 0:n.events)})}return i}function iO(t){const e={};return t?.forEach(r=>{var n;const[i,s]=r.split(":");e[i]||(e[i]={accounts:[],chains:[],events:[],methods:[]}),e[i].accounts.push(r),(n=e[i].chains)==null||n.push(`${i}:${s}`)}),e}function Gu(t,e){e=e.map(n=>n.replace("did:pkh:",""));const r=iO(e);for(const[n,i]of Object.entries(r))i.methods?i.methods=Rt(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return r}function sO(t,e){var r,n,i,s,o,a;const c=Wu(t),u=Wu(e),l={},h=Object.keys(c).concat(Object.keys(u));for(const f of h)l[f]={chains:Rt((r=c[f])==null?void 0:r.chains,(n=u[f])==null?void 0:n.chains),methods:Rt((i=c[f])==null?void 0:i.methods,(s=u[f])==null?void 0:s.methods),events:Rt((o=c[f])==null?void 0:o.events,(a=u[f])==null?void 0:a.events)};return l}const oO={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},aO={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function N(t,e){const{message:r,code:n}=aO[t];return{message:e?`${r} ${e}`:r,code:n}}function re(t,e){const{message:r,code:n}=oO[t];return{message:e?`${r} ${e}`:r,code:n}}function Et(t,e){return!!Array.isArray(t)}function nr(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function ke(t){return typeof t>"u"}function Ee(t,e){return e&&ke(t)?!0:typeof t=="string"&&!!t.trim().length}function ja(t,e){return typeof t=="number"&&!isNaN(t)}function cO(t,e){const{requiredNamespaces:r}=e,n=Object.keys(t.namespaces),i=Object.keys(r);let s=!0;return yr(i,n)?(n.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],l=Sn(a),h=r[o];(!yr(ed(o,h),l)||!yr(h.methods,c)||!yr(h.events,u))&&(s=!1)}),s):!1}function ts(t){return Ee(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function uO(t){if(Ee(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const r=e[0]+":"+e[1];return!!e[2]&&ts(r)}}return!1}function lO(t){function e(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(Ee(t,!1)){if(e(t))return!0;const r=sd(t);return e(r)}}catch{}return!1}function hO(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function fO(t){return t?.topic}function dO(t,e){let r=null;return Ee(t?.publicKey,!1)||(r=N("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function Yu(t){let e=!0;return Et(t)?t.length&&(e=t.every(r=>Ee(r,!1))):e=!1,e}function pO(t,e,r){let n=null;return Et(e)&&e.length?e.forEach(i=>{n||ts(i)||(n=re("UNSUPPORTED_CHAINS",`${r}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):ts(t)||(n=re("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function gO(t,e,r){let n=null;return Object.entries(t).forEach(([i,s])=>{if(n)return;const o=pO(i,ed(i,s),`${e} ${r}`);o&&(n=o)}),n}function yO(t,e){let r=null;return Et(t)?t.forEach(n=>{r||uO(n)||(r=re("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=re("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function mO(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;const i=yO(n?.accounts,`${e} namespace`);i&&(r=i)}),r}function wO(t,e){let r=null;return Yu(t?.methods)?Yu(t?.events)||(r=re("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=re("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function Bd(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;const i=wO(n,`${e}, namespace`);i&&(r=i)}),r}function vO(t,e,r){let n=null;if(t&&nr(t)){const i=Bd(t,e);i&&(n=i);const s=gO(t,e,r);s&&(n=s)}else n=N("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return n}function co(t,e){let r=null;if(t&&nr(t)){const n=Bd(t,e);n&&(r=n);const i=mO(t,e);i&&(r=i)}else r=N("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function Ud(t){return Ee(t.protocol,!0)}function bO(t,e){let r=!1;return t?t&&Et(t)&&t.length&&t.forEach(n=>{r=Ud(n)}):r=!0,r}function EO(t){return typeof t=="number"}function Ye(t){return typeof t<"u"&&typeof t!==null}function _O(t){return!(!t||typeof t!="object"||!t.code||!ja(t.code)||!t.message||!Ee(t.message,!1))}function $O(t){return!(ke(t)||!Ee(t.method,!1))}function OO(t){return!(ke(t)||ke(t.result)&&ke(t.error)||!ja(t.id)||!Ee(t.jsonrpc,!1))}function IO(t){return!(ke(t)||!Ee(t.name,!1))}function Ju(t,e){return!(!ts(e)||!tO(t).includes(e))}function PO(t,e,r){return Ee(r,!1)?rO(t,e).includes(r):!1}function SO(t,e,r){return Ee(r,!1)?nO(t,e).includes(r):!1}function Zu(t,e,r){let n=null;const i=DO(t),s=xO(e),o=Object.keys(i),a=Object.keys(s),c=Qu(Object.keys(t)),u=Qu(Object.keys(e)),l=c.filter(h=>!u.includes(h));return l.length&&(n=N("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.
@@ -35,5 +35,5 @@ ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Ce.from(H1(r)).toString(
35
35
  Required: ${o.toString()}
36
36
  Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||n)return;const f=Sn(e[h].accounts);f.includes(h)||(n=N("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${h}
37
37
  Required: ${h}
38
- Approved: ${f.toString()}`))}),o.forEach(h=>{n||(yr(i[h].methods,s[h].methods)?yr(i[h].events,s[h].events)||(n=N("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${h}`)):n=N("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${h}`))}),n}function DO(t){const e={};return Object.keys(t).forEach(r=>{var n;r.includes(":")?e[r]=t[r]:(n=t[r].chains)==null||n.forEach(i=>{e[i]={methods:t[r].methods,events:t[r].events}})}),e}function Qu(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function xO(t){const e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:Sn(t[r].accounts)?.forEach(i=>{e[i]={accounts:t[r].accounts.filter(s=>s.includes(`${i}:`)),methods:t[r].methods,events:t[r].events}})}),e}function AO(t,e){return ja(t)&&t<=e.max&&t>=e.min}function Xu(){const t=ai();return new Promise(e=>{switch(t){case it.browser:e(CO());break;case it.reactNative:e(LO());break;case it.node:e(RO());break;default:e(!0)}})}function CO(){return On()&&navigator?.onLine}async function LO(){return ir()&&typeof H<"u"&&H!=null&&H.NetInfo?(await(H==null?void 0:H.NetInfo.fetch()))?.isConnected:!0}function RO(){return!0}function TO(t){switch(ai()){case it.browser:NO(t);break;case it.reactNative:jO(t);break}}function NO(t){!ir()&&On()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function jO(t){ir()&&typeof H<"u"&&H!=null&&H.NetInfo&&H?.NetInfo.addEventListener(e=>t(e?.isConnected))}function MO(){var t;return On()&&vr()?((t=vr())==null?void 0:t.visibilityState)==="visible":!0}const uo={};class Rn{static get(e){return uo[e]}static set(e,r){uo[e]=r}static delete(e){delete uo[e]}}var Ma={exports:{}},cn=typeof Reflect=="object"?Reflect:null,el=cn&&typeof cn.apply=="function"?cn.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Bi;cn&&typeof cn.ownKeys=="function"?Bi=cn.ownKeys:Object.getOwnPropertySymbols?Bi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Bi=function(e){return Object.getOwnPropertyNames(e)};function BO(t){console&&console.warn&&console.warn(t)}var Fd=Number.isNaN||function(e){return e!==e};function ae(){ae.init.call(this)}Ma.exports=ae;Ma.exports.once=qO;ae.EventEmitter=ae;ae.prototype._events=void 0;ae.prototype._eventsCount=0;ae.prototype._maxListeners=void 0;var tl=10;function Ss(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ae,"defaultMaxListeners",{enumerable:!0,get:function(){return tl},set:function(t){if(typeof t!="number"||t<0||Fd(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");tl=t}});ae.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};ae.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Fd(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function kd(t){return t._maxListeners===void 0?ae.defaultMaxListeners:t._maxListeners}ae.prototype.getMaxListeners=function(){return kd(this)};ae.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")el(c,this,r);else for(var u=c.length,l=Vd(c,u),n=0;n<u;++n)el(l[n],this,r);return!0};function qd(t,e,r,n){var i,s,o;if(Ss(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=kd(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,BO(a)}return t}ae.prototype.addListener=function(e,r){return qd(this,e,r,!1)};ae.prototype.on=ae.prototype.addListener;ae.prototype.prependListener=function(e,r){return qd(this,e,r,!0)};function UO(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function zd(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=UO.bind(n);return i.listener=r,n.wrapFn=i,i}ae.prototype.once=function(e,r){return Ss(r),this.on(e,zd(this,e,r)),this};ae.prototype.prependOnceListener=function(e,r){return Ss(r),this.prependListener(e,zd(this,e,r)),this};ae.prototype.removeListener=function(e,r){var n,i,s,o,a;if(Ss(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():FO(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};ae.prototype.off=ae.prototype.removeListener;ae.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function Hd(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?kO(i):Vd(i,i.length)}ae.prototype.listeners=function(e){return Hd(this,e,!0)};ae.prototype.rawListeners=function(e){return Hd(this,e,!1)};ae.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Kd.call(t,e)};ae.prototype.listenerCount=Kd;function Kd(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}ae.prototype.eventNames=function(){return this._eventsCount>0?Bi(this._events):[]};function Vd(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function FO(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function kO(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function qO(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Wd(t,e,s,{once:!0}),e!=="error"&&zO(t,i,{once:!0})})}function zO(t,e,r){typeof t.on=="function"&&Wd(t,"error",e,r)}function Wd(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var Sr=Ma.exports;const HO=ri(Sr);function KO(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Pe(t,...e){try{return KO(t(...e))}catch(r){return Promise.reject(r)}}function VO(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function WO(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Ui(t){if(VO(t))return String(t);if(WO(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Ui(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Yo="base64:";function GO(t){return typeof t=="string"?t:Yo+ZO(t)}function YO(t){return typeof t!="string"||!t.startsWith(Yo)?t:JO(t.slice(Yo.length))}function JO(t){return globalThis.Buffer?Ce.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function ZO(t){return globalThis.Buffer?Ce.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Ge(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function QO(...t){return Ge(t.join(":"))}function Oi(t){return t=Ge(t),t?t+":":""}function XO(t,e){if(e===void 0)return!0;let r=0,n=t.indexOf(":");for(;n>-1;)r++,n=t.indexOf(":",n+1);return r<=e}function eI(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const tI="memory",rI=()=>{const t=new Map;return{name:tI,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function nI(t={}){const e={mounts:{"":t.driver||rI()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=u=>{for(const l of e.mountpoints)if(u.startsWith(l))return{base:l,relativeKey:u.slice(l.length),driver:e.mounts[l]};return{base:"",relativeKey:u,driver:e.mounts[""]}},n=(u,l)=>e.mountpoints.filter(h=>h.startsWith(u)||l&&u.startsWith(h)).map(h=>({relativeBase:u.length>h.length?u.slice(h.length):void 0,mountpoint:h,driver:e.mounts[h]})),i=(u,l)=>{if(e.watching){l=Ge(l);for(const h of e.watchListeners)h(u,l)}},s=async()=>{if(!e.watching){e.watching=!0;for(const u in e.mounts)e.unwatch[u]=await rl(e.mounts[u],i,u)}},o=async()=>{if(e.watching){for(const u in e.unwatch)await e.unwatch[u]();e.unwatch={},e.watching=!1}},a=(u,l,h)=>{const f=new Map,p=d=>{let y=f.get(d.base);return y||(y={driver:d.driver,base:d.base,items:[]},f.set(d.base,y)),y};for(const d of u){const y=typeof d=="string",w=Ge(y?d:d.key),b=y?void 0:d.value,v=y||!d.options?l:{...l,...d.options},E=r(w);p(E).items.push({key:w,value:b,relativeKey:E.relativeKey,options:v})}return Promise.all([...f.values()].map(d=>h(d))).then(d=>d.flat())},c={hasItem(u,l={}){u=Ge(u);const{relativeKey:h,driver:f}=r(u);return Pe(f.hasItem,h,l)},getItem(u,l={}){u=Ge(u);const{relativeKey:h,driver:f}=r(u);return Pe(f.getItem,h,l).then(p=>pi(p))},getItems(u,l={}){return a(u,l,h=>h.driver.getItems?Pe(h.driver.getItems,h.items.map(f=>({key:f.relativeKey,options:f.options})),l).then(f=>f.map(p=>({key:QO(h.base,p.key),value:pi(p.value)}))):Promise.all(h.items.map(f=>Pe(h.driver.getItem,f.relativeKey,f.options).then(p=>({key:f.key,value:pi(p)})))))},getItemRaw(u,l={}){u=Ge(u);const{relativeKey:h,driver:f}=r(u);return f.getItemRaw?Pe(f.getItemRaw,h,l):Pe(f.getItem,h,l).then(p=>YO(p))},async setItem(u,l,h={}){if(l===void 0)return c.removeItem(u);u=Ge(u);const{relativeKey:f,driver:p}=r(u);p.setItem&&(await Pe(p.setItem,f,Ui(l),h),p.watch||i("update",u))},async setItems(u,l){await a(u,l,async h=>{if(h.driver.setItems)return Pe(h.driver.setItems,h.items.map(f=>({key:f.relativeKey,value:Ui(f.value),options:f.options})),l);h.driver.setItem&&await Promise.all(h.items.map(f=>Pe(h.driver.setItem,f.relativeKey,Ui(f.value),f.options)))})},async setItemRaw(u,l,h={}){if(l===void 0)return c.removeItem(u,h);u=Ge(u);const{relativeKey:f,driver:p}=r(u);if(p.setItemRaw)await Pe(p.setItemRaw,f,l,h);else if(p.setItem)await Pe(p.setItem,f,GO(l),h);else return;p.watch||i("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=Ge(u);const{relativeKey:h,driver:f}=r(u);f.removeItem&&(await Pe(f.removeItem,h,l),(l.removeMeta||l.removeMata)&&await Pe(f.removeItem,h+"$",l),f.watch||i("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=Ge(u);const{relativeKey:h,driver:f}=r(u),p=Object.create(null);if(f.getMeta&&Object.assign(p,await Pe(f.getMeta,h,l)),!l.nativeOnly){const d=await Pe(f.getItem,h+"$",l).then(y=>pi(y));d&&typeof d=="object"&&(typeof d.atime=="string"&&(d.atime=new Date(d.atime)),typeof d.mtime=="string"&&(d.mtime=new Date(d.mtime)),Object.assign(p,d))}return p},setMeta(u,l,h={}){return this.setItem(u+"$",l,h)},removeMeta(u,l={}){return this.removeItem(u+"$",l)},async getKeys(u,l={}){u=Oi(u);const h=n(u,!0);let f=[];const p=[];let d=!0;for(const w of h){w.driver.flags?.maxDepth||(d=!1);const b=await Pe(w.driver.getKeys,w.relativeBase,l);for(const v of b){const E=w.mountpoint+Ge(v);f.some(O=>E.startsWith(O))||p.push(E)}f=[w.mountpoint,...f.filter(v=>!v.startsWith(w.mountpoint))]}const y=l.maxDepth!==void 0&&!d;return p.filter(w=>(!y||XO(w,l.maxDepth))&&eI(w,u))},async clear(u,l={}){u=Oi(u),await Promise.all(n(u,!1).map(async h=>{if(h.driver.clear)return Pe(h.driver.clear,h.relativeBase,l);if(h.driver.removeItem){const f=await h.driver.getKeys(h.relativeBase||"",l);return Promise.all(f.map(p=>h.driver.removeItem(p,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>nl(u)))},async watch(u){return await s(),e.watchListeners.push(u),async()=>{e.watchListeners=e.watchListeners.filter(l=>l!==u),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(u,l){if(u=Oi(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((h,f)=>f.length-h.length)),e.mounts[u]=l,e.watching&&Promise.resolve(rl(l,i,u)).then(h=>{e.unwatch[u]=h}).catch(console.error),c},async unmount(u,l=!0){u=Oi(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u]?.(),delete e.unwatch[u]),l&&await nl(e.mounts[u]),e.mountpoints=e.mountpoints.filter(h=>h!==u),delete e.mounts[u])},getMount(u=""){u=Ge(u)+":";const l=r(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=Ge(u),n(u,l.parents).map(f=>({driver:f.driver,base:f.mountpoint}))},keys:(u,l={})=>c.getKeys(u,l),get:(u,l={})=>c.getItem(u,l),set:(u,l,h={})=>c.setItem(u,l,h),has:(u,l={})=>c.hasItem(u,l),del:(u,l={})=>c.removeItem(u,l),remove:(u,l={})=>c.removeItem(u,l)};return c}function rl(t,e,r){return t.watch?t.watch((n,i)=>e(n,r+i)):()=>{}}async function nl(t){typeof t.dispose=="function"&&await Pe(t.dispose)}const iI="idb-keyval";var sI=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=i=>e+i;let n;return t.dbName&&t.storeName&&(n=gg(t.dbName,t.storeName)),{name:iI,options:t,async hasItem(i){return!(typeof await Za(r(i),n)>"u")},async getItem(i){return await Za(r(i),n)??null},setItem(i,s){return yg(r(i),s,n)},removeItem(i){return mg(r(i),n)},getKeys(){return wg(n)},clear(){return vg(n)}}};const oI="WALLET_CONNECT_V2_INDEXED_DB",aI="keyvaluestorage";let cI=class{constructor(){this.indexedDb=nI({driver:sI({dbName:oI,storeName:aI})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,Wt(r))}async removeItem(e){await this.indexedDb.removeItem(e)}};var lo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof H<"u"?H:typeof self<"u"?self:{},Fi={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,n){this[r]=String(n)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){const r=this;Object.keys(r).forEach(function(n){r[n]=void 0,delete r[n]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof lo<"u"&&lo.localStorage?Fi.exports=lo.localStorage:typeof window<"u"&&window.localStorage?Fi.exports=window.localStorage:Fi.exports=new e})();function uI(t){var e;return[t[0],wr((e=t[1])!=null?e:"")]}let lI=class{constructor(){this.localStorage=Fi.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(uI)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return wr(r)}async setItem(e,r){this.localStorage.setItem(e,Wt(r))}async removeItem(e){this.localStorage.removeItem(e)}};const hI="wc_storage_version",il=1,fI=async(t,e,r)=>{const n=hI,i=await e.getItem(n);if(i&&i>=il){r(e);return}const s=await t.getKeys();if(!s.length){r(e);return}const o=[];for(;s.length;){const a=s.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const u=await t.getItem(a);await e.setItem(a,u),o.push(a)}}await e.setItem(n,il),r(e),dI(t,o)},dI=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};let pI=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new lI;this.storage=e;try{const r=new cI;fI(e,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}};var Gd={exports:{}},un=typeof Reflect=="object"?Reflect:null,sl=un&&typeof un.apply=="function"?un.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},ki;un&&typeof un.ownKeys=="function"?ki=un.ownKeys:Object.getOwnPropertySymbols?ki=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:ki=function(e){return Object.getOwnPropertyNames(e)};function gI(t){console&&console.warn&&console.warn(t)}var Yd=Number.isNaN||function(e){return e!==e};function ce(){ce.init.call(this)}Gd.exports=ce;Gd.exports.once=vI;ce.EventEmitter=ce;ce.prototype._events=void 0;ce.prototype._eventsCount=0;ce.prototype._maxListeners=void 0;var ol=10;function Ds(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ce,"defaultMaxListeners",{enumerable:!0,get:function(){return ol},set:function(t){if(typeof t!="number"||t<0||Yd(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");ol=t}});ce.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};ce.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Yd(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Jd(t){return t._maxListeners===void 0?ce.defaultMaxListeners:t._maxListeners}ce.prototype.getMaxListeners=function(){return Jd(this)};ce.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")sl(c,this,r);else for(var u=c.length,l=tp(c,u),n=0;n<u;++n)sl(l[n],this,r);return!0};function Zd(t,e,r,n){var i,s,o;if(Ds(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=Jd(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,gI(a)}return t}ce.prototype.addListener=function(e,r){return Zd(this,e,r,!1)};ce.prototype.on=ce.prototype.addListener;ce.prototype.prependListener=function(e,r){return Zd(this,e,r,!0)};function yI(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Qd(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=yI.bind(n);return i.listener=r,n.wrapFn=i,i}ce.prototype.once=function(e,r){return Ds(r),this.on(e,Qd(this,e,r)),this};ce.prototype.prependOnceListener=function(e,r){return Ds(r),this.prependListener(e,Qd(this,e,r)),this};ce.prototype.removeListener=function(e,r){var n,i,s,o,a;if(Ds(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():mI(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};ce.prototype.off=ce.prototype.removeListener;ce.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function Xd(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?wI(i):tp(i,i.length)}ce.prototype.listeners=function(e){return Xd(this,e,!0)};ce.prototype.rawListeners=function(e){return Xd(this,e,!1)};ce.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):ep.call(t,e)};ce.prototype.listenerCount=ep;function ep(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}ce.prototype.eventNames=function(){return this._eventsCount>0?ki(this._events):[]};function tp(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function mI(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function wI(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function vI(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}rp(t,e,s,{once:!0}),e!=="error"&&bI(t,i,{once:!0})})}function bI(t,e,r){typeof t.on=="function"&&rp(t,"error",e,r)}function rp(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var EI=Object.defineProperty,_I=(t,e,r)=>e in t?EI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,al=(t,e,r)=>_I(t,typeof e!="symbol"?e+"":e,r);let $I=class extends Or{constructor(e){super(),this.opts=e,al(this,"protocol","wc"),al(this,"version",2)}};var OI=Object.defineProperty,II=(t,e,r)=>e in t?OI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,PI=(t,e,r)=>II(t,e+"",r);let SI=class extends Or{constructor(e,r){super(),this.core=e,this.logger=r,PI(this,"records",new Map)}},DI=class{constructor(e,r){this.logger=e,this.core=r}};class xI extends Or{constructor(e,r){super(),this.relayer=e,this.logger=r}}let AI=class extends Or{constructor(e){super()}},CI=class{constructor(e,r,n,i){this.core=e,this.logger=r,this.name=n}},LI=class extends Or{constructor(e,r){super(),this.relayer=e,this.logger=r}},RI=class extends Or{constructor(e,r){super(),this.core=e,this.logger=r}},TI=class{constructor(e,r,n){this.core=e,this.logger=r,this.store=n}},NI=class{constructor(e,r){this.projectId=e,this.logger=r}},jI=class{constructor(e,r,n){this.core=e,this.logger=r,this.telemetryEnabled=n}};var MI=Object.defineProperty,BI=(t,e,r)=>e in t?MI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,cl=(t,e,r)=>BI(t,typeof e!="symbol"?e+"":e,r);let UI=class{constructor(e){this.opts=e,cl(this,"protocol","wc"),cl(this,"version",2)}},FI=class{constructor(e){this.client=e}};var kI={VITE_BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23620719480.commit-7d049a4"};const np="wc",ip=2,rs="core",Tt=`${np}@2:${rs}:`,qI={name:rs,logger:"error"},zI={database:":memory:"},HI="crypto",ul="client_ed25519_seed",KI=T.ONE_DAY,VI="keychain",WI="0.3",GI="messages",YI="0.3",ll=T.SIX_HOURS,JI="publisher",sp="irn",ZI="error",op="wss://relay.walletconnect.org",QI="relayer",De={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"},XI="_subscription",at={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},e2=.1,Jo="2.21.1",me={link_mode:"link_mode",relay:"relay"},qi={inbound:"inbound",outbound:"outbound"},t2="0.3",r2="WALLETCONNECT_CLIENT_ID",hl="WALLETCONNECT_LINK_MODE_APPS",tt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},n2="subscription",i2="0.3",s2="pairing",o2="0.3",Tn={wc_pairingDelete:{req:{ttl:T.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:T.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:T.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:T.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:T.ONE_DAY,prompt:!1,tag:0},res:{ttl:T.ONE_DAY,prompt:!1,tag:0}}},dr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},yt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},a2="history",c2="0.3",u2="expirer",ut={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},l2="0.3",h2="verify-api",f2="https://verify.walletconnect.com",ap="https://verify.walletconnect.org",Hn=ap,d2=`${Hn}/v3`,p2=[f2,ap],g2="echo",y2="https://echo.walletconnect.com",St={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"},qt={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"},mt={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"},ar={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"},cr={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",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",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},Nn={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",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"},m2=.1,w2="event-client",v2=86400,b2="https://pulse.walletconnect.org/batch";function E2(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,w=0,b=0,v=d.length;b!==v&&d[b]===0;)b++,y++;for(var E=(v-b)*l+1>>>0,O=new Uint8Array(E);b!==v;){for(var x=d[b],D=0,S=E-1;(x!==0||D<w)&&S!==-1;S--,D++)x+=256*O[S]>>>0,O[S]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");w=D,b++}for(var C=E-w;C!==E&&O[C]===0;)C++;for(var I=c.repeat(y);C<E;++C)I+=t.charAt(O[C]);return I}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var w=0,b=0;d[y]===c;)w++,y++;for(var v=(d.length-y)*u+1>>>0,E=new Uint8Array(v);d[y];){var O=r[d.charCodeAt(y)];if(O===255)return;for(var x=0,D=v-1;(O!==0||x<b)&&D!==-1;D--,x++)O+=a*E[D]>>>0,E[D]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");b=x,y++}if(d[y]!==" "){for(var S=v-b;S!==v&&E[S]===0;)S++;for(var C=new Uint8Array(w+(v-S)),I=w;S!==v;)C[I++]=E[S++];return C}}}function p(d){var y=f(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var _2=E2,$2=_2;const cp=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},O2=t=>new TextEncoder().encode(t),I2=t=>new TextDecoder().decode(t);class P2{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class S2{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}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 up(this,e)}}class D2{constructor(e){this.decoders=e}or(e){return up(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const up=(t,e)=>new D2({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class x2{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new P2(e,r,n),this.decoder=new S2(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const xs=({name:t,prefix:e,encode:r,decode:n})=>new x2(t,e,r,n),di=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=$2(r,e);return xs({prefix:t,name:e,encode:n,decode:s=>cp(i(s))})},A2=(t,e,r,n)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=i[t[l]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},C2=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},Be=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>xs({prefix:e,name:t,encode(i){return C2(i,n,r)},decode(i){return A2(i,n,r,t)}}),L2=xs({prefix:"\0",name:"identity",encode:t=>I2(t),decode:t=>O2(t)});var R2=Object.freeze({__proto__:null,identity:L2});const T2=Be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var N2=Object.freeze({__proto__:null,base2:T2});const j2=Be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var M2=Object.freeze({__proto__:null,base8:j2});const B2=di({prefix:"9",name:"base10",alphabet:"0123456789"});var U2=Object.freeze({__proto__:null,base10:B2});const F2=Be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),k2=Be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var q2=Object.freeze({__proto__:null,base16:F2,base16upper:k2});const z2=Be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),H2=Be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),K2=Be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),V2=Be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),W2=Be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),G2=Be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Y2=Be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),J2=Be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Z2=Be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Q2=Object.freeze({__proto__:null,base32:z2,base32upper:H2,base32pad:K2,base32padupper:V2,base32hex:W2,base32hexupper:G2,base32hexpad:Y2,base32hexpadupper:J2,base32z:Z2});const X2=di({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),eP=di({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var tP=Object.freeze({__proto__:null,base36:X2,base36upper:eP});const rP=di({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),nP=di({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var iP=Object.freeze({__proto__:null,base58btc:rP,base58flickr:nP});const sP=Be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),oP=Be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),aP=Be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),cP=Be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var uP=Object.freeze({__proto__:null,base64:sP,base64pad:oP,base64url:aP,base64urlpad:cP});const lp=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),lP=lp.reduce((t,e,r)=>(t[r]=e,t),[]),hP=lp.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function fP(t){return t.reduce((e,r)=>(e+=lP[r],e),"")}function dP(t){const e=[];for(const r of t){const n=hP[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const pP=xs({prefix:"🚀",name:"base256emoji",encode:fP,decode:dP});var gP=Object.freeze({__proto__:null,base256emoji:pP}),yP=hp,fl=128,mP=127,wP=~mP,vP=Math.pow(2,31);function hp(t,e,r){e=e||[],r=r||0;for(var n=r;t>=vP;)e[r++]=t&255|fl,t/=128;for(;t&wP;)e[r++]=t&255|fl,t>>>=7;return e[r]=t|0,hp.bytes=r-n+1,e}var bP=Zo,EP=128,dl=127;function Zo(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw Zo.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&dl)<<i:(o&dl)*Math.pow(2,i),i+=7}while(o>=EP);return Zo.bytes=s-n,r}var _P=Math.pow(2,7),$P=Math.pow(2,14),OP=Math.pow(2,21),IP=Math.pow(2,28),PP=Math.pow(2,35),SP=Math.pow(2,42),DP=Math.pow(2,49),xP=Math.pow(2,56),AP=Math.pow(2,63),CP=function(t){return t<_P?1:t<$P?2:t<OP?3:t<IP?4:t<PP?5:t<SP?6:t<DP?7:t<xP?8:t<AP?9:10},LP={encode:yP,decode:bP,encodingLength:CP},fp=LP;const pl=(t,e,r=0)=>(fp.encode(t,e,r),e),gl=t=>fp.encodingLength(t),Qo=(t,e)=>{const r=e.byteLength,n=gl(t),i=n+gl(r),s=new Uint8Array(i+r);return pl(t,s,0),pl(r,s,n),s.set(e,i),new RP(t,r,e,s)};class RP{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const dp=({name:t,code:e,encode:r})=>new TP(t,e,r);class TP{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Qo(this.code,r):r.then(n=>Qo(this.code,n))}else throw Error("Unknown type, must be binary type")}}const pp=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),NP=dp({name:"sha2-256",code:18,encode:pp("SHA-256")}),jP=dp({name:"sha2-512",code:19,encode:pp("SHA-512")});var MP=Object.freeze({__proto__:null,sha256:NP,sha512:jP});const gp=0,BP="identity",yp=cp,UP=t=>Qo(gp,yp(t)),FP={code:gp,name:BP,encode:yp,digest:UP};var kP=Object.freeze({__proto__:null,identity:FP});new TextEncoder,new TextDecoder;const yl={...R2,...N2,...M2,...U2,...q2,...Q2,...tP,...iP,...uP,...gP};({...MP,...kP});function qP(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function mp(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const ml=mp("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ho=mp("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=qP(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),zP={utf8:ml,"utf-8":ml,hex:yl.base16,latin1:ho,ascii:ho,binary:ho,...yl};function HP(t,e="utf8"){const r=zP[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}var KP=Object.defineProperty,VP=(t,e,r)=>e in t?KP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,It=(t,e,r)=>VP(t,typeof e!="symbol"?e+"":e,r);class WP{constructor(e,r){this.core=e,this.logger=r,It(this,"keychain",new Map),It(this,"name",VI),It(this,"version",WI),It(this,"initialized",!1),It(this,"storagePrefix",Tt),It(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),It(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),It(this,"set",async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()}),It(this,"get",n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=N("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i}),It(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=Ke(r,this.name)}get context(){return Qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Mo(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Bo(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var GP=Object.defineProperty,YP=(t,e,r)=>e in t?GP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Te=(t,e,r)=>YP(t,typeof e!="symbol"?e+"":e,r);class JP{constructor(e,r,n){this.core=e,this.logger=r,Te(this,"name",HI),Te(this,"keychain"),Te(this,"randomSessionIdentifier",Go()),Te(this,"initialized",!1),Te(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Te(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Te(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=Lc(i);return rf(s.publicKey)}),Te(this,"generateKeyPair",()=>{this.isInitialized();const i=N$();return this.setPrivateKey(i.publicKey,i.privateKey)}),Te(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=Lc(s),a=this.randomSessionIdentifier;return await Dv(a,i,KI,o)}),Te(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=j$(a,s);return this.setSymKey(c,o)}),Te(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||Mi(i);return await this.keychain.set(o,i),o}),Te(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Te(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Te(this,"encode",async(i,s,o)=>{this.isInitialized();const a=Md(o),c=Wt(s);if(qu(a))return U$(c,o?.encoding);if(ku(a)){const f=a.senderPublicKey,p=a.receiverPublicKey;i=await this.generateSharedKey(f,p)}const u=this.getSymKey(i),{type:l,senderPublicKey:h}=a;return M$({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o?.encoding})}),Te(this,"decode",async(i,s,o)=>{this.isInitialized();const a=k$(s,o);if(qu(a)){const c=F$(s,o?.encoding);return wr(c)}if(ku(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=B$({symKey:c,encoded:s,encoding:o?.encoding});return wr(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Te(this,"getPayloadType",(i,s=bt)=>{const o=ti({encoded:i,encoding:s});return $r(o.type)}),Te(this,"getPayloadSenderPublicKey",(i,s=bt)=>{const o=ti({encoded:i,encoding:s});return o.senderPublicKey?Ze(o.senderPublicKey,He):void 0}),this.core=e,this.logger=Ke(r,this.name),this.keychain=n||new WP(this.core,this.logger)}get context(){return Qe(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(ul)}catch{e=Go(),await this.keychain.set(ul,e)}return HP(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var ZP=Object.defineProperty,QP=Object.defineProperties,XP=Object.getOwnPropertyDescriptors,wl=Object.getOwnPropertySymbols,eS=Object.prototype.hasOwnProperty,tS=Object.prototype.propertyIsEnumerable,Xo=(t,e,r)=>e in t?ZP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rS=(t,e)=>{for(var r in e||(e={}))eS.call(e,r)&&Xo(t,r,e[r]);if(wl)for(var r of wl(e))tS.call(e,r)&&Xo(t,r,e[r]);return t},nS=(t,e)=>QP(t,XP(e)),Xe=(t,e,r)=>Xo(t,typeof e!="symbol"?e+"":e,r);class iS extends DI{constructor(e,r){super(e,r),this.logger=e,this.core=r,Xe(this,"messages",new Map),Xe(this,"messagesWithoutClientAck",new Map),Xe(this,"name",GI),Xe(this,"version",YI),Xe(this,"initialized",!1),Xe(this,"storagePrefix",Tt),Xe(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}}),Xe(this,"set",async(n,i,s)=>{this.isInitialized();const o=Ct(i);let a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(n,a),s===qi.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,nS(rS({},c),{[o]:i}))}return await this.persist(),o}),Xe(this,"get",n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i}),Xe(this,"getWithoutAck",n=>{this.isInitialized();const i={};for(const s of n){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),Xe(this,"has",(n,i)=>{this.isInitialized();const s=this.get(n),o=Ct(i);return typeof s[o]<"u"}),Xe(this,"ack",async(n,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;const o=Ct(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),Xe(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=Ke(e,this.name),this.core=r}get context(){return Qe(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,Mo(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Mo(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Bo(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Bo(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var sS=Object.defineProperty,oS=Object.defineProperties,aS=Object.getOwnPropertyDescriptors,vl=Object.getOwnPropertySymbols,cS=Object.prototype.hasOwnProperty,uS=Object.prototype.propertyIsEnumerable,ea=(t,e,r)=>e in t?sS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ii=(t,e)=>{for(var r in e||(e={}))cS.call(e,r)&&ea(t,r,e[r]);if(vl)for(var r of vl(e))uS.call(e,r)&&ea(t,r,e[r]);return t},fo=(t,e)=>oS(t,aS(e)),wt=(t,e,r)=>ea(t,typeof e!="symbol"?e+"":e,r);class lS extends xI{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,wt(this,"events",new Sr.EventEmitter),wt(this,"name",JI),wt(this,"queue",new Map),wt(this,"publishTimeout",T.toMiliseconds(T.ONE_MINUTE)),wt(this,"initialPublishTimeout",T.toMiliseconds(T.ONE_SECOND*15)),wt(this,"needsTransportRestart",!1),wt(this,"publish",async(n,i,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});const a=s?.ttl||ll,c=es(s),u=s?.prompt||!1,l=s?.tag||0,h=s?.id||gr().toString(),f={topic:n,message:i,opts:{ttl:a,relay:c,prompt:u,tag:l,id:h,attestation:s?.attestation,tvf:s?.tvf}},p=`Failed to publish payload, please try again. id:${h} tag:${l}`;try{const d=new Promise(async y=>{const w=({id:v})=>{f.opts.id===v&&(this.removeRequestFromQueue(v),this.relayer.events.removeListener(De.publish,w),y(f))};this.relayer.events.on(De.publish,w);const b=tr(new Promise((v,E)=>{this.rpcPublish({topic:n,message:i,ttl:a,prompt:u,tag:l,id:h,attestation:s?.attestation,tvf:s?.tvf}).then(v).catch(O=>{this.logger.warn(O,O?.message),E(O)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${h} tag:${l}`);try{await b,this.events.removeListener(De.publish,w)}catch(v){this.queue.set(h,fo(Ii({},f),{attempt:1})),this.logger.warn(v,v?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:h,topic:n,message:i,opts:s}}),await tr(d,this.publishTimeout,p)}catch(d){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(d),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw d}finally{this.queue.delete(h)}}),wt(this,"on",(n,i)=>{this.events.on(n,i)}),wt(this,"once",(n,i)=>{this.events.once(n,i)}),wt(this,"off",(n,i)=>{this.events.off(n,i)}),wt(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.relayer=e,this.logger=Ke(r,this.name),this.registerEventListeners()}get context(){return Qe(this.logger)}async rpcPublish(e){var r,n,i,s;const{topic:o,message:a,ttl:c=ll,prompt:u,tag:l,id:h,attestation:f,tvf:p}=e,d={method:Un(es().protocol).publish,params:Ii({topic:o,message:a,ttl:c,prompt:u,tag:l,attestation:f},p),id:h};ke((r=d.params)==null?void 0:r.prompt)&&((n=d.params)==null||delete n.prompt),ke((i=d.params)==null?void 0:i.tag)&&((s=d.params)==null||delete s.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:d});const y=await this.relayer.request(d);return this.relayer.events.emit(De.publish,e),this.logger.debug("Successfully Published Payload"),y}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const n=e.attempt+1;this.queue.set(r,fo(Ii({},e),{attempt:n}));const{topic:i,message:s,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${n}`),await this.rpcPublish(fo(Ii({},e),{topic:i,message:s,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(Ir.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(De.connection_stalled);return}this.checkQueue()}),this.relayer.on(De.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var hS=Object.defineProperty,fS=(t,e,r)=>e in t?hS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Br=(t,e,r)=>fS(t,typeof e!="symbol"?e+"":e,r);class dS{constructor(){Br(this,"map",new Map),Br(this,"set",(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])}),Br(this,"get",e=>this.map.get(e)||[]),Br(this,"exists",(e,r)=>this.get(e).includes(r)),Br(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),Br(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var pS=Object.defineProperty,gS=Object.defineProperties,yS=Object.getOwnPropertyDescriptors,bl=Object.getOwnPropertySymbols,mS=Object.prototype.hasOwnProperty,wS=Object.prototype.propertyIsEnumerable,ta=(t,e,r)=>e in t?pS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jn=(t,e)=>{for(var r in e||(e={}))mS.call(e,r)&&ta(t,r,e[r]);if(bl)for(var r of bl(e))wS.call(e,r)&&ta(t,r,e[r]);return t},po=(t,e)=>gS(t,yS(e)),fe=(t,e,r)=>ta(t,typeof e!="symbol"?e+"":e,r);class vS extends LI{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,fe(this,"subscriptions",new Map),fe(this,"topicMap",new dS),fe(this,"events",new Sr.EventEmitter),fe(this,"name",n2),fe(this,"version",i2),fe(this,"pending",new Map),fe(this,"cached",[]),fe(this,"initialized",!1),fe(this,"storagePrefix",Tt),fe(this,"subscribeTimeout",T.toMiliseconds(T.ONE_MINUTE)),fe(this,"initialSubscribeTimeout",T.toMiliseconds(T.ONE_SECOND*15)),fe(this,"clientId"),fe(this,"batchSubscribeTopicsLimit",500),fe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),fe(this,"subscribe",async(n,i)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const s=es(i),o={topic:n,relay:s,transportType:i?.transportType};this.pending.set(n,o);const a=await this.rpcSubscribe(n,s,i);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}}),fe(this,"unsubscribe",async(n,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)}),fe(this,"isSubscribed",n=>new Promise(i=>{i(this.topicMap.topics.includes(n))})),fe(this,"isKnownTopic",n=>new Promise(i=>{i(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),fe(this,"on",(n,i)=>{this.events.on(n,i)}),fe(this,"once",(n,i)=>{this.events.once(n,i)}),fe(this,"off",(n,i)=>{this.events.off(n,i)}),fe(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),fe(this,"start",async()=>{await this.onConnect()}),fe(this,"stop",async()=>{await this.onDisconnect()}),fe(this,"restart",async()=>{await this.restore(),await this.onRestart()}),fe(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const n=[];this.pending.forEach(i=>{n.push(i)}),await this.batchSubscribe(n)}),fe(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Ir.pulse,async()=>{await this.checkPending()}),this.events.on(tt.created,async n=>{const i=tt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()}),this.events.on(tt.deleted,async n=>{const i=tt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()})}),this.relayer=e,this.logger=Ke(r,this.name),this.clientId=""}get context(){return Qe(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,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=es(n);await this.restartToComplete({topic:e,id:r,relay:i}),await this.rpcUnsubscribe(e,r,i);const s=re("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r,n){var i;(!n||n?.transportType===me.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const s={method:Un(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});const o=(i=n?.internal)==null?void 0:i.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(n?.transportType===me.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(l=>this.logger.warn(l))},T.toMiliseconds(T.ONE_SECOND)),a;const c=new Promise(async l=>{const h=f=>{f.topic===e&&(this.events.removeListener(tt.created,h),l(f.id))};this.events.on(tt.created,h);try{const f=await tr(new Promise((p,d)=>{this.relayer.request(s).catch(y=>{this.logger.warn(y,y?.message),d(y)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(tt.created,h),l(f)}catch{}}),u=await tr(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return u?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(De.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Un(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await tr(new Promise(i=>{this.relayer.request(n).catch(s=>this.logger.warn(s)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(De.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:Un(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let i;try{i=await await tr(new Promise((s,o)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(De.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:Un(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,po(jn({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,jn({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),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,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,jn({},r)),this.topicMap.set(r.topic,e),this.events.emit(tt.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=N("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(tt.deleted,po(jn({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(tt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<r;n++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(tt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=N("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}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 r=>po(jn({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await _1(T.toMiliseconds(T.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=N("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 Ct(e+await this.getClientId())}}var bS=Object.defineProperty,El=Object.getOwnPropertySymbols,ES=Object.prototype.hasOwnProperty,_S=Object.prototype.propertyIsEnumerable,ra=(t,e,r)=>e in t?bS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_l=(t,e)=>{for(var r in e||(e={}))ES.call(e,r)&&ra(t,r,e[r]);if(El)for(var r of El(e))_S.call(e,r)&&ra(t,r,e[r]);return t},Q=(t,e,r)=>ra(t,typeof e!="symbol"?e+"":e,r);class $S extends AI{constructor(e){super(e),Q(this,"protocol","wc"),Q(this,"version",2),Q(this,"core"),Q(this,"logger"),Q(this,"events",new Sr.EventEmitter),Q(this,"provider"),Q(this,"messages"),Q(this,"subscriber"),Q(this,"publisher"),Q(this,"name",QI),Q(this,"transportExplicitlyClosed",!1),Q(this,"initialized",!1),Q(this,"connectionAttemptInProgress",!1),Q(this,"relayUrl"),Q(this,"projectId"),Q(this,"packageName"),Q(this,"bundleId"),Q(this,"hasExperiencedNetworkDisruption",!1),Q(this,"pingTimeout"),Q(this,"heartBeatTimeout",T.toMiliseconds(T.THIRTY_SECONDS+T.FIVE_SECONDS)),Q(this,"reconnectTimeout"),Q(this,"connectPromise"),Q(this,"reconnectInProgress",!1),Q(this,"requestsInFlight",[]),Q(this,"connectTimeout",T.toMiliseconds(T.ONE_SECOND*15)),Q(this,"request",async r=>{var n,i;this.logger.debug("Publishing Request Payload");const s=r.id||gr().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - publishing...");const o=`${s}:${((i=r.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}}),Q(this,"resetPingTimeout",()=>{Qi()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,i,s;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(s=(i=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null?void 0:i.terminate)==null||s.call(i)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),Q(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),Q(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(De.connect)}),Q(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Q(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(De.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Q(this,"registerProviderListeners",()=>{this.provider.on(at.payload,this.onPayloadHandler),this.provider.on(at.connect,this.onConnectHandler),this.provider.on(at.disconnect,this.onDisconnectHandler),this.provider.on(at.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Ke(e.logger,this.name):ni(us({level:e.logger||ZI})),this.messages=new iS(this.logger,e.core),this.subscriber=new vS(this,this.logger),this.publisher=new lS(this,this.logger),this.relayUrl=e?.relayUrl||op,this.projectId=e.projectId,o1()?this.packageName=hu():a1()&&(this.bundleId=hu()),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?.message)}}get context(){return Qe(this.logger)}get connected(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1||!1}get connecting(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:me.relay},qi.outbound)}async subscribe(e,r){var n,i,s;this.isInitialized(),(!(r!=null&&r.transportType)||r?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((n=r?.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(i=r?.internal)==null?void 0:i.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(tt.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(tt.created,u)}),new Promise(async(l,h)=>{a=await this.subscriber.subscribe(e,_l({internal:{throwOnFailedPublish:o}},r)).catch(f=>{o&&h(f)})||a,l()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await tr(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(r,n)=>{await this.connect(e).then(r).catch(n).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 Xu())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const r=e.sort((n,i)=>n.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const n of r)try{await this.onMessageEvent(n)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:n}=e;if(!r.sessionExists){const i=_e(T.FIVE_MINUTES),s={topic:n,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(De.message,e),await this.recordMessageEvent(e,qi.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(n,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(at.disconnect,s),await tr(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{i(o)}).finally(()=>{this.provider.off(at.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(at.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(at.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,n()})}catch(n){await this.subscriber.stop();const i=n;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(n=>setTimeout(n,T.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,n,i,s;if(Qi())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(i=(n=this.provider)==null?void 0:n.connection)==null?void 0:i.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new dt(new Q0(f1({sdkVersion:Jo,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,r){const{topic:n,message:i}=e;await this.messages.set(n,i,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const i=this.messages.has(r,n);return i&&this.logger.warn(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Ia(e)){if(!e.method.endsWith(XI))return;const r=e.params,{topic:n,message:i,publishedAt:s,attestation:o}=r.data,a={topic:n,message:i,publishedAt:s,transportType:me.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(_l({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ms(e)&&this.events.emit(De.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,qi.inbound),this.events.emit(De.message,e))}async acknowledgePayload(e){const r=gs(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(at.payload,this.onPayloadHandler),this.provider.off(at.connect,this.onConnectHandler),this.provider.off(at.disconnect,this.onDisconnectHandler),this.provider.off(at.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Xu();TO(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(n=>this.logger.error(n,n?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Ir.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&MO())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(De.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?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},T.toMiliseconds(e2)))))}isInitialized(){if(!this.initialized){const{message:e}=N("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 OS(){}function $l(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function Ol(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Il(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const IS="[object RegExp]",PS="[object String]",SS="[object Number]",DS="[object Boolean]",Pl="[object Arguments]",xS="[object Symbol]",AS="[object Date]",CS="[object Map]",LS="[object Set]",RS="[object Array]",TS="[object Function]",NS="[object ArrayBuffer]",go="[object Object]",jS="[object Error]",MS="[object DataView]",BS="[object Uint8Array]",US="[object Uint8ClampedArray]",FS="[object Uint16Array]",kS="[object Uint32Array]",qS="[object BigUint64Array]",zS="[object Int8Array]",HS="[object Int16Array]",KS="[object Int32Array]",VS="[object BigInt64Array]",WS="[object Float32Array]",GS="[object Float64Array]";function YS(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function JS(t,e,r){return Fn(t,e,void 0,void 0,void 0,void 0,r)}function Fn(t,e,r,n,i,s,o){const a=o(t,e,r,n,i,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Kn(t,e,s,o)}return Kn(t,e,s,o)}function Kn(t,e,r,n){if(Object.is(t,e))return!0;let i=Il(t),s=Il(e);if(i===Pl&&(i=go),s===Pl&&(s=go),i!==s)return!1;switch(i){case PS:return t.toString()===e.toString();case SS:{const c=t.valueOf(),u=e.valueOf();return YS(c,u)}case DS:case AS:case xS:return Object.is(t.valueOf(),e.valueOf());case IS:return t.source===e.source&&t.flags===e.flags;case TS:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(i){case CS:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!Fn(u,e.get(c),c,t,e,r,n))return!1;return!0}case LS:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let l=0;l<c.length;l++){const h=c[l],f=u.findIndex(p=>Fn(h,p,void 0,t,e,r,n));if(f===-1)return!1;u.splice(f,1)}return!0}case RS:case BS:case US:case FS:case kS:case qS:case zS:case HS:case KS:case VS:case WS:case GS:{if(typeof Ce<"u"&&Ce.isBuffer(t)!==Ce.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Fn(t[c],e[c],c,t,e,r,n))return!1;return!0}case NS:return t.byteLength!==e.byteLength?!1:Kn(new Uint8Array(t),new Uint8Array(e),r,n);case MS:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Kn(new Uint8Array(t),new Uint8Array(e),r,n);case jS:return t.name===e.name&&t.message===e.message;case go:{if(!(Kn(t.constructor,e.constructor,r,n)||$l(t)&&$l(e)))return!1;const c=[...Object.keys(t),...Ol(t)],u=[...Object.keys(e),...Ol(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const h=c[l],f=t[h];if(!Object.hasOwn(e,h))return!1;const p=e[h];if(!Fn(f,p,h,t,e,r,n))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function ZS(t,e){return JS(t,e,OS)}var QS=Object.defineProperty,Sl=Object.getOwnPropertySymbols,XS=Object.prototype.hasOwnProperty,eD=Object.prototype.propertyIsEnumerable,na=(t,e,r)=>e in t?QS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Dl=(t,e)=>{for(var r in e||(e={}))XS.call(e,r)&&na(t,r,e[r]);if(Sl)for(var r of Sl(e))eD.call(e,r)&&na(t,r,e[r]);return t},We=(t,e,r)=>na(t,typeof e!="symbol"?e+"":e,r);class Dr extends CI{constructor(e,r,n,i=Tt,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,We(this,"map",new Map),We(this,"version",t2),We(this,"cached",[]),We(this,"initialized",!1),We(this,"getKey"),We(this,"storagePrefix",Tt),We(this,"recentlyDeleted",[]),We(this,"recentlyDeletedLimit",200),We(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!ke(o)?this.map.set(this.getKey(o),o):hO(o)?this.map.set(o.id,o):fO(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),We(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())}),We(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),We(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>ZS(a[c],o[c]))):this.values)),We(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=Dl(Dl({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),We(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=Ke(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return Qe(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 r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:i}=N("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=N("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}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:r}=N("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var tD=Object.defineProperty,rD=(t,e,r)=>e in t?tD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,W=(t,e,r)=>rD(t,typeof e!="symbol"?e+"":e,r);class nD{constructor(e,r){this.core=e,this.logger=r,W(this,"name",s2),W(this,"version",o2),W(this,"events",new HO),W(this,"pairings"),W(this,"initialized",!1),W(this,"storagePrefix",Tt),W(this,"ignoredPayloadTypes",[Vt]),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:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),W(this,"create",async n=>{this.isInitialized();const i=Go(),s=await this.core.crypto.setSymKey(i),o=_e(T.FIVE_MINUTES),a={protocol:sp},c={topic:s,expiry:o,relay:a,active:!1,methods:n?.methods},u=Hu({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(dr.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType}),{topic:s,uri:u}}),W(this,"pair",async n=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[St.pairing_started]}});this.isValidPair(n,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=zu(n.uri);i.props.properties.topic=s,i.addTrace(St.pairing_uri_validation_success),i.addTrace(St.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(St.existing_pairing),l.active)throw i.setError(qt.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(St.pairing_not_expired)}const h=c||_e(T.FIVE_MINUTES),f={topic:s,relay:a,expiry:h,active:!1,methods:u};this.core.expirer.set(s,h),await this.pairings.set(s,f),i.addTrace(St.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(dr.create,f),i.addTrace(St.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(St.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(qt.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(p){throw i.setError(qt.subscribe_pairing_topic_failure),p}return i.addTrace(St.subscribe_pairing_topic_success),f}),W(this,"activate",async({topic:n})=>{this.isInitialized();const i=_e(T.FIVE_MINUTES);this.core.expirer.set(n,i),await this.pairings.update(n,{active:!0,expiry:i})}),W(this,"ping",async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=n;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=ur();this.events.once(ee("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),W(this,"updateExpiry",async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})}),W(this,"updateMetadata",async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})}),W(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),W(this,"disconnect",async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",re("USER_DISCONNECTED")),await this.deletePairing(i))}),W(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(i);return Hu({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),W(this,"sendRequest",async(n,i,s)=>{const o=er(i,s),a=await this.core.crypto.encode(n,o),c=Tn[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),W(this,"sendResult",async(n,i,s)=>{const o=gs(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Tn[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),W(this,"sendError",async(n,i,s)=>{const o=ys(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Tn[c]?Tn[c].res:Tn.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),W(this,"deletePairing",async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,re("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])}),W(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(i=>Qt(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))}),W(this,"onRelayEventRequest",async n=>{const{topic:i,payload:s}=n;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,s);default:return await this.onUnknownRpcMethodRequest(i,s)}}),W(this,"onRelayEventResponse",async n=>{const{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}}),W(this,"onPairingPingRequest",async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(dr.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),W(this,"onPairingPingResponse",(n,i)=>{const{id:s}=i;setTimeout(()=>{xt(i)?this.events.emit(ee("pairing_ping",s),{}):lt(i)&&this.events.emit(ee("pairing_ping",s),{error:i.error})},500)}),W(this,"onPairingDeleteRequest",async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(dr.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),W(this,"onUnknownRpcMethodRequest",async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=re("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}}),W(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(re("WC_METHOD_UNSUPPORTED",n))}),W(this,"isValidPair",(n,i)=>{var s;if(!Ye(n)){const{message:a}=N("MISSING_OR_INVALID",`pair() params: ${n}`);throw i.setError(qt.malformed_pairing_uri),new Error(a)}if(!lO(n.uri)){const{message:a}=N("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw i.setError(qt.malformed_pairing_uri),new Error(a)}const o=zu(n?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=N("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(qt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=N("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(qt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&T.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(qt.pairing_expired);const{message:a}=N("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),W(this,"isValidPing",async n=>{if(!Ye(n)){const{message:s}=N("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),W(this,"isValidDisconnect",async n=>{if(!Ye(n)){const{message:s}=N("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),W(this,"isValidPairingTopic",async n=>{if(!Ee(n,!1)){const{message:i}=N("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=N("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(Qt(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=N("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}}),this.core=e,this.logger=Ke(r,this.name),this.pairings=new Dr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Qe(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(De.message,async e=>{const{topic:r,message:n,transportType:i}=e;if(this.pairings.keys.includes(r)&&i!==me.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const s=await this.core.crypto.decode(r,n);Ia(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ms(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,n)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(ut.expired,async e=>{const{topic:r}=id(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(dr.expire,{topic:r}))})}}var iD=Object.defineProperty,sD=(t,e,r)=>e in t?iD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ne=(t,e,r)=>sD(t,typeof e!="symbol"?e+"":e,r);class oD extends SI{constructor(e,r){super(e,r),this.core=e,this.logger=r,Ne(this,"records",new Map),Ne(this,"events",new Sr.EventEmitter),Ne(this,"name",a2),Ne(this,"version",c2),Ne(this,"cached",[]),Ne(this,"initialized",!1),Ne(this,"storagePrefix",Tt),Ne(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ne(this,"set",(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s,expiry:_e(T.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(yt.created,o)}),Ne(this,"resolve",async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=lt(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(yt.updated,i))}),Ne(this,"get",async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i))),Ne(this,"delete",(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(yt.deleted,s)}}),this.persist()}),Ne(this,"exists",async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1)),Ne(this,"on",(n,i)=>{this.events.on(n,i)}),Ne(this,"once",(n,i)=>{this.events.once(n,i)}),Ne(this,"off",(n,i)=>{this.events.off(n,i)}),Ne(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=Ke(r,this.name)}get context(){return Qe(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(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:er(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),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 r=this.records.get(e);if(!r){const{message:n}=N("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(yt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=N("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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(yt.created,e=>{const r=yt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(yt.updated,e=>{const r=yt.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(yt.deleted,e=>{const r=yt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(Ir.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{T.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(yt.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var aD=Object.defineProperty,cD=(t,e,r)=>e in t?aD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fe=(t,e,r)=>cD(t,typeof e!="symbol"?e+"":e,r);class uD extends RI{constructor(e,r){super(e,r),this.core=e,this.logger=r,Fe(this,"expirations",new Map),Fe(this,"events",new Sr.EventEmitter),Fe(this,"name",u2),Fe(this,"version",l2),Fe(this,"cached",[]),Fe(this,"initialized",!1),Fe(this,"storagePrefix",Tt),Fe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Fe(this,"has",n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}}),Fe(this,"set",(n,i)=>{this.isInitialized();const s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(ut.created,{target:s,expiration:o})}),Fe(this,"get",n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)}),Fe(this,"del",n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(ut.deleted,{target:i,expiration:s})}}),Fe(this,"on",(n,i)=>{this.events.on(n,i)}),Fe(this,"once",(n,i)=>{this.events.once(n,i)}),Fe(this,"off",(n,i)=>{this.events.off(n,i)}),Fe(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=Ke(r,this.name)}get context(){return Qe(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 d1(e);if(typeof e=="number")return p1(e);const{message:r}=N("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}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(ut.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=N("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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 r=this.expirations.get(e);if(!r){const{message:n}=N("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;T.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(ut.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Ir.pulse,()=>this.checkExpirations()),this.events.on(ut.created,e=>{const r=ut.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(ut.expired,e=>{const r=ut.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(ut.deleted,e=>{const r=ut.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var lD=Object.defineProperty,hD=(t,e,r)=>e in t?lD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,be=(t,e,r)=>hD(t,typeof e!="symbol"?e+"":e,r);class fD extends TI{constructor(e,r,n){super(e,r,n),this.core=e,this.logger=r,this.store=n,be(this,"name",h2),be(this,"abortController"),be(this,"isDevEnv"),be(this,"verifyUrlV3",d2),be(this,"storagePrefix",Tt),be(this,"version",ip),be(this,"publicKey"),be(this,"fetchPromise"),be(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&T.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),be(this,"register",async i=>{if(!On()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const u=vr(),l=this.startAbortTimer(T.ONE_SECOND*5),h=await new Promise((f,p)=>{const d=()=>{window.removeEventListener("message",w),u.body.removeChild(y),p("attestation aborted")};this.abortController.signal.addEventListener("abort",d);const y=u.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",d,{signal:this.abortController.signal});const w=b=>{if(b.data&&typeof b.data=="string")try{const v=JSON.parse(b.data);if(v.type==="verify_attestation"){if(Co(v.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(y),this.abortController.signal.removeEventListener("abort",d),window.removeEventListener("message",w),f(v.attestation===null?"":v.attestation)}}catch(v){this.logger.warn(v)}};u.body.appendChild(y),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",h),h}catch(u){this.logger.warn(u)}return""}),be(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=i;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Co(s).payload.id!==a)return;const u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!o)return;const c=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(o,c)}),be(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(T.ONE_SECOND*5),a=await fetch(`${s}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),be(this,"getVerifyUrl",i=>{let s=i||Hn;return p2.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Hn}`),s=Hn),s}),be(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(T.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await s.json()}catch(i){this.logger.warn(i)}}),be(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),be(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),be(this,"isValidJwtAttestation",async i=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(i,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),be(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),be(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),be(this,"validateAttestation",(i,s)=>{const o=z$(i,s.publicKey),a={hasExpired:T.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=Ke(r,this.name),this.abortController=new AbortController,this.isDevEnv=xa(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Qe(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),T.toMiliseconds(e))}}var dD=Object.defineProperty,pD=(t,e,r)=>e in t?dD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xl=(t,e,r)=>pD(t,typeof e!="symbol"?e+"":e,r);class gD extends NI{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,xl(this,"context",g2),xl(this,"registerDeviceToken",async n=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,c=`${y2}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:a})})}),this.logger=Ke(r,this.context)}}var yD=Object.defineProperty,Al=Object.getOwnPropertySymbols,mD=Object.prototype.hasOwnProperty,wD=Object.prototype.propertyIsEnumerable,ia=(t,e,r)=>e in t?yD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mn=(t,e)=>{for(var r in e||(e={}))mD.call(e,r)&&ia(t,r,e[r]);if(Al)for(var r of Al(e))wD.call(e,r)&&ia(t,r,e[r]);return t},Oe=(t,e,r)=>ia(t,typeof e!="symbol"?e+"":e,r);class vD extends jI{constructor(e,r,n=!0){super(e,r,n),this.core=e,this.logger=r,Oe(this,"context",w2),Oe(this,"storagePrefix",Tt),Oe(this,"storageVersion",m2),Oe(this,"events",new Map),Oe(this,"shouldPersist",!1),Oe(this,"init",async()=>{if(!xa())try{const i={eventId:du(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:rd(this.core.relayer.protocol,this.core.relayer.version,Jo)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Oe(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,u=du(),l=this.core.projectId||"",h=Date.now(),f=Mn({eventId:u,timestamp:h,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,f),this.shouldPersist=!0),f}),Oe(this,"getEvent",i=>{const{eventId:s,topic:o}=i;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Mn(Mn({},a),this.setMethods(a.eventId))}),Oe(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),Oe(this,"setEventListeners",()=>{this.core.heartbeat.on(Ir.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{T.fromMiliseconds(Date.now())-T.fromMiliseconds(i.timestamp)>v2&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Oe(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),Oe(this,"addTrace",(i,s)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(s),this.events.set(i,o),this.shouldPersist=!0)}),Oe(this,"setError",(i,s)=>{const o=this.events.get(i);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),Oe(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Oe(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(s=>{this.events.set(s.eventId,Mn(Mn({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),Oe(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[s,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const s of i)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),Oe(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${b2}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Jo}${s}`,{method:"POST",body:JSON.stringify(i)})}),Oe(this,"getAppDomain",()=>td().url),this.logger=Ke(r,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var bD=Object.defineProperty,Cl=Object.getOwnPropertySymbols,ED=Object.prototype.hasOwnProperty,_D=Object.prototype.propertyIsEnumerable,sa=(t,e,r)=>e in t?bD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ll=(t,e)=>{for(var r in e||(e={}))ED.call(e,r)&&sa(t,r,e[r]);if(Cl)for(var r of Cl(e))_D.call(e,r)&&sa(t,r,e[r]);return t},ge=(t,e,r)=>sa(t,typeof e!="symbol"?e+"":e,r);let $D=class wp extends $I{constructor(e){var r;super(e),ge(this,"protocol",np),ge(this,"version",ip),ge(this,"name",rs),ge(this,"relayUrl"),ge(this,"projectId"),ge(this,"customStoragePrefix"),ge(this,"events",new Sr.EventEmitter),ge(this,"logger"),ge(this,"heartbeat"),ge(this,"relayer"),ge(this,"crypto"),ge(this,"storage"),ge(this,"history"),ge(this,"expirer"),ge(this,"pairing"),ge(this,"verify"),ge(this,"echoClient"),ge(this,"linkModeSupportedApps"),ge(this,"eventClient"),ge(this,"initialized",!1),ge(this,"logChunkController"),ge(this,"on",(a,c)=>this.events.on(a,c)),ge(this,"once",(a,c)=>this.events.once(a,c)),ge(this,"off",(a,c)=>this.events.off(a,c)),ge(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ge(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:me.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const n=this.getGlobalCore(e?.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||op,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=us({level:typeof e?.logger=="string"&&e.logger?e.logger:qI.logger,name:rs}),{logger:s,chunkLoggerController:o}=My({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.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=Ke(s,this.name),this.heartbeat=new ry,this.crypto=new JP(this,this.logger,e?.keychain),this.history=new oD(this,this.logger),this.expirer=new uD(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new pI(Ll(Ll({},zI),e?.storageOptions)),this.relayer=new $S({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new nD(this,this.logger),this.verify=new fD(this,this.logger,this.storage),this.echoClient=new gD(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new vD(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new wp(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(r2,n),r}get context(){return Qe(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(hl,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(hl)||[],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 r=`_walletConnectCore_${e}`,n=`${r}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[n]=e}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof ft<"u"&&kI.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const OD=$D;var Ba={exports:{}},ln=typeof Reflect=="object"?Reflect:null,Rl=ln&&typeof ln.apply=="function"?ln.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},zi;ln&&typeof ln.ownKeys=="function"?zi=ln.ownKeys:Object.getOwnPropertySymbols?zi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:zi=function(e){return Object.getOwnPropertyNames(e)};function ID(t){console&&console.warn&&console.warn(t)}var vp=Number.isNaN||function(e){return e!==e};function ue(){ue.init.call(this)}Ba.exports=ue;Ba.exports.once=xD;ue.EventEmitter=ue;ue.prototype._events=void 0;ue.prototype._eventsCount=0;ue.prototype._maxListeners=void 0;var Tl=10;function As(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ue,"defaultMaxListeners",{enumerable:!0,get:function(){return Tl},set:function(t){if(typeof t!="number"||t<0||vp(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Tl=t}});ue.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};ue.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||vp(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function bp(t){return t._maxListeners===void 0?ue.defaultMaxListeners:t._maxListeners}ue.prototype.getMaxListeners=function(){return bp(this)};ue.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")Rl(c,this,r);else for(var u=c.length,l=Ip(c,u),n=0;n<u;++n)Rl(l[n],this,r);return!0};function Ep(t,e,r,n){var i,s,o;if(As(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=bp(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,ID(a)}return t}ue.prototype.addListener=function(e,r){return Ep(this,e,r,!1)};ue.prototype.on=ue.prototype.addListener;ue.prototype.prependListener=function(e,r){return Ep(this,e,r,!0)};function PD(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _p(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=PD.bind(n);return i.listener=r,n.wrapFn=i,i}ue.prototype.once=function(e,r){return As(r),this.on(e,_p(this,e,r)),this};ue.prototype.prependOnceListener=function(e,r){return As(r),this.prependListener(e,_p(this,e,r)),this};ue.prototype.removeListener=function(e,r){var n,i,s,o,a;if(As(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():SD(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};ue.prototype.off=ue.prototype.removeListener;ue.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function $p(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?DD(i):Ip(i,i.length)}ue.prototype.listeners=function(e){return $p(this,e,!0)};ue.prototype.rawListeners=function(e){return $p(this,e,!1)};ue.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Op.call(t,e)};ue.prototype.listenerCount=Op;function Op(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}ue.prototype.eventNames=function(){return this._eventsCount>0?zi(this._events):[]};function Ip(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function SD(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function DD(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function xD(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Pp(t,e,s,{once:!0}),e!=="error"&&AD(t,i,{once:!0})})}function AD(t,e,r){typeof t.on=="function"&&Pp(t,"error",e,r)}function Pp(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var Sp=Ba.exports;const CD=ri(Sp),Dp="wc",xp=2,Ap="client",Ua=`${Dp}@${xp}:${Ap}:`,yo={name:Ap,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Nl="WALLETCONNECT_DEEPLINK_CHOICE",LD="proposal",jl="Proposal expired",RD="session",Ur=T.SEVEN_DAYS,TD="engine",Ie={wc_sessionPropose:{req:{ttl:T.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:T.ONE_DAY,prompt:!1,tag:1104},res:{ttl:T.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:T.ONE_DAY,prompt:!1,tag:1106},res:{ttl:T.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:T.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:T.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:T.ONE_DAY,prompt:!1,tag:1112},res:{ttl:T.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:T.ONE_DAY,prompt:!1,tag:1114},res:{ttl:T.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:T.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:T.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1119}}},mo={min:T.FIVE_MINUTES,max:T.SEVEN_DAYS},Pt={idle:"IDLE",active:"ACTIVE"},Ml={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},ND="request",jD=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],MD="wc",BD="auth",UD="authKeys",FD="pairingTopics",kD="requests",Cs=`${MD}@${1.5}:${BD}:`,Hi=`${Cs}:PUB_KEY`;var qD=Object.defineProperty,zD=Object.defineProperties,HD=Object.getOwnPropertyDescriptors,Bl=Object.getOwnPropertySymbols,KD=Object.prototype.hasOwnProperty,VD=Object.prototype.propertyIsEnumerable,oa=(t,e,r)=>e in t?qD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,de=(t,e)=>{for(var r in e||(e={}))KD.call(e,r)&&oa(t,r,e[r]);if(Bl)for(var r of Bl(e))VD.call(e,r)&&oa(t,r,e[r]);return t},ze=(t,e)=>zD(t,HD(e)),R=(t,e,r)=>oa(t,typeof e!="symbol"?e+"":e,r);class WD extends FI{constructor(e){super(e),R(this,"name",TD),R(this,"events",new CD),R(this,"initialized",!1),R(this,"requestQueue",{state:Pt.idle,queue:[]}),R(this,"sessionRequestQueue",{state:Pt.idle,queue:[]}),R(this,"requestQueueDelay",T.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(Ie)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},T.toMiliseconds(this.requestQueueDelay)))}),R(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=ze(de({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=sO(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=n;let l=i,h,f=!1;try{if(l){const D=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),f=D.active}}catch(D){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),D}if(!l||!f){const{topic:D,uri:S}=await this.client.core.pairing.create();l=D,h=S}if(!l){const{message:D}=N("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(D)}const p=await this.client.core.crypto.generateKeyPair(),d=Ie.wc_sessionPropose.req.ttl||T.FIVE_MINUTES,y=_e(d),w=ze(de(de({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:sp}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Dt()}),b=ee("session_connect",w.id),{reject:v,resolve:E,done:O}=ur(d,jl),x=({id:D})=>{D===w.id&&(this.client.events.off("proposal_expire",x),this.pendingSessions.delete(w.id),this.events.emit(b,{error:{message:jl,code:0}}))};return this.client.events.on("proposal_expire",x),this.events.once(b,({error:D,session:S})=>{this.client.events.off("proposal_expire",x),D?v(D):S&&E(S)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:w,throwOnFailedPublish:!0,clientRpcId:w.id}),await this.setProposal(w.id,w),{uri:h,approval:O}}),R(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}}),R(this,"approve",async r=>{var n,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(n=r?.id)==null?void 0:n.toString(),trace:[mt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(I){throw o.setError(ar.no_internet_connection),I}try{await this.isValidProposalId(r?.id)}catch(I){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(ar.proposal_not_found),I}try{await this.isValidApprove(r)}catch(I){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(ar.session_approve_namespace_validation_failure),I}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:d,proposer:y,requiredNamespaces:w,optionalNamespaces:b}=p;let v=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:d});v||(v=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:mt.session_approve_started,properties:{topic:d,trace:[mt.session_approve_started,mt.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),O=y.publicKey,x=await this.client.core.crypto.generateSharedKey(E,O),D=de(de(de({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:E,metadata:this.client.metadata},expiry:_e(Ur)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),S=me.relay;v.addTrace(mt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(x,{transportType:S})}catch(I){throw v.setError(ar.subscribe_session_topic_failure),I}v.addTrace(mt.subscribe_session_topic_success);const C=ze(de({},D),{topic:x,requiredNamespaces:w,optionalNamespaces:b,pairingTopic:d,acknowledged:!1,self:D.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:E,transportType:me.relay});await this.client.session.set(x,C),v.addTrace(mt.store_session);try{v.addTrace(mt.publishing_session_settle),await this.sendRequest({topic:x,method:"wc_sessionSettle",params:D,throwOnFailedPublish:!0}).catch(I=>{throw v?.setError(ar.session_settle_publish_failure),I}),v.addTrace(mt.session_settle_publish_success),v.addTrace(mt.publishing_session_approve),await this.sendResult({id:a,topic:d,result:{relay:{protocol:c??"irn"},responderPublicKey:E},throwOnFailedPublish:!0}).catch(I=>{throw v?.setError(ar.session_approve_publish_failure),I}),v.addTrace(mt.session_approve_publish_success)}catch(I){throw this.client.logger.error(I),this.client.session.delete(x,re("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(x),I}return this.client.core.eventClient.deleteEvent({eventId:v.eventId}),await this.client.core.pairing.updateMetadata({topic:d,metadata:y.metadata}),await this.client.proposal.delete(a,re("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:d}),await this.setExpiry(x,_e(Ur)),{topic:x,acknowledged:()=>Promise.resolve(this.client.session.get(x))}}),R(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:n,reason:i}=r;let s;try{s=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}s&&(await this.sendError({id:n,topic:s,error:i,rpcOpts:Ie.wc_sessionPropose.reject}),await this.client.proposal.delete(n,re("USER_DISCONNECTED")))}),R(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:a}=ur(),c=Dt(),u=gr().toString(),l=this.client.session.get(n).namespaces;return this.events.once(ee("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(n,{namespaces:i}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(h=>{this.client.logger.error(h),this.client.session.update(n,{namespaces:l}),a(h)}),{acknowledged:s}}),R(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:n}=r,i=Dt(),{done:s,resolve:o,reject:a}=ur();return this.events.once(ee("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,_e(Ur)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),R(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:n,request:i,topic:s,expiry:o=Ie.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===me.relay&&await this.confirmOnlineStateOrThrow();const c=Dt(),u=gr().toString(),{done:l,resolve:h,reject:f}=ur(o,"Request expired. Please try again.");this.events.once(ee("session_request",c),({error:b,result:v})=>{b?f(b):h(v)});const p="wc_sessionRequest",d=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(d)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:{request:ze(de({},i),{expiryTimestamp:_e(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:d}).catch(b=>f(b)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),await l();const y={request:ze(de({},i),{expiryTimestamp:_e(o)}),chainId:n},w=this.shouldSetTVF(p,y);return await Promise.all([new Promise(async b=>{await this.sendRequest(de({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:y,expiry:o,throwOnFailedPublish:!0},w&&{tvf:this.getTVFParams(c,y)})).catch(v=>f(v)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),b()}),new Promise(async b=>{var v;if(!((v=a.sessionConfig)!=null&&v.disableDeepLink)){const E=await w1(this.client.core.storage,Nl);await g1({id:c,topic:s,wcDeepLink:E})}b()}),l()]).then(b=>b[2])}),R(this,"respond",async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:s}=i,o=this.client.session.get(n);o.transportType===me.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);xt(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0,appLink:a}):lt(i)&&await this.sendError({id:s,topic:n,error:i.error,appLink:a}),this.cleanupAfterResponse(r)}),R(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=Dt(),s=gr().toString(),{done:o,resolve:a,reject:c}=ur();this.events.once(ee("session_ping",i),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&(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:n}))}),R(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r,o=gr().toString(),a=Dt();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),R(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:re("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{const{message:i}=N("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}}),R(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>cO(n,r)))),R(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),R(this,"authenticate",async(r,n)=>{var i;this.isInitialized(),this.isValidAuthenticate(r);const s=n&&this.client.core.linkModeSupportedApps.includes(n)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?me.link_mode:me.relay;o===me.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:h,type:f,exp:p,nbf:d,methods:y=[],expiry:w}=r,b=[...r.resources||[]],{topic:v,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:v,uri:E}});const O=await this.client.core.crypto.generateKeyPair(),x=Mi(O);if(await Promise.all([this.client.auth.authKeys.set(Hi,{responseTopic:x,publicKey:O}),this.client.auth.pairingTopics.set(x,{topic:x,pairingTopic:v})]),await this.client.core.relayer.subscribe(x,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${v}`),y.length>0){const{namespace:$}=an(a[0]);let A=l_($,"request",y);ji(b)&&(A=f_(A,b.pop())),b.push(A)}const D=w&&w>Ie.wc_sessionAuthenticate.req.ttl?w:Ie.wc_sessionAuthenticate.req.ttl,S={authPayload:{type:f??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:h,iat:new Date().toISOString(),exp:p,nbf:d,resources:b},requester:{publicKey:O,metadata:this.client.metadata},expiryTimestamp:_e(D)},C={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},I={requiredNamespaces:{},optionalNamespaces:C,relays:[{protocol:"irn"}],pairingTopic:v,proposer:{publicKey:O,metadata:this.client.metadata},expiryTimestamp:_e(Ie.wc_sessionPropose.req.ttl),id:Dt()},{done:k,resolve:M,reject:j}=ur(D,"Request expired"),q=Dt(),L=ee("session_connect",I.id),g=ee("session_request",q),m=async({error:$,session:A})=>{this.events.off(g,_),$?j($):A&&M({session:A})},_=async $=>{var A,B,F;if(await this.deletePendingAuthRequest(q,{message:"fulfilled",code:0}),$.error){const J=re("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return $.error.code===J.code?void 0:(this.events.off(L,m),j($.error.message))}await this.deleteProposal(I.id),this.events.off(L,m);const{cacaos:z,responder:U}=$.result,K=[],Y=[];for(const J of z){await Eu({cacao:J,projectId:this.client.core.projectId})||(this.client.logger.error(J,"Signature verification failed"),j(re("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ue}=J,Le=ji(Ue.resources),qe=[Uo(Ue.iss)],ot=Xi(Ue.iss);if(Le){const Nt=_u(Le),Ar=$u(Le);K.push(...Nt),qe.push(...Ar)}for(const Nt of qe)Y.push(`${Nt}:${ot}`)}const pe=await this.client.core.crypto.generateSharedKey(O,U.publicKey);let te;K.length>0&&(te={topic:pe,acknowledged:!0,self:{publicKey:O,metadata:this.client.metadata},peer:U,controller:U.publicKey,expiry:_e(Ur),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:v,namespaces:Gu([...new Set(K)],[...new Set(Y)]),transportType:o},await this.client.core.relayer.subscribe(pe,{transportType:o}),await this.client.session.set(pe,te),v&&await this.client.core.pairing.updateMetadata({topic:v,metadata:U.metadata}),te=this.client.session.get(pe)),(A=this.client.metadata.redirect)!=null&&A.linkMode&&(B=U.metadata.redirect)!=null&&B.linkMode&&(F=U.metadata.redirect)!=null&&F.universal&&n&&(this.client.core.addLinkModeSupportedApp(U.metadata.redirect.universal),this.client.session.update(pe,{transportType:me.link_mode})),M({auths:z,session:te})};this.events.once(L,m),this.events.once(g,_);let P;try{if(s){const $=er("wc_sessionAuthenticate",S,q);this.client.core.history.set(v,$);const A=await this.client.core.crypto.encode("",$,{type:fi,encoding:Xt});P=$i(n,v,A)}else await Promise.all([this.sendRequest({topic:v,method:"wc_sessionAuthenticate",params:S,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:q}),this.sendRequest({topic:v,method:"wc_sessionPropose",params:I,expiry:Ie.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:I.id})])}catch($){throw this.events.off(L,m),this.events.off(g,_),$}return await this.setProposal(I.id,I),await this.setAuthRequest(q,{request:ze(de({},S),{verifyContext:{}}),pairingTopic:v,transportType:o}),{uri:P??E,response:k}}),R(this,"approveSessionAuthenticate",async r=>{const{id:n,auths:i}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[cr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw s.setError(Nn.no_internet_connection),w}const o=this.getPendingAuthRequest(n);if(!o)throw s.setError(Nn.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||me.relay;a===me.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=Mi(c),h={type:Vt,receiverPublicKey:c,senderPublicKey:u},f=[],p=[];for(const w of i){if(!await Eu({cacao:w,projectId:this.client.core.projectId})){s.setError(Nn.invalid_cacao);const x=re("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:l,error:x,encodeOpts:h}),new Error(x.message)}s.addTrace(cr.cacaos_verified);const{p:b}=w,v=ji(b.resources),E=[Uo(b.iss)],O=Xi(b.iss);if(v){const x=_u(v),D=$u(v);f.push(...x),E.push(...D)}for(const x of E)p.push(`${x}:${O}`)}const d=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(cr.create_authenticated_session_topic);let y;if(f?.length>0){y={topic:d,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:_e(Ur),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Gu([...new Set(f)],[...new Set(p)]),transportType:a},s.addTrace(cr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(d,{transportType:a})}catch(w){throw s.setError(Nn.subscribe_authenticated_session_topic_failure),w}s.addTrace(cr.subscribe_authenticated_session_topic_success),await this.client.session.set(d,y),s.addTrace(cr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(cr.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:n,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw s.setError(Nn.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:y}}),R(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:n,reason:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);s.transportType===me.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Mi(o),u={type:Vt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:i,encodeOpts:u,rpcOpts:Ie.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.client.proposal.delete(n,re("USER_DISCONNECTED"))}),R(this,"formatAuthMessage",r=>{this.isInitialized();const{request:n,iss:i}=r;return dd(n,i)}),R(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),R(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}}),R(this,"deleteSession",async r=>{var n;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,re("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),s||this.client.core.expirer.del(i),this.client.core.storage.removeItem(Nl).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===i&&this.deletePendingSessionRequest(u.id,re("USER_DISCONNECTED"))}),i===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=Pt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),R(this,"deleteProposal",async(r,n)=>{if(n)try{const i=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:i.pairingTopic})?.setError(ar.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,re("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),R(this,"deletePendingSessionRequest",async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),i&&(this.sessionRequestQueue.state=Pt.idle,this.client.events.emit("session_request_expire",{id:r}))}),R(this,"deletePendingAuthRequest",async(r,n,i=!1)=>{await Promise.all([this.client.auth.requests.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)])}),R(this,"setExpiry",async(r,n)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,n),await this.client.session.update(r,{expiry:n}))}),R(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,_e(Ie.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),R(this,"setAuthRequest",async(r,n)=>{const{request:i,pairingTopic:s,transportType:o=me.relay}=n;this.client.core.expirer.set(r,i.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:r,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),R(this,"setPendingSessionRequest",async r=>{const{id:n,topic:i,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||_e(Ie.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:i,params:s,verifyContext:o})}),R(this,"sendRequest",async r=>{const{topic:n,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:h}=r,f=er(i,s,c);let p;const d=!!l;try{const b=d?Xt:bt;p=await this.client.core.crypto.encode(n,f,{encoding:b})}catch(b){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),b}let y;if(jD.includes(i)){const b=Ct(JSON.stringify(f)),v=Ct(p);y=await this.client.core.verify.register({id:v,decryptedId:b})}const w=Ie[i].req;if(w.attestation=y,o&&(w.ttl=o),a&&(w.id=a),this.client.core.history.set(n,f),d){const b=$i(l,n,p);await H.Linking.openURL(b,this.client.name)}else{const b=Ie[i].req;o&&(b.ttl=o),a&&(b.id=a),b.tvf=ze(de({},h),{correlationId:f.id}),u?(b.internal=ze(de({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,p,b)):this.client.core.relayer.publish(n,p,b).catch(v=>this.client.logger.error(v))}return f.id}),R(this,"sendResult",async r=>{const{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,u=gs(n,s);let l;const h=c&&typeof(H==null?void 0:H.Linking)<"u";try{const d=h?Xt:bt;l=await this.client.core.crypto.encode(i,u,ze(de({},a||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),d}let f,p;try{f=await this.client.core.history.get(i,n);const d=f.request;try{this.shouldSetTVF(d.method,d.params)&&(p=this.getTVFParams(n,d.params,s))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(d){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),d}if(h){const d=$i(c,i,l);await H.Linking.openURL(d,this.client.name)}else{const d=f.request.method,y=Ie[d].res;y.tvf=ze(de({},p),{correlationId:n}),o?(y.internal=ze(de({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,y)):this.client.core.relayer.publish(i,l,y).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(u)}),R(this,"sendError",async r=>{const{id:n,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,u=ys(n,s);let l;const h=c&&typeof(H==null?void 0:H.Linking)<"u";try{const p=h?Xt:bt;l=await this.client.core.crypto.encode(i,u,ze(de({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),p}let f;try{f=await this.client.core.history.get(i,n)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),p}if(h){const p=$i(c,i,l);await H.Linking.openURL(p,this.client.name)}else{const p=f.request.method,d=a||Ie[p].res;this.client.core.relayer.publish(i,l,d)}await this.client.core.history.resolve(u)}),R(this,"cleanup",async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;Qt(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{Qt(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])}),R(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),R(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),R(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Pt.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=Pt.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Pt.idle}),R(this,"processRequest",async r=>{const{topic:n,payload:i,attestation:s,transportType:o,encryptedId:a}=r,c=i.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,i);case"wc_sessionPing":return await this.onSessionPingRequest(n,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(n,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),R(this,"onRelayEventResponse",async r=>{const{topic:n,payload:i,transportType:s}=r,o=(await this.client.core.history.get(n,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),R(this,"onRelayEventUnknownPayload",r=>{const{topic:n}=r,{message:i}=N("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),R(this,"shouldIgnorePairingRequest",r=>{const{topic:n,requestMethod:i}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),R(this,"onSessionProposeRequest",async r=>{const{topic:n,payload:i,attestation:s,encryptedId:o}=r,{params:a,id:c}=i;try{const u=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(qt.proposal_listener_not_found)),this.isValidConnect(de({},i.params));const l=a.expiryTimestamp||_e(Ie.wc_sessionPropose.req.ttl),h=de({id:c,pairingTopic:n,expiryTimestamp:l},a);await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:s,hash:Ct(JSON.stringify(i)),encryptedId:o,metadata:h.proposer.metadata});u?.addTrace(St.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(u){await this.sendError({id:c,topic:n,error:u,rpcOpts:Ie.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),R(this,"onSessionProposeResponse",async(r,n,i)=>{const{id:s}=n;if(xt(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);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 u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const l=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:l,pairingTopic:r,proposalId:s,publicKey:c});const h=await this.client.core.relayer.subscribe(l,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:r})}else if(lt(n)){await this.client.proposal.delete(s,re("USER_DISCONNECTED"));const o=ee("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:n.error})}}),R(this,"onSessionSettleRequest",async(r,n)=>{const{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f}=n.params,p=[...this.pendingSessions.values()].find(w=>w.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const d=this.client.proposal.get(p.proposalId),y=ze(de(de(de({topic:r,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:d.requiredNamespaces,optionalNamespaces:d.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{transportType:me.relay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:y.peer.metadata}),this.client.events.emit("session_connect",{session:y}),this.events.emit(ee("session_connect",p.proposalId),{session:y}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:n.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"onSessionSettleResponse",async(r,n)=>{const{id:i}=n;xt(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ee("session_approve",i),{})):lt(n)&&(await this.client.session.delete(r,re("USER_DISCONNECTED")),this.events.emit(ee("session_approve",i),{error:n.error}))}),R(this,"onSessionUpdateRequest",async(r,n)=>{const{params:i,id:s}=n;try{const o=`${r}_session_update`,a=Rn.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:re("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(de({topic:r},i));try{Rn.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(c){throw Rn.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3)<r.toString().slice(0,-3)),R(this,"onSessionUpdateResponse",(r,n)=>{const{id:i}=n,s=ee("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);xt(n)?this.events.emit(ee("session_update",i),{}):lt(n)&&this.events.emit(ee("session_update",i),{error:n.error})}),R(this,"onSessionExtendRequest",async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,_e(Ur)),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}}),R(this,"onSessionExtendResponse",(r,n)=>{const{id:i}=n,s=ee("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);xt(n)?this.events.emit(ee("session_extend",i),{}):lt(n)&&this.events.emit(ee("session_extend",i),{error:n.error})}),R(this,"onSessionPingRequest",async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}}),R(this,"onSessionPingResponse",(r,n)=>{const{id:i}=n,s=ee("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);xt(n)?this.events.emit(ee("session_ping",i),{}):lt(n)&&this.events.emit(ee("session_ping",i),{error:n.error})},500)}),R(this,"onSessionDeleteRequest",async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),Promise.all([new Promise(s=>{this.client.core.relayer.once(De.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:re("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),R(this,"onSessionRequest",async r=>{var n,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=r,{id:h,params:f}=a;try{await this.isValidRequest(de({topic:o},f));const p=this.client.session.get(o),d=await this.getVerifyContext({attestationId:c,hash:Ct(JSON.stringify(er("wc_sessionRequest",f,h))),encryptedId:u,metadata:p.peer.metadata,transportType:l}),y={id:h,topic:o,params:f,verifyContext:d};await this.setPendingSessionRequest(y),l===me.link_mode&&(n=p.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((i=p.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(p){await this.sendError({id:h,topic:o,error:p}),this.client.logger.error(p)}}),R(this,"onSessionRequestResponse",(r,n)=>{const{id:i}=n,s=ee("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);xt(n)?this.events.emit(ee("session_request",i),{result:n.result}):lt(n)&&this.events.emit(ee("session_request",i),{error:n.error})}),R(this,"onSessionEventRequest",async(r,n)=>{const{id:i,params:s}=n;try{const o=`${r}_session_event_${s.event.name}`,a=Rn.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(de({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),Rn.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"onSessionAuthenticateResponse",(r,n)=>{const{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),xt(n)?this.events.emit(ee("session_request",i),{result:n.result}):lt(n)&&this.events.emit(ee("session_request",i),{error:n.error})}),R(this,"onSessionAuthenticateRequest",async r=>{var n;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:u,authPayload:l,expiryTimestamp:h}=s.params,f=await this.getVerifyContext({attestationId:o,hash:Ct(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),p={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:f,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:p,pairingTopic:i,transportType:c}),c===me.link_mode&&(n=u.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:f})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(s.params.requester.metadata,c),p={type:Vt,receiverPublicKey:l,senderPublicKey:h};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:p,rpcOpts:Ie.wc_sessionAuthenticate.autoReject,appLink:f})}}),R(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),R(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Pt.idle,this.processSessionRequestQueue()},T.toMiliseconds(this.requestQueueDelay))}),R(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:n})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{const o=s.request.id,a=ee("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(ee("session_request",s.request.id),{error:n})})}),R(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Pt.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Pt.active,this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),R(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),R(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest({topic:r.topic,payload:er("wc_sessionPropose",ze(de({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id)})}),R(this,"isValidConnect",async r=>{if(!Ye(r)){const{message:u}=N("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=r;if(ke(n)||await this.isValidPairingTopic(n),!bO(c)){const{message:u}=N("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!ke(i)&&nr(i)!==0){const u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(i,"requiredNamespaces")}if(!ke(s)&&nr(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),ke(o)||this.validateSessionProps(o,"sessionProperties"),!ke(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),R(this,"validateNamespaces",(r,n)=>{const i=vO(r,"connect()",n);if(i)throw new Error(i.message)}),R(this,"isValidApprove",async r=>{if(!Ye(r))throw new Error(N("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);const c=this.client.proposal.get(n),u=co(i,"approve()");if(u)throw new Error(u.message);const l=Zu(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!Ee(s,!0)){const{message:h}=N("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(ke(o)||this.validateSessionProps(o,"sessionProperties"),!ke(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(i));if(!Object.keys(a).every(f=>h.has(f)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),R(this,"isValidReject",async r=>{if(!Ye(r)){const{message:s}=N("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!_O(i)){const{message:s}=N("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),R(this,"isValidSessionSettleRequest",r=>{if(!Ye(r)){const{message:u}=N("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!Ud(n)){const{message:u}=N("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=dO(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=co(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Qt(o)){const{message:u}=N("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),R(this,"isValidUpdate",async r=>{if(!Ye(r)){const{message:c}=N("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:n,namespaces:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const s=this.client.session.get(n),o=co(i,"update()");if(o)throw new Error(o.message);const a=Zu(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),R(this,"isValidExtend",async r=>{if(!Ye(r)){const{message:i}=N("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),R(this,"isValidRequest",async r=>{if(!Ye(r)){const{message:c}=N("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:n,request:i,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!Ju(a,s)){const{message:c}=N("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!$O(i)){const{message:c}=N("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!PO(a,s,i.method)){const{message:c}=N("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!AO(o,mo)){const{message:c}=N("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${mo.min} and ${mo.max}`);throw new Error(c)}}),R(this,"isValidRespond",async r=>{var n;if(!Ye(r)){const{message:o}=N("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:i,response:s}=r;try{await this.isValidSessionTopic(i)}catch(o){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),o}if(!OO(s)){const{message:o}=N("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),R(this,"isValidPing",async r=>{if(!Ye(r)){const{message:i}=N("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),R(this,"isValidEmit",async r=>{if(!Ye(r)){const{message:a}=N("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!Ju(o,s)){const{message:a}=N("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!IO(i)){const{message:a}=N("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!SO(o,s,i.name)){const{message:a}=N("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),R(this,"isValidDisconnect",async r=>{if(!Ye(r)){const{message:i}=N("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),R(this,"isValidAuthenticate",r=>{const{chains:n,uri:i,domain:s,nonce:o}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!Ee(i,!1))throw new Error("uri is required parameter");if(!Ee(s,!1))throw new Error("domain is required parameter");if(!Ee(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>an(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=an(n[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 r=>{const{attestationId:n,hash:i,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||Hn,validation:"UNKNOWN",origin:o.url||""}};try{if(a===me.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:n,hash:i,encryptedId:s,verifyUrl:o.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),R(this,"validateSessionProps",(r,n)=>{Object.values(r).forEach((i,s)=>{if(i==null){const{message:o}=N("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${i} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),R(this,"getPendingAuthRequest",r=>{const n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),R(this,"addToRecentlyDeleted",(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}}),R(this,"checkRecentlyDeleted",r=>{const n=this.recentlyDeletedMap.get(r);if(n){const{message:i}=N("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}),R(this,"isLinkModeEnabled",(r,n)=>{var i,s,o,a,c,u,l,h,f;return!r||n!==me.link_mode?!1:((s=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((l=r?.redirect)==null?void 0:l.universal)!==void 0&&((h=r?.redirect)==null?void 0:h.universal)!==""&&((f=r?.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(H==null?void 0:H.Linking)<"u"}),R(this,"getAppLinkIfEnabled",(r,n)=>{var i;return this.isLinkModeEnabled(r,n)?(i=r?.redirect)==null?void 0:i.universal:void 0}),R(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const n=fu(r,"topic")||"",i=decodeURIComponent(fu(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:me.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:i,sessionExists:s})}),R(this,"registerLinkModeListeners",async()=>{var r;if(xa()||ir()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const n=H==null?void 0:H.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await n.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),R(this,"shouldSetTVF",(r,n)=>{if(!n||r!=="wc_sessionRequest")return!1;const{request:i}=n;return Object.keys(Ml).includes(i.method)}),R(this,"getTVFParams",(r,n,i)=>{var s,o;try{const a=n.request.method,c=this.extractTxHashesFromResult(a,i);return ze(de({correlationId:r,rpcMethods:[a],chainId:n.chainId},this.isValidContractData(n.request.params)&&{contractAddresses:[(o=(s=n.request.params)==null?void 0:s[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),R(this,"isValidContractData",r=>{var n;if(!r)return!1;try{const i=r?.data||((n=r?.[0])==null?void 0:n.data);if(!i.startsWith("0x"))return!1;const s=i.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),R(this,"extractTxHashesFromResult",(r,n)=>{try{const i=Ml[r];if(typeof n=="string")return[n];const s=n[i.key];if(Et(s))return r==="solana_signAllTransactions"?s.map(o=>J1(o)):s;if(typeof s=="string")return[s]}catch(i){this.client.logger.warn("Error extracting tx hashes from result",i)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[n,i]of Object.entries(r))for(const s of i)try{await this.onProviderMessageEvent({topic:n,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${s}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(De.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:n,attestation:i,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Hi)?this.client.auth.authKeys.get(Hi):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:o,encoding:s===me.link_mode?Xt:bt});Ia(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:i,transportType:s,encryptedId:Ct(n)})):ms(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s}),await this.client.core.relayer.messages.ack(r,n)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(ut.expired,async e=>{const{topic:r,id:n}=id(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,N("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,N("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(dr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(dr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Ee(e,!1)){const{message:r}=N("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=N("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(Qt(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=N("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!Ee(e,!1)){const{message:r}=N("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=N("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(Qt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=N("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=N("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}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(Ee(e,!1)){const{message:r}=N("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=N("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!EO(e)){const{message:r}=N("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=N("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(Qt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=N("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class GD extends Dr{constructor(e,r){super(e,r,LD,Ua),this.core=e,this.logger=r}}let YD=class extends Dr{constructor(e,r){super(e,r,RD,Ua),this.core=e,this.logger=r}};class JD extends Dr{constructor(e,r){super(e,r,ND,Ua,n=>n.id),this.core=e,this.logger=r}}class ZD extends Dr{constructor(e,r){super(e,r,UD,Cs,()=>Hi),this.core=e,this.logger=r}}class QD extends Dr{constructor(e,r){super(e,r,FD,Cs),this.core=e,this.logger=r}}class XD extends Dr{constructor(e,r){super(e,r,kD,Cs,n=>n.id),this.core=e,this.logger=r}}var ex=Object.defineProperty,tx=(t,e,r)=>e in t?ex(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wo=(t,e,r)=>tx(t,typeof e!="symbol"?e+"":e,r);class rx{constructor(e,r){this.core=e,this.logger=r,wo(this,"authKeys"),wo(this,"pairingTopics"),wo(this,"requests"),this.authKeys=new ZD(this.core,this.logger),this.pairingTopics=new QD(this.core,this.logger),this.requests=new XD(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var nx=Object.defineProperty,ix=(t,e,r)=>e in t?nx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,G=(t,e,r)=>ix(t,typeof e!="symbol"?e+"":e,r);let sx=class Cp extends UI{constructor(e){super(e),G(this,"protocol",Dp),G(this,"version",xp),G(this,"name",yo.name),G(this,"metadata"),G(this,"core"),G(this,"logger"),G(this,"events",new Sp.EventEmitter),G(this,"engine"),G(this,"session"),G(this,"proposal"),G(this,"pendingRequest"),G(this,"auth"),G(this,"signConfig"),G(this,"on",(n,i)=>this.events.on(n,i)),G(this,"once",(n,i)=>this.events.once(n,i)),G(this,"off",(n,i)=>this.events.off(n,i)),G(this,"removeListener",(n,i)=>this.events.removeListener(n,i)),G(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),G(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"update",async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"request",async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"find",n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),G(this,"authenticate",async(n,i)=>{try{return await this.engine.authenticate(n,i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||yo.name,this.metadata=u1(e?.metadata),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:ni(us({level:e?.logger||yo.logger}));this.core=e?.core||new OD(e),this.logger=Ke(r,this.name),this.session=new YD(this.core,this.logger),this.proposal=new GD(this.core,this.logger),this.pendingRequest=new JD(this.core,this.logger),this.engine=new WD(this),this.auth=new rx(this.core,this.logger)}static async init(e){const r=new Cp(e);return await r.initialize(),r}get context(){return Qe(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()},T.toMiliseconds(T.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};var Fa={exports:{}},hn=typeof Reflect=="object"?Reflect:null,Ul=hn&&typeof hn.apply=="function"?hn.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Ki;hn&&typeof hn.ownKeys=="function"?Ki=hn.ownKeys:Object.getOwnPropertySymbols?Ki=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Ki=function(e){return Object.getOwnPropertyNames(e)};function ox(t){console&&console.warn&&console.warn(t)}var Lp=Number.isNaN||function(e){return e!==e};function le(){le.init.call(this)}Fa.exports=le;Fa.exports.once=lx;le.EventEmitter=le;le.prototype._events=void 0;le.prototype._eventsCount=0;le.prototype._maxListeners=void 0;var Fl=10;function Ls(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(le,"defaultMaxListeners",{enumerable:!0,get:function(){return Fl},set:function(t){if(typeof t!="number"||t<0||Lp(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Fl=t}});le.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};le.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Lp(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Rp(t){return t._maxListeners===void 0?le.defaultMaxListeners:t._maxListeners}le.prototype.getMaxListeners=function(){return Rp(this)};le.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")Ul(c,this,r);else for(var u=c.length,l=Bp(c,u),n=0;n<u;++n)Ul(l[n],this,r);return!0};function Tp(t,e,r,n){var i,s,o;if(Ls(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=Rp(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,ox(a)}return t}le.prototype.addListener=function(e,r){return Tp(this,e,r,!1)};le.prototype.on=le.prototype.addListener;le.prototype.prependListener=function(e,r){return Tp(this,e,r,!0)};function ax(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Np(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=ax.bind(n);return i.listener=r,n.wrapFn=i,i}le.prototype.once=function(e,r){return Ls(r),this.on(e,Np(this,e,r)),this};le.prototype.prependOnceListener=function(e,r){return Ls(r),this.prependListener(e,Np(this,e,r)),this};le.prototype.removeListener=function(e,r){var n,i,s,o,a;if(Ls(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():cx(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};le.prototype.off=le.prototype.removeListener;le.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function jp(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?ux(i):Bp(i,i.length)}le.prototype.listeners=function(e){return jp(this,e,!0)};le.prototype.rawListeners=function(e){return jp(this,e,!1)};le.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Mp.call(t,e)};le.prototype.listenerCount=Mp;function Mp(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}le.prototype.eventNames=function(){return this._eventsCount>0?Ki(this._events):[]};function Bp(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function cx(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function ux(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function lx(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Up(t,e,s,{once:!0}),e!=="error"&&hx(t,i,{once:!0})})}function hx(t,e,r){typeof t.on=="function"&&Up(t,"error",e,r)}function Up(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var fx=Fa.exports,aa={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof At<"u"&&At,n=function(){function s(){this.fetch=!1,this.DOMException=r.DOMException}return s.prototype=r,new s}();(function(s){(function(o){var a=typeof s<"u"&&s||typeof self<"u"&&self||typeof At<"u"&&At||{},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 u(g){return g&&DataView.prototype.isPrototypeOf(g)}if(c.arrayBuffer)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],h=ArrayBuffer.isView||function(g){return g&&l.indexOf(Object.prototype.toString.call(g))>-1};function f(g){if(typeof g!="string"&&(g=String(g)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(g)||g==="")throw new TypeError('Invalid character in header field name: "'+g+'"');return g.toLowerCase()}function p(g){return typeof g!="string"&&(g=String(g)),g}function d(g){var m={next:function(){var _=g.shift();return{done:_===void 0,value:_}}};return c.iterable&&(m[Symbol.iterator]=function(){return m}),m}function y(g){this.map={},g instanceof y?g.forEach(function(m,_){this.append(_,m)},this):Array.isArray(g)?g.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):g&&Object.getOwnPropertyNames(g).forEach(function(m){this.append(m,g[m])},this)}y.prototype.append=function(g,m){g=f(g),m=p(m);var _=this.map[g];this.map[g]=_?_+", "+m:m},y.prototype.delete=function(g){delete this.map[f(g)]},y.prototype.get=function(g){return g=f(g),this.has(g)?this.map[g]:null},y.prototype.has=function(g){return this.map.hasOwnProperty(f(g))},y.prototype.set=function(g,m){this.map[f(g)]=p(m)},y.prototype.forEach=function(g,m){for(var _ in this.map)this.map.hasOwnProperty(_)&&g.call(m,this.map[_],_,this)},y.prototype.keys=function(){var g=[];return this.forEach(function(m,_){g.push(_)}),d(g)},y.prototype.values=function(){var g=[];return this.forEach(function(m){g.push(m)}),d(g)},y.prototype.entries=function(){var g=[];return this.forEach(function(m,_){g.push([_,m])}),d(g)},c.iterable&&(y.prototype[Symbol.iterator]=y.prototype.entries);function w(g){if(!g._noBody){if(g.bodyUsed)return Promise.reject(new TypeError("Already read"));g.bodyUsed=!0}}function b(g){return new Promise(function(m,_){g.onload=function(){m(g.result)},g.onerror=function(){_(g.error)}})}function v(g){var m=new FileReader,_=b(m);return m.readAsArrayBuffer(g),_}function E(g){var m=new FileReader,_=b(m),P=/charset=([A-Za-z0-9_-]+)/.exec(g.type),$=P?P[1]:"utf-8";return m.readAsText(g,$),_}function O(g){for(var m=new Uint8Array(g),_=new Array(m.length),P=0;P<m.length;P++)_[P]=String.fromCharCode(m[P]);return _.join("")}function x(g){if(g.slice)return g.slice(0);var m=new Uint8Array(g.byteLength);return m.set(new Uint8Array(g)),m.buffer}function D(){return this.bodyUsed=!1,this._initBody=function(g){this.bodyUsed=this.bodyUsed,this._bodyInit=g,g?typeof g=="string"?this._bodyText=g:c.blob&&Blob.prototype.isPrototypeOf(g)?this._bodyBlob=g:c.formData&&FormData.prototype.isPrototypeOf(g)?this._bodyFormData=g:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(g)?this._bodyText=g.toString():c.arrayBuffer&&c.blob&&u(g)?(this._bodyArrayBuffer=x(g.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(g)||h(g))?this._bodyArrayBuffer=x(g):this._bodyText=g=Object.prototype.toString.call(g):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof g=="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(g)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var g=w(this);if(g)return g;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 g=w(this);return g||(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(v);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var g=w(this);if(g)return g;if(this._bodyBlob)return E(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(O(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(k)}),this.json=function(){return this.text().then(JSON.parse)},this}var S=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function C(g){var m=g.toUpperCase();return S.indexOf(m)>-1?m:g}function I(g,m){if(!(this instanceof I))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');m=m||{};var _=m.body;if(g instanceof I){if(g.bodyUsed)throw new TypeError("Already read");this.url=g.url,this.credentials=g.credentials,m.headers||(this.headers=new y(g.headers)),this.method=g.method,this.mode=g.mode,this.signal=g.signal,!_&&g._bodyInit!=null&&(_=g._bodyInit,g.bodyUsed=!0)}else this.url=String(g);if(this.credentials=m.credentials||this.credentials||"same-origin",(m.headers||!this.headers)&&(this.headers=new y(m.headers)),this.method=C(m.method||this.method||"GET"),this.mode=m.mode||this.mode||null,this.signal=m.signal||this.signal||function(){if("AbortController"in a){var A=new AbortController;return A.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&_)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(_),(this.method==="GET"||this.method==="HEAD")&&(m.cache==="no-store"||m.cache==="no-cache")){var P=/([?&])_=[^&]*/;if(P.test(this.url))this.url=this.url.replace(P,"$1_="+new Date().getTime());else{var $=/\?/;this.url+=($.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}I.prototype.clone=function(){return new I(this,{body:this._bodyInit})};function k(g){var m=new FormData;return g.trim().split("&").forEach(function(_){if(_){var P=_.split("="),$=P.shift().replace(/\+/g," "),A=P.join("=").replace(/\+/g," ");m.append(decodeURIComponent($),decodeURIComponent(A))}}),m}function M(g){var m=new y,_=g.replace(/\r?\n[\t ]+/g," ");return _.split("\r").map(function(P){return P.indexOf(`
39
- `)===0?P.substr(1,P.length):P}).forEach(function(P){var $=P.split(":"),A=$.shift().trim();if(A){var B=$.join(":").trim();try{m.append(A,B)}catch(F){console.warn("Response "+F.message)}}}),m}D.call(I.prototype);function j(g,m){if(!(this instanceof j))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 y(m.headers),this.url=m.url||"",this._initBody(g)}D.call(j.prototype),j.prototype.clone=function(){return new j(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},j.error=function(){var g=new j(null,{status:200,statusText:""});return g.ok=!1,g.status=0,g.type="error",g};var q=[301,302,303,307,308];j.redirect=function(g,m){if(q.indexOf(m)===-1)throw new RangeError("Invalid status code");return new j(null,{status:m,headers:{location:g}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(m,_){this.message=m,this.name=_;var P=Error(m);this.stack=P.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function L(g,m){return new Promise(function(_,P){var $=new I(g,m);if($.signal&&$.signal.aborted)return P(new o.DOMException("Aborted","AbortError"));var A=new XMLHttpRequest;function B(){A.abort()}A.onload=function(){var U={statusText:A.statusText,headers:M(A.getAllResponseHeaders()||"")};$.url.indexOf("file://")===0&&(A.status<200||A.status>599)?U.status=200:U.status=A.status,U.url="responseURL"in A?A.responseURL:U.headers.get("X-Request-URL");var K="response"in A?A.response:A.responseText;setTimeout(function(){_(new j(K,U))},0)},A.onerror=function(){setTimeout(function(){P(new TypeError("Network request failed"))},0)},A.ontimeout=function(){setTimeout(function(){P(new TypeError("Network request timed out"))},0)},A.onabort=function(){setTimeout(function(){P(new o.DOMException("Aborted","AbortError"))},0)};function F(U){try{return U===""&&a.location.href?a.location.href:U}catch{return U}}if(A.open($.method,F($.url),!0),$.credentials==="include"?A.withCredentials=!0:$.credentials==="omit"&&(A.withCredentials=!1),"responseType"in A&&(c.blob?A.responseType="blob":c.arrayBuffer&&(A.responseType="arraybuffer")),m&&typeof m.headers=="object"&&!(m.headers instanceof y||a.Headers&&m.headers instanceof a.Headers)){var z=[];Object.getOwnPropertyNames(m.headers).forEach(function(U){z.push(f(U)),A.setRequestHeader(U,p(m.headers[U]))}),$.headers.forEach(function(U,K){z.indexOf(K)===-1&&A.setRequestHeader(K,U)})}else $.headers.forEach(function(U,K){A.setRequestHeader(K,U)});$.signal&&($.signal.addEventListener("abort",B),A.onreadystatechange=function(){A.readyState===4&&$.signal.removeEventListener("abort",B)}),A.send(typeof $._bodyInit>"u"?null:$._bodyInit)})}return L.polyfill=!0,a.fetch||(a.fetch=L,a.Headers=y,a.Request=I,a.Response=j),o.Headers=y,o.Request=I,o.Response=j,o.fetch=L,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=r.fetch?r:n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(aa,aa.exports);var dx=aa.exports;const kl=ri(dx);var px=Object.defineProperty,gx=Object.defineProperties,yx=Object.getOwnPropertyDescriptors,ql=Object.getOwnPropertySymbols,mx=Object.prototype.hasOwnProperty,wx=Object.prototype.propertyIsEnumerable,zl=(t,e,r)=>e in t?px(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hl=(t,e)=>{for(var r in e||(e={}))mx.call(e,r)&&zl(t,r,e[r]);if(ql)for(var r of ql(e))wx.call(e,r)&&zl(t,r,e[r]);return t},Kl=(t,e)=>gx(t,yx(e));const vx={Accept:"application/json","Content-Type":"application/json"},bx="POST",Vl={headers:vx,method:bx},Wl=10;let _t=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new fx.EventEmitter,this.isAvailable=!1,this.registering=!1,!zc(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}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 r=Wt(e),n=await(await kl(this.url,Kl(Hl({},Vl),{body:r}))).json();this.onPayload({data:n})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!zc(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));n()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=Wt({id:1,jsonrpc:"2.0",method:"test",params:[]});await kl(e,Kl(Hl({},Vl),{body:r}))}this.onOpen()}catch(r){const n=this.parseError(r);throw this.events.emit("register_error",n),this.onClose(),n}}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 r=typeof e.data=="string"?wr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=ys(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return wf(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Wl&&this.events.setMaxListeners(Wl)}};var ka={exports:{}},fn=typeof Reflect=="object"?Reflect:null,Gl=fn&&typeof fn.apply=="function"?fn.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Vi;fn&&typeof fn.ownKeys=="function"?Vi=fn.ownKeys:Object.getOwnPropertySymbols?Vi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Vi=function(e){return Object.getOwnPropertyNames(e)};function Ex(t){console&&console.warn&&console.warn(t)}var Fp=Number.isNaN||function(e){return e!==e};function he(){he.init.call(this)}ka.exports=he;ka.exports.once=Ix;he.EventEmitter=he;he.prototype._events=void 0;he.prototype._eventsCount=0;he.prototype._maxListeners=void 0;var Yl=10;function Rs(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(he,"defaultMaxListeners",{enumerable:!0,get:function(){return Yl},set:function(t){if(typeof t!="number"||t<0||Fp(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Yl=t}});he.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};he.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Fp(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function kp(t){return t._maxListeners===void 0?he.defaultMaxListeners:t._maxListeners}he.prototype.getMaxListeners=function(){return kp(this)};he.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")Gl(c,this,r);else for(var u=c.length,l=Vp(c,u),n=0;n<u;++n)Gl(l[n],this,r);return!0};function qp(t,e,r,n){var i,s,o;if(Rs(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=kp(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,Ex(a)}return t}he.prototype.addListener=function(e,r){return qp(this,e,r,!1)};he.prototype.on=he.prototype.addListener;he.prototype.prependListener=function(e,r){return qp(this,e,r,!0)};function _x(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function zp(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=_x.bind(n);return i.listener=r,n.wrapFn=i,i}he.prototype.once=function(e,r){return Rs(r),this.on(e,zp(this,e,r)),this};he.prototype.prependOnceListener=function(e,r){return Rs(r),this.prependListener(e,zp(this,e,r)),this};he.prototype.removeListener=function(e,r){var n,i,s,o,a;if(Rs(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():$x(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};he.prototype.off=he.prototype.removeListener;he.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function Hp(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?Ox(i):Vp(i,i.length)}he.prototype.listeners=function(e){return Hp(this,e,!0)};he.prototype.rawListeners=function(e){return Hp(this,e,!1)};he.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Kp.call(t,e)};he.prototype.listenerCount=Kp;function Kp(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}he.prototype.eventNames=function(){return this._eventsCount>0?Vi(this._events):[]};function Vp(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function $x(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function Ox(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function Ix(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Wp(t,e,s,{once:!0}),e!=="error"&&Px(t,i,{once:!0})})}function Px(t,e,r){typeof t.on=="function"&&Wp(t,"error",e,r)}function Wp(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var Sx=ka.exports;const Dx=ri(Sx),Jl="error",xx="wss://relay.walletconnect.org",Ax="wc",Cx="universal_provider",Pi=`${Ax}@2:${Cx}:`,Gp="https://rpc.walletconnect.org/v1/",Qr="generic",Lx=`${Gp}bundler`,pt={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function Rx(){}function qa(t){return t==null||typeof t!="object"&&typeof t!="function"}function za(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function Tx(t){if(qa(t))return t;if(Array.isArray(t)||za(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),r=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new r(t);if(t instanceof RegExp){const n=new r(t);return n.lastIndex=t.lastIndex,n}if(t instanceof DataView)return new r(t.buffer.slice(0));if(t instanceof Error){const n=new r(t.message);return n.stack=t.stack,n.name=t.name,n.cause=t.cause,n}if(typeof File<"u"&&t instanceof File)return new r([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const n=Object.create(e);return Object.assign(n,t)}return t}function Zl(t){return typeof t=="object"&&t!==null}function Yp(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Jp(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const Nx="[object RegExp]",Zp="[object String]",Qp="[object Number]",Xp="[object Boolean]",eg="[object Arguments]",jx="[object Symbol]",Mx="[object Date]",Bx="[object Map]",Ux="[object Set]",Fx="[object Array]",kx="[object ArrayBuffer]",qx="[object Object]",zx="[object DataView]",Hx="[object Uint8Array]",Kx="[object Uint8ClampedArray]",Vx="[object Uint16Array]",Wx="[object Uint32Array]",Gx="[object Int8Array]",Yx="[object Int16Array]",Jx="[object Int32Array]",Zx="[object Float32Array]",Qx="[object Float64Array]";function Xx(t,e){return tn(t,void 0,t,new Map,e)}function tn(t,e,r,n=new Map,i=void 0){const s=i?.(t,e,r,n);if(s!=null)return s;if(qa(t))return t;if(n.has(t))return n.get(t);if(Array.isArray(t)){const o=new Array(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=tn(t[a],a,r,n,i);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;n.set(t,o);for(const[a,c]of t)o.set(a,tn(c,a,r,n,i));return o}if(t instanceof Set){const o=new Set;n.set(t,o);for(const a of t)o.add(tn(a,void 0,r,n,i));return o}if(typeof Ce<"u"&&Ce.isBuffer(t))return t.subarray();if(za(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=tn(t[a],a,r,n,i);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return n.set(t,o),pr(o,t,r,n,i),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return n.set(t,o),pr(o,t,r,n,i),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return n.set(t,o),pr(o,t,r,n,i),o}if(t instanceof Error){const o=new t.constructor;return n.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,pr(o,t,r,n,i),o}if(typeof t=="object"&&eA(t)){const o=Object.create(Object.getPrototypeOf(t));return n.set(t,o),pr(o,t,r,n,i),o}return t}function pr(t,e,r=t,n,i){const s=[...Object.keys(e),...Yp(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=tn(e[a],a,r,n,i))}}function eA(t){switch(Jp(t)){case eg:case Fx:case kx:case zx:case Xp:case Mx:case Zx:case Qx:case Gx:case Yx:case Jx:case Bx:case Qp:case qx:case Nx:case Ux:case Zp:case jx:case Hx:case Kx:case Vx:case Wx:return!0;default:return!1}}function tA(t,e){return Xx(t,(r,n,i,s)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case Qp:case Zp:case Xp:{const o=new t.constructor(t?.valueOf());return pr(o,t),o}case eg:{const o={};return pr(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function Ql(t){return tA(t)}function Xl(t){return t!==null&&typeof t=="object"&&Jp(t)==="[object Arguments]"}function rA(t){return za(t)}function nA(t){if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const r=t[Symbol.toStringTag];return r==null||!Object.getOwnPropertyDescriptor(t,Symbol.toStringTag)?.writable?!1:t.toString()===`[object ${r}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function iA(t,...e){const r=e.slice(0,-1),n=e[e.length-1];let i=t;for(let s=0;s<r.length;s++){const o=r[s];i=ca(i,o,n,new Map)}return i}function ca(t,e,r,n){if(qa(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(n.has(e))return Tx(n.get(e));if(n.set(e,t),Array.isArray(e)){e=e.slice();for(let s=0;s<e.length;s++)e[s]=e[s]??void 0}const i=[...Object.keys(e),...Yp(e)];for(let s=0;s<i.length;s++){const o=i[s];let a=e[o],c=t[o];if(Xl(a)&&(a={...a}),Xl(c)&&(c={...c}),typeof Ce<"u"&&Ce.isBuffer(a)&&(a=Ql(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],h=Reflect.ownKeys(c);for(let f=0;f<h.length;f++){const p=h[f];l[p]=c[p]}c=l}else c=[];const u=r(c,a,o,t,e,n);u!=null?t[o]=u:Array.isArray(a)||Zl(c)&&Zl(a)?t[o]=ca(c,a,r,n):c==null&&nA(a)?t[o]=ca({},a,r,n):c==null&&rA(a)?t[o]=Ql(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function sA(t,...e){return iA(t,...e,Rx)}var oA=Object.defineProperty,aA=Object.defineProperties,cA=Object.getOwnPropertyDescriptors,eh=Object.getOwnPropertySymbols,uA=Object.prototype.hasOwnProperty,lA=Object.prototype.propertyIsEnumerable,th=(t,e,r)=>e in t?oA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Si=(t,e)=>{for(var r in e||(e={}))uA.call(e,r)&&th(t,r,e[r]);if(eh)for(var r of eh(e))lA.call(e,r)&&th(t,r,e[r]);return t},hA=(t,e)=>aA(t,cA(e));function st(t,e,r){var n;const i=an(t);return((n=e.rpcMap)==null?void 0:n[i.reference])||`${Gp}?chainId=${i.namespace}:${i.reference}&projectId=${r}`}function xr(t){return t.includes(":")?t.split(":")[1]:t}function tg(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function fA(t,e){const r=Object.keys(e.namespaces).filter(i=>i.includes(t));if(!r.length)return[];const n=[];return r.forEach(i=>{const s=e.namespaces[i].accounts;n.push(...s)}),n}function Di(t={},e={}){const r=rh(t),n=rh(e);return sA(r,n)}function rh(t){var e,r,n,i,s;const o={};if(!nr(t))return o;for(const[a,c]of Object.entries(t)){const u=Ps(a)?[a]:c.chains,l=c.methods||[],h=c.events||[],f=c.rpcMap||{},p=en(a);o[p]=hA(Si(Si({},o[p]),c),{chains:Rt(u,(e=o[p])==null?void 0:e.chains),methods:Rt(l,(r=o[p])==null?void 0:r.methods),events:Rt(h,(n=o[p])==null?void 0:n.events)}),(nr(f)||nr(((i=o[p])==null?void 0:i.rpcMap)||{}))&&(o[p].rpcMap=Si(Si({},f),(s=o[p])==null?void 0:s.rpcMap))}return o}function nh(t){return t.includes(":")?t.split(":")[2]:t}function ih(t){const e={};for(const[r,n]of Object.entries(t)){const i=n.methods||[],s=n.events||[],o=n.accounts||[],a=Ps(r)?[r]:n.chains?n.chains:tg(n.accounts);e[r]={chains:a,methods:i,events:s,accounts:o}}return e}function vo(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}const rg={},X=t=>rg[t],bo=(t,e)=>{rg[t]=e};var dA=Object.defineProperty,pA=(t,e,r)=>e in t?dA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fr=(t,e,r)=>pA(t,typeof e!="symbol"?e+"":e,r);class gA{constructor(e){Fr(this,"name","polkadot"),Fr(this,"client"),Fr(this,"httpProviders"),Fr(this,"events"),Fr(this,"namespace"),Fr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(pt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=xr(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dt(new _t(n,X("disableProviderPing")))}}var yA=Object.defineProperty,mA=Object.defineProperties,wA=Object.getOwnPropertyDescriptors,sh=Object.getOwnPropertySymbols,vA=Object.prototype.hasOwnProperty,bA=Object.prototype.propertyIsEnumerable,ua=(t,e,r)=>e in t?yA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,oh=(t,e)=>{for(var r in e||(e={}))vA.call(e,r)&&ua(t,r,e[r]);if(sh)for(var r of sh(e))bA.call(e,r)&&ua(t,r,e[r]);return t},ah=(t,e)=>mA(t,wA(e)),kr=(t,e,r)=>ua(t,typeof e!="symbol"?e+"":e,r);class EA{constructor(e){kr(this,"name","eip155"),kr(this,"client"),kr(this,"chainId"),kr(this,"namespace"),kr(this,"httpProviders"),kr(this,"events"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r),this.chainId=parseInt(e),this.events.emit(pt.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,r){const n=r||st(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dt(new _t(n,X("disableProviderPing")))}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=parseInt(xr(r));e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}async handleSwitchChain(e){var r,n;let i=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";i=i.startsWith("0x")?i:`0x${i}`;const s=parseInt(i,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:i}]},chainId:(n=this.namespace.chains)==null?void 0:n[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. 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 r,n,i,s,o;const a=(n=(r=e.request)==null?void 0:r.params)==null?void 0:n[0],c=((s=(i=e.request)==null?void 0:i.params)==null?void 0:s[1])||[],u=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),h=((o=l?.sessionProperties)==null?void 0:o.capabilities)||{};if(h!=null&&h[u])return h?.[u];const f=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:ah(oh({},l.sessionProperties||{}),{capabilities:ah(oh({},h||{}),{[u]:f})})})}catch(p){console.warn("Failed to update session with capabilities",p)}return f}async getCallStatus(e){var r,n;const i=this.client.session.get(e.topic),s=(r=i.sessionProperties)==null?void 0:r.bundler_name;if(s){const a=this.getBundlerUrl(e.chainId,s);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(n=i.sessionProperties)==null?void 0:n.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,r){var n;const i=new URL(e),s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(er("eth_getUserOperationReceipt",[(n=r.request.params)==null?void 0:n[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,r){return`${Lx}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}}var _A=Object.defineProperty,$A=(t,e,r)=>e in t?_A(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qr=(t,e,r)=>$A(t,typeof e!="symbol"?e+"":e,r);class OA{constructor(e){qr(this,"name","solana"),qr(this,"client"),qr(this,"httpProviders"),qr(this,"events"),qr(this,"namespace"),qr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(pt.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(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=xr(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dt(new _t(n,X("disableProviderPing")))}}var IA=Object.defineProperty,PA=(t,e,r)=>e in t?IA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zr=(t,e,r)=>PA(t,typeof e!="symbol"?e+"":e,r);class SA{constructor(e){zr(this,"name","cosmos"),zr(this,"client"),zr(this,"httpProviders"),zr(this,"events"),zr(this,"namespace"),zr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(pt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=xr(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dt(new _t(n,X("disableProviderPing")))}}var DA=Object.defineProperty,xA=(t,e,r)=>e in t?DA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hr=(t,e,r)=>xA(t,typeof e!="symbol"?e+"":e,r);class AA{constructor(e){Hr(this,"name","algorand"),Hr(this,"client"),Hr(this,"httpProviders"),Hr(this,"events"),Hr(this,"namespace"),Hr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){if(!this.httpProviders[e]){const n=r||st(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(pt.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(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new dt(new _t(n,X("disableProviderPing")))}}var CA=Object.defineProperty,LA=(t,e,r)=>e in t?CA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Kr=(t,e,r)=>LA(t,typeof e!="symbol"?e+"":e,r);class RA{constructor(e){Kr(this,"name","cip34"),Kr(this,"client"),Kr(this,"httpProviders"),Kr(this,"events"),Kr(this,"namespace"),Kr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(pt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=this.getCardanoRPCUrl(r),i=xr(r);e[i]=this.createHttpProvider(i,n)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||this.getCardanoRPCUrl(e);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dt(new _t(n,X("disableProviderPing")))}}var TA=Object.defineProperty,NA=(t,e,r)=>e in t?TA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Vr=(t,e,r)=>NA(t,typeof e!="symbol"?e+"":e,r);class jA{constructor(e){Vr(this,"name","elrond"),Vr(this,"client"),Vr(this,"httpProviders"),Vr(this,"events"),Vr(this,"namespace"),Vr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(pt.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(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=xr(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dt(new _t(n,X("disableProviderPing")))}}var MA=Object.defineProperty,BA=(t,e,r)=>e in t?MA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wr=(t,e,r)=>BA(t,typeof e!="symbol"?e+"":e,r);class UA{constructor(e){Wr(this,"name","multiversx"),Wr(this,"client"),Wr(this,"httpProviders"),Wr(this,"events"),Wr(this,"namespace"),Wr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(pt.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(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=xr(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dt(new _t(n,X("disableProviderPing")))}}var FA=Object.defineProperty,kA=(t,e,r)=>e in t?FA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Gr=(t,e,r)=>kA(t,typeof e!="symbol"?e+"":e,r);class qA{constructor(e){Gr(this,"name","near"),Gr(this,"client"),Gr(this,"httpProviders"),Gr(this,"events"),Gr(this,"namespace"),Gr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||st(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(pt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace);return typeof n>"u"?void 0:new dt(new _t(n,X("disableProviderPing")))}}var zA=Object.defineProperty,HA=(t,e,r)=>e in t?zA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yr=(t,e,r)=>HA(t,typeof e!="symbol"?e+"":e,r);class KA{constructor(e){Yr(this,"name","tezos"),Yr(this,"client"),Yr(this,"httpProviders"),Yr(this,"events"),Yr(this,"namespace"),Yr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||st(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(pt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{e[r]=this.createHttpProvider(r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace);return typeof n>"u"?void 0:new dt(new _t(n))}}var VA=Object.defineProperty,WA=(t,e,r)=>e in t?VA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Jr=(t,e,r)=>WA(t,typeof e!="symbol"?e+"":e,r);class GA{constructor(e){Jr(this,"name",Qr),Jr(this,"client"),Jr(this,"httpProviders"),Jr(this,"events"),Jr(this,"namespace"),Jr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(pt.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(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const n={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(i=>{const s=an(i);n[`${s.namespace}:${s.reference}`]=this.createHttpProvider(i)}),n}getHttpProvider(e){const r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dt(new _t(n,X("disableProviderPing")))}}var YA=Object.defineProperty,JA=Object.defineProperties,ZA=Object.getOwnPropertyDescriptors,ch=Object.getOwnPropertySymbols,QA=Object.prototype.hasOwnProperty,XA=Object.prototype.propertyIsEnumerable,la=(t,e,r)=>e in t?YA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xi=(t,e)=>{for(var r in e||(e={}))QA.call(e,r)&&la(t,r,e[r]);if(ch)for(var r of ch(e))XA.call(e,r)&&la(t,r,e[r]);return t},Eo=(t,e)=>JA(t,ZA(e)),ct=(t,e,r)=>la(t,typeof e!="symbol"?e+"":e,r);let eC=class ng{constructor(e){ct(this,"client"),ct(this,"namespaces"),ct(this,"optionalNamespaces"),ct(this,"sessionProperties"),ct(this,"scopedProperties"),ct(this,"events",new Dx),ct(this,"rpcProviders",{}),ct(this,"session"),ct(this,"providerOpts"),ct(this,"logger"),ct(this,"uri"),ct(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:ni(us({level:e?.logger||Jl})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new ng(e);return await r.initialize(),r}async request(e,r,n){const[i,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(i).request({request:xi({},e),chainId:`${i}:${s}`,topic:this.session.topic,expiry:n})}sendAsync(e,r,n,i){const s=new Date().getTime();this.request(e,n,i).then(o=>r(null,gs(s,o))).catch(o=>r(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:re("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,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:n,response:i}=await this.client.authenticate(e,r);n&&(this.uri=n,this.events.emit("display_uri",n));const s=await i();if(this.session=s.session,this.session){const o=ih(this.session.namespaces);this.namespaces=Di(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){const{uri:r,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});r&&(this.uri=r,this.events.emit("display_uri",r));const i=await n();this.session=i;const s=ih(i.namespaces);return this.namespaces=Di(this.namespaces,s),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[n,i]=this.validateChain(e),s=this.getProvider(n);s.name===Qr?s.setDefaultChain(`${n}:${i}`,r):s.setDefaultChain(i,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(Et(r)){for(const n of r)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.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,r;if(this.client=this.providerOpts.client||await sx.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Jl,relayUrl:this.providerOpts.relayUrl||xx,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(n){throw this.logger.error("Failed to get session",n),new Error(`The provided session: ${(r=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{const n=this.client.session.getAll();this.session=n[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(r=>en(r)))];bo("client",this.client),bo("events",this.events),bo("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const n=fA(r,this.session),i=tg(n),s=Di(this.namespaces,this.optionalNamespaces),o=Eo(xi({},s[r]),{accounts:n,chains:i});switch(r){case"eip155":this.rpcProviders[r]=new EA({namespace:o});break;case"algorand":this.rpcProviders[r]=new AA({namespace:o});break;case"solana":this.rpcProviders[r]=new OA({namespace:o});break;case"cosmos":this.rpcProviders[r]=new SA({namespace:o});break;case"polkadot":this.rpcProviders[r]=new gA({namespace:o});break;case"cip34":this.rpcProviders[r]=new RA({namespace:o});break;case"elrond":this.rpcProviders[r]=new jA({namespace:o});break;case"multiversx":this.rpcProviders[r]=new UA({namespace:o});break;case"near":this.rpcProviders[r]=new qA({namespace:o});break;case"tezos":this.rpcProviders[r]=new KA({namespace:o});break;default:this.rpcProviders[Qr]?this.rpcProviders[Qr].updateNamespace(o):this.rpcProviders[Qr]=new GA({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var r;const{topic:n}=e;n===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:n,topic:i}=e;if(i!==((r=this.session)==null?void 0:r.topic))return;const{event:s}=n;if(s.name==="accountsChanged"){const o=s.data;o&&Et(o)&&this.events.emit("accountsChanged",o.map(nh))}else if(s.name==="chainChanged"){const o=n.chainId,a=n.event.data,c=en(o),u=vo(o)!==vo(a)?`${c}:${vo(a)}`:o;this.onChainChanged(u)}else this.events.emit(s.name,s.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var n,i;if(e!==((n=this.session)==null?void 0:n.topic))return;const{namespaces:s}=r,o=(i=this.client)==null?void 0:i.session.get(e);this.session=Eo(xi({},o),{namespaces:s}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{var r;e.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Eo(xi({},re("USER_DISCONNECTED")),{data:e.topic})))}),this.on(pt.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Qr]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r={},optionalNamespaces:n={},sessionProperties:i,scopedProperties:s}=e;this.optionalNamespaces=Di(r,n),this.sessionProperties=i,this.scopedProperties=s}validateChain(e){const[r,n]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,n];if(r&&!Object.keys(this.namespaces||{}).map(o=>en(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];const i=en(Object.keys(this.namespaces)[0]),s=this.rpcProviders[i].getDefaultChain();return[i,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,r=!1){if(!this.namespaces)return;const[n,i]=this.validateChain(e);if(!i)return;this.updateNamespaceChain(n,i),this.events.emit("chainChanged",i);const s=this.getProvider(n).getDefaultChain();r||this.getProvider(n).setDefaultChain(i),this.emitAccountsChangedOnChainChange({namespace:n,previousChainId:s,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:r,newChainId:n}){var i,s;try{if(r===n)return;const o=(s=(i=this.session)==null?void 0:i.namespaces[e])==null?void 0:s.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${n}:`)).map(nh);if(!Et(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,r){if(!this.namespaces)return;const n=this.namespaces[e]?e:`${e}:${r}`,i={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[n]?this.namespaces[n]&&(this.namespaces[n].defaultChain=r):this.namespaces[n]=i}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,r){var n;const i=((n=this.session)==null?void 0:n.topic)||"";await this.client.core.storage.setItem(`${Pi}/${e}${i}`,r)}async getFromStore(e){var r;const n=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${Pi}/${e}${n}`)}async deleteFromStore(e){var r;const n=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${Pi}/${e}${n}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const r=await this.client.core.storage.getKeys();for(const n of r)n.startsWith(Pi)&&await this.client.core.storage.removeItem(n)}catch(r){this.logger.warn("Failed to cleanup storage",r)}}};const tC=eC,rC="wc",nC="ethereum_provider",iC=`${rC}@2:${nC}:`,sC="https://rpc.walletconnect.org/v1/",ns=["eth_sendTransaction","personal_sign"],ig=["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"],is=["chainChanged","accountsChanged"],sg=["chainChanged","accountsChanged","message","disconnect","connect"],oC=async()=>{const{createAppKit:t}=await dh(()=>import("./core-R9E8jRfz.js").then(e=>e.X),__vite__mapDeps([3,1,2,4]));return t};var aC=Object.defineProperty,cC=Object.defineProperties,uC=Object.getOwnPropertyDescriptors,uh=Object.getOwnPropertySymbols,lC=Object.prototype.hasOwnProperty,hC=Object.prototype.propertyIsEnumerable,ha=(t,e,r)=>e in t?aC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,lr=(t,e)=>{for(var r in e||(e={}))lC.call(e,r)&&ha(t,r,e[r]);if(uh)for(var r of uh(e))hC.call(e,r)&&ha(t,r,e[r]);return t},Bn=(t,e)=>cC(t,uC(e)),et=(t,e,r)=>ha(t,typeof e!="symbol"?e+"":e,r);function ss(t){return Number(t[0].split(":")[1])}function Ai(t){return`0x${t.toString(16)}`}function fC(t){const{chains:e,optionalChains:r,methods:n,optionalMethods:i,events:s,optionalEvents:o,rpcMap:a}=t;if(!Et(e))throw new Error("Invalid chains");const c={chains:e,methods:n||ns,events:s||is,rpcMap:lr({},e.length?{[ss(e)]:a[ss(e)]}:{})},u=s?.filter(p=>!is.includes(p)),l=n?.filter(p=>!ns.includes(p));if(!r&&!o&&!i&&!(u!=null&&u.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const h=u?.length&&l?.length||!r,f={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(i!=null&&i.length?i:ig))],events:[...new Set(c.events.concat(o!=null&&o.length?o:sg))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?f:void 0}}class Ts{constructor(){et(this,"events",new sE.EventEmitter),et(this,"namespace","eip155"),et(this,"accounts",[]),et(this,"signer"),et(this,"chainId",1),et(this,"modal"),et(this,"rpc"),et(this,"STORAGE_KEY",iC),et(this,"on",(e,r)=>(this.events.on(e,r),this)),et(this,"once",(e,r)=>(this.events.once(e,r),this)),et(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),et(this,"off",(e,r)=>(this.events.off(e,r),this)),et(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new Ts;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,n){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),n)}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 r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:n,optional:i}=fC(this.rpc);try{const s=await new Promise(async(a,c)=>{var u,l;this.rpc.showQrModal&&((u=this.modal)==null||u.open(),(l=this.modal)==null||l.subscribeState(f=>{!f.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const h=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(Bn(lr({namespaces:lr({},n&&{[this.namespace]:n})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:e?.pairingTopic,scopedProperties:h})).then(f=>{a(f)}).catch(f=>{var p;(p=this.modal)==null||p.showErrorMessage("Unable to connect"),c(new Error(f.message))})});if(!s)return;const o=au(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Ai(this.chainId)})}catch(s){throw this.signer.logger.error(s),s}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var n;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const i=await new Promise(async(o,a)=>{var c,u;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(u=this.modal)==null||u.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(Bn(lr({},e),{chains:this.rpc.chains}),r).then(l=>{o(l)}).catch(l=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),s=i.session;if(s){const o=au(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Ai(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}finally{(n=this.modal)==null||n.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:r}=e,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.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 r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",Ai(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",Bn(lr({},re("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 r=e.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",Ai(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,n,i]=e.split(":");return{chainId:`${r}:${n}`,address:i}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,n;const i=(r=e?.chains)!=null?r:[],s=(n=e?.optionalChains)!=null?n:[],o=i.concat(s);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=i.length?e?.methods||ns:[],c=i.length?e?.events||is:[],u=e?.optionalMethods||[],l=e?.optionalEvents||[],h=e?.rpcMap||this.buildRpcMap(o,e.projectId),f=e?.qrModalOptions||void 0;return{chains:i?.map(p=>this.formatChainId(p)),optionalChains:s.map(p=>this.formatChainId(p)),methods:a,events:c,optionalMethods:u,optionalEvents:l,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:f,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const n={};return e.forEach(i=>{n[i]=this.getRpcUrl(i,r)}),n}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?ss(this.rpc.chains):ss(this.rpc.optionalChains),this.signer=await tC.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 r;try{const n=await oC(),{convertWCMToAppKitOptions:i}=await Promise.resolve().then(function(){return $C}),s=i(Bn(lr({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!s.networks.length)throw new Error("No networks found for WalletConnect·");r=n(Bn(lr({},s),{universalProvider:this.signer,manualWCControl:!0}))}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:n,rpcMap:i}=e;r&&Et(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)})),n&&Et(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(s=>this.formatChainId(s)),n.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)}))}getRpcUrl(e,r){var n;return((n=this.rpc.rpcMap)==null?void 0:n[e])||`${sC}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r?.accounts),this.setAccounts(r?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}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(r=>this.parseAccount(r))}}const dC=Ts;var pC=Object.defineProperty,gC=Object.defineProperties,yC=Object.getOwnPropertyDescriptors,lh=Object.getOwnPropertySymbols,mC=Object.prototype.hasOwnProperty,wC=Object.prototype.propertyIsEnumerable,hh=(t,e,r)=>e in t?pC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,og=(t,e)=>{for(var r in e||(e={}))mC.call(e,r)&&hh(t,r,e[r]);if(lh)for(var r of lh(e))wC.call(e,r)&&hh(t,r,e[r]);return t},vC=(t,e)=>gC(t,yC(e));function bC(t){if(t)return{"--w3m-font-family":t["--wcm-font-family"],"--w3m-accent":t["--wcm-accent-color"],"--w3m-color-mix":t["--wcm-background-color"],"--w3m-z-index":t["--wcm-z-index"]?Number(t["--wcm-z-index"]):void 0,"--w3m-qr-color":t["--wcm-accent-color"],"--w3m-font-size-master":t["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":t["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const EC=t=>{const[e,r]=t.split(":");return ag({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function _C(t){var e,r,n,i,s,o,a;const c=(e=t.chains)==null?void 0:e.map(EC).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const u=c.find(h=>{var f;return h.id===((f=t.defaultChain)==null?void 0:f.id)}),l={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:bC(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:u,metadata:vC(og({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((n=t.metadata)==null?void 0:n.description)||"Connect to WalletConnect-compatible wallets",url:((i=t.metadata)==null?void 0:i.url)||"https://walletconnect.org",icons:((s=t.metadata)==null?void 0:s.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:t.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(t.explorerRecommendedWalletIds)?t.explorerRecommendedWalletIds:[],excludeWalletIds:t.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(t.explorerExcludedWalletIds)?t.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=t.mobileWallets)!=null&&o.length||(a=t.desktopWallets)!=null&&a.length){const h=[...(t.mobileWallets||[]).map(d=>({id:d.id,name:d.name,links:d.links})),...(t.desktopWallets||[]).map(d=>({id:d.id,name:d.name,links:{native:d.links.native,universal:d.links.universal}}))],f=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],p=h.filter(d=>!f.includes(d.id));p.length&&(l.customWallets=p)}return l}function ag(t){return og({formatters:void 0,fees:void 0,serializers:void 0},t)}var $C=Object.freeze({__proto__:null,convertWCMToAppKitOptions:_C,defineChain:ag});const p3=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:dC,OPTIONAL_EVENTS:sg,OPTIONAL_METHODS:ig,REQUIRED_EVENTS:is,REQUIRED_METHODS:ns,default:Ts},Symbol.toStringTag,{value:"Module"}));export{My as A,ni as B,Jb as C,xt as D,Ke as E,lt as F,Dt as G,_t as H,Or as I,AE as J,HC as K,Xc as L,Vf as M,bE as N,CE as O,Lc as P,rf as Q,KC as R,zC as S,bs as T,VC as U,WC as V,p3 as W,wr as a,vr as b,T as c,pi as d,Ea as e,ht as f,sf as g,Mv as h,nf as i,qn as j,Co as k,us as l,ry as m,Q0 as n,dt as o,Ia as p,ms as q,gs as r,Wt as s,Ze as t,Ir as u,er as v,Dv as w,gr as x,Qe as y,ys as z};
38
+ Approved: ${f.toString()}`))}),o.forEach(h=>{n||(yr(i[h].methods,s[h].methods)?yr(i[h].events,s[h].events)||(n=N("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${h}`)):n=N("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${h}`))}),n}function DO(t){const e={};return Object.keys(t).forEach(r=>{var n;r.includes(":")?e[r]=t[r]:(n=t[r].chains)==null||n.forEach(i=>{e[i]={methods:t[r].methods,events:t[r].events}})}),e}function Qu(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function xO(t){const e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:Sn(t[r].accounts)?.forEach(i=>{e[i]={accounts:t[r].accounts.filter(s=>s.includes(`${i}:`)),methods:t[r].methods,events:t[r].events}})}),e}function AO(t,e){return ja(t)&&t<=e.max&&t>=e.min}function Xu(){const t=ai();return new Promise(e=>{switch(t){case it.browser:e(CO());break;case it.reactNative:e(LO());break;case it.node:e(RO());break;default:e(!0)}})}function CO(){return On()&&navigator?.onLine}async function LO(){return ir()&&typeof H<"u"&&H!=null&&H.NetInfo?(await(H==null?void 0:H.NetInfo.fetch()))?.isConnected:!0}function RO(){return!0}function TO(t){switch(ai()){case it.browser:NO(t);break;case it.reactNative:jO(t);break}}function NO(t){!ir()&&On()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function jO(t){ir()&&typeof H<"u"&&H!=null&&H.NetInfo&&H?.NetInfo.addEventListener(e=>t(e?.isConnected))}function MO(){var t;return On()&&vr()?((t=vr())==null?void 0:t.visibilityState)==="visible":!0}const uo={};class Rn{static get(e){return uo[e]}static set(e,r){uo[e]=r}static delete(e){delete uo[e]}}var Ma={exports:{}},cn=typeof Reflect=="object"?Reflect:null,el=cn&&typeof cn.apply=="function"?cn.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Bi;cn&&typeof cn.ownKeys=="function"?Bi=cn.ownKeys:Object.getOwnPropertySymbols?Bi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Bi=function(e){return Object.getOwnPropertyNames(e)};function BO(t){console&&console.warn&&console.warn(t)}var Fd=Number.isNaN||function(e){return e!==e};function ae(){ae.init.call(this)}Ma.exports=ae;Ma.exports.once=qO;ae.EventEmitter=ae;ae.prototype._events=void 0;ae.prototype._eventsCount=0;ae.prototype._maxListeners=void 0;var tl=10;function Ss(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ae,"defaultMaxListeners",{enumerable:!0,get:function(){return tl},set:function(t){if(typeof t!="number"||t<0||Fd(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");tl=t}});ae.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};ae.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Fd(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function kd(t){return t._maxListeners===void 0?ae.defaultMaxListeners:t._maxListeners}ae.prototype.getMaxListeners=function(){return kd(this)};ae.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")el(c,this,r);else for(var u=c.length,l=Vd(c,u),n=0;n<u;++n)el(l[n],this,r);return!0};function qd(t,e,r,n){var i,s,o;if(Ss(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=kd(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,BO(a)}return t}ae.prototype.addListener=function(e,r){return qd(this,e,r,!1)};ae.prototype.on=ae.prototype.addListener;ae.prototype.prependListener=function(e,r){return qd(this,e,r,!0)};function UO(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function zd(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=UO.bind(n);return i.listener=r,n.wrapFn=i,i}ae.prototype.once=function(e,r){return Ss(r),this.on(e,zd(this,e,r)),this};ae.prototype.prependOnceListener=function(e,r){return Ss(r),this.prependListener(e,zd(this,e,r)),this};ae.prototype.removeListener=function(e,r){var n,i,s,o,a;if(Ss(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():FO(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};ae.prototype.off=ae.prototype.removeListener;ae.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function Hd(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?kO(i):Vd(i,i.length)}ae.prototype.listeners=function(e){return Hd(this,e,!0)};ae.prototype.rawListeners=function(e){return Hd(this,e,!1)};ae.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Kd.call(t,e)};ae.prototype.listenerCount=Kd;function Kd(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}ae.prototype.eventNames=function(){return this._eventsCount>0?Bi(this._events):[]};function Vd(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function FO(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function kO(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function qO(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Wd(t,e,s,{once:!0}),e!=="error"&&zO(t,i,{once:!0})})}function zO(t,e,r){typeof t.on=="function"&&Wd(t,"error",e,r)}function Wd(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var Sr=Ma.exports;const HO=ri(Sr);function KO(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Pe(t,...e){try{return KO(t(...e))}catch(r){return Promise.reject(r)}}function VO(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function WO(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Ui(t){if(VO(t))return String(t);if(WO(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Ui(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Yo="base64:";function GO(t){return typeof t=="string"?t:Yo+ZO(t)}function YO(t){return typeof t!="string"||!t.startsWith(Yo)?t:JO(t.slice(Yo.length))}function JO(t){return globalThis.Buffer?Ce.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function ZO(t){return globalThis.Buffer?Ce.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Ge(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function QO(...t){return Ge(t.join(":"))}function Oi(t){return t=Ge(t),t?t+":":""}function XO(t,e){if(e===void 0)return!0;let r=0,n=t.indexOf(":");for(;n>-1;)r++,n=t.indexOf(":",n+1);return r<=e}function eI(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const tI="memory",rI=()=>{const t=new Map;return{name:tI,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function nI(t={}){const e={mounts:{"":t.driver||rI()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=u=>{for(const l of e.mountpoints)if(u.startsWith(l))return{base:l,relativeKey:u.slice(l.length),driver:e.mounts[l]};return{base:"",relativeKey:u,driver:e.mounts[""]}},n=(u,l)=>e.mountpoints.filter(h=>h.startsWith(u)||l&&u.startsWith(h)).map(h=>({relativeBase:u.length>h.length?u.slice(h.length):void 0,mountpoint:h,driver:e.mounts[h]})),i=(u,l)=>{if(e.watching){l=Ge(l);for(const h of e.watchListeners)h(u,l)}},s=async()=>{if(!e.watching){e.watching=!0;for(const u in e.mounts)e.unwatch[u]=await rl(e.mounts[u],i,u)}},o=async()=>{if(e.watching){for(const u in e.unwatch)await e.unwatch[u]();e.unwatch={},e.watching=!1}},a=(u,l,h)=>{const f=new Map,p=d=>{let y=f.get(d.base);return y||(y={driver:d.driver,base:d.base,items:[]},f.set(d.base,y)),y};for(const d of u){const y=typeof d=="string",w=Ge(y?d:d.key),b=y?void 0:d.value,v=y||!d.options?l:{...l,...d.options},E=r(w);p(E).items.push({key:w,value:b,relativeKey:E.relativeKey,options:v})}return Promise.all([...f.values()].map(d=>h(d))).then(d=>d.flat())},c={hasItem(u,l={}){u=Ge(u);const{relativeKey:h,driver:f}=r(u);return Pe(f.hasItem,h,l)},getItem(u,l={}){u=Ge(u);const{relativeKey:h,driver:f}=r(u);return Pe(f.getItem,h,l).then(p=>pi(p))},getItems(u,l={}){return a(u,l,h=>h.driver.getItems?Pe(h.driver.getItems,h.items.map(f=>({key:f.relativeKey,options:f.options})),l).then(f=>f.map(p=>({key:QO(h.base,p.key),value:pi(p.value)}))):Promise.all(h.items.map(f=>Pe(h.driver.getItem,f.relativeKey,f.options).then(p=>({key:f.key,value:pi(p)})))))},getItemRaw(u,l={}){u=Ge(u);const{relativeKey:h,driver:f}=r(u);return f.getItemRaw?Pe(f.getItemRaw,h,l):Pe(f.getItem,h,l).then(p=>YO(p))},async setItem(u,l,h={}){if(l===void 0)return c.removeItem(u);u=Ge(u);const{relativeKey:f,driver:p}=r(u);p.setItem&&(await Pe(p.setItem,f,Ui(l),h),p.watch||i("update",u))},async setItems(u,l){await a(u,l,async h=>{if(h.driver.setItems)return Pe(h.driver.setItems,h.items.map(f=>({key:f.relativeKey,value:Ui(f.value),options:f.options})),l);h.driver.setItem&&await Promise.all(h.items.map(f=>Pe(h.driver.setItem,f.relativeKey,Ui(f.value),f.options)))})},async setItemRaw(u,l,h={}){if(l===void 0)return c.removeItem(u,h);u=Ge(u);const{relativeKey:f,driver:p}=r(u);if(p.setItemRaw)await Pe(p.setItemRaw,f,l,h);else if(p.setItem)await Pe(p.setItem,f,GO(l),h);else return;p.watch||i("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=Ge(u);const{relativeKey:h,driver:f}=r(u);f.removeItem&&(await Pe(f.removeItem,h,l),(l.removeMeta||l.removeMata)&&await Pe(f.removeItem,h+"$",l),f.watch||i("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=Ge(u);const{relativeKey:h,driver:f}=r(u),p=Object.create(null);if(f.getMeta&&Object.assign(p,await Pe(f.getMeta,h,l)),!l.nativeOnly){const d=await Pe(f.getItem,h+"$",l).then(y=>pi(y));d&&typeof d=="object"&&(typeof d.atime=="string"&&(d.atime=new Date(d.atime)),typeof d.mtime=="string"&&(d.mtime=new Date(d.mtime)),Object.assign(p,d))}return p},setMeta(u,l,h={}){return this.setItem(u+"$",l,h)},removeMeta(u,l={}){return this.removeItem(u+"$",l)},async getKeys(u,l={}){u=Oi(u);const h=n(u,!0);let f=[];const p=[];let d=!0;for(const w of h){w.driver.flags?.maxDepth||(d=!1);const b=await Pe(w.driver.getKeys,w.relativeBase,l);for(const v of b){const E=w.mountpoint+Ge(v);f.some(O=>E.startsWith(O))||p.push(E)}f=[w.mountpoint,...f.filter(v=>!v.startsWith(w.mountpoint))]}const y=l.maxDepth!==void 0&&!d;return p.filter(w=>(!y||XO(w,l.maxDepth))&&eI(w,u))},async clear(u,l={}){u=Oi(u),await Promise.all(n(u,!1).map(async h=>{if(h.driver.clear)return Pe(h.driver.clear,h.relativeBase,l);if(h.driver.removeItem){const f=await h.driver.getKeys(h.relativeBase||"",l);return Promise.all(f.map(p=>h.driver.removeItem(p,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>nl(u)))},async watch(u){return await s(),e.watchListeners.push(u),async()=>{e.watchListeners=e.watchListeners.filter(l=>l!==u),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(u,l){if(u=Oi(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((h,f)=>f.length-h.length)),e.mounts[u]=l,e.watching&&Promise.resolve(rl(l,i,u)).then(h=>{e.unwatch[u]=h}).catch(console.error),c},async unmount(u,l=!0){u=Oi(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u]?.(),delete e.unwatch[u]),l&&await nl(e.mounts[u]),e.mountpoints=e.mountpoints.filter(h=>h!==u),delete e.mounts[u])},getMount(u=""){u=Ge(u)+":";const l=r(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=Ge(u),n(u,l.parents).map(f=>({driver:f.driver,base:f.mountpoint}))},keys:(u,l={})=>c.getKeys(u,l),get:(u,l={})=>c.getItem(u,l),set:(u,l,h={})=>c.setItem(u,l,h),has:(u,l={})=>c.hasItem(u,l),del:(u,l={})=>c.removeItem(u,l),remove:(u,l={})=>c.removeItem(u,l)};return c}function rl(t,e,r){return t.watch?t.watch((n,i)=>e(n,r+i)):()=>{}}async function nl(t){typeof t.dispose=="function"&&await Pe(t.dispose)}const iI="idb-keyval";var sI=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=i=>e+i;let n;return t.dbName&&t.storeName&&(n=gg(t.dbName,t.storeName)),{name:iI,options:t,async hasItem(i){return!(typeof await Za(r(i),n)>"u")},async getItem(i){return await Za(r(i),n)??null},setItem(i,s){return yg(r(i),s,n)},removeItem(i){return mg(r(i),n)},getKeys(){return wg(n)},clear(){return vg(n)}}};const oI="WALLET_CONNECT_V2_INDEXED_DB",aI="keyvaluestorage";let cI=class{constructor(){this.indexedDb=nI({driver:sI({dbName:oI,storeName:aI})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,Wt(r))}async removeItem(e){await this.indexedDb.removeItem(e)}};var lo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof H<"u"?H:typeof self<"u"?self:{},Fi={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,n){this[r]=String(n)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){const r=this;Object.keys(r).forEach(function(n){r[n]=void 0,delete r[n]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof lo<"u"&&lo.localStorage?Fi.exports=lo.localStorage:typeof window<"u"&&window.localStorage?Fi.exports=window.localStorage:Fi.exports=new e})();function uI(t){var e;return[t[0],wr((e=t[1])!=null?e:"")]}let lI=class{constructor(){this.localStorage=Fi.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(uI)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return wr(r)}async setItem(e,r){this.localStorage.setItem(e,Wt(r))}async removeItem(e){this.localStorage.removeItem(e)}};const hI="wc_storage_version",il=1,fI=async(t,e,r)=>{const n=hI,i=await e.getItem(n);if(i&&i>=il){r(e);return}const s=await t.getKeys();if(!s.length){r(e);return}const o=[];for(;s.length;){const a=s.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const u=await t.getItem(a);await e.setItem(a,u),o.push(a)}}await e.setItem(n,il),r(e),dI(t,o)},dI=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};let pI=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new lI;this.storage=e;try{const r=new cI;fI(e,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}};var Gd={exports:{}},un=typeof Reflect=="object"?Reflect:null,sl=un&&typeof un.apply=="function"?un.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},ki;un&&typeof un.ownKeys=="function"?ki=un.ownKeys:Object.getOwnPropertySymbols?ki=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:ki=function(e){return Object.getOwnPropertyNames(e)};function gI(t){console&&console.warn&&console.warn(t)}var Yd=Number.isNaN||function(e){return e!==e};function ce(){ce.init.call(this)}Gd.exports=ce;Gd.exports.once=vI;ce.EventEmitter=ce;ce.prototype._events=void 0;ce.prototype._eventsCount=0;ce.prototype._maxListeners=void 0;var ol=10;function Ds(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ce,"defaultMaxListeners",{enumerable:!0,get:function(){return ol},set:function(t){if(typeof t!="number"||t<0||Yd(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");ol=t}});ce.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};ce.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Yd(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Jd(t){return t._maxListeners===void 0?ce.defaultMaxListeners:t._maxListeners}ce.prototype.getMaxListeners=function(){return Jd(this)};ce.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")sl(c,this,r);else for(var u=c.length,l=tp(c,u),n=0;n<u;++n)sl(l[n],this,r);return!0};function Zd(t,e,r,n){var i,s,o;if(Ds(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=Jd(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,gI(a)}return t}ce.prototype.addListener=function(e,r){return Zd(this,e,r,!1)};ce.prototype.on=ce.prototype.addListener;ce.prototype.prependListener=function(e,r){return Zd(this,e,r,!0)};function yI(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Qd(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=yI.bind(n);return i.listener=r,n.wrapFn=i,i}ce.prototype.once=function(e,r){return Ds(r),this.on(e,Qd(this,e,r)),this};ce.prototype.prependOnceListener=function(e,r){return Ds(r),this.prependListener(e,Qd(this,e,r)),this};ce.prototype.removeListener=function(e,r){var n,i,s,o,a;if(Ds(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():mI(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};ce.prototype.off=ce.prototype.removeListener;ce.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function Xd(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?wI(i):tp(i,i.length)}ce.prototype.listeners=function(e){return Xd(this,e,!0)};ce.prototype.rawListeners=function(e){return Xd(this,e,!1)};ce.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):ep.call(t,e)};ce.prototype.listenerCount=ep;function ep(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}ce.prototype.eventNames=function(){return this._eventsCount>0?ki(this._events):[]};function tp(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function mI(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function wI(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function vI(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}rp(t,e,s,{once:!0}),e!=="error"&&bI(t,i,{once:!0})})}function bI(t,e,r){typeof t.on=="function"&&rp(t,"error",e,r)}function rp(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var EI=Object.defineProperty,_I=(t,e,r)=>e in t?EI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,al=(t,e,r)=>_I(t,typeof e!="symbol"?e+"":e,r);let $I=class extends Or{constructor(e){super(),this.opts=e,al(this,"protocol","wc"),al(this,"version",2)}};var OI=Object.defineProperty,II=(t,e,r)=>e in t?OI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,PI=(t,e,r)=>II(t,e+"",r);let SI=class extends Or{constructor(e,r){super(),this.core=e,this.logger=r,PI(this,"records",new Map)}},DI=class{constructor(e,r){this.logger=e,this.core=r}};class xI extends Or{constructor(e,r){super(),this.relayer=e,this.logger=r}}let AI=class extends Or{constructor(e){super()}},CI=class{constructor(e,r,n,i){this.core=e,this.logger=r,this.name=n}},LI=class extends Or{constructor(e,r){super(),this.relayer=e,this.logger=r}},RI=class extends Or{constructor(e,r){super(),this.core=e,this.logger=r}},TI=class{constructor(e,r,n){this.core=e,this.logger=r,this.store=n}},NI=class{constructor(e,r){this.projectId=e,this.logger=r}},jI=class{constructor(e,r,n){this.core=e,this.logger=r,this.telemetryEnabled=n}};var MI=Object.defineProperty,BI=(t,e,r)=>e in t?MI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,cl=(t,e,r)=>BI(t,typeof e!="symbol"?e+"":e,r);let UI=class{constructor(e){this.opts=e,cl(this,"protocol","wc"),cl(this,"version",2)}},FI=class{constructor(e){this.client=e}};var kI={VITE_BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23627664864.commit-ab90df9"};const np="wc",ip=2,rs="core",Tt=`${np}@2:${rs}:`,qI={name:rs,logger:"error"},zI={database:":memory:"},HI="crypto",ul="client_ed25519_seed",KI=T.ONE_DAY,VI="keychain",WI="0.3",GI="messages",YI="0.3",ll=T.SIX_HOURS,JI="publisher",sp="irn",ZI="error",op="wss://relay.walletconnect.org",QI="relayer",De={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"},XI="_subscription",at={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},e2=.1,Jo="2.21.1",me={link_mode:"link_mode",relay:"relay"},qi={inbound:"inbound",outbound:"outbound"},t2="0.3",r2="WALLETCONNECT_CLIENT_ID",hl="WALLETCONNECT_LINK_MODE_APPS",tt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},n2="subscription",i2="0.3",s2="pairing",o2="0.3",Tn={wc_pairingDelete:{req:{ttl:T.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:T.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:T.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:T.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:T.ONE_DAY,prompt:!1,tag:0},res:{ttl:T.ONE_DAY,prompt:!1,tag:0}}},dr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},yt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},a2="history",c2="0.3",u2="expirer",ut={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},l2="0.3",h2="verify-api",f2="https://verify.walletconnect.com",ap="https://verify.walletconnect.org",Hn=ap,d2=`${Hn}/v3`,p2=[f2,ap],g2="echo",y2="https://echo.walletconnect.com",St={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"},qt={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"},mt={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"},ar={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"},cr={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",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",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},Nn={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",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"},m2=.1,w2="event-client",v2=86400,b2="https://pulse.walletconnect.org/batch";function E2(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,w=0,b=0,v=d.length;b!==v&&d[b]===0;)b++,y++;for(var E=(v-b)*l+1>>>0,O=new Uint8Array(E);b!==v;){for(var x=d[b],D=0,S=E-1;(x!==0||D<w)&&S!==-1;S--,D++)x+=256*O[S]>>>0,O[S]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");w=D,b++}for(var C=E-w;C!==E&&O[C]===0;)C++;for(var I=c.repeat(y);C<E;++C)I+=t.charAt(O[C]);return I}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var w=0,b=0;d[y]===c;)w++,y++;for(var v=(d.length-y)*u+1>>>0,E=new Uint8Array(v);d[y];){var O=r[d.charCodeAt(y)];if(O===255)return;for(var x=0,D=v-1;(O!==0||x<b)&&D!==-1;D--,x++)O+=a*E[D]>>>0,E[D]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");b=x,y++}if(d[y]!==" "){for(var S=v-b;S!==v&&E[S]===0;)S++;for(var C=new Uint8Array(w+(v-S)),I=w;S!==v;)C[I++]=E[S++];return C}}}function p(d){var y=f(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var _2=E2,$2=_2;const cp=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},O2=t=>new TextEncoder().encode(t),I2=t=>new TextDecoder().decode(t);class P2{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class S2{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}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 up(this,e)}}class D2{constructor(e){this.decoders=e}or(e){return up(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const up=(t,e)=>new D2({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class x2{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new P2(e,r,n),this.decoder=new S2(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const xs=({name:t,prefix:e,encode:r,decode:n})=>new x2(t,e,r,n),di=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=$2(r,e);return xs({prefix:t,name:e,encode:n,decode:s=>cp(i(s))})},A2=(t,e,r,n)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=i[t[l]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},C2=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},Be=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>xs({prefix:e,name:t,encode(i){return C2(i,n,r)},decode(i){return A2(i,n,r,t)}}),L2=xs({prefix:"\0",name:"identity",encode:t=>I2(t),decode:t=>O2(t)});var R2=Object.freeze({__proto__:null,identity:L2});const T2=Be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var N2=Object.freeze({__proto__:null,base2:T2});const j2=Be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var M2=Object.freeze({__proto__:null,base8:j2});const B2=di({prefix:"9",name:"base10",alphabet:"0123456789"});var U2=Object.freeze({__proto__:null,base10:B2});const F2=Be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),k2=Be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var q2=Object.freeze({__proto__:null,base16:F2,base16upper:k2});const z2=Be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),H2=Be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),K2=Be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),V2=Be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),W2=Be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),G2=Be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Y2=Be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),J2=Be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Z2=Be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Q2=Object.freeze({__proto__:null,base32:z2,base32upper:H2,base32pad:K2,base32padupper:V2,base32hex:W2,base32hexupper:G2,base32hexpad:Y2,base32hexpadupper:J2,base32z:Z2});const X2=di({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),eP=di({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var tP=Object.freeze({__proto__:null,base36:X2,base36upper:eP});const rP=di({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),nP=di({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var iP=Object.freeze({__proto__:null,base58btc:rP,base58flickr:nP});const sP=Be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),oP=Be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),aP=Be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),cP=Be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var uP=Object.freeze({__proto__:null,base64:sP,base64pad:oP,base64url:aP,base64urlpad:cP});const lp=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),lP=lp.reduce((t,e,r)=>(t[r]=e,t),[]),hP=lp.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function fP(t){return t.reduce((e,r)=>(e+=lP[r],e),"")}function dP(t){const e=[];for(const r of t){const n=hP[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const pP=xs({prefix:"🚀",name:"base256emoji",encode:fP,decode:dP});var gP=Object.freeze({__proto__:null,base256emoji:pP}),yP=hp,fl=128,mP=127,wP=~mP,vP=Math.pow(2,31);function hp(t,e,r){e=e||[],r=r||0;for(var n=r;t>=vP;)e[r++]=t&255|fl,t/=128;for(;t&wP;)e[r++]=t&255|fl,t>>>=7;return e[r]=t|0,hp.bytes=r-n+1,e}var bP=Zo,EP=128,dl=127;function Zo(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw Zo.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&dl)<<i:(o&dl)*Math.pow(2,i),i+=7}while(o>=EP);return Zo.bytes=s-n,r}var _P=Math.pow(2,7),$P=Math.pow(2,14),OP=Math.pow(2,21),IP=Math.pow(2,28),PP=Math.pow(2,35),SP=Math.pow(2,42),DP=Math.pow(2,49),xP=Math.pow(2,56),AP=Math.pow(2,63),CP=function(t){return t<_P?1:t<$P?2:t<OP?3:t<IP?4:t<PP?5:t<SP?6:t<DP?7:t<xP?8:t<AP?9:10},LP={encode:yP,decode:bP,encodingLength:CP},fp=LP;const pl=(t,e,r=0)=>(fp.encode(t,e,r),e),gl=t=>fp.encodingLength(t),Qo=(t,e)=>{const r=e.byteLength,n=gl(t),i=n+gl(r),s=new Uint8Array(i+r);return pl(t,s,0),pl(r,s,n),s.set(e,i),new RP(t,r,e,s)};class RP{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const dp=({name:t,code:e,encode:r})=>new TP(t,e,r);class TP{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Qo(this.code,r):r.then(n=>Qo(this.code,n))}else throw Error("Unknown type, must be binary type")}}const pp=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),NP=dp({name:"sha2-256",code:18,encode:pp("SHA-256")}),jP=dp({name:"sha2-512",code:19,encode:pp("SHA-512")});var MP=Object.freeze({__proto__:null,sha256:NP,sha512:jP});const gp=0,BP="identity",yp=cp,UP=t=>Qo(gp,yp(t)),FP={code:gp,name:BP,encode:yp,digest:UP};var kP=Object.freeze({__proto__:null,identity:FP});new TextEncoder,new TextDecoder;const yl={...R2,...N2,...M2,...U2,...q2,...Q2,...tP,...iP,...uP,...gP};({...MP,...kP});function qP(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function mp(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const ml=mp("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ho=mp("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=qP(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),zP={utf8:ml,"utf-8":ml,hex:yl.base16,latin1:ho,ascii:ho,binary:ho,...yl};function HP(t,e="utf8"){const r=zP[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}var KP=Object.defineProperty,VP=(t,e,r)=>e in t?KP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,It=(t,e,r)=>VP(t,typeof e!="symbol"?e+"":e,r);class WP{constructor(e,r){this.core=e,this.logger=r,It(this,"keychain",new Map),It(this,"name",VI),It(this,"version",WI),It(this,"initialized",!1),It(this,"storagePrefix",Tt),It(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),It(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),It(this,"set",async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()}),It(this,"get",n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=N("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i}),It(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=Ke(r,this.name)}get context(){return Qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Mo(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Bo(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var GP=Object.defineProperty,YP=(t,e,r)=>e in t?GP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Te=(t,e,r)=>YP(t,typeof e!="symbol"?e+"":e,r);class JP{constructor(e,r,n){this.core=e,this.logger=r,Te(this,"name",HI),Te(this,"keychain"),Te(this,"randomSessionIdentifier",Go()),Te(this,"initialized",!1),Te(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Te(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Te(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=Lc(i);return rf(s.publicKey)}),Te(this,"generateKeyPair",()=>{this.isInitialized();const i=N$();return this.setPrivateKey(i.publicKey,i.privateKey)}),Te(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=Lc(s),a=this.randomSessionIdentifier;return await Dv(a,i,KI,o)}),Te(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=j$(a,s);return this.setSymKey(c,o)}),Te(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||Mi(i);return await this.keychain.set(o,i),o}),Te(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Te(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Te(this,"encode",async(i,s,o)=>{this.isInitialized();const a=Md(o),c=Wt(s);if(qu(a))return U$(c,o?.encoding);if(ku(a)){const f=a.senderPublicKey,p=a.receiverPublicKey;i=await this.generateSharedKey(f,p)}const u=this.getSymKey(i),{type:l,senderPublicKey:h}=a;return M$({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o?.encoding})}),Te(this,"decode",async(i,s,o)=>{this.isInitialized();const a=k$(s,o);if(qu(a)){const c=F$(s,o?.encoding);return wr(c)}if(ku(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=B$({symKey:c,encoded:s,encoding:o?.encoding});return wr(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Te(this,"getPayloadType",(i,s=bt)=>{const o=ti({encoded:i,encoding:s});return $r(o.type)}),Te(this,"getPayloadSenderPublicKey",(i,s=bt)=>{const o=ti({encoded:i,encoding:s});return o.senderPublicKey?Ze(o.senderPublicKey,He):void 0}),this.core=e,this.logger=Ke(r,this.name),this.keychain=n||new WP(this.core,this.logger)}get context(){return Qe(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(ul)}catch{e=Go(),await this.keychain.set(ul,e)}return HP(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var ZP=Object.defineProperty,QP=Object.defineProperties,XP=Object.getOwnPropertyDescriptors,wl=Object.getOwnPropertySymbols,eS=Object.prototype.hasOwnProperty,tS=Object.prototype.propertyIsEnumerable,Xo=(t,e,r)=>e in t?ZP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rS=(t,e)=>{for(var r in e||(e={}))eS.call(e,r)&&Xo(t,r,e[r]);if(wl)for(var r of wl(e))tS.call(e,r)&&Xo(t,r,e[r]);return t},nS=(t,e)=>QP(t,XP(e)),Xe=(t,e,r)=>Xo(t,typeof e!="symbol"?e+"":e,r);class iS extends DI{constructor(e,r){super(e,r),this.logger=e,this.core=r,Xe(this,"messages",new Map),Xe(this,"messagesWithoutClientAck",new Map),Xe(this,"name",GI),Xe(this,"version",YI),Xe(this,"initialized",!1),Xe(this,"storagePrefix",Tt),Xe(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}}),Xe(this,"set",async(n,i,s)=>{this.isInitialized();const o=Ct(i);let a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(n,a),s===qi.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,nS(rS({},c),{[o]:i}))}return await this.persist(),o}),Xe(this,"get",n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i}),Xe(this,"getWithoutAck",n=>{this.isInitialized();const i={};for(const s of n){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),Xe(this,"has",(n,i)=>{this.isInitialized();const s=this.get(n),o=Ct(i);return typeof s[o]<"u"}),Xe(this,"ack",async(n,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;const o=Ct(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),Xe(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=Ke(e,this.name),this.core=r}get context(){return Qe(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,Mo(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Mo(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Bo(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Bo(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var sS=Object.defineProperty,oS=Object.defineProperties,aS=Object.getOwnPropertyDescriptors,vl=Object.getOwnPropertySymbols,cS=Object.prototype.hasOwnProperty,uS=Object.prototype.propertyIsEnumerable,ea=(t,e,r)=>e in t?sS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ii=(t,e)=>{for(var r in e||(e={}))cS.call(e,r)&&ea(t,r,e[r]);if(vl)for(var r of vl(e))uS.call(e,r)&&ea(t,r,e[r]);return t},fo=(t,e)=>oS(t,aS(e)),wt=(t,e,r)=>ea(t,typeof e!="symbol"?e+"":e,r);class lS extends xI{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,wt(this,"events",new Sr.EventEmitter),wt(this,"name",JI),wt(this,"queue",new Map),wt(this,"publishTimeout",T.toMiliseconds(T.ONE_MINUTE)),wt(this,"initialPublishTimeout",T.toMiliseconds(T.ONE_SECOND*15)),wt(this,"needsTransportRestart",!1),wt(this,"publish",async(n,i,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});const a=s?.ttl||ll,c=es(s),u=s?.prompt||!1,l=s?.tag||0,h=s?.id||gr().toString(),f={topic:n,message:i,opts:{ttl:a,relay:c,prompt:u,tag:l,id:h,attestation:s?.attestation,tvf:s?.tvf}},p=`Failed to publish payload, please try again. id:${h} tag:${l}`;try{const d=new Promise(async y=>{const w=({id:v})=>{f.opts.id===v&&(this.removeRequestFromQueue(v),this.relayer.events.removeListener(De.publish,w),y(f))};this.relayer.events.on(De.publish,w);const b=tr(new Promise((v,E)=>{this.rpcPublish({topic:n,message:i,ttl:a,prompt:u,tag:l,id:h,attestation:s?.attestation,tvf:s?.tvf}).then(v).catch(O=>{this.logger.warn(O,O?.message),E(O)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${h} tag:${l}`);try{await b,this.events.removeListener(De.publish,w)}catch(v){this.queue.set(h,fo(Ii({},f),{attempt:1})),this.logger.warn(v,v?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:h,topic:n,message:i,opts:s}}),await tr(d,this.publishTimeout,p)}catch(d){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(d),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw d}finally{this.queue.delete(h)}}),wt(this,"on",(n,i)=>{this.events.on(n,i)}),wt(this,"once",(n,i)=>{this.events.once(n,i)}),wt(this,"off",(n,i)=>{this.events.off(n,i)}),wt(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.relayer=e,this.logger=Ke(r,this.name),this.registerEventListeners()}get context(){return Qe(this.logger)}async rpcPublish(e){var r,n,i,s;const{topic:o,message:a,ttl:c=ll,prompt:u,tag:l,id:h,attestation:f,tvf:p}=e,d={method:Un(es().protocol).publish,params:Ii({topic:o,message:a,ttl:c,prompt:u,tag:l,attestation:f},p),id:h};ke((r=d.params)==null?void 0:r.prompt)&&((n=d.params)==null||delete n.prompt),ke((i=d.params)==null?void 0:i.tag)&&((s=d.params)==null||delete s.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:d});const y=await this.relayer.request(d);return this.relayer.events.emit(De.publish,e),this.logger.debug("Successfully Published Payload"),y}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const n=e.attempt+1;this.queue.set(r,fo(Ii({},e),{attempt:n}));const{topic:i,message:s,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${n}`),await this.rpcPublish(fo(Ii({},e),{topic:i,message:s,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(Ir.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(De.connection_stalled);return}this.checkQueue()}),this.relayer.on(De.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var hS=Object.defineProperty,fS=(t,e,r)=>e in t?hS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Br=(t,e,r)=>fS(t,typeof e!="symbol"?e+"":e,r);class dS{constructor(){Br(this,"map",new Map),Br(this,"set",(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])}),Br(this,"get",e=>this.map.get(e)||[]),Br(this,"exists",(e,r)=>this.get(e).includes(r)),Br(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),Br(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var pS=Object.defineProperty,gS=Object.defineProperties,yS=Object.getOwnPropertyDescriptors,bl=Object.getOwnPropertySymbols,mS=Object.prototype.hasOwnProperty,wS=Object.prototype.propertyIsEnumerable,ta=(t,e,r)=>e in t?pS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jn=(t,e)=>{for(var r in e||(e={}))mS.call(e,r)&&ta(t,r,e[r]);if(bl)for(var r of bl(e))wS.call(e,r)&&ta(t,r,e[r]);return t},po=(t,e)=>gS(t,yS(e)),fe=(t,e,r)=>ta(t,typeof e!="symbol"?e+"":e,r);class vS extends LI{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,fe(this,"subscriptions",new Map),fe(this,"topicMap",new dS),fe(this,"events",new Sr.EventEmitter),fe(this,"name",n2),fe(this,"version",i2),fe(this,"pending",new Map),fe(this,"cached",[]),fe(this,"initialized",!1),fe(this,"storagePrefix",Tt),fe(this,"subscribeTimeout",T.toMiliseconds(T.ONE_MINUTE)),fe(this,"initialSubscribeTimeout",T.toMiliseconds(T.ONE_SECOND*15)),fe(this,"clientId"),fe(this,"batchSubscribeTopicsLimit",500),fe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),fe(this,"subscribe",async(n,i)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const s=es(i),o={topic:n,relay:s,transportType:i?.transportType};this.pending.set(n,o);const a=await this.rpcSubscribe(n,s,i);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}}),fe(this,"unsubscribe",async(n,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)}),fe(this,"isSubscribed",n=>new Promise(i=>{i(this.topicMap.topics.includes(n))})),fe(this,"isKnownTopic",n=>new Promise(i=>{i(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),fe(this,"on",(n,i)=>{this.events.on(n,i)}),fe(this,"once",(n,i)=>{this.events.once(n,i)}),fe(this,"off",(n,i)=>{this.events.off(n,i)}),fe(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),fe(this,"start",async()=>{await this.onConnect()}),fe(this,"stop",async()=>{await this.onDisconnect()}),fe(this,"restart",async()=>{await this.restore(),await this.onRestart()}),fe(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const n=[];this.pending.forEach(i=>{n.push(i)}),await this.batchSubscribe(n)}),fe(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Ir.pulse,async()=>{await this.checkPending()}),this.events.on(tt.created,async n=>{const i=tt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()}),this.events.on(tt.deleted,async n=>{const i=tt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()})}),this.relayer=e,this.logger=Ke(r,this.name),this.clientId=""}get context(){return Qe(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,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=es(n);await this.restartToComplete({topic:e,id:r,relay:i}),await this.rpcUnsubscribe(e,r,i);const s=re("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r,n){var i;(!n||n?.transportType===me.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const s={method:Un(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});const o=(i=n?.internal)==null?void 0:i.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(n?.transportType===me.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(l=>this.logger.warn(l))},T.toMiliseconds(T.ONE_SECOND)),a;const c=new Promise(async l=>{const h=f=>{f.topic===e&&(this.events.removeListener(tt.created,h),l(f.id))};this.events.on(tt.created,h);try{const f=await tr(new Promise((p,d)=>{this.relayer.request(s).catch(y=>{this.logger.warn(y,y?.message),d(y)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(tt.created,h),l(f)}catch{}}),u=await tr(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return u?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(De.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Un(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await tr(new Promise(i=>{this.relayer.request(n).catch(s=>this.logger.warn(s)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(De.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:Un(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let i;try{i=await await tr(new Promise((s,o)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(De.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:Un(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,po(jn({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,jn({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),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,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,jn({},r)),this.topicMap.set(r.topic,e),this.events.emit(tt.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=N("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(tt.deleted,po(jn({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(tt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<r;n++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(tt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=N("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}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 r=>po(jn({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await _1(T.toMiliseconds(T.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=N("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 Ct(e+await this.getClientId())}}var bS=Object.defineProperty,El=Object.getOwnPropertySymbols,ES=Object.prototype.hasOwnProperty,_S=Object.prototype.propertyIsEnumerable,ra=(t,e,r)=>e in t?bS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_l=(t,e)=>{for(var r in e||(e={}))ES.call(e,r)&&ra(t,r,e[r]);if(El)for(var r of El(e))_S.call(e,r)&&ra(t,r,e[r]);return t},Q=(t,e,r)=>ra(t,typeof e!="symbol"?e+"":e,r);class $S extends AI{constructor(e){super(e),Q(this,"protocol","wc"),Q(this,"version",2),Q(this,"core"),Q(this,"logger"),Q(this,"events",new Sr.EventEmitter),Q(this,"provider"),Q(this,"messages"),Q(this,"subscriber"),Q(this,"publisher"),Q(this,"name",QI),Q(this,"transportExplicitlyClosed",!1),Q(this,"initialized",!1),Q(this,"connectionAttemptInProgress",!1),Q(this,"relayUrl"),Q(this,"projectId"),Q(this,"packageName"),Q(this,"bundleId"),Q(this,"hasExperiencedNetworkDisruption",!1),Q(this,"pingTimeout"),Q(this,"heartBeatTimeout",T.toMiliseconds(T.THIRTY_SECONDS+T.FIVE_SECONDS)),Q(this,"reconnectTimeout"),Q(this,"connectPromise"),Q(this,"reconnectInProgress",!1),Q(this,"requestsInFlight",[]),Q(this,"connectTimeout",T.toMiliseconds(T.ONE_SECOND*15)),Q(this,"request",async r=>{var n,i;this.logger.debug("Publishing Request Payload");const s=r.id||gr().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - publishing...");const o=`${s}:${((i=r.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}}),Q(this,"resetPingTimeout",()=>{Qi()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,i,s;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(s=(i=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null?void 0:i.terminate)==null||s.call(i)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),Q(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),Q(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(De.connect)}),Q(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Q(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(De.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Q(this,"registerProviderListeners",()=>{this.provider.on(at.payload,this.onPayloadHandler),this.provider.on(at.connect,this.onConnectHandler),this.provider.on(at.disconnect,this.onDisconnectHandler),this.provider.on(at.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Ke(e.logger,this.name):ni(us({level:e.logger||ZI})),this.messages=new iS(this.logger,e.core),this.subscriber=new vS(this,this.logger),this.publisher=new lS(this,this.logger),this.relayUrl=e?.relayUrl||op,this.projectId=e.projectId,o1()?this.packageName=hu():a1()&&(this.bundleId=hu()),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?.message)}}get context(){return Qe(this.logger)}get connected(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1||!1}get connecting(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:me.relay},qi.outbound)}async subscribe(e,r){var n,i,s;this.isInitialized(),(!(r!=null&&r.transportType)||r?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((n=r?.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(i=r?.internal)==null?void 0:i.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(tt.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(tt.created,u)}),new Promise(async(l,h)=>{a=await this.subscriber.subscribe(e,_l({internal:{throwOnFailedPublish:o}},r)).catch(f=>{o&&h(f)})||a,l()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await tr(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(r,n)=>{await this.connect(e).then(r).catch(n).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 Xu())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const r=e.sort((n,i)=>n.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const n of r)try{await this.onMessageEvent(n)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:n}=e;if(!r.sessionExists){const i=_e(T.FIVE_MINUTES),s={topic:n,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(De.message,e),await this.recordMessageEvent(e,qi.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(n,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(at.disconnect,s),await tr(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{i(o)}).finally(()=>{this.provider.off(at.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(at.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(at.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,n()})}catch(n){await this.subscriber.stop();const i=n;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(n=>setTimeout(n,T.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,n,i,s;if(Qi())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(i=(n=this.provider)==null?void 0:n.connection)==null?void 0:i.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new dt(new Q0(f1({sdkVersion:Jo,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,r){const{topic:n,message:i}=e;await this.messages.set(n,i,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const i=this.messages.has(r,n);return i&&this.logger.warn(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Ia(e)){if(!e.method.endsWith(XI))return;const r=e.params,{topic:n,message:i,publishedAt:s,attestation:o}=r.data,a={topic:n,message:i,publishedAt:s,transportType:me.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(_l({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ms(e)&&this.events.emit(De.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,qi.inbound),this.events.emit(De.message,e))}async acknowledgePayload(e){const r=gs(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(at.payload,this.onPayloadHandler),this.provider.off(at.connect,this.onConnectHandler),this.provider.off(at.disconnect,this.onDisconnectHandler),this.provider.off(at.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Xu();TO(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(n=>this.logger.error(n,n?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Ir.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&MO())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(De.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?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},T.toMiliseconds(e2)))))}isInitialized(){if(!this.initialized){const{message:e}=N("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 OS(){}function $l(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function Ol(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Il(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const IS="[object RegExp]",PS="[object String]",SS="[object Number]",DS="[object Boolean]",Pl="[object Arguments]",xS="[object Symbol]",AS="[object Date]",CS="[object Map]",LS="[object Set]",RS="[object Array]",TS="[object Function]",NS="[object ArrayBuffer]",go="[object Object]",jS="[object Error]",MS="[object DataView]",BS="[object Uint8Array]",US="[object Uint8ClampedArray]",FS="[object Uint16Array]",kS="[object Uint32Array]",qS="[object BigUint64Array]",zS="[object Int8Array]",HS="[object Int16Array]",KS="[object Int32Array]",VS="[object BigInt64Array]",WS="[object Float32Array]",GS="[object Float64Array]";function YS(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function JS(t,e,r){return Fn(t,e,void 0,void 0,void 0,void 0,r)}function Fn(t,e,r,n,i,s,o){const a=o(t,e,r,n,i,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Kn(t,e,s,o)}return Kn(t,e,s,o)}function Kn(t,e,r,n){if(Object.is(t,e))return!0;let i=Il(t),s=Il(e);if(i===Pl&&(i=go),s===Pl&&(s=go),i!==s)return!1;switch(i){case PS:return t.toString()===e.toString();case SS:{const c=t.valueOf(),u=e.valueOf();return YS(c,u)}case DS:case AS:case xS:return Object.is(t.valueOf(),e.valueOf());case IS:return t.source===e.source&&t.flags===e.flags;case TS:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(i){case CS:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!Fn(u,e.get(c),c,t,e,r,n))return!1;return!0}case LS:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let l=0;l<c.length;l++){const h=c[l],f=u.findIndex(p=>Fn(h,p,void 0,t,e,r,n));if(f===-1)return!1;u.splice(f,1)}return!0}case RS:case BS:case US:case FS:case kS:case qS:case zS:case HS:case KS:case VS:case WS:case GS:{if(typeof Ce<"u"&&Ce.isBuffer(t)!==Ce.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Fn(t[c],e[c],c,t,e,r,n))return!1;return!0}case NS:return t.byteLength!==e.byteLength?!1:Kn(new Uint8Array(t),new Uint8Array(e),r,n);case MS:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Kn(new Uint8Array(t),new Uint8Array(e),r,n);case jS:return t.name===e.name&&t.message===e.message;case go:{if(!(Kn(t.constructor,e.constructor,r,n)||$l(t)&&$l(e)))return!1;const c=[...Object.keys(t),...Ol(t)],u=[...Object.keys(e),...Ol(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const h=c[l],f=t[h];if(!Object.hasOwn(e,h))return!1;const p=e[h];if(!Fn(f,p,h,t,e,r,n))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function ZS(t,e){return JS(t,e,OS)}var QS=Object.defineProperty,Sl=Object.getOwnPropertySymbols,XS=Object.prototype.hasOwnProperty,eD=Object.prototype.propertyIsEnumerable,na=(t,e,r)=>e in t?QS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Dl=(t,e)=>{for(var r in e||(e={}))XS.call(e,r)&&na(t,r,e[r]);if(Sl)for(var r of Sl(e))eD.call(e,r)&&na(t,r,e[r]);return t},We=(t,e,r)=>na(t,typeof e!="symbol"?e+"":e,r);class Dr extends CI{constructor(e,r,n,i=Tt,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,We(this,"map",new Map),We(this,"version",t2),We(this,"cached",[]),We(this,"initialized",!1),We(this,"getKey"),We(this,"storagePrefix",Tt),We(this,"recentlyDeleted",[]),We(this,"recentlyDeletedLimit",200),We(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!ke(o)?this.map.set(this.getKey(o),o):hO(o)?this.map.set(o.id,o):fO(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),We(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())}),We(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),We(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>ZS(a[c],o[c]))):this.values)),We(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=Dl(Dl({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),We(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=Ke(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return Qe(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 r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:i}=N("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=N("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}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:r}=N("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var tD=Object.defineProperty,rD=(t,e,r)=>e in t?tD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,W=(t,e,r)=>rD(t,typeof e!="symbol"?e+"":e,r);class nD{constructor(e,r){this.core=e,this.logger=r,W(this,"name",s2),W(this,"version",o2),W(this,"events",new HO),W(this,"pairings"),W(this,"initialized",!1),W(this,"storagePrefix",Tt),W(this,"ignoredPayloadTypes",[Vt]),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:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),W(this,"create",async n=>{this.isInitialized();const i=Go(),s=await this.core.crypto.setSymKey(i),o=_e(T.FIVE_MINUTES),a={protocol:sp},c={topic:s,expiry:o,relay:a,active:!1,methods:n?.methods},u=Hu({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(dr.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType}),{topic:s,uri:u}}),W(this,"pair",async n=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[St.pairing_started]}});this.isValidPair(n,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=zu(n.uri);i.props.properties.topic=s,i.addTrace(St.pairing_uri_validation_success),i.addTrace(St.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(St.existing_pairing),l.active)throw i.setError(qt.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(St.pairing_not_expired)}const h=c||_e(T.FIVE_MINUTES),f={topic:s,relay:a,expiry:h,active:!1,methods:u};this.core.expirer.set(s,h),await this.pairings.set(s,f),i.addTrace(St.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(dr.create,f),i.addTrace(St.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(St.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(qt.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(p){throw i.setError(qt.subscribe_pairing_topic_failure),p}return i.addTrace(St.subscribe_pairing_topic_success),f}),W(this,"activate",async({topic:n})=>{this.isInitialized();const i=_e(T.FIVE_MINUTES);this.core.expirer.set(n,i),await this.pairings.update(n,{active:!0,expiry:i})}),W(this,"ping",async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=n;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=ur();this.events.once(ee("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),W(this,"updateExpiry",async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})}),W(this,"updateMetadata",async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})}),W(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),W(this,"disconnect",async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",re("USER_DISCONNECTED")),await this.deletePairing(i))}),W(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(i);return Hu({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),W(this,"sendRequest",async(n,i,s)=>{const o=er(i,s),a=await this.core.crypto.encode(n,o),c=Tn[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),W(this,"sendResult",async(n,i,s)=>{const o=gs(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Tn[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),W(this,"sendError",async(n,i,s)=>{const o=ys(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Tn[c]?Tn[c].res:Tn.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),W(this,"deletePairing",async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,re("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])}),W(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(i=>Qt(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))}),W(this,"onRelayEventRequest",async n=>{const{topic:i,payload:s}=n;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,s);default:return await this.onUnknownRpcMethodRequest(i,s)}}),W(this,"onRelayEventResponse",async n=>{const{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}}),W(this,"onPairingPingRequest",async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(dr.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),W(this,"onPairingPingResponse",(n,i)=>{const{id:s}=i;setTimeout(()=>{xt(i)?this.events.emit(ee("pairing_ping",s),{}):lt(i)&&this.events.emit(ee("pairing_ping",s),{error:i.error})},500)}),W(this,"onPairingDeleteRequest",async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(dr.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),W(this,"onUnknownRpcMethodRequest",async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=re("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}}),W(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(re("WC_METHOD_UNSUPPORTED",n))}),W(this,"isValidPair",(n,i)=>{var s;if(!Ye(n)){const{message:a}=N("MISSING_OR_INVALID",`pair() params: ${n}`);throw i.setError(qt.malformed_pairing_uri),new Error(a)}if(!lO(n.uri)){const{message:a}=N("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw i.setError(qt.malformed_pairing_uri),new Error(a)}const o=zu(n?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=N("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(qt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=N("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(qt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&T.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(qt.pairing_expired);const{message:a}=N("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),W(this,"isValidPing",async n=>{if(!Ye(n)){const{message:s}=N("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),W(this,"isValidDisconnect",async n=>{if(!Ye(n)){const{message:s}=N("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),W(this,"isValidPairingTopic",async n=>{if(!Ee(n,!1)){const{message:i}=N("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=N("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(Qt(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=N("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}}),this.core=e,this.logger=Ke(r,this.name),this.pairings=new Dr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Qe(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(De.message,async e=>{const{topic:r,message:n,transportType:i}=e;if(this.pairings.keys.includes(r)&&i!==me.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const s=await this.core.crypto.decode(r,n);Ia(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ms(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,n)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(ut.expired,async e=>{const{topic:r}=id(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(dr.expire,{topic:r}))})}}var iD=Object.defineProperty,sD=(t,e,r)=>e in t?iD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ne=(t,e,r)=>sD(t,typeof e!="symbol"?e+"":e,r);class oD extends SI{constructor(e,r){super(e,r),this.core=e,this.logger=r,Ne(this,"records",new Map),Ne(this,"events",new Sr.EventEmitter),Ne(this,"name",a2),Ne(this,"version",c2),Ne(this,"cached",[]),Ne(this,"initialized",!1),Ne(this,"storagePrefix",Tt),Ne(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ne(this,"set",(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s,expiry:_e(T.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(yt.created,o)}),Ne(this,"resolve",async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=lt(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(yt.updated,i))}),Ne(this,"get",async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i))),Ne(this,"delete",(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(yt.deleted,s)}}),this.persist()}),Ne(this,"exists",async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1)),Ne(this,"on",(n,i)=>{this.events.on(n,i)}),Ne(this,"once",(n,i)=>{this.events.once(n,i)}),Ne(this,"off",(n,i)=>{this.events.off(n,i)}),Ne(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=Ke(r,this.name)}get context(){return Qe(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(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:er(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),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 r=this.records.get(e);if(!r){const{message:n}=N("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(yt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=N("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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(yt.created,e=>{const r=yt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(yt.updated,e=>{const r=yt.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(yt.deleted,e=>{const r=yt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(Ir.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{T.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(yt.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var aD=Object.defineProperty,cD=(t,e,r)=>e in t?aD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fe=(t,e,r)=>cD(t,typeof e!="symbol"?e+"":e,r);class uD extends RI{constructor(e,r){super(e,r),this.core=e,this.logger=r,Fe(this,"expirations",new Map),Fe(this,"events",new Sr.EventEmitter),Fe(this,"name",u2),Fe(this,"version",l2),Fe(this,"cached",[]),Fe(this,"initialized",!1),Fe(this,"storagePrefix",Tt),Fe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Fe(this,"has",n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}}),Fe(this,"set",(n,i)=>{this.isInitialized();const s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(ut.created,{target:s,expiration:o})}),Fe(this,"get",n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)}),Fe(this,"del",n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(ut.deleted,{target:i,expiration:s})}}),Fe(this,"on",(n,i)=>{this.events.on(n,i)}),Fe(this,"once",(n,i)=>{this.events.once(n,i)}),Fe(this,"off",(n,i)=>{this.events.off(n,i)}),Fe(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=Ke(r,this.name)}get context(){return Qe(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 d1(e);if(typeof e=="number")return p1(e);const{message:r}=N("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}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(ut.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=N("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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 r=this.expirations.get(e);if(!r){const{message:n}=N("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;T.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(ut.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Ir.pulse,()=>this.checkExpirations()),this.events.on(ut.created,e=>{const r=ut.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(ut.expired,e=>{const r=ut.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(ut.deleted,e=>{const r=ut.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var lD=Object.defineProperty,hD=(t,e,r)=>e in t?lD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,be=(t,e,r)=>hD(t,typeof e!="symbol"?e+"":e,r);class fD extends TI{constructor(e,r,n){super(e,r,n),this.core=e,this.logger=r,this.store=n,be(this,"name",h2),be(this,"abortController"),be(this,"isDevEnv"),be(this,"verifyUrlV3",d2),be(this,"storagePrefix",Tt),be(this,"version",ip),be(this,"publicKey"),be(this,"fetchPromise"),be(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&T.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),be(this,"register",async i=>{if(!On()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const u=vr(),l=this.startAbortTimer(T.ONE_SECOND*5),h=await new Promise((f,p)=>{const d=()=>{window.removeEventListener("message",w),u.body.removeChild(y),p("attestation aborted")};this.abortController.signal.addEventListener("abort",d);const y=u.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",d,{signal:this.abortController.signal});const w=b=>{if(b.data&&typeof b.data=="string")try{const v=JSON.parse(b.data);if(v.type==="verify_attestation"){if(Co(v.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(y),this.abortController.signal.removeEventListener("abort",d),window.removeEventListener("message",w),f(v.attestation===null?"":v.attestation)}}catch(v){this.logger.warn(v)}};u.body.appendChild(y),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",h),h}catch(u){this.logger.warn(u)}return""}),be(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=i;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Co(s).payload.id!==a)return;const u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!o)return;const c=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(o,c)}),be(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(T.ONE_SECOND*5),a=await fetch(`${s}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),be(this,"getVerifyUrl",i=>{let s=i||Hn;return p2.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Hn}`),s=Hn),s}),be(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(T.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await s.json()}catch(i){this.logger.warn(i)}}),be(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),be(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),be(this,"isValidJwtAttestation",async i=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(i,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),be(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),be(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),be(this,"validateAttestation",(i,s)=>{const o=z$(i,s.publicKey),a={hasExpired:T.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=Ke(r,this.name),this.abortController=new AbortController,this.isDevEnv=xa(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Qe(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),T.toMiliseconds(e))}}var dD=Object.defineProperty,pD=(t,e,r)=>e in t?dD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xl=(t,e,r)=>pD(t,typeof e!="symbol"?e+"":e,r);class gD extends NI{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,xl(this,"context",g2),xl(this,"registerDeviceToken",async n=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,c=`${y2}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:a})})}),this.logger=Ke(r,this.context)}}var yD=Object.defineProperty,Al=Object.getOwnPropertySymbols,mD=Object.prototype.hasOwnProperty,wD=Object.prototype.propertyIsEnumerable,ia=(t,e,r)=>e in t?yD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mn=(t,e)=>{for(var r in e||(e={}))mD.call(e,r)&&ia(t,r,e[r]);if(Al)for(var r of Al(e))wD.call(e,r)&&ia(t,r,e[r]);return t},Oe=(t,e,r)=>ia(t,typeof e!="symbol"?e+"":e,r);class vD extends jI{constructor(e,r,n=!0){super(e,r,n),this.core=e,this.logger=r,Oe(this,"context",w2),Oe(this,"storagePrefix",Tt),Oe(this,"storageVersion",m2),Oe(this,"events",new Map),Oe(this,"shouldPersist",!1),Oe(this,"init",async()=>{if(!xa())try{const i={eventId:du(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:rd(this.core.relayer.protocol,this.core.relayer.version,Jo)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Oe(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,u=du(),l=this.core.projectId||"",h=Date.now(),f=Mn({eventId:u,timestamp:h,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,f),this.shouldPersist=!0),f}),Oe(this,"getEvent",i=>{const{eventId:s,topic:o}=i;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Mn(Mn({},a),this.setMethods(a.eventId))}),Oe(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),Oe(this,"setEventListeners",()=>{this.core.heartbeat.on(Ir.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{T.fromMiliseconds(Date.now())-T.fromMiliseconds(i.timestamp)>v2&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Oe(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),Oe(this,"addTrace",(i,s)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(s),this.events.set(i,o),this.shouldPersist=!0)}),Oe(this,"setError",(i,s)=>{const o=this.events.get(i);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),Oe(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Oe(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(s=>{this.events.set(s.eventId,Mn(Mn({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),Oe(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[s,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const s of i)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),Oe(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${b2}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Jo}${s}`,{method:"POST",body:JSON.stringify(i)})}),Oe(this,"getAppDomain",()=>td().url),this.logger=Ke(r,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var bD=Object.defineProperty,Cl=Object.getOwnPropertySymbols,ED=Object.prototype.hasOwnProperty,_D=Object.prototype.propertyIsEnumerable,sa=(t,e,r)=>e in t?bD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ll=(t,e)=>{for(var r in e||(e={}))ED.call(e,r)&&sa(t,r,e[r]);if(Cl)for(var r of Cl(e))_D.call(e,r)&&sa(t,r,e[r]);return t},ge=(t,e,r)=>sa(t,typeof e!="symbol"?e+"":e,r);let $D=class wp extends $I{constructor(e){var r;super(e),ge(this,"protocol",np),ge(this,"version",ip),ge(this,"name",rs),ge(this,"relayUrl"),ge(this,"projectId"),ge(this,"customStoragePrefix"),ge(this,"events",new Sr.EventEmitter),ge(this,"logger"),ge(this,"heartbeat"),ge(this,"relayer"),ge(this,"crypto"),ge(this,"storage"),ge(this,"history"),ge(this,"expirer"),ge(this,"pairing"),ge(this,"verify"),ge(this,"echoClient"),ge(this,"linkModeSupportedApps"),ge(this,"eventClient"),ge(this,"initialized",!1),ge(this,"logChunkController"),ge(this,"on",(a,c)=>this.events.on(a,c)),ge(this,"once",(a,c)=>this.events.once(a,c)),ge(this,"off",(a,c)=>this.events.off(a,c)),ge(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ge(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:me.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const n=this.getGlobalCore(e?.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||op,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=us({level:typeof e?.logger=="string"&&e.logger?e.logger:qI.logger,name:rs}),{logger:s,chunkLoggerController:o}=My({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.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=Ke(s,this.name),this.heartbeat=new ry,this.crypto=new JP(this,this.logger,e?.keychain),this.history=new oD(this,this.logger),this.expirer=new uD(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new pI(Ll(Ll({},zI),e?.storageOptions)),this.relayer=new $S({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new nD(this,this.logger),this.verify=new fD(this,this.logger,this.storage),this.echoClient=new gD(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new vD(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new wp(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(r2,n),r}get context(){return Qe(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(hl,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(hl)||[],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 r=`_walletConnectCore_${e}`,n=`${r}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[n]=e}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof ft<"u"&&kI.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const OD=$D;var Ba={exports:{}},ln=typeof Reflect=="object"?Reflect:null,Rl=ln&&typeof ln.apply=="function"?ln.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},zi;ln&&typeof ln.ownKeys=="function"?zi=ln.ownKeys:Object.getOwnPropertySymbols?zi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:zi=function(e){return Object.getOwnPropertyNames(e)};function ID(t){console&&console.warn&&console.warn(t)}var vp=Number.isNaN||function(e){return e!==e};function ue(){ue.init.call(this)}Ba.exports=ue;Ba.exports.once=xD;ue.EventEmitter=ue;ue.prototype._events=void 0;ue.prototype._eventsCount=0;ue.prototype._maxListeners=void 0;var Tl=10;function As(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ue,"defaultMaxListeners",{enumerable:!0,get:function(){return Tl},set:function(t){if(typeof t!="number"||t<0||vp(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Tl=t}});ue.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};ue.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||vp(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function bp(t){return t._maxListeners===void 0?ue.defaultMaxListeners:t._maxListeners}ue.prototype.getMaxListeners=function(){return bp(this)};ue.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")Rl(c,this,r);else for(var u=c.length,l=Ip(c,u),n=0;n<u;++n)Rl(l[n],this,r);return!0};function Ep(t,e,r,n){var i,s,o;if(As(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=bp(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,ID(a)}return t}ue.prototype.addListener=function(e,r){return Ep(this,e,r,!1)};ue.prototype.on=ue.prototype.addListener;ue.prototype.prependListener=function(e,r){return Ep(this,e,r,!0)};function PD(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _p(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=PD.bind(n);return i.listener=r,n.wrapFn=i,i}ue.prototype.once=function(e,r){return As(r),this.on(e,_p(this,e,r)),this};ue.prototype.prependOnceListener=function(e,r){return As(r),this.prependListener(e,_p(this,e,r)),this};ue.prototype.removeListener=function(e,r){var n,i,s,o,a;if(As(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():SD(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};ue.prototype.off=ue.prototype.removeListener;ue.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function $p(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?DD(i):Ip(i,i.length)}ue.prototype.listeners=function(e){return $p(this,e,!0)};ue.prototype.rawListeners=function(e){return $p(this,e,!1)};ue.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Op.call(t,e)};ue.prototype.listenerCount=Op;function Op(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}ue.prototype.eventNames=function(){return this._eventsCount>0?zi(this._events):[]};function Ip(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function SD(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function DD(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function xD(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Pp(t,e,s,{once:!0}),e!=="error"&&AD(t,i,{once:!0})})}function AD(t,e,r){typeof t.on=="function"&&Pp(t,"error",e,r)}function Pp(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var Sp=Ba.exports;const CD=ri(Sp),Dp="wc",xp=2,Ap="client",Ua=`${Dp}@${xp}:${Ap}:`,yo={name:Ap,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Nl="WALLETCONNECT_DEEPLINK_CHOICE",LD="proposal",jl="Proposal expired",RD="session",Ur=T.SEVEN_DAYS,TD="engine",Ie={wc_sessionPropose:{req:{ttl:T.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:T.ONE_DAY,prompt:!1,tag:1104},res:{ttl:T.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:T.ONE_DAY,prompt:!1,tag:1106},res:{ttl:T.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:T.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:T.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:T.ONE_DAY,prompt:!1,tag:1112},res:{ttl:T.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:T.ONE_DAY,prompt:!1,tag:1114},res:{ttl:T.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:T.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:T.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:T.FIVE_MINUTES,prompt:!1,tag:1119}}},mo={min:T.FIVE_MINUTES,max:T.SEVEN_DAYS},Pt={idle:"IDLE",active:"ACTIVE"},Ml={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},ND="request",jD=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],MD="wc",BD="auth",UD="authKeys",FD="pairingTopics",kD="requests",Cs=`${MD}@${1.5}:${BD}:`,Hi=`${Cs}:PUB_KEY`;var qD=Object.defineProperty,zD=Object.defineProperties,HD=Object.getOwnPropertyDescriptors,Bl=Object.getOwnPropertySymbols,KD=Object.prototype.hasOwnProperty,VD=Object.prototype.propertyIsEnumerable,oa=(t,e,r)=>e in t?qD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,de=(t,e)=>{for(var r in e||(e={}))KD.call(e,r)&&oa(t,r,e[r]);if(Bl)for(var r of Bl(e))VD.call(e,r)&&oa(t,r,e[r]);return t},ze=(t,e)=>zD(t,HD(e)),R=(t,e,r)=>oa(t,typeof e!="symbol"?e+"":e,r);class WD extends FI{constructor(e){super(e),R(this,"name",TD),R(this,"events",new CD),R(this,"initialized",!1),R(this,"requestQueue",{state:Pt.idle,queue:[]}),R(this,"sessionRequestQueue",{state:Pt.idle,queue:[]}),R(this,"requestQueueDelay",T.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(Ie)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},T.toMiliseconds(this.requestQueueDelay)))}),R(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=ze(de({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=sO(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=n;let l=i,h,f=!1;try{if(l){const D=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),f=D.active}}catch(D){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),D}if(!l||!f){const{topic:D,uri:S}=await this.client.core.pairing.create();l=D,h=S}if(!l){const{message:D}=N("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(D)}const p=await this.client.core.crypto.generateKeyPair(),d=Ie.wc_sessionPropose.req.ttl||T.FIVE_MINUTES,y=_e(d),w=ze(de(de({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:sp}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Dt()}),b=ee("session_connect",w.id),{reject:v,resolve:E,done:O}=ur(d,jl),x=({id:D})=>{D===w.id&&(this.client.events.off("proposal_expire",x),this.pendingSessions.delete(w.id),this.events.emit(b,{error:{message:jl,code:0}}))};return this.client.events.on("proposal_expire",x),this.events.once(b,({error:D,session:S})=>{this.client.events.off("proposal_expire",x),D?v(D):S&&E(S)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:w,throwOnFailedPublish:!0,clientRpcId:w.id}),await this.setProposal(w.id,w),{uri:h,approval:O}}),R(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}}),R(this,"approve",async r=>{var n,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(n=r?.id)==null?void 0:n.toString(),trace:[mt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(I){throw o.setError(ar.no_internet_connection),I}try{await this.isValidProposalId(r?.id)}catch(I){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(ar.proposal_not_found),I}try{await this.isValidApprove(r)}catch(I){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(ar.session_approve_namespace_validation_failure),I}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:d,proposer:y,requiredNamespaces:w,optionalNamespaces:b}=p;let v=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:d});v||(v=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:mt.session_approve_started,properties:{topic:d,trace:[mt.session_approve_started,mt.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),O=y.publicKey,x=await this.client.core.crypto.generateSharedKey(E,O),D=de(de(de({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:E,metadata:this.client.metadata},expiry:_e(Ur)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),S=me.relay;v.addTrace(mt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(x,{transportType:S})}catch(I){throw v.setError(ar.subscribe_session_topic_failure),I}v.addTrace(mt.subscribe_session_topic_success);const C=ze(de({},D),{topic:x,requiredNamespaces:w,optionalNamespaces:b,pairingTopic:d,acknowledged:!1,self:D.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:E,transportType:me.relay});await this.client.session.set(x,C),v.addTrace(mt.store_session);try{v.addTrace(mt.publishing_session_settle),await this.sendRequest({topic:x,method:"wc_sessionSettle",params:D,throwOnFailedPublish:!0}).catch(I=>{throw v?.setError(ar.session_settle_publish_failure),I}),v.addTrace(mt.session_settle_publish_success),v.addTrace(mt.publishing_session_approve),await this.sendResult({id:a,topic:d,result:{relay:{protocol:c??"irn"},responderPublicKey:E},throwOnFailedPublish:!0}).catch(I=>{throw v?.setError(ar.session_approve_publish_failure),I}),v.addTrace(mt.session_approve_publish_success)}catch(I){throw this.client.logger.error(I),this.client.session.delete(x,re("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(x),I}return this.client.core.eventClient.deleteEvent({eventId:v.eventId}),await this.client.core.pairing.updateMetadata({topic:d,metadata:y.metadata}),await this.client.proposal.delete(a,re("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:d}),await this.setExpiry(x,_e(Ur)),{topic:x,acknowledged:()=>Promise.resolve(this.client.session.get(x))}}),R(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:n,reason:i}=r;let s;try{s=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}s&&(await this.sendError({id:n,topic:s,error:i,rpcOpts:Ie.wc_sessionPropose.reject}),await this.client.proposal.delete(n,re("USER_DISCONNECTED")))}),R(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:a}=ur(),c=Dt(),u=gr().toString(),l=this.client.session.get(n).namespaces;return this.events.once(ee("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(n,{namespaces:i}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(h=>{this.client.logger.error(h),this.client.session.update(n,{namespaces:l}),a(h)}),{acknowledged:s}}),R(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:n}=r,i=Dt(),{done:s,resolve:o,reject:a}=ur();return this.events.once(ee("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,_e(Ur)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),R(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:n,request:i,topic:s,expiry:o=Ie.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===me.relay&&await this.confirmOnlineStateOrThrow();const c=Dt(),u=gr().toString(),{done:l,resolve:h,reject:f}=ur(o,"Request expired. Please try again.");this.events.once(ee("session_request",c),({error:b,result:v})=>{b?f(b):h(v)});const p="wc_sessionRequest",d=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(d)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:{request:ze(de({},i),{expiryTimestamp:_e(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:d}).catch(b=>f(b)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),await l();const y={request:ze(de({},i),{expiryTimestamp:_e(o)}),chainId:n},w=this.shouldSetTVF(p,y);return await Promise.all([new Promise(async b=>{await this.sendRequest(de({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:y,expiry:o,throwOnFailedPublish:!0},w&&{tvf:this.getTVFParams(c,y)})).catch(v=>f(v)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),b()}),new Promise(async b=>{var v;if(!((v=a.sessionConfig)!=null&&v.disableDeepLink)){const E=await w1(this.client.core.storage,Nl);await g1({id:c,topic:s,wcDeepLink:E})}b()}),l()]).then(b=>b[2])}),R(this,"respond",async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:s}=i,o=this.client.session.get(n);o.transportType===me.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);xt(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0,appLink:a}):lt(i)&&await this.sendError({id:s,topic:n,error:i.error,appLink:a}),this.cleanupAfterResponse(r)}),R(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=Dt(),s=gr().toString(),{done:o,resolve:a,reject:c}=ur();this.events.once(ee("session_ping",i),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&(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:n}))}),R(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r,o=gr().toString(),a=Dt();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),R(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:re("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{const{message:i}=N("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}}),R(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>cO(n,r)))),R(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),R(this,"authenticate",async(r,n)=>{var i;this.isInitialized(),this.isValidAuthenticate(r);const s=n&&this.client.core.linkModeSupportedApps.includes(n)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?me.link_mode:me.relay;o===me.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:h,type:f,exp:p,nbf:d,methods:y=[],expiry:w}=r,b=[...r.resources||[]],{topic:v,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:v,uri:E}});const O=await this.client.core.crypto.generateKeyPair(),x=Mi(O);if(await Promise.all([this.client.auth.authKeys.set(Hi,{responseTopic:x,publicKey:O}),this.client.auth.pairingTopics.set(x,{topic:x,pairingTopic:v})]),await this.client.core.relayer.subscribe(x,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${v}`),y.length>0){const{namespace:$}=an(a[0]);let A=l_($,"request",y);ji(b)&&(A=f_(A,b.pop())),b.push(A)}const D=w&&w>Ie.wc_sessionAuthenticate.req.ttl?w:Ie.wc_sessionAuthenticate.req.ttl,S={authPayload:{type:f??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:h,iat:new Date().toISOString(),exp:p,nbf:d,resources:b},requester:{publicKey:O,metadata:this.client.metadata},expiryTimestamp:_e(D)},C={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},I={requiredNamespaces:{},optionalNamespaces:C,relays:[{protocol:"irn"}],pairingTopic:v,proposer:{publicKey:O,metadata:this.client.metadata},expiryTimestamp:_e(Ie.wc_sessionPropose.req.ttl),id:Dt()},{done:k,resolve:M,reject:j}=ur(D,"Request expired"),q=Dt(),L=ee("session_connect",I.id),g=ee("session_request",q),m=async({error:$,session:A})=>{this.events.off(g,_),$?j($):A&&M({session:A})},_=async $=>{var A,B,F;if(await this.deletePendingAuthRequest(q,{message:"fulfilled",code:0}),$.error){const J=re("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return $.error.code===J.code?void 0:(this.events.off(L,m),j($.error.message))}await this.deleteProposal(I.id),this.events.off(L,m);const{cacaos:z,responder:U}=$.result,K=[],Y=[];for(const J of z){await Eu({cacao:J,projectId:this.client.core.projectId})||(this.client.logger.error(J,"Signature verification failed"),j(re("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ue}=J,Le=ji(Ue.resources),qe=[Uo(Ue.iss)],ot=Xi(Ue.iss);if(Le){const Nt=_u(Le),Ar=$u(Le);K.push(...Nt),qe.push(...Ar)}for(const Nt of qe)Y.push(`${Nt}:${ot}`)}const pe=await this.client.core.crypto.generateSharedKey(O,U.publicKey);let te;K.length>0&&(te={topic:pe,acknowledged:!0,self:{publicKey:O,metadata:this.client.metadata},peer:U,controller:U.publicKey,expiry:_e(Ur),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:v,namespaces:Gu([...new Set(K)],[...new Set(Y)]),transportType:o},await this.client.core.relayer.subscribe(pe,{transportType:o}),await this.client.session.set(pe,te),v&&await this.client.core.pairing.updateMetadata({topic:v,metadata:U.metadata}),te=this.client.session.get(pe)),(A=this.client.metadata.redirect)!=null&&A.linkMode&&(B=U.metadata.redirect)!=null&&B.linkMode&&(F=U.metadata.redirect)!=null&&F.universal&&n&&(this.client.core.addLinkModeSupportedApp(U.metadata.redirect.universal),this.client.session.update(pe,{transportType:me.link_mode})),M({auths:z,session:te})};this.events.once(L,m),this.events.once(g,_);let P;try{if(s){const $=er("wc_sessionAuthenticate",S,q);this.client.core.history.set(v,$);const A=await this.client.core.crypto.encode("",$,{type:fi,encoding:Xt});P=$i(n,v,A)}else await Promise.all([this.sendRequest({topic:v,method:"wc_sessionAuthenticate",params:S,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:q}),this.sendRequest({topic:v,method:"wc_sessionPropose",params:I,expiry:Ie.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:I.id})])}catch($){throw this.events.off(L,m),this.events.off(g,_),$}return await this.setProposal(I.id,I),await this.setAuthRequest(q,{request:ze(de({},S),{verifyContext:{}}),pairingTopic:v,transportType:o}),{uri:P??E,response:k}}),R(this,"approveSessionAuthenticate",async r=>{const{id:n,auths:i}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[cr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw s.setError(Nn.no_internet_connection),w}const o=this.getPendingAuthRequest(n);if(!o)throw s.setError(Nn.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||me.relay;a===me.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=Mi(c),h={type:Vt,receiverPublicKey:c,senderPublicKey:u},f=[],p=[];for(const w of i){if(!await Eu({cacao:w,projectId:this.client.core.projectId})){s.setError(Nn.invalid_cacao);const x=re("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:l,error:x,encodeOpts:h}),new Error(x.message)}s.addTrace(cr.cacaos_verified);const{p:b}=w,v=ji(b.resources),E=[Uo(b.iss)],O=Xi(b.iss);if(v){const x=_u(v),D=$u(v);f.push(...x),E.push(...D)}for(const x of E)p.push(`${x}:${O}`)}const d=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(cr.create_authenticated_session_topic);let y;if(f?.length>0){y={topic:d,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:_e(Ur),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Gu([...new Set(f)],[...new Set(p)]),transportType:a},s.addTrace(cr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(d,{transportType:a})}catch(w){throw s.setError(Nn.subscribe_authenticated_session_topic_failure),w}s.addTrace(cr.subscribe_authenticated_session_topic_success),await this.client.session.set(d,y),s.addTrace(cr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(cr.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:n,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw s.setError(Nn.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:y}}),R(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:n,reason:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);s.transportType===me.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Mi(o),u={type:Vt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:i,encodeOpts:u,rpcOpts:Ie.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.client.proposal.delete(n,re("USER_DISCONNECTED"))}),R(this,"formatAuthMessage",r=>{this.isInitialized();const{request:n,iss:i}=r;return dd(n,i)}),R(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),R(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}}),R(this,"deleteSession",async r=>{var n;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,re("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),s||this.client.core.expirer.del(i),this.client.core.storage.removeItem(Nl).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===i&&this.deletePendingSessionRequest(u.id,re("USER_DISCONNECTED"))}),i===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=Pt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),R(this,"deleteProposal",async(r,n)=>{if(n)try{const i=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:i.pairingTopic})?.setError(ar.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,re("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),R(this,"deletePendingSessionRequest",async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),i&&(this.sessionRequestQueue.state=Pt.idle,this.client.events.emit("session_request_expire",{id:r}))}),R(this,"deletePendingAuthRequest",async(r,n,i=!1)=>{await Promise.all([this.client.auth.requests.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)])}),R(this,"setExpiry",async(r,n)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,n),await this.client.session.update(r,{expiry:n}))}),R(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,_e(Ie.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),R(this,"setAuthRequest",async(r,n)=>{const{request:i,pairingTopic:s,transportType:o=me.relay}=n;this.client.core.expirer.set(r,i.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:r,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),R(this,"setPendingSessionRequest",async r=>{const{id:n,topic:i,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||_e(Ie.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:i,params:s,verifyContext:o})}),R(this,"sendRequest",async r=>{const{topic:n,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:h}=r,f=er(i,s,c);let p;const d=!!l;try{const b=d?Xt:bt;p=await this.client.core.crypto.encode(n,f,{encoding:b})}catch(b){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),b}let y;if(jD.includes(i)){const b=Ct(JSON.stringify(f)),v=Ct(p);y=await this.client.core.verify.register({id:v,decryptedId:b})}const w=Ie[i].req;if(w.attestation=y,o&&(w.ttl=o),a&&(w.id=a),this.client.core.history.set(n,f),d){const b=$i(l,n,p);await H.Linking.openURL(b,this.client.name)}else{const b=Ie[i].req;o&&(b.ttl=o),a&&(b.id=a),b.tvf=ze(de({},h),{correlationId:f.id}),u?(b.internal=ze(de({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,p,b)):this.client.core.relayer.publish(n,p,b).catch(v=>this.client.logger.error(v))}return f.id}),R(this,"sendResult",async r=>{const{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,u=gs(n,s);let l;const h=c&&typeof(H==null?void 0:H.Linking)<"u";try{const d=h?Xt:bt;l=await this.client.core.crypto.encode(i,u,ze(de({},a||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),d}let f,p;try{f=await this.client.core.history.get(i,n);const d=f.request;try{this.shouldSetTVF(d.method,d.params)&&(p=this.getTVFParams(n,d.params,s))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(d){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),d}if(h){const d=$i(c,i,l);await H.Linking.openURL(d,this.client.name)}else{const d=f.request.method,y=Ie[d].res;y.tvf=ze(de({},p),{correlationId:n}),o?(y.internal=ze(de({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,y)):this.client.core.relayer.publish(i,l,y).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(u)}),R(this,"sendError",async r=>{const{id:n,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,u=ys(n,s);let l;const h=c&&typeof(H==null?void 0:H.Linking)<"u";try{const p=h?Xt:bt;l=await this.client.core.crypto.encode(i,u,ze(de({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),p}let f;try{f=await this.client.core.history.get(i,n)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),p}if(h){const p=$i(c,i,l);await H.Linking.openURL(p,this.client.name)}else{const p=f.request.method,d=a||Ie[p].res;this.client.core.relayer.publish(i,l,d)}await this.client.core.history.resolve(u)}),R(this,"cleanup",async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;Qt(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{Qt(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])}),R(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),R(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),R(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Pt.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=Pt.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Pt.idle}),R(this,"processRequest",async r=>{const{topic:n,payload:i,attestation:s,transportType:o,encryptedId:a}=r,c=i.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,i);case"wc_sessionPing":return await this.onSessionPingRequest(n,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(n,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),R(this,"onRelayEventResponse",async r=>{const{topic:n,payload:i,transportType:s}=r,o=(await this.client.core.history.get(n,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),R(this,"onRelayEventUnknownPayload",r=>{const{topic:n}=r,{message:i}=N("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),R(this,"shouldIgnorePairingRequest",r=>{const{topic:n,requestMethod:i}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),R(this,"onSessionProposeRequest",async r=>{const{topic:n,payload:i,attestation:s,encryptedId:o}=r,{params:a,id:c}=i;try{const u=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(qt.proposal_listener_not_found)),this.isValidConnect(de({},i.params));const l=a.expiryTimestamp||_e(Ie.wc_sessionPropose.req.ttl),h=de({id:c,pairingTopic:n,expiryTimestamp:l},a);await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:s,hash:Ct(JSON.stringify(i)),encryptedId:o,metadata:h.proposer.metadata});u?.addTrace(St.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(u){await this.sendError({id:c,topic:n,error:u,rpcOpts:Ie.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),R(this,"onSessionProposeResponse",async(r,n,i)=>{const{id:s}=n;if(xt(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);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 u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const l=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:l,pairingTopic:r,proposalId:s,publicKey:c});const h=await this.client.core.relayer.subscribe(l,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:r})}else if(lt(n)){await this.client.proposal.delete(s,re("USER_DISCONNECTED"));const o=ee("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:n.error})}}),R(this,"onSessionSettleRequest",async(r,n)=>{const{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f}=n.params,p=[...this.pendingSessions.values()].find(w=>w.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const d=this.client.proposal.get(p.proposalId),y=ze(de(de(de({topic:r,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:d.requiredNamespaces,optionalNamespaces:d.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{transportType:me.relay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:y.peer.metadata}),this.client.events.emit("session_connect",{session:y}),this.events.emit(ee("session_connect",p.proposalId),{session:y}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:n.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"onSessionSettleResponse",async(r,n)=>{const{id:i}=n;xt(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ee("session_approve",i),{})):lt(n)&&(await this.client.session.delete(r,re("USER_DISCONNECTED")),this.events.emit(ee("session_approve",i),{error:n.error}))}),R(this,"onSessionUpdateRequest",async(r,n)=>{const{params:i,id:s}=n;try{const o=`${r}_session_update`,a=Rn.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:re("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(de({topic:r},i));try{Rn.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(c){throw Rn.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3)<r.toString().slice(0,-3)),R(this,"onSessionUpdateResponse",(r,n)=>{const{id:i}=n,s=ee("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);xt(n)?this.events.emit(ee("session_update",i),{}):lt(n)&&this.events.emit(ee("session_update",i),{error:n.error})}),R(this,"onSessionExtendRequest",async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,_e(Ur)),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}}),R(this,"onSessionExtendResponse",(r,n)=>{const{id:i}=n,s=ee("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);xt(n)?this.events.emit(ee("session_extend",i),{}):lt(n)&&this.events.emit(ee("session_extend",i),{error:n.error})}),R(this,"onSessionPingRequest",async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}}),R(this,"onSessionPingResponse",(r,n)=>{const{id:i}=n,s=ee("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);xt(n)?this.events.emit(ee("session_ping",i),{}):lt(n)&&this.events.emit(ee("session_ping",i),{error:n.error})},500)}),R(this,"onSessionDeleteRequest",async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),Promise.all([new Promise(s=>{this.client.core.relayer.once(De.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:re("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),R(this,"onSessionRequest",async r=>{var n,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=r,{id:h,params:f}=a;try{await this.isValidRequest(de({topic:o},f));const p=this.client.session.get(o),d=await this.getVerifyContext({attestationId:c,hash:Ct(JSON.stringify(er("wc_sessionRequest",f,h))),encryptedId:u,metadata:p.peer.metadata,transportType:l}),y={id:h,topic:o,params:f,verifyContext:d};await this.setPendingSessionRequest(y),l===me.link_mode&&(n=p.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((i=p.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(p){await this.sendError({id:h,topic:o,error:p}),this.client.logger.error(p)}}),R(this,"onSessionRequestResponse",(r,n)=>{const{id:i}=n,s=ee("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);xt(n)?this.events.emit(ee("session_request",i),{result:n.result}):lt(n)&&this.events.emit(ee("session_request",i),{error:n.error})}),R(this,"onSessionEventRequest",async(r,n)=>{const{id:i,params:s}=n;try{const o=`${r}_session_event_${s.event.name}`,a=Rn.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(de({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),Rn.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"onSessionAuthenticateResponse",(r,n)=>{const{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),xt(n)?this.events.emit(ee("session_request",i),{result:n.result}):lt(n)&&this.events.emit(ee("session_request",i),{error:n.error})}),R(this,"onSessionAuthenticateRequest",async r=>{var n;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:u,authPayload:l,expiryTimestamp:h}=s.params,f=await this.getVerifyContext({attestationId:o,hash:Ct(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),p={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:f,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:p,pairingTopic:i,transportType:c}),c===me.link_mode&&(n=u.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:f})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(s.params.requester.metadata,c),p={type:Vt,receiverPublicKey:l,senderPublicKey:h};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:p,rpcOpts:Ie.wc_sessionAuthenticate.autoReject,appLink:f})}}),R(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),R(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Pt.idle,this.processSessionRequestQueue()},T.toMiliseconds(this.requestQueueDelay))}),R(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:n})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{const o=s.request.id,a=ee("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(ee("session_request",s.request.id),{error:n})})}),R(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Pt.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Pt.active,this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),R(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),R(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest({topic:r.topic,payload:er("wc_sessionPropose",ze(de({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id)})}),R(this,"isValidConnect",async r=>{if(!Ye(r)){const{message:u}=N("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=r;if(ke(n)||await this.isValidPairingTopic(n),!bO(c)){const{message:u}=N("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!ke(i)&&nr(i)!==0){const u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(i,"requiredNamespaces")}if(!ke(s)&&nr(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),ke(o)||this.validateSessionProps(o,"sessionProperties"),!ke(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),R(this,"validateNamespaces",(r,n)=>{const i=vO(r,"connect()",n);if(i)throw new Error(i.message)}),R(this,"isValidApprove",async r=>{if(!Ye(r))throw new Error(N("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);const c=this.client.proposal.get(n),u=co(i,"approve()");if(u)throw new Error(u.message);const l=Zu(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!Ee(s,!0)){const{message:h}=N("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(ke(o)||this.validateSessionProps(o,"sessionProperties"),!ke(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(i));if(!Object.keys(a).every(f=>h.has(f)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),R(this,"isValidReject",async r=>{if(!Ye(r)){const{message:s}=N("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!_O(i)){const{message:s}=N("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),R(this,"isValidSessionSettleRequest",r=>{if(!Ye(r)){const{message:u}=N("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!Ud(n)){const{message:u}=N("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=dO(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=co(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Qt(o)){const{message:u}=N("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),R(this,"isValidUpdate",async r=>{if(!Ye(r)){const{message:c}=N("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:n,namespaces:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const s=this.client.session.get(n),o=co(i,"update()");if(o)throw new Error(o.message);const a=Zu(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),R(this,"isValidExtend",async r=>{if(!Ye(r)){const{message:i}=N("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),R(this,"isValidRequest",async r=>{if(!Ye(r)){const{message:c}=N("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:n,request:i,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!Ju(a,s)){const{message:c}=N("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!$O(i)){const{message:c}=N("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!PO(a,s,i.method)){const{message:c}=N("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!AO(o,mo)){const{message:c}=N("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${mo.min} and ${mo.max}`);throw new Error(c)}}),R(this,"isValidRespond",async r=>{var n;if(!Ye(r)){const{message:o}=N("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:i,response:s}=r;try{await this.isValidSessionTopic(i)}catch(o){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),o}if(!OO(s)){const{message:o}=N("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),R(this,"isValidPing",async r=>{if(!Ye(r)){const{message:i}=N("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),R(this,"isValidEmit",async r=>{if(!Ye(r)){const{message:a}=N("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!Ju(o,s)){const{message:a}=N("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!IO(i)){const{message:a}=N("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!SO(o,s,i.name)){const{message:a}=N("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),R(this,"isValidDisconnect",async r=>{if(!Ye(r)){const{message:i}=N("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),R(this,"isValidAuthenticate",r=>{const{chains:n,uri:i,domain:s,nonce:o}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!Ee(i,!1))throw new Error("uri is required parameter");if(!Ee(s,!1))throw new Error("domain is required parameter");if(!Ee(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>an(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=an(n[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 r=>{const{attestationId:n,hash:i,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||Hn,validation:"UNKNOWN",origin:o.url||""}};try{if(a===me.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:n,hash:i,encryptedId:s,verifyUrl:o.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),R(this,"validateSessionProps",(r,n)=>{Object.values(r).forEach((i,s)=>{if(i==null){const{message:o}=N("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${i} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),R(this,"getPendingAuthRequest",r=>{const n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),R(this,"addToRecentlyDeleted",(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}}),R(this,"checkRecentlyDeleted",r=>{const n=this.recentlyDeletedMap.get(r);if(n){const{message:i}=N("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}),R(this,"isLinkModeEnabled",(r,n)=>{var i,s,o,a,c,u,l,h,f;return!r||n!==me.link_mode?!1:((s=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((l=r?.redirect)==null?void 0:l.universal)!==void 0&&((h=r?.redirect)==null?void 0:h.universal)!==""&&((f=r?.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(H==null?void 0:H.Linking)<"u"}),R(this,"getAppLinkIfEnabled",(r,n)=>{var i;return this.isLinkModeEnabled(r,n)?(i=r?.redirect)==null?void 0:i.universal:void 0}),R(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const n=fu(r,"topic")||"",i=decodeURIComponent(fu(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:me.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:i,sessionExists:s})}),R(this,"registerLinkModeListeners",async()=>{var r;if(xa()||ir()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const n=H==null?void 0:H.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await n.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),R(this,"shouldSetTVF",(r,n)=>{if(!n||r!=="wc_sessionRequest")return!1;const{request:i}=n;return Object.keys(Ml).includes(i.method)}),R(this,"getTVFParams",(r,n,i)=>{var s,o;try{const a=n.request.method,c=this.extractTxHashesFromResult(a,i);return ze(de({correlationId:r,rpcMethods:[a],chainId:n.chainId},this.isValidContractData(n.request.params)&&{contractAddresses:[(o=(s=n.request.params)==null?void 0:s[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),R(this,"isValidContractData",r=>{var n;if(!r)return!1;try{const i=r?.data||((n=r?.[0])==null?void 0:n.data);if(!i.startsWith("0x"))return!1;const s=i.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),R(this,"extractTxHashesFromResult",(r,n)=>{try{const i=Ml[r];if(typeof n=="string")return[n];const s=n[i.key];if(Et(s))return r==="solana_signAllTransactions"?s.map(o=>J1(o)):s;if(typeof s=="string")return[s]}catch(i){this.client.logger.warn("Error extracting tx hashes from result",i)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[n,i]of Object.entries(r))for(const s of i)try{await this.onProviderMessageEvent({topic:n,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${s}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(De.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:n,attestation:i,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Hi)?this.client.auth.authKeys.get(Hi):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:o,encoding:s===me.link_mode?Xt:bt});Ia(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:i,transportType:s,encryptedId:Ct(n)})):ms(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s}),await this.client.core.relayer.messages.ack(r,n)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(ut.expired,async e=>{const{topic:r,id:n}=id(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,N("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,N("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(dr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(dr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Ee(e,!1)){const{message:r}=N("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=N("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(Qt(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=N("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!Ee(e,!1)){const{message:r}=N("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=N("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(Qt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=N("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=N("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}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(Ee(e,!1)){const{message:r}=N("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=N("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!EO(e)){const{message:r}=N("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=N("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(Qt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=N("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class GD extends Dr{constructor(e,r){super(e,r,LD,Ua),this.core=e,this.logger=r}}let YD=class extends Dr{constructor(e,r){super(e,r,RD,Ua),this.core=e,this.logger=r}};class JD extends Dr{constructor(e,r){super(e,r,ND,Ua,n=>n.id),this.core=e,this.logger=r}}class ZD extends Dr{constructor(e,r){super(e,r,UD,Cs,()=>Hi),this.core=e,this.logger=r}}class QD extends Dr{constructor(e,r){super(e,r,FD,Cs),this.core=e,this.logger=r}}class XD extends Dr{constructor(e,r){super(e,r,kD,Cs,n=>n.id),this.core=e,this.logger=r}}var ex=Object.defineProperty,tx=(t,e,r)=>e in t?ex(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wo=(t,e,r)=>tx(t,typeof e!="symbol"?e+"":e,r);class rx{constructor(e,r){this.core=e,this.logger=r,wo(this,"authKeys"),wo(this,"pairingTopics"),wo(this,"requests"),this.authKeys=new ZD(this.core,this.logger),this.pairingTopics=new QD(this.core,this.logger),this.requests=new XD(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var nx=Object.defineProperty,ix=(t,e,r)=>e in t?nx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,G=(t,e,r)=>ix(t,typeof e!="symbol"?e+"":e,r);let sx=class Cp extends UI{constructor(e){super(e),G(this,"protocol",Dp),G(this,"version",xp),G(this,"name",yo.name),G(this,"metadata"),G(this,"core"),G(this,"logger"),G(this,"events",new Sp.EventEmitter),G(this,"engine"),G(this,"session"),G(this,"proposal"),G(this,"pendingRequest"),G(this,"auth"),G(this,"signConfig"),G(this,"on",(n,i)=>this.events.on(n,i)),G(this,"once",(n,i)=>this.events.once(n,i)),G(this,"off",(n,i)=>this.events.off(n,i)),G(this,"removeListener",(n,i)=>this.events.removeListener(n,i)),G(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),G(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"update",async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"request",async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"find",n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),G(this,"authenticate",async(n,i)=>{try{return await this.engine.authenticate(n,i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),G(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||yo.name,this.metadata=u1(e?.metadata),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:ni(us({level:e?.logger||yo.logger}));this.core=e?.core||new OD(e),this.logger=Ke(r,this.name),this.session=new YD(this.core,this.logger),this.proposal=new GD(this.core,this.logger),this.pendingRequest=new JD(this.core,this.logger),this.engine=new WD(this),this.auth=new rx(this.core,this.logger)}static async init(e){const r=new Cp(e);return await r.initialize(),r}get context(){return Qe(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()},T.toMiliseconds(T.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};var Fa={exports:{}},hn=typeof Reflect=="object"?Reflect:null,Ul=hn&&typeof hn.apply=="function"?hn.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Ki;hn&&typeof hn.ownKeys=="function"?Ki=hn.ownKeys:Object.getOwnPropertySymbols?Ki=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Ki=function(e){return Object.getOwnPropertyNames(e)};function ox(t){console&&console.warn&&console.warn(t)}var Lp=Number.isNaN||function(e){return e!==e};function le(){le.init.call(this)}Fa.exports=le;Fa.exports.once=lx;le.EventEmitter=le;le.prototype._events=void 0;le.prototype._eventsCount=0;le.prototype._maxListeners=void 0;var Fl=10;function Ls(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(le,"defaultMaxListeners",{enumerable:!0,get:function(){return Fl},set:function(t){if(typeof t!="number"||t<0||Lp(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Fl=t}});le.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};le.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Lp(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Rp(t){return t._maxListeners===void 0?le.defaultMaxListeners:t._maxListeners}le.prototype.getMaxListeners=function(){return Rp(this)};le.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")Ul(c,this,r);else for(var u=c.length,l=Bp(c,u),n=0;n<u;++n)Ul(l[n],this,r);return!0};function Tp(t,e,r,n){var i,s,o;if(Ls(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=Rp(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,ox(a)}return t}le.prototype.addListener=function(e,r){return Tp(this,e,r,!1)};le.prototype.on=le.prototype.addListener;le.prototype.prependListener=function(e,r){return Tp(this,e,r,!0)};function ax(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Np(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=ax.bind(n);return i.listener=r,n.wrapFn=i,i}le.prototype.once=function(e,r){return Ls(r),this.on(e,Np(this,e,r)),this};le.prototype.prependOnceListener=function(e,r){return Ls(r),this.prependListener(e,Np(this,e,r)),this};le.prototype.removeListener=function(e,r){var n,i,s,o,a;if(Ls(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():cx(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};le.prototype.off=le.prototype.removeListener;le.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function jp(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?ux(i):Bp(i,i.length)}le.prototype.listeners=function(e){return jp(this,e,!0)};le.prototype.rawListeners=function(e){return jp(this,e,!1)};le.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Mp.call(t,e)};le.prototype.listenerCount=Mp;function Mp(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}le.prototype.eventNames=function(){return this._eventsCount>0?Ki(this._events):[]};function Bp(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function cx(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function ux(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function lx(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Up(t,e,s,{once:!0}),e!=="error"&&hx(t,i,{once:!0})})}function hx(t,e,r){typeof t.on=="function"&&Up(t,"error",e,r)}function Up(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var fx=Fa.exports,aa={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof At<"u"&&At,n=function(){function s(){this.fetch=!1,this.DOMException=r.DOMException}return s.prototype=r,new s}();(function(s){(function(o){var a=typeof s<"u"&&s||typeof self<"u"&&self||typeof At<"u"&&At||{},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 u(g){return g&&DataView.prototype.isPrototypeOf(g)}if(c.arrayBuffer)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],h=ArrayBuffer.isView||function(g){return g&&l.indexOf(Object.prototype.toString.call(g))>-1};function f(g){if(typeof g!="string"&&(g=String(g)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(g)||g==="")throw new TypeError('Invalid character in header field name: "'+g+'"');return g.toLowerCase()}function p(g){return typeof g!="string"&&(g=String(g)),g}function d(g){var m={next:function(){var _=g.shift();return{done:_===void 0,value:_}}};return c.iterable&&(m[Symbol.iterator]=function(){return m}),m}function y(g){this.map={},g instanceof y?g.forEach(function(m,_){this.append(_,m)},this):Array.isArray(g)?g.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):g&&Object.getOwnPropertyNames(g).forEach(function(m){this.append(m,g[m])},this)}y.prototype.append=function(g,m){g=f(g),m=p(m);var _=this.map[g];this.map[g]=_?_+", "+m:m},y.prototype.delete=function(g){delete this.map[f(g)]},y.prototype.get=function(g){return g=f(g),this.has(g)?this.map[g]:null},y.prototype.has=function(g){return this.map.hasOwnProperty(f(g))},y.prototype.set=function(g,m){this.map[f(g)]=p(m)},y.prototype.forEach=function(g,m){for(var _ in this.map)this.map.hasOwnProperty(_)&&g.call(m,this.map[_],_,this)},y.prototype.keys=function(){var g=[];return this.forEach(function(m,_){g.push(_)}),d(g)},y.prototype.values=function(){var g=[];return this.forEach(function(m){g.push(m)}),d(g)},y.prototype.entries=function(){var g=[];return this.forEach(function(m,_){g.push([_,m])}),d(g)},c.iterable&&(y.prototype[Symbol.iterator]=y.prototype.entries);function w(g){if(!g._noBody){if(g.bodyUsed)return Promise.reject(new TypeError("Already read"));g.bodyUsed=!0}}function b(g){return new Promise(function(m,_){g.onload=function(){m(g.result)},g.onerror=function(){_(g.error)}})}function v(g){var m=new FileReader,_=b(m);return m.readAsArrayBuffer(g),_}function E(g){var m=new FileReader,_=b(m),P=/charset=([A-Za-z0-9_-]+)/.exec(g.type),$=P?P[1]:"utf-8";return m.readAsText(g,$),_}function O(g){for(var m=new Uint8Array(g),_=new Array(m.length),P=0;P<m.length;P++)_[P]=String.fromCharCode(m[P]);return _.join("")}function x(g){if(g.slice)return g.slice(0);var m=new Uint8Array(g.byteLength);return m.set(new Uint8Array(g)),m.buffer}function D(){return this.bodyUsed=!1,this._initBody=function(g){this.bodyUsed=this.bodyUsed,this._bodyInit=g,g?typeof g=="string"?this._bodyText=g:c.blob&&Blob.prototype.isPrototypeOf(g)?this._bodyBlob=g:c.formData&&FormData.prototype.isPrototypeOf(g)?this._bodyFormData=g:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(g)?this._bodyText=g.toString():c.arrayBuffer&&c.blob&&u(g)?(this._bodyArrayBuffer=x(g.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(g)||h(g))?this._bodyArrayBuffer=x(g):this._bodyText=g=Object.prototype.toString.call(g):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof g=="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(g)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var g=w(this);if(g)return g;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 g=w(this);return g||(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(v);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var g=w(this);if(g)return g;if(this._bodyBlob)return E(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(O(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(k)}),this.json=function(){return this.text().then(JSON.parse)},this}var S=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function C(g){var m=g.toUpperCase();return S.indexOf(m)>-1?m:g}function I(g,m){if(!(this instanceof I))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');m=m||{};var _=m.body;if(g instanceof I){if(g.bodyUsed)throw new TypeError("Already read");this.url=g.url,this.credentials=g.credentials,m.headers||(this.headers=new y(g.headers)),this.method=g.method,this.mode=g.mode,this.signal=g.signal,!_&&g._bodyInit!=null&&(_=g._bodyInit,g.bodyUsed=!0)}else this.url=String(g);if(this.credentials=m.credentials||this.credentials||"same-origin",(m.headers||!this.headers)&&(this.headers=new y(m.headers)),this.method=C(m.method||this.method||"GET"),this.mode=m.mode||this.mode||null,this.signal=m.signal||this.signal||function(){if("AbortController"in a){var A=new AbortController;return A.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&_)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(_),(this.method==="GET"||this.method==="HEAD")&&(m.cache==="no-store"||m.cache==="no-cache")){var P=/([?&])_=[^&]*/;if(P.test(this.url))this.url=this.url.replace(P,"$1_="+new Date().getTime());else{var $=/\?/;this.url+=($.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}I.prototype.clone=function(){return new I(this,{body:this._bodyInit})};function k(g){var m=new FormData;return g.trim().split("&").forEach(function(_){if(_){var P=_.split("="),$=P.shift().replace(/\+/g," "),A=P.join("=").replace(/\+/g," ");m.append(decodeURIComponent($),decodeURIComponent(A))}}),m}function M(g){var m=new y,_=g.replace(/\r?\n[\t ]+/g," ");return _.split("\r").map(function(P){return P.indexOf(`
39
+ `)===0?P.substr(1,P.length):P}).forEach(function(P){var $=P.split(":"),A=$.shift().trim();if(A){var B=$.join(":").trim();try{m.append(A,B)}catch(F){console.warn("Response "+F.message)}}}),m}D.call(I.prototype);function j(g,m){if(!(this instanceof j))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 y(m.headers),this.url=m.url||"",this._initBody(g)}D.call(j.prototype),j.prototype.clone=function(){return new j(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},j.error=function(){var g=new j(null,{status:200,statusText:""});return g.ok=!1,g.status=0,g.type="error",g};var q=[301,302,303,307,308];j.redirect=function(g,m){if(q.indexOf(m)===-1)throw new RangeError("Invalid status code");return new j(null,{status:m,headers:{location:g}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(m,_){this.message=m,this.name=_;var P=Error(m);this.stack=P.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function L(g,m){return new Promise(function(_,P){var $=new I(g,m);if($.signal&&$.signal.aborted)return P(new o.DOMException("Aborted","AbortError"));var A=new XMLHttpRequest;function B(){A.abort()}A.onload=function(){var U={statusText:A.statusText,headers:M(A.getAllResponseHeaders()||"")};$.url.indexOf("file://")===0&&(A.status<200||A.status>599)?U.status=200:U.status=A.status,U.url="responseURL"in A?A.responseURL:U.headers.get("X-Request-URL");var K="response"in A?A.response:A.responseText;setTimeout(function(){_(new j(K,U))},0)},A.onerror=function(){setTimeout(function(){P(new TypeError("Network request failed"))},0)},A.ontimeout=function(){setTimeout(function(){P(new TypeError("Network request timed out"))},0)},A.onabort=function(){setTimeout(function(){P(new o.DOMException("Aborted","AbortError"))},0)};function F(U){try{return U===""&&a.location.href?a.location.href:U}catch{return U}}if(A.open($.method,F($.url),!0),$.credentials==="include"?A.withCredentials=!0:$.credentials==="omit"&&(A.withCredentials=!1),"responseType"in A&&(c.blob?A.responseType="blob":c.arrayBuffer&&(A.responseType="arraybuffer")),m&&typeof m.headers=="object"&&!(m.headers instanceof y||a.Headers&&m.headers instanceof a.Headers)){var z=[];Object.getOwnPropertyNames(m.headers).forEach(function(U){z.push(f(U)),A.setRequestHeader(U,p(m.headers[U]))}),$.headers.forEach(function(U,K){z.indexOf(K)===-1&&A.setRequestHeader(K,U)})}else $.headers.forEach(function(U,K){A.setRequestHeader(K,U)});$.signal&&($.signal.addEventListener("abort",B),A.onreadystatechange=function(){A.readyState===4&&$.signal.removeEventListener("abort",B)}),A.send(typeof $._bodyInit>"u"?null:$._bodyInit)})}return L.polyfill=!0,a.fetch||(a.fetch=L,a.Headers=y,a.Request=I,a.Response=j),o.Headers=y,o.Request=I,o.Response=j,o.fetch=L,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=r.fetch?r:n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(aa,aa.exports);var dx=aa.exports;const kl=ri(dx);var px=Object.defineProperty,gx=Object.defineProperties,yx=Object.getOwnPropertyDescriptors,ql=Object.getOwnPropertySymbols,mx=Object.prototype.hasOwnProperty,wx=Object.prototype.propertyIsEnumerable,zl=(t,e,r)=>e in t?px(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hl=(t,e)=>{for(var r in e||(e={}))mx.call(e,r)&&zl(t,r,e[r]);if(ql)for(var r of ql(e))wx.call(e,r)&&zl(t,r,e[r]);return t},Kl=(t,e)=>gx(t,yx(e));const vx={Accept:"application/json","Content-Type":"application/json"},bx="POST",Vl={headers:vx,method:bx},Wl=10;let _t=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new fx.EventEmitter,this.isAvailable=!1,this.registering=!1,!zc(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}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 r=Wt(e),n=await(await kl(this.url,Kl(Hl({},Vl),{body:r}))).json();this.onPayload({data:n})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!zc(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));n()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=Wt({id:1,jsonrpc:"2.0",method:"test",params:[]});await kl(e,Kl(Hl({},Vl),{body:r}))}this.onOpen()}catch(r){const n=this.parseError(r);throw this.events.emit("register_error",n),this.onClose(),n}}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 r=typeof e.data=="string"?wr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=ys(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return wf(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Wl&&this.events.setMaxListeners(Wl)}};var ka={exports:{}},fn=typeof Reflect=="object"?Reflect:null,Gl=fn&&typeof fn.apply=="function"?fn.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Vi;fn&&typeof fn.ownKeys=="function"?Vi=fn.ownKeys:Object.getOwnPropertySymbols?Vi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Vi=function(e){return Object.getOwnPropertyNames(e)};function Ex(t){console&&console.warn&&console.warn(t)}var Fp=Number.isNaN||function(e){return e!==e};function he(){he.init.call(this)}ka.exports=he;ka.exports.once=Ix;he.EventEmitter=he;he.prototype._events=void 0;he.prototype._eventsCount=0;he.prototype._maxListeners=void 0;var Yl=10;function Rs(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(he,"defaultMaxListeners",{enumerable:!0,get:function(){return Yl},set:function(t){if(typeof t!="number"||t<0||Fp(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Yl=t}});he.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};he.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Fp(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function kp(t){return t._maxListeners===void 0?he.defaultMaxListeners:t._maxListeners}he.prototype.getMaxListeners=function(){return kp(this)};he.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")Gl(c,this,r);else for(var u=c.length,l=Vp(c,u),n=0;n<u;++n)Gl(l[n],this,r);return!0};function qp(t,e,r,n){var i,s,o;if(Rs(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=kp(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,Ex(a)}return t}he.prototype.addListener=function(e,r){return qp(this,e,r,!1)};he.prototype.on=he.prototype.addListener;he.prototype.prependListener=function(e,r){return qp(this,e,r,!0)};function _x(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function zp(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=_x.bind(n);return i.listener=r,n.wrapFn=i,i}he.prototype.once=function(e,r){return Rs(r),this.on(e,zp(this,e,r)),this};he.prototype.prependOnceListener=function(e,r){return Rs(r),this.prependListener(e,zp(this,e,r)),this};he.prototype.removeListener=function(e,r){var n,i,s,o,a;if(Rs(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():$x(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};he.prototype.off=he.prototype.removeListener;he.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function Hp(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?Ox(i):Vp(i,i.length)}he.prototype.listeners=function(e){return Hp(this,e,!0)};he.prototype.rawListeners=function(e){return Hp(this,e,!1)};he.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Kp.call(t,e)};he.prototype.listenerCount=Kp;function Kp(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}he.prototype.eventNames=function(){return this._eventsCount>0?Vi(this._events):[]};function Vp(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function $x(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function Ox(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function Ix(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Wp(t,e,s,{once:!0}),e!=="error"&&Px(t,i,{once:!0})})}function Px(t,e,r){typeof t.on=="function"&&Wp(t,"error",e,r)}function Wp(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var Sx=ka.exports;const Dx=ri(Sx),Jl="error",xx="wss://relay.walletconnect.org",Ax="wc",Cx="universal_provider",Pi=`${Ax}@2:${Cx}:`,Gp="https://rpc.walletconnect.org/v1/",Qr="generic",Lx=`${Gp}bundler`,pt={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function Rx(){}function qa(t){return t==null||typeof t!="object"&&typeof t!="function"}function za(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function Tx(t){if(qa(t))return t;if(Array.isArray(t)||za(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),r=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new r(t);if(t instanceof RegExp){const n=new r(t);return n.lastIndex=t.lastIndex,n}if(t instanceof DataView)return new r(t.buffer.slice(0));if(t instanceof Error){const n=new r(t.message);return n.stack=t.stack,n.name=t.name,n.cause=t.cause,n}if(typeof File<"u"&&t instanceof File)return new r([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const n=Object.create(e);return Object.assign(n,t)}return t}function Zl(t){return typeof t=="object"&&t!==null}function Yp(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Jp(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const Nx="[object RegExp]",Zp="[object String]",Qp="[object Number]",Xp="[object Boolean]",eg="[object Arguments]",jx="[object Symbol]",Mx="[object Date]",Bx="[object Map]",Ux="[object Set]",Fx="[object Array]",kx="[object ArrayBuffer]",qx="[object Object]",zx="[object DataView]",Hx="[object Uint8Array]",Kx="[object Uint8ClampedArray]",Vx="[object Uint16Array]",Wx="[object Uint32Array]",Gx="[object Int8Array]",Yx="[object Int16Array]",Jx="[object Int32Array]",Zx="[object Float32Array]",Qx="[object Float64Array]";function Xx(t,e){return tn(t,void 0,t,new Map,e)}function tn(t,e,r,n=new Map,i=void 0){const s=i?.(t,e,r,n);if(s!=null)return s;if(qa(t))return t;if(n.has(t))return n.get(t);if(Array.isArray(t)){const o=new Array(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=tn(t[a],a,r,n,i);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;n.set(t,o);for(const[a,c]of t)o.set(a,tn(c,a,r,n,i));return o}if(t instanceof Set){const o=new Set;n.set(t,o);for(const a of t)o.add(tn(a,void 0,r,n,i));return o}if(typeof Ce<"u"&&Ce.isBuffer(t))return t.subarray();if(za(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=tn(t[a],a,r,n,i);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return n.set(t,o),pr(o,t,r,n,i),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return n.set(t,o),pr(o,t,r,n,i),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return n.set(t,o),pr(o,t,r,n,i),o}if(t instanceof Error){const o=new t.constructor;return n.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,pr(o,t,r,n,i),o}if(typeof t=="object"&&eA(t)){const o=Object.create(Object.getPrototypeOf(t));return n.set(t,o),pr(o,t,r,n,i),o}return t}function pr(t,e,r=t,n,i){const s=[...Object.keys(e),...Yp(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=tn(e[a],a,r,n,i))}}function eA(t){switch(Jp(t)){case eg:case Fx:case kx:case zx:case Xp:case Mx:case Zx:case Qx:case Gx:case Yx:case Jx:case Bx:case Qp:case qx:case Nx:case Ux:case Zp:case jx:case Hx:case Kx:case Vx:case Wx:return!0;default:return!1}}function tA(t,e){return Xx(t,(r,n,i,s)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case Qp:case Zp:case Xp:{const o=new t.constructor(t?.valueOf());return pr(o,t),o}case eg:{const o={};return pr(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function Ql(t){return tA(t)}function Xl(t){return t!==null&&typeof t=="object"&&Jp(t)==="[object Arguments]"}function rA(t){return za(t)}function nA(t){if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const r=t[Symbol.toStringTag];return r==null||!Object.getOwnPropertyDescriptor(t,Symbol.toStringTag)?.writable?!1:t.toString()===`[object ${r}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function iA(t,...e){const r=e.slice(0,-1),n=e[e.length-1];let i=t;for(let s=0;s<r.length;s++){const o=r[s];i=ca(i,o,n,new Map)}return i}function ca(t,e,r,n){if(qa(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(n.has(e))return Tx(n.get(e));if(n.set(e,t),Array.isArray(e)){e=e.slice();for(let s=0;s<e.length;s++)e[s]=e[s]??void 0}const i=[...Object.keys(e),...Yp(e)];for(let s=0;s<i.length;s++){const o=i[s];let a=e[o],c=t[o];if(Xl(a)&&(a={...a}),Xl(c)&&(c={...c}),typeof Ce<"u"&&Ce.isBuffer(a)&&(a=Ql(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],h=Reflect.ownKeys(c);for(let f=0;f<h.length;f++){const p=h[f];l[p]=c[p]}c=l}else c=[];const u=r(c,a,o,t,e,n);u!=null?t[o]=u:Array.isArray(a)||Zl(c)&&Zl(a)?t[o]=ca(c,a,r,n):c==null&&nA(a)?t[o]=ca({},a,r,n):c==null&&rA(a)?t[o]=Ql(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function sA(t,...e){return iA(t,...e,Rx)}var oA=Object.defineProperty,aA=Object.defineProperties,cA=Object.getOwnPropertyDescriptors,eh=Object.getOwnPropertySymbols,uA=Object.prototype.hasOwnProperty,lA=Object.prototype.propertyIsEnumerable,th=(t,e,r)=>e in t?oA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Si=(t,e)=>{for(var r in e||(e={}))uA.call(e,r)&&th(t,r,e[r]);if(eh)for(var r of eh(e))lA.call(e,r)&&th(t,r,e[r]);return t},hA=(t,e)=>aA(t,cA(e));function st(t,e,r){var n;const i=an(t);return((n=e.rpcMap)==null?void 0:n[i.reference])||`${Gp}?chainId=${i.namespace}:${i.reference}&projectId=${r}`}function xr(t){return t.includes(":")?t.split(":")[1]:t}function tg(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function fA(t,e){const r=Object.keys(e.namespaces).filter(i=>i.includes(t));if(!r.length)return[];const n=[];return r.forEach(i=>{const s=e.namespaces[i].accounts;n.push(...s)}),n}function Di(t={},e={}){const r=rh(t),n=rh(e);return sA(r,n)}function rh(t){var e,r,n,i,s;const o={};if(!nr(t))return o;for(const[a,c]of Object.entries(t)){const u=Ps(a)?[a]:c.chains,l=c.methods||[],h=c.events||[],f=c.rpcMap||{},p=en(a);o[p]=hA(Si(Si({},o[p]),c),{chains:Rt(u,(e=o[p])==null?void 0:e.chains),methods:Rt(l,(r=o[p])==null?void 0:r.methods),events:Rt(h,(n=o[p])==null?void 0:n.events)}),(nr(f)||nr(((i=o[p])==null?void 0:i.rpcMap)||{}))&&(o[p].rpcMap=Si(Si({},f),(s=o[p])==null?void 0:s.rpcMap))}return o}function nh(t){return t.includes(":")?t.split(":")[2]:t}function ih(t){const e={};for(const[r,n]of Object.entries(t)){const i=n.methods||[],s=n.events||[],o=n.accounts||[],a=Ps(r)?[r]:n.chains?n.chains:tg(n.accounts);e[r]={chains:a,methods:i,events:s,accounts:o}}return e}function vo(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}const rg={},X=t=>rg[t],bo=(t,e)=>{rg[t]=e};var dA=Object.defineProperty,pA=(t,e,r)=>e in t?dA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fr=(t,e,r)=>pA(t,typeof e!="symbol"?e+"":e,r);class gA{constructor(e){Fr(this,"name","polkadot"),Fr(this,"client"),Fr(this,"httpProviders"),Fr(this,"events"),Fr(this,"namespace"),Fr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(pt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=xr(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dt(new _t(n,X("disableProviderPing")))}}var yA=Object.defineProperty,mA=Object.defineProperties,wA=Object.getOwnPropertyDescriptors,sh=Object.getOwnPropertySymbols,vA=Object.prototype.hasOwnProperty,bA=Object.prototype.propertyIsEnumerable,ua=(t,e,r)=>e in t?yA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,oh=(t,e)=>{for(var r in e||(e={}))vA.call(e,r)&&ua(t,r,e[r]);if(sh)for(var r of sh(e))bA.call(e,r)&&ua(t,r,e[r]);return t},ah=(t,e)=>mA(t,wA(e)),kr=(t,e,r)=>ua(t,typeof e!="symbol"?e+"":e,r);class EA{constructor(e){kr(this,"name","eip155"),kr(this,"client"),kr(this,"chainId"),kr(this,"namespace"),kr(this,"httpProviders"),kr(this,"events"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r),this.chainId=parseInt(e),this.events.emit(pt.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,r){const n=r||st(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dt(new _t(n,X("disableProviderPing")))}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=parseInt(xr(r));e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}async handleSwitchChain(e){var r,n;let i=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";i=i.startsWith("0x")?i:`0x${i}`;const s=parseInt(i,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:i}]},chainId:(n=this.namespace.chains)==null?void 0:n[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. 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 r,n,i,s,o;const a=(n=(r=e.request)==null?void 0:r.params)==null?void 0:n[0],c=((s=(i=e.request)==null?void 0:i.params)==null?void 0:s[1])||[],u=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),h=((o=l?.sessionProperties)==null?void 0:o.capabilities)||{};if(h!=null&&h[u])return h?.[u];const f=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:ah(oh({},l.sessionProperties||{}),{capabilities:ah(oh({},h||{}),{[u]:f})})})}catch(p){console.warn("Failed to update session with capabilities",p)}return f}async getCallStatus(e){var r,n;const i=this.client.session.get(e.topic),s=(r=i.sessionProperties)==null?void 0:r.bundler_name;if(s){const a=this.getBundlerUrl(e.chainId,s);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(n=i.sessionProperties)==null?void 0:n.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,r){var n;const i=new URL(e),s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(er("eth_getUserOperationReceipt",[(n=r.request.params)==null?void 0:n[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,r){return`${Lx}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}}var _A=Object.defineProperty,$A=(t,e,r)=>e in t?_A(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qr=(t,e,r)=>$A(t,typeof e!="symbol"?e+"":e,r);class OA{constructor(e){qr(this,"name","solana"),qr(this,"client"),qr(this,"httpProviders"),qr(this,"events"),qr(this,"namespace"),qr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(pt.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(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=xr(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dt(new _t(n,X("disableProviderPing")))}}var IA=Object.defineProperty,PA=(t,e,r)=>e in t?IA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zr=(t,e,r)=>PA(t,typeof e!="symbol"?e+"":e,r);class SA{constructor(e){zr(this,"name","cosmos"),zr(this,"client"),zr(this,"httpProviders"),zr(this,"events"),zr(this,"namespace"),zr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(pt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=xr(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dt(new _t(n,X("disableProviderPing")))}}var DA=Object.defineProperty,xA=(t,e,r)=>e in t?DA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hr=(t,e,r)=>xA(t,typeof e!="symbol"?e+"":e,r);class AA{constructor(e){Hr(this,"name","algorand"),Hr(this,"client"),Hr(this,"httpProviders"),Hr(this,"events"),Hr(this,"namespace"),Hr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){if(!this.httpProviders[e]){const n=r||st(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(pt.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(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new dt(new _t(n,X("disableProviderPing")))}}var CA=Object.defineProperty,LA=(t,e,r)=>e in t?CA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Kr=(t,e,r)=>LA(t,typeof e!="symbol"?e+"":e,r);class RA{constructor(e){Kr(this,"name","cip34"),Kr(this,"client"),Kr(this,"httpProviders"),Kr(this,"events"),Kr(this,"namespace"),Kr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(pt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=this.getCardanoRPCUrl(r),i=xr(r);e[i]=this.createHttpProvider(i,n)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||this.getCardanoRPCUrl(e);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dt(new _t(n,X("disableProviderPing")))}}var TA=Object.defineProperty,NA=(t,e,r)=>e in t?TA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Vr=(t,e,r)=>NA(t,typeof e!="symbol"?e+"":e,r);class jA{constructor(e){Vr(this,"name","elrond"),Vr(this,"client"),Vr(this,"httpProviders"),Vr(this,"events"),Vr(this,"namespace"),Vr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(pt.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(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=xr(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dt(new _t(n,X("disableProviderPing")))}}var MA=Object.defineProperty,BA=(t,e,r)=>e in t?MA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wr=(t,e,r)=>BA(t,typeof e!="symbol"?e+"":e,r);class UA{constructor(e){Wr(this,"name","multiversx"),Wr(this,"client"),Wr(this,"httpProviders"),Wr(this,"events"),Wr(this,"namespace"),Wr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(pt.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(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;const i=xr(r);e[i]=this.createHttpProvider(i,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dt(new _t(n,X("disableProviderPing")))}}var FA=Object.defineProperty,kA=(t,e,r)=>e in t?FA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Gr=(t,e,r)=>kA(t,typeof e!="symbol"?e+"":e,r);class qA{constructor(e){Gr(this,"name","near"),Gr(this,"client"),Gr(this,"httpProviders"),Gr(this,"events"),Gr(this,"namespace"),Gr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||st(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(pt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var n;e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace);return typeof n>"u"?void 0:new dt(new _t(n,X("disableProviderPing")))}}var zA=Object.defineProperty,HA=(t,e,r)=>e in t?zA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yr=(t,e,r)=>HA(t,typeof e!="symbol"?e+"":e,r);class KA{constructor(e){Yr(this,"name","tezos"),Yr(this,"client"),Yr(this,"httpProviders"),Yr(this,"events"),Yr(this,"namespace"),Yr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||st(`${this.name}:${e}`,this.namespace);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(pt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{e[r]=this.createHttpProvider(r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace);return typeof n>"u"?void 0:new dt(new _t(n))}}var VA=Object.defineProperty,WA=(t,e,r)=>e in t?VA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Jr=(t,e,r)=>WA(t,typeof e!="symbol"?e+"":e,r);class GA{constructor(e){Jr(this,"name",Qr),Jr(this,"client"),Jr(this,"httpProviders"),Jr(this,"events"),Jr(this,"namespace"),Jr(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(pt.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(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const n={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(i=>{const s=an(i);n[`${s.namespace}:${s.reference}`]=this.createHttpProvider(i)}),n}getHttpProvider(e){const r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||st(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dt(new _t(n,X("disableProviderPing")))}}var YA=Object.defineProperty,JA=Object.defineProperties,ZA=Object.getOwnPropertyDescriptors,ch=Object.getOwnPropertySymbols,QA=Object.prototype.hasOwnProperty,XA=Object.prototype.propertyIsEnumerable,la=(t,e,r)=>e in t?YA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xi=(t,e)=>{for(var r in e||(e={}))QA.call(e,r)&&la(t,r,e[r]);if(ch)for(var r of ch(e))XA.call(e,r)&&la(t,r,e[r]);return t},Eo=(t,e)=>JA(t,ZA(e)),ct=(t,e,r)=>la(t,typeof e!="symbol"?e+"":e,r);let eC=class ng{constructor(e){ct(this,"client"),ct(this,"namespaces"),ct(this,"optionalNamespaces"),ct(this,"sessionProperties"),ct(this,"scopedProperties"),ct(this,"events",new Dx),ct(this,"rpcProviders",{}),ct(this,"session"),ct(this,"providerOpts"),ct(this,"logger"),ct(this,"uri"),ct(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:ni(us({level:e?.logger||Jl})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new ng(e);return await r.initialize(),r}async request(e,r,n){const[i,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(i).request({request:xi({},e),chainId:`${i}:${s}`,topic:this.session.topic,expiry:n})}sendAsync(e,r,n,i){const s=new Date().getTime();this.request(e,n,i).then(o=>r(null,gs(s,o))).catch(o=>r(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:re("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,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:n,response:i}=await this.client.authenticate(e,r);n&&(this.uri=n,this.events.emit("display_uri",n));const s=await i();if(this.session=s.session,this.session){const o=ih(this.session.namespaces);this.namespaces=Di(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){const{uri:r,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});r&&(this.uri=r,this.events.emit("display_uri",r));const i=await n();this.session=i;const s=ih(i.namespaces);return this.namespaces=Di(this.namespaces,s),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[n,i]=this.validateChain(e),s=this.getProvider(n);s.name===Qr?s.setDefaultChain(`${n}:${i}`,r):s.setDefaultChain(i,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(Et(r)){for(const n of r)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.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,r;if(this.client=this.providerOpts.client||await sx.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Jl,relayUrl:this.providerOpts.relayUrl||xx,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(n){throw this.logger.error("Failed to get session",n),new Error(`The provided session: ${(r=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{const n=this.client.session.getAll();this.session=n[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(r=>en(r)))];bo("client",this.client),bo("events",this.events),bo("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const n=fA(r,this.session),i=tg(n),s=Di(this.namespaces,this.optionalNamespaces),o=Eo(xi({},s[r]),{accounts:n,chains:i});switch(r){case"eip155":this.rpcProviders[r]=new EA({namespace:o});break;case"algorand":this.rpcProviders[r]=new AA({namespace:o});break;case"solana":this.rpcProviders[r]=new OA({namespace:o});break;case"cosmos":this.rpcProviders[r]=new SA({namespace:o});break;case"polkadot":this.rpcProviders[r]=new gA({namespace:o});break;case"cip34":this.rpcProviders[r]=new RA({namespace:o});break;case"elrond":this.rpcProviders[r]=new jA({namespace:o});break;case"multiversx":this.rpcProviders[r]=new UA({namespace:o});break;case"near":this.rpcProviders[r]=new qA({namespace:o});break;case"tezos":this.rpcProviders[r]=new KA({namespace:o});break;default:this.rpcProviders[Qr]?this.rpcProviders[Qr].updateNamespace(o):this.rpcProviders[Qr]=new GA({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var r;const{topic:n}=e;n===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:n,topic:i}=e;if(i!==((r=this.session)==null?void 0:r.topic))return;const{event:s}=n;if(s.name==="accountsChanged"){const o=s.data;o&&Et(o)&&this.events.emit("accountsChanged",o.map(nh))}else if(s.name==="chainChanged"){const o=n.chainId,a=n.event.data,c=en(o),u=vo(o)!==vo(a)?`${c}:${vo(a)}`:o;this.onChainChanged(u)}else this.events.emit(s.name,s.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var n,i;if(e!==((n=this.session)==null?void 0:n.topic))return;const{namespaces:s}=r,o=(i=this.client)==null?void 0:i.session.get(e);this.session=Eo(xi({},o),{namespaces:s}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{var r;e.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Eo(xi({},re("USER_DISCONNECTED")),{data:e.topic})))}),this.on(pt.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Qr]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r={},optionalNamespaces:n={},sessionProperties:i,scopedProperties:s}=e;this.optionalNamespaces=Di(r,n),this.sessionProperties=i,this.scopedProperties=s}validateChain(e){const[r,n]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,n];if(r&&!Object.keys(this.namespaces||{}).map(o=>en(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];const i=en(Object.keys(this.namespaces)[0]),s=this.rpcProviders[i].getDefaultChain();return[i,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,r=!1){if(!this.namespaces)return;const[n,i]=this.validateChain(e);if(!i)return;this.updateNamespaceChain(n,i),this.events.emit("chainChanged",i);const s=this.getProvider(n).getDefaultChain();r||this.getProvider(n).setDefaultChain(i),this.emitAccountsChangedOnChainChange({namespace:n,previousChainId:s,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:r,newChainId:n}){var i,s;try{if(r===n)return;const o=(s=(i=this.session)==null?void 0:i.namespaces[e])==null?void 0:s.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${n}:`)).map(nh);if(!Et(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,r){if(!this.namespaces)return;const n=this.namespaces[e]?e:`${e}:${r}`,i={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[n]?this.namespaces[n]&&(this.namespaces[n].defaultChain=r):this.namespaces[n]=i}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,r){var n;const i=((n=this.session)==null?void 0:n.topic)||"";await this.client.core.storage.setItem(`${Pi}/${e}${i}`,r)}async getFromStore(e){var r;const n=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${Pi}/${e}${n}`)}async deleteFromStore(e){var r;const n=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${Pi}/${e}${n}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const r=await this.client.core.storage.getKeys();for(const n of r)n.startsWith(Pi)&&await this.client.core.storage.removeItem(n)}catch(r){this.logger.warn("Failed to cleanup storage",r)}}};const tC=eC,rC="wc",nC="ethereum_provider",iC=`${rC}@2:${nC}:`,sC="https://rpc.walletconnect.org/v1/",ns=["eth_sendTransaction","personal_sign"],ig=["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"],is=["chainChanged","accountsChanged"],sg=["chainChanged","accountsChanged","message","disconnect","connect"],oC=async()=>{const{createAppKit:t}=await dh(()=>import("./core-CIPjJeZT.js").then(e=>e.X),__vite__mapDeps([3,1,2,4]));return t};var aC=Object.defineProperty,cC=Object.defineProperties,uC=Object.getOwnPropertyDescriptors,uh=Object.getOwnPropertySymbols,lC=Object.prototype.hasOwnProperty,hC=Object.prototype.propertyIsEnumerable,ha=(t,e,r)=>e in t?aC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,lr=(t,e)=>{for(var r in e||(e={}))lC.call(e,r)&&ha(t,r,e[r]);if(uh)for(var r of uh(e))hC.call(e,r)&&ha(t,r,e[r]);return t},Bn=(t,e)=>cC(t,uC(e)),et=(t,e,r)=>ha(t,typeof e!="symbol"?e+"":e,r);function ss(t){return Number(t[0].split(":")[1])}function Ai(t){return`0x${t.toString(16)}`}function fC(t){const{chains:e,optionalChains:r,methods:n,optionalMethods:i,events:s,optionalEvents:o,rpcMap:a}=t;if(!Et(e))throw new Error("Invalid chains");const c={chains:e,methods:n||ns,events:s||is,rpcMap:lr({},e.length?{[ss(e)]:a[ss(e)]}:{})},u=s?.filter(p=>!is.includes(p)),l=n?.filter(p=>!ns.includes(p));if(!r&&!o&&!i&&!(u!=null&&u.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const h=u?.length&&l?.length||!r,f={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(i!=null&&i.length?i:ig))],events:[...new Set(c.events.concat(o!=null&&o.length?o:sg))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?f:void 0}}class Ts{constructor(){et(this,"events",new sE.EventEmitter),et(this,"namespace","eip155"),et(this,"accounts",[]),et(this,"signer"),et(this,"chainId",1),et(this,"modal"),et(this,"rpc"),et(this,"STORAGE_KEY",iC),et(this,"on",(e,r)=>(this.events.on(e,r),this)),et(this,"once",(e,r)=>(this.events.once(e,r),this)),et(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),et(this,"off",(e,r)=>(this.events.off(e,r),this)),et(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new Ts;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,n){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),n)}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 r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:n,optional:i}=fC(this.rpc);try{const s=await new Promise(async(a,c)=>{var u,l;this.rpc.showQrModal&&((u=this.modal)==null||u.open(),(l=this.modal)==null||l.subscribeState(f=>{!f.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const h=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(Bn(lr({namespaces:lr({},n&&{[this.namespace]:n})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:e?.pairingTopic,scopedProperties:h})).then(f=>{a(f)}).catch(f=>{var p;(p=this.modal)==null||p.showErrorMessage("Unable to connect"),c(new Error(f.message))})});if(!s)return;const o=au(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Ai(this.chainId)})}catch(s){throw this.signer.logger.error(s),s}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var n;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const i=await new Promise(async(o,a)=>{var c,u;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(u=this.modal)==null||u.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(Bn(lr({},e),{chains:this.rpc.chains}),r).then(l=>{o(l)}).catch(l=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),s=i.session;if(s){const o=au(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Ai(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}finally{(n=this.modal)==null||n.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:r}=e,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.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 r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",Ai(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",Bn(lr({},re("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 r=e.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",Ai(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,n,i]=e.split(":");return{chainId:`${r}:${n}`,address:i}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,n;const i=(r=e?.chains)!=null?r:[],s=(n=e?.optionalChains)!=null?n:[],o=i.concat(s);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=i.length?e?.methods||ns:[],c=i.length?e?.events||is:[],u=e?.optionalMethods||[],l=e?.optionalEvents||[],h=e?.rpcMap||this.buildRpcMap(o,e.projectId),f=e?.qrModalOptions||void 0;return{chains:i?.map(p=>this.formatChainId(p)),optionalChains:s.map(p=>this.formatChainId(p)),methods:a,events:c,optionalMethods:u,optionalEvents:l,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:f,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const n={};return e.forEach(i=>{n[i]=this.getRpcUrl(i,r)}),n}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?ss(this.rpc.chains):ss(this.rpc.optionalChains),this.signer=await tC.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 r;try{const n=await oC(),{convertWCMToAppKitOptions:i}=await Promise.resolve().then(function(){return $C}),s=i(Bn(lr({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!s.networks.length)throw new Error("No networks found for WalletConnect·");r=n(Bn(lr({},s),{universalProvider:this.signer,manualWCControl:!0}))}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:n,rpcMap:i}=e;r&&Et(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)})),n&&Et(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(s=>this.formatChainId(s)),n.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)}))}getRpcUrl(e,r){var n;return((n=this.rpc.rpcMap)==null?void 0:n[e])||`${sC}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r?.accounts),this.setAccounts(r?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}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(r=>this.parseAccount(r))}}const dC=Ts;var pC=Object.defineProperty,gC=Object.defineProperties,yC=Object.getOwnPropertyDescriptors,lh=Object.getOwnPropertySymbols,mC=Object.prototype.hasOwnProperty,wC=Object.prototype.propertyIsEnumerable,hh=(t,e,r)=>e in t?pC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,og=(t,e)=>{for(var r in e||(e={}))mC.call(e,r)&&hh(t,r,e[r]);if(lh)for(var r of lh(e))wC.call(e,r)&&hh(t,r,e[r]);return t},vC=(t,e)=>gC(t,yC(e));function bC(t){if(t)return{"--w3m-font-family":t["--wcm-font-family"],"--w3m-accent":t["--wcm-accent-color"],"--w3m-color-mix":t["--wcm-background-color"],"--w3m-z-index":t["--wcm-z-index"]?Number(t["--wcm-z-index"]):void 0,"--w3m-qr-color":t["--wcm-accent-color"],"--w3m-font-size-master":t["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":t["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const EC=t=>{const[e,r]=t.split(":");return ag({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function _C(t){var e,r,n,i,s,o,a;const c=(e=t.chains)==null?void 0:e.map(EC).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const u=c.find(h=>{var f;return h.id===((f=t.defaultChain)==null?void 0:f.id)}),l={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:bC(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:u,metadata:vC(og({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((n=t.metadata)==null?void 0:n.description)||"Connect to WalletConnect-compatible wallets",url:((i=t.metadata)==null?void 0:i.url)||"https://walletconnect.org",icons:((s=t.metadata)==null?void 0:s.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:t.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(t.explorerRecommendedWalletIds)?t.explorerRecommendedWalletIds:[],excludeWalletIds:t.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(t.explorerExcludedWalletIds)?t.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=t.mobileWallets)!=null&&o.length||(a=t.desktopWallets)!=null&&a.length){const h=[...(t.mobileWallets||[]).map(d=>({id:d.id,name:d.name,links:d.links})),...(t.desktopWallets||[]).map(d=>({id:d.id,name:d.name,links:{native:d.links.native,universal:d.links.universal}}))],f=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],p=h.filter(d=>!f.includes(d.id));p.length&&(l.customWallets=p)}return l}function ag(t){return og({formatters:void 0,fees:void 0,serializers:void 0},t)}var $C=Object.freeze({__proto__:null,convertWCMToAppKitOptions:_C,defineChain:ag});const p3=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:dC,OPTIONAL_EVENTS:sg,OPTIONAL_METHODS:ig,REQUIRED_EVENTS:is,REQUIRED_METHODS:ns,default:Ts},Symbol.toStringTag,{value:"Module"}));export{My as A,ni as B,Jb as C,xt as D,Ke as E,lt as F,Dt as G,_t as H,Or as I,AE as J,HC as K,Xc as L,Vf as M,bE as N,CE as O,Lc as P,rf as Q,KC as R,zC as S,bs as T,VC as U,WC as V,p3 as W,wr as a,vr as b,T as c,pi as d,Ea as e,ht as f,sf as g,Mv as h,nf as i,qn as j,Co as k,us as l,ry as m,Q0 as n,dt as o,Ia as p,ms as q,gs as r,Wt as s,Ze as t,Ir as u,er as v,Dv as w,gr as x,Qe as y,ys as z};