@dcl/top-scenes 1.0.2 → 1.0.3

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.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/core-D5PQaXFb.js","assets/index-gEo3Pl4_.js"])))=>i.map(i=>d[i]);
2
- import{g as Tf,e as xt,c as Ft,x as uc,a as Dy,_ as Ay}from"./index-gEo3Pl4_.js";var ul=function(t,e,r){if(r||arguments.length===2)for(var i=0,s=e.length,n;i<s;i++)(n||!(i in e))&&(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))},Py=function(){function t(e,r,i){this.name=e,this.version=r,this.os=i,this.type="browser"}return t}(),By=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),Cy=function(){function t(e,r,i,s){this.name=e,this.version=r,this.os=i,this.bot=s,this.type="bot-device"}return t}(),Ty=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),Ry=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),Uy=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Ny=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,hl=3,ky=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",Uy]],fl=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function jy(t){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Ry:typeof navigator<"u"?Ly(navigator.userAgent):qy()}function Fy(t){return t!==""&&ky.reduce(function(e,r){var i=r[0],s=r[1];if(e)return e;var n=s.exec(t);return!!n&&[i,n]},!1)}function Ly(t){var e=Fy(t);if(!e)return null;var r=e[0],i=e[1];if(r==="searchbot")return new Ty;var s=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);s?s.length<hl&&(s=ul(ul([],s,!0),zy(hl-s.length),!0)):s=[];var n=s.join("."),o=My(t),a=Ny.exec(t);return a&&a[1]?new Cy(r,n,o,a[1]):new Py(r,n,o)}function My(t){for(var e=0,r=fl.length;e<r;e++){var i=fl[e],s=i[0],n=i[1],o=n.exec(t);if(o)return s}return null}function qy(){var t=typeof process<"u"&&process.version;return t?new By(process.version.slice(1)):null}function zy(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var q={};/*! *****************************************************************************
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/core-XnCYF3S5.js","assets/index-7knOmhlQ.js"])))=>i.map(i=>d[i]);
2
+ import{g as Tf,e as xt,c as Ft,x as uc,a as Dy,_ as Ay}from"./index-7knOmhlQ.js";var ul=function(t,e,r){if(r||arguments.length===2)for(var i=0,s=e.length,n;i<s;i++)(n||!(i in e))&&(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))},Py=function(){function t(e,r,i){this.name=e,this.version=r,this.os=i,this.type="browser"}return t}(),By=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),Cy=function(){function t(e,r,i,s){this.name=e,this.version=r,this.os=i,this.bot=s,this.type="bot-device"}return t}(),Ty=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),Ry=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),Uy=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Ny=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,hl=3,ky=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",Uy]],fl=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function jy(t){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Ry:typeof navigator<"u"?Ly(navigator.userAgent):qy()}function Fy(t){return t!==""&&ky.reduce(function(e,r){var i=r[0],s=r[1];if(e)return e;var n=s.exec(t);return!!n&&[i,n]},!1)}function Ly(t){var e=Fy(t);if(!e)return null;var r=e[0],i=e[1];if(r==="searchbot")return new Ty;var s=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);s?s.length<hl&&(s=ul(ul([],s,!0),zy(hl-s.length),!0)):s=[];var n=s.join("."),o=My(t),a=Ny.exec(t);return a&&a[1]?new Cy(r,n,o,a[1]):new Py(r,n,o)}function My(t){for(var e=0,r=fl.length;e<r;e++){var i=fl[e],s=i[0],n=i[1],o=n.exec(t);if(o)return s}return null}function qy(){var t=typeof process<"u"&&process.version;return t?new By(process.version.slice(1)):null}function zy(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var q={};/*! *****************************************************************************
3
3
  Copyright (c) Microsoft Corporation.
4
4
 
5
5
  Permission to use, copy, modify, and/or distribute this software for any
@@ -38,4 +38,4 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
38
38
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
39
39
  PERFORMANCE OF THIS SOFTWARE.
40
40
  ***************************************************************************** */var Va=function(t,e){return Va=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},Va(t,e)};function q8(t,e){Va(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Ha=function(){return Ha=Object.assign||function(e){for(var r,i=1,s=arguments.length;i<s;i++){r=arguments[i];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Ha.apply(this,arguments)};function z8(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(r[i[s]]=t[i[s]]);return r}function V8(t,e,r,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(n=(s<3?o(n):s>3?o(e,r,n):o(e,r))||n);return s>3&&n&&Object.defineProperty(e,r,n),n}function H8(t,e){return function(r,i){e(r,i,t)}}function K8(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function W8(t,e,r,i){function s(n){return n instanceof r?n:new r(function(o){o(n)})}return new(r||(r=Promise))(function(n,o){function a(u){try{l(i.next(u))}catch(h){o(h)}}function c(u){try{l(i.throw(u))}catch(h){o(h)}}function l(u){u.done?n(u.value):s(u.value).then(a,c)}l((i=i.apply(t,e||[])).next())})}function G8(t,e){var r={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},i,s,n,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,s&&(n=l[0]&2?s.return:l[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,l[1])).done)return n;switch(s=0,n&&(l=[l[0]&2,n.value]),l[0]){case 0:case 1:n=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,s=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(n=r.trys,!(n=n.length>0&&n[n.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!n||l[1]>n[0]&&l[1]<n[3])){r.label=l[1];break}if(l[0]===6&&r.label<n[1]){r.label=n[1],n=l;break}if(n&&r.label<n[2]){r.label=n[2],r.ops.push(l);break}n[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],s=0}finally{i=n=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Y8(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function Z8(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Ka(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ug(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=i.next()).done;)n.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return n}function J8(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Ug(arguments[e]));return t}function X8(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),s=0,e=0;e<r;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)i[s]=n[o];return i}function Es(t){return this instanceof Es?(this.v=t,this):new Es(t)}function Q8(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){i[f]&&(s[f]=function(d){return new Promise(function(g,w){n.push([f,d,g,w])>1||a(f,d)})})}function a(f,d){try{c(i[f](d))}catch(g){h(n[0][3],g)}}function c(f){f.value instanceof Es?Promise.resolve(f.value.v).then(l,u):h(n[0][2],f)}function l(f){a("next",f)}function u(f){a("throw",f)}function h(f,d){f(d),n.shift(),n.length&&a(n[0][0],n[0][1])}}function eO(t){var e,r;return e={},i("next"),i("throw",function(s){throw s}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(s,n){e[s]=t[s]?function(o){return(r=!r)?{value:Es(t[s](o)),done:s==="return"}:n?n(o):o}:n}}function tO(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Ka=="function"?Ka(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(n){r[n]=t[n]&&function(o){return new Promise(function(a,c){o=t[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(l){n({value:l,done:a})},o)}}function rO(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function iO(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function sO(t){return t&&t.__esModule?t:{default:t}}function nO(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function oO(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}const aO=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Ha},__asyncDelegator:eO,__asyncGenerator:Q8,__asyncValues:tO,__await:Es,__awaiter:W8,__classPrivateFieldGet:nO,__classPrivateFieldSet:oO,__createBinding:Y8,__decorate:V8,__exportStar:Z8,__extends:q8,__generator:G8,__importDefault:sO,__importStar:iO,__makeTemplateObject:rO,__metadata:K8,__param:H8,__read:Ug,__rest:z8,__spread:J8,__spreadArrays:X8,__values:Ka},Symbol.toStringTag,{value:"Module"})),cO=Tf(aO);var Xt={},Ih;function lO(){if(Ih)return Xt;Ih=1,Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.isBrowserCryptoAvailable=Xt.getSubtleCrypto=Xt.getBrowerCrypto=void 0;function t(){return(Ft===null||Ft===void 0?void 0:Ft.crypto)||(Ft===null||Ft===void 0?void 0:Ft.msCrypto)||{}}Xt.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}Xt.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Xt.isBrowserCryptoAvailable=r,Xt}var Qt={},Sh;function uO(){if(Sh)return Qt;Sh=1,Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.isBrowser=Qt.isNode=Qt.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Qt.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Qt.isNode=e;function r(){return!t()&&!e()}return Qt.isBrowser=r,Qt}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=cO;e.__exportStar(lO(),t),e.__exportStar(uO(),t)})(Rg);function kt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Cr(t=6){return BigInt(kt(t))}function Dt(t,e,r){return{id:r||kt(),jsonrpc:"2.0",method:t,params:e}}function xs(t,e){return{id:t,jsonrpc:"2.0",result:e}}function ro(t,e,r){return{id:t,jsonrpc:"2.0",error:hO(e)}}function hO(t,e){return typeof t>"u"?_h(Bg):(typeof t=="string"&&(t=Object.assign(Object.assign({},_h(Gc)),{message:t})),L8(t.code)&&(t=M8(t.code)),t)}class fO{}class dO extends fO{constructor(){super()}}class pO extends dO{constructor(e){super()}}const gO="^https?:",yO="^wss?:";function wO(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Ng(t,e){const r=wO(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Oh(t){return Ng(t,gO)}function $h(t){return Ng(t,yO)}function mO(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function kg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Yc(t){return kg(t)&&"method"in t}function io(t){return kg(t)&&(jt(t)||mt(t))}function jt(t){return"result"in t}function mt(t){return"error"in t}let Zc=class extends pO{constructor(e){super(e),this.events=new xt.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Dt(e.method,e.params||[],e.id||Cr().toString()),r)}async requestStrict(e,r){return new Promise(async(i,s)=>{if(!this.connection.connected)try{await this.open()}catch(n){s(n)}this.events.on(`${e.id}`,n=>{mt(n)?s(n.error):i(n.result)});try{await this.connection.send(e,r)}catch(n){s(n)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),io(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}};const bO=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),vO=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Dh=t=>t.split("?")[0],Ah=10,EO=bO();let xO=class{constructor(e){if(this.url=e,this.events=new xt.EventEmitter,this.registering=!1,!$h(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(si(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!$h(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return s(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,i)=>{const s=Rg.isReactNative()?void 0:{rejectUnauthorized:!mO(e)},n=new EO(e,[],s);vO()?n.onerror=o=>{const a=o;i(this.emitError(a.error))}:n.on("error",o=>{i(this.emitError(o))}),n.onopen=()=>{this.onOpen(n),r(n)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ii(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),s=i.message||i.toString(),n=ro(e,s);this.events.emit("payload",n)}parseError(e,r=this.url){return Tg(e,Dh(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Ah&&this.events.setMaxListeners(Ah)}emitError(e){const r=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${Dh(this.url)}`));return this.events.emit("register_error",r),r}};var _O={VITE_SEGMENT_PROD_API_KEY:"J46ds5KOLHjFZ1GJQCYm4oNXpeWy9hpV"};const jg="wc",Fg=2,Wa="core",Ht=`${jg}@2:${Wa}:`,IO={logger:"error"},SO={database:":memory:"},OO="crypto",Ph="client_ed25519_seed",$O=q.ONE_DAY,DO="keychain",AO="0.3",PO="messages",BO="0.3",CO=q.SIX_HOURS,TO="publisher",Lg="irn",RO="error",Mg="wss://relay.walletconnect.org",UO="relayer",ye={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"},NO="_subscription",dt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},kO=.1,Ga="2.23.1",le={link_mode:"link_mode",relay:"relay"},dn={inbound:"inbound",outbound:"outbound"},jO="0.3",FO="WALLETCONNECT_CLIENT_ID",Bh="WALLETCONNECT_LINK_MODE_APPS",at={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},LO="subscription",MO="0.3",qO="pairing",zO="0.3",Ji={wc_pairingDelete:{req:{ttl:q.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:q.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:q.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:q.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:q.ONE_DAY,prompt:!1,tag:0},res:{ttl:q.ONE_DAY,prompt:!1,tag:0}}},Wr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},It={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},VO="history",HO="0.3",KO="expirer",gt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},WO="0.3",GO="verify-api",YO="https://verify.walletconnect.com",qg="https://verify.walletconnect.org",hs=qg,ZO=`${hs}/v3`,JO=[YO,qg],XO="echo",QO="https://echo.walletconnect.com",Nt={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"},tr={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"},St={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",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},Mr={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",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},qr={authenticated_session_approve_started:"authenticated_session_approve_started",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve"},Xi={no_internet_connection:"no_internet_connection",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},e$=.1,t$="event-client",r$=86400,i$="https://pulse.walletconnect.org/batch";function s$(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 s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var w=0,m=0,O=0,C=g.length;O!==C&&g[O]===0;)O++,w++;for(var b=(C-O)*u+1>>>0,x=new Uint8Array(b);O!==C;){for(var A=g[O],B=0,T=b-1;(A!==0||B<m)&&T!==-1;T--,B++)A+=256*x[T]>>>0,x[T]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");m=B,O++}for(var R=b-m;R!==b&&x[R]===0;)R++;for(var D=c.repeat(w);R<b;++R)D+=t.charAt(x[R]);return D}function f(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var w=0;if(g[w]!==" "){for(var m=0,O=0;g[w]===c;)m++,w++;for(var C=(g.length-w)*l+1>>>0,b=new Uint8Array(C);g[w];){var x=r[g.charCodeAt(w)];if(x===255)return;for(var A=0,B=C-1;(x!==0||A<O)&&B!==-1;B--,A++)x+=a*b[B]>>>0,b[B]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");O=A,w++}if(g[w]!==" "){for(var T=C-O;T!==C&&b[T]===0;)T++;for(var R=new Uint8Array(m+(C-T)),D=m;T!==C;)R[D++]=b[T++];return R}}}function d(g){var w=f(g);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var n$=s$,o$=n$;const zg=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")},a$=t=>new TextEncoder().encode(t),c$=t=>new TextDecoder().decode(t);class l${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 u${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 Vg(this,e)}}class h${constructor(e){this.decoders=e}or(e){return Vg(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 Vg=(t,e)=>new h$({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class f${constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new l$(e,r,i),this.decoder=new u$(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const so=({name:t,prefix:e,encode:r,decode:i})=>new f$(t,e,r,i),Rs=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=o$(r,e);return so({prefix:t,name:e,encode:i,decode:n=>zg(s(n))})},d$=(t,e,r,i)=>{const s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,l=0;for(let u=0;u<n;++u){const h=s[t[u]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},p$=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Ue=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>so({prefix:e,name:t,encode(s){return p$(s,i,r)},decode(s){return d$(s,i,r,t)}}),g$=so({prefix:"\0",name:"identity",encode:t=>c$(t),decode:t=>a$(t)});var y$=Object.freeze({__proto__:null,identity:g$});const w$=Ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var m$=Object.freeze({__proto__:null,base2:w$});const b$=Ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var v$=Object.freeze({__proto__:null,base8:b$});const E$=Rs({prefix:"9",name:"base10",alphabet:"0123456789"});var x$=Object.freeze({__proto__:null,base10:E$});const _$=Ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),I$=Ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var S$=Object.freeze({__proto__:null,base16:_$,base16upper:I$});const O$=Ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$$=Ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),D$=Ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),A$=Ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),P$=Ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),B$=Ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),C$=Ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),T$=Ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),R$=Ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var U$=Object.freeze({__proto__:null,base32:O$,base32upper:$$,base32pad:D$,base32padupper:A$,base32hex:P$,base32hexupper:B$,base32hexpad:C$,base32hexpadupper:T$,base32z:R$});const N$=Rs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),k$=Rs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var j$=Object.freeze({__proto__:null,base36:N$,base36upper:k$});const F$=Rs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),L$=Rs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var M$=Object.freeze({__proto__:null,base58btc:F$,base58flickr:L$});const q$=Ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),z$=Ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),V$=Ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),H$=Ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var K$=Object.freeze({__proto__:null,base64:q$,base64pad:z$,base64url:V$,base64urlpad:H$});const Hg=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),W$=Hg.reduce((t,e,r)=>(t[r]=e,t),[]),G$=Hg.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Y$(t){return t.reduce((e,r)=>(e+=W$[r],e),"")}function Z$(t){const e=[];for(const r of t){const i=G$[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const J$=so({prefix:"🚀",name:"base256emoji",encode:Y$,decode:Z$});var X$=Object.freeze({__proto__:null,base256emoji:J$}),Q$=Kg,Ch=128,eD=-128,tD=Math.pow(2,31);function Kg(t,e,r){e=e||[],r=r||0;for(var i=r;t>=tD;)e[r++]=t&255|Ch,t/=128;for(;t&eD;)e[r++]=t&255|Ch,t>>>=7;return e[r]=t|0,Kg.bytes=r-i+1,e}var rD=Ya,iD=128,Th=127;function Ya(t,i){var r=0,i=i||0,s=0,n=i,o,a=t.length;do{if(n>=a)throw Ya.bytes=0,new RangeError("Could not decode varint");o=t[n++],r+=s<28?(o&Th)<<s:(o&Th)*Math.pow(2,s),s+=7}while(o>=iD);return Ya.bytes=n-i,r}var sD=Math.pow(2,7),nD=Math.pow(2,14),oD=Math.pow(2,21),aD=Math.pow(2,28),cD=Math.pow(2,35),lD=Math.pow(2,42),uD=Math.pow(2,49),hD=Math.pow(2,56),fD=Math.pow(2,63),dD=function(t){return t<sD?1:t<nD?2:t<oD?3:t<aD?4:t<cD?5:t<lD?6:t<uD?7:t<hD?8:t<fD?9:10},pD={encode:Q$,decode:rD,encodingLength:dD},Wg=pD;const Rh=(t,e,r=0)=>(Wg.encode(t,e,r),e),Uh=t=>Wg.encodingLength(t),Za=(t,e)=>{const r=e.byteLength,i=Uh(t),s=i+Uh(r),n=new Uint8Array(s+r);return Rh(t,n,0),Rh(r,n,i),n.set(e,s),new gD(t,r,e,n)};class gD{constructor(e,r,i,s){this.code=e,this.size=r,this.digest=i,this.bytes=s}}const Gg=({name:t,code:e,encode:r})=>new yD(t,e,r);class yD{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?Za(this.code,r):r.then(i=>Za(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Yg=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),wD=Gg({name:"sha2-256",code:18,encode:Yg("SHA-256")}),mD=Gg({name:"sha2-512",code:19,encode:Yg("SHA-512")});var bD=Object.freeze({__proto__:null,sha256:wD,sha512:mD});const Zg=0,vD="identity",Jg=zg,ED=t=>Za(Zg,Jg(t)),xD={code:Zg,name:vD,encode:Jg,digest:ED};var _D=Object.freeze({__proto__:null,identity:xD});new TextEncoder,new TextDecoder;const Nh={...y$,...m$,...v$,...x$,...S$,...U$,...j$,...M$,...K$,...X$};({...bD,..._D});function Xg(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function ID(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Xg(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Qg(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const kh=Qg("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Jo=Qg("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=ID(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),SD={utf8:kh,"utf-8":kh,hex:Nh.base16,latin1:Jo,ascii:Jo,binary:Jo,...Nh};function OD(t,e="utf8"){const r=SD[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Xg(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var $D=Object.defineProperty,DD=(t,e,r)=>e in t?$D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rt=(t,e,r)=>DD(t,typeof e!="symbol"?e+"":e,r);class AD{constructor(e,r){this.core=e,this.logger=r,Rt(this,"keychain",new Map),Rt(this,"name",DO),Rt(this,"version",AO),Rt(this,"initialized",!1),Rt(this,"storagePrefix",Ht),Rt(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Rt(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Rt(this,"set",async(i,s)=>{this.isInitialized(),this.keychain.set(i,s),await this.persist()}),Rt(this,"get",i=>{this.isInitialized();const s=this.keychain.get(i);if(typeof s>"u"){const{message:n}=z("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return s}),Rt(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=ht(r,this.name)}get context(){return it(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Aa(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Pa(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var PD=Object.defineProperty,BD=(t,e,r)=>e in t?PD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xe=(t,e,r)=>BD(t,typeof e!="symbol"?e+"":e,r);class CD{constructor(e,r,i){this.core=e,this.logger=r,xe(this,"name",OO),xe(this,"keychain"),xe(this,"randomSessionIdentifier",Ma()),xe(this,"initialized",!1),xe(this,"clientId"),xe(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),xe(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),xe(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const s=await this.getClientSeed(),n=cu(s),o=ep(n.publicKey);return this.clientId=o,o}),xe(this,"generateKeyPair",()=>{this.isInitialized();const s=gI();return this.setPrivateKey(s.publicKey,s.privateKey)}),xe(this,"signJWT",async s=>{this.isInitialized();const n=await this.getClientSeed(),o=cu(n),a=this.randomSessionIdentifier;return await u2(a,s,$O,o)}),xe(this,"generateSharedKey",(s,n,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=yI(a,n);return this.setSymKey(c,o)}),xe(this,"setSymKey",async(s,n)=>{this.isInitialized();const o=n||un(s);return await this.keychain.set(o,s),o}),xe(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),xe(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),xe(this,"encode",async(s,n,o)=>{this.isInitialized();const a=Sg(o),c=si(n);if(rh(a))return bI(c,o==null?void 0:o.encoding);if(th(a)){const f=a.senderPublicKey,d=a.receiverPublicKey;s=await this.generateSharedKey(f,d)}const l=this.getSymKey(s),{type:u,senderPublicKey:h}=a;return wI({type:u,symKey:l,message:c,senderPublicKey:h,encoding:o==null?void 0:o.encoding})}),xe(this,"decode",async(s,n,o)=>{this.isInitialized();const a=EI(n,o);if(rh(a)){const c=vI(n,o==null?void 0:o.encoding);return ii(c)}if(th(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;s=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(s),l=mI({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return ii(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),xe(this,"getPayloadType",(s,n=Qe)=>{const o=vs({encoded:s,encoding:n});return oi(o.type)}),xe(this,"getPayloadSenderPublicKey",(s,n=Qe)=>{const o=vs({encoded:s,encoding:n});return o.senderPublicKey?rt(o.senderPublicKey,Ke):void 0}),this.core=e,this.logger=ht(r,this.name),this.keychain=i||new AD(this.core,this.logger)}get context(){return it(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(Ph)}catch{e=Ma(),await this.keychain.set(Ph,e)}return OD(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var TD=Object.defineProperty,RD=Object.defineProperties,UD=Object.getOwnPropertyDescriptors,jh=Object.getOwnPropertySymbols,ND=Object.prototype.hasOwnProperty,kD=Object.prototype.propertyIsEnumerable,Ja=(t,e,r)=>e in t?TD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jD=(t,e)=>{for(var r in e||(e={}))ND.call(e,r)&&Ja(t,r,e[r]);if(jh)for(var r of jh(e))kD.call(e,r)&&Ja(t,r,e[r]);return t},FD=(t,e)=>RD(t,UD(e)),st=(t,e,r)=>Ja(t,typeof e!="symbol"?e+"":e,r);class LD extends x8{constructor(e,r){super(e,r),this.logger=e,this.core=r,st(this,"messages",new Map),st(this,"messagesWithoutClientAck",new Map),st(this,"name",PO),st(this,"version",BO),st(this,"initialized",!1),st(this,"storagePrefix",Ht),st(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const s=await this.getRelayerMessagesWithoutClientAck();typeof s<"u"&&(this.messagesWithoutClientAck=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),st(this,"set",async(i,s,n)=>{this.isInitialized();const o=wt(s);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(i,a),n===dn.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,FD(jD({},c),{[o]:s}))}return await this.persist(),o}),st(this,"get",i=>{this.isInitialized();let s=this.messages.get(i);return typeof s>"u"&&(s={}),s}),st(this,"getWithoutAck",i=>{this.isInitialized();const s={};for(const n of i){const o=this.messagesWithoutClientAck.get(n)||{};s[n]=Object.values(o)}return s}),st(this,"has",(i,s)=>{this.isInitialized();const n=this.get(i),o=wt(s);return typeof n[o]<"u"}),st(this,"ack",async(i,s)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(i);if(typeof n>"u")return;const o=wt(s);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,n),await this.persist()}),st(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=ht(e,this.name),this.core=r}get context(){return it(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,Aa(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Aa(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Pa(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Pa(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var MD=Object.defineProperty,qD=Object.defineProperties,zD=Object.getOwnPropertyDescriptors,Fh=Object.getOwnPropertySymbols,VD=Object.prototype.hasOwnProperty,HD=Object.prototype.propertyIsEnumerable,Xa=(t,e,r)=>e in t?MD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,mi=(t,e)=>{for(var r in e||(e={}))VD.call(e,r)&&Xa(t,r,e[r]);if(Fh)for(var r of Fh(e))HD.call(e,r)&&Xa(t,r,e[r]);return t},Lh=(t,e)=>qD(t,zD(e)),pt=(t,e,r)=>Xa(t,typeof e!="symbol"?e+"":e,r);class KD extends _8{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,pt(this,"events",new xt.EventEmitter),pt(this,"name",TO),pt(this,"queue",new Map),pt(this,"publishTimeout",q.toMiliseconds(q.ONE_MINUTE)),pt(this,"initialPublishTimeout",q.toMiliseconds(q.ONE_SECOND*15)),pt(this,"needsTransportRestart",!1),pt(this,"publish",async(i,s,n)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:s,opts:n}});const h=(n==null?void 0:n.ttl)||CO,f=(n==null?void 0:n.prompt)||!1,d=(n==null?void 0:n.tag)||0,g=(n==null?void 0:n.id)||Cr().toString(),w=_i(Cn().protocol),m={id:g,method:(n==null?void 0:n.publishMethod)||w.publish,params:mi({topic:i,message:s,ttl:h,prompt:f,tag:d,attestation:n==null?void 0:n.attestation},n==null?void 0:n.tvf)},O=`Failed to publish payload, please try again. id:${g} tag:${d}`;try{Oe((o=m.params)==null?void 0:o.prompt)&&((a=m.params)==null||delete a.prompt),Oe((c=m.params)==null?void 0:c.tag)&&((l=m.params)==null||delete l.tag);const C=new Promise(async b=>{const x=({id:B})=>{var T;((T=m.id)==null?void 0:T.toString())===B.toString()&&(this.removeRequestFromQueue(B),this.relayer.events.removeListener(ye.publish,x),b())};this.relayer.events.on(ye.publish,x);const A=qt(new Promise((B,T)=>{this.rpcPublish(m,n).then(B).catch(R=>{this.logger.warn(R,R==null?void 0:R.message),T(R)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${g} tag:${d}`);try{await A,this.events.removeListener(ye.publish,x)}catch(B){this.queue.set(g,{request:m,opts:n,attempt:1}),this.logger.warn(B,B==null?void 0:B.message)}});this.logger.trace({type:"method",method:"publish",params:{id:g,topic:i,message:s,opts:n}}),await qt(C,this.publishTimeout,O)}catch(C){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(C),(u=n==null?void 0:n.internal)!=null&&u.throwOnFailedPublish)throw C}finally{this.queue.delete(g)}}),pt(this,"publishCustom",async i=>{var s,n,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:i});const{payload:l,opts:u={}}=i,{attestation:h,tvf:f,publishMethod:d,prompt:g,tag:w,ttl:m=q.FIVE_MINUTES}=u,O=u.id||Cr().toString(),C=_i(Cn().protocol),b=d||C.publish,x={id:O,method:b,params:mi(Lh(mi({},l),{ttl:m,prompt:g,tag:w,attestation:h}),f)},A=`Failed to publish custom payload, please try again. id:${O} tag:${w}`;try{Oe((s=x.params)==null?void 0:s.prompt)&&((n=x.params)==null||delete n.prompt),Oe((o=x.params)==null?void 0:o.tag)&&((a=x.params)==null||delete a.tag);const B=new Promise(async T=>{const R=({id:k})=>{var j;((j=x.id)==null?void 0:j.toString())===k.toString()&&(this.removeRequestFromQueue(k),this.relayer.events.removeListener(ye.publish,R),T())};this.relayer.events.on(ye.publish,R);const D=qt(new Promise((k,j)=>{this.rpcPublish(x,u).then(k).catch(P=>{this.logger.warn(P,P==null?void 0:P.message),j(P)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${b} id:${O} tag:${w}`);try{await D,this.events.removeListener(ye.publish,R)}catch(k){this.queue.set(O,{request:x,opts:u,attempt:1}),this.logger.warn(k,k==null?void 0:k.message)}});this.logger.trace({type:"method",method:"publish",params:{id:O,payload:l,opts:u}}),await qt(B,this.publishTimeout,A)}catch(B){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(B),(c=u==null?void 0:u.internal)!=null&&c.throwOnFailedPublish)throw B}finally{this.queue.delete(O)}}),pt(this,"on",(i,s)=>{this.events.on(i,s)}),pt(this,"once",(i,s)=>{this.events.once(i,s)}),pt(this,"off",(i,s)=>{this.events.off(i,s)}),pt(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.relayer=e,this.logger=ht(r,this.name),this.registerEventListeners()}get context(){return it(this.logger)}async rpcPublish(e,r){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const i=await this.relayer.request(e);return this.relayer.events.emit(ye.publish,mi(mi({},e),r)),this.logger.debug("Successfully Published Payload"),i}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{var i;const s=e.attempt+1;this.queue.set(r,Lh(mi({},e),{attempt:s})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(i=e.request.params)==null?void 0:i.tag}, attempt: ${s}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(ui.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(ye.connection_stalled);return}this.checkQueue()}),this.relayer.on(ye.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var WD=Object.defineProperty,GD=(t,e,r)=>e in t?WD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bi=(t,e,r)=>GD(t,typeof e!="symbol"?e+"":e,r);class YD{constructor(){bi(this,"map",new Map),bi(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),bi(this,"get",e=>this.map.get(e)||[]),bi(this,"exists",(e,r)=>this.get(e).includes(r)),bi(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 s=i.filter(n=>n!==r);if(!s.length){this.map.delete(e);return}this.map.set(e,s)}),bi(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var ZD=Object.defineProperty,JD=Object.defineProperties,XD=Object.getOwnPropertyDescriptors,Mh=Object.getOwnPropertySymbols,QD=Object.prototype.hasOwnProperty,eA=Object.prototype.propertyIsEnumerable,Qa=(t,e,r)=>e in t?ZD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Qi=(t,e)=>{for(var r in e||(e={}))QD.call(e,r)&&Qa(t,r,e[r]);if(Mh)for(var r of Mh(e))eA.call(e,r)&&Qa(t,r,e[r]);return t},Xo=(t,e)=>JD(t,XD(e)),oe=(t,e,r)=>Qa(t,typeof e!="symbol"?e+"":e,r);class tA extends O8{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,oe(this,"subscriptions",new Map),oe(this,"topicMap",new YD),oe(this,"events",new xt.EventEmitter),oe(this,"name",LO),oe(this,"version",MO),oe(this,"pending",new Map),oe(this,"cached",[]),oe(this,"initialized",!1),oe(this,"storagePrefix",Ht),oe(this,"subscribeTimeout",q.toMiliseconds(q.ONE_MINUTE)),oe(this,"initialSubscribeTimeout",q.toMiliseconds(q.ONE_SECOND*15)),oe(this,"clientId"),oe(this,"batchSubscribeTopicsLimit",500),oe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),oe(this,"subscribe",async(i,s)=>{var n;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}});try{const o=Cn(s),a={topic:i,relay:o,transportType:s==null?void 0:s.transportType};(n=s==null?void 0:s.internal)!=null&&n.skipSubscribe||this.pending.set(i,a);const c=await this.rpcSubscribe(i,o,s);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),oe(this,"unsubscribe",async(i,s)=>{this.isInitialized(),typeof(s==null?void 0:s.id)<"u"?await this.unsubscribeById(i,s.id,s):await this.unsubscribeByTopic(i,s)}),oe(this,"isSubscribed",i=>new Promise(s=>{s(this.topicMap.topics.includes(i))})),oe(this,"isKnownTopic",i=>new Promise(s=>{s(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(n=>n.topic===i))})),oe(this,"on",(i,s)=>{this.events.on(i,s)}),oe(this,"once",(i,s)=>{this.events.once(i,s)}),oe(this,"off",(i,s)=>{this.events.off(i,s)}),oe(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),oe(this,"start",async()=>{await this.onConnect()}),oe(this,"stop",async()=>{await this.onDisconnect()}),oe(this,"restart",async()=>{await this.restore(),await this.onRestart()}),oe(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(s=>{i.push(s)}),await this.batchSubscribe(i)}),oe(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(ui.pulse,async()=>{await this.checkPending()}),this.events.on(at.created,async i=>{const s=at.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()}),this.events.on(at.deleted,async i=>{const s=at.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()})}),this.relayer=e,this.logger=ht(r,this.name),this.clientId=""}get context(){return it(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 s=>await this.unsubscribeById(e,s,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 s=Cn(i);await this.restartToComplete({topic:e,id:r,relay:s}),await this.rpcUnsubscribe(e,r,s);const n=ue("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,r,i){var s,n;const o=await this.getSubscriptionId(e);if((s=i==null?void 0:i.internal)!=null&&s.skipSubscribe)return o;(!i||(i==null?void 0:i.transportType)===le.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const a={method:_i(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(n=i==null?void 0:i.internal)==null?void 0:n.throwOnFailedPublish;try{if((i==null?void 0:i.transportType)===le.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(h=>this.logger.warn(h))},q.toMiliseconds(q.ONE_SECOND)),o;const l=new Promise(async h=>{const f=d=>{d.topic===e&&(this.events.removeListener(at.created,f),h(d.id))};this.events.on(at.created,f);try{const d=await qt(new Promise((g,w)=>{this.relayer.request(a).catch(m=>{this.logger.warn(m,m==null?void 0:m.message),w(m)}).then(g)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(at.created,f),h(d)}catch{}}),u=await qt(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return u?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(ye.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:_i(r.protocol).batchSubscribe,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await qt(new Promise(s=>{this.relayer.request(i).catch(n=>this.logger.warn(n)).then(s)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(ye.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:_i(r.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let s;try{s=await await qt(new Promise((n,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(ye.connection_stalled)}return s}rpcUnsubscribe(e,r,i){const s={method:_i(i.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,r){this.setSubscription(e,Xo(Qi({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Qi({},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,Qi({},r)),this.topicMap.set(r.topic,e),this.events.emit(at.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}=z("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(at.deleted,Xo(Qi({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(at.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 s=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(at.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(r=>{var i;return r.topic===((i=this.subscriptions.get(r.id))==null?void 0:i.topic)})){const{message:r}=z("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=>Xo(Qi({},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 Ux(q.toMiliseconds(q.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}=z("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 wt(e+await this.getClientId())}}var rA=Object.defineProperty,qh=Object.getOwnPropertySymbols,iA=Object.prototype.hasOwnProperty,sA=Object.prototype.propertyIsEnumerable,ec=(t,e,r)=>e in t?rA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zh=(t,e)=>{for(var r in e||(e={}))iA.call(e,r)&&ec(t,r,e[r]);if(qh)for(var r of qh(e))sA.call(e,r)&&ec(t,r,e[r]);return t},re=(t,e,r)=>ec(t,typeof e!="symbol"?e+"":e,r);class nA extends I8{constructor(e){var r;super(e),re(this,"protocol","wc"),re(this,"version",2),re(this,"core"),re(this,"logger"),re(this,"events",new xt.EventEmitter),re(this,"provider"),re(this,"messages"),re(this,"subscriber"),re(this,"publisher"),re(this,"name",UO),re(this,"transportExplicitlyClosed",!1),re(this,"initialized",!1),re(this,"connectionAttemptInProgress",!1),re(this,"relayUrl"),re(this,"projectId"),re(this,"packageName"),re(this,"bundleId"),re(this,"hasExperiencedNetworkDisruption",!1),re(this,"pingTimeout"),re(this,"heartBeatTimeout",q.toMiliseconds(q.THIRTY_SECONDS+q.FIVE_SECONDS)),re(this,"reconnectTimeout"),re(this,"connectPromise"),re(this,"reconnectInProgress",!1),re(this,"requestsInFlight",[]),re(this,"connectTimeout",q.toMiliseconds(q.ONE_SECOND*15)),re(this,"request",async i=>{var s,n;this.logger.debug("Publishing Request Payload");const o=i.id||Cr().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:i.method,topic:(s=i.params)==null?void 0:s.topic},"relayer.request - publishing...");const a=`${o}:${((n=i.params)==null?void 0:n.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(i);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),re(this,"resetPingTimeout",()=>{On()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var i,s,n,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(n=(s=(i=this.provider)==null?void 0:i.connection)==null?void 0:s.socket)==null?void 0:n.terminate)==null||o.call(n)}catch(a){this.logger.warn(a,a==null?void 0:a.message)}},this.heartBeatTimeout))}),re(this,"onPayloadHandler",i=>{this.onProviderPayload(i),this.resetPingTimeout()}),re(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(ye.connect)}),re(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),re(this,"onProviderErrorHandler",i=>{this.logger.fatal(`Fatal socket error: ${i.message}`),this.events.emit(ye.error,i),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),re(this,"registerProviderListeners",()=>{this.provider.on(dt.payload,this.onPayloadHandler),this.provider.on(dt.connect,this.onConnectHandler),this.provider.on(dt.disconnect,this.onDisconnectHandler),this.provider.on(dt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=Wc({logger:(r=e.logger)!=null?r:RO,name:this.name}),this.messages=new LD(this.logger,e.core),this.subscriber=new tA(this,this.logger),this.publisher=new KD(this,this.logger),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Mg,bx()?this.packageName=_u():vx()&&(this.bundleId=_u()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e==null?void 0:e.message))}get context(){return it(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:le.relay},dn.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,r){var i,s,n;this.isInitialized(),(!(r!=null&&r.transportType)||(r==null?void 0:r.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=r==null?void 0:r.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(s=r==null?void 0:r.internal)==null?void 0:s.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(at.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(at.created,l)}),new Promise(async(u,h)=>{a=await this.subscriber.subscribe(e,zh({internal:{throwOnFailedPublish:o}},r)).catch(f=>{o&&h(f)})||a,u()})]),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 qt(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.info("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 gh())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const r=e.sort((i,s)=>i.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+(s==null?void 0:s.message))}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const s=ge(q.FIVE_MINUTES),n={topic:i,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(ye.message,e),await this.recordMessageEvent(e,dn.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,s)=>{const n=()=>{s(new Error("Connection interrupted while trying to connect"))};this.provider.once(dt.disconnect,n),await qt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{s(o)}).finally(()=>{this.provider.off(dt.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{s(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(dt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(dt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const s=i;this.logger.warn({},s.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(i=>setTimeout(i,q.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,s,n;if(On())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((n=(s=(i=this.provider)==null?void 0:i.connection)==null?void 0:s.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Zc(new xO(Sx({sdkVersion:Ga,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:s}=e;await this.messages.set(i,s,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 s=this.messages.has(r,i);return s&&this.logger.warn(`Ignoring duplicate message: ${i}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Yc(e)){if(!e.method.endsWith(NO))return;const r=e.params,{topic:i,message:s,publishedAt:n,attestation:o}=r.data,a={topic:i,message:s,publishedAt:n,transportType:le.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(zh({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else io(e)&&this.events.emit(ye.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,dn.inbound),this.events.emit(ye.message,e))}async acknowledgePayload(e){const r=xs(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(dt.payload,this.onPayloadHandler),this.provider.off(dt.connect,this.onConnectHandler),this.provider.off(dt.disconnect,this.onDisconnectHandler),this.provider.off(dt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await gh();ES(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(ui.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&IS())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r==null?void 0:r.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(ye.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},q.toMiliseconds(kO)))))}isInitialized(){if(!this.initialized){const{message:e}=z("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 oA(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Vh(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Hh(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const aA="[object RegExp]",cA="[object String]",lA="[object Number]",uA="[object Boolean]",Kh="[object Arguments]",hA="[object Symbol]",fA="[object Date]",dA="[object Map]",pA="[object Set]",gA="[object Array]",yA="[object Function]",wA="[object ArrayBuffer]",Qo="[object Object]",mA="[object Error]",bA="[object DataView]",vA="[object Uint8Array]",EA="[object Uint8ClampedArray]",xA="[object Uint16Array]",_A="[object Uint32Array]",IA="[object BigUint64Array]",SA="[object Int8Array]",OA="[object Int16Array]",$A="[object Int32Array]",DA="[object BigInt64Array]",AA="[object Float32Array]",PA="[object Float64Array]";function BA(){}function Wh(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 CA(t,e,r){return os(t,e,void 0,void 0,void 0,void 0,r)}function os(t,e,r,i,s,n,o){const a=o(t,e,r,i,s,n);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 fs(t,e,n,o)}return fs(t,e,n,o)}function fs(t,e,r,i){if(Object.is(t,e))return!0;let s=Hh(t),n=Hh(e);if(s===Kh&&(s=Qo),n===Kh&&(n=Qo),s!==n)return!1;switch(s){case cA:return t.toString()===e.toString();case lA:{const c=t.valueOf(),l=e.valueOf();return oA(c,l)}case uA:case fA:case hA:return Object.is(t.valueOf(),e.valueOf());case aA:return t.source===e.source&&t.flags===e.flags;case yA: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(s){case dA:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!os(l,e.get(c),c,t,e,r,i))return!1;return!0}case pA:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const h=c[u],f=l.findIndex(d=>os(h,d,void 0,t,e,r,i));if(f===-1)return!1;l.splice(f,1)}return!0}case gA:case vA:case EA:case xA:case _A:case IA:case SA:case OA:case $A:case DA:case AA:case PA:{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(!os(t[c],e[c],c,t,e,r,i))return!1;return!0}case wA:return t.byteLength!==e.byteLength?!1:fs(new Uint8Array(t),new Uint8Array(e),r,i);case bA:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:fs(new Uint8Array(t),new Uint8Array(e),r,i);case mA:return t.name===e.name&&t.message===e.message;case Qo:{if(!(fs(t.constructor,e.constructor,r,i)||Wh(t)&&Wh(e)))return!1;const c=[...Object.keys(t),...Vh(t)],l=[...Object.keys(e),...Vh(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const h=c[u],f=t[h];if(!Object.hasOwn(e,h))return!1;const d=e[h];if(!os(f,d,h,t,e,r,i))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function TA(t,e){return CA(t,e,BA)}var RA=Object.defineProperty,Gh=Object.getOwnPropertySymbols,UA=Object.prototype.hasOwnProperty,NA=Object.prototype.propertyIsEnumerable,tc=(t,e,r)=>e in t?RA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yh=(t,e)=>{for(var r in e||(e={}))UA.call(e,r)&&tc(t,r,e[r]);if(Gh)for(var r of Gh(e))NA.call(e,r)&&tc(t,r,e[r]);return t},Ge=(t,e,r)=>tc(t,typeof e!="symbol"?e+"":e,r);class fi extends S8{constructor(e,r,i,s=Ht,n=void 0){super(e,r,i,s),this.core=e,this.logger=r,this.name=i,Ge(this,"map",new Map),Ge(this,"version",jO),Ge(this,"cached",[]),Ge(this,"initialized",!1),Ge(this,"getKey"),Ge(this,"storagePrefix",Ht),Ge(this,"recentlyDeleted",[]),Ge(this,"recentlyDeletedLimit",200),Ge(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Oe(o)?this.map.set(this.getKey(o),o):XI(o)?this.map.set(o.id,o):QI(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Ge(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())}),Ge(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Ge(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>TA(a[c],o[c]))):this.values)),Ge(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=Yh(Yh({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Ge(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=ht(r,this.name),this.storagePrefix=s,this.getKey=n}get context(){return it(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:s}=z("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}const{message:i}=z("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}=z("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}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var kA=Object.defineProperty,jA=(t,e,r)=>e in t?kA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Q=(t,e,r)=>jA(t,typeof e!="symbol"?e+"":e,r);class FA{constructor(e,r){this.core=e,this.logger=r,Q(this,"name",qO),Q(this,"version",zO),Q(this,"events",new uc),Q(this,"pairings"),Q(this,"initialized",!1),Q(this,"storagePrefix",Ht),Q(this,"ignoredPayloadTypes",[lr]),Q(this,"registeredMethods",[]),Q(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Q(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),Q(this,"create",async i=>{this.isInitialized();const s=Ma(),n=await this.core.crypto.setSymKey(s),o=ge(q.FIVE_MINUTES),a={protocol:Lg},c={topic:n,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},l=oh({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:s,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(Wr.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:i==null?void 0:i.transportType,internal:i==null?void 0:i.internal}),{topic:n,uri:l}}),Q(this,"pair",async i=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[Nt.pairing_started]}});this.isValidPair(i,s);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:l}=nh(i.uri);s.props.properties.topic=n,s.addTrace(Nt.pairing_uri_validation_success),s.addTrace(Nt.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(n)){if(u=this.pairings.get(n),s.addTrace(Nt.existing_pairing),u.active)throw s.setError(tr.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);s.addTrace(Nt.pairing_not_expired)}const h=c||ge(q.FIVE_MINUTES),f={topic:n,relay:a,expiry:h,active:!1,methods:l};this.core.expirer.set(n,h),await this.pairings.set(n,f),s.addTrace(Nt.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(Wr.create,f),s.addTrace(Nt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),s.addTrace(Nt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(tr.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(d){throw s.setError(tr.subscribe_pairing_topic_failure),d}return s.addTrace(Nt.subscribe_pairing_topic_success),f}),Q(this,"activate",async({topic:i})=>{this.isInitialized();const s=ge(q.FIVE_MINUTES);this.core.expirer.set(i,s),await this.pairings.update(i,{active:!0,expiry:s})}),Q(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:s}=i;if(this.pairings.keys.includes(s)){const n=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Vr();this.events.once(ne("pairing_ping",n),({error:l})=>{l?c(l):a()}),await o()}}),Q(this,"updateExpiry",async({topic:i,expiry:s})=>{this.isInitialized(),await this.pairings.update(i,{expiry:s})}),Q(this,"updateMetadata",async({topic:i,metadata:s})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:s})}),Q(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Q(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:s}=i;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",ue("USER_DISCONNECTED")),await this.deletePairing(s))}),Q(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:s,relay:n,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(s);return oh({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),Q(this,"sendRequest",async(i,s,n)=>{const o=Dt(s,n),a=await this.core.crypto.encode(i,o),c=Ji[s].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),Q(this,"sendResult",async(i,s,n)=>{const o=xs(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,l=Ji[c].res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)}),Q(this,"sendError",async(i,s,n)=>{const o=ro(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,l=Ji[c]?Ji[c].res:Ji.unregistered_method.res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)}),Q(this,"deletePairing",async(i,s)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,ue("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),s?Promise.resolve():this.core.expirer.del(i)])}),Q(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(s=>Lt(s.expiry));await Promise.all(i.map(s=>this.deletePairing(s.topic)))}),Q(this,"onRelayEventRequest",async i=>{const{topic:s,payload:n}=i;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(s,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(s,n);default:return await this.onUnknownRpcMethodRequest(s,n)}}),Q(this,"onRelayEventResponse",async i=>{const{topic:s,payload:n}=i,o=(await this.core.history.get(s,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(s,n);default:return this.onUnknownRpcMethodResponse(o)}}),Q(this,"onPairingPingRequest",async(i,s)=>{const{id:n}=s;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(Wr.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),Q(this,"onPairingPingResponse",(i,s)=>{const{id:n}=s;setTimeout(()=>{jt(s)?this.events.emit(ne("pairing_ping",n),{}):mt(s)&&this.events.emit(ne("pairing_ping",n),{error:s.error})},500)}),Q(this,"onPairingDeleteRequest",async(i,s)=>{const{id:n}=s;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Wr.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),Q(this,"onUnknownRpcMethodRequest",async(i,s)=>{const{id:n,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=ue("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,i,a),this.logger.error(a)}catch(a){await this.sendError(n,i,a),this.logger.error(a)}}),Q(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(ue("WC_METHOD_UNSUPPORTED",i))}),Q(this,"isValidPair",(i,s)=>{var n;if(!Ze(i)){const{message:a}=z("MISSING_OR_INVALID",`pair() params: ${i}`);throw s.setError(tr.malformed_pairing_uri),new Error(a)}if(!JI(i.uri)){const{message:a}=z("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw s.setError(tr.malformed_pairing_uri),new Error(a)}const o=nh(i==null?void 0:i.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=z("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(tr.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=z("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(tr.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&q.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){s.setError(tr.pairing_expired);const{message:a}=z("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Q(this,"isValidPing",async i=>{if(!Ze(i)){const{message:n}=z("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),Q(this,"isValidDisconnect",async i=>{if(!Ze(i)){const{message:n}=z("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),Q(this,"isValidPairingTopic",async i=>{if(!we(i,!1)){const{message:s}=z("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(s)}if(!this.pairings.keys.includes(i)){const{message:s}=z("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(s)}if(Lt(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:s}=z("EXPIRED",`pairing topic: ${i}`);throw new Error(s)}}),this.core=e,this.logger=ht(r,this.name),this.pairings=new fi(this.core,this.logger,this.name,this.storagePrefix)}get context(){return it(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(ye.message,async e=>{const{topic:r,message:i,transportType:s}=e;if(this.pairings.keys.includes(r)&&s!==le.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const n=await this.core.crypto.decode(r,i);Yc(n)?(this.core.history.set(r,n),await this.onRelayEventRequest({topic:r,payload:n})):io(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:r,payload:n}),this.core.history.delete(r,n.id)),await this.core.relayer.messages.ack(r,i)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(gt.expired,async e=>{const{topic:r}=$p(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Wr.expire,{topic:r}))})}}var LA=Object.defineProperty,MA=(t,e,r)=>e in t?LA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pe=(t,e,r)=>MA(t,typeof e!="symbol"?e+"":e,r);class qA extends E8{constructor(e,r){super(e,r),this.core=e,this.logger=r,Pe(this,"records",new Map),Pe(this,"events",new xt.EventEmitter),Pe(this,"name",VO),Pe(this,"version",HO),Pe(this,"cached",[]),Pe(this,"initialized",!1),Pe(this,"storagePrefix",Ht),Pe(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)}),Pe(this,"set",(i,s,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:s,chainId:n}),this.records.has(s.id))return;const o={id:s.id,topic:i,request:{method:s.method,params:s.params||null},chainId:n,expiry:ge(q.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(It.created,o)}),Pe(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const s=await this.getRecord(i.id);typeof s.response>"u"&&(s.response=mt(i)?{error:i.error}:{result:i.result},this.records.set(s.id,s),this.persist(),this.events.emit(It.updated,s))}),Pe(this,"get",async(i,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:s}),await this.getRecord(s))),Pe(this,"delete",(i,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(n=>{if(n.topic===i){if(typeof s<"u"&&n.id!==s)return;this.records.delete(n.id),this.events.emit(It.deleted,n)}}),this.persist()}),Pe(this,"exists",async(i,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===i:!1)),Pe(this,"on",(i,s)=>{this.events.on(i,s)}),Pe(this,"once",(i,s)=>{this.events.once(i,s)}),Pe(this,"off",(i,s)=>{this.events.off(i,s)}),Pe(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=ht(r,this.name)}get context(){return it(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:Dt(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}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(It.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=z("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(It.created,e=>{const r=It.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(It.updated,e=>{const r=It.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(It.deleted,e=>{const r=It.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(ui.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{q.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(It.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var zA=Object.defineProperty,VA=(t,e,r)=>e in t?zA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Me=(t,e,r)=>VA(t,typeof e!="symbol"?e+"":e,r);class HA extends $8{constructor(e,r){super(e,r),this.core=e,this.logger=r,Me(this,"expirations",new Map),Me(this,"events",new xt.EventEmitter),Me(this,"name",KO),Me(this,"version",WO),Me(this,"cached",[]),Me(this,"initialized",!1),Me(this,"storagePrefix",Ht),Me(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)}),Me(this,"has",i=>{try{const s=this.formatTarget(i);return typeof this.getExpiration(s)<"u"}catch{return!1}}),Me(this,"set",(i,s)=>{this.isInitialized();const n=this.formatTarget(i),o={target:n,expiry:s};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(gt.created,{target:n,expiration:o})}),Me(this,"get",i=>{this.isInitialized();const s=this.formatTarget(i);return this.getExpiration(s)}),Me(this,"del",i=>{if(this.isInitialized(),this.has(i)){const s=this.formatTarget(i),n=this.getExpiration(s);this.expirations.delete(s),this.events.emit(gt.deleted,{target:s,expiration:n})}}),Me(this,"on",(i,s)=>{this.events.on(i,s)}),Me(this,"once",(i,s)=>{this.events.once(i,s)}),Me(this,"off",(i,s)=>{this.events.off(i,s)}),Me(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=ht(r,this.name)}get context(){return it(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 Ox(e);if(typeof e=="number")return $x(e);const{message:r}=z("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(gt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=z("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}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;q.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(gt.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(ui.pulse,()=>this.checkExpirations()),this.events.on(gt.created,e=>{const r=gt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(gt.expired,e=>{const r=gt.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(gt.deleted,e=>{const r=gt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var KA=Object.defineProperty,WA=(t,e,r)=>e in t?KA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pe=(t,e,r)=>WA(t,typeof e!="symbol"?e+"":e,r);class GA extends D8{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,pe(this,"name",GO),pe(this,"abortController"),pe(this,"isDevEnv"),pe(this,"verifyUrlV3",ZO),pe(this,"storagePrefix",Ht),pe(this,"version",Fg),pe(this,"publicKey"),pe(this,"fetchPromise"),pe(this,"init",async()=>{var s;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&q.toMiliseconds((s=this.publicKey)==null?void 0:s.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),pe(this,"register",async s=>{if(!ji()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=s,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const l=ti(),u=this.startAbortTimer(q.ONE_SECOND*5),h=await new Promise((f,d)=>{const g=()=>{window.removeEventListener("message",m),l.body.removeChild(w),d("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const w=l.createElement("iframe");w.src=c,w.style.display="none",w.addEventListener("error",g,{signal:this.abortController.signal});const m=O=>{if(O.data&&typeof O.data=="string")try{const C=JSON.parse(O.data);if(C.type==="verify_attestation"){if(Sa(C.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(w),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",m),f(C.attestation===null?"":C.attestation)}}catch(C){this.logger.warn(C)}};l.body.appendChild(w),window.addEventListener("message",m,{signal:this.abortController.signal})});return this.logger.debug(h,"jwt attestation"),h}catch(l){this.logger.warn(l)}return""}),pe(this,"resolve",async s=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=s;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(Sa(n).payload.id!==a)return;const l=await this.isValidJwtAttestation(n);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(s==null?void 0:s.verifyUrl);return this.fetchAttestation(o,c)}),pe(this,"fetchAttestation",async(s,n)=>{this.logger.debug(`resolving attestation: ${s} from url: ${n}`);const o=this.startAbortTimer(q.ONE_SECOND*5),a=await fetch(`${n}/attestation/${s}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),pe(this,"getVerifyUrl",s=>{let n=s||hs;return JO.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${hs}`),n=hs),n}),pe(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const s=this.startAbortTimer(q.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(s),await n.json()}catch(s){this.logger.warn(s)}}),pe(this,"persistPublicKey",async s=>{this.logger.debug(s,"persisting public key to local storage"),await this.store.setItem(this.storeKey,s),this.publicKey=s}),pe(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),pe(this,"isValidJwtAttestation",async s=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(s,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(s,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),pe(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),pe(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const s=await this.fetchPromise;return this.fetchPromise=void 0,s}),pe(this,"validateAttestation",(s,n)=>{const o=_I(s,n.publicKey),a={hasExpired:q.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=ht(r,this.name),this.abortController=new AbortController,this.isDevEnv=Nc(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return it(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),q.toMiliseconds(e))}}var YA=Object.defineProperty,ZA=(t,e,r)=>e in t?YA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zh=(t,e,r)=>ZA(t,typeof e!="symbol"?e+"":e,r);class JA extends A8{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,Zh(this,"context",XO),Zh(this,"registerDeviceToken",async i=>{const{clientId:s,token:n,notificationType:o,enableEncrypted:a=!1}=i,c=`${QO}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:s,type:o,token:n,always_raw:a})})}),this.logger=ht(r,this.context)}}var XA=Object.defineProperty,Jh=Object.getOwnPropertySymbols,QA=Object.prototype.hasOwnProperty,e6=Object.prototype.propertyIsEnumerable,rc=(t,e,r)=>e in t?XA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,es=(t,e)=>{for(var r in e||(e={}))QA.call(e,r)&&rc(t,r,e[r]);if(Jh)for(var r of Jh(e))e6.call(e,r)&&rc(t,r,e[r]);return t},_e=(t,e,r)=>rc(t,typeof e!="symbol"?e+"":e,r);class t6 extends P8{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,_e(this,"context",t$),_e(this,"storagePrefix",Ht),_e(this,"storageVersion",e$),_e(this,"events",new Map),_e(this,"shouldPersist",!1),_e(this,"init",async()=>{if(!Nc())try{const s={eventId:Su(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Sp(this.core.relayer.protocol,this.core.relayer.version,Ga)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}}),_e(this,"createEvent",s=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=s,l=Su(),u=this.core.projectId||"",h=Date.now(),f=es({eventId:l,timestamp:h,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,f),this.shouldPersist=!0),f}),_e(this,"getEvent",s=>{const{eventId:n,topic:o}=s;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return es(es({},a),this.setMethods(a.eventId))}),_e(this,"deleteEvent",s=>{const{eventId:n}=s;this.events.delete(n),this.shouldPersist=!0}),_e(this,"setEventListeners",()=>{this.core.heartbeat.on(ui.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{q.fromMiliseconds(Date.now())-q.fromMiliseconds(s.timestamp)>r$&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})}),_e(this,"setMethods",s=>({addTrace:n=>this.addTrace(s,n),setError:n=>this.setError(s,n)})),_e(this,"addTrace",(s,n)=>{const o=this.events.get(s);o&&(o.props.properties.trace.push(n),this.events.set(s,o),this.shouldPersist=!0)}),_e(this,"setError",(s,n)=>{const o=this.events.get(s);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(s,o),this.shouldPersist=!0)}),_e(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),_e(this,"restore",async()=>{try{const s=await this.core.storage.getItem(this.storageKey)||[];if(!s.length)return;s.forEach(n=>{this.events.set(n.eventId,es(es({},n),this.setMethods(n.eventId)))})}catch(s){this.logger.warn(s)}}),_e(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const s=[];for(const[n,o]of this.events)o.props.type&&s.push(o);if(s.length!==0)try{if((await this.sendEvent(s)).ok)for(const n of s)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),_e(this,"sendEvent",async s=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${i$}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ga}${n}`,{method:"POST",body:JSON.stringify(s)})}),_e(this,"getAppDomain",()=>Ip().url),this.logger=ht(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 r6=Object.defineProperty,Xh=Object.getOwnPropertySymbols,i6=Object.prototype.hasOwnProperty,s6=Object.prototype.propertyIsEnumerable,ic=(t,e,r)=>e in t?r6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Qh=(t,e)=>{for(var r in e||(e={}))i6.call(e,r)&&ic(t,r,e[r]);if(Xh)for(var r of Xh(e))s6.call(e,r)&&ic(t,r,e[r]);return t},ae=(t,e,r)=>ic(t,typeof e!="symbol"?e+"":e,r);let n6=class ey extends w8{constructor(e){var r;super(e),ae(this,"protocol",jg),ae(this,"version",Fg),ae(this,"name",Wa),ae(this,"relayUrl"),ae(this,"projectId"),ae(this,"customStoragePrefix"),ae(this,"events",new xt.EventEmitter),ae(this,"logger"),ae(this,"heartbeat"),ae(this,"relayer"),ae(this,"crypto"),ae(this,"storage"),ae(this,"history"),ae(this,"expirer"),ae(this,"pairing"),ae(this,"verify"),ae(this,"echoClient"),ae(this,"linkModeSupportedApps"),ae(this,"eventClient"),ae(this,"initialized",!1),ae(this,"logChunkController"),ae(this,"on",(a,c)=>this.events.on(a,c)),ae(this,"once",(a,c)=>this.events.once(a,c)),ae(this,"off",(a,c)=>this.events.off(a,c)),ae(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ae(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:le.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const i=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(i)try{return this.customStoragePrefix=i.customStoragePrefix,this.logger=i.logger,this.heartbeat=i.heartbeat,this.crypto=i.crypto,this.history=i.history,this.expirer=i.expirer,this.storage=i.storage,this.relayer=i.relayer,this.pairing=i.pairing,this.verify=i.verify,this.echoClient=i.echoClient,this.linkModeSupportedApps=i.linkModeSupportedApps,this.eventClient=i.eventClient,this.initialized=i.initialized,this.logChunkController=i.logChunkController,i}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Mg,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const s=sx({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:IO.logger,name:Wa}),{logger:n,chunkLoggerController:o}=xp({opts:s,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0: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=ht(n,this.name),this.heartbeat=new RS,this.crypto=new CD(this,this.logger,e==null?void 0:e.keychain),this.history=new qA(this,this.logger),this.expirer=new HA(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new p8(Qh(Qh({},SO),e==null?void 0:e.storageOptions)),this.relayer=new nA({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new FA(this,this.logger),this.verify=new GA(this,this.logger,this.storage),this.echoClient=new JA(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new t6(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new ey(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(FO,i),r}get context(){return it(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(Bh,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(Bh)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),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"&&_O.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const o6=n6,ty="wc",ry=2,iy="client",Jc=`${ty}@${ry}:${iy}:`,ea={name:iy,logger:"error"},ef="WALLETCONNECT_DEEPLINK_CHOICE",a6="proposal",tf="Proposal expired",c6="session",vi=q.SEVEN_DAYS,l6="engine",Be={wc_sessionPropose:{req:{ttl:q.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:q.ONE_DAY,prompt:!1,tag:1104},res:{ttl:q.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:q.ONE_DAY,prompt:!1,tag:1106},res:{ttl:q.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:q.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:q.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:q.ONE_DAY,prompt:!1,tag:1112},res:{ttl:q.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:q.ONE_DAY,prompt:!1,tag:1114},res:{ttl:q.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:q.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:q.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1119}}},ta={min:q.FIVE_MINUTES,max:q.SEVEN_DAYS},Ut={idle:"IDLE",active:"ACTIVE"},u6={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},h6="request",f6=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],d6="wc",p6="auth",g6="authKeys",y6="pairingTopics",w6="requests",no=`${d6}@${1.5}:${p6}:`,pn=`${no}:PUB_KEY`;var m6=Object.defineProperty,b6=Object.defineProperties,v6=Object.getOwnPropertyDescriptors,rf=Object.getOwnPropertySymbols,E6=Object.prototype.hasOwnProperty,x6=Object.prototype.propertyIsEnumerable,sc=(t,e,r)=>e in t?m6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,se=(t,e)=>{for(var r in e||(e={}))E6.call(e,r)&&sc(t,r,e[r]);if(rf)for(var r of rf(e))x6.call(e,r)&&sc(t,r,e[r]);return t},Ce=(t,e)=>b6(t,v6(e)),F=(t,e,r)=>sc(t,typeof e!="symbol"?e+"":e,r);class _6 extends R8{constructor(e){super(e),F(this,"name",l6),F(this,"events",new uc),F(this,"initialized",!1),F(this,"requestQueue",{state:Ut.idle,queue:[]}),F(this,"sessionRequestQueue",{state:Ut.idle,queue:[]}),F(this,"emittedSessionRequests",new Nx({limit:500})),F(this,"requestQueueDelay",q.ONE_SECOND),F(this,"expectedPairingMethodMap",new Map),F(this,"recentlyDeletedMap",new Map),F(this,"recentlyDeletedLimit",200),F(this,"relayMessageCache",[]),F(this,"pendingSessions",new Map),F(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(Be)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},q.toMiliseconds(this.requestQueueDelay)))}),F(this,"connect",async r=>{var i;this.isInitialized(),await this.confirmOnlineStateOrThrow();const s=Ce(se({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(s),s.optionalNamespaces=KI(s.requiredNamespaces,s.optionalNamespaces),s.requiredNamespaces={};const{pairingTopic:n,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:l,relays:u,authentication:h,walletPay:f}=s,d=((i=h==null?void 0:h[0])==null?void 0:i.ttl)||Be.wc_sessionPropose.req.ttl||q.FIVE_MINUTES;this.validateRequestExpiry(d);let g=n,w,m=!1;try{if(g){const D=this.client.core.pairing.pairings.get(g);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),m=D.active}}catch(D){throw this.client.logger.error(`connect() -> pairing.get(${g}) failed`),D}if(!g||!m){const{topic:D,uri:k}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});g=D,w=k}if(!g){const{message:D}=z("NO_MATCHING_KEY",`connect() pairing topic: ${g}`);throw new Error(D)}const O=await this.client.core.crypto.generateKeyPair(),C=ge(d),b=se(Ce(se(se({requiredNamespaces:o,optionalNamespaces:a,relays:u??[{protocol:Lg}],proposer:{publicKey:O,metadata:this.client.metadata},expiryTimestamp:C,pairingTopic:g},c&&{sessionProperties:c}),l&&{scopedProperties:l}),{id:kt()}),(h||f)&&{requests:{authentication:h==null?void 0:h.map(D=>{const{domain:k,chains:j,nonce:P,uri:I,exp:$,nbf:p,type:y,statement:v,requestId:S,resources:E,signatureTypes:_}=D;return{domain:k,chains:j,nonce:P,type:y??"caip122",aud:I,version:"1",iat:new Date().toISOString(),exp:$,nbf:p,statement:v,requestId:S,resources:E,signatureTypes:_}}),walletPay:f}}),x=ne("session_connect",b.id),{reject:A,resolve:B,done:T}=Vr(d,tf),R=({id:D})=>{D===b.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(b.id),this.events.emit(x,{error:{message:tf,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(x,({error:D,session:k})=>{this.client.events.off("proposal_expire",R),D?A(D):k&&B(k)}),await this.setProposal(b.id,b),await this.sendProposeSession({proposal:b,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:b.id}}}).catch(D=>{throw this.deleteProposal(b.id),D}),{uri:w,approval:T}}),F(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}}),F(this,"approve",async r=>{var i,s,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=r==null?void 0:r.id)==null?void 0:i.toString(),trace:[St.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(k){throw o.setError(Mr.no_internet_connection),k}try{await this.isValidProposalId(r==null?void 0:r.id)}catch(k){throw this.client.logger.error(`approve() -> proposal.get(${r==null?void 0:r.id}) failed`),o.setError(Mr.proposal_not_found),k}try{await this.isValidApprove(r)}catch(k){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Mr.session_approve_namespace_validation_failure),k}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=r,g=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:w,proposer:m,requiredNamespaces:O,optionalNamespaces:C}=g;let b=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:w});b||(b=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:St.session_approve_started,properties:{topic:w,trace:[St.session_approve_started,St.session_namespaces_validation_success]}}));const x=await this.client.core.crypto.generateKeyPair(),A=m.publicKey,B=await this.client.core.crypto.generateSharedKey(x,A),T=Ce(se(se(se({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:x,metadata:this.client.metadata},expiry:ge(vi)},u&&{sessionProperties:u}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{proposalRequestsResponses:d}),R=le.relay;b.addTrace(St.subscribing_session_topic);try{await this.client.core.relayer.subscribe(B,{transportType:R,internal:{skipSubscribe:!0}})}catch(k){throw b.setError(Mr.subscribe_session_topic_failure),k}b.addTrace(St.subscribe_session_topic_success);const D=Ce(se({},T),{topic:B,requiredNamespaces:O,optionalNamespaces:C,pairingTopic:w,acknowledged:!1,self:T.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:x,transportType:le.relay,authentication:d==null?void 0:d.authentication,walletPayResult:d==null?void 0:d.walletPay});await this.client.session.set(B,D),b.addTrace(St.store_session);try{await this.sendApproveSession({sessionTopic:B,proposal:g,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:x},sessionSettleRequest:T,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:se({correlationId:a},this.getTVFApproveParams(D))}}),b.addTrace(St.session_approve_publish_success)}catch(k){throw this.client.logger.error(k),this.client.session.delete(B,ue("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(B),k}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:w,metadata:m.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:w}),await this.setExpiry(B,ge(vi)),{topic:B,acknowledged:()=>Promise.resolve(this.client.session.get(B))}}),F(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:s}=r;let n;try{n=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}n&&await this.sendError({id:i,topic:n,error:s,rpcOpts:Be.wc_sessionPropose.reject}),await this.deleteProposal(i)}),F(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:s}=r,{done:n,resolve:o,reject:a}=Vr(q.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=kt(),l=Cr().toString(),u=this.client.session.get(i).namespaces;return this.events.once(ne("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(i,{namespaces:s}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(h=>{this.client.logger.error(h),this.client.session.update(i,{namespaces:u}),a(h)}),{acknowledged:n}}),F(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,s=kt(),{done:n,resolve:o,reject:a}=Vr(q.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(ne("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,ge(vi)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),F(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(m){throw this.client.logger.error("request() -> isValidRequest() failed"),m}const{chainId:i,request:s,topic:n,expiry:o=Be.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(n);(a==null?void 0:a.transportType)===le.relay&&await this.confirmOnlineStateOrThrow();const c=kt(),l=Cr().toString(),{done:u,resolve:h,reject:f}=Vr(o,"Request expired. Please try again.");this.events.once(ne("session_request",c),({error:m,result:O})=>{m?f(m):h(O)});const d="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:n,method:d,params:{request:Ce(se({},s),{expiryTimestamp:ge(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(m=>f(m)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),await u();const w={request:Ce(se({},s),{expiryTimestamp:ge(o)}),chainId:i};return await Promise.all([new Promise(async m=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:n,method:d,params:w,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,w)}).catch(O=>f(O)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),m()}),new Promise(async m=>{var O;if(!((O=a.sessionConfig)!=null&&O.disableDeepLink)){const C=await Bx(this.client.core.storage,ef);await Dx({id:c,topic:n,wcDeepLink:C})}m()}),u()]).then(m=>m[2])}),F(this,"respond",async r=>{var i,s;this.isInitialized();const n=this.client.core.eventClient.createEvent({properties:{topic:(r==null?void 0:r.topic)||((s=(i=r==null?void 0:r.response)==null?void 0:i.id)==null?void 0:s.toString()),trace:[St.session_request_response_started]}});try{await this.isValidRespond(r)}catch(h){throw n.addTrace(h==null?void 0:h.message),n.setError(Mr.session_request_response_validation_failure),h}n.addTrace(St.session_request_response_validation_success);const{topic:o,response:a}=r,{id:c}=a,l=this.client.session.get(o);l.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{n.addTrace(St.session_request_response_publish_started),jt(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:u}):mt(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:u}),this.cleanupAfterResponse(r)}catch(h){throw n.addTrace(h==null?void 0:h.message),n.setError(Mr.session_request_response_publish_failure),h}}),F(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:i}=r;if(this.client.session.keys.includes(i)){const s=kt(),n=Cr().toString(),{done:o,resolve:a,reject:c}=Vr(q.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(ne("session_ping",s),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),F(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:s,chainId:n}=r,o=Cr().toString(),a=kt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:s,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),F(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:ue("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:s}=z("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(s)}}),F(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>YI(i,r)))),F(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),F(this,"authenticate",async(r,i)=>{var s;this.isInitialized(),this.isValidAuthenticate(r);const n=i&&this.client.core.linkModeSupportedApps.includes(i)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),o=n?le.link_mode:le.relay;o===le.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:h,type:f,exp:d,nbf:g,methods:w=[],expiry:m}=r,O=[...r.resources||[]],{topic:C,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:C,uri:b}});const x=await this.client.core.crypto.generateKeyPair(),A=un(x);if(await Promise.all([this.client.auth.authKeys.set(pn,{responseTopic:A,publicKey:x}),this.client.auth.pairingTopics.set(A,{topic:A,pairingTopic:C})]),await this.client.core.relayer.subscribe(A,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${C}`),w.length>0){const{namespace:E}=cr(a[0]);let _=Y_(E,"request",w);ln(O)&&(_=J_(_,O.pop())),O.push(_)}const B=m&&m>Be.wc_sessionAuthenticate.req.ttl?m:Be.wc_sessionAuthenticate.req.ttl,T={authPayload:{type:f??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:h,iat:new Date().toISOString(),exp:d,nbf:g,resources:O},requester:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:ge(B)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},D={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:C,proposer:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:ge(Be.wc_sessionPropose.req.ttl),id:kt()},{done:k,resolve:j,reject:P}=Vr(B,"Request expired"),I=kt(),$=ne("session_connect",D.id),p=ne("session_request",I),y=async({error:E,session:_})=>{this.events.off(p,v),E?P(E):_&&j({session:_})},v=async E=>{var _,U,N;if(await this.deletePendingAuthRequest(I,{message:"fulfilled",code:0}),E.error){const W=ue("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return E.error.code===W.code?void 0:(this.events.off($,y),P(E.error.message))}await this.deleteProposal(D.id),this.events.off($,y);const{cacaos:V,responder:L}=E.result,M=[],K=[];for(const W of V){await Nu({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),P(ue("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:X}=W,fe=ln(X.resources),me=[Ba(X.iss)],Ee=Dn(X.iss);if(fe){const ze=ku(fe),Kt=ju(fe);M.push(...ze),me.push(...Kt)}for(const ze of me)K.push(`${ze}:${Ee}`)}const G=await this.client.core.crypto.generateSharedKey(x,L.publicKey);let J;M.length>0&&(J={topic:G,acknowledged:!0,self:{publicKey:x,metadata:this.client.metadata},peer:L,controller:L.publicKey,expiry:ge(vi),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:C,namespaces:uh([...new Set(M)],[...new Set(K)]),transportType:o},await this.client.core.relayer.subscribe(G,{transportType:o}),await this.client.session.set(G,J),C&&await this.client.core.pairing.updateMetadata({topic:C,metadata:L.metadata}),J=this.client.session.get(G)),(_=this.client.metadata.redirect)!=null&&_.linkMode&&(U=L.metadata.redirect)!=null&&U.linkMode&&(N=L.metadata.redirect)!=null&&N.universal&&i&&(this.client.core.addLinkModeSupportedApp(L.metadata.redirect.universal),this.client.session.update(G,{transportType:le.link_mode})),j({auths:V,session:J})};this.events.once($,y),this.events.once(p,v);let S;try{if(n){const E=Dt("wc_sessionAuthenticate",T,I);this.client.core.history.set(C,E);const _=await this.client.core.crypto.encode("",E,{type:Cs,encoding:Pr});S=Xs(i,C,_)}else await Promise.all([this.sendRequest({topic:C,method:"wc_sessionAuthenticate",params:T,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:I}),this.sendRequest({topic:C,method:"wc_sessionPropose",params:D,expiry:Be.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:D.id})])}catch(E){throw this.events.off($,y),this.events.off(p,v),E}return await this.setProposal(D.id,D),await this.setAuthRequest(I,{request:Ce(se({},T),{verifyContext:{}}),pairingTopic:C,transportType:o}),{uri:S??b,response:k}}),F(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:s}=r,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[qr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(m){throw n.setError(Xi.no_internet_connection),m}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(Xi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||le.relay;a===le.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=un(c),h={type:lr,receiverPublicKey:c,senderPublicKey:l},f=[],d=[];for(const m of s){if(!await Nu({cacao:m,projectId:this.client.core.projectId})){n.setError(Xi.invalid_cacao);const A=ue("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:u,error:A,encodeOpts:h}),new Error(A.message)}n.addTrace(qr.cacaos_verified);const{p:O}=m,C=ln(O.resources),b=[Ba(O.iss)],x=Dn(O.iss);if(C){const A=ku(C),B=ju(C);f.push(...A),b.push(...B)}for(const A of b)d.push(`${A}:${x}`)}const g=await this.client.core.crypto.generateSharedKey(l,c);n.addTrace(qr.create_authenticated_session_topic);let w;if((f==null?void 0:f.length)>0){w={topic:g,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ge(vi),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:uh([...new Set(f)],[...new Set(d)]),transportType:a},n.addTrace(qr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(m){throw n.setError(Xi.subscribe_authenticated_session_topic_failure),m}n.addTrace(qr.subscribe_authenticated_session_topic_success),await this.client.session.set(g,w),n.addTrace(qr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(qr.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:i,result:{cacaos:s,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(m){throw n.setError(Xi.authenticated_session_approve_publish_failure),m}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:w}}),F(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:i,reason:s}=r,n=this.getPendingAuthRequest(i);if(!n)throw new Error(`Could not find pending auth request with id ${i}`);n.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=un(o),l={type:lr,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:s,encodeOpts:l,rpcOpts:Be.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.deleteProposal(i)}),F(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:s}=r;return Vp(i,s)}),F(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)}),F(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&n.topic&&n.topic!==i.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),F(this,"deleteSession",async r=>{var i;const{topic:s,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,ue("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),n||this.client.core.expirer.del(s),this.client.core.storage.removeItem(ef).catch(l=>this.client.logger.warn(l)),s===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=Ut.idle),await Promise.all(this.getPendingSessionRequests().filter(l=>l.topic===s).map(l=>this.deletePendingSessionRequest(l.id,ue("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:s})}),F(this,"deleteProposal",async(r,i)=>{if(i)try{const s=this.client.proposal.get(r),n=this.client.core.eventClient.getEvent({topic:s.pairingTopic});n==null||n.setError(Mr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,ue("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),F(this,"deletePendingSessionRequest",async(r,i,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),s?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==r),s&&(this.sessionRequestQueue.state=Ut.idle,this.client.events.emit("session_request_expire",{id:r}))}),F(this,"deletePendingAuthRequest",async(r,i,s=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),s?Promise.resolve():this.client.core.expirer.del(r)])}),F(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}))}),F(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,ge(Be.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),F(this,"setAuthRequest",async(r,i)=>{const{request:s,pairingTopic:n,transportType:o=le.relay}=i;this.client.core.expirer.set(r,s.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:r,pairingTopic:n,verifyContext:s.verifyContext,transportType:o})}),F(this,"setPendingSessionRequest",async r=>{const{id:i,topic:s,params:n,verifyContext:o}=r,a=n.request.expiryTimestamp||ge(Be.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:s,params:n,verifyContext:o})}),F(this,"sendRequest",async r=>{const{topic:i,method:s,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:h,publishOpts:f={}}=r,d=Dt(s,n,c);let g;const w=!!u;try{const C=w?Pr:Qe;g=await this.client.core.crypto.encode(i,d,{encoding:C})}catch(C){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),C}let m;if(f6.includes(s)){const C=wt(JSON.stringify(d)),b=wt(g);m=await this.client.core.verify.register({id:b,decryptedId:C})}const O=se(se({},Be[s].req),f);if(O.attestation=m,o&&(O.ttl=o),a&&(O.id=a),this.client.core.history.set(i,d),w){const C=Xs(u,i,g);await global.Linking.openURL(C,this.client.name)}else O.tvf=Ce(se({},h),{correlationId:d.id}),l?(O.internal=Ce(se({},O.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,g,O)):this.client.core.relayer.publish(i,g,O).catch(C=>this.client.logger.error(C));return d.id}),F(this,"sendProposeSession",async r=>{const{proposal:i,publishOpts:s}=r,n=Dt("wc_sessionPropose",i,i.id);this.client.core.history.set(i.pairingTopic,n);const o=await this.client.core.crypto.encode(i.pairingTopic,n,{encoding:Qe}),a=wt(JSON.stringify(n)),c=wt(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:i.pairingTopic,sessionProposal:o},opts:Ce(se({},s),{publishMethod:"wc_proposeSession",attestation:l})})}),F(this,"sendApproveSession",async r=>{const{sessionTopic:i,pairingProposalResponse:s,proposal:n,sessionSettleRequest:o,publishOpts:a}=r,c=xs(n.id,s),l=await this.client.core.crypto.encode(n.pairingTopic,c,{encoding:Qe}),u=Dt("wc_sessionSettle",o,a==null?void 0:a.id),h=await this.client.core.crypto.encode(i,u,{encoding:Qe});this.client.core.history.set(i,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:i,pairingTopic:n.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:h},opts:Ce(se({},a),{publishMethod:"wc_approveSession"})})}),F(this,"sendResult",async r=>{const{id:i,topic:s,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,l=xs(i,n);let u;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const g=h?Pr:Qe;u=await this.client.core.crypto.encode(s,l,Ce(se({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),g}let f,d;try{f=await this.client.core.history.get(s,i);const g=f.request;try{d=this.getTVFParams(i,g.params,n)}catch(w){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${w==null?void 0:w.message}`)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${i}) failed`),g}if(h){const g=Xs(c,s,u);await global.Linking.openURL(g,this.client.name)}else{const g=f.request.method,w=Be[g].res;w.tvf=Ce(se({},d),{correlationId:i}),o?(w.internal=Ce(se({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,u,w)):this.client.core.relayer.publish(s,u,w).catch(m=>this.client.logger.error(m))}await this.client.core.history.resolve(l)}),F(this,"sendError",async r=>{const{id:i,topic:s,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=r,l=ro(i,n);let u;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const d=h?Pr:Qe;u=await this.client.core.crypto.encode(s,l,Ce(se({},o||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),d}let f;try{f=await this.client.core.history.get(s,i)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${s}, ${i}) failed`),d}if(h){const d=Xs(c,s,u);await global.Linking.openURL(d,this.client.name)}else{const d=f.request.method,g=a||Be[d].res;this.client.core.relayer.publish(s,u,g)}await this.client.core.history.resolve(l)}),F(this,"cleanup",async()=>{const r=[],i=[];this.client.session.getAll().forEach(s=>{let n=!1;Lt(s.expiry)&&(n=!0),this.client.core.crypto.keychain.has(s.topic)||(n=!0),n&&r.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{Lt(s.expiryTimestamp)&&i.push(s.id)}),await Promise.all([...r.map(s=>this.deleteSession({topic:s})),...i.map(s=>this.deleteProposal(s))])}),F(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),F(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),F(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Ut.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=Ut.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=Ut.idle}),F(this,"processRequest",async r=>{const{topic:i,payload:s,attestation:n,transportType:o,encryptedId:a}=r,c=s.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:s,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,s);case"wc_sessionPing":return await this.onSessionPingRequest(i,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:s,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:s,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),F(this,"onRelayEventResponse",async r=>{const{topic:i,payload:s,transportType:n}=r,o=(await this.client.core.history.get(i,s.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,s,n);case"wc_sessionSettle":return this.onSessionSettleResponse(i,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,s);case"wc_sessionExtend":return this.onSessionExtendResponse(i,s);case"wc_sessionPing":return this.onSessionPingResponse(i,s);case"wc_sessionRequest":return this.onSessionRequestResponse(i,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,s);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),F(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:s}=z("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),F(this,"shouldIgnorePairingRequest",r=>{const{topic:i,requestMethod:s}=r,n=this.expectedPairingMethodMap.get(i);return!n||n.includes(s)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),F(this,"onSessionProposeRequest",async r=>{const{topic:i,payload:s,attestation:n,encryptedId:o}=r,{params:a,id:c}=s;try{const l=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(tr.proposal_listener_not_found)),this.isValidConnect(se({},s.params));const u=a.expiryTimestamp||ge(Be.wc_sessionPropose.req.ttl),h=se({id:c,pairingTopic:i,expiryTimestamp:u,attestation:n,encryptedId:o},a);await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:n,hash:wt(JSON.stringify(s)),encryptedId:o,metadata:h.proposer.metadata});l==null||l.addTrace(Nt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(l){await this.sendError({id:c,topic:i,error:l,rpcOpts:Be.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),F(this,"onSessionProposeResponse",async(r,i,s)=>{const{id:n}=i;if(jt(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(n,{sessionTopic:u,pairingTopic:r,proposalId:n,publicKey:c});const h=await this.client.core.relayer.subscribe(u,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:r})}else if(mt(i)){await this.deleteProposal(n);const o=ne("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),F(this,"onSessionSettleRequest",async(r,i)=>{const{id:s,params:n}=i;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=i.params,g=[...this.pendingSessions.values()].find(O=>O.sessionTopic===r);if(!g)return this.client.logger.error(`Pending session not found for topic ${r}`);const w=this.client.proposal.get(g.proposalId),m=Ce(se(se(se({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:g.pairingTopic,requiredNamespaces:w.requiredNamespaces,optionalNamespaces:w.optionalNamespaces,controller:a.publicKey,self:{publicKey:g.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{transportType:le.relay,authentication:d==null?void 0:d.authentication,walletPayResult:d==null?void 0:d.walletPay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:g.pairingTopic,metadata:m.peer.metadata}),this.pendingSessions.delete(g.proposalId),this.deleteProposal(g.proposalId,!1),this.cleanupDuplicatePairings(m),await this.sendResult({id:i.id,topic:r,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:m}),this.events.emit(ne("session_connect",g.proposalId),{session:m})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),F(this,"onSessionSettleResponse",async(r,i)=>{const{id:s}=i;jt(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ne("session_approve",s),{})):mt(i)&&(await this.client.session.delete(r,ue("USER_DISCONNECTED")),this.events.emit(ne("session_approve",s),{error:i.error}))}),F(this,"onSessionUpdateRequest",async(r,i)=>{const{params:s,id:n}=i;try{const o=`${r}_session_update`,a=Zi.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:r,error:ue("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(se({topic:r},s));try{Zi.set(o,n),await this.client.session.update(r,{namespaces:s.namespaces}),await this.sendResult({id:n,topic:r,result:!0})}catch(c){throw Zi.delete(o),c}this.client.events.emit("session_update",{id:n,topic:r,params:s})}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),F(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),F(this,"onSessionUpdateResponse",(r,i)=>{const{id:s}=i,n=ne("session_update",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);jt(i)?this.events.emit(ne("session_update",s),{}):mt(i)&&this.events.emit(ne("session_update",s),{error:i.error})}),F(this,"onSessionExtendRequest",async(r,i)=>{const{id:s}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,ge(vi)),await this.sendResult({id:s,topic:r,result:!0}),this.client.events.emit("session_extend",{id:s,topic:r})}catch(n){await this.sendError({id:s,topic:r,error:n}),this.client.logger.error(n)}}),F(this,"onSessionExtendResponse",(r,i)=>{const{id:s}=i,n=ne("session_extend",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);jt(i)?this.events.emit(ne("session_extend",s),{}):mt(i)&&this.events.emit(ne("session_extend",s),{error:i.error})}),F(this,"onSessionPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:r})}catch(n){await this.sendError({id:s,topic:r,error:n}),this.client.logger.error(n)}}),F(this,"onSessionPingResponse",(r,i)=>{const{id:s}=i,n=ne("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);jt(i)?this.events.emit(ne("session_ping",s),{}):mt(i)&&this.events.emit(ne("session_ping",s),{error:i.error})},500)}),F(this,"onSessionDeleteRequest",async(r,i)=>{const{id:s}=i;try{await this.isValidDisconnect({topic:r,reason:i.params}),this.cleanupPendingSentRequestsForTopic({topic:r,error:ue("USER_DISCONNECTED")}),await this.deleteSession({topic:r,id:s})}catch(n){this.client.logger.error(n)}}),F(this,"onSessionRequest",async r=>{var i,s,n;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=r,{id:h,params:f}=a;try{await this.isValidRequest(se({topic:o},f));const d=this.client.session.get(o),g=await this.getVerifyContext({attestationId:c,hash:wt(JSON.stringify(Dt("wc_sessionRequest",f,h))),encryptedId:l,metadata:d.peer.metadata,transportType:u}),w={id:h,topic:o,params:f,verifyContext:g};await this.setPendingSessionRequest(w),u===le.link_mode&&(i=d.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((s=d.peer.metadata.redirect)==null?void 0:s.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(w):(this.addSessionRequestToSessionRequestQueue(w),this.processSessionRequestQueue())}catch(d){await this.sendError({id:h,topic:o,error:d}),this.client.logger.error(d)}}),F(this,"onSessionRequestResponse",(r,i)=>{const{id:s}=i,n=ne("session_request",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);jt(i)?this.events.emit(ne("session_request",s),{result:i.result}):mt(i)&&this.events.emit(ne("session_request",s),{error:i.error})}),F(this,"onSessionEventRequest",async(r,i)=>{const{id:s,params:n}=i;try{const o=`${r}_session_event_${n.event.name}`,a=Zi.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(se({topic:r},n)),this.client.events.emit("session_event",{id:s,topic:r,params:n}),Zi.set(o,s)}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),F(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:s}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),jt(i)?this.events.emit(ne("session_request",s),{result:i.result}):mt(i)&&this.events.emit(ne("session_request",s),{error:i.error})}),F(this,"onSessionAuthenticateRequest",async r=>{var i;const{topic:s,payload:n,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:l,authPayload:u,expiryTimestamp:h}=n.params,f=await this.getVerifyContext({attestationId:o,hash:wt(JSON.stringify(n)),encryptedId:a,metadata:l.metadata,transportType:c}),d={requester:l,pairingTopic:s,id:n.id,authPayload:u,verifyContext:f,expiryTimestamp:h};await this.setAuthRequest(n.id,{request:d,pairingTopic:s,transportType:c}),c===le.link_mode&&(i=l.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:n.params,id:n.id,verifyContext:f})}catch(l){this.client.logger.error(l);const u=n.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(n.params.requester.metadata,c),d={type:lr,receiverPublicKey:u,senderPublicKey:h};await this.sendError({id:n.id,topic:s,error:l,encodeOpts:d,rpcOpts:Be.wc_sessionAuthenticate.autoReject,appLink:f})}}),F(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),F(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Ut.idle,this.processSessionRequestQueue()},q.toMiliseconds(this.requestQueueDelay))}),F(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:i})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(n=>n.topic===r&&n.request.method==="wc_sessionRequest").forEach(n=>{this.events.emit(ne("session_request",n.request.id),{error:i})})}),F(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Ut.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.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}}),F(this,"emitSessionRequest",r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=Ut.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),F(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(s=>s.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:Dt("wc_sessionPropose",Ce(se({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id),attestation:i.attestation,encryptedId:i.encryptedId})}),F(this,"isValidConnect",async r=>{if(!Ze(r)){const{message:l}=z("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(l)}const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=r;if(Oe(i)||await this.isValidPairingTopic(i),!aS(c)){const{message:l}=z("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(s&&!Oe(s)&&Vt(s)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(s,"requiredNamespaces")}if(n&&!Oe(n)&&Vt(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),o&&!Oe(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Oe(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(s||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(u=>l.includes(u.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),F(this,"validateNamespaces",(r,i)=>{const s=oS(r,"connect()",i);if(s)throw new Error(s.message)}),F(this,"isValidApprove",async r=>{if(!Ze(r))throw new Error(z("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:s,relayProtocol:n,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),l=Wo(s,"approve()");if(l)throw new Error(l.message);const u=dh(c.requiredNamespaces,s,"approve()");if(u)throw new Error(u.message);if(!we(n,!0)){const{message:h}=z("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(h)}if(o&&!Oe(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Oe(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(s));if(!Object.keys(a).every(f=>h.has(f.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),F(this,"isValidReject",async r=>{if(!Ze(r)){const{message:n}=z("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(n)}const{id:i,reason:s}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!lS(s)){const{message:n}=z("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(n)}}),F(this,"isValidSessionSettleRequest",r=>{if(!Ze(r)){const{message:l}=z("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:i,controller:s,namespaces:n,expiry:o}=r;if(!Dg(i)){const{message:l}=z("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=eS(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Wo(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Lt(o)){const{message:l}=z("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),F(this,"isValidUpdate",async r=>{if(!Ze(r)){const{message:c}=z("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:i,namespaces:s}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const n=this.client.session.get(i),o=Wo(s,"update()");if(o)throw new Error(o.message);const a=dh(n.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)}),F(this,"isValidExtend",async r=>{if(!Ze(r)){const{message:s}=z("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(s)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),F(this,"isValidRequest",async r=>{if(!Ze(r)){const{message:c}=z("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:i,request:s,chainId:n,expiry:o}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!fh(a,n)){const{message:c}=z("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!uS(s)){const{message:c}=z("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!dS(a,n,s.method)){const{message:c}=z("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),F(this,"isValidRespond",async r=>{var i;if(!Ze(r)){const{message:a}=z("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}const{topic:s,response:n}=r;try{await this.isValidSessionTopic(s)}catch(a){throw(i=r==null?void 0:r.response)!=null&&i.id&&this.cleanupAfterResponse(r),a}if(!hS(n)){const{message:a}=z("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(a)}const o=this.client.pendingRequest.get(n.id);if(o.topic!==s){const{message:a}=z("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${n.id}, expected topic: ${o.topic}, received topic: ${s}`);throw new Error(a)}}),F(this,"isValidPing",async r=>{if(!Ze(r)){const{message:s}=z("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),F(this,"isValidEmit",async r=>{if(!Ze(r)){const{message:a}=z("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:i,event:s,chainId:n}=r;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!fh(o,n)){const{message:a}=z("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!fS(s)){const{message:a}=z("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!pS(o,n,s.name)){const{message:a}=z("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}}),F(this,"isValidDisconnect",async r=>{if(!Ze(r)){const{message:s}=z("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),F(this,"isValidAuthenticate",r=>{const{chains:i,uri:s,domain:n,nonce:o}=r;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!we(s,!1))throw new Error("uri is required parameter");if(!we(n,!1))throw new Error("domain is required parameter");if(!we(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>cr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=cr(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),F(this,"getVerifyContext",async r=>{const{attestationId:i,hash:s,encryptedId:n,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||hs,validation:"UNKNOWN",origin:o.url||""}};try{if(a===le.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:i,hash:s,encryptedId:n,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),F(this,"validateSessionProps",(r,i)=>{Object.values(r).forEach((s,n)=>{if(s==null){const{message:o}=z("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${s} for key ${Object.keys(r)[n]}`);throw new Error(o)}})}),F(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),F(this,"addToRecentlyDeleted",(r,i)=>{if(this.recentlyDeletedMap.set(r,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(s++>=n)break;this.recentlyDeletedMap.delete(o)}}}),F(this,"checkRecentlyDeleted",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:s}=z("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(s)}}),F(this,"isLinkModeEnabled",(r,i)=>{var s,n,o,a,c,l,u,h,f;return!r||i!==le.link_mode?!1:((n=(s=this.client.metadata)==null?void 0:s.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=r==null?void 0:r.redirect)==null?void 0:u.universal)!==void 0&&((h=r==null?void 0:r.redirect)==null?void 0:h.universal)!==""&&((f=r==null?void 0:r.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),F(this,"getAppLinkIfEnabled",(r,i)=>{var s;return this.isLinkModeEnabled(r,i)?(s=r==null?void 0:r.redirect)==null?void 0:s.universal:void 0}),F(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Iu(r,"topic")||"",s=decodeURIComponent(Iu(r,"wc_ev")||""),n=this.client.session.keys.includes(i);n&&this.client.session.update(i,{transportType:le.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:s,sessionExists:n})}),F(this,"registerLinkModeListeners",async()=>{var r;if(Nc()||Nr()&&(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 s=await i.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}),F(this,"getTVFApproveParams",r=>{try{const i=Og(r.namespaces),s=MI(r.namespaces),n=qI(r.namespaces),o=r.sessionProperties,a=r.scopedProperties;return{approvedChains:i,approvedMethods:s,approvedEvents:n,sessionProperties:o,scopedProperties:a}}catch(i){return this.client.logger.warn(i,"Error getting TVF approve params"),{}}}),F(this,"getTVFParams",(r,i,s)=>{var n,o,a;if(!((n=i.request)!=null&&n.method))return{};const c={correlationId:r,rpcMethods:[i.request.method],chainId:i.chainId};try{const l=this.extractTxHashesFromResult(i.request,s);c.txHashes=l,c.contractAddresses=this.isValidContractData(i.request.params)?[(a=(o=i.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn(l,"Error getting TVF params")}return c}),F(this,"isValidContractData",r=>{var i;if(!r)return!1;try{const s=(r==null?void 0:r.data)||((i=r==null?void 0:r[0])==null?void 0:i.data);if(!s.startsWith("0x"))return!1;const n=s.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),F(this,"extractTxHashesFromResult",(r,i)=>{var s;try{if(!i)return[];const n=r.method,o=u6[n];if(n==="sui_signTransaction")return[P_(i.transactionBytes)];if(n==="near_signTransaction")return[Cu(i)];if(n==="near_signTransactions")return i.map(c=>Cu(c));if(n==="xrpl_signTransactionFor"||n==="xrpl_signTransaction")return[(s=i.tx_json)==null?void 0:s.hash];if(n==="polkadot_signTransaction")return[CS({transaction:r.params.transactionPayload,signature:i.signature})];if(n==="algo_signTxn")return vt(i)?i.map(c=>Tu(c)):[Tu(i)];if(n==="cosmos_signDirect")return[C_(i)];if(n==="wallet_sendCalls")return T_(i);if(typeof i=="string")return[i];const a=i[o.key];if(vt(a))return n==="solana_signAllTransactions"?a.map(c=>A_(c)):a;if(typeof a=="string")return[a]}catch(n){this.client.logger.warn(n,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,s]of Object.entries(r))for(const n of s)try{await this.onProviderMessageEvent({topic:i,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${n}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(ye.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:i,attestation:s,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(pn)?this.client.auth.authKeys.get(pn):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,i,{receiverPublicKey:o,encoding:n===le.link_mode?Pr:Qe});Yc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:s,transportType:n,encryptedId:wt(i)})):io(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:n}),this.client.core.history.delete(r,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:n})),await this.client.core.relayer.messages.ack(r,i)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${i}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(gt.expired,async e=>{const{topic:r,id:i}=$p(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,z("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,z("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(Wr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Wr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!we(e,!1)){const{message:r}=z("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}=z("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(Lt(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=z("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!we(e,!1)){const{message:r}=z("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}=z("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(Lt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=z("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=z("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(we(e,!1)){const{message:r}=z("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=z("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!cS(e)){const{message:r}=z("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=z("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(Lt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=z("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}validateRequestExpiry(e){if(e&&!wS(e,ta)){const{message:r}=z("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${ta.min} and ${ta.max}`);throw new Error(r)}}}class I6 extends fi{constructor(e,r){super(e,r,a6,Jc),this.core=e,this.logger=r}}let S6=class extends fi{constructor(e,r){super(e,r,c6,Jc),this.core=e,this.logger=r}};class O6 extends fi{constructor(e,r){super(e,r,h6,Jc,i=>i.id),this.core=e,this.logger=r}}class $6 extends fi{constructor(e,r){super(e,r,g6,no,()=>pn),this.core=e,this.logger=r}}class D6 extends fi{constructor(e,r){super(e,r,y6,no),this.core=e,this.logger=r}}class A6 extends fi{constructor(e,r){super(e,r,w6,no,i=>i.id),this.core=e,this.logger=r}}var P6=Object.defineProperty,B6=(t,e,r)=>e in t?P6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ra=(t,e,r)=>B6(t,typeof e!="symbol"?e+"":e,r);class C6{constructor(e,r){this.core=e,this.logger=r,ra(this,"authKeys"),ra(this,"pairingTopics"),ra(this,"requests"),this.authKeys=new $6(this.core,this.logger),this.pairingTopics=new D6(this.core,this.logger),this.requests=new A6(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var T6=Object.defineProperty,R6=(t,e,r)=>e in t?T6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ee=(t,e,r)=>R6(t,typeof e!="symbol"?e+"":e,r);class Xc extends T8{constructor(e){super(e),ee(this,"protocol",ty),ee(this,"version",ry),ee(this,"name",ea.name),ee(this,"metadata"),ee(this,"core"),ee(this,"logger"),ee(this,"events",new xt.EventEmitter),ee(this,"engine"),ee(this,"session"),ee(this,"proposal"),ee(this,"pendingRequest"),ee(this,"auth"),ee(this,"signConfig"),ee(this,"on",(i,s)=>this.events.on(i,s)),ee(this,"once",(i,s)=>this.events.once(i,s)),ee(this,"off",(i,s)=>this.events.off(i,s)),ee(this,"removeListener",(i,s)=>this.events.removeListener(i,s)),ee(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),ee(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"update",async i=>{try{return await this.engine.update(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"request",async i=>{try{return await this.engine.request(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"find",i=>{try{return this.engine.find(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),ee(this,"authenticate",async(i,s)=>{try{return await this.engine.authenticate(i,s)}catch(n){throw this.logger.error(n.message),n}}),ee(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),this.name=(e==null?void 0:e.name)||ea.name,this.metadata=xx(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const r=Wc({logger:(e==null?void 0:e.logger)||ea.logger,name:this.name});this.logger=r,this.core=(e==null?void 0:e.core)||new o6(e),this.session=new S6(this.core,this.logger),this.proposal=new I6(this.core,this.logger),this.pendingRequest=new O6(this.core,this.logger),this.engine=new _6(this),this.auth=new C6(this.core,this.logger)}static async init(e){const r=new Xc(e);return await r.initialize(),r}get context(){return it(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")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const U6=Xc;var nc={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof Ft<"u"&&Ft,i=function(){function n(){this.fetch=!1,this.DOMException=r.DOMException}return n.prototype=r,new n}();(function(n){(function(o){var a=typeof n<"u"&&n||typeof self<"u"&&self||typeof Ft<"u"&&Ft||{},c={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function l(p){return p&&DataView.prototype.isPrototypeOf(p)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],h=ArrayBuffer.isView||function(p){return p&&u.indexOf(Object.prototype.toString.call(p))>-1};function f(p){if(typeof p!="string"&&(p=String(p)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(p)||p==="")throw new TypeError('Invalid character in header field name: "'+p+'"');return p.toLowerCase()}function d(p){return typeof p!="string"&&(p=String(p)),p}function g(p){var y={next:function(){var v=p.shift();return{done:v===void 0,value:v}}};return c.iterable&&(y[Symbol.iterator]=function(){return y}),y}function w(p){this.map={},p instanceof w?p.forEach(function(y,v){this.append(v,y)},this):Array.isArray(p)?p.forEach(function(y){if(y.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+y.length);this.append(y[0],y[1])},this):p&&Object.getOwnPropertyNames(p).forEach(function(y){this.append(y,p[y])},this)}w.prototype.append=function(p,y){p=f(p),y=d(y);var v=this.map[p];this.map[p]=v?v+", "+y:y},w.prototype.delete=function(p){delete this.map[f(p)]},w.prototype.get=function(p){return p=f(p),this.has(p)?this.map[p]:null},w.prototype.has=function(p){return this.map.hasOwnProperty(f(p))},w.prototype.set=function(p,y){this.map[f(p)]=d(y)},w.prototype.forEach=function(p,y){for(var v in this.map)this.map.hasOwnProperty(v)&&p.call(y,this.map[v],v,this)},w.prototype.keys=function(){var p=[];return this.forEach(function(y,v){p.push(v)}),g(p)},w.prototype.values=function(){var p=[];return this.forEach(function(y){p.push(y)}),g(p)},w.prototype.entries=function(){var p=[];return this.forEach(function(y,v){p.push([v,y])}),g(p)},c.iterable&&(w.prototype[Symbol.iterator]=w.prototype.entries);function m(p){if(!p._noBody){if(p.bodyUsed)return Promise.reject(new TypeError("Already read"));p.bodyUsed=!0}}function O(p){return new Promise(function(y,v){p.onload=function(){y(p.result)},p.onerror=function(){v(p.error)}})}function C(p){var y=new FileReader,v=O(y);return y.readAsArrayBuffer(p),v}function b(p){var y=new FileReader,v=O(y),S=/charset=([A-Za-z0-9_-]+)/.exec(p.type),E=S?S[1]:"utf-8";return y.readAsText(p,E),v}function x(p){for(var y=new Uint8Array(p),v=new Array(y.length),S=0;S<y.length;S++)v[S]=String.fromCharCode(y[S]);return v.join("")}function A(p){if(p.slice)return p.slice(0);var y=new Uint8Array(p.byteLength);return y.set(new Uint8Array(p)),y.buffer}function B(){return this.bodyUsed=!1,this._initBody=function(p){this.bodyUsed=this.bodyUsed,this._bodyInit=p,p?typeof p=="string"?this._bodyText=p:c.blob&&Blob.prototype.isPrototypeOf(p)?this._bodyBlob=p:c.formData&&FormData.prototype.isPrototypeOf(p)?this._bodyFormData=p:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)?this._bodyText=p.toString():c.arrayBuffer&&c.blob&&l(p)?(this._bodyArrayBuffer=A(p.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(p)||h(p))?this._bodyArrayBuffer=A(p):this._bodyText=p=Object.prototype.toString.call(p):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof p=="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(p)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var p=m(this);if(p)return p;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 p=m(this);return p||(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(C);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var p=m(this);if(p)return p;if(this._bodyBlob)return b(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(x(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},c.formData&&(this.formData=function(){return this.text().then(k)}),this.json=function(){return this.text().then(JSON.parse)},this}var T=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function R(p){var y=p.toUpperCase();return T.indexOf(y)>-1?y:p}function D(p,y){if(!(this instanceof D))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');y=y||{};var v=y.body;if(p instanceof D){if(p.bodyUsed)throw new TypeError("Already read");this.url=p.url,this.credentials=p.credentials,y.headers||(this.headers=new w(p.headers)),this.method=p.method,this.mode=p.mode,this.signal=p.signal,!v&&p._bodyInit!=null&&(v=p._bodyInit,p.bodyUsed=!0)}else this.url=String(p);if(this.credentials=y.credentials||this.credentials||"same-origin",(y.headers||!this.headers)&&(this.headers=new w(y.headers)),this.method=R(y.method||this.method||"GET"),this.mode=y.mode||this.mode||null,this.signal=y.signal||this.signal||function(){if("AbortController"in a){var _=new AbortController;return _.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&v)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(v),(this.method==="GET"||this.method==="HEAD")&&(y.cache==="no-store"||y.cache==="no-cache")){var S=/([?&])_=[^&]*/;if(S.test(this.url))this.url=this.url.replace(S,"$1_="+new Date().getTime());else{var E=/\?/;this.url+=(E.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}D.prototype.clone=function(){return new D(this,{body:this._bodyInit})};function k(p){var y=new FormData;return p.trim().split("&").forEach(function(v){if(v){var S=v.split("="),E=S.shift().replace(/\+/g," "),_=S.join("=").replace(/\+/g," ");y.append(decodeURIComponent(E),decodeURIComponent(_))}}),y}function j(p){var y=new w,v=p.replace(/\r?\n[\t ]+/g," ");return v.split("\r").map(function(S){return S.indexOf(`
41
- `)===0?S.substr(1,S.length):S}).forEach(function(S){var E=S.split(":"),_=E.shift().trim();if(_){var U=E.join(":").trim();try{y.append(_,U)}catch(N){console.warn("Response "+N.message)}}}),y}B.call(D.prototype);function P(p,y){if(!(this instanceof P))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(y||(y={}),this.type="default",this.status=y.status===void 0?200:y.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=y.statusText===void 0?"":""+y.statusText,this.headers=new w(y.headers),this.url=y.url||"",this._initBody(p)}B.call(P.prototype),P.prototype.clone=function(){return new P(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new w(this.headers),url:this.url})},P.error=function(){var p=new P(null,{status:200,statusText:""});return p.ok=!1,p.status=0,p.type="error",p};var I=[301,302,303,307,308];P.redirect=function(p,y){if(I.indexOf(y)===-1)throw new RangeError("Invalid status code");return new P(null,{status:y,headers:{location:p}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(y,v){this.message=y,this.name=v;var S=Error(y);this.stack=S.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function $(p,y){return new Promise(function(v,S){var E=new D(p,y);if(E.signal&&E.signal.aborted)return S(new o.DOMException("Aborted","AbortError"));var _=new XMLHttpRequest;function U(){_.abort()}_.onload=function(){var L={statusText:_.statusText,headers:j(_.getAllResponseHeaders()||"")};E.url.indexOf("file://")===0&&(_.status<200||_.status>599)?L.status=200:L.status=_.status,L.url="responseURL"in _?_.responseURL:L.headers.get("X-Request-URL");var M="response"in _?_.response:_.responseText;setTimeout(function(){v(new P(M,L))},0)},_.onerror=function(){setTimeout(function(){S(new TypeError("Network request failed"))},0)},_.ontimeout=function(){setTimeout(function(){S(new TypeError("Network request timed out"))},0)},_.onabort=function(){setTimeout(function(){S(new o.DOMException("Aborted","AbortError"))},0)};function N(L){try{return L===""&&a.location.href?a.location.href:L}catch{return L}}if(_.open(E.method,N(E.url),!0),E.credentials==="include"?_.withCredentials=!0:E.credentials==="omit"&&(_.withCredentials=!1),"responseType"in _&&(c.blob?_.responseType="blob":c.arrayBuffer&&(_.responseType="arraybuffer")),y&&typeof y.headers=="object"&&!(y.headers instanceof w||a.Headers&&y.headers instanceof a.Headers)){var V=[];Object.getOwnPropertyNames(y.headers).forEach(function(L){V.push(f(L)),_.setRequestHeader(L,d(y.headers[L]))}),E.headers.forEach(function(L,M){V.indexOf(M)===-1&&_.setRequestHeader(M,L)})}else E.headers.forEach(function(L,M){_.setRequestHeader(M,L)});E.signal&&(E.signal.addEventListener("abort",U),_.onreadystatechange=function(){_.readyState===4&&E.signal.removeEventListener("abort",U)}),_.send(typeof E._bodyInit>"u"?null:E._bodyInit)})}return $.polyfill=!0,a.fetch||(a.fetch=$,a.Headers=w,a.Request=D,a.Response=P),o.Headers=w,o.Request=D,o.Response=P,o.fetch=$,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=r.fetch?r:i;e=s.fetch,e.default=s.fetch,e.fetch=s.fetch,e.Headers=s.Headers,e.Request=s.Request,e.Response=s.Response,t.exports=e})(nc,nc.exports);var N6=nc.exports;const sf=Dy(N6);var k6=Object.defineProperty,j6=Object.defineProperties,F6=Object.getOwnPropertyDescriptors,nf=Object.getOwnPropertySymbols,L6=Object.prototype.hasOwnProperty,M6=Object.prototype.propertyIsEnumerable,of=(t,e,r)=>e in t?k6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,af=(t,e)=>{for(var r in e||(e={}))L6.call(e,r)&&of(t,r,e[r]);if(nf)for(var r of nf(e))M6.call(e,r)&&of(t,r,e[r]);return t},cf=(t,e)=>j6(t,F6(e));const q6={Accept:"application/json","Content-Type":"application/json"},z6="POST",lf={headers:q6,method:z6},uf=10;let sy=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new xt.EventEmitter,this.isAvailable=!1,this.registering=!1,!Oh(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=si(e),i=await(await sf(this.url,cf(af({},lf),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!Oh(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,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return s(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=si({id:1,jsonrpc:"2.0",method:"test",params:[]});await sf(e,cf(af({},lf),{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"?ii(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),s=i.message||i.toString(),n=ro(e,s);this.events.emit("payload",n)}parseError(e,r=this.url){return Tg(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>uf&&this.events.setMaxListeners(uf)}};function Qc(t){return t==null||typeof t!="object"&&typeof t!="function"}function ny(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function oy(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const V6="[object RegExp]",ay="[object String]",cy="[object Number]",ly="[object Boolean]",uy="[object Arguments]",H6="[object Symbol]",K6="[object Date]",W6="[object Map]",G6="[object Set]",Y6="[object Array]",Z6="[object ArrayBuffer]",J6="[object Object]",X6="[object DataView]",Q6="[object Uint8Array]",eP="[object Uint8ClampedArray]",tP="[object Uint16Array]",rP="[object Uint32Array]",iP="[object Int8Array]",sP="[object Int16Array]",nP="[object Int32Array]",oP="[object Float32Array]",aP="[object Float64Array]";function el(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function cP(t,e){return Si(t,void 0,t,new Map,e)}function Si(t,e,r,i=new Map,s=void 0){const n=s==null?void 0:s(t,e,r,i);if(n!=null)return n;if(Qc(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]=Si(t[a],a,r,i,s);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,Si(c,a,r,i,s));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(Si(a,void 0,r,i,s));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(el(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Si(t[a],a,r,i,s);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),Gr(o,t,r,i,s),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),Gr(o,t,r,i,s),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),Gr(o,t,r,i,s),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,Gr(o,t,r,i,s),o}if(typeof t=="object"&&lP(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),Gr(o,t,r,i,s),o}return t}function Gr(t,e,r=t,i,s){const n=[...Object.keys(e),...ny(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Si(e[a],a,r,i,s))}}function lP(t){switch(oy(t)){case uy:case Y6:case Z6:case X6:case ly:case K6:case oP:case aP:case iP:case sP:case nP:case W6:case cy:case J6:case V6:case G6:case ay:case H6:case Q6:case eP:case tP:case rP:return!0;default:return!1}}function uP(t,e){return cP(t,(r,i,s,n)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case cy:case ay:case ly:{const o=new t.constructor(t==null?void 0:t.valueOf());return Gr(o,t),o}case uy:{const o={};return Gr(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function hf(t){return uP(t)}function ff(t){return t!==null&&typeof t=="object"&&oy(t)==="[object Arguments]"}function df(t){return typeof t=="object"&&t!==null}function hP(){}function fP(t){return el(t)}function dP(t){var r;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const i=t[Symbol.toStringTag];return i==null||!((r=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&r.writable)?!1:t.toString()===`[object ${i}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function pP(t){if(Qc(t))return t;if(Array.isArray(t)||el(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 gP(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let s=t;for(let n=0;n<r.length;n++){const o=r[n];s=oc(s,o,i,new Map)}return s}function oc(t,e,r,i){if(Qc(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return pP(i.get(e));if(i.set(e,t),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const s=[...Object.keys(e),...ny(e)];for(let n=0;n<s.length;n++){const o=s[n];let a=e[o],c=t[o];if(ff(a)&&(a={...a}),ff(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=hf(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const u=[],h=Reflect.ownKeys(c);for(let f=0;f<h.length;f++){const d=h[f];u[d]=c[d]}c=u}else c=[];const l=r(c,a,o,t,e,i);l!=null?t[o]=l:Array.isArray(a)||df(c)&&df(a)?t[o]=oc(c,a,r,i):c==null&&dP(a)?t[o]=oc({},a,r,i):c==null&&fP(a)?t[o]=hf(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function yP(t,...e){return gP(t,...e,hP)}const pf="error",wP="wss://relay.walletconnect.org",mP="wc",hy="universal_provider",tn=`${mP}@2:${hy}:`,fy="https://rpc.walletconnect.org/v1/",dy="generic",bP=`${fy}bundler`,Pi="call_status",vP=86400,tl={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var EP=Object.defineProperty,xP=Object.defineProperties,_P=Object.getOwnPropertyDescriptors,gf=Object.getOwnPropertySymbols,IP=Object.prototype.hasOwnProperty,SP=Object.prototype.propertyIsEnumerable,yf=(t,e,r)=>e in t?EP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rn=(t,e)=>{for(var r in e||(e={}))IP.call(e,r)&&yf(t,r,e[r]);if(gf)for(var r of gf(e))SP.call(e,r)&&yf(t,r,e[r]);return t},OP=(t,e)=>xP(t,_P(e));function py(t,e,r){var i;const s=cr(t);return((i=e.rpcMap)==null?void 0:i[s.reference])||`${fy}?chainId=${s.namespace}:${s.reference}&projectId=${r}`}function $P(t){return t.includes(":")?t.split(":")[1]:t}function gy(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function DP(t,e){const r=Object.keys(e.namespaces).filter(s=>s.includes(t));if(!r.length)return[];const i=[];return r.forEach(s=>{const n=e.namespaces[s].accounts;i.push(...n)}),i}function wf(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>{var i,s;return((i=r==null?void 0:r.chains)==null?void 0:i.length)&&((s=r==null?void 0:r.chains)==null?void 0:s.length)>0}))}function sn(t={},e={}){const r=wf(mf(t)),i=wf(mf(e));return yP(r,i)}function mf(t){var e,r,i,s,n;const o={};if(!Vt(t))return o;for(const[a,c]of Object.entries(t)){const l=to(a)?[a]:c.chains,u=c.methods||[],h=c.events||[],f=c.rpcMap||{},d=Ii(a);o[d]=OP(rn(rn({},o[d]),c),{chains:zt(l,(e=o[d])==null?void 0:e.chains),methods:zt(u,(r=o[d])==null?void 0:r.methods),events:zt(h,(i=o[d])==null?void 0:i.events)}),(Vt(f)||Vt(((s=o[d])==null?void 0:s.rpcMap)||{}))&&(o[d].rpcMap=rn(rn({},f),(n=o[d])==null?void 0:n.rpcMap))}return o}function bf(t){return t.includes(":")?t.split(":")[2]:t}function vf(t){const e={};for(const[r,i]of Object.entries(t)){const s=i.methods||[],n=i.events||[],o=i.accounts||[],a=to(r)?[r]:i.chains?i.chains:gy(i.accounts);e[r]={chains:a,methods:s,events:n,accounts:o}}return e}function ia(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))}function AP(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const yy={},Bi=t=>yy[t],sa=(t,e)=>{yy[t]=e};var PP=Object.defineProperty,Ef=Object.getOwnPropertySymbols,BP=Object.prototype.hasOwnProperty,CP=Object.prototype.propertyIsEnumerable,xf=(t,e,r)=>e in t?PP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_f=(t,e)=>{for(var r in e||(e={}))BP.call(e,r)&&xf(t,r,e[r]);if(Ef)for(var r of Ef(e))CP.call(e,r)&&xf(t,r,e[r]);return t};const If="eip155",TP=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],RP=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,na=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,Sf=t=>Object.keys(t).filter(e=>TP.includes(e)).reduce((e,r)=>(e[r]=UP(t[r]),e),{}),UP=t=>typeof t=="string"&&AP(t)?JSON.parse(t):t,NP=(t,e,r)=>{const{sessionProperties:i={},scopedProperties:s={}}=t,n={};if(!Vt(s)&&!Vt(i))return;const o=Sf(i);for(const a of r){const c=RP(a);if(!c)continue;n[na(c)]=o;const l=s==null?void 0:s[`${If}:${c}`];if(l){const u=l==null?void 0:l[`${If}:${c}:${e}`];n[na(c)]=_f(_f({},n[na(c)]),Sf(u||l))}}for(const[a,c]of Object.entries(n))Object.keys(c).length===0&&delete n[a];return Object.keys(n).length>0?n:void 0};var kP=Object.defineProperty,jP=(t,e,r)=>e in t?kP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,FP=(t,e,r)=>jP(t,e+"",r);let oa,LP=class wy{constructor(e){FP(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,r){return await this.storage.setItem(e,r)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return oa||(oa=new wy(e)),oa}};var MP=Object.defineProperty,qP=Object.defineProperties,zP=Object.getOwnPropertyDescriptors,Of=Object.getOwnPropertySymbols,VP=Object.prototype.hasOwnProperty,HP=Object.prototype.propertyIsEnumerable,$f=(t,e,r)=>e in t?MP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,KP=(t,e)=>{for(var r in e||(e={}))VP.call(e,r)&&$f(t,r,e[r]);if(Of)for(var r of Of(e))HP.call(e,r)&&$f(t,r,e[r]);return t},WP=(t,e)=>qP(t,zP(e));async function GP(t,e){const r=cr(t.result.capabilities.caip345.caip2),i=t.result.capabilities.caip345.transactionHashes,s=await Promise.allSettled(i.map(h=>YP(r.reference,h,e))),n=s.filter(h=>h.status==="fulfilled").map(h=>h.value).filter(h=>h);s.filter(h=>h.status==="rejected").forEach(h=>console.warn("Failed to fetch transaction receipt:",h.reason));const o=!n.length||n.some(h=>!h),a=n.every(h=>(h==null?void 0:h.status)==="0x1"),c=n.every(h=>(h==null?void 0:h.status)==="0x0"),l=n.some(h=>(h==null?void 0:h.status)==="0x0");let u;return o?u=100:a?u=200:c?u=500:l&&(u=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:n,status:u}}async function YP(t,e,r){return await r(parseInt(t)).request(Dt("eth_getTransactionReceipt",[e]))}async function ZP({sendCalls:t,storage:e}){const r=await e.getItem(Pi);await e.setItem(Pi,WP(KP({},r),{[t.result.id]:{request:t.request,result:t.result,expiry:ge(vP)}}))}async function JP({resultId:t,storage:e}){const r=await e.getItem(Pi);if(r){delete r[t],await e.setItem(Pi,r);for(const i in r)Lt(r[i].expiry)&&delete r[i];await e.setItem(Pi,r)}}async function XP({resultId:t,storage:e}){const r=await e.getItem(Pi),i=r==null?void 0:r[t];if(i&&!Lt(i.expiry))return i;await JP({resultId:t,storage:e})}var QP=Object.defineProperty,e4=Object.defineProperties,t4=Object.getOwnPropertyDescriptors,Df=Object.getOwnPropertySymbols,r4=Object.prototype.hasOwnProperty,i4=Object.prototype.propertyIsEnumerable,ac=(t,e,r)=>e in t?QP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,aa=(t,e)=>{for(var r in e||(e={}))r4.call(e,r)&&ac(t,r,e[r]);if(Df)for(var r of Df(e))i4.call(e,r)&&ac(t,r,e[r]);return t},ca=(t,e)=>e4(t,t4(e)),zr=(t,e,r)=>ac(t,typeof e!="symbol"?e+"":e,r);class s4{constructor(e){zr(this,"name","eip155"),zr(this,"client"),zr(this,"chainId"),zr(this,"namespace"),zr(this,"httpProviders"),zr(this,"events"),zr(this,"storage"),this.namespace=e.namespace,this.events=Bi("events"),this.client=Bi("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=LP.getStorage(this.client.core.storage)}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);case"wallet_sendCalls":return await this.sendCalls(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);const i=this.chainId;this.chainId=parseInt(e),this.events.emit(tl.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}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||py(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zc(new sy(i,Bi("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 s=parseInt($P(r));e[s]=this.createHttpProvider(s,(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(e){const r=e||this.chainId;return this.httpProviders[r]||(this.httpProviders=ca(aa({},this.httpProviders),{[r]:this.createHttpProvider(r)}),this.httpProviders[r])}async handleSwitchChain(e){var r,i;let s=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";s=s.startsWith("0x")?s:`0x${s}`;const n=parseInt(s,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:s}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var r,i,s,n,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0],c=((n=(s=e.request)==null?void 0:s.params)==null?void 0:n[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{},h=`${a}${c.join(",")}`,f=u==null?void 0:u[h];if(f)return f;let d;try{d=NP(l,a,c)}catch(w){console.warn("Failed to extract capabilities from session",w)}if(d)return d;const g=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:ca(aa({},l.sessionProperties||{}),{capabilities:ca(aa({},u||{}),{[h]:g})})})}catch(w){console.warn("Failed to update session with capabilities",w)}return g}async getCallStatus(e){var r,i,s;const n=this.client.session.get(e.topic),o=(r=n.sessionProperties)==null?void 0:r.bundler_name;if(o){const l=this.getBundlerUrl(e.chainId,o);try{return await this.getUserOperationReceipt(l,e)}catch(u){console.warn("Failed to fetch call status from bundler",u,l)}}const a=(i=n.sessionProperties)==null?void 0:i.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from custom bundler",l,a)}const c=await XP({resultId:(s=e.request.params)==null?void 0:s[0],storage:this.storage});if(c)try{return await GP(c,this.getHttpProvider.bind(this))}catch(l){console.warn("Failed to fetch call status from stored send calls",l,c)}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 s=new URL(e),n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Dt("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,r){return`${bP}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}async sendCalls(e){var r,i,s;const n=await this.client.request(e),o=(r=e.request.params)==null?void 0:r[0],a=n==null?void 0:n.id,c=(n==null?void 0:n.capabilities)||{},l=(i=c==null?void 0:c.caip345)==null?void 0:i.caip2,u=(s=c==null?void 0:c.caip345)==null?void 0:s.transactionHashes;return!a||!l||!(u!=null&&u.length)||await ZP({sendCalls:{request:o,result:n},storage:this.storage}),n}}var n4=Object.defineProperty,o4=(t,e,r)=>e in t?n4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ei=(t,e,r)=>o4(t,typeof e!="symbol"?e+"":e,r);class a4{constructor(e){Ei(this,"name",dy),Ei(this,"client"),Ei(this,"httpProviders"),Ei(this,"events"),Ei(this,"namespace"),Ei(this,"chainId"),this.namespace=e.namespace,this.events=Bi("events"),this.client=Bi("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),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);const i=this.chainId;this.chainId=e,this.events.emit(tl.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}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]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return cr(e).namespace}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(s=>{var n,o;const a=cr(s),c=(o=(n=this.namespace)==null?void 0:n.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];i[a.reference]=this.createHttpProvider(s,c)}),i}getHttpProvider(e){const r=cr(e).reference,i=this.httpProviders[r];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||py(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zc(new sy(i,Bi("disableProviderPing")))}}var c4=Object.defineProperty,l4=Object.defineProperties,u4=Object.getOwnPropertyDescriptors,Af=Object.getOwnPropertySymbols,h4=Object.prototype.hasOwnProperty,f4=Object.prototype.propertyIsEnumerable,cc=(t,e,r)=>e in t?c4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ts=(t,e)=>{for(var r in e||(e={}))h4.call(e,r)&&cc(t,r,e[r]);if(Af)for(var r of Af(e))f4.call(e,r)&&cc(t,r,e[r]);return t},nn=(t,e)=>l4(t,u4(e)),nt=(t,e,r)=>cc(t,typeof e!="symbol"?e+"":e,r);class rl{constructor(e){nt(this,"client"),nt(this,"namespaces"),nt(this,"optionalNamespaces"),nt(this,"sessionProperties"),nt(this,"scopedProperties"),nt(this,"events",new uc),nt(this,"rpcProviders",{}),nt(this,"session"),nt(this,"providerOpts"),nt(this,"logger"),nt(this,"uri"),nt(this,"disableProviderPing",!1),nt(this,"connectParams");var r,i;this.providerOpts=e,this.logger=Wc({logger:(r=e.logger)!=null?r:pf,name:(i=this.providerOpts.name)!=null?i:hy}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const r=new rl(e);return await r.initialize(),r}async request(e,r,i){const[s,n]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:ts({},e),chainId:`${s}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,s){const n=new Date().getTime();this.request(e,i,s).then(o=>r(null,xs(n,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:ue("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=e,this.setNamespaces(e),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:s}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await s();if(this.session=n.session,this.session){const o=vf(this.session.namespaces);this.namespaces=sn(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}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){var r,i;const{uri:s,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(r=this.connectParams)==null?void 0:r.authentication,walletPay:(i=this.connectParams)==null?void 0:i.walletPay});s&&(this.uri=s,this.events.emit("display_uri",s));const o=await n();this.session=o;const a=vf(o.namespaces);return this.namespaces=sn(this.namespaces,a),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,s]=this.validateChain(e);this.getProvider(i).setDefaultChain(s,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(!vt(r))return;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}`)}catch(r){this.logger.warn(r,"Failed to cleanup pending pairings")}}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 U6.init({core:this.providerOpts.core,logger:this.providerOpts.logger||pf,relayUrl:this.providerOpts.relayUrl||wP,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(i,"Failed to get session"),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=>Ii(r)))];sa("client",this.client),sa("events",this.events),sa("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=DP(r,this.session);if((i==null?void 0:i.length)===0)return;const s=gy(i),n=sn(this.namespaces,this.optionalNamespaces),o=nn(ts({},n[r]),{accounts:i,chains:s});switch(r){case"eip155":this.rpcProviders[r]=new s4({namespace:o});break;default:this.rpcProviders[r]=new a4({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:s}=e;if(s!==((r=this.session)==null?void 0:r.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&&vt(o)&&this.events.emit("accountsChanged",o.map(bf))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=Ii(o),l=ia(o)!==ia(a)?`${c}:${ia(a)}`:o;this.onChainChanged({currentCaipChainId:l})}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var i,s;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=r,o=(s=this.client)==null?void 0:s.session.get(e);this.session=nn(ts({},o),{namespaces:n}),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",nn(ts({},ue("USER_DISCONNECTED")),{data:e.topic})))}),this.on(tl.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(nn(ts({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[dy]}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:s,scopedProperties:n}=e;this.optionalNamespaces=sn(r,i),this.sessionProperties=s,this.scopedProperties=n}validateChain(e){const[r,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(o=>Ii(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 s=Ii(Object.keys(this.namespaces)[0]),n=this.rpcProviders[s].getDefaultChain();return[s,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:r,internal:i=!1}){if(!this.namespaces)return;const[s,n]=this.validateChain(e);n&&(this.updateNamespaceChain(s,n),i?(this.events.emit("chainChanged",n),this.emitAccountsChangedOnChainChange({namespace:s,currentCaipChainId:e,previousCaipChainId:r})):this.getProvider(s).setDefaultChain(n),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:r,previousCaipChainId:i}){var s,n;try{if(i===r)return;const o=(n=(s=this.session)==null?void 0:s.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${r}:`)).map(bf);if(!vt(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,r){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${r}`,s={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,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,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,r){var i;const s=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${tn}/${e}${s}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${tn}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${tn}/${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(tn)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn(r,"Failed to cleanup storage")}}}const d4=rl,p4="wc",g4="ethereum_provider",y4=`${p4}@2:${g4}:`,w4="https://rpc.walletconnect.org/v1/",Rn=["eth_sendTransaction","personal_sign"],my=["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"],Un=["chainChanged","accountsChanged"],by=["chainChanged","accountsChanged","message","disconnect","connect"],m4=async()=>{const{createAppKit:t}=await Ay(()=>import("./core-D5PQaXFb.js").then(e=>e.bt),__vite__mapDeps([0,1]));return t};var b4=Object.defineProperty,v4=Object.defineProperties,E4=Object.getOwnPropertyDescriptors,Pf=Object.getOwnPropertySymbols,x4=Object.prototype.hasOwnProperty,_4=Object.prototype.propertyIsEnumerable,lc=(t,e,r)=>e in t?b4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hr=(t,e)=>{for(var r in e||(e={}))x4.call(e,r)&&lc(t,r,e[r]);if(Pf)for(var r of Pf(e))_4.call(e,r)&&lc(t,r,e[r]);return t},rs=(t,e)=>v4(t,E4(e)),ot=(t,e,r)=>lc(t,typeof e!="symbol"?e+"":e,r);function Nn(t){return Number(t[0].split(":")[1])}function on(t){return`0x${t.toString(16)}`}function I4(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:s,events:n,optionalEvents:o,rpcMap:a}=t;if(!vt(e))throw new Error("Invalid chains");const c={chains:e,methods:i||Rn,events:n||Un,rpcMap:Hr({},e.length?{[Nn(e)]:a[Nn(e)]}:{})},l=n==null?void 0:n.filter(d=>!Un.includes(d)),u=i==null?void 0:i.filter(d=>!Rn.includes(d));if(!r&&!o&&!s&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:e.length?c:void 0};const h=(l==null?void 0:l.length)&&(u==null?void 0:u.length)||!r,f={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:my))],events:[...new Set(c.events.concat(o!=null&&o.length?o:by))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?f:void 0}}class oo{constructor(){ot(this,"events",new xt.EventEmitter),ot(this,"namespace","eip155"),ot(this,"accounts",[]),ot(this,"signer"),ot(this,"chainId",1),ot(this,"modal"),ot(this,"rpc"),ot(this,"STORAGE_KEY",y4),ot(this,"on",(e,r)=>(this.events.on(e,r),this)),ot(this,"once",(e,r)=>(this.events.once(e,r),this)),ot(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),ot(this,"off",(e,r)=>(this.events.off(e,r),this)),ot(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new oo;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:s}=I4(this.rpc);try{const n=await new Promise(async(a,c)=>{var l,u;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(u=this.modal)==null||u.subscribeState(f=>{!f.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const h=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(rs(Hr({namespaces:Hr({},i&&{[this.namespace]:i})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:h})).then(f=>{a(f)}).catch(f=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),c(new Error(f.message))})});if(!n)return;const o=bu(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:on(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}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==null?void 0:e.chains});try{const s=await new Promise(async(o,a)=>{var c,l;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(l=this.modal)==null||l.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(rs(Hr({},e),{chains:this.rpc.chains}),r).then(u=>{o(u)}).catch(u=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(u.message))})}),n=s.session;if(n){const o=bu(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:on(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}finally{(i=this.modal)==null||i.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params: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",on(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",rs(Hr({},ue("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",on(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,s]=e.split(":");return{chainId:`${r}:${i}`,address:s}}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 s=(r=e==null?void 0:e.chains)!=null?r:[],n=(i=e==null?void 0:e.optionalChains)!=null?i:[],o=s.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=s.length?(e==null?void 0:e.methods)||Rn:[],c=s.length?(e==null?void 0:e.events)||Un:[],l=(e==null?void 0:e.optionalMethods)||[],u=(e==null?void 0:e.optionalEvents)||[],h=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),f=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:s==null?void 0:s.map(d=>this.formatChainId(d)),optionalChains:n.map(d=>this.formatChainId(d)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:f,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(s=>{i[s]=this.getRpcUrl(s,r)}),i}async initialize(e){var r;if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Nn(this.rpc.chains):Nn(this.rpc.optionalChains),this.signer=await d4.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 i;try{const s=await m4(),{convertWCMToAppKitOptions:n}=await Promise.resolve().then(function(){return U4}),o=n(rs(Hr({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!o.networks.length)throw new Error("No networks found for WalletConnect");i=s(rs(Hr({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((r=this.rpc.qrModalOptions)==null?void 0:r.enableMobileFullScreen)===!0}))}catch(s){throw console.warn(s),new Error("To use QR modal, please install @reown/appkit package")}if(i)try{this.modal=i}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:s}=e;r&&vt(r)&&(this.rpc.chains=r.map(n=>this.formatChainId(n)),r.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)})),i&&vt(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${w4}?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==null?void 0:r.accounts),this.setAccounts(r==null?void 0: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 S4=oo;var O4=Object.defineProperty,$4=Object.defineProperties,D4=Object.getOwnPropertyDescriptors,Bf=Object.getOwnPropertySymbols,A4=Object.prototype.hasOwnProperty,P4=Object.prototype.propertyIsEnumerable,Cf=(t,e,r)=>e in t?O4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vy=(t,e)=>{for(var r in e||(e={}))A4.call(e,r)&&Cf(t,r,e[r]);if(Bf)for(var r of Bf(e))P4.call(e,r)&&Cf(t,r,e[r]);return t},B4=(t,e)=>$4(t,D4(e));function C4(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 T4=t=>{const[e,r]=t.split(":");return Ey({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function R4(t){var e,r,i,s,n,o,a;const c=(e=t.chains)==null?void 0:e.map(T4).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const l=c.find(h=>{var f;return h.id===((f=t.defaultChain)==null?void 0:f.id)}),u={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:C4(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:l,metadata:B4(vy({},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:((s=t.metadata)==null?void 0:s.url)||"https://walletconnect.org",icons:((n=t.metadata)==null?void 0:n.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(g=>({id:g.id,name:g.name,links:g.links})),...(t.desktopWallets||[]).map(g=>({id:g.id,name:g.name,links:{native:g.links.native,universal:g.links.universal}}))],f=[...u.featuredWalletIds||[],...u.excludeWalletIds||[]],d=h.filter(g=>!f.includes(g.id));d.length&&(u.customWallets=d)}return u}function Ey(t){return vy({formatters:void 0,fees:void 0,serializers:void 0},t)}var U4=Object.freeze({__proto__:null,convertWCMToAppKitOptions:R4,defineChain:Ey});const O5=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:S4,OPTIONAL_EVENTS:by,OPTIONAL_METHODS:my,REQUIRED_EVENTS:Un,REQUIRED_METHODS:Rn,default:oo},Symbol.toStringTag,{value:"Module"}));export{RS as A,Dt as B,aE as C,ui as D,Zc as E,xO as F,Yc as G,io as H,li as I,xs as J,u2 as K,Cr as L,ro as M,jt as N,mt as O,cu as P,ep as Q,kt as R,sy as S,O5 as T,si as a,t8 as b,Pg as c,Qs as d,e8 as e,QS as f,bh as g,kf as h,bt as i,q as j,i8 as k,ti as l,hc as m,jy as n,Nf as o,cs as p,Sa as q,Ss as r,ii as s,rt as t,mb as u,lb as v,Cm as w,bE as x,vm as y,Tm as z};
41
+ `)===0?S.substr(1,S.length):S}).forEach(function(S){var E=S.split(":"),_=E.shift().trim();if(_){var U=E.join(":").trim();try{y.append(_,U)}catch(N){console.warn("Response "+N.message)}}}),y}B.call(D.prototype);function P(p,y){if(!(this instanceof P))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(y||(y={}),this.type="default",this.status=y.status===void 0?200:y.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=y.statusText===void 0?"":""+y.statusText,this.headers=new w(y.headers),this.url=y.url||"",this._initBody(p)}B.call(P.prototype),P.prototype.clone=function(){return new P(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new w(this.headers),url:this.url})},P.error=function(){var p=new P(null,{status:200,statusText:""});return p.ok=!1,p.status=0,p.type="error",p};var I=[301,302,303,307,308];P.redirect=function(p,y){if(I.indexOf(y)===-1)throw new RangeError("Invalid status code");return new P(null,{status:y,headers:{location:p}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(y,v){this.message=y,this.name=v;var S=Error(y);this.stack=S.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function $(p,y){return new Promise(function(v,S){var E=new D(p,y);if(E.signal&&E.signal.aborted)return S(new o.DOMException("Aborted","AbortError"));var _=new XMLHttpRequest;function U(){_.abort()}_.onload=function(){var L={statusText:_.statusText,headers:j(_.getAllResponseHeaders()||"")};E.url.indexOf("file://")===0&&(_.status<200||_.status>599)?L.status=200:L.status=_.status,L.url="responseURL"in _?_.responseURL:L.headers.get("X-Request-URL");var M="response"in _?_.response:_.responseText;setTimeout(function(){v(new P(M,L))},0)},_.onerror=function(){setTimeout(function(){S(new TypeError("Network request failed"))},0)},_.ontimeout=function(){setTimeout(function(){S(new TypeError("Network request timed out"))},0)},_.onabort=function(){setTimeout(function(){S(new o.DOMException("Aborted","AbortError"))},0)};function N(L){try{return L===""&&a.location.href?a.location.href:L}catch{return L}}if(_.open(E.method,N(E.url),!0),E.credentials==="include"?_.withCredentials=!0:E.credentials==="omit"&&(_.withCredentials=!1),"responseType"in _&&(c.blob?_.responseType="blob":c.arrayBuffer&&(_.responseType="arraybuffer")),y&&typeof y.headers=="object"&&!(y.headers instanceof w||a.Headers&&y.headers instanceof a.Headers)){var V=[];Object.getOwnPropertyNames(y.headers).forEach(function(L){V.push(f(L)),_.setRequestHeader(L,d(y.headers[L]))}),E.headers.forEach(function(L,M){V.indexOf(M)===-1&&_.setRequestHeader(M,L)})}else E.headers.forEach(function(L,M){_.setRequestHeader(M,L)});E.signal&&(E.signal.addEventListener("abort",U),_.onreadystatechange=function(){_.readyState===4&&E.signal.removeEventListener("abort",U)}),_.send(typeof E._bodyInit>"u"?null:E._bodyInit)})}return $.polyfill=!0,a.fetch||(a.fetch=$,a.Headers=w,a.Request=D,a.Response=P),o.Headers=w,o.Request=D,o.Response=P,o.fetch=$,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=r.fetch?r:i;e=s.fetch,e.default=s.fetch,e.fetch=s.fetch,e.Headers=s.Headers,e.Request=s.Request,e.Response=s.Response,t.exports=e})(nc,nc.exports);var N6=nc.exports;const sf=Dy(N6);var k6=Object.defineProperty,j6=Object.defineProperties,F6=Object.getOwnPropertyDescriptors,nf=Object.getOwnPropertySymbols,L6=Object.prototype.hasOwnProperty,M6=Object.prototype.propertyIsEnumerable,of=(t,e,r)=>e in t?k6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,af=(t,e)=>{for(var r in e||(e={}))L6.call(e,r)&&of(t,r,e[r]);if(nf)for(var r of nf(e))M6.call(e,r)&&of(t,r,e[r]);return t},cf=(t,e)=>j6(t,F6(e));const q6={Accept:"application/json","Content-Type":"application/json"},z6="POST",lf={headers:q6,method:z6},uf=10;let sy=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new xt.EventEmitter,this.isAvailable=!1,this.registering=!1,!Oh(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=si(e),i=await(await sf(this.url,cf(af({},lf),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!Oh(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,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return s(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=si({id:1,jsonrpc:"2.0",method:"test",params:[]});await sf(e,cf(af({},lf),{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"?ii(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),s=i.message||i.toString(),n=ro(e,s);this.events.emit("payload",n)}parseError(e,r=this.url){return Tg(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>uf&&this.events.setMaxListeners(uf)}};function Qc(t){return t==null||typeof t!="object"&&typeof t!="function"}function ny(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function oy(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const V6="[object RegExp]",ay="[object String]",cy="[object Number]",ly="[object Boolean]",uy="[object Arguments]",H6="[object Symbol]",K6="[object Date]",W6="[object Map]",G6="[object Set]",Y6="[object Array]",Z6="[object ArrayBuffer]",J6="[object Object]",X6="[object DataView]",Q6="[object Uint8Array]",eP="[object Uint8ClampedArray]",tP="[object Uint16Array]",rP="[object Uint32Array]",iP="[object Int8Array]",sP="[object Int16Array]",nP="[object Int32Array]",oP="[object Float32Array]",aP="[object Float64Array]";function el(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function cP(t,e){return Si(t,void 0,t,new Map,e)}function Si(t,e,r,i=new Map,s=void 0){const n=s==null?void 0:s(t,e,r,i);if(n!=null)return n;if(Qc(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]=Si(t[a],a,r,i,s);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,Si(c,a,r,i,s));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(Si(a,void 0,r,i,s));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(el(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Si(t[a],a,r,i,s);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),Gr(o,t,r,i,s),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),Gr(o,t,r,i,s),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),Gr(o,t,r,i,s),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,Gr(o,t,r,i,s),o}if(typeof t=="object"&&lP(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),Gr(o,t,r,i,s),o}return t}function Gr(t,e,r=t,i,s){const n=[...Object.keys(e),...ny(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Si(e[a],a,r,i,s))}}function lP(t){switch(oy(t)){case uy:case Y6:case Z6:case X6:case ly:case K6:case oP:case aP:case iP:case sP:case nP:case W6:case cy:case J6:case V6:case G6:case ay:case H6:case Q6:case eP:case tP:case rP:return!0;default:return!1}}function uP(t,e){return cP(t,(r,i,s,n)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case cy:case ay:case ly:{const o=new t.constructor(t==null?void 0:t.valueOf());return Gr(o,t),o}case uy:{const o={};return Gr(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function hf(t){return uP(t)}function ff(t){return t!==null&&typeof t=="object"&&oy(t)==="[object Arguments]"}function df(t){return typeof t=="object"&&t!==null}function hP(){}function fP(t){return el(t)}function dP(t){var r;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const i=t[Symbol.toStringTag];return i==null||!((r=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&r.writable)?!1:t.toString()===`[object ${i}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function pP(t){if(Qc(t))return t;if(Array.isArray(t)||el(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 gP(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let s=t;for(let n=0;n<r.length;n++){const o=r[n];s=oc(s,o,i,new Map)}return s}function oc(t,e,r,i){if(Qc(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return pP(i.get(e));if(i.set(e,t),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const s=[...Object.keys(e),...ny(e)];for(let n=0;n<s.length;n++){const o=s[n];let a=e[o],c=t[o];if(ff(a)&&(a={...a}),ff(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=hf(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const u=[],h=Reflect.ownKeys(c);for(let f=0;f<h.length;f++){const d=h[f];u[d]=c[d]}c=u}else c=[];const l=r(c,a,o,t,e,i);l!=null?t[o]=l:Array.isArray(a)||df(c)&&df(a)?t[o]=oc(c,a,r,i):c==null&&dP(a)?t[o]=oc({},a,r,i):c==null&&fP(a)?t[o]=hf(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function yP(t,...e){return gP(t,...e,hP)}const pf="error",wP="wss://relay.walletconnect.org",mP="wc",hy="universal_provider",tn=`${mP}@2:${hy}:`,fy="https://rpc.walletconnect.org/v1/",dy="generic",bP=`${fy}bundler`,Pi="call_status",vP=86400,tl={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var EP=Object.defineProperty,xP=Object.defineProperties,_P=Object.getOwnPropertyDescriptors,gf=Object.getOwnPropertySymbols,IP=Object.prototype.hasOwnProperty,SP=Object.prototype.propertyIsEnumerable,yf=(t,e,r)=>e in t?EP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rn=(t,e)=>{for(var r in e||(e={}))IP.call(e,r)&&yf(t,r,e[r]);if(gf)for(var r of gf(e))SP.call(e,r)&&yf(t,r,e[r]);return t},OP=(t,e)=>xP(t,_P(e));function py(t,e,r){var i;const s=cr(t);return((i=e.rpcMap)==null?void 0:i[s.reference])||`${fy}?chainId=${s.namespace}:${s.reference}&projectId=${r}`}function $P(t){return t.includes(":")?t.split(":")[1]:t}function gy(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function DP(t,e){const r=Object.keys(e.namespaces).filter(s=>s.includes(t));if(!r.length)return[];const i=[];return r.forEach(s=>{const n=e.namespaces[s].accounts;i.push(...n)}),i}function wf(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>{var i,s;return((i=r==null?void 0:r.chains)==null?void 0:i.length)&&((s=r==null?void 0:r.chains)==null?void 0:s.length)>0}))}function sn(t={},e={}){const r=wf(mf(t)),i=wf(mf(e));return yP(r,i)}function mf(t){var e,r,i,s,n;const o={};if(!Vt(t))return o;for(const[a,c]of Object.entries(t)){const l=to(a)?[a]:c.chains,u=c.methods||[],h=c.events||[],f=c.rpcMap||{},d=Ii(a);o[d]=OP(rn(rn({},o[d]),c),{chains:zt(l,(e=o[d])==null?void 0:e.chains),methods:zt(u,(r=o[d])==null?void 0:r.methods),events:zt(h,(i=o[d])==null?void 0:i.events)}),(Vt(f)||Vt(((s=o[d])==null?void 0:s.rpcMap)||{}))&&(o[d].rpcMap=rn(rn({},f),(n=o[d])==null?void 0:n.rpcMap))}return o}function bf(t){return t.includes(":")?t.split(":")[2]:t}function vf(t){const e={};for(const[r,i]of Object.entries(t)){const s=i.methods||[],n=i.events||[],o=i.accounts||[],a=to(r)?[r]:i.chains?i.chains:gy(i.accounts);e[r]={chains:a,methods:s,events:n,accounts:o}}return e}function ia(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))}function AP(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const yy={},Bi=t=>yy[t],sa=(t,e)=>{yy[t]=e};var PP=Object.defineProperty,Ef=Object.getOwnPropertySymbols,BP=Object.prototype.hasOwnProperty,CP=Object.prototype.propertyIsEnumerable,xf=(t,e,r)=>e in t?PP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_f=(t,e)=>{for(var r in e||(e={}))BP.call(e,r)&&xf(t,r,e[r]);if(Ef)for(var r of Ef(e))CP.call(e,r)&&xf(t,r,e[r]);return t};const If="eip155",TP=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],RP=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,na=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,Sf=t=>Object.keys(t).filter(e=>TP.includes(e)).reduce((e,r)=>(e[r]=UP(t[r]),e),{}),UP=t=>typeof t=="string"&&AP(t)?JSON.parse(t):t,NP=(t,e,r)=>{const{sessionProperties:i={},scopedProperties:s={}}=t,n={};if(!Vt(s)&&!Vt(i))return;const o=Sf(i);for(const a of r){const c=RP(a);if(!c)continue;n[na(c)]=o;const l=s==null?void 0:s[`${If}:${c}`];if(l){const u=l==null?void 0:l[`${If}:${c}:${e}`];n[na(c)]=_f(_f({},n[na(c)]),Sf(u||l))}}for(const[a,c]of Object.entries(n))Object.keys(c).length===0&&delete n[a];return Object.keys(n).length>0?n:void 0};var kP=Object.defineProperty,jP=(t,e,r)=>e in t?kP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,FP=(t,e,r)=>jP(t,e+"",r);let oa,LP=class wy{constructor(e){FP(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,r){return await this.storage.setItem(e,r)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return oa||(oa=new wy(e)),oa}};var MP=Object.defineProperty,qP=Object.defineProperties,zP=Object.getOwnPropertyDescriptors,Of=Object.getOwnPropertySymbols,VP=Object.prototype.hasOwnProperty,HP=Object.prototype.propertyIsEnumerable,$f=(t,e,r)=>e in t?MP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,KP=(t,e)=>{for(var r in e||(e={}))VP.call(e,r)&&$f(t,r,e[r]);if(Of)for(var r of Of(e))HP.call(e,r)&&$f(t,r,e[r]);return t},WP=(t,e)=>qP(t,zP(e));async function GP(t,e){const r=cr(t.result.capabilities.caip345.caip2),i=t.result.capabilities.caip345.transactionHashes,s=await Promise.allSettled(i.map(h=>YP(r.reference,h,e))),n=s.filter(h=>h.status==="fulfilled").map(h=>h.value).filter(h=>h);s.filter(h=>h.status==="rejected").forEach(h=>console.warn("Failed to fetch transaction receipt:",h.reason));const o=!n.length||n.some(h=>!h),a=n.every(h=>(h==null?void 0:h.status)==="0x1"),c=n.every(h=>(h==null?void 0:h.status)==="0x0"),l=n.some(h=>(h==null?void 0:h.status)==="0x0");let u;return o?u=100:a?u=200:c?u=500:l&&(u=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:n,status:u}}async function YP(t,e,r){return await r(parseInt(t)).request(Dt("eth_getTransactionReceipt",[e]))}async function ZP({sendCalls:t,storage:e}){const r=await e.getItem(Pi);await e.setItem(Pi,WP(KP({},r),{[t.result.id]:{request:t.request,result:t.result,expiry:ge(vP)}}))}async function JP({resultId:t,storage:e}){const r=await e.getItem(Pi);if(r){delete r[t],await e.setItem(Pi,r);for(const i in r)Lt(r[i].expiry)&&delete r[i];await e.setItem(Pi,r)}}async function XP({resultId:t,storage:e}){const r=await e.getItem(Pi),i=r==null?void 0:r[t];if(i&&!Lt(i.expiry))return i;await JP({resultId:t,storage:e})}var QP=Object.defineProperty,e4=Object.defineProperties,t4=Object.getOwnPropertyDescriptors,Df=Object.getOwnPropertySymbols,r4=Object.prototype.hasOwnProperty,i4=Object.prototype.propertyIsEnumerable,ac=(t,e,r)=>e in t?QP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,aa=(t,e)=>{for(var r in e||(e={}))r4.call(e,r)&&ac(t,r,e[r]);if(Df)for(var r of Df(e))i4.call(e,r)&&ac(t,r,e[r]);return t},ca=(t,e)=>e4(t,t4(e)),zr=(t,e,r)=>ac(t,typeof e!="symbol"?e+"":e,r);class s4{constructor(e){zr(this,"name","eip155"),zr(this,"client"),zr(this,"chainId"),zr(this,"namespace"),zr(this,"httpProviders"),zr(this,"events"),zr(this,"storage"),this.namespace=e.namespace,this.events=Bi("events"),this.client=Bi("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=LP.getStorage(this.client.core.storage)}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);case"wallet_sendCalls":return await this.sendCalls(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);const i=this.chainId;this.chainId=parseInt(e),this.events.emit(tl.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}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||py(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zc(new sy(i,Bi("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 s=parseInt($P(r));e[s]=this.createHttpProvider(s,(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(e){const r=e||this.chainId;return this.httpProviders[r]||(this.httpProviders=ca(aa({},this.httpProviders),{[r]:this.createHttpProvider(r)}),this.httpProviders[r])}async handleSwitchChain(e){var r,i;let s=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";s=s.startsWith("0x")?s:`0x${s}`;const n=parseInt(s,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:s}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var r,i,s,n,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0],c=((n=(s=e.request)==null?void 0:s.params)==null?void 0:n[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{},h=`${a}${c.join(",")}`,f=u==null?void 0:u[h];if(f)return f;let d;try{d=NP(l,a,c)}catch(w){console.warn("Failed to extract capabilities from session",w)}if(d)return d;const g=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:ca(aa({},l.sessionProperties||{}),{capabilities:ca(aa({},u||{}),{[h]:g})})})}catch(w){console.warn("Failed to update session with capabilities",w)}return g}async getCallStatus(e){var r,i,s;const n=this.client.session.get(e.topic),o=(r=n.sessionProperties)==null?void 0:r.bundler_name;if(o){const l=this.getBundlerUrl(e.chainId,o);try{return await this.getUserOperationReceipt(l,e)}catch(u){console.warn("Failed to fetch call status from bundler",u,l)}}const a=(i=n.sessionProperties)==null?void 0:i.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from custom bundler",l,a)}const c=await XP({resultId:(s=e.request.params)==null?void 0:s[0],storage:this.storage});if(c)try{return await GP(c,this.getHttpProvider.bind(this))}catch(l){console.warn("Failed to fetch call status from stored send calls",l,c)}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 s=new URL(e),n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Dt("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,r){return`${bP}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}async sendCalls(e){var r,i,s;const n=await this.client.request(e),o=(r=e.request.params)==null?void 0:r[0],a=n==null?void 0:n.id,c=(n==null?void 0:n.capabilities)||{},l=(i=c==null?void 0:c.caip345)==null?void 0:i.caip2,u=(s=c==null?void 0:c.caip345)==null?void 0:s.transactionHashes;return!a||!l||!(u!=null&&u.length)||await ZP({sendCalls:{request:o,result:n},storage:this.storage}),n}}var n4=Object.defineProperty,o4=(t,e,r)=>e in t?n4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ei=(t,e,r)=>o4(t,typeof e!="symbol"?e+"":e,r);class a4{constructor(e){Ei(this,"name",dy),Ei(this,"client"),Ei(this,"httpProviders"),Ei(this,"events"),Ei(this,"namespace"),Ei(this,"chainId"),this.namespace=e.namespace,this.events=Bi("events"),this.client=Bi("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),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);const i=this.chainId;this.chainId=e,this.events.emit(tl.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}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]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return cr(e).namespace}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(s=>{var n,o;const a=cr(s),c=(o=(n=this.namespace)==null?void 0:n.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];i[a.reference]=this.createHttpProvider(s,c)}),i}getHttpProvider(e){const r=cr(e).reference,i=this.httpProviders[r];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||py(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zc(new sy(i,Bi("disableProviderPing")))}}var c4=Object.defineProperty,l4=Object.defineProperties,u4=Object.getOwnPropertyDescriptors,Af=Object.getOwnPropertySymbols,h4=Object.prototype.hasOwnProperty,f4=Object.prototype.propertyIsEnumerable,cc=(t,e,r)=>e in t?c4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ts=(t,e)=>{for(var r in e||(e={}))h4.call(e,r)&&cc(t,r,e[r]);if(Af)for(var r of Af(e))f4.call(e,r)&&cc(t,r,e[r]);return t},nn=(t,e)=>l4(t,u4(e)),nt=(t,e,r)=>cc(t,typeof e!="symbol"?e+"":e,r);class rl{constructor(e){nt(this,"client"),nt(this,"namespaces"),nt(this,"optionalNamespaces"),nt(this,"sessionProperties"),nt(this,"scopedProperties"),nt(this,"events",new uc),nt(this,"rpcProviders",{}),nt(this,"session"),nt(this,"providerOpts"),nt(this,"logger"),nt(this,"uri"),nt(this,"disableProviderPing",!1),nt(this,"connectParams");var r,i;this.providerOpts=e,this.logger=Wc({logger:(r=e.logger)!=null?r:pf,name:(i=this.providerOpts.name)!=null?i:hy}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const r=new rl(e);return await r.initialize(),r}async request(e,r,i){const[s,n]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:ts({},e),chainId:`${s}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,s){const n=new Date().getTime();this.request(e,i,s).then(o=>r(null,xs(n,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:ue("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=e,this.setNamespaces(e),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:s}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await s();if(this.session=n.session,this.session){const o=vf(this.session.namespaces);this.namespaces=sn(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}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){var r,i;const{uri:s,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(r=this.connectParams)==null?void 0:r.authentication,walletPay:(i=this.connectParams)==null?void 0:i.walletPay});s&&(this.uri=s,this.events.emit("display_uri",s));const o=await n();this.session=o;const a=vf(o.namespaces);return this.namespaces=sn(this.namespaces,a),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,s]=this.validateChain(e);this.getProvider(i).setDefaultChain(s,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(!vt(r))return;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}`)}catch(r){this.logger.warn(r,"Failed to cleanup pending pairings")}}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 U6.init({core:this.providerOpts.core,logger:this.providerOpts.logger||pf,relayUrl:this.providerOpts.relayUrl||wP,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(i,"Failed to get session"),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=>Ii(r)))];sa("client",this.client),sa("events",this.events),sa("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=DP(r,this.session);if((i==null?void 0:i.length)===0)return;const s=gy(i),n=sn(this.namespaces,this.optionalNamespaces),o=nn(ts({},n[r]),{accounts:i,chains:s});switch(r){case"eip155":this.rpcProviders[r]=new s4({namespace:o});break;default:this.rpcProviders[r]=new a4({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:s}=e;if(s!==((r=this.session)==null?void 0:r.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&&vt(o)&&this.events.emit("accountsChanged",o.map(bf))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=Ii(o),l=ia(o)!==ia(a)?`${c}:${ia(a)}`:o;this.onChainChanged({currentCaipChainId:l})}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var i,s;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=r,o=(s=this.client)==null?void 0:s.session.get(e);this.session=nn(ts({},o),{namespaces:n}),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",nn(ts({},ue("USER_DISCONNECTED")),{data:e.topic})))}),this.on(tl.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(nn(ts({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[dy]}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:s,scopedProperties:n}=e;this.optionalNamespaces=sn(r,i),this.sessionProperties=s,this.scopedProperties=n}validateChain(e){const[r,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(o=>Ii(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 s=Ii(Object.keys(this.namespaces)[0]),n=this.rpcProviders[s].getDefaultChain();return[s,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:r,internal:i=!1}){if(!this.namespaces)return;const[s,n]=this.validateChain(e);n&&(this.updateNamespaceChain(s,n),i?(this.events.emit("chainChanged",n),this.emitAccountsChangedOnChainChange({namespace:s,currentCaipChainId:e,previousCaipChainId:r})):this.getProvider(s).setDefaultChain(n),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:r,previousCaipChainId:i}){var s,n;try{if(i===r)return;const o=(n=(s=this.session)==null?void 0:s.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${r}:`)).map(bf);if(!vt(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,r){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${r}`,s={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,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,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,r){var i;const s=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${tn}/${e}${s}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${tn}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${tn}/${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(tn)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn(r,"Failed to cleanup storage")}}}const d4=rl,p4="wc",g4="ethereum_provider",y4=`${p4}@2:${g4}:`,w4="https://rpc.walletconnect.org/v1/",Rn=["eth_sendTransaction","personal_sign"],my=["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"],Un=["chainChanged","accountsChanged"],by=["chainChanged","accountsChanged","message","disconnect","connect"],m4=async()=>{const{createAppKit:t}=await Ay(()=>import("./core-XnCYF3S5.js").then(e=>e.bt),__vite__mapDeps([0,1]));return t};var b4=Object.defineProperty,v4=Object.defineProperties,E4=Object.getOwnPropertyDescriptors,Pf=Object.getOwnPropertySymbols,x4=Object.prototype.hasOwnProperty,_4=Object.prototype.propertyIsEnumerable,lc=(t,e,r)=>e in t?b4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hr=(t,e)=>{for(var r in e||(e={}))x4.call(e,r)&&lc(t,r,e[r]);if(Pf)for(var r of Pf(e))_4.call(e,r)&&lc(t,r,e[r]);return t},rs=(t,e)=>v4(t,E4(e)),ot=(t,e,r)=>lc(t,typeof e!="symbol"?e+"":e,r);function Nn(t){return Number(t[0].split(":")[1])}function on(t){return`0x${t.toString(16)}`}function I4(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:s,events:n,optionalEvents:o,rpcMap:a}=t;if(!vt(e))throw new Error("Invalid chains");const c={chains:e,methods:i||Rn,events:n||Un,rpcMap:Hr({},e.length?{[Nn(e)]:a[Nn(e)]}:{})},l=n==null?void 0:n.filter(d=>!Un.includes(d)),u=i==null?void 0:i.filter(d=>!Rn.includes(d));if(!r&&!o&&!s&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:e.length?c:void 0};const h=(l==null?void 0:l.length)&&(u==null?void 0:u.length)||!r,f={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:my))],events:[...new Set(c.events.concat(o!=null&&o.length?o:by))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?f:void 0}}class oo{constructor(){ot(this,"events",new xt.EventEmitter),ot(this,"namespace","eip155"),ot(this,"accounts",[]),ot(this,"signer"),ot(this,"chainId",1),ot(this,"modal"),ot(this,"rpc"),ot(this,"STORAGE_KEY",y4),ot(this,"on",(e,r)=>(this.events.on(e,r),this)),ot(this,"once",(e,r)=>(this.events.once(e,r),this)),ot(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),ot(this,"off",(e,r)=>(this.events.off(e,r),this)),ot(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new oo;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:s}=I4(this.rpc);try{const n=await new Promise(async(a,c)=>{var l,u;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(u=this.modal)==null||u.subscribeState(f=>{!f.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const h=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(rs(Hr({namespaces:Hr({},i&&{[this.namespace]:i})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:h})).then(f=>{a(f)}).catch(f=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),c(new Error(f.message))})});if(!n)return;const o=bu(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:on(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}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==null?void 0:e.chains});try{const s=await new Promise(async(o,a)=>{var c,l;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(l=this.modal)==null||l.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(rs(Hr({},e),{chains:this.rpc.chains}),r).then(u=>{o(u)}).catch(u=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(u.message))})}),n=s.session;if(n){const o=bu(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:on(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}finally{(i=this.modal)==null||i.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params: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",on(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",rs(Hr({},ue("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",on(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,s]=e.split(":");return{chainId:`${r}:${i}`,address:s}}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 s=(r=e==null?void 0:e.chains)!=null?r:[],n=(i=e==null?void 0:e.optionalChains)!=null?i:[],o=s.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=s.length?(e==null?void 0:e.methods)||Rn:[],c=s.length?(e==null?void 0:e.events)||Un:[],l=(e==null?void 0:e.optionalMethods)||[],u=(e==null?void 0:e.optionalEvents)||[],h=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),f=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:s==null?void 0:s.map(d=>this.formatChainId(d)),optionalChains:n.map(d=>this.formatChainId(d)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:f,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(s=>{i[s]=this.getRpcUrl(s,r)}),i}async initialize(e){var r;if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Nn(this.rpc.chains):Nn(this.rpc.optionalChains),this.signer=await d4.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 i;try{const s=await m4(),{convertWCMToAppKitOptions:n}=await Promise.resolve().then(function(){return U4}),o=n(rs(Hr({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!o.networks.length)throw new Error("No networks found for WalletConnect");i=s(rs(Hr({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((r=this.rpc.qrModalOptions)==null?void 0:r.enableMobileFullScreen)===!0}))}catch(s){throw console.warn(s),new Error("To use QR modal, please install @reown/appkit package")}if(i)try{this.modal=i}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:s}=e;r&&vt(r)&&(this.rpc.chains=r.map(n=>this.formatChainId(n)),r.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)})),i&&vt(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${w4}?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==null?void 0:r.accounts),this.setAccounts(r==null?void 0: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 S4=oo;var O4=Object.defineProperty,$4=Object.defineProperties,D4=Object.getOwnPropertyDescriptors,Bf=Object.getOwnPropertySymbols,A4=Object.prototype.hasOwnProperty,P4=Object.prototype.propertyIsEnumerable,Cf=(t,e,r)=>e in t?O4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vy=(t,e)=>{for(var r in e||(e={}))A4.call(e,r)&&Cf(t,r,e[r]);if(Bf)for(var r of Bf(e))P4.call(e,r)&&Cf(t,r,e[r]);return t},B4=(t,e)=>$4(t,D4(e));function C4(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 T4=t=>{const[e,r]=t.split(":");return Ey({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function R4(t){var e,r,i,s,n,o,a;const c=(e=t.chains)==null?void 0:e.map(T4).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const l=c.find(h=>{var f;return h.id===((f=t.defaultChain)==null?void 0:f.id)}),u={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:C4(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:l,metadata:B4(vy({},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:((s=t.metadata)==null?void 0:s.url)||"https://walletconnect.org",icons:((n=t.metadata)==null?void 0:n.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(g=>({id:g.id,name:g.name,links:g.links})),...(t.desktopWallets||[]).map(g=>({id:g.id,name:g.name,links:{native:g.links.native,universal:g.links.universal}}))],f=[...u.featuredWalletIds||[],...u.excludeWalletIds||[]],d=h.filter(g=>!f.includes(g.id));d.length&&(u.customWallets=d)}return u}function Ey(t){return vy({formatters:void 0,fees:void 0,serializers:void 0},t)}var U4=Object.freeze({__proto__:null,convertWCMToAppKitOptions:R4,defineChain:Ey});const O5=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:S4,OPTIONAL_EVENTS:by,OPTIONAL_METHODS:my,REQUIRED_EVENTS:Un,REQUIRED_METHODS:Rn,default:oo},Symbol.toStringTag,{value:"Module"}));export{RS as A,Dt as B,aE as C,ui as D,Zc as E,xO as F,Yc as G,io as H,li as I,xs as J,u2 as K,Cr as L,ro as M,jt as N,mt as O,cu as P,ep as Q,kt as R,sy as S,O5 as T,si as a,t8 as b,Pg as c,Qs as d,e8 as e,QS as f,bh as g,kf as h,bt as i,q as j,i8 as k,ti as l,hc as m,jy as n,Nf as o,cs as p,Sa as q,Ss as r,ii as s,rt as t,mb as u,lb as v,Cm as w,bE as x,vm as y,Tm as z};