@dcl/explore-site 0.0.1-24252946891.commit-825a313 → 0.0.1-24267316931.commit-799a906
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/HomePage-CmbpPu7G.js +5 -0
- package/assets/{QueryClientProvider-C-NHVHHp.js → QueryClientProvider-BH-IbUQr.js} +1 -1
- package/assets/{SensorsRounded-JPN-5LAe.js → SensorsRounded-B21l4gbp.js} +1 -1
- package/assets/{__federation_expose_App-IZ0GxuOa.js → __federation_expose_App-CvYxiYru.js} +1 -1
- package/assets/{__federation_fn_import-BpUcHfOt.js → __federation_fn_import-DOOor4Tc.js} +1 -1
- package/assets/__federation_shared_@dcl/{hooks-DmfiTWc1.js → hooks-LDrJeRe8.js} +3 -3
- package/assets/__federation_shared_@emotion/react-15yK1GaH.js +1 -0
- package/assets/__federation_shared_@emotion/{styled-rphXTDtE.js → styled-DB7CfooL.js} +1 -1
- package/assets/{__federation_shared_decentraland-ui2-CGAOHsvb.js → __federation_shared_decentraland-ui2-De4vDvii.js} +6 -6
- package/assets/{__federation_shared_react-redux-DNN93ZTk.js → __federation_shared_react-redux-BTCU_VHn.js} +1 -1
- package/assets/{__federation_shared_react-router-dom-DAD_IRwb.js → __federation_shared_react-router-dom-8CrTxutN.js} +1 -1
- package/assets/{__federation_shared_viem-CtaxVkf9.js → __federation_shared_viem-L7rImFc2.js} +1 -1
- package/assets/{__federation_shared_wagmi-Cy245c18.js → __federation_shared_wagmi-xU7oGt7C.js} +1 -1
- package/assets/{add-CRDAsoS6.js → add-BIaFihyg.js} +1 -1
- package/assets/{all-wallets-M8PSbQIn.js → all-wallets-Cfqn8PYe.js} +1 -1
- package/assets/{app-store-BbwUhtBT.js → app-store-BxDqeIqC.js} +1 -1
- package/assets/{apple-KYMxwI8C.js → apple-QJkClsJb.js} +1 -1
- package/assets/{arrow-bottom-CpvmQ1Sm.js → arrow-bottom--x7UucJT.js} +1 -1
- package/assets/{arrow-bottom-circle-CerfhIVS.js → arrow-bottom-circle-B6n9IioS.js} +1 -1
- package/assets/{arrow-left-dVEFXKxi.js → arrow-left-CbI3FC2k.js} +1 -1
- package/assets/{arrow-right-Co8yigww.js → arrow-right-DUpKnhaL.js} +1 -1
- package/assets/{arrow-top-KlKLphV1.js → arrow-top-ed8A36YY.js} +1 -1
- package/assets/{auto-track-B5V2sEPk.js → auto-track-DVN9JGQL.js} +1 -1
- package/assets/{bank-DP6slqnu.js → bank-DXf1YkKA.js} +1 -1
- package/assets/{basic-Bbqn4F9Z.js → basic-DC4Q-2hh.js} +1 -1
- package/assets/{browser-DemG1Tjp.js → browser-CVrIMCbR.js} +1 -1
- package/assets/{card-DI9bRVEe.js → card-DgyBT68T.js} +1 -1
- package/assets/{ccip-BBFbZHDd.js → ccip-BFT6thRj.js} +1 -1
- package/assets/{checkmark-ClaV4zyl.js → checkmark-7hzDBsql.js} +1 -1
- package/assets/{checkmark-bold-CpTXXIQl.js → checkmark-bold-DGsuPsPt.js} +1 -1
- package/assets/{chevron-bottom-B7WEB302.js → chevron-bottom-KAJVVB8V.js} +1 -1
- package/assets/{chevron-left-s49yO0vq.js → chevron-left-QtyERYwY.js} +1 -1
- package/assets/{chevron-right-DLxDeInf.js → chevron-right-C0eFIW4T.js} +1 -1
- package/assets/{chevron-top-BNesEvvt.js → chevron-top-D_qeKe8O.js} +1 -1
- package/assets/{chrome-store-CYoj3jLA.js → chrome-store-B_QNIif-.js} +1 -1
- package/assets/{clock-Cowlhipt.js → clock-Dl1FecER.js} +1 -1
- package/assets/{close-CHDSWjeu.js → close-CVONymnQ.js} +1 -1
- package/assets/{coinPlaceholder-CWCahYS0.js → coinPlaceholder-D5mWuYoH.js} +1 -1
- package/assets/{compass-DTVuLPLx.js → compass-B6DJCHlH.js} +1 -1
- package/assets/{copy-CTWrc8Rs.js → copy-DXzUKW8b.js} +1 -1
- package/assets/{core-CpW5hIOT.js → core-CKL2t7br.js} +3 -3
- package/assets/{createClient-zxCjTTdy.js → createClient-BX8igSrC.js} +1 -1
- package/assets/{cursor-BFEE41Uw.js → cursor-BaYtj4Cp.js} +1 -1
- package/assets/{cursor-transparent-_fazXWeP.js → cursor-transparent-rkrBpH7G.js} +1 -1
- package/assets/{desktop-Cvlh7_59.js → desktop-BZmREBP0.js} +1 -1
- package/assets/{disconnect-D86MdYry.js → disconnect-JHh9OB23.js} +1 -1
- package/assets/{discord-D3nT23vI.js → discord-VVP8zM-_.js} +1 -1
- package/assets/{emotion-react.browser.esm-Dg3AE4Kj.js → emotion-react.browser.esm-DEU8IF7l.js} +1 -1
- package/assets/{emotion-use-insertion-effect-with-fallbacks.browser.esm-BB-KD4bd.js → emotion-use-insertion-effect-with-fallbacks.browser.esm-BVHTexMg.js} +1 -1
- package/assets/{etherscan-BdEW9vqc.js → etherscan-BbYifZFZ.js} +1 -1
- package/assets/{exclamation-triangle-B5oynvdL.js → exclamation-triangle-CpcXflnC.js} +1 -1
- package/assets/{extension-opfmx5KG.js → extension-CYQ7TNQ0.js} +1 -1
- package/assets/{external-link-HqD0KIHl.js → external-link-Bl_2Xa1d.js} +1 -1
- package/assets/{facebook-B4PtxY49.js → facebook-BLoOTkup.js} +1 -1
- package/assets/{farcaster-B7ZESl8t.js → farcaster-S-7ZNLCN.js} +1 -1
- package/assets/{filters-B9Lc7WUh.js → filters-rcIRW8Y2.js} +1 -1
- package/assets/{github-ej36lilR.js → github-1RRpC6gF.js} +1 -1
- package/assets/{google-SZDPskQA.js → google-BrEjql_r.js} +1 -1
- package/assets/{help-circle-Dlk1DWFb.js → help-circle-_-klJVev.js} +1 -1
- package/assets/{id-C1JuIBUw.js → id-BruMHf38.js} +1 -1
- package/assets/{image-DrbB-EB0.js → image-D_WfaLXE.js} +1 -1
- package/assets/{index-CS17BYIc.js → index-7-Mcjp5z.js} +1 -1
- package/assets/{index-WpGhNLfq.js → index-B73GCj3R.js} +1 -1
- package/assets/{index-YLeJoyMs.js → index-BUFfda2b.js} +1 -1
- package/assets/{index-0ao9d42m.js → index-Bmhq34sv.js} +1 -1
- package/assets/index-BqMgoBT5.js +1 -0
- package/assets/{index-DYH9xpq_.js → index-C4zctrBM.js} +1 -1
- package/assets/{index-BEfcyzqC.js → index-DA4Xnl3Z.js} +2 -2
- package/assets/{index-D6O4pjzC.js → index-DLT4yAcF.js} +1 -1
- package/assets/{index-Bsc49IIV.js → index-DsHsO_hv.js} +3 -3
- package/assets/index-Dy0yjznp.js +1 -1
- package/assets/index-VfkM29PH.js +1 -1
- package/assets/{index-BO7uzrKR.js → index-sWqGpxny.js} +1 -1
- package/assets/{index.es-CPsAnK0o.js → index.es-CzdwEqXn.js} +3 -3
- package/assets/{info-CGOdSL7l.js → info-XfmynO47.js} +1 -1
- package/assets/{info-circle-BwpvAP6c.js → info-circle-DVJGAyOl.js} +1 -1
- package/assets/jsx-runtime-B1l0k91v.js +1 -1
- package/assets/{lightbulb-DZgqqIhJ.js → lightbulb-DFNuvMz-.js} +1 -1
- package/assets/{localBatchGatewayRequest-DCkB3-pI.js → localBatchGatewayRequest-CaH3acob.js} +1 -1
- package/assets/{mail-DWm8ISSp.js → mail-Drod4DXU.js} +1 -1
- package/assets/{mobile-CbZLz58l.js → mobile-BJnalH7G.js} +1 -1
- package/assets/{more-DRXJyPbv.js → more-CzFkj1ed.js} +1 -1
- package/assets/{network-placeholder-n_BgsbNp.js → network-placeholder-BLUwDLic.js} +1 -1
- package/assets/{nftPlaceholder-BCafmzLA.js → nftPlaceholder-ChOx-BzT.js} +1 -1
- package/assets/{off-9RGrlpVz.js → off-CleAz5gO.js} +1 -1
- package/assets/{play-store-CgGjC9IP.js → play-store-DwxG6fai.js} +1 -1
- package/assets/{plus-DSM-LJkV.js → plus-Bvi_TZCr.js} +1 -1
- package/assets/{preload-helper-DQQ0dFoV.js → preload-helper-CDMQs6vf.js} +1 -1
- package/assets/{qr-code-B_iIzgRO.js → qr-code-A_RC2EmO.js} +1 -1
- package/assets/{recycle-horizontal-Bo6tvA9N.js → recycle-horizontal-B2rk_278.js} +1 -1
- package/assets/{refresh-B78swHHA.js → refresh-V894JvlS.js} +1 -1
- package/assets/remoteEntry.js +1 -1
- package/assets/{reown-logo-D2dt5GtC.js → reown-logo-BNIMS198.js} +1 -1
- package/assets/{search-MMFg1Zhv.js → search-DI_vEcaH.js} +1 -1
- package/assets/{secp256k1-n1MnUPPi.js → secp256k1-BW5LuV-N.js} +1 -1
- package/assets/{send-B3i1cdWv.js → send-ng28MvLm.js} +1 -1
- package/assets/{swapHorizontal-D_VQ2y9f.js → swapHorizontal-D0cqXt37.js} +1 -1
- package/assets/{swapHorizontalBold-BYohtxO2.js → swapHorizontalBold-CtmXcN3X.js} +1 -1
- package/assets/{swapHorizontalMedium-Clp3nUGv.js → swapHorizontalMedium-CjEnNl_e.js} +1 -1
- package/assets/{swapHorizontalRoundedBold-Huee7GR3.js → swapHorizontalRoundedBold-DmunpO0t.js} +1 -1
- package/assets/{swapVertical-Cnz02KmB.js → swapVertical-BSmQhuqF.js} +1 -1
- package/assets/{telegram-CfNIuKsL.js → telegram-BwcgdqeC.js} +1 -1
- package/assets/{three-dots-BHatBJ1U.js → three-dots-C4jGuJ67.js} +1 -1
- package/assets/{twitch-Beqf5KuC.js → twitch-DSM_HUQO.js} +1 -1
- package/assets/{twitterIcon-DuUcyFsu.js → twitterIcon-55En8ege.js} +1 -1
- package/assets/{uid-D-qT9Vzk.js → uid-B6TQPZnN.js} +3 -3
- package/assets/{verify-DcYfguuu.js → verify-B-XAdwYY.js} +1 -1
- package/assets/{verify-filled-Bm-OA5jk.js → verify-filled-BT00Wrp3.js} +1 -1
- package/assets/{w3m-modal-DHdvQ3lm.js → w3m-modal-Z27GCgYK.js} +1 -1
- package/assets/{wallet-BzCF_mRB.js → wallet-C3hGKolu.js} +1 -1
- package/assets/{wallet-placeholder-CLEz6Dmc.js → wallet-placeholder-CgMPW3Yz.js} +1 -1
- package/assets/{walletconnect-CFHDyppb.js → walletconnect-Blbor9eR.js} +1 -1
- package/assets/{warning-circle-CVUFMZ_R.js → warning-circle-aLVajLoj.js} +1 -1
- package/assets/{webSocket--2m-5bpv.js → webSocket-B1uGWEVk.js} +1 -1
- package/assets/{x-DpE2gOjc.js → x-CMcLjjTv.js} +1 -1
- package/index.html +14 -14
- package/package.json +3 -3
- package/assets/HomePage-CaRpsccZ.js +0 -5
- package/assets/__federation_shared_@emotion/react-CQqlYazz.js +0 -1
- package/assets/index-JFBsW0Hp.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__fileDeps=["assets/core-
|
|
2
|
-
import{_ as _p}from"./preload-helper-
|
|
1
|
+
const __vite__fileDeps=["assets/core-CKL2t7br.js","assets/preload-helper-CDMQs6vf.js","assets/_commonjsHelpers-C4iS2aBk.js","assets/index-nibyPLVP.js","assets/__federation_fn_import-DOOor4Tc.js"],__vite__mapDeps=i=>i.map(i=>__vite__fileDeps[i]);
|
|
2
|
+
import{_ as _p}from"./preload-helper-CDMQs6vf.js";import{g as pl,a as Ro,c as It}from"./_commonjsHelpers-C4iS2aBk.js";import{importShared as Ip}from"./__federation_fn_import-DOOor4Tc.js";import{c as $p,g as ga,s as Op,d as Dp,k as Sp,a as Pp}from"./index-nibyPLVP.js";var To={exports:{}},Vr=typeof Reflect=="object"?Reflect:null,ya=Vr&&typeof Vr.apply=="function"?Vr.apply:function(e,r,i){return Function.prototype.apply.call(e,r,i)},hn;Vr&&typeof Vr.ownKeys=="function"?hn=Vr.ownKeys:Object.getOwnPropertySymbols?hn=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:hn=function(e){return Object.getOwnPropertyNames(e)};function Ap(t){console&&console.warn&&console.warn(t)}var fl=Number.isNaN||function(e){return e!==e};function re(){re.init.call(this)}To.exports=re;To.exports.once=Tp;re.EventEmitter=re;re.prototype._events=void 0;re.prototype._eventsCount=0;re.prototype._maxListeners=void 0;var ma=10;function Ln(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(re,"defaultMaxListeners",{enumerable:!0,get:function(){return ma},set:function(t){if(typeof t!="number"||t<0||fl(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");ma=t}});re.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};re.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||fl(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 gl(t){return t._maxListeners===void 0?re.defaultMaxListeners:t._maxListeners}re.prototype.getMaxListeners=function(){return gl(this)};re.prototype.emit=function(e){for(var r=[],i=1;i<arguments.length;i++)r.push(arguments[i]);var n=e==="error",s=this._events;if(s!==void 0)n=n&&s.error===void 0;else if(!n)return!1;if(n){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")ya(c,this,r);else for(var u=c.length,l=vl(c,u),i=0;i<u;++i)ya(l[i],this,r);return!0};function yl(t,e,r,i){var n,s,o;if(Ln(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]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),n=gl(t),n>0&&o.length>n&&!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,Ap(a)}return t}re.prototype.addListener=function(e,r){return yl(this,e,r,!1)};re.prototype.on=re.prototype.addListener;re.prototype.prependListener=function(e,r){return yl(this,e,r,!0)};function xp(){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 ml(t,e,r){var i={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},n=xp.bind(i);return n.listener=r,i.wrapFn=n,n}re.prototype.once=function(e,r){return Ln(r),this.on(e,ml(this,e,r)),this};re.prototype.prependOnceListener=function(e,r){return Ln(r),this.prependListener(e,ml(this,e,r)),this};re.prototype.removeListener=function(e,r){var i,n,s,o,a;if(Ln(r),n=this._events,n===void 0)return this;if(i=n[e],i===void 0)return this;if(i===r||i.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||r));else if(typeof i!="function"){for(s=-1,o=i.length-1;o>=0;o--)if(i[o]===r||i[o].listener===r){a=i[o].listener,s=o;break}if(s<0)return this;s===0?i.shift():Cp(i,s),i.length===1&&(n[e]=i[0]),n.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};re.prototype.off=re.prototype.removeListener;re.prototype.removeAllListeners=function(e){var r,i,n;if(i=this._events,i===void 0)return this;if(i.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):i[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete i[e]),this;if(arguments.length===0){var s=Object.keys(i),o;for(n=0;n<s.length;++n)o=s[n],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=i[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(n=r.length-1;n>=0;n--)this.removeListener(e,r[n]);return this};function wl(t,e,r){var i=t._events;if(i===void 0)return[];var n=i[e];return n===void 0?[]:typeof n=="function"?r?[n.listener||n]:[n]:r?Rp(n):vl(n,n.length)}re.prototype.listeners=function(e){return wl(this,e,!0)};re.prototype.rawListeners=function(e){return wl(this,e,!1)};re.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):bl.call(t,e)};re.prototype.listenerCount=bl;function bl(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}re.prototype.eventNames=function(){return this._eventsCount>0?hn(this._events):[]};function vl(t,e){for(var r=new Array(e),i=0;i<e;++i)r[i]=t[i];return r}function Cp(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function Rp(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function Tp(t,e){return new Promise(function(r,i){function n(o){t.removeListener(e,s),i(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",n),r([].slice.call(arguments))}El(t,e,s,{once:!0}),e!=="error"&&Np(t,n,{once:!0})})}function Np(t,e,r){typeof t.on=="function"&&El(t,"error",e,r)}function El(t,e,r,i){if(typeof t.on=="function")i.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function n(s){i.once&&t.removeEventListener(e,n),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var Lp=To.exports,N={};/*! *****************************************************************************
|
|
3
3
|
Copyright (c) Microsoft Corporation.
|
|
4
4
|
|
|
5
5
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
@@ -35,4 +35,4 @@ ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(p0(r)).toStr
|
|
|
35
35
|
Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||i)return;const d=li(e[h].accounts);d.includes(h)||(i=L("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${h}
|
|
36
36
|
Required: ${h}
|
|
37
37
|
Approved: ${d.toString()}`))}),o.forEach(h=>{i||(ur(n[h].methods,s[h].methods)?ur(n[h].events,s[h].events)||(i=L("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${h}`)):i=L("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${h}`))}),i}function ZE(t){const e={};return Object.keys(t).forEach(r=>{var i;r.includes(":")?e[r]=t[r]:(i=t[r].chains)==null||i.forEach(n=>{e[n]={methods:t[r].methods,events:t[r].events}})}),e}function au(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function QE(t){const e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:li(t[r].accounts)?.forEach(n=>{e[n]={accounts:t[r].accounts.filter(s=>s.includes(`${n}:`)),methods:t[r].methods,events:t[r].events}})}),e}function XE(t,e){return ia(t)&&t<=e.max&&t>=e.min}function cu(){const t=qi();return new Promise(e=>{switch(t){case Qe.browser:e(e_());break;case Qe.reactNative:e(t_());break;case Qe.node:e(r_());break;default:e(!0)}})}function e_(){return ai()&&navigator?.onLine}async function t_(){return Zt()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function r_(){return!0}function i_(t){switch(qi()){case Qe.browser:n_(t);break;case Qe.reactNative:s_(t);break}}function n_(t){!Zt()&&ai()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function s_(t){Zt()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function o_(){var t;return ai()&&dr()?((t=dr())==null?void 0:t.visibilityState)==="visible":!0}const Cs={};class gi{static get(e){return Cs[e]}static set(e,r){Cs[e]=r}static delete(e){delete Cs[e]}}function a_(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Ee(t,...e){try{return a_(t(...e))}catch(r){return Promise.reject(r)}}function c_(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function u_(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function wn(t){if(c_(t))return String(t);if(u_(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return wn(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const go="base64:";function l_(t){return typeof t=="string"?t:go+p_(t)}function h_(t){return typeof t!="string"||!t.startsWith(go)?t:d_(t.slice(go.length))}function d_(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function p_(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function ke(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function f_(...t){return ke(t.join(":"))}function nn(t){return t=ke(t),t?t+":":""}function g_(t,e){if(e===void 0)return!0;let r=0,i=t.indexOf(":");for(;i>-1;)r++,i=t.indexOf(":",i+1);return r<=e}function y_(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const m_="memory",w_=()=>{const t=new Map;return{name:m_,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 b_(t={}){const e={mounts:{"":t.driver||w_()},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[""]}},i=(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]})),n=(u,l)=>{if(e.watching){l=ke(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 uu(e.mounts[u],n,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 d=new Map,f=p=>{let y=d.get(p.base);return y||(y={driver:p.driver,base:p.base,items:[]},d.set(p.base,y)),y};for(const p of u){const y=typeof p=="string",w=ke(y?p:p.key),v=y?void 0:p.value,b=y||!p.options?l:{...l,...p.options},E=r(w);f(E).items.push({key:w,value:v,relativeKey:E.relativeKey,options:b})}return Promise.all([...d.values()].map(p=>h(p))).then(p=>p.flat())},c={hasItem(u,l={}){u=ke(u);const{relativeKey:h,driver:d}=r(u);return Ee(d.hasItem,h,l)},getItem(u,l={}){u=ke(u);const{relativeKey:h,driver:d}=r(u);return Ee(d.getItem,h,l).then(f=>Gi(f))},getItems(u,l={}){return a(u,l,h=>h.driver.getItems?Ee(h.driver.getItems,h.items.map(d=>({key:d.relativeKey,options:d.options})),l).then(d=>d.map(f=>({key:f_(h.base,f.key),value:Gi(f.value)}))):Promise.all(h.items.map(d=>Ee(h.driver.getItem,d.relativeKey,d.options).then(f=>({key:d.key,value:Gi(f)})))))},getItemRaw(u,l={}){u=ke(u);const{relativeKey:h,driver:d}=r(u);return d.getItemRaw?Ee(d.getItemRaw,h,l):Ee(d.getItem,h,l).then(f=>h_(f))},async setItem(u,l,h={}){if(l===void 0)return c.removeItem(u);u=ke(u);const{relativeKey:d,driver:f}=r(u);f.setItem&&(await Ee(f.setItem,d,wn(l),h),f.watch||n("update",u))},async setItems(u,l){await a(u,l,async h=>{if(h.driver.setItems)return Ee(h.driver.setItems,h.items.map(d=>({key:d.relativeKey,value:wn(d.value),options:d.options})),l);h.driver.setItem&&await Promise.all(h.items.map(d=>Ee(h.driver.setItem,d.relativeKey,wn(d.value),d.options)))})},async setItemRaw(u,l,h={}){if(l===void 0)return c.removeItem(u,h);u=ke(u);const{relativeKey:d,driver:f}=r(u);if(f.setItemRaw)await Ee(f.setItemRaw,d,l,h);else if(f.setItem)await Ee(f.setItem,d,l_(l),h);else return;f.watch||n("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=ke(u);const{relativeKey:h,driver:d}=r(u);d.removeItem&&(await Ee(d.removeItem,h,l),(l.removeMeta||l.removeMata)&&await Ee(d.removeItem,h+"$",l),d.watch||n("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=ke(u);const{relativeKey:h,driver:d}=r(u),f=Object.create(null);if(d.getMeta&&Object.assign(f,await Ee(d.getMeta,h,l)),!l.nativeOnly){const p=await Ee(d.getItem,h+"$",l).then(y=>Gi(y));p&&typeof p=="object"&&(typeof p.atime=="string"&&(p.atime=new Date(p.atime)),typeof p.mtime=="string"&&(p.mtime=new Date(p.mtime)),Object.assign(f,p))}return f},setMeta(u,l,h={}){return this.setItem(u+"$",l,h)},removeMeta(u,l={}){return this.removeItem(u+"$",l)},async getKeys(u,l={}){u=nn(u);const h=i(u,!0);let d=[];const f=[];let p=!0;for(const w of h){w.driver.flags?.maxDepth||(p=!1);const v=await Ee(w.driver.getKeys,w.relativeBase,l);for(const b of v){const E=w.mountpoint+ke(b);d.some($=>E.startsWith($))||f.push(E)}d=[w.mountpoint,...d.filter(b=>!b.startsWith(w.mountpoint))]}const y=l.maxDepth!==void 0&&!p;return f.filter(w=>(!y||g_(w,l.maxDepth))&&y_(w,u))},async clear(u,l={}){u=nn(u),await Promise.all(i(u,!1).map(async h=>{if(h.driver.clear)return Ee(h.driver.clear,h.relativeBase,l);if(h.driver.removeItem){const d=await h.driver.getKeys(h.relativeBase||"",l);return Promise.all(d.map(f=>h.driver.removeItem(f,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>lu(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=nn(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((h,d)=>d.length-h.length)),e.mounts[u]=l,e.watching&&Promise.resolve(uu(l,n,u)).then(h=>{e.unwatch[u]=h}).catch(console.error),c},async unmount(u,l=!0){u=nn(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u]?.(),delete e.unwatch[u]),l&&await lu(e.mounts[u]),e.mountpoints=e.mountpoints.filter(h=>h!==u),delete e.mounts[u])},getMount(u=""){u=ke(u)+":";const l=r(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=ke(u),i(u,l.parents).map(d=>({driver:d.driver,base:d.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 uu(t,e,r){return t.watch?t.watch((i,n)=>e(i,r+n)):()=>{}}async function lu(t){typeof t.dispose=="function"&&await Ee(t.dispose)}const v_="idb-keyval";var E_=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=n=>e+n;let i;return t.dbName&&t.storeName&&(i=$p(t.dbName,t.storeName)),{name:v_,options:t,async hasItem(n){return!(typeof await ga(r(n),i)>"u")},async getItem(n){return await ga(r(n),i)??null},setItem(n,s){return Op(r(n),s,i)},removeItem(n){return Dp(r(n),i)},getKeys(){return Sp(i)},clear(){return Pp(i)}}};const __="WALLET_CONNECT_V2_INDEXED_DB",I_="keyvaluestorage";let $_=class{constructor(){this.indexedDb=b_({driver:E_({dbName:__,storeName:I_})})}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,Ft(r))}async removeItem(e){await this.indexedDb.removeItem(e)}};var Rs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},bn={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,i){this[r]=String(i)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){const r=this;Object.keys(r).forEach(function(i){r[i]=void 0,delete r[i]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof Rs<"u"&&Rs.localStorage?bn.exports=Rs.localStorage:typeof window<"u"&&window.localStorage?bn.exports=window.localStorage:bn.exports=new e})();function O_(t){var e;return[t[0],hr((e=t[1])!=null?e:"")]}let D_=class{constructor(){this.localStorage=bn.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(O_)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return hr(r)}async setItem(e,r){this.localStorage.setItem(e,Ft(r))}async removeItem(e){this.localStorage.removeItem(e)}};const S_="wc_storage_version",hu=1,P_=async(t,e,r)=>{const i=S_,n=await e.getItem(i);if(n&&n>=hu){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(i,hu),r(e),A_(t,o)},A_=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};let x_=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new D_;this.storage=e;try{const r=new $_;P_(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 C_=Object.defineProperty,R_=(t,e,r)=>e in t?C_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,du=(t,e,r)=>R_(t,typeof e!="symbol"?e+"":e,r);let T_=class extends yr{constructor(e){super(),this.opts=e,du(this,"protocol","wc"),du(this,"version",2)}};var N_=Object.defineProperty,L_=(t,e,r)=>e in t?N_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,j_=(t,e,r)=>L_(t,e+"",r);let B_=class extends yr{constructor(e,r){super(),this.core=e,this.logger=r,j_(this,"records",new Map)}},M_=class{constructor(e,r){this.logger=e,this.core=r}};class F_ extends yr{constructor(e,r){super(),this.relayer=e,this.logger=r}}let U_=class extends yr{constructor(e){super()}},q_=class{constructor(e,r,i,n){this.core=e,this.logger=r,this.name=i}},k_=class extends yr{constructor(e,r){super(),this.relayer=e,this.logger=r}},z_=class extends yr{constructor(e,r){super(),this.core=e,this.logger=r}},H_=class{constructor(e,r,i){this.core=e,this.logger=r,this.store=i}},K_=class{constructor(e,r){this.projectId=e,this.logger=r}},V_=class{constructor(e,r,i){this.core=e,this.logger=r,this.telemetryEnabled=i}};var W_=Object.defineProperty,G_=(t,e,r)=>e in t?W_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pu=(t,e,r)=>G_(t,typeof e!="symbol"?e+"":e,r);let Y_=class{constructor(e){this.opts=e,pu(this,"protocol","wc"),pu(this,"version",2)}},J_=class{constructor(e){this.client=e}};var Z_={};const Sd="wc",Pd=2,Cn="core",St=`${Sd}@2:${Cn}:`,Q_={name:Cn,logger:"error"},X_={database:":memory:"},eI="crypto",fu="client_ed25519_seed",tI=N.ONE_DAY,rI="keychain",iI="0.3",nI="messages",sI="0.3",gu=N.SIX_HOURS,oI="publisher",Ad="irn",aI="error",xd="wss://relay.walletconnect.org",cI="relayer",Ie={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"},uI="_subscription",tt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},lI=.1,yo="2.21.1",de={link_mode:"link_mode",relay:"relay"},vn={inbound:"inbound",outbound:"outbound"},hI="0.3",dI="WALLETCONNECT_CLIENT_ID",yu="WALLETCONNECT_LINK_MODE_APPS",Ye={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},pI="subscription",fI="0.3",gI="pairing",yI="0.3",yi={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}}},or={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},ut={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},mI="history",wI="0.3",bI="expirer",it={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},vI="0.3",EI="verify-api",_I="https://verify.walletconnect.com",Cd="https://verify.walletconnect.org",Di=Cd,II=`${Di}/v3`,$I=[_I,Cd],OI="echo",DI="https://echo.walletconnect.com",vt={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"},Nt={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"},lt={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"},er={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"},tr={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"},mi={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"},SI=.1,PI="event-client",AI=86400,xI="https://pulse.walletconnect.org/batch";function CI(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=n}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,w=0,v=0,b=p.length;v!==b&&p[v]===0;)v++,y++;for(var E=(b-v)*l+1>>>0,$=new Uint8Array(E);v!==b;){for(var A=p[v],P=0,S=E-1;(A!==0||P<w)&&S!==-1;S--,P++)A+=256*$[S]>>>0,$[S]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");w=P,v++}for(var C=E-w;C!==E&&$[C]===0;)C++;for(var O=c.repeat(y);C<E;++C)O+=t.charAt($[C]);return O}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var w=0,v=0;p[y]===c;)w++,y++;for(var b=(p.length-y)*u+1>>>0,E=new Uint8Array(b);p[y];){var $=r[p.charCodeAt(y)];if($===255)return;for(var A=0,P=b-1;($!==0||A<v)&&P!==-1;P--,A++)$+=a*E[P]>>>0,E[P]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");v=A,y++}if(p[y]!==" "){for(var S=b-v;S!==b&&E[S]===0;)S++;for(var C=new Uint8Array(w+(b-S)),O=w;S!==b;)C[O++]=E[S++];return C}}}function f(p){var y=d(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:f}}var RI=CI,TI=RI;const Rd=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")},NI=t=>new TextEncoder().encode(t),LI=t=>new TextDecoder().decode(t);class jI{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class BI{constructor(e,r,i){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=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Td(this,e)}}class MI{constructor(e){this.decoders=e}or(e){return Td(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Td=(t,e)=>new MI({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class FI{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new jI(e,r,i),this.decoder=new BI(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ts=({name:t,prefix:e,encode:r,decode:i})=>new FI(t,e,r,i),Wi=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=TI(r,e);return ts({prefix:t,name:e,encode:i,decode:s=>Rd(n(s))})},UI=(t,e,r,i)=>{const n={};for(let l=0;l<e.length;++l)n[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=n[t[l]];if(h===void 0)throw new SyntaxError(`Non-${i} 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},qI=(t,e,r)=>{const i=e[e.length-1]==="=",n=(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[n&a>>o];if(o&&(s+=e[n&a<<r-o]),i)for(;s.length*r&7;)s+="=";return s},Re=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>ts({prefix:e,name:t,encode(n){return qI(n,i,r)},decode(n){return UI(n,i,r,t)}}),kI=ts({prefix:"\0",name:"identity",encode:t=>LI(t),decode:t=>NI(t)});var zI=Object.freeze({__proto__:null,identity:kI});const HI=Re({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var KI=Object.freeze({__proto__:null,base2:HI});const VI=Re({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var WI=Object.freeze({__proto__:null,base8:VI});const GI=Wi({prefix:"9",name:"base10",alphabet:"0123456789"});var YI=Object.freeze({__proto__:null,base10:GI});const JI=Re({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ZI=Re({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var QI=Object.freeze({__proto__:null,base16:JI,base16upper:ZI});const XI=Re({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),e$=Re({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),t$=Re({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),r$=Re({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),i$=Re({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),n$=Re({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),s$=Re({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),o$=Re({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),a$=Re({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var c$=Object.freeze({__proto__:null,base32:XI,base32upper:e$,base32pad:t$,base32padupper:r$,base32hex:i$,base32hexupper:n$,base32hexpad:s$,base32hexpadupper:o$,base32z:a$});const u$=Wi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),l$=Wi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var h$=Object.freeze({__proto__:null,base36:u$,base36upper:l$});const d$=Wi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),p$=Wi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var f$=Object.freeze({__proto__:null,base58btc:d$,base58flickr:p$});const g$=Re({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),y$=Re({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),m$=Re({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),w$=Re({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var b$=Object.freeze({__proto__:null,base64:g$,base64pad:y$,base64url:m$,base64urlpad:w$});const Nd=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),v$=Nd.reduce((t,e,r)=>(t[r]=e,t),[]),E$=Nd.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function _$(t){return t.reduce((e,r)=>(e+=v$[r],e),"")}function I$(t){const e=[];for(const r of t){const i=E$[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const $$=ts({prefix:"🚀",name:"base256emoji",encode:_$,decode:I$});var O$=Object.freeze({__proto__:null,base256emoji:$$}),D$=Ld,mu=128,S$=127,P$=~S$,A$=Math.pow(2,31);function Ld(t,e,r){e=e||[],r=r||0;for(var i=r;t>=A$;)e[r++]=t&255|mu,t/=128;for(;t&P$;)e[r++]=t&255|mu,t>>>=7;return e[r]=t|0,Ld.bytes=r-i+1,e}var x$=mo,C$=128,wu=127;function mo(t,i){var r=0,i=i||0,n=0,s=i,o,a=t.length;do{if(s>=a)throw mo.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=n<28?(o&wu)<<n:(o&wu)*Math.pow(2,n),n+=7}while(o>=C$);return mo.bytes=s-i,r}var R$=Math.pow(2,7),T$=Math.pow(2,14),N$=Math.pow(2,21),L$=Math.pow(2,28),j$=Math.pow(2,35),B$=Math.pow(2,42),M$=Math.pow(2,49),F$=Math.pow(2,56),U$=Math.pow(2,63),q$=function(t){return t<R$?1:t<T$?2:t<N$?3:t<L$?4:t<j$?5:t<B$?6:t<M$?7:t<F$?8:t<U$?9:10},k$={encode:D$,decode:x$,encodingLength:q$},jd=k$;const bu=(t,e,r=0)=>(jd.encode(t,e,r),e),vu=t=>jd.encodingLength(t),wo=(t,e)=>{const r=e.byteLength,i=vu(t),n=i+vu(r),s=new Uint8Array(n+r);return bu(t,s,0),bu(r,s,i),s.set(e,n),new z$(t,r,e,s)};class z${constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const Bd=({name:t,code:e,encode:r})=>new H$(t,e,r);class H${constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?wo(this.code,r):r.then(i=>wo(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Md=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),K$=Bd({name:"sha2-256",code:18,encode:Md("SHA-256")}),V$=Bd({name:"sha2-512",code:19,encode:Md("SHA-512")});var W$=Object.freeze({__proto__:null,sha256:K$,sha512:V$});const Fd=0,G$="identity",Ud=Rd,Y$=t=>wo(Fd,Ud(t)),J$={code:Fd,name:G$,encode:Ud,digest:Y$};var Z$=Object.freeze({__proto__:null,identity:J$});new TextEncoder,new TextDecoder;const Eu={...zI,...KI,...WI,...YI,...QI,...c$,...h$,...f$,...b$,...O$};({...W$,...Z$});function Q$(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function qd(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const _u=qd("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Ts=qd("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=Q$(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),X$={utf8:_u,"utf-8":_u,hex:Eu.base16,latin1:Ts,ascii:Ts,binary:Ts,...Eu};function eO(t,e="utf8"){const r=X$[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 tO=Object.defineProperty,rO=(t,e,r)=>e in t?tO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wt=(t,e,r)=>rO(t,typeof e!="symbol"?e+"":e,r);class iO{constructor(e,r){this.core=e,this.logger=r,wt(this,"keychain",new Map),wt(this,"name",rI),wt(this,"version",iI),wt(this,"initialized",!1),wt(this,"storagePrefix",St),wt(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),wt(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),wt(this,"set",async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()}),wt(this,"get",i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=L("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n}),wt(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=Fe(r,this.name)}get context(){return Ve(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,ro(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?io(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var nO=Object.defineProperty,sO=(t,e,r)=>e in t?nO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pe=(t,e,r)=>sO(t,typeof e!="symbol"?e+"":e,r);class oO{constructor(e,r,i){this.core=e,this.logger=r,Pe(this,"name",eI),Pe(this,"keychain"),Pe(this,"randomSessionIdentifier",fo()),Pe(this,"initialized",!1),Pe(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Pe(this,"hasKeys",n=>(this.isInitialized(),this.keychain.has(n))),Pe(this,"getClientId",async()=>{this.isInitialized();const n=await this.getClientSeed(),s=Ja(n);return rh(s.publicKey)}),Pe(this,"generateKeyPair",()=>{this.isInitialized();const n=nE();return this.setPrivateKey(n.publicKey,n.privateKey)}),Pe(this,"signJWT",async n=>{this.isInitialized();const s=await this.getClientSeed(),o=Ja(s),a=this.randomSessionIdentifier;return await Mm(a,n,tI,o)}),Pe(this,"generateSharedKey",(n,s,o)=>{this.isInitialized();const a=this.getPrivateKey(n),c=sE(a,s);return this.setSymKey(c,o)}),Pe(this,"setSymKey",async(n,s)=>{this.isInitialized();const o=s||mn(n);return await this.keychain.set(o,n),o}),Pe(this,"deleteKeyPair",async n=>{this.isInitialized(),await this.keychain.del(n)}),Pe(this,"deleteSymKey",async n=>{this.isInitialized(),await this.keychain.del(n)}),Pe(this,"encode",async(n,s,o)=>{this.isInitialized();const a=$d(o),c=Ft(s);if(Zc(a))return cE(c,o?.encoding);if(Jc(a)){const d=a.senderPublicKey,f=a.receiverPublicKey;n=await this.generateSharedKey(d,f)}const u=this.getSymKey(n),{type:l,senderPublicKey:h}=a;return oE({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o?.encoding})}),Pe(this,"decode",async(n,s,o)=>{this.isInitialized();const a=lE(s,o);if(Zc(a)){const c=uE(s,o?.encoding);return hr(c)}if(Jc(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;n=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(n),u=aE({symKey:c,encoded:s,encoding:o?.encoding});return hr(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Pe(this,"getPayloadType",(n,s=pt)=>{const o=ji({encoded:n,encoding:s});return gr(o.type)}),Pe(this,"getPayloadSenderPublicKey",(n,s=pt)=>{const o=ji({encoded:n,encoding:s});return o.senderPublicKey?Ke(o.senderPublicKey,Me):void 0}),this.core=e,this.logger=Fe(r,this.name),this.keychain=i||new iO(this.core,this.logger)}get context(){return Ve(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(fu)}catch{e=fo(),await this.keychain.set(fu,e)}return eO(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var aO=Object.defineProperty,cO=Object.defineProperties,uO=Object.getOwnPropertyDescriptors,Iu=Object.getOwnPropertySymbols,lO=Object.prototype.hasOwnProperty,hO=Object.prototype.propertyIsEnumerable,bo=(t,e,r)=>e in t?aO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,dO=(t,e)=>{for(var r in e||(e={}))lO.call(e,r)&&bo(t,r,e[r]);if(Iu)for(var r of Iu(e))hO.call(e,r)&&bo(t,r,e[r]);return t},pO=(t,e)=>cO(t,uO(e)),We=(t,e,r)=>bo(t,typeof e!="symbol"?e+"":e,r);class fO extends M_{constructor(e,r){super(e,r),this.logger=e,this.core=r,We(this,"messages",new Map),We(this,"messagesWithoutClientAck",new Map),We(this,"name",nI),We(this,"version",sI),We(this,"initialized",!1),We(this,"storagePrefix",St),We(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const n=await this.getRelayerMessagesWithoutClientAck();typeof n<"u"&&(this.messagesWithoutClientAck=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),We(this,"set",async(i,n,s)=>{this.isInitialized();const o=$t(n);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=n,this.messages.set(i,a),s===vn.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,pO(dO({},c),{[o]:n}))}return await this.persist(),o}),We(this,"get",i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n}),We(this,"getWithoutAck",i=>{this.isInitialized();const n={};for(const s of i){const o=this.messagesWithoutClientAck.get(s)||{};n[s]=Object.values(o)}return n}),We(this,"has",(i,n)=>{this.isInitialized();const s=this.get(i),o=$t(n);return typeof s[o]<"u"}),We(this,"ack",async(i,n)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(i);if(typeof s>"u")return;const o=$t(n);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,s),await this.persist()}),We(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=Fe(e,this.name),this.core=r}get context(){return Ve(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,ro(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,ro(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?io(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?io(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var gO=Object.defineProperty,yO=Object.defineProperties,mO=Object.getOwnPropertyDescriptors,$u=Object.getOwnPropertySymbols,wO=Object.prototype.hasOwnProperty,bO=Object.prototype.propertyIsEnumerable,vo=(t,e,r)=>e in t?gO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sn=(t,e)=>{for(var r in e||(e={}))wO.call(e,r)&&vo(t,r,e[r]);if($u)for(var r of $u(e))bO.call(e,r)&&vo(t,r,e[r]);return t},Ns=(t,e)=>yO(t,mO(e)),ht=(t,e,r)=>vo(t,typeof e!="symbol"?e+"":e,r);class vO extends F_{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ht(this,"events",new Ut.EventEmitter),ht(this,"name",oI),ht(this,"queue",new Map),ht(this,"publishTimeout",N.toMiliseconds(N.ONE_MINUTE)),ht(this,"initialPublishTimeout",N.toMiliseconds(N.ONE_SECOND*15)),ht(this,"needsTransportRestart",!1),ht(this,"publish",async(i,n,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:s}});const a=s?.ttl||gu,c=An(s),u=s?.prompt||!1,l=s?.tag||0,h=s?.id||cr().toString(),d={topic:i,message:n,opts:{ttl:a,relay:c,prompt:u,tag:l,id:h,attestation:s?.attestation,tvf:s?.tvf}},f=`Failed to publish payload, please try again. id:${h} tag:${l}`;try{const p=new Promise(async y=>{const w=({id:b})=>{d.opts.id===b&&(this.removeRequestFromQueue(b),this.relayer.events.removeListener(Ie.publish,w),y(d))};this.relayer.events.on(Ie.publish,w);const v=Gt(new Promise((b,E)=>{this.rpcPublish({topic:i,message:n,ttl:a,prompt:u,tag:l,id:h,attestation:s?.attestation,tvf:s?.tvf}).then(b).catch($=>{this.logger.warn($,$?.message),E($)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${h} tag:${l}`);try{await v,this.events.removeListener(Ie.publish,w)}catch(b){this.queue.set(h,Ns(sn({},d),{attempt:1})),this.logger.warn(b,b?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:h,topic:i,message:n,opts:s}}),await Gt(p,this.publishTimeout,f)}catch(p){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(p),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw p}finally{this.queue.delete(h)}}),ht(this,"on",(i,n)=>{this.events.on(i,n)}),ht(this,"once",(i,n)=>{this.events.once(i,n)}),ht(this,"off",(i,n)=>{this.events.off(i,n)}),ht(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.relayer=e,this.logger=Fe(r,this.name),this.registerEventListeners()}get context(){return Ve(this.logger)}async rpcPublish(e){var r,i,n,s;const{topic:o,message:a,ttl:c=gu,prompt:u,tag:l,id:h,attestation:d,tvf:f}=e,p={method:Ei(An().protocol).publish,params:sn({topic:o,message:a,ttl:c,prompt:u,tag:l,attestation:d},f),id:h};Le((r=p.params)==null?void 0:r.prompt)&&((i=p.params)==null||delete i.prompt),Le((n=p.params)==null?void 0:n.tag)&&((s=p.params)==null||delete s.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:p});const y=await this.relayer.request(p);return this.relayer.events.emit(Ie.publish,e),this.logger.debug("Successfully Published Payload"),y}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const i=e.attempt+1;this.queue.set(r,Ns(sn({},e),{attempt:i}));const{topic:n,message:s,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish(Ns(sn({},e),{topic:n,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(mr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Ie.connection_stalled);return}this.checkQueue()}),this.relayer.on(Ie.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var EO=Object.defineProperty,_O=(t,e,r)=>e in t?EO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pr=(t,e,r)=>_O(t,typeof e!="symbol"?e+"":e,r);class IO{constructor(){Pr(this,"map",new Map),Pr(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),Pr(this,"get",e=>this.map.get(e)||[]),Pr(this,"exists",(e,r)=>this.get(e).includes(r)),Pr(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,r))return;const n=i.filter(s=>s!==r);if(!n.length){this.map.delete(e);return}this.map.set(e,n)}),Pr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var $O=Object.defineProperty,OO=Object.defineProperties,DO=Object.getOwnPropertyDescriptors,Ou=Object.getOwnPropertySymbols,SO=Object.prototype.hasOwnProperty,PO=Object.prototype.propertyIsEnumerable,Eo=(t,e,r)=>e in t?$O(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wi=(t,e)=>{for(var r in e||(e={}))SO.call(e,r)&&Eo(t,r,e[r]);if(Ou)for(var r of Ou(e))PO.call(e,r)&&Eo(t,r,e[r]);return t},Ls=(t,e)=>OO(t,DO(e)),ae=(t,e,r)=>Eo(t,typeof e!="symbol"?e+"":e,r);class AO extends k_{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ae(this,"subscriptions",new Map),ae(this,"topicMap",new IO),ae(this,"events",new Ut.EventEmitter),ae(this,"name",pI),ae(this,"version",fI),ae(this,"pending",new Map),ae(this,"cached",[]),ae(this,"initialized",!1),ae(this,"storagePrefix",St),ae(this,"subscribeTimeout",N.toMiliseconds(N.ONE_MINUTE)),ae(this,"initialSubscribeTimeout",N.toMiliseconds(N.ONE_SECOND*15)),ae(this,"clientId"),ae(this,"batchSubscribeTopicsLimit",500),ae(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ae(this,"subscribe",async(i,n)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const s=An(n),o={topic:i,relay:s,transportType:n?.transportType};this.pending.set(i,o);const a=await this.rpcSubscribe(i,s,n);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}})),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}}),ae(this,"unsubscribe",async(i,n)=>{this.isInitialized(),typeof n?.id<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)}),ae(this,"isSubscribed",i=>new Promise(n=>{n(this.topicMap.topics.includes(i))})),ae(this,"isKnownTopic",i=>new Promise(n=>{n(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(s=>s.topic===i))})),ae(this,"on",(i,n)=>{this.events.on(i,n)}),ae(this,"once",(i,n)=>{this.events.once(i,n)}),ae(this,"off",(i,n)=>{this.events.off(i,n)}),ae(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),ae(this,"start",async()=>{await this.onConnect()}),ae(this,"stop",async()=>{await this.onDisconnect()}),ae(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ae(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(n=>{i.push(n)}),await this.batchSubscribe(i)}),ae(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(mr.pulse,async()=>{await this.checkPending()}),this.events.on(Ye.created,async i=>{const n=Ye.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()}),this.events.on(Ye.deleted,async i=>{const n=Ye.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()})}),this.relayer=e,this.logger=Fe(r,this.name),this.clientId=""}get context(){return Ve(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 i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const i=this.topicMap.get(e);await Promise.all(i.map(async n=>await this.unsubscribeById(e,n,r)))}async unsubscribeById(e,r,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}});try{const n=An(i);await this.restartToComplete({topic:e,id:r,relay:n}),await this.rpcUnsubscribe(e,r,n);const s=te("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:i}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,r,i){var n;(!i||i?.transportType===de.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const s={method:Ei(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});const o=(n=i?.internal)==null?void 0:n.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(i?.transportType===de.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=d=>{d.topic===e&&(this.events.removeListener(Ye.created,h),l(d.id))};this.events.on(Ye.created,h);try{const d=await Gt(new Promise((f,p)=>{this.relayer.request(s).catch(y=>{this.logger.warn(y,y?.message),p(y)}).then(f)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Ye.created,h),l(d)}catch{}}),u=await Gt(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(Ie.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:Ei(r.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await Gt(new Promise(n=>{this.relayer.request(i).catch(s=>this.logger.warn(s)).then(n)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Ie.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:Ei(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let n;try{n=await await Gt(new Promise((s,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Ie.connection_stalled)}return n}rpcUnsubscribe(e,r,i){const n={method:Ei(i.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,r){this.setSubscription(e,Ls(wi({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,wi({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,i){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,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,wi({},r)),this.topicMap.set(r.topic,e),this.events.emit(Ye.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:i}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(Ye.deleted,Ls(wi({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Ye.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<r;i++){const n=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}}this.events.emit(Ye.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=L("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=>Ls(wi({},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 Kv(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}=L("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 $t(e+await this.getClientId())}}var xO=Object.defineProperty,Du=Object.getOwnPropertySymbols,CO=Object.prototype.hasOwnProperty,RO=Object.prototype.propertyIsEnumerable,_o=(t,e,r)=>e in t?xO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Su=(t,e)=>{for(var r in e||(e={}))CO.call(e,r)&&_o(t,r,e[r]);if(Du)for(var r of Du(e))RO.call(e,r)&&_o(t,r,e[r]);return t},Z=(t,e,r)=>_o(t,typeof e!="symbol"?e+"":e,r);class TO extends U_{constructor(e){super(e),Z(this,"protocol","wc"),Z(this,"version",2),Z(this,"core"),Z(this,"logger"),Z(this,"events",new Ut.EventEmitter),Z(this,"provider"),Z(this,"messages"),Z(this,"subscriber"),Z(this,"publisher"),Z(this,"name",cI),Z(this,"transportExplicitlyClosed",!1),Z(this,"initialized",!1),Z(this,"connectionAttemptInProgress",!1),Z(this,"relayUrl"),Z(this,"projectId"),Z(this,"packageName"),Z(this,"bundleId"),Z(this,"hasExperiencedNetworkDisruption",!1),Z(this,"pingTimeout"),Z(this,"heartBeatTimeout",N.toMiliseconds(N.THIRTY_SECONDS+N.FIVE_SECONDS)),Z(this,"reconnectTimeout"),Z(this,"connectPromise"),Z(this,"reconnectInProgress",!1),Z(this,"requestsInFlight",[]),Z(this,"connectTimeout",N.toMiliseconds(N.ONE_SECOND*15)),Z(this,"request",async r=>{var i,n;this.logger.debug("Publishing Request Payload");const s=r.id||cr().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - publishing...");const o=`${s}:${((n=r.params)==null?void 0:n.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}}),Z(this,"resetPingTimeout",()=>{Sn()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,i,n,s;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(s=(n=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null?void 0:n.terminate)==null||s.call(n)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),Z(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),Z(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(Ie.connect)}),Z(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Z(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(Ie.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Z(this,"registerProviderListeners",()=>{this.provider.on(tt.payload,this.onPayloadHandler),this.provider.on(tt.connect,this.onConnectHandler),this.provider.on(tt.disconnect,this.onDisconnectHandler),this.provider.on(tt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Fe(e.logger,this.name):Bi(Mn({level:e.logger||aI})),this.messages=new fO(this.logger,e.core),this.subscriber=new AO(this,this.logger),this.publisher=new vO(this,this.logger),this.relayUrl=e?.relayUrl||xd,this.projectId=e.projectId,Av()?this.packageName=vc():xv()&&(this.bundleId=vc()),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 Ve(this.logger)}get connected(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,i){this.isInitialized(),await this.publisher.publish(e,r,i),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:de.relay},vn.outbound)}async subscribe(e,r){var i,n,s;this.isInitialized(),(!(r!=null&&r.transportType)||r?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((i=r?.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(n=r?.internal)==null?void 0:n.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(Ye.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(Ye.created,u)}),new Promise(async(l,h)=>{a=await this.subscriber.subscribe(e,Su({internal:{throwOnFailedPublish:o}},r)).catch(d=>{o&&h(d)})||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 Gt(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,i)=>{await this.connect(e).then(r).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await cu())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((i,n)=>i.publishedAt-n.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n,"Error while processing batch message event: "+n?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const n=me(N.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,s)}this.events.emit(Ie.message,e),await this.recordMessageEvent(e,vn.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(i,n)=>{const s=()=>{n(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(tt.disconnect,s),await Gt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{n(o)}).finally(()=>{this.provider.off(tt.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(tt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(tt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const n=i;this.logger.warn({},n.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(i=>setTimeout(i,N.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,n,s;if(Sn())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(n=(i=this.provider)==null?void 0:i.connection)==null?void 0:n.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 ot(new cv(Lv({sdkVersion:yo,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:i,message:n}=e;await this.messages.set(i,n,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const n=this.messages.has(r,i);return n&&this.logger.warn(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Vo(e)){if(!e.method.endsWith(uI))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:o}=r.data,a={topic:i,message:n,publishedAt:s,transportType:de.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Su({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Vn(e)&&this.events.emit(Ie.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,vn.inbound),this.events.emit(Ie.message,e))}async acknowledgePayload(e){const r=Hn(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(tt.payload,this.onPayloadHandler),this.provider.off(tt.connect,this.onConnectHandler),this.provider.off(tt.disconnect,this.onDisconnectHandler),this.provider.off(tt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await cu();i_(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(i=>this.logger.error(i,i?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(mr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&o_())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Ie.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(lI)))))}isInitialized(){if(!this.initialized){const{message:e}=L("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 NO(){}function Pu(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 Au(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function xu(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const LO="[object RegExp]",jO="[object String]",BO="[object Number]",MO="[object Boolean]",Cu="[object Arguments]",FO="[object Symbol]",UO="[object Date]",qO="[object Map]",kO="[object Set]",zO="[object Array]",HO="[object Function]",KO="[object ArrayBuffer]",js="[object Object]",VO="[object Error]",WO="[object DataView]",GO="[object Uint8Array]",YO="[object Uint8ClampedArray]",JO="[object Uint16Array]",ZO="[object Uint32Array]",QO="[object BigUint64Array]",XO="[object Int8Array]",e2="[object Int16Array]",t2="[object Int32Array]",r2="[object BigInt64Array]",i2="[object Float32Array]",n2="[object Float64Array]";function s2(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function o2(t,e,r){return _i(t,e,void 0,void 0,void 0,void 0,r)}function _i(t,e,r,i,n,s,o){const a=o(t,e,r,i,n,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 Si(t,e,s,o)}return Si(t,e,s,o)}function Si(t,e,r,i){if(Object.is(t,e))return!0;let n=xu(t),s=xu(e);if(n===Cu&&(n=js),s===Cu&&(s=js),n!==s)return!1;switch(n){case jO:return t.toString()===e.toString();case BO:{const c=t.valueOf(),u=e.valueOf();return s2(c,u)}case MO:case UO:case FO:return Object.is(t.valueOf(),e.valueOf());case LO:return t.source===e.source&&t.flags===e.flags;case HO: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(n){case qO:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!_i(u,e.get(c),c,t,e,r,i))return!1;return!0}case kO:{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],d=u.findIndex(f=>_i(h,f,void 0,t,e,r,i));if(d===-1)return!1;u.splice(d,1)}return!0}case zO:case GO:case YO:case JO:case ZO:case QO:case XO:case e2:case t2:case r2:case i2:case n2:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!_i(t[c],e[c],c,t,e,r,i))return!1;return!0}case KO:return t.byteLength!==e.byteLength?!1:Si(new Uint8Array(t),new Uint8Array(e),r,i);case WO:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Si(new Uint8Array(t),new Uint8Array(e),r,i);case VO:return t.name===e.name&&t.message===e.message;case js:{if(!(Si(t.constructor,e.constructor,r,i)||Pu(t)&&Pu(e)))return!1;const c=[...Object.keys(t),...Au(t)],u=[...Object.keys(e),...Au(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const h=c[l],d=t[h];if(!Object.hasOwn(e,h))return!1;const f=e[h];if(!_i(d,f,h,t,e,r,i))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function a2(t,e){return o2(t,e,NO)}var c2=Object.defineProperty,Ru=Object.getOwnPropertySymbols,u2=Object.prototype.hasOwnProperty,l2=Object.prototype.propertyIsEnumerable,Io=(t,e,r)=>e in t?c2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tu=(t,e)=>{for(var r in e||(e={}))u2.call(e,r)&&Io(t,r,e[r]);if(Ru)for(var r of Ru(e))l2.call(e,r)&&Io(t,r,e[r]);return t},qe=(t,e,r)=>Io(t,typeof e!="symbol"?e+"":e,r);class br extends q_{constructor(e,r,i,n=St,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,qe(this,"map",new Map),qe(this,"version",hI),qe(this,"cached",[]),qe(this,"initialized",!1),qe(this,"getKey"),qe(this,"storagePrefix",St),qe(this,"recentlyDeleted",[]),qe(this,"recentlyDeletedLimit",200),qe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Le(o)?this.map.set(this.getKey(o),o):NE(o)?this.map.set(o.id,o):LE(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),qe(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())}),qe(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),qe(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>a2(a[c],o[c]))):this.values)),qe(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=Tu(Tu({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),qe(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=Fe(r,this.name),this.storagePrefix=n,this.getKey=s}get context(){return Ve(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:n}=L("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:i}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}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}=L("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}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var h2=Object.defineProperty,d2=(t,e,r)=>e in t?h2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,V=(t,e,r)=>d2(t,typeof e!="symbol"?e+"":e,r);class p2{constructor(e,r){this.core=e,this.logger=r,V(this,"name",gI),V(this,"version",yI),V(this,"events",new Yo),V(this,"pairings"),V(this,"initialized",!1),V(this,"storagePrefix",St),V(this,"ignoredPayloadTypes",[Mt]),V(this,"registeredMethods",[]),V(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),V(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),V(this,"create",async i=>{this.isInitialized();const n=fo(),s=await this.core.crypto.setSymKey(n),o=me(N.FIVE_MINUTES),a={protocol:Ad},c={topic:s,expiry:o,relay:a,active:!1,methods:i?.methods},u=Xc({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:a,expiryTimestamp:o,methods:i?.methods});return this.events.emit(or.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:i?.transportType}),{topic:s,uri:u}}),V(this,"pair",async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i?.uri,trace:[vt.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=Qc(i.uri);n.props.properties.topic=s,n.addTrace(vt.pairing_uri_validation_success),n.addTrace(vt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),n.addTrace(vt.existing_pairing),l.active)throw n.setError(Nt.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(vt.pairing_not_expired)}const h=c||me(N.FIVE_MINUTES),d={topic:s,relay:a,expiry:h,active:!1,methods:u};this.core.expirer.set(s,h),await this.pairings.set(s,d),n.addTrace(vt.store_new_pairing),i.activatePairing&&await this.activate({topic:s}),this.events.emit(or.create,d),n.addTrace(vt.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),n.addTrace(vt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(Nt.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(f){throw n.setError(Nt.subscribe_pairing_topic_failure),f}return n.addTrace(vt.subscribe_pairing_topic_success),d}),V(this,"activate",async({topic:i})=>{this.isInitialized();const n=me(N.FIVE_MINUTES);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})}),V(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:n}=i;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=rr();this.events.once(X("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),V(this,"updateExpiry",async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})}),V(this,"updateMetadata",async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})}),V(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),V(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:n}=i;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",te("USER_DISCONNECTED")),await this.deletePairing(n))}),V(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:n,relay:s,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(n);return Xc({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),V(this,"sendRequest",async(i,n,s)=>{const o=Wt(n,s),a=await this.core.crypto.encode(i,o),c=yi[n].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),V(this,"sendResult",async(i,n,s)=>{const o=Hn(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,u=yi[c].res;await this.core.relayer.publish(n,a,u),await this.core.history.resolve(o)}),V(this,"sendError",async(i,n,s)=>{const o=Kn(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,u=yi[c]?yi[c].res:yi.unregistered_method.res;await this.core.relayer.publish(n,a,u),await this.core.history.resolve(o)}),V(this,"deletePairing",async(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,te("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])}),V(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(n=>Kt(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))}),V(this,"onRelayEventRequest",async i=>{const{topic:n,payload:s}=i;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(n,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(n,s);default:return await this.onUnknownRpcMethodRequest(n,s)}}),V(this,"onRelayEventResponse",async i=>{const{topic:n,payload:s}=i,o=(await this.core.history.get(n,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(n,s);default:return this.onUnknownRpcMethodResponse(o)}}),V(this,"onPairingPingRequest",async(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(or.ping,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),V(this,"onPairingPingResponse",(i,n)=>{const{id:s}=n;setTimeout(()=>{_t(n)?this.events.emit(X("pairing_ping",s),{}):nt(n)&&this.events.emit(X("pairing_ping",s),{error:n.error})},500)}),V(this,"onPairingDeleteRequest",async(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(or.delete,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),V(this,"onUnknownRpcMethodRequest",async(i,n)=>{const{id:s,method:o}=n;try{if(this.registeredMethods.includes(o))return;const a=te("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,i,a),this.logger.error(a)}catch(a){await this.sendError(s,i,a),this.logger.error(a)}}),V(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(te("WC_METHOD_UNSUPPORTED",i))}),V(this,"isValidPair",(i,n)=>{var s;if(!ze(i)){const{message:a}=L("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(Nt.malformed_pairing_uri),new Error(a)}if(!TE(i.uri)){const{message:a}=L("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(Nt.malformed_pairing_uri),new Error(a)}const o=Qc(i?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=L("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(Nt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=L("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(Nt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&N.toMiliseconds(o?.expiryTimestamp)<Date.now()){n.setError(Nt.pairing_expired);const{message:a}=L("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),V(this,"isValidPing",async i=>{if(!ze(i)){const{message:s}=L("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),V(this,"isValidDisconnect",async i=>{if(!ze(i)){const{message:s}=L("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),V(this,"isValidPairingTopic",async i=>{if(!ye(i,!1)){const{message:n}=L("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=L("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(Kt(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=L("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}}),this.core=e,this.logger=Fe(r,this.name),this.pairings=new br(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Ve(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Ie.message,async e=>{const{topic:r,message:i,transportType:n}=e;if(this.pairings.keys.includes(r)&&n!==de.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const s=await this.core.crypto.decode(r,i);Vo(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):Vn(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,i)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(it.expired,async e=>{const{topic:r}=Kh(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(or.expire,{topic:r}))})}}var f2=Object.defineProperty,g2=(t,e,r)=>e in t?f2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ae=(t,e,r)=>g2(t,typeof e!="symbol"?e+"":e,r);class y2 extends B_{constructor(e,r){super(e,r),this.core=e,this.logger=r,Ae(this,"records",new Map),Ae(this,"events",new Ut.EventEmitter),Ae(this,"name",mI),Ae(this,"version",wI),Ae(this,"cached",[]),Ae(this,"initialized",!1),Ae(this,"storagePrefix",St),Ae(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ae(this,"set",(i,n,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:n,chainId:s}),this.records.has(n.id))return;const o={id:n.id,topic:i,request:{method:n.method,params:n.params||null},chainId:s,expiry:me(N.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(ut.created,o)}),Ae(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const n=await this.getRecord(i.id);typeof n.response>"u"&&(n.response=nt(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(ut.updated,n))}),Ae(this,"get",async(i,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:n}),await this.getRecord(n))),Ae(this,"delete",(i,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(s=>{if(s.topic===i){if(typeof n<"u"&&s.id!==n)return;this.records.delete(s.id),this.events.emit(ut.deleted,s)}}),this.persist()}),Ae(this,"exists",async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1)),Ae(this,"on",(i,n)=>{this.events.on(i,n)}),Ae(this,"once",(i,n)=>{this.events.once(i,n)}),Ae(this,"off",(i,n)=>{this.events.off(i,n)}),Ae(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=Fe(r,this.name)}get context(){return Ve(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 i={topic:r.topic,request:Wt(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:i}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(ut.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=L("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(ut.created,e=>{const r=ut.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ut.updated,e=>{const r=ut.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ut.deleted,e=>{const r=ut.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(mr.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(ut.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var m2=Object.defineProperty,w2=(t,e,r)=>e in t?m2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ne=(t,e,r)=>w2(t,typeof e!="symbol"?e+"":e,r);class b2 extends z_{constructor(e,r){super(e,r),this.core=e,this.logger=r,Ne(this,"expirations",new Map),Ne(this,"events",new Ut.EventEmitter),Ne(this,"name",bI),Ne(this,"version",vI),Ne(this,"cached",[]),Ne(this,"initialized",!1),Ne(this,"storagePrefix",St),Ne(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ne(this,"has",i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}}),Ne(this,"set",(i,n)=>{this.isInitialized();const s=this.formatTarget(i),o={target:s,expiry:n};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(it.created,{target:s,expiration:o})}),Ne(this,"get",i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)}),Ne(this,"del",i=>{if(this.isInitialized(),this.has(i)){const n=this.formatTarget(i),s=this.getExpiration(n);this.expirations.delete(n),this.events.emit(it.deleted,{target:n,expiration:s})}}),Ne(this,"on",(i,n)=>{this.events.on(i,n)}),Ne(this,"once",(i,n)=>{this.events.once(i,n)}),Ne(this,"off",(i,n)=>{this.events.off(i,n)}),Ne(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=Fe(r,this.name)}get context(){return Ve(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 jv(e);if(typeof e=="number")return Bv(e);const{message:r}=L("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(it.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=L("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:i}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;N.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(it.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(mr.pulse,()=>this.checkExpirations()),this.events.on(it.created,e=>{const r=it.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(it.expired,e=>{const r=it.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(it.deleted,e=>{const r=it.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var v2=Object.defineProperty,E2=(t,e,r)=>e in t?v2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ge=(t,e,r)=>E2(t,typeof e!="symbol"?e+"":e,r);class _2 extends H_{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,ge(this,"name",EI),ge(this,"abortController"),ge(this,"isDevEnv"),ge(this,"verifyUrlV3",II),ge(this,"storagePrefix",St),ge(this,"version",Pd),ge(this,"publicKey"),ge(this,"fetchPromise"),ge(this,"init",async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&N.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ge(this,"register",async n=>{if(!ai()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=n,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const u=dr(),l=this.startAbortTimer(N.ONE_SECOND*5),h=await new Promise((d,f)=>{const p=()=>{window.removeEventListener("message",w),u.body.removeChild(y),f("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const y=u.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",p,{signal:this.abortController.signal});const w=v=>{if(v.data&&typeof v.data=="string")try{const b=JSON.parse(v.data);if(b.type==="verify_attestation"){if(Qs(b.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(y),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",w),d(b.attestation===null?"":b.attestation)}}catch(b){this.logger.warn(b)}};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""}),ge(this,"resolve",async n=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=n;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Qs(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(n?.verifyUrl);return this.fetchAttestation(o,c)}),ge(this,"fetchAttestation",async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const o=this.startAbortTimer(N.ONE_SECOND*5),a=await fetch(`${s}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),ge(this,"getVerifyUrl",n=>{let s=n||Di;return $I.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Di}`),s=Di),s}),ge(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(N.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(n),await s.json()}catch(n){this.logger.warn(n)}}),ge(this,"persistPublicKey",async n=>{this.logger.debug("persisting public key to local storage",n),await this.store.setItem(this.storeKey,n),this.publicKey=n}),ge(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ge(this,"isValidJwtAttestation",async n=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(n,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(n,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),ge(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ge(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 n=await this.fetchPromise;return this.fetchPromise=void 0,n}),ge(this,"validateAttestation",(n,s)=>{const o=dE(n,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=Fe(r,this.name),this.abortController=new AbortController,this.isDevEnv=Jo(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Ve(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),N.toMiliseconds(e))}}var I2=Object.defineProperty,$2=(t,e,r)=>e in t?I2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nu=(t,e,r)=>$2(t,typeof e!="symbol"?e+"":e,r);class O2 extends K_{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,Nu(this,"context",OI),Nu(this,"registerDeviceToken",async i=>{const{clientId:n,token:s,notificationType:o,enableEncrypted:a=!1}=i,c=`${DI}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:o,token:s,always_raw:a})})}),this.logger=Fe(r,this.context)}}var D2=Object.defineProperty,Lu=Object.getOwnPropertySymbols,S2=Object.prototype.hasOwnProperty,P2=Object.prototype.propertyIsEnumerable,$o=(t,e,r)=>e in t?D2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bi=(t,e)=>{for(var r in e||(e={}))S2.call(e,r)&&$o(t,r,e[r]);if(Lu)for(var r of Lu(e))P2.call(e,r)&&$o(t,r,e[r]);return t},be=(t,e,r)=>$o(t,typeof e!="symbol"?e+"":e,r);class A2 extends V_{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,be(this,"context",PI),be(this,"storagePrefix",St),be(this,"storageVersion",SI),be(this,"events",new Map),be(this,"shouldPersist",!1),be(this,"init",async()=>{if(!Jo())try{const n={eventId:_c(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:zh(this.core.relayer.protocol,this.core.relayer.version,yo)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}}),be(this,"createEvent",n=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=n,u=_c(),l=this.core.projectId||"",h=Date.now(),d=bi({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,d),this.shouldPersist=!0),d}),be(this,"getEvent",n=>{const{eventId:s,topic:o}=n;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return bi(bi({},a),this.setMethods(a.eventId))}),be(this,"deleteEvent",n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0}),be(this,"setEventListeners",()=>{this.core.heartbeat.on(mr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{N.fromMiliseconds(Date.now())-N.fromMiliseconds(n.timestamp)>AI&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})}),be(this,"setMethods",n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)})),be(this,"addTrace",(n,s)=>{const o=this.events.get(n);o&&(o.props.properties.trace.push(s),this.events.set(n,o),this.shouldPersist=!0)}),be(this,"setError",(n,s)=>{const o=this.events.get(n);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(n,o),this.shouldPersist=!0)}),be(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),be(this,"restore",async()=>{try{const n=await this.core.storage.getItem(this.storageKey)||[];if(!n.length)return;n.forEach(s=>{this.events.set(s.eventId,bi(bi({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}}),be(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[s,o]of this.events)o.props.type&&n.push(o);if(n.length!==0)try{if((await this.sendEvent(n)).ok)for(const s of n)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),be(this,"sendEvent",async n=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${xI}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${yo}${s}`,{method:"POST",body:JSON.stringify(n)})}),be(this,"getAppDomain",()=>kh().url),this.logger=Fe(r,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var x2=Object.defineProperty,ju=Object.getOwnPropertySymbols,C2=Object.prototype.hasOwnProperty,R2=Object.prototype.propertyIsEnumerable,Oo=(t,e,r)=>e in t?x2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Bu=(t,e)=>{for(var r in e||(e={}))C2.call(e,r)&&Oo(t,r,e[r]);if(ju)for(var r of ju(e))R2.call(e,r)&&Oo(t,r,e[r]);return t},le=(t,e,r)=>Oo(t,typeof e!="symbol"?e+"":e,r);let T2=class kd extends T_{constructor(e){var r;super(e),le(this,"protocol",Sd),le(this,"version",Pd),le(this,"name",Cn),le(this,"relayUrl"),le(this,"projectId"),le(this,"customStoragePrefix"),le(this,"events",new Ut.EventEmitter),le(this,"logger"),le(this,"heartbeat"),le(this,"relayer"),le(this,"crypto"),le(this,"storage"),le(this,"history"),le(this,"expirer"),le(this,"pairing"),le(this,"verify"),le(this,"echoClient"),le(this,"linkModeSupportedApps"),le(this,"eventClient"),le(this,"initialized",!1),le(this,"logChunkController"),le(this,"on",(a,c)=>this.events.on(a,c)),le(this,"once",(a,c)=>this.events.once(a,c)),le(this,"off",(a,c)=>this.events.off(a,c)),le(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),le(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:de.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const i=this.getGlobalCore(e?.customStoragePrefix);if(i)try{return this.customStoragePrefix=i.customStoragePrefix,this.logger=i.logger,this.heartbeat=i.heartbeat,this.crypto=i.crypto,this.history=i.history,this.expirer=i.expirer,this.storage=i.storage,this.relayer=i.relayer,this.pairing=i.pairing,this.verify=i.verify,this.echoClient=i.echoClient,this.linkModeSupportedApps=i.linkModeSupportedApps,this.eventClient=i.eventClient,this.initialized=i.initialized,this.logChunkController=i.logChunkController,i}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||xd,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const n=Mn({level:typeof e?.logger=="string"&&e.logger?e.logger:Q_.logger,name:Cn}),{logger:s,chunkLoggerController:o}=Wf({opts:n,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=Fe(s,this.name),this.heartbeat=new df,this.crypto=new oO(this,this.logger,e?.keychain),this.history=new y2(this,this.logger),this.expirer=new b2(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new x_(Bu(Bu({},X_),e?.storageOptions)),this.relayer=new TO({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new p2(this,this.logger),this.verify=new _2(this,this.logger,this.storage),this.echoClient=new O2(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new A2(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new kd(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(dI,i),r}get context(){return Ve(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(yu,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(yu)||[],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}`,i=`${r}_count`;return globalThis[i]=(globalThis[i]||0)+1,globalThis[i]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[i]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[i]=e}catch(i){console.warn("Failed to set global WalletConnect core",i)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&Z_.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const N2=T2,zd="wc",Hd=2,Kd="client",na=`${zd}@${Hd}:${Kd}:`,Bs={name:Kd,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Mu="WALLETCONNECT_DEEPLINK_CHOICE",L2="proposal",Fu="Proposal expired",j2="session",Ar=N.SEVEN_DAYS,B2="engine",ve={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}}},Ms={min:N.FIVE_MINUTES,max:N.SEVEN_DAYS},bt={idle:"IDLE",active:"ACTIVE"},Uu={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},M2="request",F2=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],U2="wc",q2="auth",k2="authKeys",z2="pairingTopics",H2="requests",rs=`${U2}@${1.5}:${q2}:`,En=`${rs}:PUB_KEY`;var K2=Object.defineProperty,V2=Object.defineProperties,W2=Object.getOwnPropertyDescriptors,qu=Object.getOwnPropertySymbols,G2=Object.prototype.hasOwnProperty,Y2=Object.prototype.propertyIsEnumerable,Do=(t,e,r)=>e in t?K2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ce=(t,e)=>{for(var r in e||(e={}))G2.call(e,r)&&Do(t,r,e[r]);if(qu)for(var r of qu(e))Y2.call(e,r)&&Do(t,r,e[r]);return t},Be=(t,e)=>V2(t,W2(e)),T=(t,e,r)=>Do(t,typeof e!="symbol"?e+"":e,r);class J2 extends J_{constructor(e){super(e),T(this,"name",B2),T(this,"events",new Yo),T(this,"initialized",!1),T(this,"requestQueue",{state:bt.idle,queue:[]}),T(this,"sessionRequestQueue",{state:bt.idle,queue:[]}),T(this,"requestQueueDelay",N.ONE_SECOND),T(this,"expectedPairingMethodMap",new Map),T(this,"recentlyDeletedMap",new Map),T(this,"recentlyDeletedLimit",200),T(this,"relayMessageCache",[]),T(this,"pendingSessions",new Map),T(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(ve)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},N.toMiliseconds(this.requestQueueDelay)))}),T(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Be(ce({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(i),i.optionalNamespaces=PE(i.requiredNamespaces,i.optionalNamespaces),i.requiredNamespaces={};const{pairingTopic:n,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=i;let l=n,h,d=!1;try{if(l){const P=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."),d=P.active}}catch(P){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),P}if(!l||!d){const{topic:P,uri:S}=await this.client.core.pairing.create();l=P,h=S}if(!l){const{message:P}=L("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(P)}const f=await this.client.core.crypto.generateKeyPair(),p=ve.wc_sessionPropose.req.ttl||N.FIVE_MINUTES,y=me(p),w=Be(ce(ce({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:Ad}],proposer:{publicKey:f,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Et()}),v=X("session_connect",w.id),{reject:b,resolve:E,done:$}=rr(p,Fu),A=({id:P})=>{P===w.id&&(this.client.events.off("proposal_expire",A),this.pendingSessions.delete(w.id),this.events.emit(v,{error:{message:Fu,code:0}}))};return this.client.events.on("proposal_expire",A),this.events.once(v,({error:P,session:S})=>{this.client.events.off("proposal_expire",A),P?b(P):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:$}}),T(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(i){throw this.client.logger.error("pair() failed"),i}}),T(this,"approve",async r=>{var i,n,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=r?.id)==null?void 0:i.toString(),trace:[lt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(O){throw o.setError(er.no_internet_connection),O}try{await this.isValidProposalId(r?.id)}catch(O){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(er.proposal_not_found),O}try{await this.isValidApprove(r)}catch(O){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(er.session_approve_namespace_validation_failure),O}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:d}=r,f=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:p,proposer:y,requiredNamespaces:w,optionalNamespaces:v}=f;let b=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:p});b||(b=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:lt.session_approve_started,properties:{topic:p,trace:[lt.session_approve_started,lt.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),$=y.publicKey,A=await this.client.core.crypto.generateSharedKey(E,$),P=ce(ce(ce({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:E,metadata:this.client.metadata},expiry:me(Ar)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),S=de.relay;b.addTrace(lt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(A,{transportType:S})}catch(O){throw b.setError(er.subscribe_session_topic_failure),O}b.addTrace(lt.subscribe_session_topic_success);const C=Be(ce({},P),{topic:A,requiredNamespaces:w,optionalNamespaces:v,pairingTopic:p,acknowledged:!1,self:P.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:E,transportType:de.relay});await this.client.session.set(A,C),b.addTrace(lt.store_session);try{b.addTrace(lt.publishing_session_settle),await this.sendRequest({topic:A,method:"wc_sessionSettle",params:P,throwOnFailedPublish:!0}).catch(O=>{throw b?.setError(er.session_settle_publish_failure),O}),b.addTrace(lt.session_settle_publish_success),b.addTrace(lt.publishing_session_approve),await this.sendResult({id:a,topic:p,result:{relay:{protocol:c??"irn"},responderPublicKey:E},throwOnFailedPublish:!0}).catch(O=>{throw b?.setError(er.session_approve_publish_failure),O}),b.addTrace(lt.session_approve_publish_success)}catch(O){throw this.client.logger.error(O),this.client.session.delete(A,te("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(A),O}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:y.metadata}),await this.client.proposal.delete(a,te("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:p}),await this.setExpiry(A,me(Ar)),{topic:A,acknowledged:()=>Promise.resolve(this.client.session.get(A))}}),T(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:i,reason:n}=r;let s;try{s=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}s&&(await this.sendError({id:i,topic:s,error:n,rpcOpts:ve.wc_sessionPropose.reject}),await this.client.proposal.delete(i,te("USER_DISCONNECTED")))}),T(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:i,namespaces:n}=r,{done:s,resolve:o,reject:a}=rr(),c=Et(),u=cr().toString(),l=this.client.session.get(i).namespaces;return this.events.once(X("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(h=>{this.client.logger.error(h),this.client.session.update(i,{namespaces:l}),a(h)}),{acknowledged:s}}),T(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:i}=r,n=Et(),{done:s,resolve:o,reject:a}=rr();return this.events.once(X("session_extend",n),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,me(Ar)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),T(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(v){throw this.client.logger.error("request() -> isValidRequest() failed"),v}const{chainId:i,request:n,topic:s,expiry:o=ve.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===de.relay&&await this.confirmOnlineStateOrThrow();const c=Et(),u=cr().toString(),{done:l,resolve:h,reject:d}=rr(o,"Request expired. Please try again.");this.events.once(X("session_request",c),({error:v,result:b})=>{v?d(v):h(b)});const f="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:f,params:{request:Be(ce({},n),{expiryTimestamp:me(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(v=>d(v)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),await l();const y={request:Be(ce({},n),{expiryTimestamp:me(o)}),chainId:i},w=this.shouldSetTVF(f,y);return await Promise.all([new Promise(async v=>{await this.sendRequest(ce({clientRpcId:c,relayRpcId:u,topic:s,method:f,params:y,expiry:o,throwOnFailedPublish:!0},w&&{tvf:this.getTVFParams(c,y)})).catch(b=>d(b)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),v()}),new Promise(async v=>{var b;if(!((b=a.sessionConfig)!=null&&b.disableDeepLink)){const E=await qv(this.client.core.storage,Mu);await Mv({id:c,topic:s,wcDeepLink:E})}v()}),l()]).then(v=>v[2])}),T(this,"respond",async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:i,response:n}=r,{id:s}=n,o=this.client.session.get(i);o.transportType===de.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);_t(n)?await this.sendResult({id:s,topic:i,result:n.result,throwOnFailedPublish:!0,appLink:a}):nt(n)&&await this.sendError({id:s,topic:i,error:n.error,appLink:a}),this.cleanupAfterResponse(r)}),T(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:i}=r;if(this.client.session.keys.includes(i)){const n=Et(),s=cr().toString(),{done:o,resolve:a,reject:c}=rr();this.events.once(X("session_ping",n),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),T(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,o=cr().toString(),a=Et();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),T(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:i}=r;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:te("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=L("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}}),T(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>CE(i,r)))),T(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),T(this,"authenticate",async(r,i)=>{var n;this.isInitialized(),this.isValidAuthenticate(r);const s=i&&this.client.core.linkModeSupportedApps.includes(i)&&((n=this.client.metadata.redirect)==null?void 0:n.linkMode),o=s?de.link_mode:de.relay;o===de.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:h,type:d,exp:f,nbf:p,methods:y=[],expiry:w}=r,v=[...r.resources||[]],{topic:b,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:b,uri:E}});const $=await this.client.core.crypto.generateKeyPair(),A=mn($);if(await Promise.all([this.client.auth.authKeys.set(En,{responseTopic:A,publicKey:$}),this.client.auth.pairingTopics.set(A,{topic:A,pairingTopic:b})]),await this.client.core.relayer.subscribe(A,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${b}`),y.length>0){const{namespace:I}=Jr(a[0]);let x=T0(I,"request",y);yn(v)&&(x=L0(x,v.pop())),v.push(x)}const P=w&&w>ve.wc_sessionAuthenticate.req.ttl?w:ve.wc_sessionAuthenticate.req.ttl,S={authPayload:{type:d??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:h,iat:new Date().toISOString(),exp:f,nbf:p,resources:v},requester:{publicKey:$,metadata:this.client.metadata},expiryTimestamp:me(P)},C={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},O={requiredNamespaces:{},optionalNamespaces:C,relays:[{protocol:"irn"}],pairingTopic:b,proposer:{publicKey:$,metadata:this.client.metadata},expiryTimestamp:me(ve.wc_sessionPropose.req.ttl),id:Et()},{done:q,resolve:B,reject:j}=rr(P,"Request expired"),k=Et(),R=X("session_connect",O.id),g=X("session_request",k),m=async({error:I,session:x})=>{this.events.off(g,_),I?j(I):x&&B({session:x})},_=async I=>{var x,M,U;if(await this.deletePendingAuthRequest(k,{message:"fulfilled",code:0}),I.error){const Y=te("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return I.error.code===Y.code?void 0:(this.events.off(R,m),j(I.error.message))}await this.deleteProposal(O.id),this.events.off(R,m);const{cacaos:z,responder:F}=I.result,H=[],G=[];for(const Y of z){await xc({cacao:Y,projectId:this.client.core.projectId})||(this.client.logger.error(Y,"Signature verification failed"),j(te("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Te}=Y,De=yn(Te.resources),je=[no(Te.iss)],et=Pn(Te.iss);if(De){const Pt=Cc(De),Er=Rc(De);H.push(...Pt),je.push(...Er)}for(const Pt of je)G.push(`${Pt}:${et}`)}const ue=await this.client.core.crypto.generateSharedKey($,F.publicKey);let ee;H.length>0&&(ee={topic:ue,acknowledged:!0,self:{publicKey:$,metadata:this.client.metadata},peer:F,controller:F.publicKey,expiry:me(Ar),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:b,namespaces:iu([...new Set(H)],[...new Set(G)]),transportType:o},await this.client.core.relayer.subscribe(ue,{transportType:o}),await this.client.session.set(ue,ee),b&&await this.client.core.pairing.updateMetadata({topic:b,metadata:F.metadata}),ee=this.client.session.get(ue)),(x=this.client.metadata.redirect)!=null&&x.linkMode&&(M=F.metadata.redirect)!=null&&M.linkMode&&(U=F.metadata.redirect)!=null&&U.universal&&i&&(this.client.core.addLinkModeSupportedApp(F.metadata.redirect.universal),this.client.session.update(ue,{transportType:de.link_mode})),B({auths:z,session:ee})};this.events.once(R,m),this.events.once(g,_);let D;try{if(s){const I=Wt("wc_sessionAuthenticate",S,k);this.client.core.history.set(b,I);const x=await this.client.core.crypto.encode("",I,{type:Vi,encoding:Vt});D=rn(i,b,x)}else await Promise.all([this.sendRequest({topic:b,method:"wc_sessionAuthenticate",params:S,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:k}),this.sendRequest({topic:b,method:"wc_sessionPropose",params:O,expiry:ve.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:O.id})])}catch(I){throw this.events.off(R,m),this.events.off(g,_),I}return await this.setProposal(O.id,O),await this.setAuthRequest(k,{request:Be(ce({},S),{verifyContext:{}}),pairingTopic:b,transportType:o}),{uri:D??E,response:q}}),T(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[tr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw s.setError(mi.no_internet_connection),w}const o=this.getPendingAuthRequest(i);if(!o)throw s.setError(mi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||de.relay;a===de.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=mn(c),h={type:Mt,receiverPublicKey:c,senderPublicKey:u},d=[],f=[];for(const w of n){if(!await xc({cacao:w,projectId:this.client.core.projectId})){s.setError(mi.invalid_cacao);const A=te("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:l,error:A,encodeOpts:h}),new Error(A.message)}s.addTrace(tr.cacaos_verified);const{p:v}=w,b=yn(v.resources),E=[no(v.iss)],$=Pn(v.iss);if(b){const A=Cc(b),P=Rc(b);d.push(...A),E.push(...P)}for(const A of E)f.push(`${A}:${$}`)}const p=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(tr.create_authenticated_session_topic);let y;if(d?.length>0){y={topic:p,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:me(Ar),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:iu([...new Set(d)],[...new Set(f)]),transportType:a},s.addTrace(tr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(w){throw s.setError(mi.subscribe_authenticated_session_topic_failure),w}s.addTrace(tr.subscribe_authenticated_session_topic_success),await this.client.session.set(p,y),s.addTrace(tr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(tr.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:i,result:{cacaos:n,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw s.setError(mi.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:y}}),T(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:i,reason:n}=r,s=this.getPendingAuthRequest(i);if(!s)throw new Error(`Could not find pending auth request with id ${i}`);s.transportType===de.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=mn(o),u={type:Mt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:n,encodeOpts:u,rpcOpts:ve.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,te("USER_DISCONNECTED"))}),T(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:n}=r;return ed(i,n)}),T(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)}),T(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.pairingTopic),n=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!==i.topic});if(n.length===0)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),T(this,"deleteSession",async r=>{var i;const{topic:n,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,te("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),s||this.client.core.expirer.del(n),this.client.core.storage.removeItem(Mu).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===n&&this.deletePendingSessionRequest(u.id,te("USER_DISCONNECTED"))}),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=bt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:n})}),T(this,"deleteProposal",async(r,i)=>{if(i)try{const n=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:n.pairingTopic})?.setError(er.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,te("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),T(this,"deletePendingSessionRequest",async(r,i,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),n&&(this.sessionRequestQueue.state=bt.idle,this.client.events.emit("session_request_expire",{id:r}))}),T(this,"deletePendingAuthRequest",async(r,i,n=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)])}),T(this,"setExpiry",async(r,i)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,i),await this.client.session.update(r,{expiry:i}))}),T(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,me(ve.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),T(this,"setAuthRequest",async(r,i)=>{const{request:n,pairingTopic:s,transportType:o=de.relay}=i;this.client.core.expirer.set(r,n.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:r,pairingTopic:s,verifyContext:n.verifyContext,transportType:o})}),T(this,"setPendingSessionRequest",async r=>{const{id:i,topic:n,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||me(ve.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:n,params:s,verifyContext:o})}),T(this,"sendRequest",async r=>{const{topic:i,method:n,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:h}=r,d=Wt(n,s,c);let f;const p=!!l;try{const v=p?Vt:pt;f=await this.client.core.crypto.encode(i,d,{encoding:v})}catch(v){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),v}let y;if(F2.includes(n)){const v=$t(JSON.stringify(d)),b=$t(f);y=await this.client.core.verify.register({id:b,decryptedId:v})}const w=ve[n].req;if(w.attestation=y,o&&(w.ttl=o),a&&(w.id=a),this.client.core.history.set(i,d),p){const v=rn(l,i,f);await global.Linking.openURL(v,this.client.name)}else{const v=ve[n].req;o&&(v.ttl=o),a&&(v.id=a),v.tvf=Be(ce({},h),{correlationId:d.id}),u?(v.internal=Be(ce({},v.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,f,v)):this.client.core.relayer.publish(i,f,v).catch(b=>this.client.logger.error(b))}return d.id}),T(this,"sendResult",async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,u=Hn(i,s);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=h?Vt:pt;l=await this.client.core.crypto.encode(n,u,Be(ce({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),p}let d,f;try{d=await this.client.core.history.get(n,i);const p=d.request;try{this.shouldSetTVF(p.method,p.params)&&(f=this.getTVFParams(i,p.params,s))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),p}if(h){const p=rn(c,n,l);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,y=ve[p].res;y.tvf=Be(ce({},f),{correlationId:i}),o?(y.internal=Be(ce({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,l,y)):this.client.core.relayer.publish(n,l,y).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(u)}),T(this,"sendError",async r=>{const{id:i,topic:n,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,u=Kn(i,s);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=h?Vt:pt;l=await this.client.core.crypto.encode(n,u,Be(ce({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),f}let d;try{d=await this.client.core.history.get(n,i)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),f}if(h){const f=rn(c,n,l);await global.Linking.openURL(f,this.client.name)}else{const f=d.request.method,p=a||ve[f].res;this.client.core.relayer.publish(n,l,p)}await this.client.core.history.resolve(u)}),T(this,"cleanup",async()=>{const r=[],i=[];this.client.session.getAll().forEach(n=>{let s=!1;Kt(n.expiry)&&(s=!0),this.client.core.crypto.keychain.has(n.topic)||(s=!0),s&&r.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{Kt(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...r.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])}),T(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),T(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),T(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===bt.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=bt.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=bt.idle}),T(this,"processRequest",async r=>{const{topic:i,payload:n,attestation:s,transportType:o,encryptedId:a}=r,c=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),T(this,"onRelayEventResponse",async r=>{const{topic:i,payload:n,transportType:s}=r,o=(await this.client.core.history.get(i,n.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n,s);case"wc_sessionSettle":return this.onSessionSettleResponse(i,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,n);case"wc_sessionExtend":return this.onSessionExtendResponse(i,n);case"wc_sessionPing":return this.onSessionPingResponse(i,n);case"wc_sessionRequest":return this.onSessionRequestResponse(i,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,n);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),T(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:n}=L("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)}),T(this,"shouldIgnorePairingRequest",r=>{const{topic:i,requestMethod:n}=r,s=this.expectedPairingMethodMap.get(i);return!s||s.includes(n)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),T(this,"onSessionProposeRequest",async r=>{const{topic:i,payload:n,attestation:s,encryptedId:o}=r,{params:a,id:c}=n;try{const u=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(Nt.proposal_listener_not_found)),this.isValidConnect(ce({},n.params));const l=a.expiryTimestamp||me(ve.wc_sessionPropose.req.ttl),h=ce({id:c,pairingTopic:i,expiryTimestamp:l},a);await this.setProposal(c,h);const d=await this.getVerifyContext({attestationId:s,hash:$t(JSON.stringify(n)),encryptedId:o,metadata:h.proposer.metadata});u?.addTrace(vt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:d})}catch(u){await this.sendError({id:c,topic:i,error:u,rpcOpts:ve.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),T(this,"onSessionProposeResponse",async(r,i,n)=>{const{id:s}=i;if(_t(i)){const{result:o}=i;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:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:r})}else if(nt(i)){await this.client.proposal.delete(s,te("USER_DISCONNECTED"));const o=X("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),T(this,"onSessionSettleRequest",async(r,i)=>{const{id:n,params:s}=i;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:d}=i.params,f=[...this.pendingSessions.values()].find(w=>w.sessionTopic===r);if(!f)return this.client.logger.error(`Pending session not found for topic ${r}`);const p=this.client.proposal.get(f.proposalId),y=Be(ce(ce(ce({topic:r,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:f.pairingTopic,requiredNamespaces:p.requiredNamespaces,optionalNamespaces:p.optionalNamespaces,controller:a.publicKey,self:{publicKey:f.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),{transportType:de.relay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:f.pairingTopic,metadata:y.peer.metadata}),this.client.events.emit("session_connect",{session:y}),this.events.emit(X("session_connect",f.proposalId),{session:y}),this.pendingSessions.delete(f.proposalId),this.deleteProposal(f.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:i.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),T(this,"onSessionSettleResponse",async(r,i)=>{const{id:n}=i;_t(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(X("session_approve",n),{})):nt(i)&&(await this.client.session.delete(r,te("USER_DISCONNECTED")),this.events.emit(X("session_approve",n),{error:i.error}))}),T(this,"onSessionUpdateRequest",async(r,i)=>{const{params:n,id:s}=i;try{const o=`${r}_session_update`,a=gi.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:te("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ce({topic:r},n));try{gi.set(o,s),await this.client.session.update(r,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(c){throw gi.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:n})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),T(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),T(this,"onSessionUpdateResponse",(r,i)=>{const{id:n}=i,s=X("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);_t(i)?this.events.emit(X("session_update",n),{}):nt(i)&&this.events.emit(X("session_update",n),{error:i.error})}),T(this,"onSessionExtendRequest",async(r,i)=>{const{id:n}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,me(Ar)),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),T(this,"onSessionExtendResponse",(r,i)=>{const{id:n}=i,s=X("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);_t(i)?this.events.emit(X("session_extend",n),{}):nt(i)&&this.events.emit(X("session_extend",n),{error:i.error})}),T(this,"onSessionPingRequest",async(r,i)=>{const{id:n}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),T(this,"onSessionPingResponse",(r,i)=>{const{id:n}=i,s=X("session_ping",n);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);_t(i)?this.events.emit(X("session_ping",n),{}):nt(i)&&this.events.emit(X("session_ping",n),{error:i.error})},500)}),T(this,"onSessionDeleteRequest",async(r,i)=>{const{id:n}=i;try{this.isValidDisconnect({topic:r,reason:i.params}),Promise.all([new Promise(s=>{this.client.core.relayer.once(Ie.publish,async()=>{s(await this.deleteSession({topic:r,id:n}))})}),this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:te("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),T(this,"onSessionRequest",async r=>{var i,n,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=r,{id:h,params:d}=a;try{await this.isValidRequest(ce({topic:o},d));const f=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:$t(JSON.stringify(Wt("wc_sessionRequest",d,h))),encryptedId:u,metadata:f.peer.metadata,transportType:l}),y={id:h,topic:o,params:d,verifyContext:p};await this.setPendingSessionRequest(y),l===de.link_mode&&(i=f.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((n=f.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(f){await this.sendError({id:h,topic:o,error:f}),this.client.logger.error(f)}}),T(this,"onSessionRequestResponse",(r,i)=>{const{id:n}=i,s=X("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);_t(i)?this.events.emit(X("session_request",n),{result:i.result}):nt(i)&&this.events.emit(X("session_request",n),{error:i.error})}),T(this,"onSessionEventRequest",async(r,i)=>{const{id:n,params:s}=i;try{const o=`${r}_session_event_${s.event.name}`,a=gi.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(ce({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),gi.set(o,n)}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),T(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),_t(i)?this.events.emit(X("session_request",n),{result:i.result}):nt(i)&&this.events.emit(X("session_request",n),{error:i.error})}),T(this,"onSessionAuthenticateRequest",async r=>{var i;const{topic:n,payload:s,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:u,authPayload:l,expiryTimestamp:h}=s.params,d=await this.getVerifyContext({attestationId:o,hash:$t(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),f={requester:u,pairingTopic:n,id:s.id,authPayload:l,verifyContext:d,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:f,pairingTopic:n,transportType:c}),c===de.link_mode&&(i=u.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:s.params,id:s.id,verifyContext:d})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(s.params.requester.metadata,c),f={type:Mt,receiverPublicKey:l,senderPublicKey:h};await this.sendError({id:s.id,topic:n,error:u,encodeOpts:f,rpcOpts:ve.wc_sessionAuthenticate.autoReject,appLink:d})}}),T(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),T(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=bt.idle,this.processSessionRequestQueue()},N.toMiliseconds(this.requestQueueDelay))}),T(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:i})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{const o=s.request.id,a=X("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(X("session_request",s.request.id),{error:i})})}),T(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===bt.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=bt.active,this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}}),T(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),T(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(n=>n.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:Wt("wc_sessionPropose",Be(ce({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id)})}),T(this,"isValidConnect",async r=>{if(!ze(r)){const{message:u}=L("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=r;if(Le(i)||await this.isValidPairingTopic(i),!zE(c)){const{message:u}=L("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!Le(n)&&Jt(n)!==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(n,"requiredNamespaces")}if(!Le(s)&&Jt(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),Le(o)||this.validateSessionProps(o,"sessionProperties"),!Le(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(n||{}).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)}`)}}),T(this,"validateNamespaces",(r,i)=>{const n=kE(r,"connect()",i);if(n)throw new Error(n.message)}),T(this,"isValidApprove",async r=>{if(!ze(r))throw new Error(L("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:n,relayProtocol:s,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),u=xs(n,"approve()");if(u)throw new Error(u.message);const l=ou(c.requiredNamespaces,n,"approve()");if(l)throw new Error(l.message);if(!ye(s,!0)){const{message:h}=L("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(Le(o)||this.validateSessionProps(o,"sessionProperties"),!Le(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(n));if(!Object.keys(a).every(d=>h.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),T(this,"isValidReject",async r=>{if(!ze(r)){const{message:s}=L("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:i,reason:n}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!KE(n)){const{message:s}=L("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}}),T(this,"isValidSessionSettleRequest",r=>{if(!ze(r)){const{message:u}=L("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}const{relay:i,controller:n,namespaces:s,expiry:o}=r;if(!Dd(i)){const{message:u}=L("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=jE(n,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=xs(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Kt(o)){const{message:u}=L("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),T(this,"isValidUpdate",async r=>{if(!ze(r)){const{message:c}=L("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:i,namespaces:n}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),o=xs(n,"update()");if(o)throw new Error(o.message);const a=ou(s.requiredNamespaces,n,"update()");if(a)throw new Error(a.message)}),T(this,"isValidExtend",async r=>{if(!ze(r)){const{message:n}=L("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(n)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),T(this,"isValidRequest",async r=>{if(!ze(r)){const{message:c}=L("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:i,request:n,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!su(a,s)){const{message:c}=L("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!VE(n)){const{message:c}=L("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(c)}if(!YE(a,s,n.method)){const{message:c}=L("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(c)}if(o&&!XE(o,Ms)){const{message:c}=L("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Ms.min} and ${Ms.max}`);throw new Error(c)}}),T(this,"isValidRespond",async r=>{var i;if(!ze(r)){const{message:o}=L("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:n,response:s}=r;try{await this.isValidSessionTopic(n)}catch(o){throw(i=r?.response)!=null&&i.id&&this.cleanupAfterResponse(r),o}if(!WE(s)){const{message:o}=L("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),T(this,"isValidPing",async r=>{if(!ze(r)){const{message:n}=L("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),T(this,"isValidEmit",async r=>{if(!ze(r)){const{message:a}=L("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:i,event:n,chainId:s}=r;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!su(o,s)){const{message:a}=L("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!GE(n)){const{message:a}=L("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}if(!JE(o,s,n.name)){const{message:a}=L("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}}),T(this,"isValidDisconnect",async r=>{if(!ze(r)){const{message:n}=L("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),T(this,"isValidAuthenticate",r=>{const{chains:i,uri:n,domain:s,nonce:o}=r;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!ye(n,!1))throw new Error("uri is required parameter");if(!ye(s,!1))throw new Error("domain is required parameter");if(!ye(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>Jr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Jr(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),T(this,"getVerifyContext",async r=>{const{attestationId:i,hash:n,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||Di,validation:"UNKNOWN",origin:o.url||""}};try{if(a===de.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:i,hash:n,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}),T(this,"validateSessionProps",(r,i)=>{Object.values(r).forEach((n,s)=>{if(n==null){const{message:o}=L("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${n} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),T(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),T(this,"addToRecentlyDeleted",(r,i)=>{if(this.recentlyDeletedMap.set(r,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let n=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(n++>=s)break;this.recentlyDeletedMap.delete(o)}}}),T(this,"checkRecentlyDeleted",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:n}=L("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(n)}}),T(this,"isLinkModeEnabled",(r,i)=>{var n,s,o,a,c,u,l,h,d;return!r||i!==de.link_mode?!1:((s=(n=this.client.metadata)==null?void 0:n.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)!==""&&((d=r?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),T(this,"getAppLinkIfEnabled",(r,i)=>{var n;return this.isLinkModeEnabled(r,i)?(n=r?.redirect)==null?void 0:n.universal:void 0}),T(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Ec(r,"topic")||"",n=decodeURIComponent(Ec(r,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:de.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})}),T(this,"registerLinkModeListeners",async()=>{var r;if(Jo()||Zt()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const i=global==null?void 0:global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await i.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}),T(this,"shouldSetTVF",(r,i)=>{if(!i||r!=="wc_sessionRequest")return!1;const{request:n}=i;return Object.keys(Uu).includes(n.method)}),T(this,"getTVFParams",(r,i,n)=>{var s,o;try{const a=i.request.method,c=this.extractTxHashesFromResult(a,n);return Be(ce({correlationId:r,rpcMethods:[a],chainId:i.chainId},this.isValidContractData(i.request.params)&&{contractAddresses:[(o=(s=i.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{}}),T(this,"isValidContractData",r=>{var i;if(!r)return!1;try{const n=r?.data||((i=r?.[0])==null?void 0:i.data);if(!n.startsWith("0x"))return!1;const s=n.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),T(this,"extractTxHashesFromResult",(r,i)=>{try{const n=Uu[r];if(typeof i=="string")return[i];const s=i[n.key];if(ft(s))return r==="solana_signAllTransactions"?s.map(o=>b0(o)):s;if(typeof s=="string")return[s]}catch(n){this.client.logger.warn("Error extracting tx hashes from result",n)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,n]of Object.entries(r))for(const s of n)try{await this.onProviderMessageEvent({topic:i,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${s}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ie.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:i,attestation:n,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(En)?this.client.auth.authKeys.get(En):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,i,{receiverPublicKey:o,encoding:s===de.link_mode?Vt:pt});Vo(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:n,transportType:s,encryptedId:$t(i)})):Vn(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,i)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(it.expired,async e=>{const{topic:r,id:i}=Kh(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,L("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,L("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(or.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(or.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ye(e,!1)){const{message:r}=L("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}=L("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(Kt(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=L("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!ye(e,!1)){const{message:r}=L("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}=L("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(Kt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=L("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=L("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(ye(e,!1)){const{message:r}=L("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=L("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!HE(e)){const{message:r}=L("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=L("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(Kt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=L("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class Z2 extends br{constructor(e,r){super(e,r,L2,na),this.core=e,this.logger=r}}let Q2=class extends br{constructor(e,r){super(e,r,j2,na),this.core=e,this.logger=r}};class X2 extends br{constructor(e,r){super(e,r,M2,na,i=>i.id),this.core=e,this.logger=r}}class eD extends br{constructor(e,r){super(e,r,k2,rs,()=>En),this.core=e,this.logger=r}}class tD extends br{constructor(e,r){super(e,r,z2,rs),this.core=e,this.logger=r}}class rD extends br{constructor(e,r){super(e,r,H2,rs,i=>i.id),this.core=e,this.logger=r}}var iD=Object.defineProperty,nD=(t,e,r)=>e in t?iD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fs=(t,e,r)=>nD(t,typeof e!="symbol"?e+"":e,r);class sD{constructor(e,r){this.core=e,this.logger=r,Fs(this,"authKeys"),Fs(this,"pairingTopics"),Fs(this,"requests"),this.authKeys=new eD(this.core,this.logger),this.pairingTopics=new tD(this.core,this.logger),this.requests=new rD(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var oD=Object.defineProperty,aD=(t,e,r)=>e in t?oD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,W=(t,e,r)=>aD(t,typeof e!="symbol"?e+"":e,r);let cD=class Vd extends Y_{constructor(e){super(e),W(this,"protocol",zd),W(this,"version",Hd),W(this,"name",Bs.name),W(this,"metadata"),W(this,"core"),W(this,"logger"),W(this,"events",new Ut.EventEmitter),W(this,"engine"),W(this,"session"),W(this,"proposal"),W(this,"pendingRequest"),W(this,"auth"),W(this,"signConfig"),W(this,"on",(i,n)=>this.events.on(i,n)),W(this,"once",(i,n)=>this.events.once(i,n)),W(this,"off",(i,n)=>this.events.off(i,n)),W(this,"removeListener",(i,n)=>this.events.removeListener(i,n)),W(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),W(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}}),W(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}}),W(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}}),W(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}}),W(this,"update",async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}}),W(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}}),W(this,"request",async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}}),W(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}}),W(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}}),W(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}}),W(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}}),W(this,"find",i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}}),W(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),W(this,"authenticate",async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}}),W(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}}),W(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),W(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),this.name=e?.name||Bs.name,this.metadata=Rv(e?.metadata),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Bi(Mn({level:e?.logger||Bs.logger}));this.core=e?.core||new N2(e),this.logger=Fe(r,this.name),this.session=new Q2(this.core,this.logger),this.proposal=new Z2(this.core,this.logger),this.pendingRequest=new X2(this.core,this.logger),this.engine=new J2(this),this.auth=new sD(this.core,this.logger)}static async init(e){const r=new Vd(e);return await r.initialize(),r}get context(){return Ve(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 sa={exports:{}},Zr=typeof Reflect=="object"?Reflect:null,ku=Zr&&typeof Zr.apply=="function"?Zr.apply:function(e,r,i){return Function.prototype.apply.call(e,r,i)},_n;Zr&&typeof Zr.ownKeys=="function"?_n=Zr.ownKeys:Object.getOwnPropertySymbols?_n=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:_n=function(e){return Object.getOwnPropertyNames(e)};function uD(t){console&&console.warn&&console.warn(t)}var Wd=Number.isNaN||function(e){return e!==e};function oe(){oe.init.call(this)}sa.exports=oe;sa.exports.once=pD;oe.EventEmitter=oe;oe.prototype._events=void 0;oe.prototype._eventsCount=0;oe.prototype._maxListeners=void 0;var zu=10;function is(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 zu},set:function(t){if(typeof t!="number"||t<0||Wd(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");zu=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||Wd(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 Gd(t){return t._maxListeners===void 0?oe.defaultMaxListeners:t._maxListeners}oe.prototype.getMaxListeners=function(){return Gd(this)};oe.prototype.emit=function(e){for(var r=[],i=1;i<arguments.length;i++)r.push(arguments[i]);var n=e==="error",s=this._events;if(s!==void 0)n=n&&s.error===void 0;else if(!n)return!1;if(n){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")ku(c,this,r);else for(var u=c.length,l=Xd(c,u),i=0;i<u;++i)ku(l[i],this,r);return!0};function Yd(t,e,r,i){var n,s,o;if(is(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]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),n=Gd(t),n>0&&o.length>n&&!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,uD(a)}return t}oe.prototype.addListener=function(e,r){return Yd(this,e,r,!1)};oe.prototype.on=oe.prototype.addListener;oe.prototype.prependListener=function(e,r){return Yd(this,e,r,!0)};function lD(){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 Jd(t,e,r){var i={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},n=lD.bind(i);return n.listener=r,i.wrapFn=n,n}oe.prototype.once=function(e,r){return is(r),this.on(e,Jd(this,e,r)),this};oe.prototype.prependOnceListener=function(e,r){return is(r),this.prependListener(e,Jd(this,e,r)),this};oe.prototype.removeListener=function(e,r){var i,n,s,o,a;if(is(r),n=this._events,n===void 0)return this;if(i=n[e],i===void 0)return this;if(i===r||i.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||r));else if(typeof i!="function"){for(s=-1,o=i.length-1;o>=0;o--)if(i[o]===r||i[o].listener===r){a=i[o].listener,s=o;break}if(s<0)return this;s===0?i.shift():hD(i,s),i.length===1&&(n[e]=i[0]),n.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};oe.prototype.off=oe.prototype.removeListener;oe.prototype.removeAllListeners=function(e){var r,i,n;if(i=this._events,i===void 0)return this;if(i.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):i[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete i[e]),this;if(arguments.length===0){var s=Object.keys(i),o;for(n=0;n<s.length;++n)o=s[n],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=i[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(n=r.length-1;n>=0;n--)this.removeListener(e,r[n]);return this};function Zd(t,e,r){var i=t._events;if(i===void 0)return[];var n=i[e];return n===void 0?[]:typeof n=="function"?r?[n.listener||n]:[n]:r?dD(n):Xd(n,n.length)}oe.prototype.listeners=function(e){return Zd(this,e,!0)};oe.prototype.rawListeners=function(e){return Zd(this,e,!1)};oe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Qd.call(t,e)};oe.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}oe.prototype.eventNames=function(){return this._eventsCount>0?_n(this._events):[]};function Xd(t,e){for(var r=new Array(e),i=0;i<e;++i)r[i]=t[i];return r}function hD(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 pD(t,e){return new Promise(function(r,i){function n(o){t.removeListener(e,s),i(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",n),r([].slice.call(arguments))}ep(t,e,s,{once:!0}),e!=="error"&&fD(t,n,{once:!0})})}function fD(t,e,r){typeof t.on=="function"&&ep(t,"error",e,r)}function ep(t,e,r,i){if(typeof t.on=="function")i.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function n(s){i.once&&t.removeEventListener(e,n),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var gD=sa.exports,So={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof It<"u"&&It,i=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 It<"u"&&It||{},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 d(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 f(g){return typeof g!="string"&&(g=String(g)),g}function p(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=d(g),m=f(m);var _=this.map[g];this.map[g]=_?_+", "+m:m},y.prototype.delete=function(g){delete this.map[d(g)]},y.prototype.get=function(g){return g=d(g),this.has(g)?this.map[g]:null},y.prototype.has=function(g){return this.map.hasOwnProperty(d(g))},y.prototype.set=function(g,m){this.map[d(g)]=f(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(_)}),p(g)},y.prototype.values=function(){var g=[];return this.forEach(function(m){g.push(m)}),p(g)},y.prototype.entries=function(){var g=[];return this.forEach(function(m,_){g.push([_,m])}),p(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 v(g){return new Promise(function(m,_){g.onload=function(){m(g.result)},g.onerror=function(){_(g.error)}})}function b(g){var m=new FileReader,_=v(m);return m.readAsArrayBuffer(g),_}function E(g){var m=new FileReader,_=v(m),D=/charset=([A-Za-z0-9_-]+)/.exec(g.type),I=D?D[1]:"utf-8";return m.readAsText(g,I),_}function $(g){for(var m=new Uint8Array(g),_=new Array(m.length),D=0;D<m.length;D++)_[D]=String.fromCharCode(m[D]);return _.join("")}function A(g){if(g.slice)return g.slice(0);var m=new Uint8Array(g.byteLength);return m.set(new Uint8Array(g)),m.buffer}function P(){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=A(g.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(g)||h(g))?this._bodyArrayBuffer=A(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(b);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($(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 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 O(g,m){if(!(this instanceof O))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 O){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 x=new AbortController;return x.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 D=/([?&])_=[^&]*/;if(D.test(this.url))this.url=this.url.replace(D,"$1_="+new Date().getTime());else{var I=/\?/;this.url+=(I.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}O.prototype.clone=function(){return new O(this,{body:this._bodyInit})};function q(g){var m=new FormData;return g.trim().split("&").forEach(function(_){if(_){var D=_.split("="),I=D.shift().replace(/\+/g," "),x=D.join("=").replace(/\+/g," ");m.append(decodeURIComponent(I),decodeURIComponent(x))}}),m}function B(g){var m=new y,_=g.replace(/\r?\n[\t ]+/g," ");return _.split("\r").map(function(D){return D.indexOf(`
|
|
38
|
-
`)===0?D.substr(1,D.length):D}).forEach(function(D){var I=D.split(":"),x=I.shift().trim();if(x){var M=I.join(":").trim();try{m.append(x,M)}catch(U){console.warn("Response "+U.message)}}}),m}P.call(O.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)}P.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 D=Error(m);this.stack=D.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function R(g,m){return new Promise(function(_,D){var I=new O(g,m);if(I.signal&&I.signal.aborted)return D(new o.DOMException("Aborted","AbortError"));var x=new XMLHttpRequest;function M(){x.abort()}x.onload=function(){var F={statusText:x.statusText,headers:B(x.getAllResponseHeaders()||"")};I.url.indexOf("file://")===0&&(x.status<200||x.status>599)?F.status=200:F.status=x.status,F.url="responseURL"in x?x.responseURL:F.headers.get("X-Request-URL");var H="response"in x?x.response:x.responseText;setTimeout(function(){_(new j(H,F))},0)},x.onerror=function(){setTimeout(function(){D(new TypeError("Network request failed"))},0)},x.ontimeout=function(){setTimeout(function(){D(new TypeError("Network request timed out"))},0)},x.onabort=function(){setTimeout(function(){D(new o.DOMException("Aborted","AbortError"))},0)};function U(F){try{return F===""&&a.location.href?a.location.href:F}catch{return F}}if(x.open(I.method,U(I.url),!0),I.credentials==="include"?x.withCredentials=!0:I.credentials==="omit"&&(x.withCredentials=!1),"responseType"in x&&(c.blob?x.responseType="blob":c.arrayBuffer&&(x.responseType="arraybuffer")),m&&typeof m.headers=="object"&&!(m.headers instanceof y||a.Headers&&m.headers instanceof a.Headers)){var z=[];Object.getOwnPropertyNames(m.headers).forEach(function(F){z.push(d(F)),x.setRequestHeader(F,f(m.headers[F]))}),I.headers.forEach(function(F,H){z.indexOf(H)===-1&&x.setRequestHeader(H,F)})}else I.headers.forEach(function(F,H){x.setRequestHeader(H,F)});I.signal&&(I.signal.addEventListener("abort",M),x.onreadystatechange=function(){x.readyState===4&&I.signal.removeEventListener("abort",M)}),x.send(typeof I._bodyInit>"u"?null:I._bodyInit)})}return R.polyfill=!0,a.fetch||(a.fetch=R,a.Headers=y,a.Request=O,a.Response=j),o.Headers=y,o.Request=O,o.Response=j,o.fetch=R,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var n=r.fetch?r:i;e=n.fetch,e.default=n.fetch,e.fetch=n.fetch,e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response,t.exports=e})(So,So.exports);var yD=So.exports;const Hu=Ro(yD);var mD=Object.defineProperty,wD=Object.defineProperties,bD=Object.getOwnPropertyDescriptors,Ku=Object.getOwnPropertySymbols,vD=Object.prototype.hasOwnProperty,ED=Object.prototype.propertyIsEnumerable,Vu=(t,e,r)=>e in t?mD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wu=(t,e)=>{for(var r in e||(e={}))vD.call(e,r)&&Vu(t,r,e[r]);if(Ku)for(var r of Ku(e))ED.call(e,r)&&Vu(t,r,e[r]);return t},Gu=(t,e)=>wD(t,bD(e));const _D={Accept:"application/json","Content-Type":"application/json"},ID="POST",Yu={headers:_D,method:ID},Ju=10;let gt=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new gD.EventEmitter,this.isAvailable=!1,this.registering=!1,!ac(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=Ft(e),i=await(await Hu(this.url,Gu(Wu({},Yu),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!ac(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((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return n(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=Ft({id:1,jsonrpc:"2.0",method:"test",params:[]});await Hu(e,Gu(Wu({},Yu),{body:r}))}this.onOpen()}catch(r){const i=this.parseError(r);throw this.events.emit("register_error",i),this.onClose(),i}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?hr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=Kn(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return mh(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Ju&&this.events.setMaxListeners(Ju)}};const Zu="error",$D="wss://relay.walletconnect.org",OD="wc",DD="universal_provider",on=`${OD}@2:${DD}:`,tp="https://rpc.walletconnect.org/v1/",kr="generic",SD=`${tp}bundler`,at={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function PD(){}function oa(t){return t==null||typeof t!="object"&&typeof t!="function"}function aa(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function AD(t){if(oa(t))return t;if(Array.isArray(t)||aa(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 i=new r(t);return i.lastIndex=t.lastIndex,i}if(t instanceof DataView)return new r(t.buffer.slice(0));if(t instanceof Error){const i=new r(t.message);return i.stack=t.stack,i.name=t.name,i.cause=t.cause,i}if(typeof File<"u"&&t instanceof File)return new r([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const i=Object.create(e);return Object.assign(i,t)}return t}function Qu(t){return typeof t=="object"&&t!==null}function rp(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function ip(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const xD="[object RegExp]",np="[object String]",sp="[object Number]",op="[object Boolean]",ap="[object Arguments]",CD="[object Symbol]",RD="[object Date]",TD="[object Map]",ND="[object Set]",LD="[object Array]",jD="[object ArrayBuffer]",BD="[object Object]",MD="[object DataView]",FD="[object Uint8Array]",UD="[object Uint8ClampedArray]",qD="[object Uint16Array]",kD="[object Uint32Array]",zD="[object Int8Array]",HD="[object Int16Array]",KD="[object Int32Array]",VD="[object Float32Array]",WD="[object Float64Array]";function GD(t,e){return Kr(t,void 0,t,new Map,e)}function Kr(t,e,r,i=new Map,n=void 0){const s=n?.(t,e,r,i);if(s!=null)return s;if(oa(t))return t;if(i.has(t))return i.get(t);if(Array.isArray(t)){const o=new Array(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Kr(t[a],a,r,i,n);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;i.set(t,o);for(const[a,c]of t)o.set(a,Kr(c,a,r,i,n));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(Kr(a,void 0,r,i,n));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(aa(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Kr(t[a],a,r,i,n);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 i.set(t,o),ar(o,t,r,i,n),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),ar(o,t,r,i,n),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),ar(o,t,r,i,n),o}if(t instanceof Error){const o=new t.constructor;return i.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,ar(o,t,r,i,n),o}if(typeof t=="object"&&YD(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),ar(o,t,r,i,n),o}return t}function ar(t,e,r=t,i,n){const s=[...Object.keys(e),...rp(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Kr(e[a],a,r,i,n))}}function YD(t){switch(ip(t)){case ap:case LD:case jD:case MD:case op:case RD:case VD:case WD:case zD:case HD:case KD:case TD:case sp:case BD:case xD:case ND:case np:case CD:case FD:case UD:case qD:case kD:return!0;default:return!1}}function JD(t,e){return GD(t,(r,i,n,s)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case sp:case np:case op:{const o=new t.constructor(t?.valueOf());return ar(o,t),o}case ap:{const o={};return ar(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function Xu(t){return JD(t)}function el(t){return t!==null&&typeof t=="object"&&ip(t)==="[object Arguments]"}function ZD(t){return aa(t)}function QD(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 XD(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let n=t;for(let s=0;s<r.length;s++){const o=r[s];n=Po(n,o,i,new Map)}return n}function Po(t,e,r,i){if(oa(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return AD(i.get(e));if(i.set(e,t),Array.isArray(e)){e=e.slice();for(let s=0;s<e.length;s++)e[s]=e[s]??void 0}const n=[...Object.keys(e),...rp(e)];for(let s=0;s<n.length;s++){const o=n[s];let a=e[o],c=t[o];if(el(a)&&(a={...a}),el(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=Xu(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],h=Reflect.ownKeys(c);for(let d=0;d<h.length;d++){const f=h[d];l[f]=c[f]}c=l}else c=[];const u=r(c,a,o,t,e,i);u!=null?t[o]=u:Array.isArray(a)||Qu(c)&&Qu(a)?t[o]=Po(c,a,r,i):c==null&&QD(a)?t[o]=Po({},a,r,i):c==null&&ZD(a)?t[o]=Xu(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function eS(t,...e){return XD(t,...e,PD)}var tS=Object.defineProperty,rS=Object.defineProperties,iS=Object.getOwnPropertyDescriptors,tl=Object.getOwnPropertySymbols,nS=Object.prototype.hasOwnProperty,sS=Object.prototype.propertyIsEnumerable,rl=(t,e,r)=>e in t?tS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,an=(t,e)=>{for(var r in e||(e={}))nS.call(e,r)&&rl(t,r,e[r]);if(tl)for(var r of tl(e))sS.call(e,r)&&rl(t,r,e[r]);return t},oS=(t,e)=>rS(t,iS(e));function Xe(t,e,r){var i;const n=Jr(t);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${tp}?chainId=${n.namespace}:${n.reference}&projectId=${r}`}function vr(t){return t.includes(":")?t.split(":")[1]:t}function cp(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function aS(t,e){const r=Object.keys(e.namespaces).filter(n=>n.includes(t));if(!r.length)return[];const i=[];return r.forEach(n=>{const s=e.namespaces[n].accounts;i.push(...s)}),i}function cn(t={},e={}){const r=il(t),i=il(e);return eS(r,i)}function il(t){var e,r,i,n,s;const o={};if(!Jt(t))return o;for(const[a,c]of Object.entries(t)){const u=es(a)?[a]:c.chains,l=c.methods||[],h=c.events||[],d=c.rpcMap||{},f=Hr(a);o[f]=oS(an(an({},o[f]),c),{chains:Dt(u,(e=o[f])==null?void 0:e.chains),methods:Dt(l,(r=o[f])==null?void 0:r.methods),events:Dt(h,(i=o[f])==null?void 0:i.events)}),(Jt(d)||Jt(((n=o[f])==null?void 0:n.rpcMap)||{}))&&(o[f].rpcMap=an(an({},d),(s=o[f])==null?void 0:s.rpcMap))}return o}function nl(t){return t.includes(":")?t.split(":")[2]:t}function sl(t){const e={};for(const[r,i]of Object.entries(t)){const n=i.methods||[],s=i.events||[],o=i.accounts||[],a=es(r)?[r]:i.chains?i.chains:cp(i.accounts);e[r]={chains:a,methods:n,events:s,accounts:o}}return e}function Us(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 up={},Q=t=>up[t],qs=(t,e)=>{up[t]=e};var cS=Object.defineProperty,uS=(t,e,r)=>e in t?cS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xr=(t,e,r)=>uS(t,typeof e!="symbol"?e+"":e,r);class lS{constructor(e){xr(this,"name","polkadot"),xr(this,"client"),xr(this,"httpProviders"),xr(this,"events"),xr(this,"namespace"),xr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.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 i;const n=vr(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ot(new gt(i,Q("disableProviderPing")))}}var hS=Object.defineProperty,dS=Object.defineProperties,pS=Object.getOwnPropertyDescriptors,ol=Object.getOwnPropertySymbols,fS=Object.prototype.hasOwnProperty,gS=Object.prototype.propertyIsEnumerable,Ao=(t,e,r)=>e in t?hS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,al=(t,e)=>{for(var r in e||(e={}))fS.call(e,r)&&Ao(t,r,e[r]);if(ol)for(var r of ol(e))gS.call(e,r)&&Ao(t,r,e[r]);return t},cl=(t,e)=>dS(t,pS(e)),Cr=(t,e,r)=>Ao(t,typeof e!="symbol"?e+"":e,r);class yS{constructor(e){Cr(this,"name","eip155"),Cr(this,"client"),Cr(this,"chainId"),Cr(this,"namespace"),Cr(this,"httpProviders"),Cr(this,"events"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r),this.chainId=parseInt(e),this.events.emit(at.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 i=r||Xe(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ot(new gt(i,Q("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=parseInt(vr(r));e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[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,i;let n=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";n=n.startsWith("0x")?n:`0x${n}`;const s=parseInt(n,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:n}]},chainId:(i=this.namespace.chains)==null?void 0:i[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,i,n,s,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0],c=((s=(n=e.request)==null?void 0:n.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 d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:cl(al({},l.sessionProperties||{}),{capabilities:cl(al({},h||{}),{[u]:d})})})}catch(f){console.warn("Failed to update session with capabilities",f)}return d}async getCallStatus(e){var r,i;const n=this.client.session.get(e.topic),s=(r=n.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=(i=n.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,r){var i;const n=new URL(e),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Wt("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,r){return`${SD}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}}var mS=Object.defineProperty,wS=(t,e,r)=>e in t?mS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rr=(t,e,r)=>wS(t,typeof e!="symbol"?e+"":e,r);class bS{constructor(e){Rr(this,"name","solana"),Rr(this,"client"),Rr(this,"httpProviders"),Rr(this,"events"),Rr(this,"namespace"),Rr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.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 i;const n=vr(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ot(new gt(i,Q("disableProviderPing")))}}var vS=Object.defineProperty,ES=(t,e,r)=>e in t?vS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tr=(t,e,r)=>ES(t,typeof e!="symbol"?e+"":e,r);class _S{constructor(e){Tr(this,"name","cosmos"),Tr(this,"client"),Tr(this,"httpProviders"),Tr(this,"events"),Tr(this,"namespace"),Tr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=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(at.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 i;const n=vr(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ot(new gt(i,Q("disableProviderPing")))}}var IS=Object.defineProperty,$S=(t,e,r)=>e in t?IS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nr=(t,e,r)=>$S(t,typeof e!="symbol"?e+"":e,r);class OS{constructor(e){Nr(this,"name","algorand"),Nr(this,"client"),Nr(this,"httpProviders"),Nr(this,"events"),Nr(this,"namespace"),Nr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const i=r||Xe(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(at.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 i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new ot(new gt(i,Q("disableProviderPing")))}}var DS=Object.defineProperty,SS=(t,e,r)=>e in t?DS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lr=(t,e,r)=>SS(t,typeof e!="symbol"?e+"":e,r);class PS{constructor(e){Lr(this,"name","cip34"),Lr(this,"client"),Lr(this,"httpProviders"),Lr(this,"events"),Lr(this,"namespace"),Lr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.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 i=this.getCardanoRPCUrl(r),n=vr(r);e[n]=this.createHttpProvider(n,i)}),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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ot(new gt(i,Q("disableProviderPing")))}}var AS=Object.defineProperty,xS=(t,e,r)=>e in t?AS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jr=(t,e,r)=>xS(t,typeof e!="symbol"?e+"":e,r);class CS{constructor(e){jr(this,"name","elrond"),jr(this,"client"),jr(this,"httpProviders"),jr(this,"events"),jr(this,"namespace"),jr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.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 i;const n=vr(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ot(new gt(i,Q("disableProviderPing")))}}var RS=Object.defineProperty,TS=(t,e,r)=>e in t?RS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Br=(t,e,r)=>TS(t,typeof e!="symbol"?e+"":e,r);class NS{constructor(e){Br(this,"name","multiversx"),Br(this,"client"),Br(this,"httpProviders"),Br(this,"events"),Br(this,"namespace"),Br(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.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 i;const n=vr(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ot(new gt(i,Q("disableProviderPing")))}}var LS=Object.defineProperty,jS=(t,e,r)=>e in t?LS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mr=(t,e,r)=>jS(t,typeof e!="symbol"?e+"":e,r);class BS{constructor(e){Mr(this,"name","near"),Mr(this,"client"),Mr(this,"httpProviders"),Mr(this,"events"),Mr(this,"namespace"),Mr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const i=r||Xe(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(at.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 i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace);return typeof i>"u"?void 0:new ot(new gt(i,Q("disableProviderPing")))}}var MS=Object.defineProperty,FS=(t,e,r)=>e in t?MS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fr=(t,e,r)=>FS(t,typeof e!="symbol"?e+"":e,r);class US{constructor(e){Fr(this,"name","tezos"),Fr(this,"client"),Fr(this,"httpProviders"),Fr(this,"events"),Fr(this,"namespace"),Fr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const i=r||Xe(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(at.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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace);return typeof i>"u"?void 0:new ot(new gt(i))}}var qS=Object.defineProperty,kS=(t,e,r)=>e in t?qS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ur=(t,e,r)=>kS(t,typeof e!="symbol"?e+"":e,r);class zS{constructor(e){Ur(this,"name",kr),Ur(this,"client"),Ur(this,"httpProviders"),Ur(this,"events"),Ur(this,"namespace"),Ur(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.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 i={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(n=>{const s=Jr(n);i[`${s.namespace}:${s.reference}`]=this.createHttpProvider(n)}),i}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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ot(new gt(i,Q("disableProviderPing")))}}var HS=Object.defineProperty,KS=Object.defineProperties,VS=Object.getOwnPropertyDescriptors,ul=Object.getOwnPropertySymbols,WS=Object.prototype.hasOwnProperty,GS=Object.prototype.propertyIsEnumerable,xo=(t,e,r)=>e in t?HS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,un=(t,e)=>{for(var r in e||(e={}))WS.call(e,r)&&xo(t,r,e[r]);if(ul)for(var r of ul(e))GS.call(e,r)&&xo(t,r,e[r]);return t},ks=(t,e)=>KS(t,VS(e)),rt=(t,e,r)=>xo(t,typeof e!="symbol"?e+"":e,r);let YS=class lp{constructor(e){rt(this,"client"),rt(this,"namespaces"),rt(this,"optionalNamespaces"),rt(this,"sessionProperties"),rt(this,"scopedProperties"),rt(this,"events",new Yo),rt(this,"rpcProviders",{}),rt(this,"session"),rt(this,"providerOpts"),rt(this,"logger"),rt(this,"uri"),rt(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Bi(Mn({level:e?.logger||Zu})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new lp(e);return await r.initialize(),r}async request(e,r,i){const[n,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:un({},e),chainId:`${n}:${s}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,n){const s=new Date().getTime();this.request(e,i,n).then(o=>r(null,Hn(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:te("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:n}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const s=await n();if(this.session=s.session,this.session){const o=sl(this.session.namespaces);this.namespaces=cn(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:i}=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 n=await i();this.session=n;const s=sl(n.namespaces);return this.namespaces=cn(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[i,n]=this.validateChain(e),s=this.getProvider(i);s.name===kr?s.setDefaultChain(`${i}:${n}`,r):s.setDefaultChain(n,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(ft(r)){for(const i of r)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${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 cD.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Zu,relayUrl:this.providerOpts.relayUrl||$D,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(i){throw this.logger.error("Failed to get session",i),new Error(`The provided session: ${(r=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(r=>Hr(r)))];qs("client",this.client),qs("events",this.events),qs("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=aS(r,this.session),n=cp(i),s=cn(this.namespaces,this.optionalNamespaces),o=ks(un({},s[r]),{accounts:i,chains:n});switch(r){case"eip155":this.rpcProviders[r]=new yS({namespace:o});break;case"algorand":this.rpcProviders[r]=new OS({namespace:o});break;case"solana":this.rpcProviders[r]=new bS({namespace:o});break;case"cosmos":this.rpcProviders[r]=new _S({namespace:o});break;case"polkadot":this.rpcProviders[r]=new lS({namespace:o});break;case"cip34":this.rpcProviders[r]=new PS({namespace:o});break;case"elrond":this.rpcProviders[r]=new CS({namespace:o});break;case"multiversx":this.rpcProviders[r]=new NS({namespace:o});break;case"near":this.rpcProviders[r]=new BS({namespace:o});break;case"tezos":this.rpcProviders[r]=new US({namespace:o});break;default:this.rpcProviders[kr]?this.rpcProviders[kr].updateNamespace(o):this.rpcProviders[kr]=new zS({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:i}=e;i===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:i,topic:n}=e;if(n!==((r=this.session)==null?void 0:r.topic))return;const{event:s}=i;if(s.name==="accountsChanged"){const o=s.data;o&&ft(o)&&this.events.emit("accountsChanged",o.map(nl))}else if(s.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=Hr(o),u=Us(o)!==Us(a)?`${c}:${Us(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 i,n;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:s}=r,o=(n=this.client)==null?void 0:n.session.get(e);this.session=ks(un({},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",ks(un({},te("USER_DISCONNECTED")),{data:e.topic})))}),this.on(at.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[kr]}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:i={},sessionProperties:n,scopedProperties:s}=e;this.optionalNamespaces=cn(r,i),this.sessionProperties=n,this.scopedProperties=s}validateChain(e){const[r,i]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(o=>Hr(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const n=Hr(Object.keys(this.namespaces)[0]),s=this.rpcProviders[n].getDefaultChain();return[n,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,r=!1){if(!this.namespaces)return;const[i,n]=this.validateChain(e);if(!n)return;this.updateNamespaceChain(i,n),this.events.emit("chainChanged",n);const s=this.getProvider(i).getDefaultChain();r||this.getProvider(i).setDefaultChain(n),this.emitAccountsChangedOnChainChange({namespace:i,previousChainId:s,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:r,newChainId:i}){var n,s;try{if(r===i)return;const o=(s=(n=this.session)==null?void 0:n.namespaces[e])==null?void 0:s.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${i}:`)).map(nl);if(!ft(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 i=this.namespaces[e]?e:`${e}:${r}`,n={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=n}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 i;const n=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${on}/${e}${n}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${on}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${on}/${e}${i}`)}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 i of r)i.startsWith(on)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn("Failed to cleanup storage",r)}}};const JS=YS,ZS="wc",QS="ethereum_provider",XS=`${ZS}@2:${QS}:`,eP="https://rpc.walletconnect.org/v1/",Rn=["eth_sendTransaction","personal_sign"],hp=["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"],Tn=["chainChanged","accountsChanged"],dp=["chainChanged","accountsChanged","message","disconnect","connect"],tP=async()=>{const{createAppKit:t}=await _p(()=>import("./core-CpW5hIOT.js").then(e=>e.G),__vite__mapDeps([0,1,2,3,4]));return t};var rP=Object.defineProperty,iP=Object.defineProperties,nP=Object.getOwnPropertyDescriptors,ll=Object.getOwnPropertySymbols,sP=Object.prototype.hasOwnProperty,oP=Object.prototype.propertyIsEnumerable,Co=(t,e,r)=>e in t?rP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ir=(t,e)=>{for(var r in e||(e={}))sP.call(e,r)&&Co(t,r,e[r]);if(ll)for(var r of ll(e))oP.call(e,r)&&Co(t,r,e[r]);return t},vi=(t,e)=>iP(t,nP(e)),Ge=(t,e,r)=>Co(t,typeof e!="symbol"?e+"":e,r);function Nn(t){return Number(t[0].split(":")[1])}function ln(t){return`0x${t.toString(16)}`}function aP(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:n,events:s,optionalEvents:o,rpcMap:a}=t;if(!ft(e))throw new Error("Invalid chains");const c={chains:e,methods:i||Rn,events:s||Tn,rpcMap:ir({},e.length?{[Nn(e)]:a[Nn(e)]}:{})},u=s?.filter(f=>!Tn.includes(f)),l=i?.filter(f=>!Rn.includes(f));if(!r&&!o&&!n&&!(u!=null&&u.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const h=u?.length&&l?.length||!r,d={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(n!=null&&n.length?n:hp))],events:[...new Set(c.events.concat(o!=null&&o.length?o:dp))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?d:void 0}}class ns{constructor(){Ge(this,"events",new Ut.EventEmitter),Ge(this,"namespace","eip155"),Ge(this,"accounts",[]),Ge(this,"signer"),Ge(this,"chainId",1),Ge(this,"modal"),Ge(this,"rpc"),Ge(this,"STORAGE_KEY",XS),Ge(this,"on",(e,r)=>(this.events.on(e,r),this)),Ge(this,"once",(e,r)=>(this.events.once(e,r),this)),Ge(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),Ge(this,"off",(e,r)=>(this.events.off(e,r),this)),Ge(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new ns;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:n}=aP(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(d=>{!d.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(vi(ir({namespaces:ir({},i&&{[this.namespace]:i})},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e?.pairingTopic,scopedProperties:h})).then(d=>{a(d)}).catch(d=>{var f;(f=this.modal)==null||f.showErrorMessage("Unable to connect"),c(new Error(d.message))})});if(!s)return;const o=yc(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ln(this.chainId)})}catch(s){throw this.signer.logger.error(s),s}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const n=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(vi(ir({},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=n.session;if(s){const o=yc(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ln(this.chainId)})}return n}catch(n){throw this.signer.logger.error(n),n}finally{(i=this.modal)==null||i.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:i}=r;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",ln(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",vi(ir({},te("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",ln(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,i,n]=e.split(":");return{chainId:`${r}:${i}`,address:n}}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,i;const n=(r=e?.chains)!=null?r:[],s=(i=e?.optionalChains)!=null?i:[],o=n.concat(s);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=n.length?e?.methods||Rn:[],c=n.length?e?.events||Tn:[],u=e?.optionalMethods||[],l=e?.optionalEvents||[],h=e?.rpcMap||this.buildRpcMap(o,e.projectId),d=e?.qrModalOptions||void 0;return{chains:n?.map(f=>this.formatChainId(f)),optionalChains:s.map(f=>this.formatChainId(f)),methods:a,events:c,optionalMethods:u,optionalEvents:l,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:d,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(n=>{i[n]=this.getRpcUrl(n,r)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Nn(this.rpc.chains):Nn(this.rpc.optionalChains),this.signer=await JS.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 i=await tP(),{convertWCMToAppKitOptions:n}=await Promise.resolve().then(function(){return wP}),s=n(vi(ir({},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=i(vi(ir({},s),{universalProvider:this.signer,manualWCControl:!0}))}catch(i){throw console.warn(i),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:n}=e;r&&ft(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=n?.[s]||this.getRpcUrl(s)})),i&&ft(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(s=>this.formatChainId(s)),i.forEach(s=>{this.rpc.rpcMap[s]=n?.[s]||this.getRpcUrl(s)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${eP}?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 cP=ns;var uP=Object.defineProperty,lP=Object.defineProperties,hP=Object.getOwnPropertyDescriptors,hl=Object.getOwnPropertySymbols,dP=Object.prototype.hasOwnProperty,pP=Object.prototype.propertyIsEnumerable,dl=(t,e,r)=>e in t?uP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pp=(t,e)=>{for(var r in e||(e={}))dP.call(e,r)&&dl(t,r,e[r]);if(hl)for(var r of hl(e))pP.call(e,r)&&dl(t,r,e[r]);return t},fP=(t,e)=>lP(t,hP(e));function gP(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 yP=t=>{const[e,r]=t.split(":");return fp({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function mP(t){var e,r,i,n,s,o,a;const c=(e=t.chains)==null?void 0:e.map(yP).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const u=c.find(h=>{var d;return h.id===((d=t.defaultChain)==null?void 0:d.id)}),l={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:gP(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:u,metadata:fP(pp({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((i=t.metadata)==null?void 0:i.description)||"Connect to WalletConnect-compatible wallets",url:((n=t.metadata)==null?void 0:n.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(p=>({id:p.id,name:p.name,links:p.links})),...(t.desktopWallets||[]).map(p=>({id:p.id,name:p.name,links:{native:p.links.native,universal:p.links.universal}}))],d=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],f=h.filter(p=>!d.includes(p.id));f.length&&(l.customWallets=f)}return l}function fp(t){return pp({formatters:void 0,fees:void 0,serializers:void 0},t)}var wP=Object.freeze({__proto__:null,convertWCMToAppKitOptions:mP,defineChain:fp});const oA=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:cP,OPTIONAL_EVENTS:dp,OPTIONAL_METHODS:hp,REQUIRED_EVENTS:Tn,REQUIRED_METHODS:Rn,default:ns},Symbol.toStringTag,{value:"Module"}));export{Wf as A,Bi as B,ob as C,Et as D,Fe as E,gt as F,oA as G,yr as I,Ja as P,rh as Q,hr as a,tc as b,N as c,Gi as d,dr as e,ko as f,nh as g,Wm as h,ih as i,Qs as j,Mn as k,df as l,cv as m,Vo as n,ot as o,Vn as p,Hn as q,mr as r,Ft as s,Wt as t,Mm as u,cr as v,Kn as w,_t as x,Ve as y,nt as z};
|
|
38
|
+
`)===0?D.substr(1,D.length):D}).forEach(function(D){var I=D.split(":"),x=I.shift().trim();if(x){var M=I.join(":").trim();try{m.append(x,M)}catch(U){console.warn("Response "+U.message)}}}),m}P.call(O.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)}P.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 D=Error(m);this.stack=D.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function R(g,m){return new Promise(function(_,D){var I=new O(g,m);if(I.signal&&I.signal.aborted)return D(new o.DOMException("Aborted","AbortError"));var x=new XMLHttpRequest;function M(){x.abort()}x.onload=function(){var F={statusText:x.statusText,headers:B(x.getAllResponseHeaders()||"")};I.url.indexOf("file://")===0&&(x.status<200||x.status>599)?F.status=200:F.status=x.status,F.url="responseURL"in x?x.responseURL:F.headers.get("X-Request-URL");var H="response"in x?x.response:x.responseText;setTimeout(function(){_(new j(H,F))},0)},x.onerror=function(){setTimeout(function(){D(new TypeError("Network request failed"))},0)},x.ontimeout=function(){setTimeout(function(){D(new TypeError("Network request timed out"))},0)},x.onabort=function(){setTimeout(function(){D(new o.DOMException("Aborted","AbortError"))},0)};function U(F){try{return F===""&&a.location.href?a.location.href:F}catch{return F}}if(x.open(I.method,U(I.url),!0),I.credentials==="include"?x.withCredentials=!0:I.credentials==="omit"&&(x.withCredentials=!1),"responseType"in x&&(c.blob?x.responseType="blob":c.arrayBuffer&&(x.responseType="arraybuffer")),m&&typeof m.headers=="object"&&!(m.headers instanceof y||a.Headers&&m.headers instanceof a.Headers)){var z=[];Object.getOwnPropertyNames(m.headers).forEach(function(F){z.push(d(F)),x.setRequestHeader(F,f(m.headers[F]))}),I.headers.forEach(function(F,H){z.indexOf(H)===-1&&x.setRequestHeader(H,F)})}else I.headers.forEach(function(F,H){x.setRequestHeader(H,F)});I.signal&&(I.signal.addEventListener("abort",M),x.onreadystatechange=function(){x.readyState===4&&I.signal.removeEventListener("abort",M)}),x.send(typeof I._bodyInit>"u"?null:I._bodyInit)})}return R.polyfill=!0,a.fetch||(a.fetch=R,a.Headers=y,a.Request=O,a.Response=j),o.Headers=y,o.Request=O,o.Response=j,o.fetch=R,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var n=r.fetch?r:i;e=n.fetch,e.default=n.fetch,e.fetch=n.fetch,e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response,t.exports=e})(So,So.exports);var yD=So.exports;const Hu=Ro(yD);var mD=Object.defineProperty,wD=Object.defineProperties,bD=Object.getOwnPropertyDescriptors,Ku=Object.getOwnPropertySymbols,vD=Object.prototype.hasOwnProperty,ED=Object.prototype.propertyIsEnumerable,Vu=(t,e,r)=>e in t?mD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wu=(t,e)=>{for(var r in e||(e={}))vD.call(e,r)&&Vu(t,r,e[r]);if(Ku)for(var r of Ku(e))ED.call(e,r)&&Vu(t,r,e[r]);return t},Gu=(t,e)=>wD(t,bD(e));const _D={Accept:"application/json","Content-Type":"application/json"},ID="POST",Yu={headers:_D,method:ID},Ju=10;let gt=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new gD.EventEmitter,this.isAvailable=!1,this.registering=!1,!ac(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=Ft(e),i=await(await Hu(this.url,Gu(Wu({},Yu),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!ac(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((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return n(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=Ft({id:1,jsonrpc:"2.0",method:"test",params:[]});await Hu(e,Gu(Wu({},Yu),{body:r}))}this.onOpen()}catch(r){const i=this.parseError(r);throw this.events.emit("register_error",i),this.onClose(),i}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?hr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=Kn(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return mh(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Ju&&this.events.setMaxListeners(Ju)}};const Zu="error",$D="wss://relay.walletconnect.org",OD="wc",DD="universal_provider",on=`${OD}@2:${DD}:`,tp="https://rpc.walletconnect.org/v1/",kr="generic",SD=`${tp}bundler`,at={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function PD(){}function oa(t){return t==null||typeof t!="object"&&typeof t!="function"}function aa(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function AD(t){if(oa(t))return t;if(Array.isArray(t)||aa(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 i=new r(t);return i.lastIndex=t.lastIndex,i}if(t instanceof DataView)return new r(t.buffer.slice(0));if(t instanceof Error){const i=new r(t.message);return i.stack=t.stack,i.name=t.name,i.cause=t.cause,i}if(typeof File<"u"&&t instanceof File)return new r([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const i=Object.create(e);return Object.assign(i,t)}return t}function Qu(t){return typeof t=="object"&&t!==null}function rp(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function ip(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const xD="[object RegExp]",np="[object String]",sp="[object Number]",op="[object Boolean]",ap="[object Arguments]",CD="[object Symbol]",RD="[object Date]",TD="[object Map]",ND="[object Set]",LD="[object Array]",jD="[object ArrayBuffer]",BD="[object Object]",MD="[object DataView]",FD="[object Uint8Array]",UD="[object Uint8ClampedArray]",qD="[object Uint16Array]",kD="[object Uint32Array]",zD="[object Int8Array]",HD="[object Int16Array]",KD="[object Int32Array]",VD="[object Float32Array]",WD="[object Float64Array]";function GD(t,e){return Kr(t,void 0,t,new Map,e)}function Kr(t,e,r,i=new Map,n=void 0){const s=n?.(t,e,r,i);if(s!=null)return s;if(oa(t))return t;if(i.has(t))return i.get(t);if(Array.isArray(t)){const o=new Array(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Kr(t[a],a,r,i,n);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;i.set(t,o);for(const[a,c]of t)o.set(a,Kr(c,a,r,i,n));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(Kr(a,void 0,r,i,n));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(aa(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Kr(t[a],a,r,i,n);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 i.set(t,o),ar(o,t,r,i,n),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),ar(o,t,r,i,n),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),ar(o,t,r,i,n),o}if(t instanceof Error){const o=new t.constructor;return i.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,ar(o,t,r,i,n),o}if(typeof t=="object"&&YD(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),ar(o,t,r,i,n),o}return t}function ar(t,e,r=t,i,n){const s=[...Object.keys(e),...rp(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Kr(e[a],a,r,i,n))}}function YD(t){switch(ip(t)){case ap:case LD:case jD:case MD:case op:case RD:case VD:case WD:case zD:case HD:case KD:case TD:case sp:case BD:case xD:case ND:case np:case CD:case FD:case UD:case qD:case kD:return!0;default:return!1}}function JD(t,e){return GD(t,(r,i,n,s)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case sp:case np:case op:{const o=new t.constructor(t?.valueOf());return ar(o,t),o}case ap:{const o={};return ar(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function Xu(t){return JD(t)}function el(t){return t!==null&&typeof t=="object"&&ip(t)==="[object Arguments]"}function ZD(t){return aa(t)}function QD(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 XD(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let n=t;for(let s=0;s<r.length;s++){const o=r[s];n=Po(n,o,i,new Map)}return n}function Po(t,e,r,i){if(oa(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return AD(i.get(e));if(i.set(e,t),Array.isArray(e)){e=e.slice();for(let s=0;s<e.length;s++)e[s]=e[s]??void 0}const n=[...Object.keys(e),...rp(e)];for(let s=0;s<n.length;s++){const o=n[s];let a=e[o],c=t[o];if(el(a)&&(a={...a}),el(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=Xu(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],h=Reflect.ownKeys(c);for(let d=0;d<h.length;d++){const f=h[d];l[f]=c[f]}c=l}else c=[];const u=r(c,a,o,t,e,i);u!=null?t[o]=u:Array.isArray(a)||Qu(c)&&Qu(a)?t[o]=Po(c,a,r,i):c==null&&QD(a)?t[o]=Po({},a,r,i):c==null&&ZD(a)?t[o]=Xu(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function eS(t,...e){return XD(t,...e,PD)}var tS=Object.defineProperty,rS=Object.defineProperties,iS=Object.getOwnPropertyDescriptors,tl=Object.getOwnPropertySymbols,nS=Object.prototype.hasOwnProperty,sS=Object.prototype.propertyIsEnumerable,rl=(t,e,r)=>e in t?tS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,an=(t,e)=>{for(var r in e||(e={}))nS.call(e,r)&&rl(t,r,e[r]);if(tl)for(var r of tl(e))sS.call(e,r)&&rl(t,r,e[r]);return t},oS=(t,e)=>rS(t,iS(e));function Xe(t,e,r){var i;const n=Jr(t);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${tp}?chainId=${n.namespace}:${n.reference}&projectId=${r}`}function vr(t){return t.includes(":")?t.split(":")[1]:t}function cp(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function aS(t,e){const r=Object.keys(e.namespaces).filter(n=>n.includes(t));if(!r.length)return[];const i=[];return r.forEach(n=>{const s=e.namespaces[n].accounts;i.push(...s)}),i}function cn(t={},e={}){const r=il(t),i=il(e);return eS(r,i)}function il(t){var e,r,i,n,s;const o={};if(!Jt(t))return o;for(const[a,c]of Object.entries(t)){const u=es(a)?[a]:c.chains,l=c.methods||[],h=c.events||[],d=c.rpcMap||{},f=Hr(a);o[f]=oS(an(an({},o[f]),c),{chains:Dt(u,(e=o[f])==null?void 0:e.chains),methods:Dt(l,(r=o[f])==null?void 0:r.methods),events:Dt(h,(i=o[f])==null?void 0:i.events)}),(Jt(d)||Jt(((n=o[f])==null?void 0:n.rpcMap)||{}))&&(o[f].rpcMap=an(an({},d),(s=o[f])==null?void 0:s.rpcMap))}return o}function nl(t){return t.includes(":")?t.split(":")[2]:t}function sl(t){const e={};for(const[r,i]of Object.entries(t)){const n=i.methods||[],s=i.events||[],o=i.accounts||[],a=es(r)?[r]:i.chains?i.chains:cp(i.accounts);e[r]={chains:a,methods:n,events:s,accounts:o}}return e}function Us(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 up={},Q=t=>up[t],qs=(t,e)=>{up[t]=e};var cS=Object.defineProperty,uS=(t,e,r)=>e in t?cS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xr=(t,e,r)=>uS(t,typeof e!="symbol"?e+"":e,r);class lS{constructor(e){xr(this,"name","polkadot"),xr(this,"client"),xr(this,"httpProviders"),xr(this,"events"),xr(this,"namespace"),xr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.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 i;const n=vr(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ot(new gt(i,Q("disableProviderPing")))}}var hS=Object.defineProperty,dS=Object.defineProperties,pS=Object.getOwnPropertyDescriptors,ol=Object.getOwnPropertySymbols,fS=Object.prototype.hasOwnProperty,gS=Object.prototype.propertyIsEnumerable,Ao=(t,e,r)=>e in t?hS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,al=(t,e)=>{for(var r in e||(e={}))fS.call(e,r)&&Ao(t,r,e[r]);if(ol)for(var r of ol(e))gS.call(e,r)&&Ao(t,r,e[r]);return t},cl=(t,e)=>dS(t,pS(e)),Cr=(t,e,r)=>Ao(t,typeof e!="symbol"?e+"":e,r);class yS{constructor(e){Cr(this,"name","eip155"),Cr(this,"client"),Cr(this,"chainId"),Cr(this,"namespace"),Cr(this,"httpProviders"),Cr(this,"events"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r),this.chainId=parseInt(e),this.events.emit(at.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 i=r||Xe(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ot(new gt(i,Q("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=parseInt(vr(r));e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[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,i;let n=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";n=n.startsWith("0x")?n:`0x${n}`;const s=parseInt(n,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:n}]},chainId:(i=this.namespace.chains)==null?void 0:i[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,i,n,s,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0],c=((s=(n=e.request)==null?void 0:n.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 d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:cl(al({},l.sessionProperties||{}),{capabilities:cl(al({},h||{}),{[u]:d})})})}catch(f){console.warn("Failed to update session with capabilities",f)}return d}async getCallStatus(e){var r,i;const n=this.client.session.get(e.topic),s=(r=n.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=(i=n.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,r){var i;const n=new URL(e),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Wt("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,r){return`${SD}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}}var mS=Object.defineProperty,wS=(t,e,r)=>e in t?mS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rr=(t,e,r)=>wS(t,typeof e!="symbol"?e+"":e,r);class bS{constructor(e){Rr(this,"name","solana"),Rr(this,"client"),Rr(this,"httpProviders"),Rr(this,"events"),Rr(this,"namespace"),Rr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.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 i;const n=vr(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ot(new gt(i,Q("disableProviderPing")))}}var vS=Object.defineProperty,ES=(t,e,r)=>e in t?vS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tr=(t,e,r)=>ES(t,typeof e!="symbol"?e+"":e,r);class _S{constructor(e){Tr(this,"name","cosmos"),Tr(this,"client"),Tr(this,"httpProviders"),Tr(this,"events"),Tr(this,"namespace"),Tr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=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(at.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 i;const n=vr(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ot(new gt(i,Q("disableProviderPing")))}}var IS=Object.defineProperty,$S=(t,e,r)=>e in t?IS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nr=(t,e,r)=>$S(t,typeof e!="symbol"?e+"":e,r);class OS{constructor(e){Nr(this,"name","algorand"),Nr(this,"client"),Nr(this,"httpProviders"),Nr(this,"events"),Nr(this,"namespace"),Nr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const i=r||Xe(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(at.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 i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new ot(new gt(i,Q("disableProviderPing")))}}var DS=Object.defineProperty,SS=(t,e,r)=>e in t?DS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lr=(t,e,r)=>SS(t,typeof e!="symbol"?e+"":e,r);class PS{constructor(e){Lr(this,"name","cip34"),Lr(this,"client"),Lr(this,"httpProviders"),Lr(this,"events"),Lr(this,"namespace"),Lr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.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 i=this.getCardanoRPCUrl(r),n=vr(r);e[n]=this.createHttpProvider(n,i)}),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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ot(new gt(i,Q("disableProviderPing")))}}var AS=Object.defineProperty,xS=(t,e,r)=>e in t?AS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jr=(t,e,r)=>xS(t,typeof e!="symbol"?e+"":e,r);class CS{constructor(e){jr(this,"name","elrond"),jr(this,"client"),jr(this,"httpProviders"),jr(this,"events"),jr(this,"namespace"),jr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.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 i;const n=vr(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ot(new gt(i,Q("disableProviderPing")))}}var RS=Object.defineProperty,TS=(t,e,r)=>e in t?RS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Br=(t,e,r)=>TS(t,typeof e!="symbol"?e+"":e,r);class NS{constructor(e){Br(this,"name","multiversx"),Br(this,"client"),Br(this,"httpProviders"),Br(this,"events"),Br(this,"namespace"),Br(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.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 i;const n=vr(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ot(new gt(i,Q("disableProviderPing")))}}var LS=Object.defineProperty,jS=(t,e,r)=>e in t?LS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mr=(t,e,r)=>jS(t,typeof e!="symbol"?e+"":e,r);class BS{constructor(e){Mr(this,"name","near"),Mr(this,"client"),Mr(this,"httpProviders"),Mr(this,"events"),Mr(this,"namespace"),Mr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const i=r||Xe(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(at.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 i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace);return typeof i>"u"?void 0:new ot(new gt(i,Q("disableProviderPing")))}}var MS=Object.defineProperty,FS=(t,e,r)=>e in t?MS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fr=(t,e,r)=>FS(t,typeof e!="symbol"?e+"":e,r);class US{constructor(e){Fr(this,"name","tezos"),Fr(this,"client"),Fr(this,"httpProviders"),Fr(this,"events"),Fr(this,"namespace"),Fr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const i=r||Xe(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(at.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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace);return typeof i>"u"?void 0:new ot(new gt(i))}}var qS=Object.defineProperty,kS=(t,e,r)=>e in t?qS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ur=(t,e,r)=>kS(t,typeof e!="symbol"?e+"":e,r);class zS{constructor(e){Ur(this,"name",kr),Ur(this,"client"),Ur(this,"httpProviders"),Ur(this,"events"),Ur(this,"namespace"),Ur(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.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 i={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(n=>{const s=Jr(n);i[`${s.namespace}:${s.reference}`]=this.createHttpProvider(n)}),i}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 i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ot(new gt(i,Q("disableProviderPing")))}}var HS=Object.defineProperty,KS=Object.defineProperties,VS=Object.getOwnPropertyDescriptors,ul=Object.getOwnPropertySymbols,WS=Object.prototype.hasOwnProperty,GS=Object.prototype.propertyIsEnumerable,xo=(t,e,r)=>e in t?HS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,un=(t,e)=>{for(var r in e||(e={}))WS.call(e,r)&&xo(t,r,e[r]);if(ul)for(var r of ul(e))GS.call(e,r)&&xo(t,r,e[r]);return t},ks=(t,e)=>KS(t,VS(e)),rt=(t,e,r)=>xo(t,typeof e!="symbol"?e+"":e,r);let YS=class lp{constructor(e){rt(this,"client"),rt(this,"namespaces"),rt(this,"optionalNamespaces"),rt(this,"sessionProperties"),rt(this,"scopedProperties"),rt(this,"events",new Yo),rt(this,"rpcProviders",{}),rt(this,"session"),rt(this,"providerOpts"),rt(this,"logger"),rt(this,"uri"),rt(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Bi(Mn({level:e?.logger||Zu})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new lp(e);return await r.initialize(),r}async request(e,r,i){const[n,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:un({},e),chainId:`${n}:${s}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,n){const s=new Date().getTime();this.request(e,i,n).then(o=>r(null,Hn(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:te("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:n}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const s=await n();if(this.session=s.session,this.session){const o=sl(this.session.namespaces);this.namespaces=cn(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:i}=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 n=await i();this.session=n;const s=sl(n.namespaces);return this.namespaces=cn(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[i,n]=this.validateChain(e),s=this.getProvider(i);s.name===kr?s.setDefaultChain(`${i}:${n}`,r):s.setDefaultChain(n,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(ft(r)){for(const i of r)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${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 cD.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Zu,relayUrl:this.providerOpts.relayUrl||$D,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(i){throw this.logger.error("Failed to get session",i),new Error(`The provided session: ${(r=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(r=>Hr(r)))];qs("client",this.client),qs("events",this.events),qs("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=aS(r,this.session),n=cp(i),s=cn(this.namespaces,this.optionalNamespaces),o=ks(un({},s[r]),{accounts:i,chains:n});switch(r){case"eip155":this.rpcProviders[r]=new yS({namespace:o});break;case"algorand":this.rpcProviders[r]=new OS({namespace:o});break;case"solana":this.rpcProviders[r]=new bS({namespace:o});break;case"cosmos":this.rpcProviders[r]=new _S({namespace:o});break;case"polkadot":this.rpcProviders[r]=new lS({namespace:o});break;case"cip34":this.rpcProviders[r]=new PS({namespace:o});break;case"elrond":this.rpcProviders[r]=new CS({namespace:o});break;case"multiversx":this.rpcProviders[r]=new NS({namespace:o});break;case"near":this.rpcProviders[r]=new BS({namespace:o});break;case"tezos":this.rpcProviders[r]=new US({namespace:o});break;default:this.rpcProviders[kr]?this.rpcProviders[kr].updateNamespace(o):this.rpcProviders[kr]=new zS({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:i}=e;i===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:i,topic:n}=e;if(n!==((r=this.session)==null?void 0:r.topic))return;const{event:s}=i;if(s.name==="accountsChanged"){const o=s.data;o&&ft(o)&&this.events.emit("accountsChanged",o.map(nl))}else if(s.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=Hr(o),u=Us(o)!==Us(a)?`${c}:${Us(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 i,n;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:s}=r,o=(n=this.client)==null?void 0:n.session.get(e);this.session=ks(un({},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",ks(un({},te("USER_DISCONNECTED")),{data:e.topic})))}),this.on(at.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[kr]}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:i={},sessionProperties:n,scopedProperties:s}=e;this.optionalNamespaces=cn(r,i),this.sessionProperties=n,this.scopedProperties=s}validateChain(e){const[r,i]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(o=>Hr(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const n=Hr(Object.keys(this.namespaces)[0]),s=this.rpcProviders[n].getDefaultChain();return[n,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,r=!1){if(!this.namespaces)return;const[i,n]=this.validateChain(e);if(!n)return;this.updateNamespaceChain(i,n),this.events.emit("chainChanged",n);const s=this.getProvider(i).getDefaultChain();r||this.getProvider(i).setDefaultChain(n),this.emitAccountsChangedOnChainChange({namespace:i,previousChainId:s,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:r,newChainId:i}){var n,s;try{if(r===i)return;const o=(s=(n=this.session)==null?void 0:n.namespaces[e])==null?void 0:s.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${i}:`)).map(nl);if(!ft(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 i=this.namespaces[e]?e:`${e}:${r}`,n={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=n}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 i;const n=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${on}/${e}${n}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${on}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${on}/${e}${i}`)}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 i of r)i.startsWith(on)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn("Failed to cleanup storage",r)}}};const JS=YS,ZS="wc",QS="ethereum_provider",XS=`${ZS}@2:${QS}:`,eP="https://rpc.walletconnect.org/v1/",Rn=["eth_sendTransaction","personal_sign"],hp=["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"],Tn=["chainChanged","accountsChanged"],dp=["chainChanged","accountsChanged","message","disconnect","connect"],tP=async()=>{const{createAppKit:t}=await _p(()=>import("./core-CKL2t7br.js").then(e=>e.G),__vite__mapDeps([0,1,2,3,4]));return t};var rP=Object.defineProperty,iP=Object.defineProperties,nP=Object.getOwnPropertyDescriptors,ll=Object.getOwnPropertySymbols,sP=Object.prototype.hasOwnProperty,oP=Object.prototype.propertyIsEnumerable,Co=(t,e,r)=>e in t?rP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ir=(t,e)=>{for(var r in e||(e={}))sP.call(e,r)&&Co(t,r,e[r]);if(ll)for(var r of ll(e))oP.call(e,r)&&Co(t,r,e[r]);return t},vi=(t,e)=>iP(t,nP(e)),Ge=(t,e,r)=>Co(t,typeof e!="symbol"?e+"":e,r);function Nn(t){return Number(t[0].split(":")[1])}function ln(t){return`0x${t.toString(16)}`}function aP(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:n,events:s,optionalEvents:o,rpcMap:a}=t;if(!ft(e))throw new Error("Invalid chains");const c={chains:e,methods:i||Rn,events:s||Tn,rpcMap:ir({},e.length?{[Nn(e)]:a[Nn(e)]}:{})},u=s?.filter(f=>!Tn.includes(f)),l=i?.filter(f=>!Rn.includes(f));if(!r&&!o&&!n&&!(u!=null&&u.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const h=u?.length&&l?.length||!r,d={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(n!=null&&n.length?n:hp))],events:[...new Set(c.events.concat(o!=null&&o.length?o:dp))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?d:void 0}}class ns{constructor(){Ge(this,"events",new Ut.EventEmitter),Ge(this,"namespace","eip155"),Ge(this,"accounts",[]),Ge(this,"signer"),Ge(this,"chainId",1),Ge(this,"modal"),Ge(this,"rpc"),Ge(this,"STORAGE_KEY",XS),Ge(this,"on",(e,r)=>(this.events.on(e,r),this)),Ge(this,"once",(e,r)=>(this.events.once(e,r),this)),Ge(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),Ge(this,"off",(e,r)=>(this.events.off(e,r),this)),Ge(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new ns;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:n}=aP(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(d=>{!d.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(vi(ir({namespaces:ir({},i&&{[this.namespace]:i})},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e?.pairingTopic,scopedProperties:h})).then(d=>{a(d)}).catch(d=>{var f;(f=this.modal)==null||f.showErrorMessage("Unable to connect"),c(new Error(d.message))})});if(!s)return;const o=yc(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ln(this.chainId)})}catch(s){throw this.signer.logger.error(s),s}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const n=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(vi(ir({},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=n.session;if(s){const o=yc(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ln(this.chainId)})}return n}catch(n){throw this.signer.logger.error(n),n}finally{(i=this.modal)==null||i.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:i}=r;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",ln(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",vi(ir({},te("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",ln(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,i,n]=e.split(":");return{chainId:`${r}:${i}`,address:n}}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,i;const n=(r=e?.chains)!=null?r:[],s=(i=e?.optionalChains)!=null?i:[],o=n.concat(s);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=n.length?e?.methods||Rn:[],c=n.length?e?.events||Tn:[],u=e?.optionalMethods||[],l=e?.optionalEvents||[],h=e?.rpcMap||this.buildRpcMap(o,e.projectId),d=e?.qrModalOptions||void 0;return{chains:n?.map(f=>this.formatChainId(f)),optionalChains:s.map(f=>this.formatChainId(f)),methods:a,events:c,optionalMethods:u,optionalEvents:l,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:d,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(n=>{i[n]=this.getRpcUrl(n,r)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Nn(this.rpc.chains):Nn(this.rpc.optionalChains),this.signer=await JS.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 i=await tP(),{convertWCMToAppKitOptions:n}=await Promise.resolve().then(function(){return wP}),s=n(vi(ir({},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=i(vi(ir({},s),{universalProvider:this.signer,manualWCControl:!0}))}catch(i){throw console.warn(i),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:n}=e;r&&ft(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=n?.[s]||this.getRpcUrl(s)})),i&&ft(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(s=>this.formatChainId(s)),i.forEach(s=>{this.rpc.rpcMap[s]=n?.[s]||this.getRpcUrl(s)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${eP}?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 cP=ns;var uP=Object.defineProperty,lP=Object.defineProperties,hP=Object.getOwnPropertyDescriptors,hl=Object.getOwnPropertySymbols,dP=Object.prototype.hasOwnProperty,pP=Object.prototype.propertyIsEnumerable,dl=(t,e,r)=>e in t?uP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pp=(t,e)=>{for(var r in e||(e={}))dP.call(e,r)&&dl(t,r,e[r]);if(hl)for(var r of hl(e))pP.call(e,r)&&dl(t,r,e[r]);return t},fP=(t,e)=>lP(t,hP(e));function gP(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 yP=t=>{const[e,r]=t.split(":");return fp({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function mP(t){var e,r,i,n,s,o,a;const c=(e=t.chains)==null?void 0:e.map(yP).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const u=c.find(h=>{var d;return h.id===((d=t.defaultChain)==null?void 0:d.id)}),l={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:gP(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:u,metadata:fP(pp({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((i=t.metadata)==null?void 0:i.description)||"Connect to WalletConnect-compatible wallets",url:((n=t.metadata)==null?void 0:n.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(p=>({id:p.id,name:p.name,links:p.links})),...(t.desktopWallets||[]).map(p=>({id:p.id,name:p.name,links:{native:p.links.native,universal:p.links.universal}}))],d=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],f=h.filter(p=>!d.includes(p.id));f.length&&(l.customWallets=f)}return l}function fp(t){return pp({formatters:void 0,fees:void 0,serializers:void 0},t)}var wP=Object.freeze({__proto__:null,convertWCMToAppKitOptions:mP,defineChain:fp});const oA=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:cP,OPTIONAL_EVENTS:dp,OPTIONAL_METHODS:hp,REQUIRED_EVENTS:Tn,REQUIRED_METHODS:Rn,default:ns},Symbol.toStringTag,{value:"Module"}));export{Wf as A,Bi as B,ob as C,Et as D,Fe as E,gt as F,oA as G,yr as I,Ja as P,rh as Q,hr as a,tc as b,N as c,Gi as d,dr as e,ko as f,nh as g,Wm as h,ih as i,Qs as j,Mn as k,df as l,cv as m,Vo as n,ot as o,Vn as p,Hn as q,mr as r,Ft as s,Wt as t,Mm as u,cr as v,Kn as w,_t as x,Ve as y,nt as z};
|