@dcl/landing-site 0.0.1-23617412190.commit-e3cca1e → 0.0.1-23618345269.commit-1e2a634
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.
- package/assets/{AnimatedBackground-gNtI-YhV.js → AnimatedBackground-DaItTQFq.js} +2 -2
- package/assets/FooterLanding-DssbnrQv.js +1 -0
- package/assets/{add-CHM98Fes.js → add-DPPiowNV.js} +1 -1
- package/assets/all-wallets-Bz44-vkK.js +6 -0
- package/assets/{app-store-CRgqc_8W.js → app-store-BIDMwYtJ.js} +2 -2
- package/assets/{apple-DA-gL0ew.js → apple-N0qVBHJ_.js} +2 -2
- package/assets/arrow-bottom-DEr0DxNQ.js +8 -0
- package/assets/{arrow-bottom-circle-W7EphmHv.js → arrow-bottom-circle-CyIUslGZ.js} +2 -2
- package/assets/arrow-left-CL8RzR1U.js +8 -0
- package/assets/arrow-right-9ngyyIUg.js +8 -0
- package/assets/arrow-top-Ds4_-RxX.js +8 -0
- package/assets/auto-track-CCVKJMew.js +1 -0
- package/assets/{bank-BJ_zMNdO.js → bank-BXxzgEEm.js} +1 -1
- package/assets/{basic-Cbs3wtVd.js → basic-BeVmC8wl.js} +1 -1
- package/assets/{browser-BZI6LlMK.js → browser-BFjIZRUr.js} +2 -2
- package/assets/{card-a0PEwixX.js → card-QrT_SqqP.js} +2 -2
- package/assets/ccip-Cnf8kps5.js +1 -0
- package/assets/{checkmark-DxhM6kxf.js → checkmark-BMbPxxD7.js} +2 -2
- package/assets/{checkmark-bold-nUmAb0Jv.js → checkmark-bold-CJr27ZWW.js} +2 -2
- package/assets/chevron-bottom-D-0_NZL7.js +8 -0
- package/assets/chevron-left-CkfqwG7X.js +8 -0
- package/assets/chevron-right-VRrVnjRX.js +8 -0
- package/assets/chevron-top-DmsHTjIi.js +8 -0
- package/assets/{chrome-store-C0l7_S46.js → chrome-store-Cxd7qy2P.js} +2 -2
- package/assets/{clock-CGFlkuTk.js → clock-BnERhsls.js} +2 -2
- package/assets/close-CegnAZI6.js +8 -0
- package/assets/{coinPlaceholder-BcTAu_IN.js → coinPlaceholder-ChJPLsLs.js} +2 -2
- package/assets/{compass-AzcmZa1s.js → compass-DhggJQin.js} +2 -2
- package/assets/{copy-DU6nZmjR.js → copy-CPyS9JID.js} +2 -2
- package/assets/{core-kZLq_ADy.js → core-BsX5IiWg.js} +33 -32
- package/assets/cursor-DuDLrsyW.js +3 -0
- package/assets/{cursor-transparent-CBn-iCcY.js → cursor-transparent-nm7_wJtu.js} +1 -1
- package/assets/{desktop-Cgv-18ZV.js → desktop-lh-TFiWV.js} +2 -2
- package/assets/{disconnect-BccJ3jIT.js → disconnect-BVdZSUk4.js} +2 -2
- package/assets/{discord-5RUDhSal.js → discord-DXIOms3e.js} +2 -2
- package/assets/{etherscan-C3fPztHb.js → etherscan-C7MLFrad.js} +2 -2
- package/assets/{exclamation-triangle-D_ozpW4c.js → exclamation-triangle-BQlSv988.js} +2 -2
- package/assets/{extension-BBOn_gDX.js → extension-BpS3-8TK.js} +1 -1
- package/assets/{external-link-BWUOLdmG.js → external-link-Bhl3PYp_.js} +1 -1
- package/assets/{facebook-CPf0OEse.js → facebook-BhDHaw9e.js} +2 -2
- package/assets/{farcaster-CR6V0phI.js → farcaster-4D2R9BLw.js} +2 -2
- package/assets/filters-Cx1L6OOr.js +8 -0
- package/assets/{github-Df-6J-fJ.js → github-ZEREWWLi.js} +2 -2
- package/assets/{google-ZDEMGNHZ.js → google-G5T2o3XW.js} +1 -1
- package/assets/{help-circle-BL4M8ISL.js → help-circle-rjs8mUc4.js} +1 -1
- package/assets/hooks.module-Dz_XB4AG.js +1 -0
- package/assets/{id-B8ywMzga.js → id-CdFeC_id.js} +2 -2
- package/assets/{image-CwqhHOgq.js → image-25IylLgD.js} +2 -2
- package/assets/index-0pT38_PF.js +2 -0
- package/assets/index-1kXtXmtZ.js +1 -0
- package/assets/index-B06iF3RB.js +1 -0
- package/assets/index-B37VckPJ.js +1 -0
- package/assets/index-Ba0skkGV.js +51 -0
- package/assets/index-BgDqerLq.js +2 -0
- package/assets/index-BvDvxY19.js +811 -0
- package/assets/index-Cdwkr0dW.js +1 -0
- package/assets/{index-BfZPjAvn.js → index-CnGR-jpk.js} +3 -3
- package/assets/index-DBXLKIqk.js +1 -0
- package/assets/index-DmYudDJU.js +1 -0
- package/assets/index-UGAdGA2y.js +5 -0
- package/assets/index-WuZ7mIic.js +7 -0
- package/assets/index-i_Rpb8UV.js +1 -0
- package/assets/index-ikT2QzgB.js +1 -0
- package/assets/index-nibyPLVP.js +1 -0
- package/assets/index-rj6I7Dp8.js +44 -0
- package/assets/index-z5AtYTFU.js +1 -0
- package/assets/{index.es-D0tGeUGR.js → index.es-A2H6_-n5.js} +12 -11
- package/assets/index.umd-DLkXoDDP.js +1 -0
- package/assets/{info-COI3OebQ.js → info-BCYaCSNh.js} +2 -2
- package/assets/{info-circle-D_RgtoG_.js → info-circle-gsgfsSpe.js} +2 -2
- package/assets/{lightbulb-D29oA1kW.js → lightbulb-BDHFTG5h.js} +2 -2
- package/assets/{mail-CJ9rvNEO.js → mail-DiTw9Nrl.js} +1 -1
- package/assets/{mobile-BSTR0oWP.js → mobile-CXqu2RHA.js} +2 -2
- package/assets/{more-BcYAHybc.js → more-C2sMArXI.js} +2 -2
- package/assets/{network-placeholder-Cnunuezr.js → network-placeholder-CPz8HGx-.js} +2 -2
- package/assets/{nftPlaceholder-rT8UJE4K.js → nftPlaceholder-DfXkrt19.js} +2 -2
- package/assets/node-Dh3n99U-.js +4 -0
- package/assets/off-DkrCs4Mj.js +8 -0
- package/assets/{play-store-DvfWnN4y.js → play-store-bfQWoaGY.js} +2 -2
- package/assets/{plus-gHBDgGjM.js → plus-QWHXQdAC.js} +2 -2
- package/assets/{qr-code-DDHcNUue.js → qr-code-BkDfZ-Qo.js} +1 -1
- package/assets/{recycle-horizontal-BRiwD6Mt.js → recycle-horizontal-QwbqvQmV.js} +1 -1
- package/assets/{refresh-B9gXvGXV.js → refresh-mrgGy3xW.js} +2 -2
- package/assets/{reown-logo-WhOyJ0P-.js → reown-logo-BPaNSMQx.js} +2 -2
- package/assets/search-BC-KS3un.js +8 -0
- package/assets/secp256k1-Bm0d2i6U.js +1 -0
- package/assets/secp256k1-MIfy00vZ.js +1 -0
- package/assets/{send-Bwl7uhNH.js → send-TXNvdG3J.js} +2 -2
- package/assets/{swapHorizontal-DZpWZtIz.js → swapHorizontal-DB0tAXym.js} +2 -2
- package/assets/{swapHorizontalBold-BsXTfOUB.js → swapHorizontalBold-bt9pkPYB.js} +2 -2
- package/assets/{swapHorizontalMedium-C_6kbXTl.js → swapHorizontalMedium-sWdoPCsB.js} +2 -2
- package/assets/{swapHorizontalRoundedBold-C0Zn63rG.js → swapHorizontalRoundedBold-DHHovHd5.js} +2 -2
- package/assets/{swapVertical-3Bh1HEox.js → swapVertical-DTfIwviz.js} +2 -2
- package/assets/swiper-react-Bl4aS6YN.js +1 -0
- package/assets/{telegram-DNIzTF3I.js → telegram-5bTwLHz7.js} +2 -2
- package/assets/{three-dots-COxARji7.js → three-dots-C33y8Xmm.js} +2 -2
- package/assets/{twitch-CZ-7Kiwd.js → twitch-CHjNW3bL.js} +2 -2
- package/assets/{twitterIcon-Dcm6rS6L.js → twitterIcon-Bsvg5_qQ.js} +2 -2
- package/assets/{verify-CDFvKR62.js → verify-Cadwtk5M.js} +2 -2
- package/assets/{verify-filled-xoYiPqK4.js → verify-filled-tSZv_9lr.js} +2 -2
- package/assets/{w3m-modal-DelFzwRg.js → w3m-modal-9Q6B4hli.js} +1 -1
- package/assets/{wallet-BFpTXEJT.js → wallet-DhjaFVTL.js} +2 -2
- package/assets/{wallet-placeholder-AXXSMd3R.js → wallet-placeholder-B-dNSlaX.js} +2 -2
- package/assets/{walletconnect-Cz3JVcWt.js → walletconnect-BcwzL0ZV.js} +4 -4
- package/assets/{warning-circle-8Kak1pmh.js → warning-circle-D3W3qLdq.js} +1 -1
- package/assets/{x-C-F8mfxV.js → x-BZWPQTuH.js} +2 -2
- package/index.html +2 -5
- package/package.json +3 -3
- package/assets/FooterLanding-iYuz415B.js +0 -1
- package/assets/all-wallets-Qb9stbRm.js +0 -6
- package/assets/arrow-bottom-rhor6qOA.js +0 -8
- package/assets/arrow-left-Bq3H-u24.js +0 -8
- package/assets/arrow-right-CkiCqXKz.js +0 -8
- package/assets/arrow-top-BbayD3ny.js +0 -8
- package/assets/auto-track-CpyrW7jj.js +0 -1
- package/assets/chevron-bottom-C2GrTkGW.js +0 -8
- package/assets/chevron-left-TOHygVkY.js +0 -8
- package/assets/chevron-right-kK9l_fNM.js +0 -8
- package/assets/chevron-top-GkMD6fM_.js +0 -8
- package/assets/close-D_Rm3jAw.js +0 -8
- package/assets/cursor-BkgcU3pB.js +0 -3
- package/assets/filters-DJ44i8Mo.js +0 -8
- package/assets/index-BA7pz-wf.js +0 -1
- package/assets/index-BFntqBXC.js +0 -1
- package/assets/index-B_dMHlXr.js +0 -1
- package/assets/index-BgXJ6Z6L.js +0 -1
- package/assets/index-CJxXHUcP.js +0 -1
- package/assets/index-CXz9iuA3.js +0 -1
- package/assets/index-Cg_5qxO-.js +0 -2
- package/assets/index-CntXRSz5.js +0 -2
- package/assets/index-DIS5DQM_.js +0 -1
- package/assets/index-Dbv53o1b.js +0 -1
- package/assets/index-DoaqdCF9.js +0 -601
- package/assets/index-Dsk1niAz.js +0 -7
- package/assets/index-HuL12PNJ.js +0 -5
- package/assets/index-mgaHX57j.js +0 -1
- package/assets/index-vWYtvmN_.js +0 -1
- package/assets/index.umd-CIiTi8qb.js +0 -1
- package/assets/off-B_Wn42xj.js +0 -8
- package/assets/search-DpE00x6Q.js +0 -8
- package/assets/swiper-react-BALcxKpm.js +0 -1
- package/assets/vendor-mui-40jyI-Tp.js +0 -197
- package/assets/vendor-react-DJXYd7Dm.js +0 -40
- package/assets/vendor-web3-Dw3dBix7.js +0 -74
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/
|
|
2
|
-
import{
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/secp256k1-MIfy00vZ.js","assets/index-BvDvxY19.js","assets/index-nibyPLVP.js","assets/core-BsX5IiWg.js","assets/node-Dh3n99U-.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{i as fh,j as ri,p as ft,f as At,g as H,h as dh,B as Ce}from"./index-BvDvxY19.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
|
|
@@ -12,7 +12,7 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
|
12
12
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
13
13
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
14
14
|
PERFORMANCE OF THIS SOFTWARE.
|
|
15
|
-
***************************************************************************** */var uo=function(t,e){return uo=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])},uo(t,e)};function Vp(t,e){uo(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var lo=function(){return lo=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},lo.apply(this,arguments)};function Wp(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 Gp(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 Yp(t,e){return function(r,n){e(r,n,t)}}function Jp(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Zp(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 Qp(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 Xp(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function eg(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function ho(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 Zl(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 tg(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Zl(arguments[e]));return t}function rg(){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 Un(t){return this instanceof Un?(this.v=t,this):new Un(t)}function ng(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 Un?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 ig(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:Un(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function sg(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 ho=="function"?ho(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 og(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function ag(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 cg(t){return t&&t.__esModule?t:{default:t}}function ug(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function lg(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 hg=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return lo},__asyncDelegator:ig,__asyncGenerator:ng,__asyncValues:sg,__await:Un,__awaiter:Zp,__classPrivateFieldGet:ug,__classPrivateFieldSet:lg,__createBinding:Xp,__decorate:Gp,__exportStar:eg,__extends:Vp,__generator:Qp,__importDefault:cg,__importStar:ag,__makeTemplateObject:og,__metadata:Jp,__param:Yp,__read:Zl,__rest:Wp,__spread:tg,__spreadArrays:rg,__values:ho},Symbol.toStringTag,{value:"Module"})),Qi=kl(hg);var Ps={},$n={},Ba;function fg(){if(Ba)return $n;Ba=1,Object.defineProperty($n,"__esModule",{value:!0}),$n.delay=void 0;function t(e){return new Promise(r=>{setTimeout(()=>{r(!0)},e)})}return $n.delay=t,$n}var ir={},Ds={},sr={},Ua;function dg(){return Ua||(Ua=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.ONE_THOUSAND=sr.ONE_HUNDRED=void 0,sr.ONE_HUNDRED=100,sr.ONE_THOUSAND=1e3),sr}var Ss={},qa;function pg(){return qa||(qa=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ONE_YEAR=t.FOUR_WEEKS=t.THREE_WEEKS=t.TWO_WEEKS=t.ONE_WEEK=t.THIRTY_DAYS=t.SEVEN_DAYS=t.FIVE_DAYS=t.THREE_DAYS=t.ONE_DAY=t.TWENTY_FOUR_HOURS=t.TWELVE_HOURS=t.SIX_HOURS=t.THREE_HOURS=t.ONE_HOUR=t.SIXTY_MINUTES=t.THIRTY_MINUTES=t.TEN_MINUTES=t.FIVE_MINUTES=t.ONE_MINUTE=t.SIXTY_SECONDS=t.THIRTY_SECONDS=t.TEN_SECONDS=t.FIVE_SECONDS=t.ONE_SECOND=void 0,t.ONE_SECOND=1,t.FIVE_SECONDS=5,t.TEN_SECONDS=10,t.THIRTY_SECONDS=30,t.SIXTY_SECONDS=60,t.ONE_MINUTE=t.SIXTY_SECONDS,t.FIVE_MINUTES=t.ONE_MINUTE*5,t.TEN_MINUTES=t.ONE_MINUTE*10,t.THIRTY_MINUTES=t.ONE_MINUTE*30,t.SIXTY_MINUTES=t.ONE_MINUTE*60,t.ONE_HOUR=t.SIXTY_MINUTES,t.THREE_HOURS=t.ONE_HOUR*3,t.SIX_HOURS=t.ONE_HOUR*6,t.TWELVE_HOURS=t.ONE_HOUR*12,t.TWENTY_FOUR_HOURS=t.ONE_HOUR*24,t.ONE_DAY=t.TWENTY_FOUR_HOURS,t.THREE_DAYS=t.ONE_DAY*3,t.FIVE_DAYS=t.ONE_DAY*5,t.SEVEN_DAYS=t.ONE_DAY*7,t.THIRTY_DAYS=t.ONE_DAY*30,t.ONE_WEEK=t.SEVEN_DAYS,t.TWO_WEEKS=t.ONE_WEEK*2,t.THREE_WEEKS=t.ONE_WEEK*3,t.FOUR_WEEKS=t.ONE_WEEK*4,t.ONE_YEAR=t.ONE_DAY*365}(Ss)),Ss}var ka;function Ql(){return ka||(ka=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Qi;e.__exportStar(dg(),t),e.__exportStar(pg(),t)}(Ds)),Ds}var za;function gg(){if(za)return ir;za=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.fromMiliseconds=ir.toMiliseconds=void 0;const t=Ql();function e(n){return n*t.ONE_THOUSAND}ir.toMiliseconds=e;function r(n){return Math.floor(n/t.ONE_THOUSAND)}return ir.fromMiliseconds=r,ir}var Ka;function yg(){return Ka||(Ka=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Qi;e.__exportStar(fg(),t),e.__exportStar(gg(),t)}(Ps)),Ps}var xr={},Ha;function mg(){if(Ha)return xr;Ha=1,Object.defineProperty(xr,"__esModule",{value:!0}),xr.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(r){if(this.timestamps.has(r))throw new Error(`Watch already started for label: ${r}`);this.timestamps.set(r,{started:Date.now()})}stop(r){const n=this.get(r);if(typeof n.elapsed<"u")throw new Error(`Watch already stopped for label: ${r}`);const i=Date.now()-n.started;this.timestamps.set(r,{started:n.started,elapsed:i})}get(r){const n=this.timestamps.get(r);if(typeof n>"u")throw new Error(`No timestamp found for label: ${r}`);return n}elapsed(r){const n=this.get(r);return n.elapsed||Date.now()-n.started}}return xr.Watch=t,xr.default=t,xr}var xs={},On={},Va;function vg(){if(Va)return On;Va=1,Object.defineProperty(On,"__esModule",{value:!0}),On.IWatch=void 0;class t{}return On.IWatch=t,On}var Wa;function wg(){return Wa||(Wa=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),Qi.__exportStar(vg(),t)}(xs)),xs}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Qi;e.__exportStar(yg(),t),e.__exportStar(mg(),t),e.__exportStar(wg(),t),e.__exportStar(Ql(),t)})(N);class _r{}let bg=class extends _r{constructor(e){super()}};const Ga=N.FIVE_SECONDS,$r={pulse:"heartbeat_pulse"};let Eg=class Xl extends bg{constructor(e){super(e),this.events=new Hp.EventEmitter,this.interval=Ga,this.interval=e?.interval||Ga}static async init(e){const r=new Xl(e);return await r.init(),r}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}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 initialize(){this.intervalRef=setInterval(()=>this.pulse(),N.toMiliseconds(this.interval))}pulse(){this.events.emit($r.pulse)}};const _g=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,$g=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,Og=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function Ig(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){Pg(t);return}return e}function Pg(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function ai(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const r=t.trim();if(r.length<=9)switch(r.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!Og.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(_g.test(t)||$g.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,Ig)}return JSON.parse(t)}catch(n){if(e.strict)throw n;return t}}const Dg=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),Sg=t=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(n,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)};function mr(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return Sg(t)}catch{return t}}function Vt(t){return typeof t=="string"?t:Dg(t)||""}function xg(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var Ag=Cg;function Cg(t,e,r){var n=r&&r.stringify||xg,i=1;if(typeof t=="object"&&t!==null){var s=e.length+i;if(s===1)return t;var o=new Array(s);o[0]=n(t);for(var a=1;a<s;a++)o[a]=n(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var u="",l=1-i,h=-1,f=t&&t.length||0,p=0;p<f;){if(t.charCodeAt(p)===37&&p+1<f){switch(h=h>-1?h:0,t.charCodeAt(p+1)){case 100:case 102:if(l>=c||e[l]==null)break;h<p&&(u+=t.slice(h,p)),u+=Number(e[l]),h=p+2,p++;break;case 105:if(l>=c||e[l]==null)break;h<p&&(u+=t.slice(h,p)),u+=Math.floor(Number(e[l])),h=p+2,p++;break;case 79:case 111:case 106:if(l>=c||e[l]===void 0)break;h<p&&(u+=t.slice(h,p));var d=typeof e[l];if(d==="string"){u+="'"+e[l]+"'",h=p+2,p++;break}if(d==="function"){u+=e[l].name||"<anonymous>",h=p+2,p++;break}u+=n(e[l]),h=p+2,p++;break;case 115:if(l>=c)break;h<p&&(u+=t.slice(h,p)),u+=String(e[l]),h=p+2,p++;break;case 37:h<p&&(u+=t.slice(h,p)),u+="%",h=p+2,p++,l--;break}++l}++p}return h===-1?t:(h<f&&(u+=t.slice(h)),u)}const Ya=Ag;var Gr=Lt;const qn=qg().console||{},Lg={mapHttpRequest:ci,mapHttpResponse:ci,wrapRequestSerializer:As,wrapResponseSerializer:As,wrapErrorSerializer:As,req:ci,res:ci,err:Mg};function Rg(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function Lt(t){t=t||{},t.browser=t.browser||{};const e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const r=t.browser.write||qn;t.browser.write&&(t.browser.asObject=!0);const n=t.serializers||{},i=Rg(t.browser.serialize,n);let s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);const o=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),t.enabled===!1&&(t.level="silent");const a=t.level||"info",c=Object.create(r);c.log||(c.log=kn),Object.defineProperty(c,"levelVal",{get:l}),Object.defineProperty(c,"level",{get:h,set:f});const u={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:Fg(t)};c.levels=Lt.levels,c.level=a,c.setMaxListeners=c.getMaxListeners=c.emit=c.addListener=c.on=c.prependListener=c.once=c.prependOnceListener=c.removeListener=c.removeAllListeners=c.listeners=c.listenerCount=c.eventNames=c.write=c.flush=kn,c.serializers=n,c._serialize=i,c._stdErrSerialize=s,c.child=p,e&&(c._logEvent=fo());function l(){return this.level==="silent"?1/0:this.levels.values[this.level]}function h(){return this._level}function f(d){if(d!=="silent"&&!this.levels.values[d])throw Error("unknown level "+d);this._level=d,Ar(u,c,"error","log"),Ar(u,c,"fatal","error"),Ar(u,c,"warn","error"),Ar(u,c,"info","log"),Ar(u,c,"debug","log"),Ar(u,c,"trace","log")}function p(d,y){if(!d)throw new Error("missing bindings for child Pino");y=y||{},i&&d.serializers&&(y.serializers=d.serializers);const v=y.serializers;if(i&&v){var b=Object.assign({},n,v),w=t.browser.serialize===!0?Object.keys(b):i;delete d.serializers,Xi([d],w,b,this._stdErrSerialize)}function E(O){this._childLevel=(O._childLevel|0)+1,this.error=Cr(O,d,"error"),this.fatal=Cr(O,d,"fatal"),this.warn=Cr(O,d,"warn"),this.info=Cr(O,d,"info"),this.debug=Cr(O,d,"debug"),this.trace=Cr(O,d,"trace"),b&&(this.serializers=b,this._serialize=w),e&&(this._logEvent=fo([].concat(O._logEvent.bindings,d)))}return E.prototype=this,new E(this)}return c}Lt.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}};Lt.stdSerializers=Lg;Lt.stdTimeFunctions=Object.assign({},{nullTime:eh,epochTime:th,unixTime:Bg,isoTime:Ug});function Ar(t,e,r,n){const i=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?kn:i[r]?i[r]:qn[r]||qn[n]||kn,Ng(t,e,r)}function Ng(t,e,r){!t.transmit&&e[r]===kn||(e[r]=function(n){return function(){const s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===qn?qn:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(t.serialize&&!t.asObject&&Xi(o,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?n.call(a,Tg(this,r,o,s)):n.apply(a,o),t.transmit){const u=t.transmit.level||e.level,l=Lt.levels.values[u],h=Lt.levels.values[r];if(h<l)return;jg(this,{ts:s,methodLevel:r,methodValue:h,transmitLevel:u,transmitValue:Lt.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},o)}}}(e[r]))}function Tg(t,e,r,n){t._serialize&&Xi(r,t._serialize,t.serializers,t._stdErrSerialize);const i=r.slice();let s=i[0];const o={};n&&(o.time=n),o.level=Lt.levels.values[e];let a=(t._childLevel|0)+1;if(a<1&&(a=1),s!==null&&typeof s=="object"){for(;a--&&typeof i[0]=="object";)Object.assign(o,i.shift());s=i.length?Ya(i.shift(),i):void 0}else typeof s=="string"&&(s=Ya(i.shift(),i));return s!==void 0&&(o.msg=s),o}function Xi(t,e,r,n){for(const i in t)if(n&&t[i]instanceof Error)t[i]=Lt.stdSerializers.err(t[i]);else if(typeof t[i]=="object"&&!Array.isArray(t[i]))for(const s in t[i])e&&e.indexOf(s)>-1&&s in r&&(t[i][s]=r[s](t[i][s]))}function Cr(t,e,r){return function(){const n=new Array(1+arguments.length);n[0]=e;for(var i=1;i<n.length;i++)n[i]=arguments[i-1];return t[r].apply(this,n)}}function jg(t,e,r){const n=e.send,i=e.ts,s=e.methodLevel,o=e.methodValue,a=e.val,c=t._logEvent.bindings;Xi(r,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=i,t._logEvent.messages=r.filter(function(u){return c.indexOf(u)===-1}),t._logEvent.level.label=s,t._logEvent.level.value=o,n(s,t._logEvent,a),t._logEvent=fo(c)}function fo(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function Mg(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const r in t)e[r]===void 0&&(e[r]=t[r]);return e}function Fg(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?eh:th}function ci(){return{}}function As(t){return t}function kn(){}function eh(){return!1}function th(){return Date.now()}function Bg(){return Math.round(Date.now()/1e3)}function Ug(){return new Date(Date.now()).toISOString()}function qg(){function t(e){return typeof e<"u"&&e}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return t(self)||t(window)||t(this)||{}}}const Jn=Yn(Gr),kg={level:"info"},Zn="custom_context",Xo=1e3*1024;let zg=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},Ja=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const r=new zg(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let r=this.head;for(;r!==null;)e.push(r.value),r=r.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const r=e.value;return e=e.next,{done:!1,value:r}}}}},rh=class{constructor(e,r=Xo){this.level=e??"error",this.levelValue=Gr.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new Ja(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===Gr.levels.values.error?console.error(e):r===Gr.levels.values.warn?console.warn(e):r===Gr.levels.values.debug?console.debug(e):r===Gr.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Vt({timestamp:new Date().toISOString(),log:e}));const r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new Ja(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const r=this.getLogArray();return r.push(Vt({extraMetadata:e})),new Blob(r,{type:"application/json"})}},Kg=class{constructor(e,r=Xo){this.baseChunkLogger=new rh(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const r=URL.createObjectURL(this.logsToBlob(e)),n=document.createElement("a");n.href=r,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}},Hg=class{constructor(e,r=Xo){this.baseChunkLogger=new rh(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var Vg=Object.defineProperty,Wg=Object.defineProperties,Gg=Object.getOwnPropertyDescriptors,Za=Object.getOwnPropertySymbols,Yg=Object.prototype.hasOwnProperty,Jg=Object.prototype.propertyIsEnumerable,Qa=(t,e,r)=>e in t?Vg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Bi=(t,e)=>{for(var r in e||(e={}))Yg.call(e,r)&&Qa(t,r,e[r]);if(Za)for(var r of Za(e))Jg.call(e,r)&&Qa(t,r,e[r]);return t},Ui=(t,e)=>Wg(t,Gg(e));function es(t){return Ui(Bi({},t),{level:t?.level||kg.level})}function Zg(t,e=Zn){return t[e]||""}function Qg(t,e,r=Zn){return t[r]=e,t}function Qe(t,e=Zn){let r="";return typeof t.bindings>"u"?r=Zg(t,e):r=t.bindings().context||"",r}function Xg(t,e,r=Zn){const n=Qe(t,r);return n.trim()?`${n}/${e}`:e}function He(t,e,r=Zn){const n=Xg(t,e,r),i=t.child({context:n});return Qg(i,n,r)}function ey(t){var e,r;const n=new Kg((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Jn(Ui(Bi({},t.opts),{level:"trace",browser:Ui(Bi({},(r=t.opts)==null?void 0:r.browser),{write:i=>n.write(i)})})),chunkLoggerController:n}}function ty(t){var e;const r=new Hg((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Jn(Ui(Bi({},t.opts),{level:"trace"}),r),chunkLoggerController:r}}function ry(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?ey(t):ty(t)}function ny(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function nh(t,...e){if(!ny(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 Xa(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 iy(t,e){nh(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const Lr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Cs=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function sy(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function ih(t){return typeof t=="string"&&(t=sy(t)),nh(t),t}let oy=class{clone(){return this._cloneInto()}};function ay(t){const e=n=>t().update(ih(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function sh(t=32){if(Lr&&typeof Lr.getRandomValues=="function")return Lr.getRandomValues(new Uint8Array(t));if(Lr&&typeof Lr.randomBytes=="function")return Lr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function cy(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)}let uy=class extends oy{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=Cs(this.buffer)}update(e){Xa(this);const{view:r,buffer:n,blockLen:i}=this;e=ih(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=Cs(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){Xa(this),iy(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;cy(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=Cs(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 ui=BigInt(2**32-1),po=BigInt(32);function oh(t,e=!1){return e?{h:Number(t&ui),l:Number(t>>po&ui)}:{h:Number(t>>po&ui)|0,l:Number(t&ui)|0}}function ly(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}=oh(t[i],e);[r[i],n[i]]=[s,o]}return[r,n]}const hy=(t,e)=>BigInt(t>>>0)<<po|BigInt(e>>>0),fy=(t,e,r)=>t>>>r,dy=(t,e,r)=>t<<32-r|e>>>r,py=(t,e,r)=>t>>>r|e<<32-r,gy=(t,e,r)=>t<<32-r|e>>>r,yy=(t,e,r)=>t<<64-r|e>>>r-32,my=(t,e,r)=>t>>>r-32|e<<64-r,vy=(t,e)=>e,wy=(t,e)=>t,by=(t,e,r)=>t<<r|e>>>32-r,Ey=(t,e,r)=>e<<r|t>>>32-r,_y=(t,e,r)=>e<<r-32|t>>>64-r,$y=(t,e,r)=>t<<r-32|e>>>64-r;function Oy(t,e,r,n){const i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}const Iy=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Py=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Dy=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Sy=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,xy=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Ay=(t,e,r,n,i,s)=>e+r+n+i+s+(t/2**32|0)|0,V={fromBig:oh,split:ly,toBig:hy,shrSH:fy,shrSL:dy,rotrSH:py,rotrSL:gy,rotrBH:yy,rotrBL:my,rotr32H:vy,rotr32L:wy,rotlSH:by,rotlSL:Ey,rotlBH:_y,rotlBL:$y,add:Oy,add3L:Iy,add3H:Py,add4L:Dy,add4H:Sy,add5H:Ay,add5L:xy},[Cy,Ly]=V.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Wt=new Uint32Array(80),Gt=new Uint32Array(80);let Ry=class extends uy{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:r,Bh:n,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:f,Gh:p,Gl:d,Hh:y,Hl:v}=this;return[e,r,n,i,s,o,a,c,u,l,h,f,p,d,y,v]}set(e,r,n,i,s,o,a,c,u,l,h,f,p,d,y,v){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=y|0,this.Hl=v|0}process(e,r){for(let E=0;E<16;E++,r+=4)Wt[E]=e.getUint32(r),Gt[E]=e.getUint32(r+=4);for(let E=16;E<80;E++){const O=Wt[E-15]|0,x=Gt[E-15]|0,S=V.rotrSH(O,x,1)^V.rotrSH(O,x,8)^V.shrSH(O,x,7),D=V.rotrSL(O,x,1)^V.rotrSL(O,x,8)^V.shrSL(O,x,7),C=Wt[E-2]|0,I=Gt[E-2]|0,q=V.rotrSH(C,I,19)^V.rotrBH(C,I,61)^V.shrSH(C,I,6),M=V.rotrSL(C,I,19)^V.rotrBL(C,I,61)^V.shrSL(C,I,6),j=V.add4L(D,M,Gt[E-7],Gt[E-16]),k=V.add4H(j,S,q,Wt[E-7],Wt[E-16]);Wt[E]=k|0,Gt[E]=j|0}let{Ah:n,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:f,Fh:p,Fl:d,Gh:y,Gl:v,Hh:b,Hl:w}=this;for(let E=0;E<80;E++){const O=V.rotrSH(h,f,14)^V.rotrSH(h,f,18)^V.rotrBH(h,f,41),x=V.rotrSL(h,f,14)^V.rotrSL(h,f,18)^V.rotrBL(h,f,41),S=h&p^~h&y,D=f&d^~f&v,C=V.add5L(w,x,D,Ly[E],Gt[E]),I=V.add5H(C,b,O,S,Cy[E],Wt[E]),q=C|0,M=V.rotrSH(n,i,28)^V.rotrBH(n,i,34)^V.rotrBH(n,i,39),j=V.rotrSL(n,i,28)^V.rotrBL(n,i,34)^V.rotrBL(n,i,39),k=n&s^n&a^s&a,L=i&o^i&c^o&c;b=y|0,w=v|0,y=p|0,v=d|0,p=h|0,d=f|0,{h,l:f}=V.add(u|0,l|0,I|0,q|0),u=a|0,l=c|0,a=s|0,c=o|0,s=n|0,o=i|0;const g=V.add3L(q,j,L);n=V.add3H(g,I,M,k),i=g|0}({h:n,l:i}=V.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:s,l:o}=V.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=V.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=V.add(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:f}=V.add(this.Eh|0,this.El|0,h|0,f|0),{h:p,l:d}=V.add(this.Fh|0,this.Fl|0,p|0,d|0),{h:y,l:v}=V.add(this.Gh|0,this.Gl|0,y|0,v|0),{h:b,l:w}=V.add(this.Hh|0,this.Hl|0,b|0,w|0),this.set(n,i,s,o,a,c,u,l,h,f,p,d,y,v,b,w)}roundClean(){Wt.fill(0),Gt.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};const Ny=ay(()=>new Ry);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ea=BigInt(0),ah=BigInt(1),Ty=BigInt(2);function ta(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ra(t){if(!ta(t))throw new Error("Uint8Array expected")}function Ls(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const jy=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function na(t){ra(t);let e="";for(let r=0;r<t.length;r++)e+=jy[t[r]];return e}function ch(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?ea:BigInt("0x"+t)}const jt={_0:48,_9:57,A:65,F:70,a:97,f:102};function ec(t){if(t>=jt._0&&t<=jt._9)return t-jt._0;if(t>=jt.A&&t<=jt.F)return t-(jt.A-10);if(t>=jt.a&&t<=jt.f)return t-(jt.a-10)}function uh(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=ec(t.charCodeAt(s)),a=ec(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 My(t){return ch(na(t))}function Oi(t){return ra(t),ch(na(Uint8Array.from(t).reverse()))}function lh(t,e){return uh(t.toString(16).padStart(e*2,"0"))}function go(t,e){return lh(t,e).reverse()}function Mt(t,e,r){let n;if(typeof e=="string")try{n=uh(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(ta(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 tc(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];ra(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}const Rs=t=>typeof t=="bigint"&&ea<=t;function Fy(t,e,r){return Rs(t)&&Rs(e)&&Rs(r)&&e<=t&&t<r}function In(t,e,r,n){if(!Fy(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function By(t){let e;for(e=0;t>ea;t>>=ah,e+=1);return e}const Uy=t=>(Ty<<BigInt(t-1))-ah,qy={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"||ta(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 ia(t,e,r={}){const n=(i,s,o)=>{const a=qy[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}function rc(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}}const xe=BigInt(0),ve=BigInt(1),lr=BigInt(2),ky=BigInt(3),yo=BigInt(4),nc=BigInt(5),ic=BigInt(8);function $e(t,e){const r=t%e;return r>=xe?r:e+r}function zy(t,e,r){if(e<xe)throw new Error("invalid exponent, negatives unsupported");if(r<=xe)throw new Error("invalid modulus");if(r===ve)return xe;let n=ve;for(;e>xe;)e&ve&&(n=n*t%r),t=t*t%r,e>>=ve;return n}function $t(t,e,r){let n=t;for(;e-- >xe;)n*=n,n%=r;return n}function sc(t,e){if(t===xe)throw new Error("invert: expected non-zero number");if(e<=xe)throw new Error("invert: expected positive modulus, got "+e);let r=$e(t,e),n=e,i=xe,s=ve;for(;r!==xe;){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 $e(i,e)}function Ky(t){const e=(t-ve)/lr;let r,n,i;for(r=t-ve,n=0;r%lr===xe;r/=lr,n++);for(i=lr;i<t&&zy(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)/yo;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)/lr;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 Hy(t){if(t%yo===ky){const e=(t+ve)/yo;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%ic===nc){const e=(t-nc)/ic;return function(r,n){const i=r.mul(n,lr),s=r.pow(i,e),o=r.mul(n,s),a=r.mul(r.mul(o,lr),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 Ky(t)}const Vy=(t,e)=>($e(t,e)&ve)===ve,Wy=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Gy(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Wy.reduce((n,i)=>(n[i]="function",n),e);return ia(t,r)}function Yy(t,e,r){if(r<xe)throw new Error("invalid exponent, negatives unsupported");if(r===xe)return t.ONE;if(r===ve)return e;let n=t.ONE,i=e;for(;r>xe;)r&ve&&(n=t.mul(n,i)),i=t.sqr(i),r>>=ve;return n}function Jy(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 hh(t,e){const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function fh(t,e,r=!1,n={}){if(t<=xe)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=hh(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:Uy(i),ZERO:xe,ONE:ve,create:c=>$e(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return xe<=c&&c<t},is0:c=>c===xe,isOdd:c=>(c&ve)===ve,neg:c=>$e(-c,t),eql:(c,u)=>c===u,sqr:c=>$e(c*c,t),add:(c,u)=>$e(c+u,t),sub:(c,u)=>$e(c-u,t),mul:(c,u)=>$e(c*u,t),pow:(c,u)=>Yy(a,c,u),div:(c,u)=>$e(c*sc(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>sc(c,t),sqrt:n.sqrt||(c=>(o||(o=Hy(t)),o(a,c))),invertBatch:c=>Jy(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?go(c,s):lh(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?Oi(c):My(c)}});return Object.freeze(a)}const oc=BigInt(0),li=BigInt(1);function Ns(t,e){const r=e.negate();return t?r:e}function dh(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ts(t,e){dh(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1);return{windows:r,windowSize:n}}function Zy(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 Qy(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 js=new WeakMap,ph=new WeakMap;function Ms(t){return ph.get(t)||1}function Xy(t,e){return{constTimeNegate:Ns,hasPrecomputes(r){return Ms(r)!==1},unsafeLadder(r,n,i=t.ZERO){let s=r;for(;n>oc;)n&li&&(i=i.add(s)),s=s.double(),n>>=li;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=Ts(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}=Ts(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+=li);const y=p,v=p+Math.abs(d)-1,b=f%2!==0,w=d<0;d===0?c=c.add(Ns(b,n[y])):a=a.add(Ns(w,n[v]))}return{p:a,f:c}},wNAFUnsafe(r,n,i,s=t.ZERO){const{windows:o,windowSize:a}=Ts(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===oc)break;let p=Number(i&c);if(i>>=l,p>a&&(p-=u,i+=li),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=js.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&js.set(n,i(s))),s},wNAFCached(r,n,i){const s=Ms(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=Ms(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){dh(n,e),ph.set(r,n),js.delete(r)}}}function em(t,e,r,n){if(Zy(r,t),Qy(n,e),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=By(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 tm(t){return Gy(t.Fp),ia(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...hh(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const gt=BigInt(0),Ve=BigInt(1),hi=BigInt(2),rm=BigInt(8),nm={zip215:!0};function im(t){const e=tm(t);return ia(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function sm(t){const e=im(t),{Fp:r,n,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=e,u=hi<<BigInt(a*8)-Ve,l=r.create,h=fh(e.n,e.nBitLength),f=e.uvRatio||((g,m)=>{try{return{isValid:!0,value:r.sqrt(g*r.inv(m))}}catch{return{isValid:!1,value:gt}}}),p=e.adjustScalarBytes||(g=>g),d=e.domain||((g,m,_)=>{if(Ls("phflag",_),m.length||_)throw new Error("Contexts/pre-hash are not supported");return g});function y(g,m){In("coordinate "+g,m,gt,u)}function v(g){if(!(g instanceof E))throw new Error("ExtendedPoint expected")}const b=rc((g,m)=>{const{ex:_,ey:P,ez:$}=g,A=g.is0();m==null&&(m=A?rm:r.inv($));const F=l(_*m),U=l(P*m),z=l($*m);if(A)return{x:gt,y:Ve};if(z!==Ve)throw new Error("invZ was invalid");return{x:F,y:U}}),w=rc(g=>{const{a:m,d:_}=e;if(g.is0())throw new Error("bad point: ZERO");const{ex:P,ey:$,ez:A,et:F}=g,U=l(P*P),z=l($*$),B=l(A*A),H=l(B*B),Y=l(U*m),pe=l(B*l(Y+z)),te=l(H+l(_*l(U*z)));if(pe!==te)throw new Error("bad point: equation left != right (1)");const J=l(P*$),Be=l(A*F);if(J!==Be)throw new Error("bad point: equation left != right (2)");return!0});class E{constructor(m,_,P,$){this.ex=m,this.ey=_,this.ez=P,this.et=$,y("x",m),y("y",_),y("z",P),y("t",$),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(m){if(m instanceof E)throw new Error("extended point not allowed");const{x:_,y:P}=m||{};return y("x",_),y("y",P),new E(_,P,Ve,l(_*P))}static normalizeZ(m){const _=r.invertBatch(m.map(P=>P.ez));return m.map((P,$)=>P.toAffine(_[$])).map(E.fromAffine)}static msm(m,_){return em(E,h,m,_)}_setWindowSize(m){S.setWindowSize(this,m)}assertValidity(){w(this)}equals(m){v(m);const{ex:_,ey:P,ez:$}=this,{ex:A,ey:F,ez:U}=m,z=l(_*U),B=l(A*$),H=l(P*U),Y=l(F*$);return z===B&&H===Y}is0(){return this.equals(E.ZERO)}negate(){return new E(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:m}=e,{ex:_,ey:P,ez:$}=this,A=l(_*_),F=l(P*P),U=l(hi*l($*$)),z=l(m*A),B=_+P,H=l(l(B*B)-A-F),Y=z+F,pe=Y-U,te=z-F,J=l(H*pe),Be=l(Y*te),Le=l(H*te),ke=l(pe*Y);return new E(J,Be,ke,Le)}add(m){v(m);const{a:_,d:P}=e,{ex:$,ey:A,ez:F,et:U}=this,{ex:z,ey:B,ez:H,et:Y}=m;if(_===BigInt(-1)){const xa=l((A-$)*(B+z)),Aa=l((A+$)*(B-z)),Is=l(Aa-xa);if(Is===gt)return this.double();const Ca=l(F*hi*Y),La=l(U*hi*H),Ra=La+Ca,Na=Aa+xa,Ta=La-Ca,Sp=l(Ra*Is),xp=l(Na*Ta),Ap=l(Ra*Ta),Cp=l(Is*Na);return new E(Sp,xp,Cp,Ap)}const pe=l($*z),te=l(A*B),J=l(U*P*Y),Be=l(F*H),Le=l(($+A)*(z+B)-pe-te),ke=Be-J,ot=Be+J,Tt=l(te-_*pe),Sr=l(Le*ke),Ip=l(ot*Tt),Pp=l(Le*Tt),Dp=l(ke*ot);return new E(Sr,Ip,Dp,Pp)}subtract(m){return this.add(m.negate())}wNAF(m){return S.wNAFCached(this,m,E.normalizeZ)}multiply(m){const _=m;In("scalar",_,Ve,n);const{p:P,f:$}=this.wNAF(_);return E.normalizeZ([P,$])[0]}multiplyUnsafe(m,_=E.ZERO){const P=m;return In("scalar",P,gt,n),P===gt?x:this.is0()||P===Ve?this:S.wNAFCachedUnsafe(this,P,E.normalizeZ,_)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return S.unsafeLadder(this,n).is0()}toAffine(m){return b(this,m)}clearCofactor(){const{h:m}=e;return m===Ve?this:this.multiplyUnsafe(m)}static fromHex(m,_=!1){const{d:P,a:$}=e,A=r.BYTES;m=Mt("pointHex",m,A),Ls("zip215",_);const F=m.slice(),U=m[A-1];F[A-1]=U&-129;const z=Oi(F),B=_?u:r.ORDER;In("pointHex.y",z,gt,B);const H=l(z*z),Y=l(H-Ve),pe=l(P*H-$);let{isValid:te,value:J}=f(Y,pe);if(!te)throw new Error("Point.fromHex: invalid y coordinate");const Be=(J&Ve)===Ve,Le=(U&128)!==0;if(!_&&J===gt&&Le)throw new Error("Point.fromHex: x=0 and x_0=1");return Le!==Be&&(J=l(-J)),E.fromAffine({x:J,y:z})}static fromPrivateKey(m){return I(m).point}toRawBytes(){const{x:m,y:_}=this.toAffine(),P=go(_,r.BYTES);return P[P.length-1]|=m&Ve?128:0,P}toHex(){return na(this.toRawBytes())}}E.BASE=new E(e.Gx,e.Gy,Ve,l(e.Gx*e.Gy)),E.ZERO=new E(gt,Ve,Ve,gt);const{BASE:O,ZERO:x}=E,S=Xy(E,a*8);function D(g){return $e(g,n)}function C(g){return D(Oi(g))}function I(g){const m=r.BYTES;g=Mt("private key",g,m);const _=Mt("hashed private key",s(g),2*m),P=p(_.slice(0,m)),$=_.slice(m,2*m),A=C(P),F=O.multiply(A),U=F.toRawBytes();return{head:P,prefix:$,scalar:A,point:F,pointBytes:U}}function q(g){return I(g).pointBytes}function M(g=new Uint8Array,...m){const _=tc(...m);return C(s(d(_,Mt("context",g),!!i)))}function j(g,m,_={}){g=Mt("message",g),i&&(g=i(g));const{prefix:P,scalar:$,pointBytes:A}=I(m),F=M(_.context,P,g),U=O.multiply(F).toRawBytes(),z=M(_.context,U,A,g),B=D(F+z*$);In("signature.s",B,gt,n);const H=tc(U,go(B,r.BYTES));return Mt("result",H,r.BYTES*2)}const k=nm;function L(g,m,_,P=k){const{context:$,zip215:A}=P,F=r.BYTES;g=Mt("signature",g,2*F),m=Mt("message",m),_=Mt("publicKey",_,F),A!==void 0&&Ls("zip215",A),i&&(m=i(m));const U=Oi(g.slice(F,2*F));let z,B,H;try{z=E.fromHex(_,A),B=E.fromHex(g.slice(0,F),A),H=O.multiplyUnsafe(U)}catch{return!1}if(!A&&z.isSmallOrder())return!1;const Y=M($,B.toRawBytes(),z.toRawBytes(),m);return B.add(z.multiplyUnsafe(Y)).subtract(H).clearCofactor().equals(E.ZERO)}return O._setWindowSize(8),{CURVE:e,getPublicKey:q,sign:j,verify:L,ExtendedPoint:E,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>o(r.BYTES),precompute(g=8,m=E.BASE){return m._setWindowSize(g),m.multiply(BigInt(3)),m}}}}BigInt(0),BigInt(1);const sa=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),ac=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const om=BigInt(1),cc=BigInt(2);BigInt(3);const am=BigInt(5),cm=BigInt(8);function um(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=sa,o=t*t%s*t%s,a=$t(o,cc,s)*o%s,c=$t(a,om,s)*t%s,u=$t(c,am,s)*c%s,l=$t(u,e,s)*u%s,h=$t(l,r,s)*l%s,f=$t(h,n,s)*h%s,p=$t(f,i,s)*f%s,d=$t(p,i,s)*f%s,y=$t(d,e,s)*u%s;return{pow_p_5_8:$t(y,cc,s)*t%s,b2:o}}function lm(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function hm(t,e){const r=sa,n=$e(e*e*e,r),i=$e(n*n*e,r),s=um(t*i).pow_p_5_8;let o=$e(t*n*s,r);const a=$e(e*o*o,r),c=o,u=$e(o*ac,r),l=a===t,h=a===$e(-t,r),f=a===$e(-t*ac,r);return l&&(o=c),(h||f)&&(o=u),Vy(o,r)&&(o=$e(-o,r)),{isValid:l||h,value:o}}const fm=fh(sa,void 0,!0),dm={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:fm,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:cm,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Ny,randomBytes:sh,adjustScalarBytes:lm,uvRatio:hm},gh=sm(dm),pm="EdDSA",gm="JWT",qi=".",ts="base64url",yh="utf8",mh="utf8",ym=":",mm="did",vm="key",uc="base58btc",wm="z",bm="K36",Em=32;function oa(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function vh(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?oa(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function wh(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const r=vh(e);let n=0;for(const i of t)r.set(i,n),n+=i.length;return oa(r)}function _m(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,v=0,b=0,w=d.length;b!==w&&d[b]===0;)b++,y++;for(var E=(w-b)*l+1>>>0,O=new Uint8Array(E);b!==w;){for(var x=d[b],S=0,D=E-1;(x!==0||S<v)&&D!==-1;D--,S++)x+=256*O[D]>>>0,O[D]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");v=S,b++}for(var C=E-v;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 v=0,b=0;d[y]===c;)v++,y++;for(var w=(d.length-y)*u+1>>>0,E=new Uint8Array(w);d[y];){var O=r[d.charCodeAt(y)];if(O===255)return;for(var x=0,S=w-1;(O!==0||x<b)&&S!==-1;S--,x++)O+=a*E[S]>>>0,E[S]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");b=x,y++}if(d[y]!==" "){for(var D=w-b;D!==w&&E[D]===0;)D++;for(var C=new Uint8Array(v+(w-D)),I=v;D!==w;)C[I++]=E[D++];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 $m=_m,Om=$m;const bh=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")},Im=t=>new TextEncoder().encode(t),Pm=t=>new TextDecoder().decode(t);let Dm=class{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")}},Sm=class{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 Eh(this,e)}},xm=class{constructor(e){this.decoders=e}or(e){return Eh(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 Eh=(t,e)=>new xm({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let Am=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new Dm(e,r,n),this.decoder=new Sm(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const rs=({name:t,prefix:e,encode:r,decode:n})=>new Am(t,e,r,n),Qn=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=Om(r,e);return rs({prefix:t,name:e,encode:n,decode:s=>bh(i(s))})},Cm=(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},Lm=(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},je=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>rs({prefix:e,name:t,encode(i){return Lm(i,n,r)},decode(i){return Cm(i,n,r,t)}}),Rm=rs({prefix:"\0",name:"identity",encode:t=>Pm(t),decode:t=>Im(t)});var Nm=Object.freeze({__proto__:null,identity:Rm});const Tm=je({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var jm=Object.freeze({__proto__:null,base2:Tm});const Mm=je({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Fm=Object.freeze({__proto__:null,base8:Mm});const Bm=Qn({prefix:"9",name:"base10",alphabet:"0123456789"});var Um=Object.freeze({__proto__:null,base10:Bm});const qm=je({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),km=je({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var zm=Object.freeze({__proto__:null,base16:qm,base16upper:km});const Km=je({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Hm=je({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Vm=je({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Wm=je({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Gm=je({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ym=je({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Jm=je({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Zm=je({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Qm=je({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Xm=Object.freeze({__proto__:null,base32:Km,base32upper:Hm,base32pad:Vm,base32padupper:Wm,base32hex:Gm,base32hexupper:Ym,base32hexpad:Jm,base32hexpadupper:Zm,base32z:Qm});const ev=Qn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),tv=Qn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var rv=Object.freeze({__proto__:null,base36:ev,base36upper:tv});const nv=Qn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),iv=Qn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var sv=Object.freeze({__proto__:null,base58btc:nv,base58flickr:iv});const ov=je({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),av=je({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cv=je({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),uv=je({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var lv=Object.freeze({__proto__:null,base64:ov,base64pad:av,base64url:cv,base64urlpad:uv});const _h=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),hv=_h.reduce((t,e,r)=>(t[r]=e,t),[]),fv=_h.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function dv(t){return t.reduce((e,r)=>(e+=hv[r],e),"")}function pv(t){const e=[];for(const r of t){const n=fv[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const gv=rs({prefix:"🚀",name:"base256emoji",encode:dv,decode:pv});var yv=Object.freeze({__proto__:null,base256emoji:gv}),mv=$h,lc=128,vv=127,wv=~vv,bv=Math.pow(2,31);function $h(t,e,r){e=e||[],r=r||0;for(var n=r;t>=bv;)e[r++]=t&255|lc,t/=128;for(;t&wv;)e[r++]=t&255|lc,t>>>=7;return e[r]=t|0,$h.bytes=r-n+1,e}var Ev=mo,_v=128,hc=127;function mo(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw mo.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&hc)<<i:(o&hc)*Math.pow(2,i),i+=7}while(o>=_v);return mo.bytes=s-n,r}var $v=Math.pow(2,7),Ov=Math.pow(2,14),Iv=Math.pow(2,21),Pv=Math.pow(2,28),Dv=Math.pow(2,35),Sv=Math.pow(2,42),xv=Math.pow(2,49),Av=Math.pow(2,56),Cv=Math.pow(2,63),Lv=function(t){return t<$v?1:t<Ov?2:t<Iv?3:t<Pv?4:t<Dv?5:t<Sv?6:t<xv?7:t<Av?8:t<Cv?9:10},Rv={encode:mv,decode:Ev,encodingLength:Lv},Oh=Rv;const fc=(t,e,r=0)=>(Oh.encode(t,e,r),e),dc=t=>Oh.encodingLength(t),vo=(t,e)=>{const r=e.byteLength,n=dc(t),i=n+dc(r),s=new Uint8Array(i+r);return fc(t,s,0),fc(r,s,n),s.set(e,i),new Nv(t,r,e,s)};let Nv=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};const Ih=({name:t,code:e,encode:r})=>new Tv(t,e,r);let Tv=class{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?vo(this.code,r):r.then(n=>vo(this.code,n))}else throw Error("Unknown type, must be binary type")}};const Ph=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),jv=Ih({name:"sha2-256",code:18,encode:Ph("SHA-256")}),Mv=Ih({name:"sha2-512",code:19,encode:Ph("SHA-512")});var Fv=Object.freeze({__proto__:null,sha256:jv,sha512:Mv});const Dh=0,Bv="identity",Sh=bh,Uv=t=>vo(Dh,Sh(t)),qv={code:Dh,name:Bv,encode:Sh,digest:Uv};var kv=Object.freeze({__proto__:null,identity:qv});new TextEncoder,new TextDecoder;const pc={...Nm,...jm,...Fm,...Um,...zm,...Xm,...rv,...sv,...lv,...yv};({...Fv,...kv});function xh(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const gc=xh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Fs=xh("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=vh(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Ah={utf8:gc,"utf-8":gc,hex:pc.base16,latin1:Fs,ascii:Fs,binary:Fs,...pc};function ns(t,e="utf8"){const r=Ah[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)}function mn(t,e="utf8"){const r=Ah[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?oa(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function yc(t){return mr(ns(mn(t,ts),yh))}function ki(t){return ns(mn(Vt(t),yh),ts)}function Ch(t){const e=mn(bm,uc),r=wm+ns(wh([e,t]),uc);return[mm,vm,r].join(ym)}function zv(t){return ns(t,ts)}function Kv(t){return mn(t,ts)}function Hv(t){return mn([ki(t.header),ki(t.payload)].join(qi),mh)}function Vv(t){return[ki(t.header),ki(t.payload),zv(t.signature)].join(qi)}function wo(t){const e=t.split(qi),r=yc(e[0]),n=yc(e[1]),i=Kv(e[2]),s=mn(e.slice(0,2).join(qi),mh);return{header:r,payload:n,signature:i,data:s}}function mc(t=sh(Em)){const e=gh.getPublicKey(t);return{secretKey:wh([t,e]),publicKey:e}}async function Wv(t,e,r,n,i=N.fromMiliseconds(Date.now())){const s={alg:pm,typ:gm},o=Ch(n.publicKey),a=i+r,c={iss:o,sub:t,aud:e,iat:i,exp:a},u=Hv({header:s,payload:c}),l=gh.sign(u,n.secretKey.slice(0,32));return Vv({header:s,payload:c,signature:l})}var vc=function(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))},Gv=function(){function t(e,r,n){this.name=e,this.version=r,this.os=n,this.type="browser"}return t}(),Yv=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=ft.platform}return t}(),Jv=function(){function t(e,r,n,i){this.name=e,this.version=r,this.os=n,this.bot=i,this.type="bot-device"}return t}(),Zv=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),Qv=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),Xv=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,ew=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,wc=3,tw=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",Xv]],bc=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function rw(t){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Qv:typeof navigator<"u"?iw(navigator.userAgent):ow()}function nw(t){return t!==""&&tw.reduce(function(e,r){var n=r[0],i=r[1];if(e)return e;var s=i.exec(t);return!!s&&[n,s]},!1)}function iw(t){var e=nw(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new Zv;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length<wc&&(i=vc(vc([],i,!0),aw(wc-i.length),!0)):i=[];var s=i.join("."),o=sw(t),a=ew.exec(t);return a&&a[1]?new Jv(r,s,o,a[1]):new Gv(r,s,o)}function sw(t){for(var e=0,r=bc.length;e<r;e++){var n=bc[e],i=n[0],s=n[1],o=s.exec(t);if(o)return i}return null}function ow(){var t=typeof ft<"u"&&ft.version;return t?new Yv(ft.version.slice(1)):null}function aw(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var ye={};Object.defineProperty(ye,"__esModule",{value:!0});ye.getLocalStorage=ye.getLocalStorageOrThrow=ye.getCrypto=ye.getCryptoOrThrow=Lh=ye.getLocation=ye.getLocationOrThrow=aa=ye.getNavigator=ye.getNavigatorOrThrow=vr=ye.getDocument=ye.getDocumentOrThrow=ye.getFromWindowOrThrow=ye.getFromWindow=void 0;function Or(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}ye.getFromWindow=Or;function vn(t){const e=Or(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}ye.getFromWindowOrThrow=vn;function cw(){return vn("document")}ye.getDocumentOrThrow=cw;function uw(){return Or("document")}var vr=ye.getDocument=uw;function lw(){return vn("navigator")}ye.getNavigatorOrThrow=lw;function hw(){return Or("navigator")}var aa=ye.getNavigator=hw;function fw(){return vn("location")}ye.getLocationOrThrow=fw;function dw(){return Or("location")}var Lh=ye.getLocation=dw;function pw(){return vn("crypto")}ye.getCryptoOrThrow=pw;function gw(){return Or("crypto")}ye.getCrypto=gw;function yw(){return vn("localStorage")}ye.getLocalStorageOrThrow=yw;function mw(){return Or("localStorage")}ye.getLocalStorage=mw;var ca={};Object.defineProperty(ca,"__esModule",{value:!0});var Rh=ca.getWindowMetadata=void 0;const Ec=ye;function vw(){let t,e;try{t=Ec.getDocumentOrThrow(),e=Ec.getLocationOrThrow()}catch{return null}function r(){const h=t.getElementsByTagName("link"),f=[];for(let p=0;p<h.length;p++){const d=h[p],y=d.getAttribute("rel");if(y&&y.toLowerCase().indexOf("icon")>-1){const v=d.getAttribute("href");if(v)if(v.toLowerCase().indexOf("https:")===-1&&v.toLowerCase().indexOf("http:")===-1&&v.indexOf("//")!==0){let b=e.protocol+"//"+e.host;if(v.indexOf("/")===0)b+=v;else{const w=e.pathname.split("/");w.pop();const E=w.join("/");b+=E+"/"+v}f.push(b)}else if(v.indexOf("//")===0){const b=e.protocol+v;f.push(b)}else f.push(v)}}return f}function n(...h){const f=t.getElementsByTagName("meta");for(let p=0;p<f.length;p++){const d=f[p],y=["itemprop","property","name"].map(v=>d.getAttribute(v)).filter(v=>v?h.includes(v):!1);if(y.length&&y){const v=d.getAttribute("content");if(v)return v}}return""}function i(){let h=n("name","og:site_name","og:title","twitter:title");return h||(h=t.title),h}function s(){return n("description","og:description","twitter:description","keywords")}const o=i(),a=s(),c=e.origin,u=r();return{description:a,url:c,icons:u,name:o}}Rh=ca.getWindowMetadata=vw;function ww(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,v=0,b=0,w=d.length;b!==w&&d[b]===0;)b++,y++;for(var E=(w-b)*l+1>>>0,O=new Uint8Array(E);b!==w;){for(var x=d[b],S=0,D=E-1;(x!==0||S<v)&&D!==-1;D--,S++)x+=256*O[D]>>>0,O[D]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");v=S,b++}for(var C=E-v;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 v=0,b=0;d[y]===c;)v++,y++;for(var w=(d.length-y)*u+1>>>0,E=new Uint8Array(w);d[y];){var O=r[d.charCodeAt(y)];if(O===255)return;for(var x=0,S=w-1;(O!==0||x<b)&&S!==-1;S--,x++)O+=a*E[S]>>>0,E[S]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");b=x,y++}if(d[y]!==" "){for(var D=w-b;D!==w&&E[D]===0;)D++;for(var C=new Uint8Array(v+(w-D)),I=v;D!==w;)C[I++]=E[D++];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 bw=ww,Ew=bw;const _w=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")},$w=t=>new TextEncoder().encode(t),Ow=t=>new TextDecoder().decode(t);class Iw{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 Pw{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 Nh(this,e)}}class Dw{constructor(e){this.decoders=e}or(e){return Nh(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 Nh=(t,e)=>new Dw({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class Sw{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new Iw(e,r,n),this.decoder=new Pw(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const is=({name:t,prefix:e,encode:r,decode:n})=>new Sw(t,e,r,n),Xn=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=Ew(r,e);return is({prefix:t,name:e,encode:n,decode:s=>_w(i(s))})},xw=(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},Aw=(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},Me=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>is({prefix:e,name:t,encode(i){return Aw(i,n,r)},decode(i){return xw(i,n,r,t)}}),Cw=is({prefix:"\0",name:"identity",encode:t=>Ow(t),decode:t=>$w(t)}),Lw=Object.freeze(Object.defineProperty({__proto__:null,identity:Cw},Symbol.toStringTag,{value:"Module"})),Rw=Me({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Nw=Object.freeze(Object.defineProperty({__proto__:null,base2:Rw},Symbol.toStringTag,{value:"Module"})),Tw=Me({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),jw=Object.freeze(Object.defineProperty({__proto__:null,base8:Tw},Symbol.toStringTag,{value:"Module"})),Mw=Xn({prefix:"9",name:"base10",alphabet:"0123456789"}),Fw=Object.freeze(Object.defineProperty({__proto__:null,base10:Mw},Symbol.toStringTag,{value:"Module"})),Bw=Me({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Uw=Me({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),qw=Object.freeze(Object.defineProperty({__proto__:null,base16:Bw,base16upper:Uw},Symbol.toStringTag,{value:"Module"})),kw=Me({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),zw=Me({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Kw=Me({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Hw=Me({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Vw=Me({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ww=Me({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Gw=Me({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Yw=Me({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Jw=Me({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Zw=Object.freeze(Object.defineProperty({__proto__:null,base32:kw,base32hex:Vw,base32hexpad:Gw,base32hexpadupper:Yw,base32hexupper:Ww,base32pad:Kw,base32padupper:Hw,base32upper:zw,base32z:Jw},Symbol.toStringTag,{value:"Module"})),Qw=Xn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Xw=Xn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),eb=Object.freeze(Object.defineProperty({__proto__:null,base36:Qw,base36upper:Xw},Symbol.toStringTag,{value:"Module"})),tb=Xn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),rb=Xn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),nb=Object.freeze(Object.defineProperty({__proto__:null,base58btc:tb,base58flickr:rb},Symbol.toStringTag,{value:"Module"})),ib=Me({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),sb=Me({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ob=Me({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ab=Me({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),cb=Object.freeze(Object.defineProperty({__proto__:null,base64:ib,base64pad:sb,base64url:ob,base64urlpad:ab},Symbol.toStringTag,{value:"Module"})),Th=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ub=Th.reduce((t,e,r)=>(t[r]=e,t),[]),lb=Th.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function hb(t){return t.reduce((e,r)=>(e+=ub[r],e),"")}function fb(t){const e=[];for(const r of t){const n=lb[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const db=is({prefix:"🚀",name:"base256emoji",encode:hb,decode:fb}),pb=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:db},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const _c={...Lw,...Nw,...jw,...Fw,...qw,...Zw,...eb,...nb,...cb,...pb},gb={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}};var ua={exports:{}},en=typeof Reflect=="object"?Reflect:null,$c=en&&typeof en.apply=="function"?en.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Ii;en&&typeof en.ownKeys=="function"?Ii=en.ownKeys:Object.getOwnPropertySymbols?Ii=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Ii=function(e){return Object.getOwnPropertyNames(e)};function yb(t){console&&console.warn&&console.warn(t)}var jh=Number.isNaN||function(e){return e!==e};function ie(){ie.init.call(this)}ua.exports=ie;ua.exports.once=bb;ie.EventEmitter=ie;ie.prototype._events=void 0;ie.prototype._eventsCount=0;ie.prototype._maxListeners=void 0;var Oc=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(ie,"defaultMaxListeners",{enumerable:!0,get:function(){return Oc},set:function(t){if(typeof t!="number"||t<0||jh(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Oc=t}});ie.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};ie.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||jh(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 Mh(t){return t._maxListeners===void 0?ie.defaultMaxListeners:t._maxListeners}ie.prototype.getMaxListeners=function(){return Mh(this)};ie.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")$c(c,this,r);else for(var u=c.length,l=kh(c,u),n=0;n<u;++n)$c(l[n],this,r);return!0};function Fh(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=Mh(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,yb(a)}return t}ie.prototype.addListener=function(e,r){return Fh(this,e,r,!1)};ie.prototype.on=ie.prototype.addListener;ie.prototype.prependListener=function(e,r){return Fh(this,e,r,!0)};function mb(){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 Bh(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=mb.bind(n);return i.listener=r,n.wrapFn=i,i}ie.prototype.once=function(e,r){return ss(r),this.on(e,Bh(this,e,r)),this};ie.prototype.prependOnceListener=function(e,r){return ss(r),this.prependListener(e,Bh(this,e,r)),this};ie.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():vb(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};ie.prototype.off=ie.prototype.removeListener;ie.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 Uh(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?wb(i):kh(i,i.length)}ie.prototype.listeners=function(e){return Uh(this,e,!0)};ie.prototype.rawListeners=function(e){return Uh(this,e,!1)};ie.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):qh.call(t,e)};ie.prototype.listenerCount=qh;function qh(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}ie.prototype.eventNames=function(){return this._eventsCount>0?Ii(this._events):[]};function kh(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function vb(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function wb(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function bb(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))}zh(t,e,s,{once:!0}),e!=="error"&&Eb(t,i,{once:!0})})}function Eb(t,e,r){typeof t.on=="function"&&zh(t,"error",e,r)}function zh(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 _b=ua.exports;const $b="PARSE_ERROR",Ob="INVALID_REQUEST",Ib="METHOD_NOT_FOUND",Pb="INVALID_PARAMS",Kh="INTERNAL_ERROR",la="SERVER_ERROR",Db=[-32700,-32600,-32601,-32602,-32603],Tn={[$b]:{code:-32700,message:"Parse error"},[Ob]:{code:-32600,message:"Invalid Request"},[Ib]:{code:-32601,message:"Method not found"},[Pb]:{code:-32602,message:"Invalid params"},[Kh]:{code:-32603,message:"Internal error"},[la]:{code:-32e3,message:"Server error"}},Hh=la;function Sb(t){return Db.includes(t)}function Ic(t){return Object.keys(Tn).includes(t)?Tn[t]:Tn[Hh]}function xb(t){const e=Object.values(Tn).find(r=>r.code===t);return e||Tn[Hh]}function Vh(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var Wh={};/*! *****************************************************************************
|
|
15
|
+
***************************************************************************** */var _o=function(t,e){return _o=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])},_o(t,e)};function Sg(t,e){_o(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var $o=function(){return $o=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},$o.apply(this,arguments)};function Dg(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 xg(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 Ag(t,e){return function(r,n){e(r,n,t)}}function Cg(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Lg(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 Rg(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 Tg(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function Ng(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Oo(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 _h(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 jg(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(_h(arguments[e]));return t}function Mg(){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 Vn(t){return this instanceof Vn?(this.v=t,this):new Vn(t)}function Bg(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 Vn?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 Ug(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:Vn(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function Fg(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 Oo=="function"?Oo(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 kg(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function qg(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 zg(t){return t&&t.__esModule?t:{default:t}}function Hg(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function Kg(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 Vg=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return $o},__asyncDelegator:Ug,__asyncGenerator:Bg,__asyncValues:Fg,__await:Vn,__awaiter:Lg,__classPrivateFieldGet:Hg,__classPrivateFieldSet:Kg,__createBinding:Tg,__decorate:xg,__exportStar:Ng,__extends:Sg,__generator:Rg,__importDefault:zg,__importStar:qg,__makeTemplateObject:kg,__metadata:Cg,__param:Ag,__read:_h,__rest:Dg,__spread:jg,__spreadArrays:Mg,__values:Oo},Symbol.toStringTag,{value:"Module"})),as=fh(Vg);var js={},Dn={},ec;function Wg(){if(ec)return Dn;ec=1,Object.defineProperty(Dn,"__esModule",{value:!0}),Dn.delay=void 0;function t(e){return new Promise(r=>{setTimeout(()=>{r(!0)},e)})}return Dn.delay=t,Dn}var sr={},Ms={},or={},tc;function Gg(){return tc||(tc=1,Object.defineProperty(or,"__esModule",{value:!0}),or.ONE_THOUSAND=or.ONE_HUNDRED=void 0,or.ONE_HUNDRED=100,or.ONE_THOUSAND=1e3),or}var Bs={},rc;function Yg(){return rc||(rc=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ONE_YEAR=t.FOUR_WEEKS=t.THREE_WEEKS=t.TWO_WEEKS=t.ONE_WEEK=t.THIRTY_DAYS=t.SEVEN_DAYS=t.FIVE_DAYS=t.THREE_DAYS=t.ONE_DAY=t.TWENTY_FOUR_HOURS=t.TWELVE_HOURS=t.SIX_HOURS=t.THREE_HOURS=t.ONE_HOUR=t.SIXTY_MINUTES=t.THIRTY_MINUTES=t.TEN_MINUTES=t.FIVE_MINUTES=t.ONE_MINUTE=t.SIXTY_SECONDS=t.THIRTY_SECONDS=t.TEN_SECONDS=t.FIVE_SECONDS=t.ONE_SECOND=void 0,t.ONE_SECOND=1,t.FIVE_SECONDS=5,t.TEN_SECONDS=10,t.THIRTY_SECONDS=30,t.SIXTY_SECONDS=60,t.ONE_MINUTE=t.SIXTY_SECONDS,t.FIVE_MINUTES=t.ONE_MINUTE*5,t.TEN_MINUTES=t.ONE_MINUTE*10,t.THIRTY_MINUTES=t.ONE_MINUTE*30,t.SIXTY_MINUTES=t.ONE_MINUTE*60,t.ONE_HOUR=t.SIXTY_MINUTES,t.THREE_HOURS=t.ONE_HOUR*3,t.SIX_HOURS=t.ONE_HOUR*6,t.TWELVE_HOURS=t.ONE_HOUR*12,t.TWENTY_FOUR_HOURS=t.ONE_HOUR*24,t.ONE_DAY=t.TWENTY_FOUR_HOURS,t.THREE_DAYS=t.ONE_DAY*3,t.FIVE_DAYS=t.ONE_DAY*5,t.SEVEN_DAYS=t.ONE_DAY*7,t.THIRTY_DAYS=t.ONE_DAY*30,t.ONE_WEEK=t.SEVEN_DAYS,t.TWO_WEEKS=t.ONE_WEEK*2,t.THREE_WEEKS=t.ONE_WEEK*3,t.FOUR_WEEKS=t.ONE_WEEK*4,t.ONE_YEAR=t.ONE_DAY*365}(Bs)),Bs}var nc;function $h(){return nc||(nc=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=as;e.__exportStar(Gg(),t),e.__exportStar(Yg(),t)}(Ms)),Ms}var ic;function Jg(){if(ic)return sr;ic=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.fromMiliseconds=sr.toMiliseconds=void 0;const t=$h();function e(n){return n*t.ONE_THOUSAND}sr.toMiliseconds=e;function r(n){return Math.floor(n/t.ONE_THOUSAND)}return sr.fromMiliseconds=r,sr}var sc;function Zg(){return sc||(sc=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=as;e.__exportStar(Wg(),t),e.__exportStar(Jg(),t)}(js)),js}var Cr={},oc;function Qg(){if(oc)return Cr;oc=1,Object.defineProperty(Cr,"__esModule",{value:!0}),Cr.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(r){if(this.timestamps.has(r))throw new Error(`Watch already started for label: ${r}`);this.timestamps.set(r,{started:Date.now()})}stop(r){const n=this.get(r);if(typeof n.elapsed<"u")throw new Error(`Watch already stopped for label: ${r}`);const i=Date.now()-n.started;this.timestamps.set(r,{started:n.started,elapsed:i})}get(r){const n=this.timestamps.get(r);if(typeof n>"u")throw new Error(`No timestamp found for label: ${r}`);return n}elapsed(r){const n=this.get(r);return n.elapsed||Date.now()-n.started}}return Cr.Watch=t,Cr.default=t,Cr}var Us={},xn={},ac;function Xg(){if(ac)return xn;ac=1,Object.defineProperty(xn,"__esModule",{value:!0}),xn.IWatch=void 0;class t{}return xn.IWatch=t,xn}var cc;function ey(){return cc||(cc=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),as.__exportStar(Xg(),t)}(Us)),Us}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=as;e.__exportStar(Zg(),t),e.__exportStar(Qg(),t),e.__exportStar(ey(),t),e.__exportStar($h(),t)})(T);class Or{}let ty=class extends Or{constructor(e){super()}};const uc=T.FIVE_SECONDS,Ir={pulse:"heartbeat_pulse"};let ry=class Oh extends ty{constructor(e){super(e),this.events=new Pg.EventEmitter,this.interval=uc,this.interval=e?.interval||uc}static async init(e){const r=new Oh(e);return await r.init(),r}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}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 initialize(){this.intervalRef=setInterval(()=>this.pulse(),T.toMiliseconds(this.interval))}pulse(){this.events.emit(Ir.pulse)}};const ny=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,iy=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,sy=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function oy(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){ay(t);return}return e}function ay(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function pi(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const r=t.trim();if(r.length<=9)switch(r.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!sy.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(ny.test(t)||iy.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,oy)}return JSON.parse(t)}catch(n){if(e.strict)throw n;return t}}const cy=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),uy=t=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(n,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)};function wr(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return uy(t)}catch{return t}}function Wt(t){return typeof t=="string"?t:cy(t)||""}function ly(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var hy=fy;function fy(t,e,r){var n=r&&r.stringify||ly,i=1;if(typeof t=="object"&&t!==null){var s=e.length+i;if(s===1)return t;var o=new Array(s);o[0]=n(t);for(var a=1;a<s;a++)o[a]=n(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var u="",l=1-i,h=-1,f=t&&t.length||0,p=0;p<f;){if(t.charCodeAt(p)===37&&p+1<f){switch(h=h>-1?h:0,t.charCodeAt(p+1)){case 100:case 102:if(l>=c||e[l]==null)break;h<p&&(u+=t.slice(h,p)),u+=Number(e[l]),h=p+2,p++;break;case 105:if(l>=c||e[l]==null)break;h<p&&(u+=t.slice(h,p)),u+=Math.floor(Number(e[l])),h=p+2,p++;break;case 79:case 111:case 106:if(l>=c||e[l]===void 0)break;h<p&&(u+=t.slice(h,p));var d=typeof e[l];if(d==="string"){u+="'"+e[l]+"'",h=p+2,p++;break}if(d==="function"){u+=e[l].name||"<anonymous>",h=p+2,p++;break}u+=n(e[l]),h=p+2,p++;break;case 115:if(l>=c)break;h<p&&(u+=t.slice(h,p)),u+=String(e[l]),h=p+2,p++;break;case 37:h<p&&(u+=t.slice(h,p)),u+="%",h=p+2,p++,l--;break}++l}++p}return h===-1?t:(h<f&&(u+=t.slice(h)),u)}const lc=hy;var Zr=Lt;const Wn=_y().console||{},dy={mapHttpRequest:gi,mapHttpResponse:gi,wrapRequestSerializer:Fs,wrapResponseSerializer:Fs,wrapErrorSerializer:Fs,req:gi,res:gi,err:wy};function py(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function Lt(t){t=t||{},t.browser=t.browser||{};const e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const r=t.browser.write||Wn;t.browser.write&&(t.browser.asObject=!0);const n=t.serializers||{},i=py(t.browser.serialize,n);let s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);const o=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),t.enabled===!1&&(t.level="silent");const a=t.level||"info",c=Object.create(r);c.log||(c.log=Gn),Object.defineProperty(c,"levelVal",{get:l}),Object.defineProperty(c,"level",{get:h,set:f});const u={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:vy(t)};c.levels=Lt.levels,c.level=a,c.setMaxListeners=c.getMaxListeners=c.emit=c.addListener=c.on=c.prependListener=c.once=c.prependOnceListener=c.removeListener=c.removeAllListeners=c.listeners=c.listenerCount=c.eventNames=c.write=c.flush=Gn,c.serializers=n,c._serialize=i,c._stdErrSerialize=s,c.child=p,e&&(c._logEvent=Io());function l(){return this.level==="silent"?1/0:this.levels.values[this.level]}function h(){return this._level}function f(d){if(d!=="silent"&&!this.levels.values[d])throw Error("unknown level "+d);this._level=d,Lr(u,c,"error","log"),Lr(u,c,"fatal","error"),Lr(u,c,"warn","error"),Lr(u,c,"info","log"),Lr(u,c,"debug","log"),Lr(u,c,"trace","log")}function p(d,y){if(!d)throw new Error("missing bindings for child Pino");y=y||{},i&&d.serializers&&(y.serializers=d.serializers);const w=y.serializers;if(i&&w){var b=Object.assign({},n,w),v=t.browser.serialize===!0?Object.keys(b):i;delete d.serializers,cs([d],v,b,this._stdErrSerialize)}function E(O){this._childLevel=(O._childLevel|0)+1,this.error=Rr(O,d,"error"),this.fatal=Rr(O,d,"fatal"),this.warn=Rr(O,d,"warn"),this.info=Rr(O,d,"info"),this.debug=Rr(O,d,"debug"),this.trace=Rr(O,d,"trace"),b&&(this.serializers=b,this._serialize=v),e&&(this._logEvent=Io([].concat(O._logEvent.bindings,d)))}return E.prototype=this,new E(this)}return c}Lt.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}};Lt.stdSerializers=dy;Lt.stdTimeFunctions=Object.assign({},{nullTime:Ih,epochTime:Ph,unixTime:by,isoTime:Ey});function Lr(t,e,r,n){const i=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?Gn:i[r]?i[r]:Wn[r]||Wn[n]||Gn,gy(t,e,r)}function gy(t,e,r){!t.transmit&&e[r]===Gn||(e[r]=function(n){return function(){const s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===Wn?Wn:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(t.serialize&&!t.asObject&&cs(o,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?n.call(a,yy(this,r,o,s)):n.apply(a,o),t.transmit){const u=t.transmit.level||e.level,l=Lt.levels.values[u],h=Lt.levels.values[r];if(h<l)return;my(this,{ts:s,methodLevel:r,methodValue:h,transmitLevel:u,transmitValue:Lt.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},o)}}}(e[r]))}function yy(t,e,r,n){t._serialize&&cs(r,t._serialize,t.serializers,t._stdErrSerialize);const i=r.slice();let s=i[0];const o={};n&&(o.time=n),o.level=Lt.levels.values[e];let a=(t._childLevel|0)+1;if(a<1&&(a=1),s!==null&&typeof s=="object"){for(;a--&&typeof i[0]=="object";)Object.assign(o,i.shift());s=i.length?lc(i.shift(),i):void 0}else typeof s=="string"&&(s=lc(i.shift(),i));return s!==void 0&&(o.msg=s),o}function cs(t,e,r,n){for(const i in t)if(n&&t[i]instanceof Error)t[i]=Lt.stdSerializers.err(t[i]);else if(typeof t[i]=="object"&&!Array.isArray(t[i]))for(const s in t[i])e&&e.indexOf(s)>-1&&s in r&&(t[i][s]=r[s](t[i][s]))}function Rr(t,e,r){return function(){const n=new Array(1+arguments.length);n[0]=e;for(var i=1;i<n.length;i++)n[i]=arguments[i-1];return t[r].apply(this,n)}}function my(t,e,r){const n=e.send,i=e.ts,s=e.methodLevel,o=e.methodValue,a=e.val,c=t._logEvent.bindings;cs(r,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=i,t._logEvent.messages=r.filter(function(u){return c.indexOf(u)===-1}),t._logEvent.level.label=s,t._logEvent.level.value=o,n(s,t._logEvent,a),t._logEvent=Io(c)}function Io(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function wy(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const r in t)e[r]===void 0&&(e[r]=t[r]);return e}function vy(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?Ih:Ph}function gi(){return{}}function Fs(t){return t}function Gn(){}function Ih(){return!1}function Ph(){return Date.now()}function by(){return Math.round(Date.now()/1e3)}function Ey(){return new Date(Date.now()).toISOString()}function _y(){function t(e){return typeof e<"u"&&e}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return t(self)||t(window)||t(this)||{}}}const ni=ri(Zr),$y={level:"info"},ii="custom_context",da=1e3*1024;let Oy=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},hc=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const r=new Oy(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let r=this.head;for(;r!==null;)e.push(r.value),r=r.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const r=e.value;return e=e.next,{done:!1,value:r}}}}},Sh=class{constructor(e,r=da){this.level=e??"error",this.levelValue=Zr.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new hc(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===Zr.levels.values.error?console.error(e):r===Zr.levels.values.warn?console.warn(e):r===Zr.levels.values.debug?console.debug(e):r===Zr.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Wt({timestamp:new Date().toISOString(),log:e}));const r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new hc(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const r=this.getLogArray();return r.push(Wt({extraMetadata:e})),new Blob(r,{type:"application/json"})}},Iy=class{constructor(e,r=da){this.baseChunkLogger=new Sh(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const r=URL.createObjectURL(this.logsToBlob(e)),n=document.createElement("a");n.href=r,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}},Py=class{constructor(e,r=da){this.baseChunkLogger=new Sh(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var Sy=Object.defineProperty,Dy=Object.defineProperties,xy=Object.getOwnPropertyDescriptors,fc=Object.getOwnPropertySymbols,Ay=Object.prototype.hasOwnProperty,Cy=Object.prototype.propertyIsEnumerable,dc=(t,e,r)=>e in t?Sy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wi=(t,e)=>{for(var r in e||(e={}))Ay.call(e,r)&&dc(t,r,e[r]);if(fc)for(var r of fc(e))Cy.call(e,r)&&dc(t,r,e[r]);return t},Gi=(t,e)=>Dy(t,xy(e));function us(t){return Gi(Wi({},t),{level:t?.level||$y.level})}function Ly(t,e=ii){return t[e]||""}function Ry(t,e,r=ii){return t[r]=e,t}function Qe(t,e=ii){let r="";return typeof t.bindings>"u"?r=Ly(t,e):r=t.bindings().context||"",r}function Ty(t,e,r=ii){const n=Qe(t,r);return n.trim()?`${n}/${e}`:e}function Ke(t,e,r=ii){const n=Ty(t,e,r),i=t.child({context:n});return Ry(i,n,r)}function Ny(t){var e,r;const n=new Iy((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:ni(Gi(Wi({},t.opts),{level:"trace",browser:Gi(Wi({},(r=t.opts)==null?void 0:r.browser),{write:i=>n.write(i)})})),chunkLoggerController:n}}function jy(t){var e;const r=new Py((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:ni(Gi(Wi({},t.opts),{level:"trace"}),r),chunkLoggerController:r}}function My(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?Ny(t):jy(t)}function By(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Dh(t,...e){if(!By(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 pc(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 Uy(t,e){Dh(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const Tr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ks=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function Fy(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function xh(t){return typeof t=="string"&&(t=Fy(t)),Dh(t),t}let ky=class{clone(){return this._cloneInto()}};function qy(t){const e=n=>t().update(xh(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Ah(t=32){if(Tr&&typeof Tr.getRandomValues=="function")return Tr.getRandomValues(new Uint8Array(t));if(Tr&&typeof Tr.randomBytes=="function")return Tr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function zy(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)}let Hy=class extends ky{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=ks(this.buffer)}update(e){pc(this);const{view:r,buffer:n,blockLen:i}=this;e=xh(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=ks(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){pc(this),Uy(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;zy(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=ks(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 yi=BigInt(2**32-1),Po=BigInt(32);function Ch(t,e=!1){return e?{h:Number(t&yi),l:Number(t>>Po&yi)}:{h:Number(t>>Po&yi)|0,l:Number(t&yi)|0}}function Ky(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}=Ch(t[i],e);[r[i],n[i]]=[s,o]}return[r,n]}const Vy=(t,e)=>BigInt(t>>>0)<<Po|BigInt(e>>>0),Wy=(t,e,r)=>t>>>r,Gy=(t,e,r)=>t<<32-r|e>>>r,Yy=(t,e,r)=>t>>>r|e<<32-r,Jy=(t,e,r)=>t<<32-r|e>>>r,Zy=(t,e,r)=>t<<64-r|e>>>r-32,Qy=(t,e,r)=>t>>>r-32|e<<64-r,Xy=(t,e)=>e,em=(t,e)=>t,tm=(t,e,r)=>t<<r|e>>>32-r,rm=(t,e,r)=>e<<r|t>>>32-r,nm=(t,e,r)=>e<<r-32|t>>>64-r,im=(t,e,r)=>t<<r-32|e>>>64-r;function sm(t,e,r,n){const i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}const om=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),am=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,cm=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),um=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,lm=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),hm=(t,e,r,n,i,s)=>e+r+n+i+s+(t/2**32|0)|0,V={fromBig:Ch,split:Ky,toBig:Vy,shrSH:Wy,shrSL:Gy,rotrSH:Yy,rotrSL:Jy,rotrBH:Zy,rotrBL:Qy,rotr32H:Xy,rotr32L:em,rotlSH:tm,rotlSL:rm,rotlBH:nm,rotlBL:im,add:sm,add3L:om,add3H:am,add4L:cm,add4H:um,add5H:hm,add5L:lm},[fm,dm]=V.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Gt=new Uint32Array(80),Yt=new Uint32Array(80);let pm=class extends Hy{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:r,Bh:n,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:f,Gh:p,Gl:d,Hh:y,Hl:w}=this;return[e,r,n,i,s,o,a,c,u,l,h,f,p,d,y,w]}set(e,r,n,i,s,o,a,c,u,l,h,f,p,d,y,w){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=y|0,this.Hl=w|0}process(e,r){for(let E=0;E<16;E++,r+=4)Gt[E]=e.getUint32(r),Yt[E]=e.getUint32(r+=4);for(let E=16;E<80;E++){const O=Gt[E-15]|0,x=Yt[E-15]|0,D=V.rotrSH(O,x,1)^V.rotrSH(O,x,8)^V.shrSH(O,x,7),S=V.rotrSL(O,x,1)^V.rotrSL(O,x,8)^V.shrSL(O,x,7),C=Gt[E-2]|0,I=Yt[E-2]|0,k=V.rotrSH(C,I,19)^V.rotrBH(C,I,61)^V.shrSH(C,I,6),M=V.rotrSL(C,I,19)^V.rotrBL(C,I,61)^V.shrSL(C,I,6),j=V.add4L(S,M,Yt[E-7],Yt[E-16]),q=V.add4H(j,D,k,Gt[E-7],Gt[E-16]);Gt[E]=q|0,Yt[E]=j|0}let{Ah:n,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:f,Fh:p,Fl:d,Gh:y,Gl:w,Hh:b,Hl:v}=this;for(let E=0;E<80;E++){const O=V.rotrSH(h,f,14)^V.rotrSH(h,f,18)^V.rotrBH(h,f,41),x=V.rotrSL(h,f,14)^V.rotrSL(h,f,18)^V.rotrBL(h,f,41),D=h&p^~h&y,S=f&d^~f&w,C=V.add5L(v,x,S,dm[E],Yt[E]),I=V.add5H(C,b,O,D,fm[E],Gt[E]),k=C|0,M=V.rotrSH(n,i,28)^V.rotrBH(n,i,34)^V.rotrBH(n,i,39),j=V.rotrSL(n,i,28)^V.rotrBL(n,i,34)^V.rotrBL(n,i,39),q=n&s^n&a^s&a,L=i&o^i&c^o&c;b=y|0,v=w|0,y=p|0,w=d|0,p=h|0,d=f|0,{h,l:f}=V.add(u|0,l|0,I|0,k|0),u=a|0,l=c|0,a=s|0,c=o|0,s=n|0,o=i|0;const g=V.add3L(k,j,L);n=V.add3H(g,I,M,q),i=g|0}({h:n,l:i}=V.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:s,l:o}=V.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=V.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=V.add(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:f}=V.add(this.Eh|0,this.El|0,h|0,f|0),{h:p,l:d}=V.add(this.Fh|0,this.Fl|0,p|0,d|0),{h:y,l:w}=V.add(this.Gh|0,this.Gl|0,y|0,w|0),{h:b,l:v}=V.add(this.Hh|0,this.Hl|0,b|0,v|0),this.set(n,i,s,o,a,c,u,l,h,f,p,d,y,w,b,v)}roundClean(){Gt.fill(0),Yt.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};const gm=qy(()=>new pm);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const pa=BigInt(0),Lh=BigInt(1),ym=BigInt(2);function ga(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ya(t){if(!ga(t))throw new Error("Uint8Array expected")}function qs(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const mm=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ma(t){ya(t);let e="";for(let r=0;r<t.length;r++)e+=mm[t[r]];return e}function Rh(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?pa:BigInt("0x"+t)}const jt={_0:48,_9:57,A:65,F:70,a:97,f:102};function gc(t){if(t>=jt._0&&t<=jt._9)return t-jt._0;if(t>=jt.A&&t<=jt.F)return t-(jt.A-10);if(t>=jt.a&&t<=jt.f)return t-(jt.a-10)}function Th(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=gc(t.charCodeAt(s)),a=gc(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 wm(t){return Rh(ma(t))}function Li(t){return ya(t),Rh(ma(Uint8Array.from(t).reverse()))}function Nh(t,e){return Th(t.toString(16).padStart(e*2,"0"))}function So(t,e){return Nh(t,e).reverse()}function Mt(t,e,r){let n;if(typeof e=="string")try{n=Th(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(ga(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 yc(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];ya(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}const zs=t=>typeof t=="bigint"&&pa<=t;function vm(t,e,r){return zs(t)&&zs(e)&&zs(r)&&e<=t&&t<r}function An(t,e,r,n){if(!vm(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function bm(t){let e;for(e=0;t>pa;t>>=Lh,e+=1);return e}const Em=t=>(ym<<BigInt(t-1))-Lh,_m={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"||ga(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 wa(t,e,r={}){const n=(i,s,o)=>{const a=_m[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}function mc(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}}const xe=BigInt(0),we=BigInt(1),hr=BigInt(2),$m=BigInt(3),Do=BigInt(4),wc=BigInt(5),vc=BigInt(8);function $e(t,e){const r=t%e;return r>=xe?r:e+r}function Om(t,e,r){if(e<xe)throw new Error("invalid exponent, negatives unsupported");if(r<=xe)throw new Error("invalid modulus");if(r===we)return xe;let n=we;for(;e>xe;)e&we&&(n=n*t%r),t=t*t%r,e>>=we;return n}function $t(t,e,r){let n=t;for(;e-- >xe;)n*=n,n%=r;return n}function bc(t,e){if(t===xe)throw new Error("invert: expected non-zero number");if(e<=xe)throw new Error("invert: expected positive modulus, got "+e);let r=$e(t,e),n=e,i=xe,s=we;for(;r!==xe;){const o=n/r,a=n%r,c=i-s*o;n=r,r=a,i=s,s=c}if(n!==we)throw new Error("invert: does not exist");return $e(i,e)}function Im(t){const e=(t-we)/hr;let r,n,i;for(r=t-we,n=0;r%hr===xe;r/=hr,n++);for(i=hr;i<t&&Om(i,e,t)!==t-we;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){const o=(t+we)/Do;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+we)/hr;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,we<<BigInt(c-f-1));u=o.sqr(p),l=o.mul(l,p),h=o.mul(h,u),c=f}return l}}function Pm(t){if(t%Do===$m){const e=(t+we)/Do;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%vc===wc){const e=(t-wc)/vc;return function(r,n){const i=r.mul(n,hr),s=r.pow(i,e),o=r.mul(n,s),a=r.mul(r.mul(o,hr),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 Im(t)}const Sm=(t,e)=>($e(t,e)&we)===we,Dm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function xm(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Dm.reduce((n,i)=>(n[i]="function",n),e);return wa(t,r)}function Am(t,e,r){if(r<xe)throw new Error("invalid exponent, negatives unsupported");if(r===xe)return t.ONE;if(r===we)return e;let n=t.ONE,i=e;for(;r>xe;)r&we&&(n=t.mul(n,i)),i=t.sqr(i),r>>=we;return n}function Cm(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 jh(t,e){const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Mh(t,e,r=!1,n={}){if(t<=xe)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=jh(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:Em(i),ZERO:xe,ONE:we,create:c=>$e(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return xe<=c&&c<t},is0:c=>c===xe,isOdd:c=>(c&we)===we,neg:c=>$e(-c,t),eql:(c,u)=>c===u,sqr:c=>$e(c*c,t),add:(c,u)=>$e(c+u,t),sub:(c,u)=>$e(c-u,t),mul:(c,u)=>$e(c*u,t),pow:(c,u)=>Am(a,c,u),div:(c,u)=>$e(c*bc(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>bc(c,t),sqrt:n.sqrt||(c=>(o||(o=Pm(t)),o(a,c))),invertBatch:c=>Cm(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?So(c,s):Nh(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?Li(c):wm(c)}});return Object.freeze(a)}const Ec=BigInt(0),mi=BigInt(1);function Hs(t,e){const r=e.negate();return t?r:e}function Bh(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ks(t,e){Bh(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1);return{windows:r,windowSize:n}}function Lm(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 Rm(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 Vs=new WeakMap,Uh=new WeakMap;function Ws(t){return Uh.get(t)||1}function Tm(t,e){return{constTimeNegate:Hs,hasPrecomputes(r){return Ws(r)!==1},unsafeLadder(r,n,i=t.ZERO){let s=r;for(;n>Ec;)n&mi&&(i=i.add(s)),s=s.double(),n>>=mi;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=Ks(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}=Ks(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+=mi);const y=p,w=p+Math.abs(d)-1,b=f%2!==0,v=d<0;d===0?c=c.add(Hs(b,n[y])):a=a.add(Hs(v,n[w]))}return{p:a,f:c}},wNAFUnsafe(r,n,i,s=t.ZERO){const{windows:o,windowSize:a}=Ks(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===Ec)break;let p=Number(i&c);if(i>>=l,p>a&&(p-=u,i+=mi),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=Vs.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&Vs.set(n,i(s))),s},wNAFCached(r,n,i){const s=Ws(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=Ws(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){Bh(n,e),Uh.set(r,n),Vs.delete(r)}}}function Nm(t,e,r,n){if(Lm(r,t),Rm(n,e),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=bm(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 jm(t){return xm(t.Fp),wa(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...jh(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const gt=BigInt(0),Ve=BigInt(1),wi=BigInt(2),Mm=BigInt(8),Bm={zip215:!0};function Um(t){const e=jm(t);return wa(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Fm(t){const e=Um(t),{Fp:r,n,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=e,u=wi<<BigInt(a*8)-Ve,l=r.create,h=Mh(e.n,e.nBitLength),f=e.uvRatio||((g,m)=>{try{return{isValid:!0,value:r.sqrt(g*r.inv(m))}}catch{return{isValid:!1,value:gt}}}),p=e.adjustScalarBytes||(g=>g),d=e.domain||((g,m,_)=>{if(qs("phflag",_),m.length||_)throw new Error("Contexts/pre-hash are not supported");return g});function y(g,m){An("coordinate "+g,m,gt,u)}function w(g){if(!(g instanceof E))throw new Error("ExtendedPoint expected")}const b=mc((g,m)=>{const{ex:_,ey:P,ez:$}=g,A=g.is0();m==null&&(m=A?Mm:r.inv($));const B=l(_*m),F=l(P*m),z=l($*m);if(A)return{x:gt,y:Ve};if(z!==Ve)throw new Error("invZ was invalid");return{x:B,y:F}}),v=mc(g=>{const{a:m,d:_}=e;if(g.is0())throw new Error("bad point: ZERO");const{ex:P,ey:$,ez:A,et:B}=g,F=l(P*P),z=l($*$),U=l(A*A),K=l(U*U),Y=l(F*m),pe=l(U*l(Y+z)),te=l(K+l(_*l(F*z)));if(pe!==te)throw new Error("bad point: equation left != right (1)");const J=l(P*$),Ue=l(A*B);if(J!==Ue)throw new Error("bad point: equation left != right (2)");return!0});class E{constructor(m,_,P,$){this.ex=m,this.ey=_,this.ez=P,this.et=$,y("x",m),y("y",_),y("z",P),y("t",$),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(m){if(m instanceof E)throw new Error("extended point not allowed");const{x:_,y:P}=m||{};return y("x",_),y("y",P),new E(_,P,Ve,l(_*P))}static normalizeZ(m){const _=r.invertBatch(m.map(P=>P.ez));return m.map((P,$)=>P.toAffine(_[$])).map(E.fromAffine)}static msm(m,_){return Nm(E,h,m,_)}_setWindowSize(m){D.setWindowSize(this,m)}assertValidity(){v(this)}equals(m){w(m);const{ex:_,ey:P,ez:$}=this,{ex:A,ey:B,ez:F}=m,z=l(_*F),U=l(A*$),K=l(P*F),Y=l(B*$);return z===U&&K===Y}is0(){return this.equals(E.ZERO)}negate(){return new E(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:m}=e,{ex:_,ey:P,ez:$}=this,A=l(_*_),B=l(P*P),F=l(wi*l($*$)),z=l(m*A),U=_+P,K=l(l(U*U)-A-B),Y=z+B,pe=Y-F,te=z-B,J=l(K*pe),Ue=l(Y*te),Le=l(K*te),qe=l(pe*Y);return new E(J,Ue,qe,Le)}add(m){w(m);const{a:_,d:P}=e,{ex:$,ey:A,ez:B,et:F}=this,{ex:z,ey:U,ez:K,et:Y}=m;if(_===BigInt(-1)){const Ha=l((A-$)*(U+z)),Ka=l((A+$)*(U-z)),Ns=l(Ka-Ha);if(Ns===gt)return this.double();const Va=l(B*wi*Y),Wa=l(F*wi*K),Ga=Wa+Va,Ya=Ka+Ha,Ja=Wa-Va,hg=l(Ga*Ns),fg=l(Ya*Ja),dg=l(Ga*Ja),pg=l(Ns*Ya);return new E(hg,fg,pg,dg)}const pe=l($*z),te=l(A*U),J=l(F*P*Y),Ue=l(B*K),Le=l(($+A)*(z+U)-pe-te),qe=Ue-J,ot=Ue+J,Nt=l(te-_*pe),Ar=l(Le*qe),cg=l(ot*Nt),ug=l(Le*Nt),lg=l(qe*ot);return new E(Ar,cg,lg,ug)}subtract(m){return this.add(m.negate())}wNAF(m){return D.wNAFCached(this,m,E.normalizeZ)}multiply(m){const _=m;An("scalar",_,Ve,n);const{p:P,f:$}=this.wNAF(_);return E.normalizeZ([P,$])[0]}multiplyUnsafe(m,_=E.ZERO){const P=m;return An("scalar",P,gt,n),P===gt?x:this.is0()||P===Ve?this:D.wNAFCachedUnsafe(this,P,E.normalizeZ,_)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return D.unsafeLadder(this,n).is0()}toAffine(m){return b(this,m)}clearCofactor(){const{h:m}=e;return m===Ve?this:this.multiplyUnsafe(m)}static fromHex(m,_=!1){const{d:P,a:$}=e,A=r.BYTES;m=Mt("pointHex",m,A),qs("zip215",_);const B=m.slice(),F=m[A-1];B[A-1]=F&-129;const z=Li(B),U=_?u:r.ORDER;An("pointHex.y",z,gt,U);const K=l(z*z),Y=l(K-Ve),pe=l(P*K-$);let{isValid:te,value:J}=f(Y,pe);if(!te)throw new Error("Point.fromHex: invalid y coordinate");const Ue=(J&Ve)===Ve,Le=(F&128)!==0;if(!_&&J===gt&&Le)throw new Error("Point.fromHex: x=0 and x_0=1");return Le!==Ue&&(J=l(-J)),E.fromAffine({x:J,y:z})}static fromPrivateKey(m){return I(m).point}toRawBytes(){const{x:m,y:_}=this.toAffine(),P=So(_,r.BYTES);return P[P.length-1]|=m&Ve?128:0,P}toHex(){return ma(this.toRawBytes())}}E.BASE=new E(e.Gx,e.Gy,Ve,l(e.Gx*e.Gy)),E.ZERO=new E(gt,Ve,Ve,gt);const{BASE:O,ZERO:x}=E,D=Tm(E,a*8);function S(g){return $e(g,n)}function C(g){return S(Li(g))}function I(g){const m=r.BYTES;g=Mt("private key",g,m);const _=Mt("hashed private key",s(g),2*m),P=p(_.slice(0,m)),$=_.slice(m,2*m),A=C(P),B=O.multiply(A),F=B.toRawBytes();return{head:P,prefix:$,scalar:A,point:B,pointBytes:F}}function k(g){return I(g).pointBytes}function M(g=new Uint8Array,...m){const _=yc(...m);return C(s(d(_,Mt("context",g),!!i)))}function j(g,m,_={}){g=Mt("message",g),i&&(g=i(g));const{prefix:P,scalar:$,pointBytes:A}=I(m),B=M(_.context,P,g),F=O.multiply(B).toRawBytes(),z=M(_.context,F,A,g),U=S(B+z*$);An("signature.s",U,gt,n);const K=yc(F,So(U,r.BYTES));return Mt("result",K,r.BYTES*2)}const q=Bm;function L(g,m,_,P=q){const{context:$,zip215:A}=P,B=r.BYTES;g=Mt("signature",g,2*B),m=Mt("message",m),_=Mt("publicKey",_,B),A!==void 0&&qs("zip215",A),i&&(m=i(m));const F=Li(g.slice(B,2*B));let z,U,K;try{z=E.fromHex(_,A),U=E.fromHex(g.slice(0,B),A),K=O.multiplyUnsafe(F)}catch{return!1}if(!A&&z.isSmallOrder())return!1;const Y=M($,U.toRawBytes(),z.toRawBytes(),m);return U.add(z.multiplyUnsafe(Y)).subtract(K).clearCofactor().equals(E.ZERO)}return O._setWindowSize(8),{CURVE:e,getPublicKey:k,sign:j,verify:L,ExtendedPoint:E,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>o(r.BYTES),precompute(g=8,m=E.BASE){return m._setWindowSize(g),m.multiply(BigInt(3)),m}}}}BigInt(0),BigInt(1);const va=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),_c=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const km=BigInt(1),$c=BigInt(2);BigInt(3);const qm=BigInt(5),zm=BigInt(8);function Hm(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=va,o=t*t%s*t%s,a=$t(o,$c,s)*o%s,c=$t(a,km,s)*t%s,u=$t(c,qm,s)*c%s,l=$t(u,e,s)*u%s,h=$t(l,r,s)*l%s,f=$t(h,n,s)*h%s,p=$t(f,i,s)*f%s,d=$t(p,i,s)*f%s,y=$t(d,e,s)*u%s;return{pow_p_5_8:$t(y,$c,s)*t%s,b2:o}}function Km(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Vm(t,e){const r=va,n=$e(e*e*e,r),i=$e(n*n*e,r),s=Hm(t*i).pow_p_5_8;let o=$e(t*n*s,r);const a=$e(e*o*o,r),c=o,u=$e(o*_c,r),l=a===t,h=a===$e(-t,r),f=a===$e(-t*_c,r);return l&&(o=c),(h||f)&&(o=u),Sm(o,r)&&(o=$e(-o,r)),{isValid:l||h,value:o}}const Wm=Mh(va,void 0,!0),Gm={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Wm,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:zm,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:gm,randomBytes:Ah,adjustScalarBytes:Km,uvRatio:Vm},Fh=Fm(Gm),Ym="EdDSA",Jm="JWT",Yi=".",ls="base64url",kh="utf8",qh="utf8",Zm=":",Qm="did",Xm="key",Oc="base58btc",ew="z",tw="K36",rw=32;function ba(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function zh(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?ba(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Hh(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const r=zh(e);let n=0;for(const i of t)r.set(i,n),n+=i.length;return ba(r)}function nw(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 iw=nw,sw=iw;const Kh=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")},ow=t=>new TextEncoder().encode(t),aw=t=>new TextDecoder().decode(t);let cw=class{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")}},uw=class{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 Vh(this,e)}},lw=class{constructor(e){this.decoders=e}or(e){return Vh(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 Vh=(t,e)=>new lw({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let hw=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new cw(e,r,n),this.decoder=new uw(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const hs=({name:t,prefix:e,encode:r,decode:n})=>new hw(t,e,r,n),si=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=sw(r,e);return hs({prefix:t,name:e,encode:n,decode:s=>Kh(i(s))})},fw=(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},dw=(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},je=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>hs({prefix:e,name:t,encode(i){return dw(i,n,r)},decode(i){return fw(i,n,r,t)}}),pw=hs({prefix:"\0",name:"identity",encode:t=>aw(t),decode:t=>ow(t)});var gw=Object.freeze({__proto__:null,identity:pw});const yw=je({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var mw=Object.freeze({__proto__:null,base2:yw});const ww=je({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var vw=Object.freeze({__proto__:null,base8:ww});const bw=si({prefix:"9",name:"base10",alphabet:"0123456789"});var Ew=Object.freeze({__proto__:null,base10:bw});const _w=je({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),$w=je({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ow=Object.freeze({__proto__:null,base16:_w,base16upper:$w});const Iw=je({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Pw=je({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Sw=je({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Dw=je({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),xw=je({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Aw=je({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Cw=je({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Lw=je({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Rw=je({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Tw=Object.freeze({__proto__:null,base32:Iw,base32upper:Pw,base32pad:Sw,base32padupper:Dw,base32hex:xw,base32hexupper:Aw,base32hexpad:Cw,base32hexpadupper:Lw,base32z:Rw});const Nw=si({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),jw=si({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Mw=Object.freeze({__proto__:null,base36:Nw,base36upper:jw});const Bw=si({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Uw=si({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Fw=Object.freeze({__proto__:null,base58btc:Bw,base58flickr:Uw});const kw=je({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),qw=je({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),zw=je({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Hw=je({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Kw=Object.freeze({__proto__:null,base64:kw,base64pad:qw,base64url:zw,base64urlpad:Hw});const Wh=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Vw=Wh.reduce((t,e,r)=>(t[r]=e,t),[]),Ww=Wh.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Gw(t){return t.reduce((e,r)=>(e+=Vw[r],e),"")}function Yw(t){const e=[];for(const r of t){const n=Ww[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const Jw=hs({prefix:"🚀",name:"base256emoji",encode:Gw,decode:Yw});var Zw=Object.freeze({__proto__:null,base256emoji:Jw}),Qw=Gh,Ic=128,Xw=127,ev=~Xw,tv=Math.pow(2,31);function Gh(t,e,r){e=e||[],r=r||0;for(var n=r;t>=tv;)e[r++]=t&255|Ic,t/=128;for(;t&ev;)e[r++]=t&255|Ic,t>>>=7;return e[r]=t|0,Gh.bytes=r-n+1,e}var rv=xo,nv=128,Pc=127;function xo(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw xo.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&Pc)<<i:(o&Pc)*Math.pow(2,i),i+=7}while(o>=nv);return xo.bytes=s-n,r}var iv=Math.pow(2,7),sv=Math.pow(2,14),ov=Math.pow(2,21),av=Math.pow(2,28),cv=Math.pow(2,35),uv=Math.pow(2,42),lv=Math.pow(2,49),hv=Math.pow(2,56),fv=Math.pow(2,63),dv=function(t){return t<iv?1:t<sv?2:t<ov?3:t<av?4:t<cv?5:t<uv?6:t<lv?7:t<hv?8:t<fv?9:10},pv={encode:Qw,decode:rv,encodingLength:dv},Yh=pv;const Sc=(t,e,r=0)=>(Yh.encode(t,e,r),e),Dc=t=>Yh.encodingLength(t),Ao=(t,e)=>{const r=e.byteLength,n=Dc(t),i=n+Dc(r),s=new Uint8Array(i+r);return Sc(t,s,0),Sc(r,s,n),s.set(e,i),new gv(t,r,e,s)};let gv=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};const Jh=({name:t,code:e,encode:r})=>new yv(t,e,r);let yv=class{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?Ao(this.code,r):r.then(n=>Ao(this.code,n))}else throw Error("Unknown type, must be binary type")}};const Zh=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),mv=Jh({name:"sha2-256",code:18,encode:Zh("SHA-256")}),wv=Jh({name:"sha2-512",code:19,encode:Zh("SHA-512")});var vv=Object.freeze({__proto__:null,sha256:mv,sha512:wv});const Qh=0,bv="identity",Xh=Kh,Ev=t=>Ao(Qh,Xh(t)),_v={code:Qh,name:bv,encode:Xh,digest:Ev};var $v=Object.freeze({__proto__:null,identity:_v});new TextEncoder,new TextDecoder;const xc={...gw,...mw,...vw,...Ew,...Ow,...Tw,...Mw,...Fw,...Kw,...Zw};({...vv,...$v});function ef(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Ac=ef("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Gs=ef("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=zh(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),tf={utf8:Ac,"utf-8":Ac,hex:xc.base16,latin1:Gs,ascii:Gs,binary:Gs,...xc};function fs(t,e="utf8"){const r=tf[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)}function bn(t,e="utf8"){const r=tf[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?ba(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function Cc(t){return wr(fs(bn(t,ls),kh))}function Ji(t){return fs(bn(Wt(t),kh),ls)}function rf(t){const e=bn(tw,Oc),r=ew+fs(Hh([e,t]),Oc);return[Qm,Xm,r].join(Zm)}function Ov(t){return fs(t,ls)}function Iv(t){return bn(t,ls)}function Pv(t){return bn([Ji(t.header),Ji(t.payload)].join(Yi),qh)}function Sv(t){return[Ji(t.header),Ji(t.payload),Ov(t.signature)].join(Yi)}function Co(t){const e=t.split(Yi),r=Cc(e[0]),n=Cc(e[1]),i=Iv(e[2]),s=bn(e.slice(0,2).join(Yi),qh);return{header:r,payload:n,signature:i,data:s}}function Lc(t=Ah(rw)){const e=Fh.getPublicKey(t);return{secretKey:Hh([t,e]),publicKey:e}}async function Dv(t,e,r,n,i=T.fromMiliseconds(Date.now())){const s={alg:Ym,typ:Jm},o=rf(n.publicKey),a=i+r,c={iss:o,sub:t,aud:e,iat:i,exp:a},u=Pv({header:s,payload:c}),l=Fh.sign(u,n.secretKey.slice(0,32));return Sv({header:s,payload:c,signature:l})}var Rc=function(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))},xv=function(){function t(e,r,n){this.name=e,this.version=r,this.os=n,this.type="browser"}return t}(),Av=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=ft.platform}return t}(),Cv=function(){function t(e,r,n,i){this.name=e,this.version=r,this.os=n,this.bot=i,this.type="bot-device"}return t}(),Lv=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),Rv=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),Tv=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Nv=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Tc=3,jv=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",Tv]],Nc=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function Mv(t){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Rv:typeof navigator<"u"?Uv(navigator.userAgent):kv()}function Bv(t){return t!==""&&jv.reduce(function(e,r){var n=r[0],i=r[1];if(e)return e;var s=i.exec(t);return!!s&&[n,s]},!1)}function Uv(t){var e=Bv(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new Lv;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length<Tc&&(i=Rc(Rc([],i,!0),qv(Tc-i.length),!0)):i=[];var s=i.join("."),o=Fv(t),a=Nv.exec(t);return a&&a[1]?new Cv(r,s,o,a[1]):new xv(r,s,o)}function Fv(t){for(var e=0,r=Nc.length;e<r;e++){var n=Nc[e],i=n[0],s=n[1],o=s.exec(t);if(o)return i}return null}function kv(){var t=typeof ft<"u"&&ft.version;return t?new Av(ft.version.slice(1)):null}function qv(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var ye={};Object.defineProperty(ye,"__esModule",{value:!0});ye.getLocalStorage=ye.getLocalStorageOrThrow=ye.getCrypto=ye.getCryptoOrThrow=nf=ye.getLocation=ye.getLocationOrThrow=Ea=ye.getNavigator=ye.getNavigatorOrThrow=vr=ye.getDocument=ye.getDocumentOrThrow=ye.getFromWindowOrThrow=ye.getFromWindow=void 0;function Pr(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}ye.getFromWindow=Pr;function En(t){const e=Pr(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}ye.getFromWindowOrThrow=En;function zv(){return En("document")}ye.getDocumentOrThrow=zv;function Hv(){return Pr("document")}var vr=ye.getDocument=Hv;function Kv(){return En("navigator")}ye.getNavigatorOrThrow=Kv;function Vv(){return Pr("navigator")}var Ea=ye.getNavigator=Vv;function Wv(){return En("location")}ye.getLocationOrThrow=Wv;function Gv(){return Pr("location")}var nf=ye.getLocation=Gv;function Yv(){return En("crypto")}ye.getCryptoOrThrow=Yv;function Jv(){return Pr("crypto")}ye.getCrypto=Jv;function Zv(){return En("localStorage")}ye.getLocalStorageOrThrow=Zv;function Qv(){return Pr("localStorage")}ye.getLocalStorage=Qv;var _a={};Object.defineProperty(_a,"__esModule",{value:!0});var sf=_a.getWindowMetadata=void 0;const jc=ye;function Xv(){let t,e;try{t=jc.getDocumentOrThrow(),e=jc.getLocationOrThrow()}catch{return null}function r(){const h=t.getElementsByTagName("link"),f=[];for(let p=0;p<h.length;p++){const d=h[p],y=d.getAttribute("rel");if(y&&y.toLowerCase().indexOf("icon")>-1){const w=d.getAttribute("href");if(w)if(w.toLowerCase().indexOf("https:")===-1&&w.toLowerCase().indexOf("http:")===-1&&w.indexOf("//")!==0){let b=e.protocol+"//"+e.host;if(w.indexOf("/")===0)b+=w;else{const v=e.pathname.split("/");v.pop();const E=v.join("/");b+=E+"/"+w}f.push(b)}else if(w.indexOf("//")===0){const b=e.protocol+w;f.push(b)}else f.push(w)}}return f}function n(...h){const f=t.getElementsByTagName("meta");for(let p=0;p<f.length;p++){const d=f[p],y=["itemprop","property","name"].map(w=>d.getAttribute(w)).filter(w=>w?h.includes(w):!1);if(y.length&&y){const w=d.getAttribute("content");if(w)return w}}return""}function i(){let h=n("name","og:site_name","og:title","twitter:title");return h||(h=t.title),h}function s(){return n("description","og:description","twitter:description","keywords")}const o=i(),a=s(),c=e.origin,u=r();return{description:a,url:c,icons:u,name:o}}sf=_a.getWindowMetadata=Xv;function eb(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 tb=eb,rb=tb;const nb=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")},ib=t=>new TextEncoder().encode(t),sb=t=>new TextDecoder().decode(t);class ob{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 ab{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 of(this,e)}}class cb{constructor(e){this.decoders=e}or(e){return of(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 of=(t,e)=>new cb({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class ub{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new ob(e,r,n),this.decoder=new ab(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ds=({name:t,prefix:e,encode:r,decode:n})=>new ub(t,e,r,n),oi=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=rb(r,e);return ds({prefix:t,name:e,encode:n,decode:s=>nb(i(s))})},lb=(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},hb=(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},Me=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>ds({prefix:e,name:t,encode(i){return hb(i,n,r)},decode(i){return lb(i,n,r,t)}}),fb=ds({prefix:"\0",name:"identity",encode:t=>sb(t),decode:t=>ib(t)}),db=Object.freeze(Object.defineProperty({__proto__:null,identity:fb},Symbol.toStringTag,{value:"Module"})),pb=Me({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),gb=Object.freeze(Object.defineProperty({__proto__:null,base2:pb},Symbol.toStringTag,{value:"Module"})),yb=Me({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),mb=Object.freeze(Object.defineProperty({__proto__:null,base8:yb},Symbol.toStringTag,{value:"Module"})),wb=oi({prefix:"9",name:"base10",alphabet:"0123456789"}),vb=Object.freeze(Object.defineProperty({__proto__:null,base10:wb},Symbol.toStringTag,{value:"Module"})),bb=Me({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Eb=Me({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),_b=Object.freeze(Object.defineProperty({__proto__:null,base16:bb,base16upper:Eb},Symbol.toStringTag,{value:"Module"})),$b=Me({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ob=Me({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ib=Me({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Pb=Me({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Sb=Me({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Db=Me({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),xb=Me({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ab=Me({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Cb=Me({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Lb=Object.freeze(Object.defineProperty({__proto__:null,base32:$b,base32hex:Sb,base32hexpad:xb,base32hexpadupper:Ab,base32hexupper:Db,base32pad:Ib,base32padupper:Pb,base32upper:Ob,base32z:Cb},Symbol.toStringTag,{value:"Module"})),Rb=oi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Tb=oi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Nb=Object.freeze(Object.defineProperty({__proto__:null,base36:Rb,base36upper:Tb},Symbol.toStringTag,{value:"Module"})),jb=oi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Mb=oi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Bb=Object.freeze(Object.defineProperty({__proto__:null,base58btc:jb,base58flickr:Mb},Symbol.toStringTag,{value:"Module"})),Ub=Me({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Fb=Me({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),kb=Me({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),qb=Me({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),zb=Object.freeze(Object.defineProperty({__proto__:null,base64:Ub,base64pad:Fb,base64url:kb,base64urlpad:qb},Symbol.toStringTag,{value:"Module"})),af=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Hb=af.reduce((t,e,r)=>(t[r]=e,t),[]),Kb=af.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Vb(t){return t.reduce((e,r)=>(e+=Hb[r],e),"")}function Wb(t){const e=[];for(const r of t){const n=Kb[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const Gb=ds({prefix:"🚀",name:"base256emoji",encode:Vb,decode:Wb}),Yb=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:Gb},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Mc={...db,...gb,...mb,...vb,..._b,...Lb,...Nb,...Bb,...zb,...Yb},Jb={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}};var $a={exports:{}},nn=typeof Reflect=="object"?Reflect:null,Bc=nn&&typeof nn.apply=="function"?nn.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Ri;nn&&typeof nn.ownKeys=="function"?Ri=nn.ownKeys:Object.getOwnPropertySymbols?Ri=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Ri=function(e){return Object.getOwnPropertyNames(e)};function Zb(t){console&&console.warn&&console.warn(t)}var cf=Number.isNaN||function(e){return e!==e};function ie(){ie.init.call(this)}$a.exports=ie;$a.exports.once=t0;ie.EventEmitter=ie;ie.prototype._events=void 0;ie.prototype._eventsCount=0;ie.prototype._maxListeners=void 0;var Uc=10;function ps(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ie,"defaultMaxListeners",{enumerable:!0,get:function(){return Uc},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+".");Uc=t}});ie.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};ie.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 uf(t){return t._maxListeners===void 0?ie.defaultMaxListeners:t._maxListeners}ie.prototype.getMaxListeners=function(){return uf(this)};ie.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")Bc(c,this,r);else for(var u=c.length,l=pf(c,u),n=0;n<u;++n)Bc(l[n],this,r);return!0};function lf(t,e,r,n){var i,s,o;if(ps(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=uf(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,Zb(a)}return t}ie.prototype.addListener=function(e,r){return lf(this,e,r,!1)};ie.prototype.on=ie.prototype.addListener;ie.prototype.prependListener=function(e,r){return lf(this,e,r,!0)};function Qb(){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 hf(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=Qb.bind(n);return i.listener=r,n.wrapFn=i,i}ie.prototype.once=function(e,r){return ps(r),this.on(e,hf(this,e,r)),this};ie.prototype.prependOnceListener=function(e,r){return ps(r),this.prependListener(e,hf(this,e,r)),this};ie.prototype.removeListener=function(e,r){var n,i,s,o,a;if(ps(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():Xb(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};ie.prototype.off=ie.prototype.removeListener;ie.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 ff(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?e0(i):pf(i,i.length)}ie.prototype.listeners=function(e){return ff(this,e,!0)};ie.prototype.rawListeners=function(e){return ff(this,e,!1)};ie.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):df.call(t,e)};ie.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}ie.prototype.eventNames=function(){return this._eventsCount>0?Ri(this._events):[]};function pf(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function Xb(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function e0(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function t0(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))}gf(t,e,s,{once:!0}),e!=="error"&&r0(t,i,{once:!0})})}function r0(t,e,r){typeof t.on=="function"&&gf(t,"error",e,r)}function gf(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 n0=$a.exports;const i0="PARSE_ERROR",s0="INVALID_REQUEST",o0="METHOD_NOT_FOUND",a0="INVALID_PARAMS",yf="INTERNAL_ERROR",Oa="SERVER_ERROR",c0=[-32700,-32600,-32601,-32602,-32603],kn={[i0]:{code:-32700,message:"Parse error"},[s0]:{code:-32600,message:"Invalid Request"},[o0]:{code:-32601,message:"Method not found"},[a0]:{code:-32602,message:"Invalid params"},[yf]:{code:-32603,message:"Internal error"},[Oa]:{code:-32e3,message:"Server error"}},mf=Oa;function u0(t){return c0.includes(t)}function Fc(t){return Object.keys(kn).includes(t)?kn[t]:kn[mf]}function l0(t){const e=Object.values(kn).find(r=>r.code===t);return e||kn[mf]}function wf(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var vf={};/*! *****************************************************************************
|
|
16
16
|
Copyright (c) Microsoft Corporation.
|
|
17
17
|
|
|
18
18
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
@@ -25,14 +25,15 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
|
25
25
|
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
|
-
***************************************************************************** */var bo=function(t,e){return bo=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])},bo(t,e)};function Ab(t,e){bo(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Eo=function(){return Eo=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},Eo.apply(this,arguments)};function Cb(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 Lb(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 Rb(t,e){return function(r,n){e(r,n,t)}}function Nb(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Tb(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 jb(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 Mb(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function Fb(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function _o(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 Gh(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 Bb(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Gh(arguments[e]));return t}function Ub(){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 zn(t){return this instanceof zn?(this.v=t,this):new zn(t)}function qb(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 zn?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 kb(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:zn(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function zb(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 _o=="function"?_o(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 Kb(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function Hb(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 Vb(t){return t&&t.__esModule?t:{default:t}}function Wb(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function Gb(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 Yb=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Eo},__asyncDelegator:kb,__asyncGenerator:qb,__asyncValues:zb,__await:zn,__awaiter:Tb,__classPrivateFieldGet:Wb,__classPrivateFieldSet:Gb,__createBinding:Mb,__decorate:Lb,__exportStar:Fb,__extends:Ab,__generator:jb,__importDefault:Vb,__importStar:Hb,__makeTemplateObject:Kb,__metadata:Nb,__param:Rb,__read:Gh,__rest:Cb,__spread:Bb,__spreadArrays:Ub,__values:_o},Symbol.toStringTag,{value:"Module"})),Jb=kl(Yb);var Ft={},Pc;function Zb(){if(Pc)return Ft;Pc=1,Object.defineProperty(Ft,"__esModule",{value:!0}),Ft.isBrowserCryptoAvailable=Ft.getSubtleCrypto=Ft.getBrowerCrypto=void 0;function t(){return(At===null||At===void 0?void 0:At.crypto)||(At===null||At===void 0?void 0:At.msCrypto)||{}}Ft.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}Ft.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Ft.isBrowserCryptoAvailable=r,Ft}var Bt={},Dc;function Qb(){if(Dc)return Bt;Dc=1,Object.defineProperty(Bt,"__esModule",{value:!0}),Bt.isBrowser=Bt.isNode=Bt.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Bt.isReactNative=t;function e(){return typeof ft<"u"&&typeof ft.versions<"u"&&typeof ft.versions.node<"u"}Bt.isNode=e;function r(){return!t()&&!e()}return Bt.isBrowser=r,Bt}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Jb;e.__exportStar(Zb(),t),e.__exportStar(Qb(),t)})(Wh);function St(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function pr(t=6){return BigInt(St(t))}function Xt(t,e,r){return{id:r||St(),jsonrpc:"2.0",method:t,params:e}}function os(t,e){return{id:t,jsonrpc:"2.0",result:e}}function as(t,e,r){return{id:t,jsonrpc:"2.0",error:Xb(e)}}function Xb(t,e){return typeof t>"u"?Ic(Kh):(typeof t=="string"&&(t=Object.assign(Object.assign({},Ic(la)),{message:t})),Sb(t.code)&&(t=xb(t.code)),t)}class e0{}class t0 extends e0{constructor(){super()}}class r0 extends t0{constructor(e){super()}}const n0="^https?:",i0="^wss?:";function s0(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Yh(t,e){const r=s0(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Sc(t){return Yh(t,n0)}function xc(t){return Yh(t,i0)}function o0(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Jh(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function ha(t){return Jh(t)&&"method"in t}function cs(t){return Jh(t)&&(xt(t)||lt(t))}function xt(t){return"result"in t}function lt(t){return"error"in t}let dt=class extends r0{constructor(e){super(e),this.events=new _b.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(Xt(e.method,e.params||[],e.id||pr().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),cs(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 fa={exports:{}},tn=typeof Reflect=="object"?Reflect:null,Ac=tn&&typeof tn.apply=="function"?tn.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Pi;tn&&typeof tn.ownKeys=="function"?Pi=tn.ownKeys:Object.getOwnPropertySymbols?Pi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Pi=function(e){return Object.getOwnPropertyNames(e)};function a0(t){console&&console.warn&&console.warn(t)}var Zh=Number.isNaN||function(e){return e!==e};function se(){se.init.call(this)}fa.exports=se;fa.exports.once=h0;se.EventEmitter=se;se.prototype._events=void 0;se.prototype._eventsCount=0;se.prototype._maxListeners=void 0;var Cc=10;function us(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 Cc},set:function(t){if(typeof t!="number"||t<0||Zh(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Cc=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||Zh(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 Qh(t){return t._maxListeners===void 0?se.defaultMaxListeners:t._maxListeners}se.prototype.getMaxListeners=function(){return Qh(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")Ac(c,this,r);else for(var u=c.length,l=nf(c,u),n=0;n<u;++n)Ac(l[n],this,r);return!0};function Xh(t,e,r,n){var i,s,o;if(us(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=Qh(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,a0(a)}return t}se.prototype.addListener=function(e,r){return Xh(this,e,r,!1)};se.prototype.on=se.prototype.addListener;se.prototype.prependListener=function(e,r){return Xh(this,e,r,!0)};function c0(){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 ef(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=c0.bind(n);return i.listener=r,n.wrapFn=i,i}se.prototype.once=function(e,r){return us(r),this.on(e,ef(this,e,r)),this};se.prototype.prependOnceListener=function(e,r){return us(r),this.prependListener(e,ef(this,e,r)),this};se.prototype.removeListener=function(e,r){var n,i,s,o,a;if(us(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():u0(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 tf(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?l0(i):nf(i,i.length)}se.prototype.listeners=function(e){return tf(this,e,!0)};se.prototype.rawListeners=function(e){return tf(this,e,!1)};se.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):rf.call(t,e)};se.prototype.listenerCount=rf;function rf(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?Pi(this._events):[]};function nf(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function u0(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function l0(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function h0(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))}sf(t,e,s,{once:!0}),e!=="error"&&f0(t,i,{once:!0})})}function f0(t,e,r){typeof t.on=="function"&&sf(t,"error",e,r)}function sf(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 d0=fa.exports;const p0=()=>typeof WebSocket<"u"?WebSocket:typeof K<"u"&&typeof K.WebSocket<"u"?K.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),g0=()=>typeof WebSocket<"u"||typeof K<"u"&&typeof K.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Lc=t=>t.split("?")[0],Rc=10,y0=p0();let m0=class{constructor(e){if(this.url=e,this.events=new d0.EventEmitter,this.registering=!1,!xc(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,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(Vt(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!xc(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=Wh.isReactNative()?void 0:{rejectUnauthorized:!o0(e)},s=new y0(e,[],i);g0()?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"?mr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=as(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return Vh(e,Lc(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Rc&&this.events.setMaxListeners(Rc)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Lc(this.url)}`));return this.events.emit("register_error",r),r}};var da={exports:{}},rn=typeof Reflect=="object"?Reflect:null,Nc=rn&&typeof rn.apply=="function"?rn.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Di;rn&&typeof rn.ownKeys=="function"?Di=rn.ownKeys:Object.getOwnPropertySymbols?Di=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Di=function(e){return Object.getOwnPropertyNames(e)};function v0(t){console&&console.warn&&console.warn(t)}var of=Number.isNaN||function(e){return e!==e};function oe(){oe.init.call(this)}da.exports=oe;da.exports.once=_0;oe.EventEmitter=oe;oe.prototype._events=void 0;oe.prototype._eventsCount=0;oe.prototype._maxListeners=void 0;var Tc=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(oe,"defaultMaxListeners",{enumerable:!0,get:function(){return Tc},set:function(t){if(typeof t!="number"||t<0||of(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Tc=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||of(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 af(t){return t._maxListeners===void 0?oe.defaultMaxListeners:t._maxListeners}oe.prototype.getMaxListeners=function(){return af(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")Nc(c,this,r);else for(var u=c.length,l=ff(c,u),n=0;n<u;++n)Nc(l[n],this,r);return!0};function cf(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=af(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,v0(a)}return t}oe.prototype.addListener=function(e,r){return cf(this,e,r,!1)};oe.prototype.on=oe.prototype.addListener;oe.prototype.prependListener=function(e,r){return cf(this,e,r,!0)};function w0(){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 uf(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=w0.bind(n);return i.listener=r,n.wrapFn=i,i}oe.prototype.once=function(e,r){return ls(r),this.on(e,uf(this,e,r)),this};oe.prototype.prependOnceListener=function(e,r){return ls(r),this.prependListener(e,uf(this,e,r)),this};oe.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():b0(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 lf(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?E0(i):ff(i,i.length)}oe.prototype.listeners=function(e){return lf(this,e,!0)};oe.prototype.rawListeners=function(e){return lf(this,e,!1)};oe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):hf.call(t,e)};oe.prototype.listenerCount=hf;function hf(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?Di(this._events):[]};function ff(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function b0(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function E0(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function _0(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))}df(t,e,s,{once:!0}),e!=="error"&&$0(t,i,{once:!0})})}function $0(t,e,r){typeof t.on=="function"&&df(t,"error",e,r)}function df(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 O0=da.exports;function I0(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 w=u[f],E=0;for(let O=d-1;(w!==0||E<h)&&O!==-1;O--,E++)w+=256*y[O]>>>0,y[O]=w%r>>>0,w=w/r>>>0;if(w!==0)throw new Error("Non-zero carry");h=E,f++}let v=d-h;for(;v!==d&&y[v]===0;)v++;let b=n.repeat(l);for(;v<d;++v)b+=t.charAt(y[v]);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 w=u.charCodeAt(l);if(w>255)return;let E=e[w];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 v=new Uint8Array(h+(p-y));let b=h;for(;y!==p;)v[b++]=d[y++];return v}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 P0="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const D0=I0(P0);function pf(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function jn(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const r=pf(e);let n=0;for(const i of t)r.set(i,n),n+=i.length;return r}function gf(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const jc=gf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Bs=gf("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=pf(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),yf={utf8:jc,"utf-8":jc,hex:_c.base16,latin1:Bs,ascii:Bs,binary:Bs,..._c};function ht(t,e="utf8"){const r=yf[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=yf[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 S0={};const x0=":";function nn(t){const[e,r]=t.split(x0);return{namespace:e,reference:r}}function Mc(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 mf(t,e){return t.includes(":")?[t]:e.chains||[]}var A0=Object.defineProperty,C0=Object.defineProperties,L0=Object.getOwnPropertyDescriptors,Fc=Object.getOwnPropertySymbols,R0=Object.prototype.hasOwnProperty,N0=Object.prototype.propertyIsEnumerable,Bc=(t,e,r)=>e in t?A0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Uc=(t,e)=>{for(var r in e||(e={}))R0.call(e,r)&&Bc(t,r,e[r]);if(Fc)for(var r of Fc(e))N0.call(e,r)&&Bc(t,r,e[r]);return t},T0=(t,e)=>C0(t,L0(e));const j0="ReactNative",it={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},M0="js";function zi(){return typeof ft<"u"&&typeof ft.versions<"u"&&typeof ft.versions.node<"u"}function nr(){return!vr()&&!!aa()&&navigator.product===j0}function F0(){return nr()&&typeof K<"u"&&typeof(K==null?void 0:K.Platform)<"u"&&(K==null?void 0:K.Platform.OS)==="android"}function B0(){return nr()&&typeof K<"u"&&typeof(K==null?void 0:K.Platform)<"u"&&(K==null?void 0:K.Platform.OS)==="ios"}function wn(){return!zi()&&!!aa()&&!!vr()}function ei(){return nr()?it.reactNative:zi()?it.node:wn()?it.browser:it.unknown}function qc(){var t;try{return nr()&&typeof K<"u"&&typeof(K==null?void 0:K.Application)<"u"?(t=K.Application)==null?void 0:t.applicationId:void 0}catch{return}}function U0(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 q0(t){var e,r;const n=vf();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!=="")),T0(Uc(Uc({},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 vf(){return Rh()||{name:"",description:"",url:"",icons:[""]}}function k0(){if(ei()===it.reactNative&&typeof K<"u"&&typeof(K==null?void 0:K.Platform)<"u"){const{OS:r,Version:n}=K.Platform;return[r,n].join("-")}const t=rw();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 z0(){var t;const e=ei();return e===it.browser?[e,((t=Lh())==null?void 0:t.host)||"unknown"].join(":"):e}function wf(t,e,r){const n=k0(),i=z0();return[[t,e].join("-"),[M0,r].join("-"),n,i].join("/")}function K0({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=r.split("?"),l=wf(t,e,n),h={auth:i,ua:l,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},f=U0(u[1]||"",h);return u[0]+"?"+f}function gr(t,e){return t.filter(r=>e.includes(r)).length===t.length}function $o(t){return Object.fromEntries(t.entries())}function Oo(t){return new Map(Object.entries(t))}function cr(t=N.FIVE_MINUTES,e){const r=N.toMiliseconds(t||N.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 er(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 bf(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 H0(t){return bf("topic",t)}function V0(t){return bf("id",t)}function Ef(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 N.fromMiliseconds(Date.now()+N.toMiliseconds(t))}function Zt(t){return Date.now()>=N.toMiliseconds(t)}function ee(t,e){return`${t}${e?`:${e}`:""}`}function Rt(t=[],e=[]){return[...new Set([...t,...e])]}async function W0({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=G0(s,t,e),a=ei();if(a===it.browser){if(!((n=vr())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Y0(o)}else a===it.reactNative&&typeof(K==null?void 0:K.Linking)<"u"&&await K.Linking.openURL(o)}catch(i){console.error(i)}}function G0(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}${X0(n,!0)}`}else i=`${i}/wc?${n}`;return i}function Y0(t){let e="_self";Q0()?e="_top":(Z0()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function J0(t,e){let r="";try{if(wn()&&(r=localStorage.getItem(e),r))return r;r=await t.getItem(e)}catch(n){console.error(n)}return r}function kc(t,e){if(!t.includes(e))return null;const r=t.split(/([&,?,=])/),n=r.indexOf(e);return r[n+2]}function zc(){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 pa(){return typeof ft<"u"&&S0.IS_VITEST==="true"}function Z0(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Q0(){try{return window.self!==window.top}catch{return!1}}function X0(t,e=!1){const r=Ce.from(t).toString("base64");return e?r.replace(/[=]/g,""):r}function _f(t){return Ce.from(t,"base64").toString("utf-8")}function eE(t){return new Promise(e=>setTimeout(e,t))}function Kn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function tE(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ti(t,...e){if(!tE(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 ga(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Kn(t.outputLen),Kn(t.blockLen)}function ln(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 $f(t,e){ti(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const fi=BigInt(2**32-1),Kc=BigInt(32);function rE(t,e=!1){return e?{h:Number(t&fi),l:Number(t>>Kc&fi)}:{h:Number(t>>Kc&fi)|0,l:Number(t&fi)|0}}function nE(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}=rE(t[i],e);[r[i],n[i]]=[s,o]}return[r,n]}const iE=(t,e,r)=>t<<r|e>>>32-r,sE=(t,e,r)=>e<<r|t>>>32-r,oE=(t,e,r)=>e<<r-32|t>>>64-r,aE=(t,e,r)=>t<<r-32|e>>>64-r,Rr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function cE(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Us(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Ot(t,e){return t<<32-e|t>>>e}const Hc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function uE(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Vc(t){for(let e=0;e<t.length;e++)t[e]=uE(t[e])}function lE(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function hn(t){return typeof t=="string"&&(t=lE(t)),ti(t),t}function hE(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];ti(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 ya=class{clone(){return this._cloneInto()}};function Of(t){const e=n=>t().update(hn(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function bn(t=32){if(Rr&&typeof Rr.getRandomValues=="function")return Rr.getRandomValues(new Uint8Array(t));if(Rr&&typeof Rr.randomBytes=="function")return Rr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const If=[],Pf=[],Df=[],fE=BigInt(0),Pn=BigInt(1),dE=BigInt(2),pE=BigInt(7),gE=BigInt(256),yE=BigInt(113);for(let t=0,e=Pn,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],If.push(2*(5*n+r)),Pf.push((t+1)*(t+2)/2%64);let i=fE;for(let s=0;s<7;s++)e=(e<<Pn^(e>>pE)*yE)%gE,e&dE&&(i^=Pn<<(Pn<<BigInt(s))-Pn);Df.push(i)}const[mE,vE]=nE(Df,!0),Wc=(t,e,r)=>r>32?oE(t,e,r):iE(t,e,r),Gc=(t,e,r)=>r>32?aE(t,e,r):sE(t,e,r);function wE(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=Wc(u,l,1)^r[a],f=Gc(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=Pf[o],c=Wc(i,s,a),u=Gc(i,s,a),l=If[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]^=vE[n]}r.fill(0)}let bE=class Sf extends ya{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,Kn(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=cE(this.state)}keccak(){Hc||Vc(this.state32),wE(this.state32,this.rounds),Hc||Vc(this.state32),this.posOut=0,this.pos=0}update(e){ln(this);const{blockLen:r,state:n}=this;e=hn(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){ln(this,!1),ti(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 Kn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if($f(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 Sf(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 EE=(t,e,r)=>Of(()=>new bE(e,t,r)),_E=EE(1,136,256/8),$E="https://rpc.walletconnect.org/v1";function xf(t){const e=`Ethereum Signed Message:
|
|
29
|
-
${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Ce.from(_E(r)).toString("hex")}async function OE(t,e,r,n,i,s){switch(r.t){case"eip191":return await IE(t,e,r.s);case"eip1271":return await PE(t,e,r.s,n,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}async function IE(t,e,r){return(await Lp({hash:xf(e),signature:r})).toLowerCase()===t.toLowerCase()}async function PE(t,e,r,n,i,s){const o=nn(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=xf(e).substring(2),f=a+h+c+u+l,p=await fetch(`${s||$E}/?chainId=${n}&projectId=${i}`,{method:"POST",body:JSON.stringify({id:DE(),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 DE(){return Date.now()+Math.floor(Math.random()*1e3)}function SE(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 D0.encode(s)}var xE=Object.defineProperty,AE=Object.defineProperties,CE=Object.getOwnPropertyDescriptors,Yc=Object.getOwnPropertySymbols,LE=Object.prototype.hasOwnProperty,RE=Object.prototype.propertyIsEnumerable,Jc=(t,e,r)=>e in t?xE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,NE=(t,e)=>{for(var r in e||(e={}))LE.call(e,r)&&Jc(t,r,e[r]);if(Yc)for(var r of Yc(e))RE.call(e,r)&&Jc(t,r,e[r]);return t},TE=(t,e)=>AE(t,CE(e));const jE="did:pkh:",ma=t=>t?.split(":"),ME=t=>{const e=t&&ma(t);if(e)return t.includes(jE)?e[3]:e[1]},Io=t=>{const e=t&&ma(t);if(e)return e[2]+":"+e[3]},Ki=t=>{const e=t&&ma(t);if(e)return e.pop()};async function Zc(t){const{cacao:e,projectId:r}=t,{s:n,p:i}=e,s=Af(i,i.iss),o=Ki(i.iss);return await OE(o,s,n,Io(i.iss),r)}const Af=(t,e)=>{const r=`${t.domain} wants you to sign in with your Ethereum account:`,n=Ki(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: ${ME(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=>`
|
|
30
|
-
- ${
|
|
31
|
-
`)};function FE(t){return Ce.from(JSON.stringify(t)).toString("base64")}function BE(t){return JSON.parse(Ce.from(t,"base64").toString("utf-8"))}function wr(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 UE(t,e,r,n={}){return r?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:qE(e,r,n)}}}function qE(t,e,r={}){e=e?.sort((i,s)=>i.localeCompare(s));const n=e.map(i=>({[`${t}/${i}`]:[r]}));return Object.assign({},...n)}function Cf(t){return wr(t),`urn:recap:${FE(t).replace(/=/g,"")}`}function Hn(t){const e=BE(t.replace("urn:recap:",""));return wr(e),e}function kE(t,e,r){const n=UE(t,e,r);return Cf(n)}function zE(t){return t&&t.includes("urn:recap:")}function KE(t,e){const r=Hn(t),n=Hn(e),i=HE(r,n);return Cf(i)}function HE(t,e){wr(t),wr(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]=TE(NE({},n.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((u=e.att[i])==null?void 0:u[a])})})}),n}function VE(t="",e){wr(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 Qc(t){var e;const r=Hn(t);wr(r);const n=(e=r.att)==null?void 0:e.eip155;return n?Object.keys(n).map(i=>i.split("/")[1]):[]}function Xc(t){const e=Hn(t);wr(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 Si(t){if(!t)return;const e=t?.[t.length-1];return zE(e)?e:void 0}function qs(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Lf(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function nt(t,...e){if(!Lf(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 eu(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 WE(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 tu(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}const tr=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),GE=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),YE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!YE)throw new Error("Non little-endian hardware is not supported");function JE(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Po(t){if(typeof t=="string")t=JE(t);else if(Lf(t))t=Do(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function ZE(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function QE(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 XE=(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 ru(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&&!e1(e))throw new Error("invalid output, must be aligned");return e}function nu(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 e1(t){return t.byteOffset%4===0}function Do(t){return Uint8Array.from(t)}function fn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}const Rf=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),t1=Rf("expand 16-byte k"),r1=Rf("expand 32-byte k"),n1=tr(t1),i1=tr(r1);function Z(t,e){return t<<e|t>>>32-e}function So(t){return t.byteOffset%4===0}const di=64,s1=16,Nf=2**32-1,iu=new Uint32Array;function o1(t,e,r,n,i,s,o,a){const c=i.length,u=new Uint8Array(di),l=tr(u),h=So(i)&&So(s),f=h?tr(i):iu,p=h?tr(s):iu;for(let d=0;d<c;o++){if(t(e,r,n,l,o,a),o>=Nf)throw new Error("arx: counter overflow");const y=Math.min(di,c-d);if(h&&y===di){const v=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let b=0,w;b<s1;b++)w=v+b,p[w]=f[w]^l[b];d+=di;continue}for(let v=0,b;v<y;v++)b=d+v,s[b]=i[b]^u[v];d+=y}}function a1(t,e){const{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=ZE({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return qs(i),qs(o),tu(s),tu(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),qs(h),h<0||h>=Nf)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,v;if(d===32)p.push(y=Do(a)),v=i1;else if(d===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),v=n1,p.push(y);else throw new Error(`arx: invalid 32-byte key, got length=${d}`);So(c)||p.push(c=Do(c));const b=tr(y);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(v,b,tr(c.subarray(0,16)),b),c=c.subarray(16)}const w=16-i;if(w!==c.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(w!==12){const O=new Uint8Array(12);O.set(c,s?0:12-c.length),c=O,p.push(c)}const E=tr(c);return o1(t,v,b,E,u,l,h,o),fn(...p),l}}const Re=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class c1{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=Po(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],v=o[9],b=Re(e,r+0),w=Re(e,r+2),E=Re(e,r+4),O=Re(e,r+6),x=Re(e,r+8),S=Re(e,r+10),D=Re(e,r+12),C=Re(e,r+14);let I=s[0]+(b&8191),q=s[1]+((b>>>13|w<<3)&8191),M=s[2]+((w>>>10|E<<6)&8191),j=s[3]+((E>>>7|O<<9)&8191),k=s[4]+((O>>>4|x<<12)&8191),L=s[5]+(x>>>1&8191),g=s[6]+((x>>>14|S<<2)&8191),m=s[7]+((S>>>11|D<<5)&8191),_=s[8]+((D>>>8|C<<8)&8191),P=s[9]+(C>>>5|i),$=0,A=$+I*a+q*(5*v)+M*(5*y)+j*(5*d)+k*(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 F=$+I*c+q*a+M*(5*v)+j*(5*y)+k*(5*d);$=F>>>13,F&=8191,F+=L*(5*p)+g*(5*f)+m*(5*h)+_*(5*l)+P*(5*u),$+=F>>>13,F&=8191;let U=$+I*u+q*c+M*a+j*(5*v)+k*(5*y);$=U>>>13,U&=8191,U+=L*(5*d)+g*(5*p)+m*(5*f)+_*(5*h)+P*(5*l),$+=U>>>13,U&=8191;let z=$+I*l+q*u+M*c+j*a+k*(5*v);$=z>>>13,z&=8191,z+=L*(5*y)+g*(5*d)+m*(5*p)+_*(5*f)+P*(5*h),$+=z>>>13,z&=8191;let B=$+I*h+q*l+M*u+j*c+k*a;$=B>>>13,B&=8191,B+=L*(5*v)+g*(5*y)+m*(5*d)+_*(5*p)+P*(5*f),$+=B>>>13,B&=8191;let H=$+I*f+q*h+M*l+j*u+k*c;$=H>>>13,H&=8191,H+=L*a+g*(5*v)+m*(5*y)+_*(5*d)+P*(5*p),$+=H>>>13,H&=8191;let Y=$+I*p+q*f+M*h+j*l+k*u;$=Y>>>13,Y&=8191,Y+=L*c+g*a+m*(5*v)+_*(5*y)+P*(5*d),$+=Y>>>13,Y&=8191;let pe=$+I*d+q*p+M*f+j*h+k*l;$=pe>>>13,pe&=8191,pe+=L*u+g*c+m*a+_*(5*v)+P*(5*y),$+=pe>>>13,pe&=8191;let te=$+I*y+q*d+M*p+j*f+k*h;$=te>>>13,te&=8191,te+=L*l+g*u+m*c+_*a+P*(5*v),$+=te>>>13,te&=8191;let J=$+I*v+q*y+M*d+j*p+k*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,F+=$,s[0]=A,s[1]=F,s[2]=U,s[3]=z,s[4]=B,s[5]=H,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;fn(n)}update(e){eu(this);const{buffer:r,blockLen:n}=this;e=Po(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(){fn(this.h,this.r,this.buffer,this.pad)}digestInto(e){eu(this),WE(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 u1(t){const e=(n,i)=>t(i).update(Po(n)).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}const l1=u1(t=>new c1(t));function h1(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],v=e[6],b=e[7],w=i,E=r[0],O=r[1],x=r[2],S=o,D=a,C=c,I=u,q=l,M=h,j=f,k=p,L=d,g=y,m=v,_=b,P=w,$=E,A=O,F=x;for(let z=0;z<s;z+=2)S=S+q|0,P=Z(P^S,16),L=L+P|0,q=Z(q^L,12),S=S+q|0,P=Z(P^S,8),L=L+P|0,q=Z(q^L,7),D=D+M|0,$=Z($^D,16),g=g+$|0,M=Z(M^g,12),D=D+M|0,$=Z($^D,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+k|0,F=Z(F^I,16),_=_+F|0,k=Z(k^_,12),I=I+k|0,F=Z(F^I,8),_=_+F|0,k=Z(k^_,7),S=S+M|0,F=Z(F^S,16),m=m+F|0,M=Z(M^m,12),S=S+M|0,F=Z(F^S,8),m=m+F|0,M=Z(M^m,7),D=D+j|0,P=Z(P^D,16),_=_+P|0,j=Z(j^_,12),D=D+j|0,P=Z(P^D,8),_=_+P|0,j=Z(j^_,7),C=C+k|0,$=Z($^C,16),L=L+$|0,k=Z(k^L,12),C=C+k|0,$=Z($^C,8),L=L+$|0,k=Z(k^L,7),I=I+q|0,A=Z(A^I,16),g=g+A|0,q=Z(q^g,12),I=I+q|0,A=Z(A^I,8),g=g+A|0,q=Z(q^g,7);let U=0;n[U++]=o+S|0,n[U++]=a+D|0,n[U++]=c+C|0,n[U++]=u+I|0,n[U++]=l+q|0,n[U++]=h+M|0,n[U++]=f+j|0,n[U++]=p+k|0,n[U++]=d+L|0,n[U++]=y+g|0,n[U++]=v+m|0,n[U++]=b+_|0,n[U++]=w+P|0,n[U++]=E+$|0,n[U++]=O+A|0,n[U++]=x+F|0}const f1=a1(h1,{counterRight:!1,counterLength:4,allowShortKeys:!1}),d1=new Uint8Array(16),su=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(d1.subarray(r))},p1=new Uint8Array(32);function ou(t,e,r,n,i){const s=t(e,r,p1),o=l1.create(s);i&&su(o,i),su(o,n);const a=new Uint8Array(16),c=GE(a);nu(c,0,BigInt(i?i.length:0),!0),nu(c,8,BigInt(n.length),!0),o.update(a);const u=o.digest();return fn(s,a),u}const g1=t=>(e,r,n)=>({encrypt(i,s){const o=i.length;s=ru(o+16,s,!1),s.set(i);const a=s.subarray(0,-16);t(e,r,a,a,1);const c=ou(t,e,r,a,n);return s.set(c,o),fn(c),s},decrypt(i,s){s=ru(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=ou(t,e,r,o,n);if(!QE(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,r,s,s,1),fn(c),s}}),Tf=XE({blockSize:64,nonceLength:12,tagLength:16},g1(f1));let jf=class extends ya{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,ga(e);const n=hn(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 ln(this),this.iHash.update(e),this}digestInto(e){ln(this),ti(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 hs=(t,e,r)=>new jf(t,e).update(r).digest();hs.create=(t,e)=>new jf(t,e);function y1(t,e,r){return ga(t),r===void 0&&(r=new Uint8Array(t.outputLen)),hs(t,hn(r),hn(e))}const ks=new Uint8Array([0]),au=new Uint8Array;function m1(t,e,r,n=32){if(ga(t),Kn(n),n>255*t.outputLen)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(n/t.outputLen);r===void 0&&(r=au);const s=new Uint8Array(i*t.outputLen),o=hs.create(t,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let u=0;u<i;u++)ks[0]=u+1,a.update(u===0?au:c).update(r).update(ks).digestInto(c),s.set(c,t.outputLen*u),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),ks.fill(0),s.slice(0,n)}const v1=(t,e,r,n,i)=>m1(t,y1(t,e,r),n,i);function w1(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 b1(t,e,r){return t&e^~t&r}function E1(t,e,r){return t&e^t&r^e&r}let _1=class extends ya{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=Us(this.buffer)}update(e){ln(this);const{view:r,buffer:n,blockLen:i}=this;e=hn(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=Us(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){ln(this),$f(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;w1(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=Us(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 $1=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]),Yt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Jt=new Uint32Array(64);class O1 extends _1{constructor(){super(64,32,8,!1),this.A=Yt[0]|0,this.B=Yt[1]|0,this.C=Yt[2]|0,this.D=Yt[3]|0,this.E=Yt[4]|0,this.F=Yt[5]|0,this.G=Yt[6]|0,this.H=Yt[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)Jt[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const f=Jt[h-15],p=Jt[h-2],d=Ot(f,7)^Ot(f,18)^f>>>3,y=Ot(p,17)^Ot(p,19)^p>>>10;Jt[h]=y+Jt[h-7]+d+Jt[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+b1(a,c,u)+$1[h]+Jt[h]|0,d=(Ot(n,2)^Ot(n,13)^Ot(n,22))+E1(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(){Jt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const ri=Of(()=>new O1);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const fs=BigInt(0),ds=BigInt(1),I1=BigInt(2);function br(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ni(t){if(!br(t))throw new Error("Uint8Array expected")}function dn(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const P1=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function pn(t){ni(t);let e="";for(let r=0;r<t.length;r++)e+=P1[t[r]];return e}function Jr(t){const e=t.toString(16);return e.length&1?"0"+e:e}function va(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?fs:BigInt("0x"+t)}const Ut={_0:48,_9:57,A:65,F:70,a:97,f:102};function cu(t){if(t>=Ut._0&&t<=Ut._9)return t-Ut._0;if(t>=Ut.A&&t<=Ut.F)return t-(Ut.A-10);if(t>=Ut.a&&t<=Ut.f)return t-(Ut.a-10)}function gn(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=cu(t.charCodeAt(s)),a=cu(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 yr(t){return va(pn(t))}function Vn(t){return ni(t),va(pn(Uint8Array.from(t).reverse()))}function yn(t,e){return gn(t.toString(16).padStart(e*2,"0"))}function ps(t,e){return yn(t,e).reverse()}function D1(t){return gn(Jr(t))}function rt(t,e,r){let n;if(typeof e=="string")try{n=gn(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(br(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 Wn(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];ni(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 S1(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 x1(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const zs=t=>typeof t=="bigint"&&fs<=t;function gs(t,e,r){return zs(t)&&zs(e)&&zs(r)&&e<=t&&t<r}function Kt(t,e,r,n){if(!gs(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Mf(t){let e;for(e=0;t>fs;t>>=ds,e+=1);return e}function A1(t,e){return t>>BigInt(e)&ds}function C1(t,e,r){return t|(r?ds:fs)<<BigInt(e)}const wa=t=>(I1<<BigInt(t-1))-ds,Ks=t=>new Uint8Array(t),uu=t=>Uint8Array.from(t);function Ff(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=Ks(t),i=Ks(t),s=0;const o=()=>{n.fill(1),i.fill(0),s=0},a=(...l)=>r(i,n,...l),c=(l=Ks())=>{i=a(uu([0]),l),n=a(),l.length!==0&&(i=a(uu([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 Wn(...h)};return(l,h)=>{o(),c(l);let f;for(;!(f=h(u()));)c();return o(),f}}const L1={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"||br(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 En(t,e,r={}){const n=(i,s,o)=>{const a=L1[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 R1=()=>{throw new Error("not implemented")};function xo(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 N1=Object.freeze({__proto__:null,isBytes:br,abytes:ni,abool:dn,bytesToHex:pn,numberToHexUnpadded:Jr,hexToNumber:va,hexToBytes:gn,bytesToNumberBE:yr,bytesToNumberLE:Vn,numberToBytesBE:yn,numberToBytesLE:ps,numberToVarBytesBE:D1,ensureBytes:rt,concatBytes:Wn,equalBytes:S1,utf8ToBytes:x1,inRange:gs,aInRange:Kt,bitLen:Mf,bitGet:A1,bitSet:C1,bitMask:wa,createHmacDrbg:Ff,validateObject:En,notImplemented:R1,memoized:xo});const Ae=BigInt(0),we=BigInt(1),hr=BigInt(2),T1=BigInt(3),Ao=BigInt(4),lu=BigInt(5),hu=BigInt(8);function Je(t,e){const r=t%e;return r>=Ae?r:e+r}function Bf(t,e,r){if(e<Ae)throw new Error("invalid exponent, negatives unsupported");if(r<=Ae)throw new Error("invalid modulus");if(r===we)return Ae;let n=we;for(;e>Ae;)e&we&&(n=n*t%r),t=t*t%r,e>>=we;return n}function wt(t,e,r){let n=t;for(;e-- >Ae;)n*=n,n%=r;return n}function Co(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=we;for(;r!==Ae;){const o=n/r,a=n%r,c=i-s*o;n=r,r=a,i=s,s=c}if(n!==we)throw new Error("invert: does not exist");return Je(i,e)}function j1(t){const e=(t-we)/hr;let r,n,i;for(r=t-we,n=0;r%hr===Ae;r/=hr,n++);for(i=hr;i<t&&Bf(i,e,t)!==t-we;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){const o=(t+we)/Ao;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+we)/hr;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,we<<BigInt(c-f-1));u=o.sqr(p),l=o.mul(l,p),h=o.mul(h,u),c=f}return l}}function M1(t){if(t%Ao===T1){const e=(t+we)/Ao;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%hu===lu){const e=(t-lu)/hu;return function(r,n){const i=r.mul(n,hr),s=r.pow(i,e),o=r.mul(n,s),a=r.mul(r.mul(o,hr),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 j1(t)}const F1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function B1(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=F1.reduce((n,i)=>(n[i]="function",n),e);return En(t,r)}function U1(t,e,r){if(r<Ae)throw new Error("invalid exponent, negatives unsupported");if(r===Ae)return t.ONE;if(r===we)return e;let n=t.ONE,i=e;for(;r>Ae;)r&we&&(n=t.mul(n,i)),i=t.sqr(i),r>>=we;return n}function q1(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 Uf(t,e){const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function qf(t,e,r=!1,n={}){if(t<=Ae)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=Uf(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:wa(i),ZERO:Ae,ONE:we,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&we)===we,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)=>U1(a,c,u),div:(c,u)=>Je(c*Co(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Co(c,t),sqrt:n.sqrt||(c=>(o||(o=M1(t)),o(a,c))),invertBatch:c=>q1(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?ps(c,s):yn(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?Vn(c):yr(c)}});return Object.freeze(a)}function kf(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 zf(t){const e=kf(t);return e+Math.ceil(e/2)}function k1(t,e,r=!1){const n=t.length,i=kf(e),s=zf(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const o=r?Vn(t):yr(t),a=Je(o,e-we)+we;return r?ps(a,i):yn(a,i)}const fu=BigInt(0),pi=BigInt(1);function Hs(t,e){const r=e.negate();return t?r:e}function Kf(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Vs(t,e){Kf(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1);return{windows:r,windowSize:n}}function z1(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 K1(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 Ws=new WeakMap,Hf=new WeakMap;function Gs(t){return Hf.get(t)||1}function H1(t,e){return{constTimeNegate:Hs,hasPrecomputes(r){return Gs(r)!==1},unsafeLadder(r,n,i=t.ZERO){let s=r;for(;n>fu;)n&pi&&(i=i.add(s)),s=s.double(),n>>=pi;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=Vs(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}=Vs(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+=pi);const y=p,v=p+Math.abs(d)-1,b=f%2!==0,w=d<0;d===0?c=c.add(Hs(b,n[y])):a=a.add(Hs(w,n[v]))}return{p:a,f:c}},wNAFUnsafe(r,n,i,s=t.ZERO){const{windows:o,windowSize:a}=Vs(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===fu)break;let p=Number(i&c);if(i>>=l,p>a&&(p-=u,i+=pi),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=Ws.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&Ws.set(n,i(s))),s},wNAFCached(r,n,i){const s=Gs(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=Gs(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){Kf(n,e),Hf.set(r,n),Ws.delete(r)}}}function V1(t,e,r,n){if(z1(r,t),K1(n,e),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=Mf(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 Vf(t){return B1(t.Fp),En(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Uf(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Nr=BigInt(0),Ys=BigInt(1);function W1(t){return En(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function G1(t){const e=W1(t),{P:r}=e,n=w=>Je(w,r),i=e.montgomeryBits,s=Math.ceil(i/8),o=e.nByteLength,a=e.adjustScalarBytes||(w=>w),c=e.powPminus2||(w=>Bf(w,r-BigInt(2),r));function u(w,E,O){const x=n(w*(E-O));return E=n(E-x),O=n(O+x),[E,O]}const l=(e.a-BigInt(2))/BigInt(4);function h(w,E){Kt("u",w,Nr,r),Kt("scalar",E,Nr,r);const O=E,x=w;let S=Ys,D=Nr,C=w,I=Ys,q=Nr,M;for(let k=BigInt(i-1);k>=Nr;k--){const L=O>>k&Ys;q^=L,M=u(q,S,C),S=M[0],C=M[1],M=u(q,D,I),D=M[0],I=M[1],q=L;const g=S+D,m=n(g*g),_=S-D,P=n(_*_),$=m-P,A=C+I,F=C-I,U=n(F*g),z=n(A*_),B=U+z,H=U-z;C=n(B*B),I=n(x*n(H*H)),S=n(m*P),D=n($*(m+n(l*$)))}M=u(q,S,C),S=M[0],C=M[1],M=u(q,D,I),D=M[0],I=M[1];const j=c(D);return n(S*j)}function f(w){return ps(n(w),s)}function p(w){const E=rt("u coordinate",w,s);return o===32&&(E[31]&=127),Vn(E)}function d(w){const E=rt("scalar",w),O=E.length;if(O!==s&&O!==o){let x=""+s+" or "+o;throw new Error("invalid scalar, expected "+x+" bytes, got "+O)}return Vn(a(E))}function y(w,E){const O=p(E),x=d(w),S=h(O,x);if(S===Nr)throw new Error("invalid private or public key received");return f(S)}const v=f(e.Gu);function b(w){return y(w,v)}return{scalarMult:y,scalarMultBase:b,getSharedSecret:(w,E)=>y(w,E),getPublicKey:w=>b(w),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:v}}const Lo=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const Y1=BigInt(1),du=BigInt(2),J1=BigInt(3),Z1=BigInt(5);BigInt(8);function Q1(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=Lo,o=t*t%s*t%s,a=wt(o,du,s)*o%s,c=wt(a,Y1,s)*t%s,u=wt(c,Z1,s)*c%s,l=wt(u,e,s)*u%s,h=wt(l,r,s)*l%s,f=wt(h,n,s)*h%s,p=wt(f,i,s)*f%s,d=wt(p,i,s)*f%s,y=wt(d,e,s)*u%s;return{pow_p_5_8:wt(y,du,s)*t%s,b2:o}}function X1(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Ro=G1({P:Lo,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{const e=Lo,{pow_p_5_8:r,b2:n}=Q1(t);return Je(wt(r,J1,e)*n,e)},adjustScalarBytes:X1,randomBytes:bn});function pu(t){t.lowS!==void 0&&dn("lowS",t.lowS),t.prehash!==void 0&&dn("prehash",t.prehash)}function e_(t){const e=Vf(t);En(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:t_,hexToBytes:r_}=N1;class n_ extends Error{constructor(e=""){super(e)}}const kt={Err:n_,_tlv:{encode:(t,e)=>{const{Err:r}=kt;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=Jr(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?Jr(i.length/2|128):"";return Jr(t)+s+i+e},decode(t,e){const{Err:r}=kt;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}=kt;if(t<zt)throw new e("integer: negative integers are not allowed");let r=Jr(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}=kt;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_(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=kt,i=typeof t=="string"?r_(t):t;ni(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}=kt,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),s=n+i;return e.encode(48,s)}},zt=BigInt(0),De=BigInt(1);BigInt(2);const gu=BigInt(3);BigInt(4);function i_(t){const e=e_(t),{Fp:r}=e,n=qf(e.n,e.nBitLength),i=e.toBytes||((y,v,b)=>{const w=v.toAffine();return Wn(Uint8Array.from([4]),r.toBytes(w.x),r.toBytes(w.y))}),s=e.fromBytes||(y=>{const v=y.subarray(1),b=r.fromBytes(v.subarray(0,r.BYTES)),w=r.fromBytes(v.subarray(r.BYTES,2*r.BYTES));return{x:b,y:w}});function o(y){const{a:v,b}=e,w=r.sqr(y),E=r.mul(w,y);return r.add(r.add(E,r.mul(y,v)),b)}if(!r.eql(r.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return gs(y,De,e.n)}function c(y){const{allowedPrivateKeyLengths:v,nByteLength:b,wrapPrivateKey:w,n:E}=e;if(v&&typeof y!="bigint"){if(br(y)&&(y=pn(y)),typeof y!="string"||!v.includes(y.length))throw new Error("invalid private key");y=y.padStart(b*2,"0")}let O;try{O=typeof y=="bigint"?y:yr(rt("private key",y,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof y)}return w&&(O=Je(O,E)),Kt("private key",O,De,E),O}function u(y){if(!(y instanceof f))throw new Error("ProjectivePoint expected")}const l=xo((y,v)=>{const{px:b,py:w,pz:E}=y;if(r.eql(E,r.ONE))return{x:b,y:w};const O=y.is0();v==null&&(v=O?r.ONE:r.inv(E));const x=r.mul(b,v),S=r.mul(w,v),D=r.mul(E,v);if(O)return{x:r.ZERO,y:r.ZERO};if(!r.eql(D,r.ONE))throw new Error("invZ was invalid");return{x,y:S}}),h=xo(y=>{if(y.is0()){if(e.allowInfinityPoint&&!r.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:v,y:b}=y.toAffine();if(!r.isValid(v)||!r.isValid(b))throw new Error("bad point: x or y not FE");const w=r.sqr(b),E=o(v);if(!r.eql(w,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(v,b,w){if(this.px=v,this.py=b,this.pz=w,v==null||!r.isValid(v))throw new Error("x required");if(b==null||!r.isValid(b))throw new Error("y required");if(w==null||!r.isValid(w))throw new Error("z required");Object.freeze(this)}static fromAffine(v){const{x:b,y:w}=v||{};if(!v||!r.isValid(b)||!r.isValid(w))throw new Error("invalid affine point");if(v instanceof f)throw new Error("projective point not allowed");const E=O=>r.eql(O,r.ZERO);return E(b)&&E(w)?f.ZERO:new f(b,w,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(v){const b=r.invertBatch(v.map(w=>w.pz));return v.map((w,E)=>w.toAffine(b[E])).map(f.fromAffine)}static fromHex(v){const b=f.fromAffine(s(rt("pointHex",v)));return b.assertValidity(),b}static fromPrivateKey(v){return f.BASE.multiply(c(v))}static msm(v,b){return V1(f,n,v,b)}_setWindowSize(v){d.setWindowSize(this,v)}assertValidity(){h(this)}hasEvenY(){const{y:v}=this.toAffine();if(r.isOdd)return!r.isOdd(v);throw new Error("Field doesn't support isOdd")}equals(v){u(v);const{px:b,py:w,pz:E}=this,{px:O,py:x,pz:S}=v,D=r.eql(r.mul(b,S),r.mul(O,E)),C=r.eql(r.mul(w,S),r.mul(x,E));return D&&C}negate(){return new f(this.px,r.neg(this.py),this.pz)}double(){const{a:v,b}=e,w=r.mul(b,gu),{px:E,py:O,pz:x}=this;let S=r.ZERO,D=r.ZERO,C=r.ZERO,I=r.mul(E,E),q=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),S=r.mul(v,C),D=r.mul(w,M),D=r.add(S,D),S=r.sub(q,D),D=r.add(q,D),D=r.mul(S,D),S=r.mul(j,S),C=r.mul(w,C),M=r.mul(v,M),j=r.sub(I,M),j=r.mul(v,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),D=r.add(D,I),M=r.mul(O,x),M=r.add(M,M),I=r.mul(M,j),S=r.sub(S,I),C=r.mul(M,q),C=r.add(C,C),C=r.add(C,C),new f(S,D,C)}add(v){u(v);const{px:b,py:w,pz:E}=this,{px:O,py:x,pz:S}=v;let D=r.ZERO,C=r.ZERO,I=r.ZERO;const q=e.a,M=r.mul(e.b,gu);let j=r.mul(b,O),k=r.mul(w,x),L=r.mul(E,S),g=r.add(b,w),m=r.add(O,x);g=r.mul(g,m),m=r.add(j,k),g=r.sub(g,m),m=r.add(b,E);let _=r.add(O,S);return m=r.mul(m,_),_=r.add(j,L),m=r.sub(m,_),_=r.add(w,E),D=r.add(x,S),_=r.mul(_,D),D=r.add(k,L),_=r.sub(_,D),I=r.mul(q,m),D=r.mul(M,L),I=r.add(D,I),D=r.sub(k,I),I=r.add(k,I),C=r.mul(D,I),k=r.add(j,j),k=r.add(k,j),L=r.mul(q,L),m=r.mul(M,m),k=r.add(k,L),L=r.sub(j,L),L=r.mul(q,L),m=r.add(m,L),j=r.mul(k,m),C=r.add(C,j),j=r.mul(_,m),D=r.mul(g,D),D=r.sub(D,j),j=r.mul(g,k),I=r.mul(_,I),I=r.add(I,j),new f(D,C,I)}subtract(v){return this.add(v.negate())}is0(){return this.equals(f.ZERO)}wNAF(v){return d.wNAFCached(this,v,f.normalizeZ)}multiplyUnsafe(v){const{endo:b,n:w}=e;Kt("scalar",v,zt,w);const E=f.ZERO;if(v===zt)return E;if(this.is0()||v===De)return this;if(!b||d.hasPrecomputes(this))return d.wNAFCachedUnsafe(this,v,f.normalizeZ);let{k1neg:O,k1:x,k2neg:S,k2:D}=b.splitScalar(v),C=E,I=E,q=this;for(;x>zt||D>zt;)x&De&&(C=C.add(q)),D&De&&(I=I.add(q)),q=q.double(),x>>=De,D>>=De;return O&&(C=C.negate()),S&&(I=I.negate()),I=new f(r.mul(I.px,b.beta),I.py,I.pz),C.add(I)}multiply(v){const{endo:b,n:w}=e;Kt("scalar",v,De,w);let E,O;if(b){const{k1neg:x,k1:S,k2neg:D,k2:C}=b.splitScalar(v);let{p:I,f:q}=this.wNAF(S),{p:M,f:j}=this.wNAF(C);I=d.constTimeNegate(x,I),M=d.constTimeNegate(D,M),M=new f(r.mul(M.px,b.beta),M.py,M.pz),E=I.add(M),O=q.add(j)}else{const{p:x,f:S}=this.wNAF(v);E=x,O=S}return f.normalizeZ([E,O])[0]}multiplyAndAddUnsafe(v,b,w){const E=f.BASE,O=(S,D)=>D===zt||D===De||!S.equals(E)?S.multiplyUnsafe(D):S.multiply(D),x=O(this,b).add(O(v,w));return x.is0()?void 0:x}toAffine(v){return l(this,v)}isTorsionFree(){const{h:v,isTorsionFree:b}=e;if(v===De)return!0;if(b)return b(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:v,clearCofactor:b}=e;return v===De?this:b?b(f,this):this.multiplyUnsafe(e.h)}toRawBytes(v=!0){return dn("isCompressed",v),this.assertValidity(),i(f,this,v)}toHex(v=!0){return dn("isCompressed",v),pn(this.toRawBytes(v))}}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=H1(f,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function s_(t){const e=Vf(t);return En(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function o_(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 Co(L,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:h}=i_({...e,toBytes(L,g,m){const _=g.toAffine(),P=r.toBytes(_.x),$=Wn;return dn("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=yr(_);if(!gs(P,De,r.ORDER))throw new Error("Point is not on curve");const $=l(P);let A;try{A=r.sqrt($)}catch(U){const z=U instanceof Error?": "+U.message:"";throw new Error("Point is not on curve"+z)}const F=(A&De)===De;return(m&1)===1!==F&&(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=>pn(yn(L,e.nByteLength));function p(L){const g=n>>De;return L>g}function d(L){return p(L)?o(-L):L}const y=(L,g,m)=>yr(L.slice(g,m));class v{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 v(y(g,0,m),y(g,m,2*m))}static fromDER(g){const{r:m,s:_}=kt.toSig(rt("DER",g));return new v(m,_)}assertValidity(){Kt("r",this.r,De,n),Kt("s",this.s,De,n)}addRecoveryBit(g){return new v(this.r,this.s,g)}recoverPublicKey(g){const{r:m,s:_,recovery:P}=this,$=S(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 F=P&1?"03":"02",U=c.fromHex(F+f(A)),z=a(A),B=o(-$*z),H=o(_*z),Y=c.BASE.multiplyAndAddUnsafe(U,B,H);if(!Y)throw new Error("point at infinify");return Y.assertValidity(),Y}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return gn(this.toDERHex())}toDERHex(){return kt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return gn(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=zf(e.n);return k1(e.randomBytes(L),e.n)},precompute(L=8,g=c.BASE){return g._setWindowSize(L),g.multiply(BigInt(3)),g}};function w(L,g=!0){return c.fromPrivateKey(L).toRawBytes(g)}function E(L){const g=br(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=yr(L),m=L.length*8-e.nBitLength;return m>0?g>>BigInt(m):g},S=e.bits2int_modN||function(L){return o(x(L))},D=wa(e.nBitLength);function C(L){return Kt("num < 2^"+e.nBitLength,L,zt,D),yn(L,e.nByteLength)}function I(L,g,m=q){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:F}=m;$==null&&($=!0),L=rt("msgHash",L),pu(m),A&&(L=rt("prehashed msgHash",_(L)));const U=S(L),z=u(g),B=[C(z),C(U)];if(F!=null&&F!==!1){const te=F===!0?P(r.BYTES):F;B.push(rt("extraEntropy",te))}const H=Wn(...B),Y=U;function pe(te){const J=x(te);if(!h(J))return;const Be=a(J),Le=c.BASE.multiply(J).toAffine(),ke=o(Le.x);if(ke===zt)return;const ot=o(Be*o(Y+ke*z));if(ot===zt)return;let Tt=(Le.x===ke?0:2)|Number(Le.y&De),Sr=ot;return $&&p(ot)&&(Sr=d(ot),Tt^=1),new v(ke,Sr,Tt)}return{seed:H,k2sig:pe}}const q={lowS:e.lowS,prehash:!1},M={lowS:e.lowS,prehash:!1};function j(L,g,m=q){const{seed:_,k2sig:P}=I(L,g,m),$=e;return Ff($.hash.outputLen,$.nByteLength,$.hmac)(_,P)}c.BASE._setWindowSize(8);function k(L,g,m,_=M){const P=L;g=rt("msgHash",g),m=rt("publicKey",m);const{lowS:$,prehash:A,format:F}=_;if(pu(_),"strict"in _)throw new Error("options.strict was renamed to lowS");if(F!==void 0&&F!=="compact"&&F!=="der")throw new Error("format must be compact or der");const U=typeof P=="string"||br(P),z=!U&&!F&&typeof P=="object"&&P!==null&&typeof P.r=="bigint"&&typeof P.s=="bigint";if(!U&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let B,H;try{if(z&&(B=new v(P.r,P.s)),U){try{F!=="compact"&&(B=v.fromDER(P))}catch(ot){if(!(ot instanceof kt.Err))throw ot}!B&&F!=="der"&&(B=v.fromCompact(P))}H=c.fromHex(m)}catch{return!1}if(!B||$&&B.hasHighS())return!1;A&&(g=e.hash(g));const{r:Y,s:pe}=B,te=S(g),J=a(pe),Be=o(te*J),Le=o(Y*J),ke=c.BASE.multiplyAndAddUnsafe(H,Be,Le)?.toAffine();return ke?o(ke.x)===Y:!1}return{CURVE:e,getPublicKey:w,getSharedSecret:O,sign:j,verify:k,ProjectivePoint:c,Signature:v,utils:b}}function a_(t){return{hash:t,hmac:(e,...r)=>hs(t,e,hE(...r)),randomBytes:bn}}function c_(t,e){const r=n=>o_({...t,...a_(n)});return{...r(e),create:r}}const Wf=qf(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),u_=Wf.create(BigInt("-3")),l_=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),h_=c_({a:u_,b:l_,Fp:Wf,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},ri),Gf="base10",Ke="base16",bt="base64pad",Qt="base64url",ii="utf8",Yf=0,Ht=1,si=2,f_=0,yu=1,Mn=12,ba=32;function d_(){const t=Ro.utils.randomPrivateKey(),e=Ro.getPublicKey(t);return{privateKey:Ze(t,Ke),publicKey:Ze(e,Ke)}}function No(){const t=bn(ba);return Ze(t,Ke)}function p_(t,e){const r=Ro.getSharedSecret(ht(t,Ke),ht(e,Ke)),n=v1(ri,r,void 0,void 0,ba);return Ze(n,Ke)}function xi(t){const e=ri(ht(t,Ke));return Ze(e,Ke)}function Ct(t){const e=ri(ht(t,ii));return Ze(e,Ke)}function Jf(t){return ht(`${t}`,Gf)}function Er(t){return Number(Ze(t,Gf))}function Zf(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Qf(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4;return e+"=".repeat(r)}function g_(t){const e=Jf(typeof t.type<"u"?t.type:Yf);if(Er(e)===Ht&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof t.senderPublicKey<"u"?ht(t.senderPublicKey,Ke):void 0,n=typeof t.iv<"u"?ht(t.iv,Ke):bn(Mn),i=ht(t.symKey,Ke),s=Tf(i,n).encrypt(ht(t.message,ii)),o=Xf({type:e,sealed:s,iv:n,senderPublicKey:r});return t.encoding===Qt?Zf(o):o}function y_(t){const e=ht(t.symKey,Ke),{sealed:r,iv:n}=Gn({encoded:t.encoded,encoding:t.encoding}),i=Tf(e,n).decrypt(r);if(i===null)throw new Error("Failed to decrypt");return Ze(i,ii)}function m_(t,e){const r=Jf(si),n=bn(Mn),i=ht(t,ii),s=Xf({type:r,sealed:i,iv:n});return e===Qt?Zf(s):s}function v_(t,e){const{sealed:r}=Gn({encoded:t,encoding:e});return Ze(r,ii)}function Xf(t){if(Er(t.type)===si)return Ze(jn([t.type,t.sealed]),bt);if(Er(t.type)===Ht){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ze(jn([t.type,t.senderPublicKey,t.iv,t.sealed]),bt)}return Ze(jn([t.type,t.iv,t.sealed]),bt)}function Gn(t){const e=(t.encoding||bt)===Qt?Qf(t.encoded):t.encoded,r=ht(e,bt),n=r.slice(f_,yu),i=yu;if(Er(n)===Ht){const c=i+ba,u=c+Mn,l=r.slice(i,c),h=r.slice(c,u),f=r.slice(u);return{type:n,sealed:f,iv:h,senderPublicKey:l}}if(Er(n)===si){const c=r.slice(i),u=bn(Mn);return{type:n,sealed:c,iv:u}}const s=i+Mn,o=r.slice(i,s),a=r.slice(s);return{type:n,sealed:a,iv:o}}function w_(t,e){const r=Gn({encoded:t,encoding:e?.encoding});return ed({type:Er(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Ze(r.senderPublicKey,Ke):void 0,receiverPublicKey:e?.receiverPublicKey})}function ed(t){const e=t?.type||Yf;if(e===Ht){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 mu(t){return t.type===Ht&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function vu(t){return t.type===si}function b_(t){const e=Ce.from(t.x,"base64"),r=Ce.from(t.y,"base64");return jn([new Uint8Array([4]),e,r])}function E_(t,e){const[r,n,i]=t.split("."),s=Ce.from(Qf(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=ri(c),l=b_(e);if(!h_.verify(jn([o,a]),u,l))throw new Error("Invalid signature");return wo(t).payload}const __="irn";function Hi(t){return t?.relay||{protocol:__}}function Rn(t){const e=gb[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function $_(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 wu(t){if(!t.includes("wc:")){const u=_f(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:O_(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:$_(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function O_(t){return t.startsWith("//")?t.substring(2):t}function I_(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 bu(t){const e=new URLSearchParams,r=I_(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 gi(t,e,r){return`${t}?wc_ev=${r}&topic=${e}`}var P_=Object.defineProperty,D_=Object.defineProperties,S_=Object.getOwnPropertyDescriptors,Eu=Object.getOwnPropertySymbols,x_=Object.prototype.hasOwnProperty,A_=Object.prototype.propertyIsEnumerable,_u=(t,e,r)=>e in t?P_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,C_=(t,e)=>{for(var r in e||(e={}))x_.call(e,r)&&_u(t,r,e[r]);if(Eu)for(var r of Eu(e))A_.call(e,r)&&_u(t,r,e[r]);return t},L_=(t,e)=>D_(t,S_(e));function _n(t){const e=[];return t.forEach(r=>{const[n,i]=r.split(":");e.push(`${n}:${i}`)}),e}function R_(t){const e=[];return Object.values(t).forEach(r=>{e.push(..._n(r.accounts))}),e}function N_(t,e){const r=[];return Object.values(t).forEach(n=>{_n(n.accounts).includes(e)&&r.push(...n.methods)}),r}function T_(t,e){const r=[];return Object.values(t).forEach(n=>{_n(n.accounts).includes(e)&&r.push(...n.events)}),r}function ys(t){return t.includes(":")}function Zr(t){return ys(t)?t.split(":")[0]:t}function $u(t){var e,r,n;const i={};if(!rr(t))return i;for(const[s,o]of Object.entries(t)){const a=ys(s)?[s]:o.chains,c=o.methods||[],u=o.events||[],l=Zr(s);i[l]=L_(C_({},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 j_(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 Ou(t,e){e=e.map(n=>n.replace("did:pkh:",""));const r=j_(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 M_(t,e){var r,n,i,s,o,a;const c=$u(t),u=$u(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 F_={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}},B_={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 T(t,e){const{message:r,code:n}=B_[t];return{message:e?`${r} ${e}`:r,code:n}}function re(t,e){const{message:r,code:n}=F_[t];return{message:e?`${r} ${e}`:r,code:n}}function Et(t,e){return!!Array.isArray(t)}function rr(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function qe(t){return typeof t>"u"}function Ee(t,e){return e&&qe(t)?!0:typeof t=="string"&&!!t.trim().length}function Ea(t,e){return typeof t=="number"&&!isNaN(t)}function U_(t,e){const{requiredNamespaces:r}=e,n=Object.keys(t.namespaces),i=Object.keys(r);let s=!0;return gr(i,n)?(n.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],l=_n(a),h=r[o];(!gr(mf(o,h),l)||!gr(h.methods,c)||!gr(h.events,u))&&(s=!1)}),s):!1}function Vi(t){return Ee(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function q_(t){if(Ee(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const r=e[0]+":"+e[1];return!!e[2]&&Vi(r)}}return!1}function k_(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=_f(t);return e(r)}}catch{}return!1}function z_(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function K_(t){return t?.topic}function H_(t,e){let r=null;return Ee(t?.publicKey,!1)||(r=T("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function Iu(t){let e=!0;return Et(t)?t.length&&(e=t.every(r=>Ee(r,!1))):e=!1,e}function V_(t,e,r){let n=null;return Et(e)&&e.length?e.forEach(i=>{n||Vi(i)||(n=re("UNSUPPORTED_CHAINS",`${r}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):Vi(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 W_(t,e,r){let n=null;return Object.entries(t).forEach(([i,s])=>{if(n)return;const o=V_(i,mf(i,s),`${e} ${r}`);o&&(n=o)}),n}function G_(t,e){let r=null;return Et(t)?t.forEach(n=>{r||q_(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 Y_(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;const i=G_(n?.accounts,`${e} namespace`);i&&(r=i)}),r}function J_(t,e){let r=null;return Iu(t?.methods)?Iu(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 td(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;const i=J_(n,`${e}, namespace`);i&&(r=i)}),r}function Z_(t,e,r){let n=null;if(t&&rr(t)){const i=td(t,e);i&&(n=i);const s=W_(t,e,r);s&&(n=s)}else n=T("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return n}function Js(t,e){let r=null;if(t&&rr(t)){const n=td(t,e);n&&(r=n);const i=Y_(t,e);i&&(r=i)}else r=T("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function rd(t){return Ee(t.protocol,!0)}function Q_(t,e){let r=!1;return t?t&&Et(t)&&t.length&&t.forEach(n=>{r=rd(n)}):r=!0,r}function X_(t){return typeof t=="number"}function Ye(t){return typeof t<"u"&&typeof t!==null}function e$(t){return!(!t||typeof t!="object"||!t.code||!Ea(t.code)||!t.message||!Ee(t.message,!1))}function t$(t){return!(qe(t)||!Ee(t.method,!1))}function r$(t){return!(qe(t)||qe(t.result)&&qe(t.error)||!Ea(t.id)||!Ee(t.jsonrpc,!1))}function n$(t){return!(qe(t)||!Ee(t.name,!1))}function Pu(t,e){return!(!Vi(e)||!R_(t).includes(e))}function i$(t,e,r){return Ee(r,!1)?N_(t,e).includes(r):!1}function s$(t,e,r){return Ee(r,!1)?T_(t,e).includes(r):!1}function Du(t,e,r){let n=null;const i=o$(t),s=a$(e),o=Object.keys(i),a=Object.keys(s),c=Su(Object.keys(t)),u=Su(Object.keys(e)),l=c.filter(h=>!u.includes(h));return l.length&&(n=T("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.
|
|
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-MIfy00vZ.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={};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
|
+
${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
|
+
- ${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
|
+
`)};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.
|
|
32
33
|
Required: ${l.toString()}
|
|
33
|
-
Received: ${Object.keys(e).toString()}`)),
|
|
34
|
+
Received: ${Object.keys(e).toString()}`)),yr(o,a)||(n=N("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces.
|
|
34
35
|
Required: ${o.toString()}
|
|
35
|
-
Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||n)return;const f=
|
|
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}
|
|
36
37
|
Required: ${h}
|
|
37
|
-
Approved: ${f.toString()}`))}),o.forEach(h=>{n||(gr(i[h].methods,s[h].methods)?gr(i[h].events,s[h].events)||(n=T("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${h}`)):n=T("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${h}`))}),n}function o$(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 Su(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function a$(t){const e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:_n(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 c$(t,e){return Ea(t)&&t<=e.max&&t>=e.min}function xu(){const t=ei();return new Promise(e=>{switch(t){case it.browser:e(u$());break;case it.reactNative:e(l$());break;case it.node:e(h$());break;default:e(!0)}})}function u$(){return wn()&&navigator?.onLine}async function l$(){return nr()&&typeof K<"u"&&K!=null&&K.NetInfo?(await(K==null?void 0:K.NetInfo.fetch()))?.isConnected:!0}function h$(){return!0}function f$(t){switch(ei()){case it.browser:d$(t);break;case it.reactNative:p$(t);break}}function d$(t){!nr()&&wn()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function p$(t){nr()&&typeof K<"u"&&K!=null&&K.NetInfo&&K?.NetInfo.addEventListener(e=>t(e?.isConnected))}function g$(){var t;return wn()&&vr()?((t=vr())==null?void 0:t.visibilityState)==="visible":!0}const Zs={};class Dn{static get(e){return Zs[e]}static set(e,r){Zs[e]=r}static delete(e){delete Zs[e]}}var _a={exports:{}},sn=typeof Reflect=="object"?Reflect:null,Au=sn&&typeof sn.apply=="function"?sn.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Ai;sn&&typeof sn.ownKeys=="function"?Ai=sn.ownKeys:Object.getOwnPropertySymbols?Ai=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Ai=function(e){return Object.getOwnPropertyNames(e)};function y$(t){console&&console.warn&&console.warn(t)}var nd=Number.isNaN||function(e){return e!==e};function ae(){ae.init.call(this)}_a.exports=ae;_a.exports.once=b$;ae.EventEmitter=ae;ae.prototype._events=void 0;ae.prototype._eventsCount=0;ae.prototype._maxListeners=void 0;var Cu=10;function ms(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 Cu},set:function(t){if(typeof t!="number"||t<0||nd(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Cu=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||nd(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 id(t){return t._maxListeners===void 0?ae.defaultMaxListeners:t._maxListeners}ae.prototype.getMaxListeners=function(){return id(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")Au(c,this,r);else for(var u=c.length,l=ud(c,u),n=0;n<u;++n)Au(l[n],this,r);return!0};function sd(t,e,r,n){var i,s,o;if(ms(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=id(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,y$(a)}return t}ae.prototype.addListener=function(e,r){return sd(this,e,r,!1)};ae.prototype.on=ae.prototype.addListener;ae.prototype.prependListener=function(e,r){return sd(this,e,r,!0)};function m$(){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 od(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=m$.bind(n);return i.listener=r,n.wrapFn=i,i}ae.prototype.once=function(e,r){return ms(r),this.on(e,od(this,e,r)),this};ae.prototype.prependOnceListener=function(e,r){return ms(r),this.prependListener(e,od(this,e,r)),this};ae.prototype.removeListener=function(e,r){var n,i,s,o,a;if(ms(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():v$(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 ad(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?w$(i):ud(i,i.length)}ae.prototype.listeners=function(e){return ad(this,e,!0)};ae.prototype.rawListeners=function(e){return ad(this,e,!1)};ae.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):cd.call(t,e)};ae.prototype.listenerCount=cd;function cd(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?Ai(this._events):[]};function ud(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function v$(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function w$(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function b$(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))}ld(t,e,s,{once:!0}),e!=="error"&&E$(t,i,{once:!0})})}function E$(t,e,r){typeof t.on=="function"&&ld(t,"error",e,r)}function ld(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 Ir=_a.exports;const _$=Yn(Ir);function $$(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Pe(t,...e){try{return $$(t(...e))}catch(r){return Promise.reject(r)}}function O$(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function I$(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Ci(t){if(O$(t))return String(t);if(I$(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Ci(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const To="base64:";function P$(t){return typeof t=="string"?t:To+x$(t)}function D$(t){return typeof t!="string"||!t.startsWith(To)?t:S$(t.slice(To.length))}function S$(t){return globalThis.Buffer?Ce.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function x$(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 A$(...t){return Ge(t.join(":"))}function yi(t){return t=Ge(t),t?t+":":""}function C$(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 L$(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const R$="memory",N$=()=>{const t=new Map;return{name:R$,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 T$(t={}){const e={mounts:{"":t.driver||N$()},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 Lu(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",v=Ge(y?d:d.key),b=y?void 0:d.value,w=y||!d.options?l:{...l,...d.options},E=r(v);p(E).items.push({key:v,value:b,relativeKey:E.relativeKey,options:w})}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=>ai(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:A$(h.base,p.key),value:ai(p.value)}))):Promise.all(h.items.map(f=>Pe(h.driver.getItem,f.relativeKey,f.options).then(p=>({key:f.key,value:ai(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=>D$(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,Ci(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:Ci(f.value),options:f.options})),l);h.driver.setItem&&await Promise.all(h.items.map(f=>Pe(h.driver.setItem,f.relativeKey,Ci(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,P$(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=>ai(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=yi(u);const h=n(u,!0);let f=[];const p=[];let d=!0;for(const v of h){v.driver.flags?.maxDepth||(d=!1);const b=await Pe(v.driver.getKeys,v.relativeBase,l);for(const w of b){const E=v.mountpoint+Ge(w);f.some(O=>E.startsWith(O))||p.push(E)}f=[v.mountpoint,...f.filter(w=>!w.startsWith(v.mountpoint))]}const y=l.maxDepth!==void 0&&!d;return p.filter(v=>(!y||C$(v,l.maxDepth))&&L$(v,u))},async clear(u,l={}){u=yi(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=>Ru(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=yi(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(Lu(l,i,u)).then(h=>{e.unwatch[u]=h}).catch(console.error),c},async unmount(u,l=!0){u=yi(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u]?.(),delete e.unwatch[u]),l&&await Ru(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 Lu(t,e,r){return t.watch?t.watch((n,i)=>e(n,r+i)):()=>{}}async function Ru(t){typeof t.dispose=="function"&&await Pe(t.dispose)}const j$="idb-keyval";var M$=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=i=>e+i;let n;return t.dbName&&t.storeName&&(n=Rp(t.dbName,t.storeName)),{name:j$,options:t,async hasItem(i){return!(typeof await ja(r(i),n)>"u")},async getItem(i){return await ja(r(i),n)??null},setItem(i,s){return Np(r(i),s,n)},removeItem(i){return Tp(r(i),n)},getKeys(){return jp(n)},clear(){return Mp(n)}}};const F$="WALLET_CONNECT_V2_INDEXED_DB",B$="keyvaluestorage";let U$=class{constructor(){this.indexedDb=T$({driver:M$({dbName:F$,storeName:B$})})}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,Vt(r))}async removeItem(e){await this.indexedDb.removeItem(e)}};var Qs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof K<"u"?K:typeof self<"u"?self:{},Li={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 Qs<"u"&&Qs.localStorage?Li.exports=Qs.localStorage:typeof window<"u"&&window.localStorage?Li.exports=window.localStorage:Li.exports=new e})();function q$(t){var e;return[t[0],mr((e=t[1])!=null?e:"")]}let k$=class{constructor(){this.localStorage=Li.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(q$)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return mr(r)}async setItem(e,r){this.localStorage.setItem(e,Vt(r))}async removeItem(e){this.localStorage.removeItem(e)}};const z$="wc_storage_version",Nu=1,K$=async(t,e,r)=>{const n=z$,i=await e.getItem(n);if(i&&i>=Nu){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,Nu),r(e),H$(t,o)},H$=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};let V$=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new k$;this.storage=e;try{const r=new U$;K$(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 hd={exports:{}},on=typeof Reflect=="object"?Reflect:null,Tu=on&&typeof on.apply=="function"?on.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Ri;on&&typeof on.ownKeys=="function"?Ri=on.ownKeys:Object.getOwnPropertySymbols?Ri=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Ri=function(e){return Object.getOwnPropertyNames(e)};function W$(t){console&&console.warn&&console.warn(t)}var fd=Number.isNaN||function(e){return e!==e};function ce(){ce.init.call(this)}hd.exports=ce;hd.exports.once=Z$;ce.EventEmitter=ce;ce.prototype._events=void 0;ce.prototype._eventsCount=0;ce.prototype._maxListeners=void 0;var ju=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(ce,"defaultMaxListeners",{enumerable:!0,get:function(){return ju},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+".");ju=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||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 dd(t){return t._maxListeners===void 0?ce.defaultMaxListeners:t._maxListeners}ce.prototype.getMaxListeners=function(){return dd(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")Tu(c,this,r);else for(var u=c.length,l=vd(c,u),n=0;n<u;++n)Tu(l[n],this,r);return!0};function pd(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=dd(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,W$(a)}return t}ce.prototype.addListener=function(e,r){return pd(this,e,r,!1)};ce.prototype.on=ce.prototype.addListener;ce.prototype.prependListener=function(e,r){return pd(this,e,r,!0)};function G$(){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 gd(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=G$.bind(n);return i.listener=r,n.wrapFn=i,i}ce.prototype.once=function(e,r){return vs(r),this.on(e,gd(this,e,r)),this};ce.prototype.prependOnceListener=function(e,r){return vs(r),this.prependListener(e,gd(this,e,r)),this};ce.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():Y$(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 yd(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?J$(i):vd(i,i.length)}ce.prototype.listeners=function(e){return yd(this,e,!0)};ce.prototype.rawListeners=function(e){return yd(this,e,!1)};ce.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):md.call(t,e)};ce.prototype.listenerCount=md;function md(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?Ri(this._events):[]};function vd(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function Y$(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function J$(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function Z$(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"&&Q$(t,i,{once:!0})})}function Q$(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 X$=Object.defineProperty,eO=(t,e,r)=>e in t?X$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mu=(t,e,r)=>eO(t,typeof e!="symbol"?e+"":e,r);let tO=class extends _r{constructor(e){super(),this.opts=e,Mu(this,"protocol","wc"),Mu(this,"version",2)}};var rO=Object.defineProperty,nO=(t,e,r)=>e in t?rO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,iO=(t,e,r)=>nO(t,e+"",r);let sO=class extends _r{constructor(e,r){super(),this.core=e,this.logger=r,iO(this,"records",new Map)}},oO=class{constructor(e,r){this.logger=e,this.core=r}};class aO extends _r{constructor(e,r){super(),this.relayer=e,this.logger=r}}let cO=class extends _r{constructor(e){super()}},uO=class{constructor(e,r,n,i){this.core=e,this.logger=r,this.name=n}},lO=class extends _r{constructor(e,r){super(),this.relayer=e,this.logger=r}},hO=class extends _r{constructor(e,r){super(),this.core=e,this.logger=r}},fO=class{constructor(e,r,n){this.core=e,this.logger=r,this.store=n}},dO=class{constructor(e,r){this.projectId=e,this.logger=r}},pO=class{constructor(e,r,n){this.core=e,this.logger=r,this.telemetryEnabled=n}};var gO=Object.defineProperty,yO=(t,e,r)=>e in t?gO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fu=(t,e,r)=>yO(t,typeof e!="symbol"?e+"":e,r);let mO=class{constructor(e){this.opts=e,Fu(this,"protocol","wc"),Fu(this,"version",2)}},vO=class{constructor(e){this.client=e}};var wO={};const bd="wc",Ed=2,Wi="core",Nt=`${bd}@2:${Wi}:`,bO={name:Wi,logger:"error"},EO={database:":memory:"},_O="crypto",Bu="client_ed25519_seed",$O=N.ONE_DAY,OO="keychain",IO="0.3",PO="messages",DO="0.3",Uu=N.SIX_HOURS,SO="publisher",_d="irn",xO="error",$d="wss://relay.walletconnect.org",AO="relayer",Se={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"},CO="_subscription",at={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},LO=.1,jo="2.21.1",me={link_mode:"link_mode",relay:"relay"},Ni={inbound:"inbound",outbound:"outbound"},RO="0.3",NO="WALLETCONNECT_CLIENT_ID",qu="WALLETCONNECT_LINK_MODE_APPS",tt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},TO="subscription",jO="0.3",MO="pairing",FO="0.3",Sn={wc_pairingDelete:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:N.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:N.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:N.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:N.ONE_DAY,prompt:!1,tag:0},res:{ttl:N.ONE_DAY,prompt:!1,tag:0}}},fr={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"},BO="history",UO="0.3",qO="expirer",ut={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},kO="0.3",zO="verify-api",KO="https://verify.walletconnect.com",Od="https://verify.walletconnect.org",Fn=Od,HO=`${Fn}/v3`,VO=[KO,Od],WO="echo",GO="https://echo.walletconnect.com",Dt={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"},or={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"},ar={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"},xn={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"},YO=.1,JO="event-client",ZO=86400,QO="https://pulse.walletconnect.org/batch";function XO(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,v=0,b=0,w=d.length;b!==w&&d[b]===0;)b++,y++;for(var E=(w-b)*l+1>>>0,O=new Uint8Array(E);b!==w;){for(var x=d[b],S=0,D=E-1;(x!==0||S<v)&&D!==-1;D--,S++)x+=256*O[D]>>>0,O[D]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");v=S,b++}for(var C=E-v;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 v=0,b=0;d[y]===c;)v++,y++;for(var w=(d.length-y)*u+1>>>0,E=new Uint8Array(w);d[y];){var O=r[d.charCodeAt(y)];if(O===255)return;for(var x=0,S=w-1;(O!==0||x<b)&&S!==-1;S--,x++)O+=a*E[S]>>>0,E[S]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");b=x,y++}if(d[y]!==" "){for(var D=w-b;D!==w&&E[D]===0;)D++;for(var C=new Uint8Array(v+(w-D)),I=v;D!==w;)C[I++]=E[D++];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 eI=XO,tI=eI;const Id=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")},rI=t=>new TextEncoder().encode(t),nI=t=>new TextDecoder().decode(t);class iI{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 sI{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 Pd(this,e)}}class oI{constructor(e){this.decoders=e}or(e){return Pd(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 Pd=(t,e)=>new oI({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class aI{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new iI(e,r,n),this.decoder=new sI(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ws=({name:t,prefix:e,encode:r,decode:n})=>new aI(t,e,r,n),oi=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=tI(r,e);return ws({prefix:t,name:e,encode:n,decode:s=>Id(i(s))})},cI=(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},uI=(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},Fe=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>ws({prefix:e,name:t,encode(i){return uI(i,n,r)},decode(i){return cI(i,n,r,t)}}),lI=ws({prefix:"\0",name:"identity",encode:t=>nI(t),decode:t=>rI(t)});var hI=Object.freeze({__proto__:null,identity:lI});const fI=Fe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var dI=Object.freeze({__proto__:null,base2:fI});const pI=Fe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var gI=Object.freeze({__proto__:null,base8:pI});const yI=oi({prefix:"9",name:"base10",alphabet:"0123456789"});var mI=Object.freeze({__proto__:null,base10:yI});const vI=Fe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),wI=Fe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var bI=Object.freeze({__proto__:null,base16:vI,base16upper:wI});const EI=Fe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),_I=Fe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),$I=Fe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),OI=Fe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),II=Fe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),PI=Fe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),DI=Fe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),SI=Fe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),xI=Fe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var AI=Object.freeze({__proto__:null,base32:EI,base32upper:_I,base32pad:$I,base32padupper:OI,base32hex:II,base32hexupper:PI,base32hexpad:DI,base32hexpadupper:SI,base32z:xI});const CI=oi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),LI=oi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var RI=Object.freeze({__proto__:null,base36:CI,base36upper:LI});const NI=oi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),TI=oi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var jI=Object.freeze({__proto__:null,base58btc:NI,base58flickr:TI});const MI=Fe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),FI=Fe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),BI=Fe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),UI=Fe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var qI=Object.freeze({__proto__:null,base64:MI,base64pad:FI,base64url:BI,base64urlpad:UI});const Dd=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),kI=Dd.reduce((t,e,r)=>(t[r]=e,t),[]),zI=Dd.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function KI(t){return t.reduce((e,r)=>(e+=kI[r],e),"")}function HI(t){const e=[];for(const r of t){const n=zI[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const VI=ws({prefix:"🚀",name:"base256emoji",encode:KI,decode:HI});var WI=Object.freeze({__proto__:null,base256emoji:VI}),GI=Sd,ku=128,YI=127,JI=~YI,ZI=Math.pow(2,31);function Sd(t,e,r){e=e||[],r=r||0;for(var n=r;t>=ZI;)e[r++]=t&255|ku,t/=128;for(;t&JI;)e[r++]=t&255|ku,t>>>=7;return e[r]=t|0,Sd.bytes=r-n+1,e}var QI=Mo,XI=128,zu=127;function Mo(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw Mo.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&zu)<<i:(o&zu)*Math.pow(2,i),i+=7}while(o>=XI);return Mo.bytes=s-n,r}var e2=Math.pow(2,7),t2=Math.pow(2,14),r2=Math.pow(2,21),n2=Math.pow(2,28),i2=Math.pow(2,35),s2=Math.pow(2,42),o2=Math.pow(2,49),a2=Math.pow(2,56),c2=Math.pow(2,63),u2=function(t){return t<e2?1:t<t2?2:t<r2?3:t<n2?4:t<i2?5:t<s2?6:t<o2?7:t<a2?8:t<c2?9:10},l2={encode:GI,decode:QI,encodingLength:u2},xd=l2;const Ku=(t,e,r=0)=>(xd.encode(t,e,r),e),Hu=t=>xd.encodingLength(t),Fo=(t,e)=>{const r=e.byteLength,n=Hu(t),i=n+Hu(r),s=new Uint8Array(i+r);return Ku(t,s,0),Ku(r,s,n),s.set(e,i),new h2(t,r,e,s)};class h2{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Ad=({name:t,code:e,encode:r})=>new f2(t,e,r);class f2{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?Fo(this.code,r):r.then(n=>Fo(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Cd=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),d2=Ad({name:"sha2-256",code:18,encode:Cd("SHA-256")}),p2=Ad({name:"sha2-512",code:19,encode:Cd("SHA-512")});var g2=Object.freeze({__proto__:null,sha256:d2,sha512:p2});const Ld=0,y2="identity",Rd=Id,m2=t=>Fo(Ld,Rd(t)),v2={code:Ld,name:y2,encode:Rd,digest:m2};var w2=Object.freeze({__proto__:null,identity:v2});new TextEncoder,new TextDecoder;const Vu={...hI,...dI,...gI,...mI,...bI,...AI,...RI,...jI,...qI,...WI};({...g2,...w2});function b2(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Nd(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Wu=Nd("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Xs=Nd("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=b2(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),E2={utf8:Wu,"utf-8":Wu,hex:Vu.base16,latin1:Xs,ascii:Xs,binary:Xs,...Vu};function _2(t,e="utf8"){const r=E2[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 $2=Object.defineProperty,O2=(t,e,r)=>e in t?$2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,It=(t,e,r)=>O2(t,typeof e!="symbol"?e+"":e,r);class I2{constructor(e,r){this.core=e,this.logger=r,It(this,"keychain",new Map),It(this,"name",OO),It(this,"version",IO),It(this,"initialized",!1),It(this,"storagePrefix",Nt),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}=T("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=He(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,$o(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Oo(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=T("NOT_INITIALIZED",this.name);throw new Error(e)}}}var P2=Object.defineProperty,D2=(t,e,r)=>e in t?P2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ne=(t,e,r)=>D2(t,typeof e!="symbol"?e+"":e,r);class S2{constructor(e,r,n){this.core=e,this.logger=r,Ne(this,"name",_O),Ne(this,"keychain"),Ne(this,"randomSessionIdentifier",No()),Ne(this,"initialized",!1),Ne(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ne(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Ne(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=mc(i);return Ch(s.publicKey)}),Ne(this,"generateKeyPair",()=>{this.isInitialized();const i=d_();return this.setPrivateKey(i.publicKey,i.privateKey)}),Ne(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=mc(s),a=this.randomSessionIdentifier;return await Wv(a,i,$O,o)}),Ne(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=p_(a,s);return this.setSymKey(c,o)}),Ne(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||xi(i);return await this.keychain.set(o,i),o}),Ne(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ne(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ne(this,"encode",async(i,s,o)=>{this.isInitialized();const a=ed(o),c=Vt(s);if(vu(a))return m_(c,o?.encoding);if(mu(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 g_({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o?.encoding})}),Ne(this,"decode",async(i,s,o)=>{this.isInitialized();const a=w_(s,o);if(vu(a)){const c=v_(s,o?.encoding);return mr(c)}if(mu(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=y_({symKey:c,encoded:s,encoding:o?.encoding});return mr(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ne(this,"getPayloadType",(i,s=bt)=>{const o=Gn({encoded:i,encoding:s});return Er(o.type)}),Ne(this,"getPayloadSenderPublicKey",(i,s=bt)=>{const o=Gn({encoded:i,encoding:s});return o.senderPublicKey?Ze(o.senderPublicKey,Ke):void 0}),this.core=e,this.logger=He(r,this.name),this.keychain=n||new I2(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(Bu)}catch{e=No(),await this.keychain.set(Bu,e)}return _2(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=T("NOT_INITIALIZED",this.name);throw new Error(e)}}}var x2=Object.defineProperty,A2=Object.defineProperties,C2=Object.getOwnPropertyDescriptors,Gu=Object.getOwnPropertySymbols,L2=Object.prototype.hasOwnProperty,R2=Object.prototype.propertyIsEnumerable,Bo=(t,e,r)=>e in t?x2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,N2=(t,e)=>{for(var r in e||(e={}))L2.call(e,r)&&Bo(t,r,e[r]);if(Gu)for(var r of Gu(e))R2.call(e,r)&&Bo(t,r,e[r]);return t},T2=(t,e)=>A2(t,C2(e)),Xe=(t,e,r)=>Bo(t,typeof e!="symbol"?e+"":e,r);class j2 extends oO{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",PO),Xe(this,"version",DO),Xe(this,"initialized",!1),Xe(this,"storagePrefix",Nt),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===Ni.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,T2(N2({},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=He(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,$o(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,$o(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Oo(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Oo(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=T("NOT_INITIALIZED",this.name);throw new Error(e)}}}var M2=Object.defineProperty,F2=Object.defineProperties,B2=Object.getOwnPropertyDescriptors,Yu=Object.getOwnPropertySymbols,U2=Object.prototype.hasOwnProperty,q2=Object.prototype.propertyIsEnumerable,Uo=(t,e,r)=>e in t?M2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,mi=(t,e)=>{for(var r in e||(e={}))U2.call(e,r)&&Uo(t,r,e[r]);if(Yu)for(var r of Yu(e))q2.call(e,r)&&Uo(t,r,e[r]);return t},eo=(t,e)=>F2(t,B2(e)),vt=(t,e,r)=>Uo(t,typeof e!="symbol"?e+"":e,r);class k2 extends aO{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,vt(this,"events",new Ir.EventEmitter),vt(this,"name",SO),vt(this,"queue",new Map),vt(this,"publishTimeout",N.toMiliseconds(N.ONE_MINUTE)),vt(this,"initialPublishTimeout",N.toMiliseconds(N.ONE_SECOND*15)),vt(this,"needsTransportRestart",!1),vt(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||Uu,c=Hi(s),u=s?.prompt||!1,l=s?.tag||0,h=s?.id||pr().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 v=({id:w})=>{f.opts.id===w&&(this.removeRequestFromQueue(w),this.relayer.events.removeListener(Se.publish,v),y(f))};this.relayer.events.on(Se.publish,v);const b=er(new Promise((w,E)=>{this.rpcPublish({topic:n,message:i,ttl:a,prompt:u,tag:l,id:h,attestation:s?.attestation,tvf:s?.tvf}).then(w).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(Se.publish,v)}catch(w){this.queue.set(h,eo(mi({},f),{attempt:1})),this.logger.warn(w,w?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:h,topic:n,message:i,opts:s}}),await er(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)}}),vt(this,"on",(n,i)=>{this.events.on(n,i)}),vt(this,"once",(n,i)=>{this.events.once(n,i)}),vt(this,"off",(n,i)=>{this.events.off(n,i)}),vt(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.relayer=e,this.logger=He(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=Uu,prompt:u,tag:l,id:h,attestation:f,tvf:p}=e,d={method:Rn(Hi().protocol).publish,params:mi({topic:o,message:a,ttl:c,prompt:u,tag:l,attestation:f},p),id:h};qe((r=d.params)==null?void 0:r.prompt)&&((n=d.params)==null||delete n.prompt),qe((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(Se.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,eo(mi({},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(eo(mi({},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($r.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Se.connection_stalled);return}this.checkQueue()}),this.relayer.on(Se.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var z2=Object.defineProperty,K2=(t,e,r)=>e in t?z2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tr=(t,e,r)=>K2(t,typeof e!="symbol"?e+"":e,r);class H2{constructor(){Tr(this,"map",new Map),Tr(this,"set",(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])}),Tr(this,"get",e=>this.map.get(e)||[]),Tr(this,"exists",(e,r)=>this.get(e).includes(r)),Tr(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)}),Tr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var V2=Object.defineProperty,W2=Object.defineProperties,G2=Object.getOwnPropertyDescriptors,Ju=Object.getOwnPropertySymbols,Y2=Object.prototype.hasOwnProperty,J2=Object.prototype.propertyIsEnumerable,qo=(t,e,r)=>e in t?V2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,An=(t,e)=>{for(var r in e||(e={}))Y2.call(e,r)&&qo(t,r,e[r]);if(Ju)for(var r of Ju(e))J2.call(e,r)&&qo(t,r,e[r]);return t},to=(t,e)=>W2(t,G2(e)),fe=(t,e,r)=>qo(t,typeof e!="symbol"?e+"":e,r);class Z2 extends lO{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,fe(this,"subscriptions",new Map),fe(this,"topicMap",new H2),fe(this,"events",new Ir.EventEmitter),fe(this,"name",TO),fe(this,"version",jO),fe(this,"pending",new Map),fe(this,"cached",[]),fe(this,"initialized",!1),fe(this,"storagePrefix",Nt),fe(this,"subscribeTimeout",N.toMiliseconds(N.ONE_MINUTE)),fe(this,"initialSubscribeTimeout",N.toMiliseconds(N.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=Hi(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($r.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=He(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=Hi(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:Rn(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))},N.toMiliseconds(N.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 er(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 er(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(Se.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Rn(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 er(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(Se.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:Rn(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 er(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(Se.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:Rn(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,to(An({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,An({},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,An({},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}=T("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,to(An({},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}=T("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=>to(An({},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 eE(N.toMiliseconds(N.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}=T("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 Q2=Object.defineProperty,Zu=Object.getOwnPropertySymbols,X2=Object.prototype.hasOwnProperty,eP=Object.prototype.propertyIsEnumerable,ko=(t,e,r)=>e in t?Q2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Qu=(t,e)=>{for(var r in e||(e={}))X2.call(e,r)&&ko(t,r,e[r]);if(Zu)for(var r of Zu(e))eP.call(e,r)&&ko(t,r,e[r]);return t},Q=(t,e,r)=>ko(t,typeof e!="symbol"?e+"":e,r);class tP extends cO{constructor(e){super(e),Q(this,"protocol","wc"),Q(this,"version",2),Q(this,"core"),Q(this,"logger"),Q(this,"events",new Ir.EventEmitter),Q(this,"provider"),Q(this,"messages"),Q(this,"subscriber"),Q(this,"publisher"),Q(this,"name",AO),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",N.toMiliseconds(N.THIRTY_SECONDS+N.FIVE_SECONDS)),Q(this,"reconnectTimeout"),Q(this,"connectPromise"),Q(this,"reconnectInProgress",!1),Q(this,"requestsInFlight",[]),Q(this,"connectTimeout",N.toMiliseconds(N.ONE_SECOND*15)),Q(this,"request",async r=>{var n,i;this.logger.debug("Publishing Request Payload");const s=r.id||pr().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",()=>{zi()&&(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(Se.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(Se.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"?He(e.logger,this.name):Jn(es({level:e.logger||xO})),this.messages=new j2(this.logger,e.core),this.subscriber=new Z2(this,this.logger),this.publisher=new k2(this,this.logger),this.relayUrl=e?.relayUrl||$d,this.projectId=e.projectId,F0()?this.packageName=qc():B0()&&(this.bundleId=qc()),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},Ni.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,Qu({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 er(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(N.FIVE_MINUTES),s={topic:n,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(Se.message,e),await this.recordMessageEvent(e,Ni.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 er(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,N.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,n,i,s;if(zi())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 m0(K0({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}),ha(e)){if(!e.method.endsWith(CO))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(Qu({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else cs(e)&&this.events.emit(Se.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Ni.inbound),this.events.emit(Se.message,e))}async acknowledgePayload(e){const r=os(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();f$(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($r.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&g$())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Se.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},N.toMiliseconds(LO)))))}isInitialized(){if(!this.initialized){const{message:e}=T("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 rP(){}function Xu(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 el(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function tl(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const nP="[object RegExp]",iP="[object String]",sP="[object Number]",oP="[object Boolean]",rl="[object Arguments]",aP="[object Symbol]",cP="[object Date]",uP="[object Map]",lP="[object Set]",hP="[object Array]",fP="[object Function]",dP="[object ArrayBuffer]",ro="[object Object]",pP="[object Error]",gP="[object DataView]",yP="[object Uint8Array]",mP="[object Uint8ClampedArray]",vP="[object Uint16Array]",wP="[object Uint32Array]",bP="[object BigUint64Array]",EP="[object Int8Array]",_P="[object Int16Array]",$P="[object Int32Array]",OP="[object BigInt64Array]",IP="[object Float32Array]",PP="[object Float64Array]";function DP(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function SP(t,e,r){return Nn(t,e,void 0,void 0,void 0,void 0,r)}function Nn(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 Bn(t,e,s,o)}return Bn(t,e,s,o)}function Bn(t,e,r,n){if(Object.is(t,e))return!0;let i=tl(t),s=tl(e);if(i===rl&&(i=ro),s===rl&&(s=ro),i!==s)return!1;switch(i){case iP:return t.toString()===e.toString();case sP:{const c=t.valueOf(),u=e.valueOf();return DP(c,u)}case oP:case cP:case aP:return Object.is(t.valueOf(),e.valueOf());case nP:return t.source===e.source&&t.flags===e.flags;case fP: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 uP:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!Nn(u,e.get(c),c,t,e,r,n))return!1;return!0}case lP:{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=>Nn(h,p,void 0,t,e,r,n));if(f===-1)return!1;u.splice(f,1)}return!0}case hP:case yP:case mP:case vP:case wP:case bP:case EP:case _P:case $P:case OP:case IP:case PP:{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(!Nn(t[c],e[c],c,t,e,r,n))return!1;return!0}case dP:return t.byteLength!==e.byteLength?!1:Bn(new Uint8Array(t),new Uint8Array(e),r,n);case gP:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Bn(new Uint8Array(t),new Uint8Array(e),r,n);case pP:return t.name===e.name&&t.message===e.message;case ro:{if(!(Bn(t.constructor,e.constructor,r,n)||Xu(t)&&Xu(e)))return!1;const c=[...Object.keys(t),...el(t)],u=[...Object.keys(e),...el(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(!Nn(f,p,h,t,e,r,n))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function xP(t,e){return SP(t,e,rP)}var AP=Object.defineProperty,nl=Object.getOwnPropertySymbols,CP=Object.prototype.hasOwnProperty,LP=Object.prototype.propertyIsEnumerable,zo=(t,e,r)=>e in t?AP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,il=(t,e)=>{for(var r in e||(e={}))CP.call(e,r)&&zo(t,r,e[r]);if(nl)for(var r of nl(e))LP.call(e,r)&&zo(t,r,e[r]);return t},We=(t,e,r)=>zo(t,typeof e!="symbol"?e+"":e,r);class Pr extends uO{constructor(e,r,n,i=Nt,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",RO),We(this,"cached",[]),We(this,"initialized",!1),We(this,"getKey"),We(this,"storagePrefix",Nt),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&&!qe(o)?this.map.set(this.getKey(o),o):z_(o)?this.map.set(o.id,o):K_(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=>xP(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=il(il({},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=He(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}=T("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=T("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}=T("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}=T("NOT_INITIALIZED",this.name);throw new Error(e)}}}var RP=Object.defineProperty,NP=(t,e,r)=>e in t?RP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,W=(t,e,r)=>NP(t,typeof e!="symbol"?e+"":e,r);class TP{constructor(e,r){this.core=e,this.logger=r,W(this,"name",MO),W(this,"version",FO),W(this,"events",new _$),W(this,"pairings"),W(this,"initialized",!1),W(this,"storagePrefix",Nt),W(this,"ignoredPayloadTypes",[Ht]),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=No(),s=await this.core.crypto.setSymKey(i),o=_e(N.FIVE_MINUTES),a={protocol:_d},c={topic:s,expiry:o,relay:a,active:!1,methods:n?.methods},u=bu({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(fr.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:[Dt.pairing_started]}});this.isValidPair(n,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=wu(n.uri);i.props.properties.topic=s,i.addTrace(Dt.pairing_uri_validation_success),i.addTrace(Dt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(Dt.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(Dt.pairing_not_expired)}const h=c||_e(N.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(Dt.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(fr.create,f),i.addTrace(Dt.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(Dt.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(Dt.subscribe_pairing_topic_success),f}),W(this,"activate",async({topic:n})=>{this.isInitialized();const i=_e(N.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}=cr();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 bu({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=Xt(i,s),a=await this.core.crypto.encode(n,o),c=Sn[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=os(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Sn[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=as(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Sn[c]?Sn[c].res:Sn.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=>Zt(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(fr.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(fr.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}=T("MISSING_OR_INVALID",`pair() params: ${n}`);throw i.setError(qt.malformed_pairing_uri),new Error(a)}if(!k_(n.uri)){const{message:a}=T("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw i.setError(qt.malformed_pairing_uri),new Error(a)}const o=wu(n?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=T("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}=T("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(qt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&N.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(qt.pairing_expired);const{message:a}=T("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}=T("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}=T("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}=T("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=T("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(Zt(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=T("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}}),this.core=e,this.logger=He(r,this.name),this.pairings=new Pr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Qe(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=T("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Se.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);ha(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):cs(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}=Ef(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(fr.expire,{topic:r}))})}}var jP=Object.defineProperty,MP=(t,e,r)=>e in t?jP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Te=(t,e,r)=>MP(t,typeof e!="symbol"?e+"":e,r);class FP extends sO{constructor(e,r){super(e,r),this.core=e,this.logger=r,Te(this,"records",new Map),Te(this,"events",new Ir.EventEmitter),Te(this,"name",BO),Te(this,"version",UO),Te(this,"cached",[]),Te(this,"initialized",!1),Te(this,"storagePrefix",Nt),Te(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)}),Te(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(N.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(yt.created,o)}),Te(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))}),Te(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))),Te(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()}),Te(this,"exists",async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1)),Te(this,"on",(n,i)=>{this.events.on(n,i)}),Te(this,"once",(n,i)=>{this.events.once(n,i)}),Te(this,"off",(n,i)=>{this.events.off(n,i)}),Te(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=He(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:Xt(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}=T("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}=T("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($r.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{N.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}=T("NOT_INITIALIZED",this.name);throw new Error(e)}}}var BP=Object.defineProperty,UP=(t,e,r)=>e in t?BP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ue=(t,e,r)=>UP(t,typeof e!="symbol"?e+"":e,r);class qP extends hO{constructor(e,r){super(e,r),this.core=e,this.logger=r,Ue(this,"expirations",new Map),Ue(this,"events",new Ir.EventEmitter),Ue(this,"name",qO),Ue(this,"version",kO),Ue(this,"cached",[]),Ue(this,"initialized",!1),Ue(this,"storagePrefix",Nt),Ue(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)}),Ue(this,"has",n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}}),Ue(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})}),Ue(this,"get",n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)}),Ue(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})}}),Ue(this,"on",(n,i)=>{this.events.on(n,i)}),Ue(this,"once",(n,i)=>{this.events.once(n,i)}),Ue(this,"off",(n,i)=>{this.events.off(n,i)}),Ue(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=He(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 H0(e);if(typeof e=="number")return V0(e);const{message:r}=T("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}=T("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}=T("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;N.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($r.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}=T("NOT_INITIALIZED",this.name);throw new Error(e)}}}var kP=Object.defineProperty,zP=(t,e,r)=>e in t?kP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,be=(t,e,r)=>zP(t,typeof e!="symbol"?e+"":e,r);class KP extends fO{constructor(e,r,n){super(e,r,n),this.core=e,this.logger=r,this.store=n,be(this,"name",zO),be(this,"abortController"),be(this,"isDevEnv"),be(this,"verifyUrlV3",HO),be(this,"storagePrefix",Nt),be(this,"version",Ed),be(this,"publicKey"),be(this,"fetchPromise"),be(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&N.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(!wn()||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(N.ONE_SECOND*5),h=await new Promise((f,p)=>{const d=()=>{window.removeEventListener("message",v),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 v=b=>{if(b.data&&typeof b.data=="string")try{const w=JSON.parse(b.data);if(w.type==="verify_attestation"){if(wo(w.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(y),this.abortController.signal.removeEventListener("abort",d),window.removeEventListener("message",v),f(w.attestation===null?"":w.attestation)}}catch(w){this.logger.warn(w)}};u.body.appendChild(y),window.addEventListener("message",v,{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(wo(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(N.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||Fn;return VO.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Fn}`),s=Fn),s}),be(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(N.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=E_(i,s.publicKey),a={hasExpired:N.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=He(r,this.name),this.abortController=new AbortController,this.isDevEnv=pa(),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(),N.toMiliseconds(e))}}var HP=Object.defineProperty,VP=(t,e,r)=>e in t?HP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sl=(t,e,r)=>VP(t,typeof e!="symbol"?e+"":e,r);class WP extends dO{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,sl(this,"context",WO),sl(this,"registerDeviceToken",async n=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,c=`${GO}/${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=He(r,this.context)}}var GP=Object.defineProperty,ol=Object.getOwnPropertySymbols,YP=Object.prototype.hasOwnProperty,JP=Object.prototype.propertyIsEnumerable,Ko=(t,e,r)=>e in t?GP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Cn=(t,e)=>{for(var r in e||(e={}))YP.call(e,r)&&Ko(t,r,e[r]);if(ol)for(var r of ol(e))JP.call(e,r)&&Ko(t,r,e[r]);return t},Oe=(t,e,r)=>Ko(t,typeof e!="symbol"?e+"":e,r);class ZP extends pO{constructor(e,r,n=!0){super(e,r,n),this.core=e,this.logger=r,Oe(this,"context",JO),Oe(this,"storagePrefix",Nt),Oe(this,"storageVersion",YO),Oe(this,"events",new Map),Oe(this,"shouldPersist",!1),Oe(this,"init",async()=>{if(!pa())try{const i={eventId:zc(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:wf(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=zc(),l=this.core.projectId||"",h=Date.now(),f=Cn({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 Cn(Cn({},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($r.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{N.fromMiliseconds(Date.now())-N.fromMiliseconds(i.timestamp)>ZO&&(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,Cn(Cn({},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(`${QO}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${jo}${s}`,{method:"POST",body:JSON.stringify(i)})}),Oe(this,"getAppDomain",()=>vf().url),this.logger=He(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 QP=Object.defineProperty,al=Object.getOwnPropertySymbols,XP=Object.prototype.hasOwnProperty,eD=Object.prototype.propertyIsEnumerable,Ho=(t,e,r)=>e in t?QP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,cl=(t,e)=>{for(var r in e||(e={}))XP.call(e,r)&&Ho(t,r,e[r]);if(al)for(var r of al(e))eD.call(e,r)&&Ho(t,r,e[r]);return t},ge=(t,e,r)=>Ho(t,typeof e!="symbol"?e+"":e,r);let tD=class Td extends tO{constructor(e){var r;super(e),ge(this,"protocol",bd),ge(this,"version",Ed),ge(this,"name",Wi),ge(this,"relayUrl"),ge(this,"projectId"),ge(this,"customStoragePrefix"),ge(this,"events",new Ir.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||$d,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=es({level:typeof e?.logger=="string"&&e.logger?e.logger:bO.logger,name:Wi}),{logger:s,chunkLoggerController:o}=ry({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=He(s,this.name),this.heartbeat=new Eg,this.crypto=new S2(this,this.logger,e?.keychain),this.history=new FP(this,this.logger),this.expirer=new qP(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new V$(cl(cl({},EO),e?.storageOptions)),this.relayer=new tP({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new TP(this,this.logger),this.verify=new KP(this,this.logger,this.storage),this.echoClient=new WP(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new ZP(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new Td(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(NO,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(qu,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(qu)||[],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"&&wO.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const rD=tD;var $a={exports:{}},an=typeof Reflect=="object"?Reflect:null,ul=an&&typeof an.apply=="function"?an.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Ti;an&&typeof an.ownKeys=="function"?Ti=an.ownKeys:Object.getOwnPropertySymbols?Ti=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Ti=function(e){return Object.getOwnPropertyNames(e)};function nD(t){console&&console.warn&&console.warn(t)}var jd=Number.isNaN||function(e){return e!==e};function ue(){ue.init.call(this)}$a.exports=ue;$a.exports.once=aD;ue.EventEmitter=ue;ue.prototype._events=void 0;ue.prototype._eventsCount=0;ue.prototype._maxListeners=void 0;var ll=10;function bs(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 ll},set:function(t){if(typeof t!="number"||t<0||jd(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");ll=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||jd(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 Md(t){return t._maxListeners===void 0?ue.defaultMaxListeners:t._maxListeners}ue.prototype.getMaxListeners=function(){return Md(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")ul(c,this,r);else for(var u=c.length,l=kd(c,u),n=0;n<u;++n)ul(l[n],this,r);return!0};function Fd(t,e,r,n){var i,s,o;if(bs(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=Md(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,nD(a)}return t}ue.prototype.addListener=function(e,r){return Fd(this,e,r,!1)};ue.prototype.on=ue.prototype.addListener;ue.prototype.prependListener=function(e,r){return Fd(this,e,r,!0)};function iD(){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 Bd(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=iD.bind(n);return i.listener=r,n.wrapFn=i,i}ue.prototype.once=function(e,r){return bs(r),this.on(e,Bd(this,e,r)),this};ue.prototype.prependOnceListener=function(e,r){return bs(r),this.prependListener(e,Bd(this,e,r)),this};ue.prototype.removeListener=function(e,r){var n,i,s,o,a;if(bs(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 Ud(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?oD(i):kd(i,i.length)}ue.prototype.listeners=function(e){return Ud(this,e,!0)};ue.prototype.rawListeners=function(e){return Ud(this,e,!1)};ue.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):qd.call(t,e)};ue.prototype.listenerCount=qd;function qd(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?Ti(this._events):[]};function kd(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 oD(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function aD(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))}zd(t,e,s,{once:!0}),e!=="error"&&cD(t,i,{once:!0})})}function cD(t,e,r){typeof t.on=="function"&&zd(t,"error",e,r)}function zd(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 Kd=$a.exports;const uD=Yn(Kd),Hd="wc",Vd=2,Wd="client",Oa=`${Hd}@${Vd}:${Wd}:`,no={name:Wd,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},hl="WALLETCONNECT_DEEPLINK_CHOICE",lD="proposal",fl="Proposal expired",hD="session",jr=N.SEVEN_DAYS,fD="engine",Ie={wc_sessionPropose:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1104},res:{ttl:N.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1106},res:{ttl:N.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1112},res:{ttl:N.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1114},res:{ttl:N.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:N.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:N.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1119}}},io={min:N.FIVE_MINUTES,max:N.SEVEN_DAYS},Pt={idle:"IDLE",active:"ACTIVE"},dl={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},dD="request",pD=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],gD="wc",yD="auth",mD="authKeys",vD="pairingTopics",wD="requests",Es=`${gD}@${1.5}:${yD}:`,ji=`${Es}:PUB_KEY`;var bD=Object.defineProperty,ED=Object.defineProperties,_D=Object.getOwnPropertyDescriptors,pl=Object.getOwnPropertySymbols,$D=Object.prototype.hasOwnProperty,OD=Object.prototype.propertyIsEnumerable,Vo=(t,e,r)=>e in t?bD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,de=(t,e)=>{for(var r in e||(e={}))$D.call(e,r)&&Vo(t,r,e[r]);if(pl)for(var r of pl(e))OD.call(e,r)&&Vo(t,r,e[r]);return t},ze=(t,e)=>ED(t,_D(e)),R=(t,e,r)=>Vo(t,typeof e!="symbol"?e+"":e,r);class ID extends vO{constructor(e){super(e),R(this,"name",fD),R(this,"events",new uD),R(this,"initialized",!1),R(this,"requestQueue",{state:Pt.idle,queue:[]}),R(this,"sessionRequestQueue",{state:Pt.idle,queue:[]}),R(this,"requestQueueDelay",N.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()},N.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=M_(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 S=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=S.active}}catch(S){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),S}if(!l||!f){const{topic:S,uri:D}=await this.client.core.pairing.create();l=S,h=D}if(!l){const{message:S}=T("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(S)}const p=await this.client.core.crypto.generateKeyPair(),d=Ie.wc_sessionPropose.req.ttl||N.FIVE_MINUTES,y=_e(d),v=ze(de(de({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:_d}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:St()}),b=ee("session_connect",v.id),{reject:w,resolve:E,done:O}=cr(d,fl),x=({id:S})=>{S===v.id&&(this.client.events.off("proposal_expire",x),this.pendingSessions.delete(v.id),this.events.emit(b,{error:{message:fl,code:0}}))};return this.client.events.on("proposal_expire",x),this.events.once(b,({error:S,session:D})=>{this.client.events.off("proposal_expire",x),S?w(S):D&&E(D)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:v,throwOnFailedPublish:!0,clientRpcId:v.id}),await this.setProposal(v.id,v),{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(or.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(or.proposal_not_found),I}try{await this.isValidApprove(r)}catch(I){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(or.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:v,optionalNamespaces:b}=p;let w=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:d});w||(w=(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),S=de(de(de({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:E,metadata:this.client.metadata},expiry:_e(jr)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),D=me.relay;w.addTrace(mt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(x,{transportType:D})}catch(I){throw w.setError(or.subscribe_session_topic_failure),I}w.addTrace(mt.subscribe_session_topic_success);const C=ze(de({},S),{topic:x,requiredNamespaces:v,optionalNamespaces:b,pairingTopic:d,acknowledged:!1,self:S.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:E,transportType:me.relay});await this.client.session.set(x,C),w.addTrace(mt.store_session);try{w.addTrace(mt.publishing_session_settle),await this.sendRequest({topic:x,method:"wc_sessionSettle",params:S,throwOnFailedPublish:!0}).catch(I=>{throw w?.setError(or.session_settle_publish_failure),I}),w.addTrace(mt.session_settle_publish_success),w.addTrace(mt.publishing_session_approve),await this.sendResult({id:a,topic:d,result:{relay:{protocol:c??"irn"},responderPublicKey:E},throwOnFailedPublish:!0}).catch(I=>{throw w?.setError(or.session_approve_publish_failure),I}),w.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:w.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(jr)),{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}=cr(),c=St(),u=pr().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=St(),{done:s,resolve:o,reject:a}=cr();return this.events.once(ee("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,_e(jr)),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=St(),u=pr().toString(),{done:l,resolve:h,reject:f}=cr(o,"Request expired. Please try again.");this.events.once(ee("session_request",c),({error:b,result:w})=>{b?f(b):h(w)});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},v=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},v&&{tvf:this.getTVFParams(c,y)})).catch(w=>f(w)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),b()}),new Promise(async b=>{var w;if(!((w=a.sessionConfig)!=null&&w.disableDeepLink)){const E=await J0(this.client.core.storage,hl);await W0({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=St(),s=pr().toString(),{done:o,resolve:a,reject:c}=cr();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=pr().toString(),a=St();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}=T("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=>U_(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:v}=r,b=[...r.resources||[]],{topic:w,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:w,uri:E}});const O=await this.client.core.crypto.generateKeyPair(),x=xi(O);if(await Promise.all([this.client.auth.authKeys.set(ji,{responseTopic:x,publicKey:O}),this.client.auth.pairingTopics.set(x,{topic:x,pairingTopic:w})]),await this.client.core.relayer.subscribe(x,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${w}`),y.length>0){const{namespace:$}=nn(a[0]);let A=kE($,"request",y);Si(b)&&(A=KE(A,b.pop())),b.push(A)}const S=v&&v>Ie.wc_sessionAuthenticate.req.ttl?v:Ie.wc_sessionAuthenticate.req.ttl,D={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(S)},C={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},I={requiredNamespaces:{},optionalNamespaces:C,relays:[{protocol:"irn"}],pairingTopic:w,proposer:{publicKey:O,metadata:this.client.metadata},expiryTimestamp:_e(Ie.wc_sessionPropose.req.ttl),id:St()},{done:q,resolve:M,reject:j}=cr(S,"Request expired"),k=St(),L=ee("session_connect",I.id),g=ee("session_request",k),m=async({error:$,session:A})=>{this.events.off(g,_),$?j($):A&&M({session:A})},_=async $=>{var A,F,U;if(await this.deletePendingAuthRequest(k,{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:B}=$.result,H=[],Y=[];for(const J of z){await Zc({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:Be}=J,Le=Si(Be.resources),ke=[Io(Be.iss)],ot=Ki(Be.iss);if(Le){const Tt=Qc(Le),Sr=Xc(Le);H.push(...Tt),ke.push(...Sr)}for(const Tt of ke)Y.push(`${Tt}:${ot}`)}const pe=await this.client.core.crypto.generateSharedKey(O,B.publicKey);let te;H.length>0&&(te={topic:pe,acknowledged:!0,self:{publicKey:O,metadata:this.client.metadata},peer:B,controller:B.publicKey,expiry:_e(jr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:w,namespaces:Ou([...new Set(H)],[...new Set(Y)]),transportType:o},await this.client.core.relayer.subscribe(pe,{transportType:o}),await this.client.session.set(pe,te),w&&await this.client.core.pairing.updateMetadata({topic:w,metadata:B.metadata}),te=this.client.session.get(pe)),(A=this.client.metadata.redirect)!=null&&A.linkMode&&(F=B.metadata.redirect)!=null&&F.linkMode&&(U=B.metadata.redirect)!=null&&U.universal&&n&&(this.client.core.addLinkModeSupportedApp(B.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 $=Xt("wc_sessionAuthenticate",D,k);this.client.core.history.set(w,$);const A=await this.client.core.crypto.encode("",$,{type:si,encoding:Qt});P=gi(n,w,A)}else await Promise.all([this.sendRequest({topic:w,method:"wc_sessionAuthenticate",params:D,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:k}),this.sendRequest({topic:w,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(k,{request:ze(de({},D),{verifyContext:{}}),pairingTopic:w,transportType:o}),{uri:P??E,response:q}}),R(this,"approveSessionAuthenticate",async r=>{const{id:n,auths:i}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[ar.authenticated_session_approve_started]}});try{this.isInitialized()}catch(v){throw s.setError(xn.no_internet_connection),v}const o=this.getPendingAuthRequest(n);if(!o)throw s.setError(xn.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=xi(c),h={type:Ht,receiverPublicKey:c,senderPublicKey:u},f=[],p=[];for(const v of i){if(!await Zc({cacao:v,projectId:this.client.core.projectId})){s.setError(xn.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(ar.cacaos_verified);const{p:b}=v,w=Si(b.resources),E=[Io(b.iss)],O=Ki(b.iss);if(w){const x=Qc(w),S=Xc(w);f.push(...x),E.push(...S)}for(const x of E)p.push(`${x}:${O}`)}const d=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(ar.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(jr),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Ou([...new Set(f)],[...new Set(p)]),transportType:a},s.addTrace(ar.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(d,{transportType:a})}catch(v){throw s.setError(xn.subscribe_authenticated_session_topic_failure),v}s.addTrace(ar.subscribe_authenticated_session_topic_success),await this.client.session.set(d,y),s.addTrace(ar.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(ar.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(v){throw s.setError(xn.authenticated_session_approve_publish_failure),v}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=xi(o),u={type:Ht,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 Af(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(hl).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(or.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=Xt(i,s,c);let p;const d=!!l;try{const b=d?Qt: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(pD.includes(i)){const b=Ct(JSON.stringify(f)),w=Ct(p);y=await this.client.core.verify.register({id:w,decryptedId:b})}const v=Ie[i].req;if(v.attestation=y,o&&(v.ttl=o),a&&(v.id=a),this.client.core.history.set(n,f),d){const b=gi(l,n,p);await K.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(w=>this.client.logger.error(w))}return f.id}),R(this,"sendResult",async r=>{const{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,u=os(n,s);let l;const h=c&&typeof(K==null?void 0:K.Linking)<"u";try{const d=h?Qt: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=gi(c,i,l);await K.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(v=>this.client.logger.error(v))}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=as(n,s);let l;const h=c&&typeof(K==null?void 0:K.Linking)<"u";try{const p=h?Qt: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=gi(c,i,l);await K.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;Zt(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=>{Zt(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}=T("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(Dt.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(v=>v.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=Dn.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{Dn.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 Dn.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(jr)),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(Se.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(Xt("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=Dn.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}),Dn.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:Ht,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()},N.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:Xt("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}=T("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(qe(n)||await this.isValidPairingTopic(n),!Q_(c)){const{message:u}=T("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!qe(i)&&rr(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(!qe(s)&&rr(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),qe(o)||this.validateSessionProps(o,"sessionProperties"),!qe(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=Z_(r,"connect()",n);if(i)throw new Error(i.message)}),R(this,"isValidApprove",async r=>{if(!Ye(r))throw new Error(T("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=Js(i,"approve()");if(u)throw new Error(u.message);const l=Du(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!Ee(s,!0)){const{message:h}=T("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(qe(o)||this.validateSessionProps(o,"sessionProperties"),!qe(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}=T("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!e$(i)){const{message:s}=T("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),R(this,"isValidSessionSettleRequest",r=>{if(!Ye(r)){const{message:u}=T("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!rd(n)){const{message:u}=T("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=H_(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Js(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Zt(o)){const{message:u}=T("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),R(this,"isValidUpdate",async r=>{if(!Ye(r)){const{message:c}=T("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=Js(i,"update()");if(o)throw new Error(o.message);const a=Du(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),R(this,"isValidExtend",async r=>{if(!Ye(r)){const{message:i}=T("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}=T("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(!Pu(a,s)){const{message:c}=T("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!t$(i)){const{message:c}=T("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!i$(a,s,i.method)){const{message:c}=T("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!c$(o,io)){const{message:c}=T("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${io.min} and ${io.max}`);throw new Error(c)}}),R(this,"isValidRespond",async r=>{var n;if(!Ye(r)){const{message:o}=T("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(!r$(s)){const{message:o}=T("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),R(this,"isValidPing",async r=>{if(!Ye(r)){const{message:i}=T("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}=T("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(!Pu(o,s)){const{message:a}=T("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!n$(i)){const{message:a}=T("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!s$(o,s,i.name)){const{message:a}=T("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),R(this,"isValidDisconnect",async r=>{if(!Ye(r)){const{message:i}=T("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=>nn(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=nn(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||Fn,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}=T("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}=T("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(K==null?void 0:K.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=kc(r,"topic")||"",i=decodeURIComponent(kc(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(pa()||nr()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const n=K==null?void 0:K.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(dl).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=dl[r];if(typeof n=="string")return[n];const s=n[i.key];if(Et(s))return r==="solana_signAllTransactions"?s.map(o=>SE(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}=T("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Se.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(ji)?this.client.auth.authKeys.get(ji):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:o,encoding:s===me.link_mode?Qt:bt});ha(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:i,transportType:s,encryptedId:Ct(n)})):cs(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}=Ef(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,T("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,T("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(fr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(fr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Ee(e,!1)){const{message:r}=T("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}=T("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(Zt(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=T("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!Ee(e,!1)){const{message:r}=T("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}=T("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(Zt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=T("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=T("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}=T("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=T("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!X_(e)){const{message:r}=T("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=T("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(Zt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=T("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class PD extends Pr{constructor(e,r){super(e,r,lD,Oa),this.core=e,this.logger=r}}let DD=class extends Pr{constructor(e,r){super(e,r,hD,Oa),this.core=e,this.logger=r}};class SD extends Pr{constructor(e,r){super(e,r,dD,Oa,n=>n.id),this.core=e,this.logger=r}}class xD extends Pr{constructor(e,r){super(e,r,mD,Es,()=>ji),this.core=e,this.logger=r}}class AD extends Pr{constructor(e,r){super(e,r,vD,Es),this.core=e,this.logger=r}}class CD extends Pr{constructor(e,r){super(e,r,wD,Es,n=>n.id),this.core=e,this.logger=r}}var LD=Object.defineProperty,RD=(t,e,r)=>e in t?LD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,so=(t,e,r)=>RD(t,typeof e!="symbol"?e+"":e,r);class ND{constructor(e,r){this.core=e,this.logger=r,so(this,"authKeys"),so(this,"pairingTopics"),so(this,"requests"),this.authKeys=new xD(this.core,this.logger),this.pairingTopics=new AD(this.core,this.logger),this.requests=new CD(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var TD=Object.defineProperty,jD=(t,e,r)=>e in t?TD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,G=(t,e,r)=>jD(t,typeof e!="symbol"?e+"":e,r);let MD=class Gd extends mO{constructor(e){super(e),G(this,"protocol",Hd),G(this,"version",Vd),G(this,"name",no.name),G(this,"metadata"),G(this,"core"),G(this,"logger"),G(this,"events",new Kd.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||no.name,this.metadata=q0(e?.metadata),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Jn(es({level:e?.logger||no.logger}));this.core=e?.core||new rD(e),this.logger=He(r,this.name),this.session=new DD(this.core,this.logger),this.proposal=new PD(this.core,this.logger),this.pendingRequest=new SD(this.core,this.logger),this.engine=new ID(this),this.auth=new ND(this.core,this.logger)}static async init(e){const r=new Gd(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()},N.toMiliseconds(N.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};var Ia={exports:{}},cn=typeof Reflect=="object"?Reflect:null,gl=cn&&typeof cn.apply=="function"?cn.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Mi;cn&&typeof cn.ownKeys=="function"?Mi=cn.ownKeys:Object.getOwnPropertySymbols?Mi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Mi=function(e){return Object.getOwnPropertyNames(e)};function FD(t){console&&console.warn&&console.warn(t)}var Yd=Number.isNaN||function(e){return e!==e};function le(){le.init.call(this)}Ia.exports=le;Ia.exports.once=kD;le.EventEmitter=le;le.prototype._events=void 0;le.prototype._eventsCount=0;le.prototype._maxListeners=void 0;var yl=10;function _s(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 yl},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+".");yl=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||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?le.defaultMaxListeners:t._maxListeners}le.prototype.getMaxListeners=function(){return Jd(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")gl(c,this,r);else for(var u=c.length,l=tp(c,u),n=0;n<u;++n)gl(l[n],this,r);return!0};function Zd(t,e,r,n){var i,s,o;if(_s(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,FD(a)}return t}le.prototype.addListener=function(e,r){return Zd(this,e,r,!1)};le.prototype.on=le.prototype.addListener;le.prototype.prependListener=function(e,r){return Zd(this,e,r,!0)};function BD(){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=BD.bind(n);return i.listener=r,n.wrapFn=i,i}le.prototype.once=function(e,r){return _s(r),this.on(e,Qd(this,e,r)),this};le.prototype.prependOnceListener=function(e,r){return _s(r),this.prependListener(e,Qd(this,e,r)),this};le.prototype.removeListener=function(e,r){var n,i,s,o,a;if(_s(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():UD(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 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?qD(i):tp(i,i.length)}le.prototype.listeners=function(e){return Xd(this,e,!0)};le.prototype.rawListeners=function(e){return Xd(this,e,!1)};le.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):ep.call(t,e)};le.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}le.prototype.eventNames=function(){return this._eventsCount>0?Mi(this._events):[]};function tp(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function UD(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function qD(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function kD(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"&&zD(t,i,{once:!0})})}function zD(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 KD=Ia.exports,Wo={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 v(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 w(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 S(){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=v(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=v(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(w);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var g=v(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(q)}),this.json=function(){return this.text().then(JSON.parse)},this}var D=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function C(g){var m=g.toUpperCase();return D.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 q(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(`
|
|
38
|
-
`)===0?P.substr(1,P.length):P}).forEach(function(P){var $=P.split(":"),A=$.shift().trim();if(A){var F=$.join(":").trim();try{m.append(A,F)}catch(U){console.warn("Response "+U.message)}}}),m}S.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)}S.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 k=[301,302,303,307,308];j.redirect=function(g,m){if(k.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 F(){A.abort()}A.onload=function(){var B={statusText:A.statusText,headers:M(A.getAllResponseHeaders()||"")};$.url.indexOf("file://")===0&&(A.status<200||A.status>599)?B.status=200:B.status=A.status,B.url="responseURL"in A?A.responseURL:B.headers.get("X-Request-URL");var H="response"in A?A.response:A.responseText;setTimeout(function(){_(new j(H,B))},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 U(B){try{return B===""&&a.location.href?a.location.href:B}catch{return B}}if(A.open($.method,U($.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(B){z.push(f(B)),A.setRequestHeader(B,p(m.headers[B]))}),$.headers.forEach(function(B,H){z.indexOf(H)===-1&&A.setRequestHeader(H,B)})}else $.headers.forEach(function(B,H){A.setRequestHeader(H,B)});$.signal&&($.signal.addEventListener("abort",F),A.onreadystatechange=function(){A.readyState===4&&$.signal.removeEventListener("abort",F)}),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})(Wo,Wo.exports);var HD=Wo.exports;const ml=Yn(HD);var VD=Object.defineProperty,WD=Object.defineProperties,GD=Object.getOwnPropertyDescriptors,vl=Object.getOwnPropertySymbols,YD=Object.prototype.hasOwnProperty,JD=Object.prototype.propertyIsEnumerable,wl=(t,e,r)=>e in t?VD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bl=(t,e)=>{for(var r in e||(e={}))YD.call(e,r)&&wl(t,r,e[r]);if(vl)for(var r of vl(e))JD.call(e,r)&&wl(t,r,e[r]);return t},El=(t,e)=>WD(t,GD(e));const ZD={Accept:"application/json","Content-Type":"application/json"},QD="POST",_l={headers:ZD,method:QD},$l=10;let _t=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new KD.EventEmitter,this.isAvailable=!1,this.registering=!1,!Sc(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=Vt(e),n=await(await ml(this.url,El(bl({},_l),{body:r}))).json();this.onPayload({data:n})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!Sc(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=Vt({id:1,jsonrpc:"2.0",method:"test",params:[]});await ml(e,El(bl({},_l),{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"?mr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=as(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return Vh(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>$l&&this.events.setMaxListeners($l)}};var Pa={exports:{}},un=typeof Reflect=="object"?Reflect:null,Ol=un&&typeof un.apply=="function"?un.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Fi;un&&typeof un.ownKeys=="function"?Fi=un.ownKeys:Object.getOwnPropertySymbols?Fi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Fi=function(e){return Object.getOwnPropertyNames(e)};function XD(t){console&&console.warn&&console.warn(t)}var np=Number.isNaN||function(e){return e!==e};function he(){he.init.call(this)}Pa.exports=he;Pa.exports.once=nS;he.EventEmitter=he;he.prototype._events=void 0;he.prototype._eventsCount=0;he.prototype._maxListeners=void 0;var Il=10;function $s(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 Il},set:function(t){if(typeof t!="number"||t<0||np(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Il=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||np(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 ip(t){return t._maxListeners===void 0?he.defaultMaxListeners:t._maxListeners}he.prototype.getMaxListeners=function(){return ip(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")Ol(c,this,r);else for(var u=c.length,l=up(c,u),n=0;n<u;++n)Ol(l[n],this,r);return!0};function sp(t,e,r,n){var i,s,o;if($s(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=ip(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,XD(a)}return t}he.prototype.addListener=function(e,r){return sp(this,e,r,!1)};he.prototype.on=he.prototype.addListener;he.prototype.prependListener=function(e,r){return sp(this,e,r,!0)};function eS(){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 op(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=eS.bind(n);return i.listener=r,n.wrapFn=i,i}he.prototype.once=function(e,r){return $s(r),this.on(e,op(this,e,r)),this};he.prototype.prependOnceListener=function(e,r){return $s(r),this.prependListener(e,op(this,e,r)),this};he.prototype.removeListener=function(e,r){var n,i,s,o,a;if($s(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():tS(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 ap(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?rS(i):up(i,i.length)}he.prototype.listeners=function(e){return ap(this,e,!0)};he.prototype.rawListeners=function(e){return ap(this,e,!1)};he.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):cp.call(t,e)};he.prototype.listenerCount=cp;function cp(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?Fi(this._events):[]};function up(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function tS(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function rS(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function nS(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))}lp(t,e,s,{once:!0}),e!=="error"&&iS(t,i,{once:!0})})}function iS(t,e,r){typeof t.on=="function"&&lp(t,"error",e,r)}function lp(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 sS=Pa.exports;const oS=Yn(sS),Pl="error",aS="wss://relay.walletconnect.org",cS="wc",uS="universal_provider",vi=`${cS}@2:${uS}:`,hp="https://rpc.walletconnect.org/v1/",Yr="generic",lS=`${hp}bundler`,pt={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function hS(){}function Da(t){return t==null||typeof t!="object"&&typeof t!="function"}function Sa(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function fS(t){if(Da(t))return t;if(Array.isArray(t)||Sa(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 Dl(t){return typeof t=="object"&&t!==null}function fp(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function dp(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const dS="[object RegExp]",pp="[object String]",gp="[object Number]",yp="[object Boolean]",mp="[object Arguments]",pS="[object Symbol]",gS="[object Date]",yS="[object Map]",mS="[object Set]",vS="[object Array]",wS="[object ArrayBuffer]",bS="[object Object]",ES="[object DataView]",_S="[object Uint8Array]",$S="[object Uint8ClampedArray]",OS="[object Uint16Array]",IS="[object Uint32Array]",PS="[object Int8Array]",DS="[object Int16Array]",SS="[object Int32Array]",xS="[object Float32Array]",AS="[object Float64Array]";function CS(t,e){return Qr(t,void 0,t,new Map,e)}function Qr(t,e,r,n=new Map,i=void 0){const s=i?.(t,e,r,n);if(s!=null)return s;if(Da(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]=Qr(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,Qr(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(Qr(a,void 0,r,n,i));return o}if(typeof Ce<"u"&&Ce.isBuffer(t))return t.subarray();if(Sa(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=Qr(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),dr(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),dr(o,t,r,n,i),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return n.set(t,o),dr(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,dr(o,t,r,n,i),o}if(typeof t=="object"&&LS(t)){const o=Object.create(Object.getPrototypeOf(t));return n.set(t,o),dr(o,t,r,n,i),o}return t}function dr(t,e,r=t,n,i){const s=[...Object.keys(e),...fp(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Qr(e[a],a,r,n,i))}}function LS(t){switch(dp(t)){case mp:case vS:case wS:case ES:case yp:case gS:case xS:case AS:case PS:case DS:case SS:case yS:case gp:case bS:case dS:case mS:case pp:case pS:case _S:case $S:case OS:case IS:return!0;default:return!1}}function RS(t,e){return CS(t,(r,n,i,s)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case gp:case pp:case yp:{const o=new t.constructor(t?.valueOf());return dr(o,t),o}case mp:{const o={};return dr(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function Sl(t){return RS(t)}function xl(t){return t!==null&&typeof t=="object"&&dp(t)==="[object Arguments]"}function NS(t){return Sa(t)}function TS(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 jS(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=Go(i,o,n,new Map)}return i}function Go(t,e,r,n){if(Da(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(n.has(e))return fS(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),...fp(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=Sl(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)||Dl(c)&&Dl(a)?t[o]=Go(c,a,r,n):c==null&&TS(a)?t[o]=Go({},a,r,n):c==null&&NS(a)?t[o]=Sl(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function MS(t,...e){return jS(t,...e,hS)}var FS=Object.defineProperty,BS=Object.defineProperties,US=Object.getOwnPropertyDescriptors,Al=Object.getOwnPropertySymbols,qS=Object.prototype.hasOwnProperty,kS=Object.prototype.propertyIsEnumerable,Cl=(t,e,r)=>e in t?FS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wi=(t,e)=>{for(var r in e||(e={}))qS.call(e,r)&&Cl(t,r,e[r]);if(Al)for(var r of Al(e))kS.call(e,r)&&Cl(t,r,e[r]);return t},zS=(t,e)=>BS(t,US(e));function st(t,e,r){var n;const i=nn(t);return((n=e.rpcMap)==null?void 0:n[i.reference])||`${hp}?chainId=${i.namespace}:${i.reference}&projectId=${r}`}function Dr(t){return t.includes(":")?t.split(":")[1]:t}function vp(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function KS(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 bi(t={},e={}){const r=Ll(t),n=Ll(e);return MS(r,n)}function Ll(t){var e,r,n,i,s;const o={};if(!rr(t))return o;for(const[a,c]of Object.entries(t)){const u=ys(a)?[a]:c.chains,l=c.methods||[],h=c.events||[],f=c.rpcMap||{},p=Zr(a);o[p]=zS(wi(wi({},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)}),(rr(f)||rr(((i=o[p])==null?void 0:i.rpcMap)||{}))&&(o[p].rpcMap=wi(wi({},f),(s=o[p])==null?void 0:s.rpcMap))}return o}function Rl(t){return t.includes(":")?t.split(":")[2]:t}function Nl(t){const e={};for(const[r,n]of Object.entries(t)){const i=n.methods||[],s=n.events||[],o=n.accounts||[],a=ys(r)?[r]:n.chains?n.chains:vp(n.accounts);e[r]={chains:a,methods:i,events:s,accounts:o}}return e}function oo(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 wp={},X=t=>wp[t],ao=(t,e)=>{wp[t]=e};var HS=Object.defineProperty,VS=(t,e,r)=>e in t?HS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mr=(t,e,r)=>VS(t,typeof e!="symbol"?e+"":e,r);class WS{constructor(e){Mr(this,"name","polkadot"),Mr(this,"client"),Mr(this,"httpProviders"),Mr(this,"events"),Mr(this,"namespace"),Mr(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=Dr(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 GS=Object.defineProperty,YS=Object.defineProperties,JS=Object.getOwnPropertyDescriptors,Tl=Object.getOwnPropertySymbols,ZS=Object.prototype.hasOwnProperty,QS=Object.prototype.propertyIsEnumerable,Yo=(t,e,r)=>e in t?GS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jl=(t,e)=>{for(var r in e||(e={}))ZS.call(e,r)&&Yo(t,r,e[r]);if(Tl)for(var r of Tl(e))QS.call(e,r)&&Yo(t,r,e[r]);return t},Ml=(t,e)=>YS(t,JS(e)),Fr=(t,e,r)=>Yo(t,typeof e!="symbol"?e+"":e,r);class XS{constructor(e){Fr(this,"name","eip155"),Fr(this,"client"),Fr(this,"chainId"),Fr(this,"namespace"),Fr(this,"httpProviders"),Fr(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(Dr(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:Ml(jl({},l.sessionProperties||{}),{capabilities:Ml(jl({},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(Xt("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`${lS}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${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,Br=(t,e,r)=>tx(t,typeof e!="symbol"?e+"":e,r);class rx{constructor(e){Br(this,"name","solana"),Br(this,"client"),Br(this,"httpProviders"),Br(this,"events"),Br(this,"namespace"),Br(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=Dr(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 nx=Object.defineProperty,ix=(t,e,r)=>e in t?nx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ur=(t,e,r)=>ix(t,typeof e!="symbol"?e+"":e,r);class sx{constructor(e){Ur(this,"name","cosmos"),Ur(this,"client"),Ur(this,"httpProviders"),Ur(this,"events"),Ur(this,"namespace"),Ur(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=Dr(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 ox=Object.defineProperty,ax=(t,e,r)=>e in t?ox(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qr=(t,e,r)=>ax(t,typeof e!="symbol"?e+"":e,r);class cx{constructor(e){qr(this,"name","algorand"),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){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 ux=Object.defineProperty,lx=(t,e,r)=>e in t?ux(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,kr=(t,e,r)=>lx(t,typeof e!="symbol"?e+"":e,r);class hx{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=Dr(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 fx=Object.defineProperty,dx=(t,e,r)=>e in t?fx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zr=(t,e,r)=>dx(t,typeof e!="symbol"?e+"":e,r);class px{constructor(e){zr(this,"name","elrond"),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()}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=Dr(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 gx=Object.defineProperty,yx=(t,e,r)=>e in t?gx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Kr=(t,e,r)=>yx(t,typeof e!="symbol"?e+"":e,r);class mx{constructor(e){Kr(this,"name","multiversx"),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()}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=Dr(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 vx=Object.defineProperty,wx=(t,e,r)=>e in t?vx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hr=(t,e,r)=>wx(t,typeof e!="symbol"?e+"":e,r);class bx{constructor(e){Hr(this,"name","near"),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()}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 Ex=Object.defineProperty,_x=(t,e,r)=>e in t?Ex(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Vr=(t,e,r)=>_x(t,typeof e!="symbol"?e+"":e,r);class $x{constructor(e){Vr(this,"name","tezos"),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()}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 Ox=Object.defineProperty,Ix=(t,e,r)=>e in t?Ox(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wr=(t,e,r)=>Ix(t,typeof e!="symbol"?e+"":e,r);class Px{constructor(e){Wr(this,"name",Yr),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.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=nn(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 Dx=Object.defineProperty,Sx=Object.defineProperties,xx=Object.getOwnPropertyDescriptors,Fl=Object.getOwnPropertySymbols,Ax=Object.prototype.hasOwnProperty,Cx=Object.prototype.propertyIsEnumerable,Jo=(t,e,r)=>e in t?Dx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ei=(t,e)=>{for(var r in e||(e={}))Ax.call(e,r)&&Jo(t,r,e[r]);if(Fl)for(var r of Fl(e))Cx.call(e,r)&&Jo(t,r,e[r]);return t},co=(t,e)=>Sx(t,xx(e)),ct=(t,e,r)=>Jo(t,typeof e!="symbol"?e+"":e,r);let Lx=class bp{constructor(e){ct(this,"client"),ct(this,"namespaces"),ct(this,"optionalNamespaces"),ct(this,"sessionProperties"),ct(this,"scopedProperties"),ct(this,"events",new oS),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:Jn(es({level:e?.logger||Pl})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new bp(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:Ei({},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,os(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=Nl(this.session.namespaces);this.namespaces=bi(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=Nl(i.namespaces);return this.namespaces=bi(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===Yr?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 MD.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Pl,relayUrl:this.providerOpts.relayUrl||aS,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=>Zr(r)))];ao("client",this.client),ao("events",this.events),ao("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const n=KS(r,this.session),i=vp(n),s=bi(this.namespaces,this.optionalNamespaces),o=co(Ei({},s[r]),{accounts:n,chains:i});switch(r){case"eip155":this.rpcProviders[r]=new XS({namespace:o});break;case"algorand":this.rpcProviders[r]=new cx({namespace:o});break;case"solana":this.rpcProviders[r]=new rx({namespace:o});break;case"cosmos":this.rpcProviders[r]=new sx({namespace:o});break;case"polkadot":this.rpcProviders[r]=new WS({namespace:o});break;case"cip34":this.rpcProviders[r]=new hx({namespace:o});break;case"elrond":this.rpcProviders[r]=new px({namespace:o});break;case"multiversx":this.rpcProviders[r]=new mx({namespace:o});break;case"near":this.rpcProviders[r]=new bx({namespace:o});break;case"tezos":this.rpcProviders[r]=new $x({namespace:o});break;default:this.rpcProviders[Yr]?this.rpcProviders[Yr].updateNamespace(o):this.rpcProviders[Yr]=new Px({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(Rl))}else if(s.name==="chainChanged"){const o=n.chainId,a=n.event.data,c=Zr(o),u=oo(o)!==oo(a)?`${c}:${oo(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=co(Ei({},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",co(Ei({},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[Yr]}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=bi(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=>Zr(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=Zr(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(Rl);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(`${vi}/${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(`${vi}/${e}${n}`)}async deleteFromStore(e){var r;const n=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${vi}/${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(vi)&&await this.client.core.storage.removeItem(n)}catch(r){this.logger.warn("Failed to cleanup storage",r)}}};const Rx=Lx,Nx="wc",Tx="ethereum_provider",jx=`${Nx}@2:${Tx}:`,Mx="https://rpc.walletconnect.org/v1/",Gi=["eth_sendTransaction","personal_sign"],Ep=["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"],Yi=["chainChanged","accountsChanged"],_p=["chainChanged","accountsChanged","message","disconnect","connect"],Fx=async()=>{const{createAppKit:t}=await Fp(()=>import("./core-kZLq_ADy.js").then(e=>e.G),__vite__mapDeps([0,1,2,3,4]));return t};var Bx=Object.defineProperty,Ux=Object.defineProperties,qx=Object.getOwnPropertyDescriptors,Bl=Object.getOwnPropertySymbols,kx=Object.prototype.hasOwnProperty,zx=Object.prototype.propertyIsEnumerable,Zo=(t,e,r)=>e in t?Bx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ur=(t,e)=>{for(var r in e||(e={}))kx.call(e,r)&&Zo(t,r,e[r]);if(Bl)for(var r of Bl(e))zx.call(e,r)&&Zo(t,r,e[r]);return t},Ln=(t,e)=>Ux(t,qx(e)),et=(t,e,r)=>Zo(t,typeof e!="symbol"?e+"":e,r);function Ji(t){return Number(t[0].split(":")[1])}function _i(t){return`0x${t.toString(16)}`}function Kx(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||Gi,events:s||Yi,rpcMap:ur({},e.length?{[Ji(e)]:a[Ji(e)]}:{})},u=s?.filter(p=>!Yi.includes(p)),l=n?.filter(p=>!Gi.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:Ep))],events:[...new Set(c.events.concat(o!=null&&o.length?o:_p))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?f:void 0}}class Os{constructor(){et(this,"events",new O0.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",jx),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 Os;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}=Kx(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(Ln(ur({namespaces:ur({},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=Mc(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:_i(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(Ln(ur({},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=Mc(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:_i(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",_i(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",Ln(ur({},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",_i(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||Gi:[],c=i.length?e?.events||Yi:[],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?Ji(this.rpc.chains):Ji(this.rpc.optionalChains),this.signer=await Rx.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 Fx(),{convertWCMToAppKitOptions:i}=await Promise.resolve().then(function(){return tA}),s=i(Ln(ur({},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(Ln(ur({},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])||`${Mx}?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 Hx=Os;var Vx=Object.defineProperty,Wx=Object.defineProperties,Gx=Object.getOwnPropertyDescriptors,Ul=Object.getOwnPropertySymbols,Yx=Object.prototype.hasOwnProperty,Jx=Object.prototype.propertyIsEnumerable,ql=(t,e,r)=>e in t?Vx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$p=(t,e)=>{for(var r in e||(e={}))Yx.call(e,r)&&ql(t,r,e[r]);if(Ul)for(var r of Ul(e))Jx.call(e,r)&&ql(t,r,e[r]);return t},Zx=(t,e)=>Wx(t,Gx(e));function Qx(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 Xx=t=>{const[e,r]=t.split(":");return Op({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function eA(t){var e,r,n,i,s,o,a;const c=(e=t.chains)==null?void 0:e.map(Xx).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:Qx(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:u,metadata:Zx($p({},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 Op(t){return $p({formatters:void 0,fees:void 0,serializers:void 0},t)}var tA=Object.freeze({__proto__:null,convertWCMToAppKitOptions:eA,defineChain:Op});const kA=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:Hx,OPTIONAL_EVENTS:_p,OPTIONAL_METHODS:Ep,REQUIRED_EVENTS:Yi,REQUIRED_METHODS:Gi,default:Os},Symbol.toStringTag,{value:"Module"}));export{ry as A,Jn as B,gb as C,xt as D,He as E,lt as F,St as G,_t as H,_r as I,kA as J,mc as P,Ch as Q,mr as a,vr as b,N as c,ai as d,aa as e,ht as f,Rh as g,rw as h,Lh as i,jn as j,wo as k,es as l,Eg as m,m0 as n,dt as o,ha as p,cs as q,os as r,Vt as s,Ze as t,$r as u,Xt as v,Wv as w,pr as x,Qe as y,as 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={};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-BsX5IiWg.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};
|