@dcl/governance-site 1.14.0 → 1.14.1-19766186141.commit-f68c9c1

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,4 +1,4 @@
1
- import{e as xt,g as kf,h as R0,i as Y,B as re,k as St,c as pi,x as pc,o as pu,_ as F0}from"./index-aa7d7c43.js";var gu=globalThis&&globalThis.__spreadArray||function(t,e,r){if(r||arguments.length===2)for(var i=0,n=e.length,s;i<n;i++)(s||!(i in e))&&(s||(s=Array.prototype.slice.call(e,0,i)),s[i]=e[i]);return t.concat(s||Array.prototype.slice.call(e))},N0=function(){function t(e,r,i){this.name=e,this.version=r,this.os=i,this.type="browser"}return t}(),U0=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=xt.platform}return t}(),k0=function(){function t(e,r,i,n){this.name=e,this.version=r,this.os=i,this.bot=n,this.type="bot-device"}return t}(),j0=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),L0=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),M0=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,q0=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,yu=3,z0=[["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",M0]],wu=[["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 V0(t){return t?mu(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new L0:typeof navigator<"u"?mu(navigator.userAgent):W0()}function H0(t){return t!==""&&z0.reduce(function(e,r){var i=r[0],n=r[1];if(e)return e;var s=n.exec(t);return!!s&&[i,s]},!1)}function mu(t){var e=H0(t);if(!e)return null;var r=e[0],i=e[1];if(r==="searchbot")return new j0;var n=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);n?n.length<yu&&(n=gu(gu([],n,!0),G0(yu-n.length),!0)):n=[];var s=n.join("."),o=K0(t),a=q0.exec(t);return a&&a[1]?new k0(r,s,o,a[1]):new N0(r,s,o)}function K0(t){for(var e=0,r=wu.length;e<r;e++){var i=wu[e],n=i[0],s=i[1],o=s.exec(t);if(o)return n}return null}function W0(){var t=typeof xt<"u"&&xt.version;return t?new U0(xt.version.slice(1)):null}function G0(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var L={};/*! *****************************************************************************
1
+ import{e as xt,g as kf,h as R0,i as Y,B as re,k as St,c as pi,x as pc,o as pu,_ as F0}from"./index-76a72ce6.js";var gu=globalThis&&globalThis.__spreadArray||function(t,e,r){if(r||arguments.length===2)for(var i=0,n=e.length,s;i<n;i++)(s||!(i in e))&&(s||(s=Array.prototype.slice.call(e,0,i)),s[i]=e[i]);return t.concat(s||Array.prototype.slice.call(e))},N0=function(){function t(e,r,i){this.name=e,this.version=r,this.os=i,this.type="browser"}return t}(),U0=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=xt.platform}return t}(),k0=function(){function t(e,r,i,n){this.name=e,this.version=r,this.os=i,this.bot=n,this.type="bot-device"}return t}(),j0=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),L0=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),M0=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,q0=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,yu=3,z0=[["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",M0]],wu=[["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 V0(t){return t?mu(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new L0:typeof navigator<"u"?mu(navigator.userAgent):W0()}function H0(t){return t!==""&&z0.reduce(function(e,r){var i=r[0],n=r[1];if(e)return e;var s=n.exec(t);return!!s&&[i,s]},!1)}function mu(t){var e=H0(t);if(!e)return null;var r=e[0],i=e[1];if(r==="searchbot")return new j0;var n=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);n?n.length<yu&&(n=gu(gu([],n,!0),G0(yu-n.length),!0)):n=[];var s=n.join("."),o=K0(t),a=q0.exec(t);return a&&a[1]?new k0(r,s,o,a[1]):new N0(r,s,o)}function K0(t){for(var e=0,r=wu.length;e<r;e++){var i=wu[e],n=i[0],s=i[1],o=s.exec(t);if(o)return n}return null}function W0(){var t=typeof xt<"u"&&xt.version;return t?new U0(xt.version.slice(1)):null}function G0(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var L={};/*! *****************************************************************************
2
2
  Copyright (c) Microsoft Corporation.
3
3
 
4
4
  Permission to use, copy, modify, and/or distribute this software for any
@@ -36,4 +36,4 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
36
36
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
37
37
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
38
38
  PERFORMANCE OF THIS SOFTWARE.
39
- ***************************************************************************** */var Za=function(t,e){return Za=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var n in i)i.hasOwnProperty(n)&&(r[n]=i[n])},Za(t,e)};function W8(t,e){Za(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Ja=function(){return Ja=Object.assign||function(e){for(var r,i=1,n=arguments.length;i<n;i++){r=arguments[i];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},Ja.apply(this,arguments)};function G8(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 n=0,i=Object.getOwnPropertySymbols(t);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(r[i[n]]=t[i[n]]);return r}function Y8(t,e,r,i){var n=arguments.length,s=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(n<3?o(s):n>3?o(e,r,s):o(e,r))||s);return n>3&&s&&Object.defineProperty(e,r,s),s}function Z8(t,e){return function(r,i){e(r,i,t)}}function J8(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function X8(t,e,r,i){function n(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(l){try{u(i.next(l))}catch(h){o(h)}}function c(l){try{u(i.throw(l))}catch(h){o(h)}}function u(l){l.done?s(l.value):n(l.value).then(a,c)}u((i=i.apply(t,e||[])).next())})}function Q8(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,n&&(s=u[0]&2?n.return:u[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,u[1])).done)return s;switch(n=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,n=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],n=0}finally{i=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function e$(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function t$(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Xa(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 Mg(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function r$(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Mg(arguments[e]));return t}function i$(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),n=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,n++)i[n]=s[o];return i}function Sn(t){return this instanceof Sn?(this.v=t,this):new Sn(t)}function n$(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),n,s=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(f){i[f]&&(n[f]=function(d){return new Promise(function(p,g){s.push([f,d,p,g])>1||a(f,d)})})}function a(f,d){try{c(i[f](d))}catch(p){h(s[0][3],p)}}function c(f){f.value instanceof Sn?Promise.resolve(f.value.v).then(u,l):h(s[0][2],f)}function u(f){a("next",f)}function l(f){a("throw",f)}function h(f,d){f(d),s.shift(),s.length&&a(s[0][0],s[0][1])}}function s$(t){var e,r;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,s){e[n]=t[n]?function(o){return(r=!r)?{value:Sn(t[n](o)),done:n==="return"}:s?s(o):o}:s}}function o$(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 Xa=="function"?Xa(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),n(a,c,o.done,o.value)})}}function n(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function a$(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function c$(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 u$(t){return t&&t.__esModule?t:{default:t}}function l$(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function h$(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 f$=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Ja},__asyncDelegator:s$,__asyncGenerator:n$,__asyncValues:o$,__await:Sn,__awaiter:X8,__classPrivateFieldGet:l$,__classPrivateFieldSet:h$,__createBinding:e$,__decorate:Y8,__exportStar:t$,__extends:W8,__generator:Q8,__importDefault:u$,__importStar:c$,__makeTemplateObject:a$,__metadata:J8,__param:Z8,__read:Mg,__rest:G8,__spread:r$,__spreadArrays:i$,__values:Xa},Symbol.toStringTag,{value:"Module"})),d$=kf(f$);var Qt={},Ah;function p$(){if(Ah)return Qt;Ah=1,Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.isBrowserCryptoAvailable=Qt.getSubtleCrypto=Qt.getBrowerCrypto=void 0;function t(){return(pi===null||pi===void 0?void 0:pi.crypto)||(pi===null||pi===void 0?void 0:pi.msCrypto)||{}}Qt.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}Qt.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Qt.isBrowserCryptoAvailable=r,Qt}var er={},Ph;function g$(){if(Ph)return er;Ph=1,Object.defineProperty(er,"__esModule",{value:!0}),er.isBrowser=er.isNode=er.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}er.isReactNative=t;function e(){return typeof xt<"u"&&typeof xt.versions<"u"&&typeof xt.versions.node<"u"}er.isNode=e;function r(){return!t()&&!e()}return er.isBrowser=r,er}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=d$;e.__exportStar(p$(),t),e.__exportStar(g$(),t)})(Lg);function Lt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Rr(t=6){return BigInt(Lt(t))}function Ct(t,e,r){return{id:r||Lt(),jsonrpc:"2.0",method:t,params:e}}function $n(t,e){return{id:t,jsonrpc:"2.0",result:e}}function ao(t,e,r){return{id:t,jsonrpc:"2.0",error:y$(e,r)}}function y$(t,e){return typeof t>"u"?Dh(Ug):(typeof t=="string"&&(t=Object.assign(Object.assign({},Dh(Xc)),{message:t})),typeof e<"u"&&(t.data=e),H8(t.code)&&(t=K8(t.code)),t)}class w${}class m$ extends w${constructor(){super()}}class b$ extends m${constructor(e){super()}}const v$="^https?:",E$="^wss?:";function x$(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function qg(t,e){const r=x$(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Ch(t){return qg(t,v$)}function Bh(t){return qg(t,E$)}function _$(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function zg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Qc(t){return zg(t)&&"method"in t}function co(t){return zg(t)&&(Mt(t)||vt(t))}function Mt(t){return"result"in t}function vt(t){return"error"in t}class eu extends b${constructor(e){super(e),this.events=new St.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(Ct(e.method,e.params||[],e.id||Rr().toString()),r)}async requestStrict(e,r){return new Promise(async(i,n)=>{if(!this.connection.connected)try{await this.open()}catch(s){n(s)}this.events.on(`${e.id}`,s=>{vt(s)?n(s.error):i(s.result)});try{await this.connection.send(e,r)}catch(s){n(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),co(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}var ra,Th;function I$(){return Th||(Th=1,ra=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}),ra}const S$=()=>typeof WebSocket<"u"?WebSocket:typeof Y<"u"&&typeof Y.WebSocket<"u"?Y.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:I$(),$$=()=>typeof WebSocket<"u"||typeof Y<"u"&&typeof Y.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Rh=t=>t.split("?")[0],Fh=10,O$=S$();let D$=class{constructor(e){if(this.url=e,this.events=new St.EventEmitter,this.registering=!1,!Bh(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(lr(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Bh(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,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return n(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,i)=>{const n=Lg.isReactNative()?void 0:{rejectUnauthorized:!_$(e)},s=new O$(e,[],n);$$()?s.onerror=o=>{const a=o;i(this.emitError(a.error))}:s.on("error",o=>{i(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?si(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=ao(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return jg(e,Rh(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Fh&&this.events.setMaxListeners(Fh)}emitError(e){const r=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${Rh(this.url)}`));return this.events.emit("register_error",r),r}};const Vg="wc",Hg=2,Us="core",Kt=`${Vg}@2:${Us}:`,A$={name:Us,logger:"error"},P$={database:":memory:"},C$="crypto",Nh="client_ed25519_seed",B$=L.ONE_DAY,T$="keychain",R$="0.3",F$="messages",N$="0.3",U$=L.SIX_HOURS,k$="publisher",Kg="irn",j$="error",Wg="wss://relay.walletconnect.org",L$="relayer",me={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"},M$="_subscription",gt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},q$=.1,Qa="2.23.0",he={link_mode:"link_mode",relay:"relay"},ys={inbound:"inbound",outbound:"outbound"},z$="0.3",V$="WALLETCONNECT_CLIENT_ID",Uh="WALLETCONNECT_LINK_MODE_APPS",ut={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},H$="subscription",K$="0.3",W$="pairing",G$="0.3",en={wc_pairingDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:L.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:L.ONE_DAY,prompt:!1,tag:0},res:{ttl:L.ONE_DAY,prompt:!1,tag:0}}},Yr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ot={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Y$="history",Z$="0.3",J$="expirer",wt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},X$="0.3",Q$="verify-api",e6="https://verify.walletconnect.com",Gg="https://verify.walletconnect.org",gn=Gg,t6=`${gn}/v3`,r6=[e6,Gg],i6="echo",n6="https://echo.walletconnect.com",jt={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"},rr={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"},Dt={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"},zr={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"},Vr={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},tn={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},s6=.1,o6="event-client",a6=86400,c6="https://pulse.walletconnect.org/batch";function u6(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=n}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,w=0,I=0,C=p.length;I!==C&&p[I]===0;)I++,g++;for(var b=(C-I)*l+1>>>0,v=new Uint8Array(b);I!==C;){for(var D=p[I],P=0,T=b-1;(D!==0||P<w)&&T!==-1;T--,P++)D+=256*v[T]>>>0,v[T]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");w=P,I++}for(var R=b-w;R!==b&&v[R]===0;)R++;for(var A=c.repeat(g);R<b;++R)A+=t.charAt(v[R]);return A}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var w=0,I=0;p[g]===c;)w++,g++;for(var C=(p.length-g)*u+1>>>0,b=new Uint8Array(C);p[g];){var v=r[p.charCodeAt(g)];if(v===255)return;for(var D=0,P=C-1;(v!==0||D<I)&&P!==-1;P--,D++)v+=a*b[P]>>>0,b[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");I=D,g++}if(p[g]!==" "){for(var T=C-I;T!==C&&b[T]===0;)T++;for(var R=new Uint8Array(w+(C-T)),A=w;T!==C;)R[A++]=b[T++];return R}}}function d(p){var g=f(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var l6=u6,h6=l6;const Yg=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")},f6=t=>new TextEncoder().encode(t),d6=t=>new TextDecoder().decode(t);class p6{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 g6{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 Zg(this,e)}}class y6{constructor(e){this.decoders=e}or(e){return Zg(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 Zg=(t,e)=>new y6({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class w6{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new p6(e,r,i),this.decoder=new g6(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const uo=({name:t,prefix:e,encode:r,decode:i})=>new w6(t,e,r,i),kn=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=h6(r,e);return uo({prefix:t,name:e,encode:i,decode:s=>Yg(n(s))})},m6=(t,e,r,i)=>{const n={};for(let l=0;l<e.length;++l)n[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=n[t[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},b6=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[n&a>>o];if(o&&(s+=e[n&a<<r-o]),i)for(;s.length*r&7;)s+="=";return s},Ue=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>uo({prefix:e,name:t,encode(n){return b6(n,i,r)},decode(n){return m6(n,i,r,t)}}),v6=uo({prefix:"\0",name:"identity",encode:t=>d6(t),decode:t=>f6(t)});var E6=Object.freeze({__proto__:null,identity:v6});const x6=Ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var _6=Object.freeze({__proto__:null,base2:x6});const I6=Ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var S6=Object.freeze({__proto__:null,base8:I6});const $6=kn({prefix:"9",name:"base10",alphabet:"0123456789"});var O6=Object.freeze({__proto__:null,base10:$6});const D6=Ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),A6=Ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var P6=Object.freeze({__proto__:null,base16:D6,base16upper:A6});const C6=Ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),B6=Ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),T6=Ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),R6=Ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),F6=Ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),N6=Ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),U6=Ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),k6=Ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),j6=Ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var L6=Object.freeze({__proto__:null,base32:C6,base32upper:B6,base32pad:T6,base32padupper:R6,base32hex:F6,base32hexupper:N6,base32hexpad:U6,base32hexpadupper:k6,base32z:j6});const M6=kn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),q6=kn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var z6=Object.freeze({__proto__:null,base36:M6,base36upper:q6});const V6=kn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),H6=kn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var K6=Object.freeze({__proto__:null,base58btc:V6,base58flickr:H6});const W6=Ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),G6=Ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Y6=Ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Z6=Ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var J6=Object.freeze({__proto__:null,base64:W6,base64pad:G6,base64url:Y6,base64urlpad:Z6});const Jg=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),X6=Jg.reduce((t,e,r)=>(t[r]=e,t),[]),Q6=Jg.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function eO(t){return t.reduce((e,r)=>(e+=X6[r],e),"")}function tO(t){const e=[];for(const r of t){const i=Q6[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const rO=uo({prefix:"🚀",name:"base256emoji",encode:eO,decode:tO});var iO=Object.freeze({__proto__:null,base256emoji:rO}),nO=Xg,kh=128,sO=127,oO=~sO,aO=Math.pow(2,31);function Xg(t,e,r){e=e||[],r=r||0;for(var i=r;t>=aO;)e[r++]=t&255|kh,t/=128;for(;t&oO;)e[r++]=t&255|kh,t>>>=7;return e[r]=t|0,Xg.bytes=r-i+1,e}var cO=ec,uO=128,jh=127;function ec(t,i){var r=0,i=i||0,n=0,s=i,o,a=t.length;do{if(s>=a)throw ec.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=n<28?(o&jh)<<n:(o&jh)*Math.pow(2,n),n+=7}while(o>=uO);return ec.bytes=s-i,r}var lO=Math.pow(2,7),hO=Math.pow(2,14),fO=Math.pow(2,21),dO=Math.pow(2,28),pO=Math.pow(2,35),gO=Math.pow(2,42),yO=Math.pow(2,49),wO=Math.pow(2,56),mO=Math.pow(2,63),bO=function(t){return t<lO?1:t<hO?2:t<fO?3:t<dO?4:t<pO?5:t<gO?6:t<yO?7:t<wO?8:t<mO?9:10},vO={encode:nO,decode:cO,encodingLength:bO},Qg=vO;const Lh=(t,e,r=0)=>(Qg.encode(t,e,r),e),Mh=t=>Qg.encodingLength(t),tc=(t,e)=>{const r=e.byteLength,i=Mh(t),n=i+Mh(r),s=new Uint8Array(n+r);return Lh(t,s,0),Lh(r,s,i),s.set(e,n),new EO(t,r,e,s)};class EO{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const e0=({name:t,code:e,encode:r})=>new xO(t,e,r);class xO{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?tc(this.code,r):r.then(i=>tc(this.code,i))}else throw Error("Unknown type, must be binary type")}}const t0=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),_O=e0({name:"sha2-256",code:18,encode:t0("SHA-256")}),IO=e0({name:"sha2-512",code:19,encode:t0("SHA-512")});var SO=Object.freeze({__proto__:null,sha256:_O,sha512:IO});const r0=0,$O="identity",i0=Yg,OO=t=>tc(r0,i0(t)),DO={code:r0,name:$O,encode:i0,digest:OO};var AO=Object.freeze({__proto__:null,identity:DO});new TextEncoder,new TextDecoder;const qh={...E6,..._6,...S6,...O6,...P6,...L6,...z6,...K6,...J6,...iO};({...SO,...AO});function n0(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function PO(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?n0(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function s0(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const zh=s0("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ia=s0("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=PO(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),CO={utf8:zh,"utf-8":zh,hex:qh.base16,latin1:ia,ascii:ia,binary:ia,...qh};function BO(t,e="utf8"){const r=CO[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?n0(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var TO=Object.defineProperty,RO=(t,e,r)=>e in t?TO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ut=(t,e,r)=>RO(t,typeof e!="symbol"?e+"":e,r);class FO{constructor(e,r){this.core=e,this.logger=r,Ut(this,"keychain",new Map),Ut(this,"name",T$),Ut(this,"version",R$),Ut(this,"initialized",!1),Ut(this,"storagePrefix",Kt),Ut(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Ut(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Ut(this,"set",async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()}),Ut(this,"get",i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=M("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n}),Ut(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=dt(r,this.name)}get context(){return st(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Fa(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Na(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var NO=Object.defineProperty,UO=(t,e,r)=>e in t?NO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Se=(t,e,r)=>UO(t,typeof e!="symbol"?e+"":e,r);class kO{constructor(e,r,i){this.core=e,this.logger=r,Se(this,"name",C$),Se(this,"keychain"),Se(this,"randomSessionIdentifier",Wa()),Se(this,"initialized",!1),Se(this,"clientId"),Se(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Se(this,"hasKeys",n=>(this.isInitialized(),this.keychain.has(n))),Se(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const n=await this.getClientSeed(),s=pl(n),o=sp(s.publicKey);return this.clientId=o,o}),Se(this,"generateKeyPair",()=>{this.isInitialized();const n=vI();return this.setPrivateKey(n.publicKey,n.privateKey)}),Se(this,"signJWT",async n=>{this.isInitialized();const s=await this.getClientSeed(),o=pl(s),a=this.randomSessionIdentifier;return await y2(a,n,B$,o)}),Se(this,"generateSharedKey",(n,s,o)=>{this.isInitialized();const a=this.getPrivateKey(n),c=EI(a,s);return this.setSymKey(c,o)}),Se(this,"setSymKey",async(n,s)=>{this.isInitialized();const o=s||ds(n);return await this.keychain.set(o,n),o}),Se(this,"deleteKeyPair",async n=>{this.isInitialized(),await this.keychain.del(n)}),Se(this,"deleteSymKey",async n=>{this.isInitialized(),await this.keychain.del(n)}),Se(this,"encode",async(n,s,o)=>{this.isInitialized();const a=Cg(o),c=lr(s);if(ah(a))return II(c,o==null?void 0:o.encoding);if(oh(a)){const f=a.senderPublicKey,d=a.receiverPublicKey;n=await this.generateSharedKey(f,d)}const u=this.getSymKey(n),{type:l,senderPublicKey:h}=a;return xI({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o==null?void 0:o.encoding})}),Se(this,"decode",async(n,s,o)=>{this.isInitialized();const a=$I(s,o);if(ah(a)){const c=SI(s,o==null?void 0:o.encoding);return si(c)}if(oh(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;n=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(n),u=_I({symKey:c,encoded:s,encoding:o==null?void 0:o.encoding});return si(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Se(this,"getPayloadType",(n,s=tt)=>{const o=In({encoded:n,encoding:s});return ai(o.type)}),Se(this,"getPayloadSenderPublicKey",(n,s=tt)=>{const o=In({encoded:n,encoding:s});return o.senderPublicKey?nt(o.senderPublicKey,Ge):void 0}),this.core=e,this.logger=dt(r,this.name),this.keychain=i||new FO(this.core,this.logger)}get context(){return st(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(Nh)}catch{e=Wa(),await this.keychain.set(Nh,e)}return BO(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var jO=Object.defineProperty,LO=Object.defineProperties,MO=Object.getOwnPropertyDescriptors,Vh=Object.getOwnPropertySymbols,qO=Object.prototype.hasOwnProperty,zO=Object.prototype.propertyIsEnumerable,rc=(t,e,r)=>e in t?jO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,VO=(t,e)=>{for(var r in e||(e={}))qO.call(e,r)&&rc(t,r,e[r]);if(Vh)for(var r of Vh(e))zO.call(e,r)&&rc(t,r,e[r]);return t},HO=(t,e)=>LO(t,MO(e)),ot=(t,e,r)=>rc(t,typeof e!="symbol"?e+"":e,r);class KO extends O8{constructor(e,r){super(e,r),this.logger=e,this.core=r,ot(this,"messages",new Map),ot(this,"messagesWithoutClientAck",new Map),ot(this,"name",F$),ot(this,"version",N$),ot(this,"initialized",!1),ot(this,"storagePrefix",Kt),ot(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const n=await this.getRelayerMessagesWithoutClientAck();typeof n<"u"&&(this.messagesWithoutClientAck=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),ot(this,"set",async(i,n,s)=>{this.isInitialized();const o=bt(n);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=n,this.messages.set(i,a),s===ys.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,HO(VO({},c),{[o]:n}))}return await this.persist(),o}),ot(this,"get",i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n}),ot(this,"getWithoutAck",i=>{this.isInitialized();const n={};for(const s of i){const o=this.messagesWithoutClientAck.get(s)||{};n[s]=Object.values(o)}return n}),ot(this,"has",(i,n)=>{this.isInitialized();const s=this.get(i),o=bt(n);return typeof s[o]<"u"}),ot(this,"ack",async(i,n)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(i);if(typeof s>"u")return;const o=bt(n);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,s),await this.persist()}),ot(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=dt(e,this.name),this.core=r}get context(){return st(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,Fa(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Fa(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Na(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Na(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var WO=Object.defineProperty,GO=Object.defineProperties,YO=Object.getOwnPropertyDescriptors,Hh=Object.getOwnPropertySymbols,ZO=Object.prototype.hasOwnProperty,JO=Object.prototype.propertyIsEnumerable,ic=(t,e,r)=>e in t?WO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vi=(t,e)=>{for(var r in e||(e={}))ZO.call(e,r)&&ic(t,r,e[r]);if(Hh)for(var r of Hh(e))JO.call(e,r)&&ic(t,r,e[r]);return t},Kh=(t,e)=>GO(t,YO(e)),yt=(t,e,r)=>ic(t,typeof e!="symbol"?e+"":e,r);class XO extends D8{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,yt(this,"events",new St.EventEmitter),yt(this,"name",k$),yt(this,"queue",new Map),yt(this,"publishTimeout",L.toMiliseconds(L.ONE_MINUTE)),yt(this,"initialPublishTimeout",L.toMiliseconds(L.ONE_SECOND*15)),yt(this,"needsTransportRestart",!1),yt(this,"publish",async(i,n,s)=>{var o,a,c,u,l;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:s}});const h=(s==null?void 0:s.ttl)||U$,f=(s==null?void 0:s.prompt)||!1,d=(s==null?void 0:s.tag)||0,p=(s==null?void 0:s.id)||Rr().toString(),g=$i(Fs().protocol),w={id:p,method:(s==null?void 0:s.publishMethod)||g.publish,params:vi({topic:i,message:n,ttl:h,prompt:f,tag:d,attestation:s==null?void 0:s.attestation},s==null?void 0:s.tvf)},I=`Failed to publish payload, please try again. id:${p} tag:${d}`;try{_e((o=w.params)==null?void 0:o.prompt)&&((a=w.params)==null||delete a.prompt),_e((c=w.params)==null?void 0:c.tag)&&((u=w.params)==null||delete u.tag);const C=new Promise(async b=>{const v=({id:P})=>{var T;((T=w.id)==null?void 0:T.toString())===P.toString()&&(this.removeRequestFromQueue(P),this.relayer.events.removeListener(me.publish,v),b())};this.relayer.events.on(me.publish,v);const D=zt(new Promise((P,T)=>{this.rpcPublish(w,s).then(P).catch(R=>{this.logger.warn(R,R==null?void 0:R.message),T(R)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${d}`);try{await D,this.events.removeListener(me.publish,v)}catch(P){this.queue.set(p,{request:w,opts:s,attempt:1}),this.logger.warn(P,P==null?void 0:P.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:i,message:n,opts:s}}),await zt(C,this.publishTimeout,I)}catch(C){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(C),(l=s==null?void 0:s.internal)!=null&&l.throwOnFailedPublish)throw C}finally{this.queue.delete(p)}}),yt(this,"publishCustom",async i=>{var n,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:i});const{payload:u,opts:l={}}=i,{attestation:h,tvf:f,publishMethod:d,prompt:p,tag:g,ttl:w=L.FIVE_MINUTES}=l,I=l.id||Rr().toString(),C=$i(Fs().protocol),b=d||C.publish,v={id:I,method:b,params:vi(Kh(vi({},u),{ttl:w,prompt:p,tag:g,attestation:h}),f)},D=`Failed to publish custom payload, please try again. id:${I} tag:${g}`;try{_e((n=v.params)==null?void 0:n.prompt)&&((s=v.params)==null||delete s.prompt),_e((o=v.params)==null?void 0:o.tag)&&((a=v.params)==null||delete a.tag);const P=new Promise(async T=>{const R=({id:U})=>{var j;((j=v.id)==null?void 0:j.toString())===U.toString()&&(this.removeRequestFromQueue(U),this.relayer.events.removeListener(me.publish,R),T())};this.relayer.events.on(me.publish,R);const A=zt(new Promise((U,j)=>{this.rpcPublish(v,l).then(U).catch(B=>{this.logger.warn(B,B==null?void 0:B.message),j(B)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${b} id:${I} tag:${g}`);try{await A,this.events.removeListener(me.publish,R)}catch(U){this.queue.set(I,{request:v,opts:l,attempt:1}),this.logger.warn(U,U==null?void 0:U.message)}});this.logger.trace({type:"method",method:"publish",params:{id:I,payload:u,opts:l}}),await zt(P,this.publishTimeout,D)}catch(P){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(P),(c=l==null?void 0:l.internal)!=null&&c.throwOnFailedPublish)throw P}finally{this.queue.delete(I)}}),yt(this,"on",(i,n)=>{this.events.on(i,n)}),yt(this,"once",(i,n)=>{this.events.once(i,n)}),yt(this,"off",(i,n)=>{this.events.off(i,n)}),yt(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.relayer=e,this.logger=dt(r,this.name),this.registerEventListeners()}get context(){return st(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(me.publish,vi(vi({},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 n=e.attempt+1;this.queue.set(r,Kh(vi({},e),{attempt:n})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(i=e.request.params)==null?void 0:i.tag}, attempt: ${n}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(hi.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(me.connection_stalled);return}this.checkQueue()}),this.relayer.on(me.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var QO=Object.defineProperty,eD=(t,e,r)=>e in t?QO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ei=(t,e,r)=>eD(t,typeof e!="symbol"?e+"":e,r);class tD{constructor(){Ei(this,"map",new Map),Ei(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),Ei(this,"get",e=>this.map.get(e)||[]),Ei(this,"exists",(e,r)=>this.get(e).includes(r)),Ei(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,r))return;const n=i.filter(s=>s!==r);if(!n.length){this.map.delete(e);return}this.map.set(e,n)}),Ei(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var rD=Object.defineProperty,iD=Object.defineProperties,nD=Object.getOwnPropertyDescriptors,Wh=Object.getOwnPropertySymbols,sD=Object.prototype.hasOwnProperty,oD=Object.prototype.propertyIsEnumerable,nc=(t,e,r)=>e in t?rD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rn=(t,e)=>{for(var r in e||(e={}))sD.call(e,r)&&nc(t,r,e[r]);if(Wh)for(var r of Wh(e))oD.call(e,r)&&nc(t,r,e[r]);return t},na=(t,e)=>iD(t,nD(e)),ce=(t,e,r)=>nc(t,typeof e!="symbol"?e+"":e,r);class aD extends C8{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ce(this,"subscriptions",new Map),ce(this,"topicMap",new tD),ce(this,"events",new St.EventEmitter),ce(this,"name",H$),ce(this,"version",K$),ce(this,"pending",new Map),ce(this,"cached",[]),ce(this,"initialized",!1),ce(this,"storagePrefix",Kt),ce(this,"subscribeTimeout",L.toMiliseconds(L.ONE_MINUTE)),ce(this,"initialSubscribeTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ce(this,"clientId"),ce(this,"batchSubscribeTopicsLimit",500),ce(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ce(this,"subscribe",async(i,n)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const o=Fs(n),a={topic:i,relay:o,transportType:n==null?void 0:n.transportType};(s=n==null?void 0:n.internal)!=null&&s.skipSubscribe||this.pending.set(i,a);const c=await this.rpcSubscribe(i,o,n);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:n}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ce(this,"unsubscribe",async(i,n)=>{this.isInitialized(),typeof(n==null?void 0:n.id)<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)}),ce(this,"isSubscribed",i=>new Promise(n=>{n(this.topicMap.topics.includes(i))})),ce(this,"isKnownTopic",i=>new Promise(n=>{n(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(s=>s.topic===i))})),ce(this,"on",(i,n)=>{this.events.on(i,n)}),ce(this,"once",(i,n)=>{this.events.once(i,n)}),ce(this,"off",(i,n)=>{this.events.off(i,n)}),ce(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),ce(this,"start",async()=>{await this.onConnect()}),ce(this,"stop",async()=>{await this.onDisconnect()}),ce(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ce(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(n=>{i.push(n)}),await this.batchSubscribe(i)}),ce(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(hi.pulse,async()=>{await this.checkPending()}),this.events.on(ut.created,async i=>{const n=ut.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()}),this.events.on(ut.deleted,async i=>{const n=ut.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()})}),this.relayer=e,this.logger=dt(r,this.name),this.clientId=""}get context(){return st(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const i=this.topicMap.get(e);await Promise.all(i.map(async n=>await this.unsubscribeById(e,n,r)))}async unsubscribeById(e,r,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}});try{const n=Fs(i);await this.restartToComplete({topic:e,id:r,relay:n}),await this.rpcUnsubscribe(e,r,n);const s=fe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,r,i){var n,s;const o=await this.getSubscriptionId(e);if((n=i==null?void 0:i.internal)!=null&&n.skipSubscribe)return o;(!i||(i==null?void 0:i.transportType)===he.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=(s=i==null?void 0:i.internal)==null?void 0:s.throwOnFailedPublish;try{if((i==null?void 0:i.transportType)===he.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(h=>this.logger.warn(h))},L.toMiliseconds(L.ONE_SECOND)),o;const u=new Promise(async h=>{const f=d=>{d.topic===e&&(this.events.removeListener(ut.created,f),h(d.id))};this.events.on(ut.created,f);try{const d=await zt(new Promise((p,g)=>{this.relayer.request(a).catch(w=>{this.logger.warn(w,w==null?void 0:w.message),g(w)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(ut.created,f),h(d)}catch{}}),l=await zt(u,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return l?o:null}catch(u){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(me.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:$i(r.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await zt(new Promise(n=>{this.relayer.request(i).catch(s=>this.logger.warn(s)).then(n)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(me.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:$i(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let n;try{n=await await zt(new Promise((s,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(me.connection_stalled)}return n}rpcUnsubscribe(e,r,i){const n={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:n}),this.relayer.request(n)}onSubscribe(e,r){this.setSubscription(e,na(rn({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,rn({},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,rn({},r)),this.topicMap.set(r.topic,e),this.events.emit(ut.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}=M("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(ut.deleted,na(rn({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(ut.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<r;i++){const n=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}}this.events.emit(ut.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}=M("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=>na(rn({},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 j3(L.toMiliseconds(L.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}=M("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 bt(e+await this.getClientId())}}var cD=Object.defineProperty,Gh=Object.getOwnPropertySymbols,uD=Object.prototype.hasOwnProperty,lD=Object.prototype.propertyIsEnumerable,sc=(t,e,r)=>e in t?cD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yh=(t,e)=>{for(var r in e||(e={}))uD.call(e,r)&&sc(t,r,e[r]);if(Gh)for(var r of Gh(e))lD.call(e,r)&&sc(t,r,e[r]);return t},ne=(t,e,r)=>sc(t,typeof e!="symbol"?e+"":e,r);class hD extends A8{constructor(e){var r;super(e),ne(this,"protocol","wc"),ne(this,"version",2),ne(this,"core"),ne(this,"logger"),ne(this,"events",new St.EventEmitter),ne(this,"provider"),ne(this,"messages"),ne(this,"subscriber"),ne(this,"publisher"),ne(this,"name",L$),ne(this,"transportExplicitlyClosed",!1),ne(this,"initialized",!1),ne(this,"connectionAttemptInProgress",!1),ne(this,"relayUrl"),ne(this,"projectId"),ne(this,"packageName"),ne(this,"bundleId"),ne(this,"hasExperiencedNetworkDisruption",!1),ne(this,"pingTimeout"),ne(this,"heartBeatTimeout",L.toMiliseconds(L.THIRTY_SECONDS+L.FIVE_SECONDS)),ne(this,"reconnectTimeout"),ne(this,"connectPromise"),ne(this,"reconnectInProgress",!1),ne(this,"requestsInFlight",[]),ne(this,"connectTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ne(this,"request",async i=>{var n,s;this.logger.debug("Publishing Request Payload");const o=i.id||Rr().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:i.method,topic:(n=i.params)==null?void 0:n.topic},"relayer.request - publishing...");const a=`${o}:${((s=i.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(i);return this.requestsInFlight=this.requestsInFlight.filter(u=>u!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),ne(this,"resetPingTimeout",()=>{As()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var i,n,s,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(s=(n=(i=this.provider)==null?void 0:i.connection)==null?void 0:n.socket)==null?void 0:s.terminate)==null||o.call(s)}catch(a){this.logger.warn(a,a==null?void 0:a.message)}},this.heartBeatTimeout))}),ne(this,"onPayloadHandler",i=>{this.onProviderPayload(i),this.resetPingTimeout()}),ne(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(me.connect)}),ne(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),ne(this,"onProviderErrorHandler",i=>{this.logger.fatal(`Fatal socket error: ${i.message}`),this.events.emit(me.error,i),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ne(this,"registerProviderListeners",()=>{this.provider.on(gt.payload,this.onPayloadHandler),this.provider.on(gt.connect,this.onConnectHandler),this.provider.on(gt.disconnect,this.onDisconnectHandler),this.provider.on(gt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=Jc({logger:(r=e.logger)!=null?r:j$,name:this.name}),this.messages=new KO(this.logger,e.core),this.subscriber=new aD(this,this.logger),this.publisher=new XO(this,this.logger),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Wg,_3()?this.packageName=Dl():I3()&&(this.bundleId=Dl()),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 st(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:he.relay},ys.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,r){var i,n,s;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:(n=r==null?void 0:r.internal)==null?void 0:n.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(ut.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(ut.created,u)}),new Promise(async(l,h)=>{a=await this.subscriber.subscribe(e,Yh({internal:{throwOnFailedPublish:o}},r)).catch(f=>{o&&h(f)})||a,l()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await zt(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 vh())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,n)=>i.publishedAt-n.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n,"Error while processing batch message event: "+(n==null?void 0:n.message))}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const n=we(L.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,s)}this.events.emit(me.message,e),await this.recordMessageEvent(e,ys.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(i,n)=>{const s=()=>{n(new Error("Connection interrupted while trying to connect"))};this.provider.once(gt.disconnect,s),await zt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{n(o)}).finally(()=>{this.provider.off(gt.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{n(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(gt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(gt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const n=i;this.logger.warn({},n.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(i=>setTimeout(i,L.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,n,s;if(As())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(n=(i=this.provider)==null?void 0:i.connection)==null?void 0:n.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new eu(new D$(A3({sdkVersion:Qa,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,r){const{topic:i,message:n}=e;await this.messages.set(i,n,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const n=this.messages.has(r,i);return n&&this.logger.warn(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Qc(e)){if(!e.method.endsWith(M$))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:o}=r.data,a={topic:i,message:n,publishedAt:s,transportType:he.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Yh({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else co(e)&&this.events.emit(me.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,ys.inbound),this.events.emit(me.message,e))}async acknowledgePayload(e){const r=$n(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(gt.payload,this.onPayloadHandler),this.provider.off(gt.connect,this.onConnectHandler),this.provider.off(gt.disconnect,this.onDisconnectHandler),this.provider.off(gt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await vh();$S(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(hi.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&AS())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(me.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},L.toMiliseconds(q$)))))}isInitialized(){if(!this.initialized){const{message:e}=M("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 fD(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Zh(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Jh(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const dD="[object RegExp]",pD="[object String]",gD="[object Number]",yD="[object Boolean]",Xh="[object Arguments]",wD="[object Symbol]",mD="[object Date]",bD="[object Map]",vD="[object Set]",ED="[object Array]",xD="[object Function]",_D="[object ArrayBuffer]",sa="[object Object]",ID="[object Error]",SD="[object DataView]",$D="[object Uint8Array]",OD="[object Uint8ClampedArray]",DD="[object Uint16Array]",AD="[object Uint32Array]",PD="[object BigUint64Array]",CD="[object Int8Array]",BD="[object Int16Array]",TD="[object Int32Array]",RD="[object BigInt64Array]",FD="[object Float32Array]",ND="[object Float64Array]";function UD(){}function Qh(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 kD(t,e,r){return ln(t,e,void 0,void 0,void 0,void 0,r)}function ln(t,e,r,i,n,s,o){const a=o(t,e,r,i,n,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return yn(t,e,s,o)}return yn(t,e,s,o)}function yn(t,e,r,i){if(Object.is(t,e))return!0;let n=Jh(t),s=Jh(e);if(n===Xh&&(n=sa),s===Xh&&(s=sa),n!==s)return!1;switch(n){case pD:return t.toString()===e.toString();case gD:{const c=t.valueOf(),u=e.valueOf();return fD(c,u)}case yD:case mD:case wD:return Object.is(t.valueOf(),e.valueOf());case dD:return t.source===e.source&&t.flags===e.flags;case xD:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(n){case bD:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!ln(u,e.get(c),c,t,e,r,i))return!1;return!0}case vD:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let l=0;l<c.length;l++){const h=c[l],f=u.findIndex(d=>ln(h,d,void 0,t,e,r,i));if(f===-1)return!1;u.splice(f,1)}return!0}case ED:case $D:case OD:case DD:case AD:case PD:case CD:case BD:case TD:case RD:case FD:case ND:{if(typeof re<"u"&&re.isBuffer(t)!==re.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!ln(t[c],e[c],c,t,e,r,i))return!1;return!0}case _D:return t.byteLength!==e.byteLength?!1:yn(new Uint8Array(t),new Uint8Array(e),r,i);case SD:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:yn(new Uint8Array(t),new Uint8Array(e),r,i);case ID:return t.name===e.name&&t.message===e.message;case sa:{if(!(yn(t.constructor,e.constructor,r,i)||Qh(t)&&Qh(e)))return!1;const c=[...Object.keys(t),...Zh(t)],u=[...Object.keys(e),...Zh(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const h=c[l],f=t[h];if(!Object.hasOwn(e,h))return!1;const d=e[h];if(!ln(f,d,h,t,e,r,i))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function jD(t,e){return kD(t,e,UD)}var LD=Object.defineProperty,ef=Object.getOwnPropertySymbols,MD=Object.prototype.hasOwnProperty,qD=Object.prototype.propertyIsEnumerable,oc=(t,e,r)=>e in t?LD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,tf=(t,e)=>{for(var r in e||(e={}))MD.call(e,r)&&oc(t,r,e[r]);if(ef)for(var r of ef(e))qD.call(e,r)&&oc(t,r,e[r]);return t},Ze=(t,e,r)=>oc(t,typeof e!="symbol"?e+"":e,r);class di extends P8{constructor(e,r,i,n=Kt,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,Ze(this,"map",new Map),Ze(this,"version",z$),Ze(this,"cached",[]),Ze(this,"initialized",!1),Ze(this,"getKey"),Ze(this,"storagePrefix",Kt),Ze(this,"recentlyDeleted",[]),Ze(this,"recentlyDeletedLimit",200),Ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!_e(o)?this.map.set(this.getKey(o),o):iS(o)?this.map.set(o.id,o):nS(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Ze(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())}),Ze(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Ze(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>jD(a[c],o[c]))):this.values)),Ze(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=tf(tf({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Ze(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=dt(r,this.name),this.storagePrefix=n,this.getKey=s}get context(){return st(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:n}=M("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:i}=M("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}=M("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}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var zD=Object.defineProperty,VD=(t,e,r)=>e in t?zD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ee=(t,e,r)=>VD(t,typeof e!="symbol"?e+"":e,r);class HD{constructor(e,r){this.core=e,this.logger=r,ee(this,"name",W$),ee(this,"version",G$),ee(this,"events",new pc),ee(this,"pairings"),ee(this,"initialized",!1),ee(this,"storagePrefix",Kt),ee(this,"ignoredPayloadTypes",[ur]),ee(this,"registeredMethods",[]),ee(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),ee(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),ee(this,"create",async i=>{this.isInitialized();const n=Wa(),s=await this.core.crypto.setSymKey(n),o=we(L.FIVE_MINUTES),a={protocol:Kg},c={topic:s,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},u=hh({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(Yr.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:i==null?void 0:i.transportType,internal:i==null?void 0:i.internal}),{topic:s,uri:u}}),ee(this,"pair",async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[jt.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=lh(i.uri);n.props.properties.topic=s,n.addTrace(jt.pairing_uri_validation_success),n.addTrace(jt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),n.addTrace(jt.existing_pairing),l.active)throw n.setError(rr.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(jt.pairing_not_expired)}const h=c||we(L.FIVE_MINUTES),f={topic:s,relay:a,expiry:h,active:!1,methods:u};this.core.expirer.set(s,h),await this.pairings.set(s,f),n.addTrace(jt.store_new_pairing),i.activatePairing&&await this.activate({topic:s}),this.events.emit(Yr.create,f),n.addTrace(jt.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),n.addTrace(jt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(rr.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(d){throw n.setError(rr.subscribe_pairing_topic_failure),d}return n.addTrace(jt.subscribe_pairing_topic_success),f}),ee(this,"activate",async({topic:i})=>{this.isInitialized();const n=we(L.FIVE_MINUTES);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})}),ee(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:n}=i;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Kr();this.events.once(ae("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),ee(this,"updateExpiry",async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})}),ee(this,"updateMetadata",async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})}),ee(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ee(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:n}=i;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",fe("USER_DISCONNECTED")),await this.deletePairing(n))}),ee(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:n,relay:s,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(n);return hh({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),ee(this,"sendRequest",async(i,n,s)=>{const o=Ct(n,s),a=await this.core.crypto.encode(i,o),c=en[n].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),ee(this,"sendResult",async(i,n,s)=>{const o=$n(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,u=en[c].res;await this.core.relayer.publish(n,a,u),await this.core.history.resolve(o)}),ee(this,"sendError",async(i,n,s)=>{const o=ao(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,u=en[c]?en[c].res:en.unregistered_method.res;await this.core.relayer.publish(n,a,u),await this.core.history.resolve(o)}),ee(this,"deletePairing",async(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,fe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])}),ee(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(n=>qt(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))}),ee(this,"onRelayEventRequest",async i=>{const{topic:n,payload:s}=i;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(n,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(n,s);default:return await this.onUnknownRpcMethodRequest(n,s)}}),ee(this,"onRelayEventResponse",async i=>{const{topic:n,payload:s}=i,o=(await this.core.history.get(n,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(n,s);default:return this.onUnknownRpcMethodResponse(o)}}),ee(this,"onPairingPingRequest",async(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(Yr.ping,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),ee(this,"onPairingPingResponse",(i,n)=>{const{id:s}=n;setTimeout(()=>{Mt(n)?this.events.emit(ae("pairing_ping",s),{}):vt(n)&&this.events.emit(ae("pairing_ping",s),{error:n.error})},500)}),ee(this,"onPairingDeleteRequest",async(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Yr.delete,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),ee(this,"onUnknownRpcMethodRequest",async(i,n)=>{const{id:s,method:o}=n;try{if(this.registeredMethods.includes(o))return;const a=fe("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,i,a),this.logger.error(a)}catch(a){await this.sendError(s,i,a),this.logger.error(a)}}),ee(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(fe("WC_METHOD_UNSUPPORTED",i))}),ee(this,"isValidPair",(i,n)=>{var s;if(!Xe(i)){const{message:a}=M("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(rr.malformed_pairing_uri),new Error(a)}if(!rS(i.uri)){const{message:a}=M("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(rr.malformed_pairing_uri),new Error(a)}const o=lh(i==null?void 0:i.uri);if(!((s=o==null?void 0:o.relay)!=null&&s.protocol)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(rr.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(rr.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&L.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){n.setError(rr.pairing_expired);const{message:a}=M("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),ee(this,"isValidPing",async i=>{if(!Xe(i)){const{message:s}=M("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),ee(this,"isValidDisconnect",async i=>{if(!Xe(i)){const{message:s}=M("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),ee(this,"isValidPairingTopic",async i=>{if(!be(i,!1)){const{message:n}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(qt(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=M("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}}),this.core=e,this.logger=dt(r,this.name),this.pairings=new di(this.core,this.logger,this.name,this.storagePrefix)}get context(){return st(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(me.message,async e=>{const{topic:r,message:i,transportType:n}=e;if(this.pairings.keys.includes(r)&&n!==he.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const s=await this.core.crypto.decode(r,i);Qc(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):co(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,i)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(wt.expired,async e=>{const{topic:r}=Tp(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Yr.expire,{topic:r}))})}}var KD=Object.defineProperty,WD=(t,e,r)=>e in t?KD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Be=(t,e,r)=>WD(t,typeof e!="symbol"?e+"":e,r);class GD extends $8{constructor(e,r){super(e,r),this.core=e,this.logger=r,Be(this,"records",new Map),Be(this,"events",new St.EventEmitter),Be(this,"name",Y$),Be(this,"version",Z$),Be(this,"cached",[]),Be(this,"initialized",!1),Be(this,"storagePrefix",Kt),Be(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)}),Be(this,"set",(i,n,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:n,chainId:s}),this.records.has(n.id))return;const o={id:n.id,topic:i,request:{method:n.method,params:n.params||null},chainId:s,expiry:we(L.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Ot.created,o)}),Be(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const n=await this.getRecord(i.id);typeof n.response>"u"&&(n.response=vt(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(Ot.updated,n))}),Be(this,"get",async(i,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:n}),await this.getRecord(n))),Be(this,"delete",(i,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(s=>{if(s.topic===i){if(typeof n<"u"&&s.id!==n)return;this.records.delete(s.id),this.events.emit(Ot.deleted,s)}}),this.persist()}),Be(this,"exists",async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1)),Be(this,"on",(i,n)=>{this.events.on(i,n)}),Be(this,"once",(i,n)=>{this.events.once(i,n)}),Be(this,"off",(i,n)=>{this.events.off(i,n)}),Be(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=dt(r,this.name)}get context(){return st(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:Ct(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}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ot.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=M("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(Ot.created,e=>{const r=Ot.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Ot.updated,e=>{const r=Ot.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Ot.deleted,e=>{const r=Ot.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(hi.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{L.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Ot.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var YD=Object.defineProperty,ZD=(t,e,r)=>e in t?YD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ze=(t,e,r)=>ZD(t,typeof e!="symbol"?e+"":e,r);class JD extends B8{constructor(e,r){super(e,r),this.core=e,this.logger=r,ze(this,"expirations",new Map),ze(this,"events",new St.EventEmitter),ze(this,"name",J$),ze(this,"version",X$),ze(this,"cached",[]),ze(this,"initialized",!1),ze(this,"storagePrefix",Kt),ze(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)}),ze(this,"has",i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}}),ze(this,"set",(i,n)=>{this.isInitialized();const s=this.formatTarget(i),o={target:s,expiry:n};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(wt.created,{target:s,expiration:o})}),ze(this,"get",i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)}),ze(this,"del",i=>{if(this.isInitialized(),this.has(i)){const n=this.formatTarget(i),s=this.getExpiration(n);this.expirations.delete(n),this.events.emit(wt.deleted,{target:n,expiration:s})}}),ze(this,"on",(i,n)=>{this.events.on(i,n)}),ze(this,"once",(i,n)=>{this.events.once(i,n)}),ze(this,"off",(i,n)=>{this.events.off(i,n)}),ze(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=dt(r,this.name)}get context(){return st(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 P3(e);if(typeof e=="number")return C3(e);const{message:r}=M("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(wt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=M("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}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;L.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(wt.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(hi.pulse,()=>this.checkExpirations()),this.events.on(wt.created,e=>{const r=wt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(wt.expired,e=>{const r=wt.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(wt.deleted,e=>{const r=wt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var XD=Object.defineProperty,QD=(t,e,r)=>e in t?XD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ye=(t,e,r)=>QD(t,typeof e!="symbol"?e+"":e,r);class eA extends T8{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,ye(this,"name",Q$),ye(this,"abortController"),ye(this,"isDevEnv"),ye(this,"verifyUrlV3",t6),ye(this,"storagePrefix",Kt),ye(this,"version",Hg),ye(this,"publicKey"),ye(this,"fetchPromise"),ye(this,"init",async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&L.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ye(this,"register",async n=>{if(!Mi()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=n,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const u=ii(),l=this.startAbortTimer(L.ONE_SECOND*5),h=await new Promise((f,d)=>{const p=()=>{window.removeEventListener("message",w),u.body.removeChild(g),d("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=u.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const w=I=>{if(I.data&&typeof I.data=="string")try{const C=JSON.parse(I.data);if(C.type==="verify_attestation"){if(Ca(C.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",w),f(C.attestation===null?"":C.attestation)}}catch(C){this.logger.warn(C)}};u.body.appendChild(g),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug(h,"jwt attestation"),h}catch(u){this.logger.warn(u)}return""}),ye(this,"resolve",async n=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=n;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Ca(s).payload.id!==a)return;const u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!o)return;const c=this.getVerifyUrl(n==null?void 0:n.verifyUrl);return this.fetchAttestation(o,c)}),ye(this,"fetchAttestation",async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const o=this.startAbortTimer(L.ONE_SECOND*5),a=await fetch(`${s}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),ye(this,"getVerifyUrl",n=>{let s=n||gn;return r6.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${gn}`),s=gn),s}),ye(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(L.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(n),await s.json()}catch(n){this.logger.warn(n)}}),ye(this,"persistPublicKey",async n=>{this.logger.debug(n,"persisting public key to local storage"),await this.store.setItem(this.storeKey,n),this.publicKey=n}),ye(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ye(this,"isValidJwtAttestation",async n=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(n,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(n,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),ye(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ye(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const n=await this.fetchPromise;return this.fetchPromise=void 0,n}),ye(this,"validateAttestation",(n,s)=>{const o=DI(n,s.publicKey),a={hasExpired:L.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=dt(r,this.name),this.abortController=new AbortController,this.isDevEnv=Lc(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return st(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),L.toMiliseconds(e))}}var tA=Object.defineProperty,rA=(t,e,r)=>e in t?tA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rf=(t,e,r)=>rA(t,typeof e!="symbol"?e+"":e,r);class iA extends R8{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,rf(this,"context",i6),rf(this,"registerDeviceToken",async i=>{const{clientId:n,token:s,notificationType:o,enableEncrypted:a=!1}=i,c=`${n6}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:o,token:s,always_raw:a})})}),this.logger=dt(r,this.context)}}var nA=Object.defineProperty,nf=Object.getOwnPropertySymbols,sA=Object.prototype.hasOwnProperty,oA=Object.prototype.propertyIsEnumerable,ac=(t,e,r)=>e in t?nA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,nn=(t,e)=>{for(var r in e||(e={}))sA.call(e,r)&&ac(t,r,e[r]);if(nf)for(var r of nf(e))oA.call(e,r)&&ac(t,r,e[r]);return t},$e=(t,e,r)=>ac(t,typeof e!="symbol"?e+"":e,r);class aA extends F8{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,$e(this,"context",o6),$e(this,"storagePrefix",Kt),$e(this,"storageVersion",s6),$e(this,"events",new Map),$e(this,"shouldPersist",!1),$e(this,"init",async()=>{if(!Lc())try{const n={eventId:Pl(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Cp(this.core.relayer.protocol,this.core.relayer.version,Qa)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}}),$e(this,"createEvent",n=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=n,u=Pl(),l=this.core.projectId||"",h=Date.now(),f=nn({eventId:u,timestamp:h,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,f),this.shouldPersist=!0),f}),$e(this,"getEvent",n=>{const{eventId:s,topic:o}=n;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return nn(nn({},a),this.setMethods(a.eventId))}),$e(this,"deleteEvent",n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0}),$e(this,"setEventListeners",()=>{this.core.heartbeat.on(hi.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{L.fromMiliseconds(Date.now())-L.fromMiliseconds(n.timestamp)>a6&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})}),$e(this,"setMethods",n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)})),$e(this,"addTrace",(n,s)=>{const o=this.events.get(n);o&&(o.props.properties.trace.push(s),this.events.set(n,o),this.shouldPersist=!0)}),$e(this,"setError",(n,s)=>{const o=this.events.get(n);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(n,o),this.shouldPersist=!0)}),$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 n=await this.core.storage.getItem(this.storageKey)||[];if(!n.length)return;n.forEach(s=>{this.events.set(s.eventId,nn(nn({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}}),$e(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[s,o]of this.events)o.props.type&&n.push(o);if(n.length!==0)try{if((await this.sendEvent(n)).ok)for(const s of n)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),$e(this,"sendEvent",async n=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${c6}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Qa}${s}`,{method:"POST",body:JSON.stringify(n)})}),$e(this,"getAppDomain",()=>Pp().url),this.logger=dt(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 cA=Object.defineProperty,sf=Object.getOwnPropertySymbols,uA=Object.prototype.hasOwnProperty,lA=Object.prototype.propertyIsEnumerable,cc=(t,e,r)=>e in t?cA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,of=(t,e)=>{for(var r in e||(e={}))uA.call(e,r)&&cc(t,r,e[r]);if(sf)for(var r of sf(e))lA.call(e,r)&&cc(t,r,e[r]);return t},ue=(t,e,r)=>cc(t,typeof e!="symbol"?e+"":e,r);let hA=class o0 extends x8{constructor(e){var r;super(e),ue(this,"protocol",Vg),ue(this,"version",Hg),ue(this,"name",Us),ue(this,"relayUrl"),ue(this,"projectId"),ue(this,"customStoragePrefix"),ue(this,"events",new St.EventEmitter),ue(this,"logger"),ue(this,"heartbeat"),ue(this,"relayer"),ue(this,"crypto"),ue(this,"storage"),ue(this,"history"),ue(this,"expirer"),ue(this,"pairing"),ue(this,"verify"),ue(this,"echoClient"),ue(this,"linkModeSupportedApps"),ue(this,"eventClient"),ue(this,"initialized",!1),ue(this,"logChunkController"),ue(this,"on",(a,c)=>this.events.on(a,c)),ue(this,"once",(a,c)=>this.events.once(a,c)),ue(this,"off",(a,c)=>this.events.off(a,c)),ue(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ue(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:he.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});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)||Wg,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const n=u3({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:A$.logger,name:Us}),{logger:s,chunkLoggerController:o}=Dp({opts:n,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=dt(s,this.name),this.heartbeat=new jS,this.crypto=new kO(this,this.logger,e==null?void 0:e.keychain),this.history=new GD(this,this.logger),this.expirer=new JD(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new b8(of(of({},P$),e==null?void 0:e.storageOptions)),this.relayer=new hD({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new HD(this,this.logger),this.verify=new eA(this,this.logger,this.storage),this.echoClient=new iA(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new aA(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new o0(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(V$,i),r}get context(){return st(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(Uh,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(Uh)||[],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 xt<"u"&&{}.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const fA=hA,a0="wc",c0=2,u0="client",tu=`${a0}@${c0}:${u0}:`,oa={name:u0,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},af="WALLETCONNECT_DEEPLINK_CHOICE",dA="proposal",cf="Proposal expired",pA="session",xi=L.SEVEN_DAYS,gA="engine",Te={wc_sessionPropose:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1104},res:{ttl:L.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1106},res:{ttl:L.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1112},res:{ttl:L.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1114},res:{ttl:L.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:L.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:L.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1119}}},aa={min:L.FIVE_MINUTES,max:L.SEVEN_DAYS},kt={idle:"IDLE",active:"ACTIVE"},yA={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:""}},wA="request",mA=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],bA="wc",vA="auth",EA="authKeys",xA="pairingTopics",_A="requests",lo=`${bA}@${1.5}:${vA}:`,ws=`${lo}:PUB_KEY`;var IA=Object.defineProperty,SA=Object.defineProperties,$A=Object.getOwnPropertyDescriptors,uf=Object.getOwnPropertySymbols,OA=Object.prototype.hasOwnProperty,DA=Object.prototype.propertyIsEnumerable,uc=(t,e,r)=>e in t?IA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,oe=(t,e)=>{for(var r in e||(e={}))OA.call(e,r)&&uc(t,r,e[r]);if(uf)for(var r of uf(e))DA.call(e,r)&&uc(t,r,e[r]);return t},Re=(t,e)=>SA(t,$A(e)),k=(t,e,r)=>uc(t,typeof e!="symbol"?e+"":e,r);class AA extends j8{constructor(e){super(e),k(this,"name",gA),k(this,"events",new pc),k(this,"initialized",!1),k(this,"requestQueue",{state:kt.idle,queue:[]}),k(this,"sessionRequestQueue",{state:kt.idle,queue:[]}),k(this,"emittedSessionRequests",new L3({limit:500})),k(this,"requestQueueDelay",L.ONE_SECOND),k(this,"expectedPairingMethodMap",new Map),k(this,"recentlyDeletedMap",new Map),k(this,"recentlyDeletedLimit",200),k(this,"relayMessageCache",[]),k(this,"pendingSessions",new Map),k(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(Te)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay)))}),k(this,"connect",async r=>{var i;this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=Re(oe({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=JI(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:u,relays:l,authentication:h,walletPay:f}=n,d=((i=h==null?void 0:h[0])==null?void 0:i.ttl)||Te.wc_sessionPropose.req.ttl||L.FIVE_MINUTES;this.validateRequestExpiry(d);let p=s,g,w=!1;try{if(p){const A=this.client.core.pairing.pairings.get(p);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),w=A.active}}catch(A){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),A}if(!p||!w){const{topic:A,uri:U}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=A,g=U}if(!p){const{message:A}=M("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(A)}const I=await this.client.core.crypto.generateKeyPair(),C=we(d),b=oe(Re(oe(oe({requiredNamespaces:o,optionalNamespaces:a,relays:l??[{protocol:Kg}],proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:C,pairingTopic:p},c&&{sessionProperties:c}),u&&{scopedProperties:u}),{id:Lt()}),(h||f)&&{requests:{authentication:h==null?void 0:h.map(A=>{const{domain:U,chains:j,nonce:B,uri:_,exp:O,nbf:m,type:y,statement:x,requestId:$,resources:E,signatureTypes:S}=A;return{domain:U,chains:j,nonce:B,type:y??"caip122",aud:_,version:"1",iat:new Date().toISOString(),exp:O,nbf:m,statement:x,requestId:$,resources:E,signatureTypes:S}}),walletPay:f}}),v=ae("session_connect",b.id),{reject:D,resolve:P,done:T}=Kr(d,cf),R=({id:A})=>{A===b.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(b.id),this.events.emit(v,{error:{message:cf,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(v,({error:A,session:U})=>{this.client.events.off("proposal_expire",R),A?D(A):U&&P(U)}),await this.setProposal(b.id,b),await this.sendProposeSession({proposal:b,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:b.id}}}).catch(A=>{throw this.deleteProposal(b.id),A}),{uri:g,approval:T}}),k(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}}),k(this,"approve",async r=>{var i,n,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=r==null?void 0:r.id)==null?void 0:i.toString(),trace:[Dt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(U){throw o.setError(zr.no_internet_connection),U}try{await this.isValidProposalId(r==null?void 0:r.id)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${r==null?void 0:r.id}) failed`),o.setError(zr.proposal_not_found),U}try{await this.isValidApprove(r)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(zr.session_approve_namespace_validation_failure),U}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:w,requiredNamespaces:I,optionalNamespaces:C}=p;let b=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:g});b||(b=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Dt.session_approve_started,properties:{topic:g,trace:[Dt.session_approve_started,Dt.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),D=w.publicKey,P=await this.client.core.crypto.generateSharedKey(v,D),T=Re(oe(oe(oe({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:v,metadata:this.client.metadata},expiry:we(xi)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{proposalRequestsResponses:d}),R=he.relay;b.addTrace(Dt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:R,internal:{skipSubscribe:!0}})}catch(U){throw b.setError(zr.subscribe_session_topic_failure),U}b.addTrace(Dt.subscribe_session_topic_success);const A=Re(oe({},T),{topic:P,requiredNamespaces:I,optionalNamespaces:C,pairingTopic:g,acknowledged:!1,self:T.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:v,transportType:he.relay,authentication:d==null?void 0:d.authentication,walletPayResult:d==null?void 0:d.walletPay});await this.client.session.set(P,A),b.addTrace(Dt.store_session);try{await this.sendApproveSession({sessionTopic:P,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:v},sessionSettleRequest:T,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:oe({correlationId:a},this.getTVFApproveParams(A))}}),b.addTrace(Dt.session_approve_publish_success)}catch(U){throw this.client.logger.error(U),this.client.session.delete(P,fe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(P),U}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:w.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(P,we(xi)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),k(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:n}=r;let s;try{s=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}s&&await this.sendError({id:i,topic:s,error:n,rpcOpts:Te.wc_sessionPropose.reject}),await this.deleteProposal(i)}),k(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:i,namespaces:n}=r,{done:s,resolve:o,reject:a}=Kr(L.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Lt(),u=Rr().toString(),l=this.client.session.get(i).namespaces;return this.events.once(ae("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(h=>{this.client.logger.error(h),this.client.session.update(i,{namespaces:l}),a(h)}),{acknowledged:s}}),k(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=r,n=Lt(),{done:s,resolve:o,reject:a}=Kr(L.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(ae("session_extend",n),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,we(xi)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),k(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:i,request:n,topic:s,expiry:o=Te.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);(a==null?void 0:a.transportType)===he.relay&&await this.confirmOnlineStateOrThrow();const c=Lt(),u=Rr().toString(),{done:l,resolve:h,reject:f}=Kr(o,"Request expired. Please try again.");this.events.once(ae("session_request",c),({error:w,result:I})=>{w?f(w):h(I)});const d="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:d,params:{request:Re(oe({},n),{expiryTimestamp:we(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(w=>f(w)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),await l();const g={request:Re(oe({},n),{expiryTimestamp:we(o)}),chainId:i};return await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:d,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(I=>f(I)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),w()}),new Promise(async w=>{var I;if(!((I=a.sessionConfig)!=null&&I.disableDeepLink)){const C=await F3(this.client.core.storage,af);await B3({id:c,topic:s,wcDeepLink:C})}w()}),l()]).then(w=>w[2])}),k(this,"respond",async r=>{var i,n;this.isInitialized();const s=this.client.core.eventClient.createEvent({properties:{topic:(r==null?void 0:r.topic)||((n=(i=r==null?void 0:r.response)==null?void 0:i.id)==null?void 0:n.toString()),trace:[Dt.session_request_response_started]}});try{await this.isValidRespond(r)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zr.session_request_response_validation_failure),h}s.addTrace(Dt.session_request_response_validation_success);const{topic:o,response:a}=r,{id:c}=a,u=this.client.session.get(o);u.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const l=this.getAppLinkIfEnabled(u.peer.metadata,u.transportType);try{s.addTrace(Dt.session_request_response_publish_started),Mt(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:l}):vt(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:l}),this.cleanupAfterResponse(r)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zr.session_request_response_publish_failure),h}}),k(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:i}=r;if(this.client.session.keys.includes(i)){const n=Lt(),s=Rr().toString(),{done:o,resolve:a,reject:c}=Kr(L.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(ae("session_ping",n),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),k(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,o=Rr().toString(),a=Lt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),k(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:fe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=M("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}}),k(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>eS(i,r)))),k(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),k(this,"authenticate",async(r,i)=>{var n;this.isInitialized(),this.isValidAuthenticate(r);const s=i&&this.client.core.linkModeSupportedApps.includes(i)&&((n=this.client.metadata.redirect)==null?void 0:n.linkMode),o=s?he.link_mode:he.relay;o===he.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:h,type:f,exp:d,nbf:p,methods:g=[],expiry:w}=r,I=[...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 v=await this.client.core.crypto.generateKeyPair(),D=ds(v);if(await Promise.all([this.client.auth.authKeys.set(ws,{responseTopic:D,publicKey:v}),this.client.auth.pairingTopics.set(D,{topic:D,pairingTopic:C})]),await this.client.core.relayer.subscribe(D,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${C}`),g.length>0){const{namespace:E}=cr(a[0]);let S=Qx(E,"request",g);fs(I)&&(S=t_(S,I.pop())),I.push(S)}const P=w&&w>Te.wc_sessionAuthenticate.req.ttl?w:Te.wc_sessionAuthenticate.req.ttl,T={authPayload:{type:f??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:h,iat:new Date().toISOString(),exp:d,nbf:p,resources:I},requester:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:we(P)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},A={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:C,proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:we(Te.wc_sessionPropose.req.ttl),id:Lt()},{done:U,resolve:j,reject:B}=Kr(P,"Request expired"),_=Lt(),O=ae("session_connect",A.id),m=ae("session_request",_),y=async({error:E,session:S})=>{this.events.off(m,x),E?B(E):S&&j({session:S})},x=async E=>{var S,F,N;if(await this.deletePendingAuthRequest(_,{message:"fulfilled",code:0}),E.error){const W=fe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return E.error.code===W.code?void 0:(this.events.off(O,y),B(E.error.message))}await this.deleteProposal(A.id),this.events.off(O,y);const{cacaos:H,responder:z}=E.result,q=[],K=[];for(const W of H){await Ml({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),B(fe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Q}=W,pe=fs(Q.resources),ve=[Ua(Q.iss)],Ie=Cs(Q.iss);if(pe){const He=ql(pe),Wt=zl(pe);q.push(...He),ve.push(...Wt)}for(const He of ve)K.push(`${He}:${Ie}`)}const G=await this.client.core.crypto.generateSharedKey(v,z.publicKey);let X;q.length>0&&(X={topic:G,acknowledged:!0,self:{publicKey:v,metadata:this.client.metadata},peer:z,controller:z.publicKey,expiry:we(xi),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:C,namespaces:gh([...new Set(q)],[...new Set(K)]),transportType:o},await this.client.core.relayer.subscribe(G,{transportType:o}),await this.client.session.set(G,X),C&&await this.client.core.pairing.updateMetadata({topic:C,metadata:z.metadata}),X=this.client.session.get(G)),(S=this.client.metadata.redirect)!=null&&S.linkMode&&(F=z.metadata.redirect)!=null&&F.linkMode&&(N=z.metadata.redirect)!=null&&N.universal&&i&&(this.client.core.addLinkModeSupportedApp(z.metadata.redirect.universal),this.client.session.update(G,{transportType:he.link_mode})),j({auths:H,session:X})};this.events.once(O,y),this.events.once(m,x);let $;try{if(s){const E=Ct("wc_sessionAuthenticate",T,_);this.client.core.history.set(C,E);const S=await this.client.core.crypto.encode("",E,{type:Nn,encoding:Br});$=rs(i,C,S)}else await Promise.all([this.sendRequest({topic:C,method:"wc_sessionAuthenticate",params:T,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:_}),this.sendRequest({topic:C,method:"wc_sessionPropose",params:A,expiry:Te.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:A.id})])}catch(E){throw this.events.off(O,y),this.events.off(m,x),E}return await this.setProposal(A.id,A),await this.setAuthRequest(_,{request:Re(oe({},T),{verifyContext:{}}),pairingTopic:C,transportType:o}),{uri:$??b,response:U}}),k(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Vr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw s.setError(tn.no_internet_connection),w}const o=this.getPendingAuthRequest(i);if(!o)throw s.setError(tn.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||he.relay;a===he.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=ds(c),h={type:ur,receiverPublicKey:c,senderPublicKey:u},f=[],d=[];for(const w of n){if(!await Ml({cacao:w,projectId:this.client.core.projectId})){s.setError(tn.invalid_cacao);const D=fe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:l,error:D,encodeOpts:h}),new Error(D.message)}s.addTrace(Vr.cacaos_verified);const{p:I}=w,C=fs(I.resources),b=[Ua(I.iss)],v=Cs(I.iss);if(C){const D=ql(C),P=zl(C);f.push(...D),b.push(...P)}for(const D of b)d.push(`${D}:${v}`)}const p=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(Vr.create_authenticated_session_topic);let g;if((f==null?void 0:f.length)>0){g={topic:p,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:we(xi),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:gh([...new Set(f)],[...new Set(d)]),transportType:a},s.addTrace(Vr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(w){throw s.setError(tn.subscribe_authenticated_session_topic_failure),w}s.addTrace(Vr.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Vr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Vr.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:i,result:{cacaos:n,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw s.setError(tn.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:g}}),k(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:i,reason:n}=r,s=this.getPendingAuthRequest(i);if(!s)throw new Error(`Could not find pending auth request with id ${i}`);s.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ds(o),u={type:ur,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:n,encodeOpts:u,rpcOpts:Te.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.deleteProposal(i)}),k(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:n}=r;return Zp(i,n)}),k(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)}),k(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.pairingTopic),n=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==i.topic});if(n.length===0)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),k(this,"deleteSession",async r=>{var i;const{topic:n,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,fe("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),s||this.client.core.expirer.del(n),this.client.core.storage.removeItem(af).catch(u=>this.client.logger.warn(u)),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=kt.idle),await Promise.all(this.getPendingSessionRequests().filter(u=>u.topic===n).map(u=>this.deletePendingSessionRequest(u.id,fe("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:n})}),k(this,"deleteProposal",async(r,i)=>{if(i)try{const n=this.client.proposal.get(r),s=this.client.core.eventClient.getEvent({topic:n.pairingTopic});s==null||s.setError(zr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,fe("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),k(this,"deletePendingSessionRequest",async(r,i,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),n&&(this.sessionRequestQueue.state=kt.idle,this.client.events.emit("session_request_expire",{id:r}))}),k(this,"deletePendingAuthRequest",async(r,i,n=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)])}),k(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}))}),k(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,we(Te.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),k(this,"setAuthRequest",async(r,i)=>{const{request:n,pairingTopic:s,transportType:o=he.relay}=i;this.client.core.expirer.set(r,n.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:r,pairingTopic:s,verifyContext:n.verifyContext,transportType:o})}),k(this,"setPendingSessionRequest",async r=>{const{id:i,topic:n,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||we(Te.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:n,params:s,verifyContext:o})}),k(this,"sendRequest",async r=>{const{topic:i,method:n,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:h,publishOpts:f={}}=r,d=Ct(n,s,c);let p;const g=!!l;try{const C=g?Br:tt;p=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 w;if(mA.includes(n)){const C=bt(JSON.stringify(d)),b=bt(p);w=await this.client.core.verify.register({id:b,decryptedId:C})}const I=oe(oe({},Te[n].req),f);if(I.attestation=w,o&&(I.ttl=o),a&&(I.id=a),this.client.core.history.set(i,d),g){const C=rs(l,i,p);await Y.Linking.openURL(C,this.client.name)}else I.tvf=Re(oe({},h),{correlationId:d.id}),u?(I.internal=Re(oe({},I.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,p,I)):this.client.core.relayer.publish(i,p,I).catch(C=>this.client.logger.error(C));return d.id}),k(this,"sendProposeSession",async r=>{const{proposal:i,publishOpts:n}=r,s=Ct("wc_sessionPropose",i,i.id);this.client.core.history.set(i.pairingTopic,s);const o=await this.client.core.crypto.encode(i.pairingTopic,s,{encoding:tt}),a=bt(JSON.stringify(s)),c=bt(o),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:i.pairingTopic,sessionProposal:o},opts:Re(oe({},n),{publishMethod:"wc_proposeSession",attestation:u})})}),k(this,"sendApproveSession",async r=>{const{sessionTopic:i,pairingProposalResponse:n,proposal:s,sessionSettleRequest:o,publishOpts:a}=r,c=$n(s.id,n),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:tt}),l=Ct("wc_sessionSettle",o,a==null?void 0:a.id),h=await this.client.core.crypto.encode(i,l,{encoding:tt});this.client.core.history.set(i,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:i,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:h},opts:Re(oe({},a),{publishMethod:"wc_approveSession"})})}),k(this,"sendResult",async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,u=$n(i,s);let l;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const p=h?Br:tt;l=await this.client.core.crypto.encode(n,u,Re(oe({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),p}let f,d;try{f=await this.client.core.history.get(n,i);const p=f.request;try{d=this.getTVFParams(i,p.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g==null?void 0:g.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),p}if(h){const p=rs(c,n,l);await Y.Linking.openURL(p,this.client.name)}else{const p=f.request.method,g=Te[p].res;g.tvf=Re(oe({},d),{correlationId:i}),o?(g.internal=Re(oe({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,l,g)):this.client.core.relayer.publish(n,l,g).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(u)}),k(this,"sendError",async r=>{const{id:i,topic:n,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,u=ao(i,s);let l;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const d=h?Br:tt;l=await this.client.core.crypto.encode(n,u,Re(oe({},o||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),d}let f;try{f=await this.client.core.history.get(n,i)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),d}if(h){const d=rs(c,n,l);await Y.Linking.openURL(d,this.client.name)}else{const d=f.request.method,p=a||Te[d].res;this.client.core.relayer.publish(n,l,p)}await this.client.core.history.resolve(u)}),k(this,"cleanup",async()=>{const r=[],i=[];this.client.session.getAll().forEach(n=>{let s=!1;qt(n.expiry)&&(s=!0),this.client.core.crypto.keychain.has(n.topic)||(s=!0),s&&r.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{qt(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...r.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])}),k(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),k(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),k(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===kt.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=kt.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=kt.idle}),k(this,"processRequest",async r=>{const{topic:i,payload:n,attestation:s,transportType:o,encryptedId:a}=r,c=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),k(this,"onRelayEventResponse",async r=>{const{topic:i,payload:n,transportType:s}=r,o=(await this.client.core.history.get(i,n.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n,s);case"wc_sessionSettle":return this.onSessionSettleResponse(i,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,n);case"wc_sessionExtend":return this.onSessionExtendResponse(i,n);case"wc_sessionPing":return this.onSessionPingResponse(i,n);case"wc_sessionRequest":return this.onSessionRequestResponse(i,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,n);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),k(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:n}=M("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)}),k(this,"shouldIgnorePairingRequest",r=>{const{topic:i,requestMethod:n}=r,s=this.expectedPairingMethodMap.get(i);return!s||s.includes(n)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),k(this,"onSessionProposeRequest",async r=>{const{topic:i,payload:n,attestation:s,encryptedId:o}=r,{params:a,id:c}=n;try{const u=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u==null||u.setError(rr.proposal_listener_not_found)),this.isValidConnect(oe({},n.params));const l=a.expiryTimestamp||we(Te.wc_sessionPropose.req.ttl),h=oe({id:c,pairingTopic:i,expiryTimestamp:l,attestation:s,encryptedId:o},a);await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:s,hash:bt(JSON.stringify(n)),encryptedId:o,metadata:h.proposer.metadata});u==null||u.addTrace(jt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(u){await this.sendError({id:c,topic:i,error:u,rpcOpts:Te.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),k(this,"onSessionProposeResponse",async(r,i,n)=>{const{id:s}=i;if(Mt(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const l=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:l,pairingTopic:r,proposalId:s,publicKey:c});const h=await this.client.core.relayer.subscribe(l,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:r})}else if(vt(i)){await this.deleteProposal(s);const o=ae("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),k(this,"onSessionSettleRequest",async(r,i)=>{const{id:n,params:s}=i;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=i.params,p=[...this.pendingSessions.values()].find(I=>I.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const g=this.client.proposal.get(p.proposalId),w=Re(oe(oe(oe({topic:r,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{transportType:he.relay,authentication:d==null?void 0:d.authentication,walletPayResult:d==null?void 0:d.walletPay});await this.client.session.set(w.topic,w),await this.setExpiry(w.topic,w.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:w.peer.metadata}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(w),await this.sendResult({id:i.id,topic:r,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:w}),this.events.emit(ae("session_connect",p.proposalId),{session:w})}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"onSessionSettleResponse",async(r,i)=>{const{id:n}=i;Mt(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ae("session_approve",n),{})):vt(i)&&(await this.client.session.delete(r,fe("USER_DISCONNECTED")),this.events.emit(ae("session_approve",n),{error:i.error}))}),k(this,"onSessionUpdateRequest",async(r,i)=>{const{params:n,id:s}=i;try{const o=`${r}_session_update`,a=Qi.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:fe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(oe({topic:r},n));try{Qi.set(o,s),await this.client.session.update(r,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:r,result:!0})}catch(c){throw Qi.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:n})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),k(this,"onSessionUpdateResponse",(r,i)=>{const{id:n}=i,s=ae("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_update",n),{}):vt(i)&&this.events.emit(ae("session_update",n),{error:i.error})}),k(this,"onSessionExtendRequest",async(r,i)=>{const{id:n}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,we(xi)),await this.sendResult({id:n,topic:r,result:!0}),this.client.events.emit("session_extend",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),k(this,"onSessionExtendResponse",(r,i)=>{const{id:n}=i,s=ae("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_extend",n),{}):vt(i)&&this.events.emit(ae("session_extend",n),{error:i.error})}),k(this,"onSessionPingRequest",async(r,i)=>{const{id:n}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),k(this,"onSessionPingResponse",(r,i)=>{const{id:n}=i,s=ae("session_ping",n);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Mt(i)?this.events.emit(ae("session_ping",n),{}):vt(i)&&this.events.emit(ae("session_ping",n),{error:i.error})},500)}),k(this,"onSessionDeleteRequest",async(r,i)=>{const{id:n}=i;try{await this.isValidDisconnect({topic:r,reason:i.params}),this.cleanupPendingSentRequestsForTopic({topic:r,error:fe("USER_DISCONNECTED")}),await this.deleteSession({topic:r,id:n})}catch(s){this.client.logger.error(s)}}),k(this,"onSessionRequest",async r=>{var i,n,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=r,{id:h,params:f}=a;try{await this.isValidRequest(oe({topic:o},f));const d=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:bt(JSON.stringify(Ct("wc_sessionRequest",f,h))),encryptedId:u,metadata:d.peer.metadata,transportType:l}),g={id:h,topic:o,params:f,verifyContext:p};await this.setPendingSessionRequest(g),l===he.link_mode&&(i=d.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((n=d.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(d){await this.sendError({id:h,topic:o,error:d}),this.client.logger.error(d)}}),k(this,"onSessionRequestResponse",(r,i)=>{const{id:n}=i,s=ae("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_request",n),{result:i.result}):vt(i)&&this.events.emit(ae("session_request",n),{error:i.error})}),k(this,"onSessionEventRequest",async(r,i)=>{const{id:n,params:s}=i;try{const o=`${r}_session_event_${s.event.name}`,a=Qi.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(oe({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),Qi.set(o,n)}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),Mt(i)?this.events.emit(ae("session_request",n),{result:i.result}):vt(i)&&this.events.emit(ae("session_request",n),{error:i.error})}),k(this,"onSessionAuthenticateRequest",async r=>{var i;const{topic:n,payload:s,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:u,authPayload:l,expiryTimestamp:h}=s.params,f=await this.getVerifyContext({attestationId:o,hash:bt(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),d={requester:u,pairingTopic:n,id:s.id,authPayload:l,verifyContext:f,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:d,pairingTopic:n,transportType:c}),c===he.link_mode&&(i=u.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:s.params,id:s.id,verifyContext:f})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(s.params.requester.metadata,c),d={type:ur,receiverPublicKey:l,senderPublicKey:h};await this.sendError({id:s.id,topic:n,error:u,encodeOpts:d,rpcOpts:Te.wc_sessionAuthenticate.autoReject,appLink:f})}}),k(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),k(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=kt.idle,this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay))}),k(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:i})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(ae("session_request",s.request.id),{error:i})})}),k(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===kt.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)}}),k(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=kt.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),k(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(n=>n.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:Ct("wc_sessionPropose",Re(oe({},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})}),k(this,"isValidConnect",async r=>{if(!Xe(r)){const{message:u}=M("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=r;if(_e(i)||await this.isValidPairingTopic(i),!fS(c,!0)){const{message:u}=M("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(n&&!_e(n)&&Ht(n)!==0){const u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(n,"requiredNamespaces")}if(s&&!_e(s)&&Ht(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!_e(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!_e(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(n||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),k(this,"validateNamespaces",(r,i)=>{const n=hS(r,"connect()",i);if(n)throw new Error(n.message)}),k(this,"isValidApprove",async r=>{if(!Xe(r))throw new Error(M("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:n,relayProtocol:s,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),u=Xo(n,"approve()");if(u)throw new Error(u.message);const l=mh(c.requiredNamespaces,n,"approve()");if(l)throw new Error(l.message);if(!be(s,!0)){const{message:h}=M("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(o&&!_e(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!_e(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(n));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(", ")}`)}}),k(this,"isValidReject",async r=>{if(!Xe(r)){const{message:s}=M("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:i,reason:n}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!pS(n)){const{message:s}=M("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}}),k(this,"isValidSessionSettleRequest",r=>{if(!Xe(r)){const{message:u}=M("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}const{relay:i,controller:n,namespaces:s,expiry:o}=r;if(!Rg(i)){const{message:u}=M("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=sS(n,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Xo(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(qt(o)){const{message:u}=M("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),k(this,"isValidUpdate",async r=>{if(!Xe(r)){const{message:c}=M("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:i,namespaces:n}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),o=Xo(n,"update()");if(o)throw new Error(o.message);const a=mh(s.requiredNamespaces,n,"update()");if(a)throw new Error(a.message)}),k(this,"isValidExtend",async r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(n)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),k(this,"isValidRequest",async r=>{if(!Xe(r)){const{message:c}=M("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:i,request:n,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!wh(a,s)){const{message:c}=M("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!gS(n)){const{message:c}=M("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(c)}if(!mS(a,s,n.method)){const{message:c}=M("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),k(this,"isValidRespond",async r=>{var i;if(!Xe(r)){const{message:a}=M("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}const{topic:n,response:s}=r;try{await this.isValidSessionTopic(n)}catch(a){throw(i=r==null?void 0:r.response)!=null&&i.id&&this.cleanupAfterResponse(r),a}if(!yS(s)){const{message:a}=M("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}const o=this.client.pendingRequest.get(s.id);if(o.topic!==n){const{message:a}=M("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${o.topic}, received topic: ${n}`);throw new Error(a)}}),k(this,"isValidPing",async r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),k(this,"isValidEmit",async r=>{if(!Xe(r)){const{message:a}=M("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:i,event:n,chainId:s}=r;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!wh(o,s)){const{message:a}=M("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!wS(n)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}if(!bS(o,s,n.name)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}}),k(this,"isValidDisconnect",async r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),k(this,"isValidAuthenticate",r=>{const{chains:i,uri:n,domain:s,nonce:o}=r;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!be(n,!1))throw new Error("uri is required parameter");if(!be(s,!1))throw new Error("domain is required parameter");if(!be(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.")}),k(this,"getVerifyContext",async r=>{const{attestationId:i,hash:n,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||gn,validation:"UNKNOWN",origin:o.url||""}};try{if(a===he.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:i,hash:n,encryptedId:s,verifyUrl:o.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),k(this,"validateSessionProps",(r,i)=>{Object.values(r).forEach((n,s)=>{if(n==null){const{message:o}=M("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${n} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),k(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),k(this,"addToRecentlyDeleted",(r,i)=>{if(this.recentlyDeletedMap.set(r,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let n=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(n++>=s)break;this.recentlyDeletedMap.delete(o)}}}),k(this,"checkRecentlyDeleted",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:n}=M("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(n)}}),k(this,"isLinkModeEnabled",(r,i)=>{var n,s,o,a,c,u,l,h,f;return!r||i!==he.link_mode?!1:((s=(n=this.client.metadata)==null?void 0:n.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((l=r==null?void 0:r.redirect)==null?void 0:l.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(Y==null?void 0:Y.Linking)<"u"}),k(this,"getAppLinkIfEnabled",(r,i)=>{var n;return this.isLinkModeEnabled(r,i)?(n=r==null?void 0:r.redirect)==null?void 0:n.universal:void 0}),k(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Al(r,"topic")||"",n=decodeURIComponent(Al(r,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:he.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})}),k(this,"registerLinkModeListeners",async()=>{var r;if(Lc()||kr()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const i=Y==null?void 0:Y.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await i.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}),k(this,"getTVFApproveParams",r=>{try{const i=Bg(r.namespaces),n=KI(r.namespaces),s=WI(r.namespaces),o=r.sessionProperties,a=r.scopedProperties;return{approvedChains:i,approvedMethods:n,approvedEvents:s,sessionProperties:o,scopedProperties:a}}catch(i){return this.client.logger.warn(i,"Error getting TVF approve params"),{}}}),k(this,"getTVFParams",(r,i,n)=>{var s,o,a;if(!((s=i.request)!=null&&s.method))return{};const c={correlationId:r,rpcMethods:[i.request.method],chainId:i.chainId};try{const u=this.extractTxHashesFromResult(i.request,n);c.txHashes=u,c.contractAddresses=this.isValidContractData(i.request.params)?[(a=(o=i.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(u){this.client.logger.warn(u,"Error getting TVF params")}return c}),k(this,"isValidContractData",r=>{var i;if(!r)return!1;try{const n=(r==null?void 0:r.data)||((i=r==null?void 0:r[0])==null?void 0:i.data);if(!n.startsWith("0x"))return!1;const s=n.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),k(this,"extractTxHashesFromResult",(r,i)=>{var n;try{if(!i)return[];const s=r.method,o=yA[s];if(s==="sui_signTransaction")return[Rx(i.transactionBytes)];if(s==="near_signTransaction")return[Ul(i)];if(s==="near_signTransactions")return i.map(c=>Ul(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(n=i.tx_json)==null?void 0:n.hash];if(s==="polkadot_signTransaction")return[US({transaction:r.params.transactionPayload,signature:i.signature})];if(s==="algo_signTxn")return _t(i)?i.map(c=>kl(c)):[kl(i)];if(s==="cosmos_signDirect")return[Nx(i)];if(s==="wallet_sendCalls")return Ux(i);if(typeof i=="string")return[i];const a=i[o.key];if(_t(a))return s==="solana_signAllTransactions"?a.map(c=>Tx(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn(s,"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,n]of Object.entries(r))for(const s of n)try{await this.onProviderMessageEvent({topic:i,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${s}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(me.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:i,attestation:n,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(ws)?this.client.auth.authKeys.get(ws):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,i,{receiverPublicKey:o,encoding:s===he.link_mode?Br:tt});Qc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:n,transportType:s,encryptedId:bt(i)})):co(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s})),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(wt.expired,async e=>{const{topic:r,id:i}=Tp(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,M("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,M("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(Yr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Yr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!be(e,!1)){const{message:r}=M("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}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=M("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!be(e,!1)){const{message:r}=M("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}=M("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=M("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=M("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(be(e,!1)){const{message:r}=M("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=M("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!dS(e)){const{message:r}=M("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=M("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=M("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}validateRequestExpiry(e){if(e&&!xS(e,aa)){const{message:r}=M("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${aa.min} and ${aa.max}`);throw new Error(r)}}}class PA extends di{constructor(e,r){super(e,r,dA,tu),this.core=e,this.logger=r}}let CA=class extends di{constructor(e,r){super(e,r,pA,tu),this.core=e,this.logger=r}};class BA extends di{constructor(e,r){super(e,r,wA,tu,i=>i.id),this.core=e,this.logger=r}}class TA extends di{constructor(e,r){super(e,r,EA,lo,()=>ws),this.core=e,this.logger=r}}class RA extends di{constructor(e,r){super(e,r,xA,lo),this.core=e,this.logger=r}}class FA extends di{constructor(e,r){super(e,r,_A,lo,i=>i.id),this.core=e,this.logger=r}}var NA=Object.defineProperty,UA=(t,e,r)=>e in t?NA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ca=(t,e,r)=>UA(t,typeof e!="symbol"?e+"":e,r);class kA{constructor(e,r){this.core=e,this.logger=r,ca(this,"authKeys"),ca(this,"pairingTopics"),ca(this,"requests"),this.authKeys=new TA(this.core,this.logger),this.pairingTopics=new RA(this.core,this.logger),this.requests=new FA(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var jA=Object.defineProperty,LA=(t,e,r)=>e in t?jA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,te=(t,e,r)=>LA(t,typeof e!="symbol"?e+"":e,r);class ru extends k8{constructor(e){super(e),te(this,"protocol",a0),te(this,"version",c0),te(this,"name",oa.name),te(this,"metadata"),te(this,"core"),te(this,"logger"),te(this,"events",new St.EventEmitter),te(this,"engine"),te(this,"session"),te(this,"proposal"),te(this,"pendingRequest"),te(this,"auth"),te(this,"signConfig"),te(this,"on",(i,n)=>this.events.on(i,n)),te(this,"once",(i,n)=>this.events.once(i,n)),te(this,"off",(i,n)=>this.events.off(i,n)),te(this,"removeListener",(i,n)=>this.events.removeListener(i,n)),te(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),te(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"update",async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"request",async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"find",i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),te(this,"authenticate",async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}}),te(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),this.name=(e==null?void 0:e.name)||oa.name,this.metadata=$3(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const r=Jc({logger:(e==null?void 0:e.logger)||oa.logger,name:this.name});this.logger=r,this.core=(e==null?void 0:e.core)||new fA(e),this.session=new CA(this.core,this.logger),this.proposal=new PA(this.core,this.logger),this.pendingRequest=new BA(this.core,this.logger),this.engine=new AA(this),this.auth=new kA(this.core,this.logger)}static async init(e){const r=new ru(e);return await r.initialize(),r}get context(){return st(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 MA=ru;var qA=Object.defineProperty,zA=Object.defineProperties,VA=Object.getOwnPropertyDescriptors,lf=Object.getOwnPropertySymbols,HA=Object.prototype.hasOwnProperty,KA=Object.prototype.propertyIsEnumerable,hf=(t,e,r)=>e in t?qA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ff=(t,e)=>{for(var r in e||(e={}))HA.call(e,r)&&hf(t,r,e[r]);if(lf)for(var r of lf(e))KA.call(e,r)&&hf(t,r,e[r]);return t},df=(t,e)=>zA(t,VA(e));const WA={Accept:"application/json","Content-Type":"application/json"},GA="POST",pf={headers:WA,method:GA},gf=10;let l0=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new St.EventEmitter,this.isAvailable=!1,this.registering=!1,!Ch(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=lr(e),i=await(await pu(this.url,df(ff({},pf),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!Ch(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return n(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=lr({id:1,jsonrpc:"2.0",method:"test",params:[]});await pu(e,df(ff({},pf),{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"?si(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=ao(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return jg(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>gf&&this.events.setMaxListeners(gf)}};function iu(t){return t==null||typeof t!="object"&&typeof t!="function"}function h0(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function f0(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const YA="[object RegExp]",d0="[object String]",p0="[object Number]",g0="[object Boolean]",y0="[object Arguments]",ZA="[object Symbol]",JA="[object Date]",XA="[object Map]",QA="[object Set]",e4="[object Array]",t4="[object ArrayBuffer]",r4="[object Object]",i4="[object DataView]",n4="[object Uint8Array]",s4="[object Uint8ClampedArray]",o4="[object Uint16Array]",a4="[object Uint32Array]",c4="[object Int8Array]",u4="[object Int16Array]",l4="[object Int32Array]",h4="[object Float32Array]",f4="[object Float64Array]";function nu(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function d4(t,e){return Di(t,void 0,t,new Map,e)}function Di(t,e,r,i=new Map,n=void 0){const s=n==null?void 0:n(t,e,r,i);if(s!=null)return s;if(iu(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]=Di(t[a],a,r,i,n);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;i.set(t,o);for(const[a,c]of t)o.set(a,Di(c,a,r,i,n));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(Di(a,void 0,r,i,n));return o}if(typeof re<"u"&&re.isBuffer(t))return t.subarray();if(nu(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Di(t[a],a,r,i,n);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return i.set(t,o),Zr(o,t,r,i,n),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),Zr(o,t,r,i,n),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),Zr(o,t,r,i,n),o}if(t instanceof Error){const o=new t.constructor;return i.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Zr(o,t,r,i,n),o}if(typeof t=="object"&&p4(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),Zr(o,t,r,i,n),o}return t}function Zr(t,e,r=t,i,n){const s=[...Object.keys(e),...h0(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Di(e[a],a,r,i,n))}}function p4(t){switch(f0(t)){case y0:case e4:case t4:case i4:case g0:case JA:case h4:case f4:case c4:case u4:case l4:case XA:case p0:case r4:case YA:case QA:case d0:case ZA:case n4:case s4:case o4:case a4:return!0;default:return!1}}function g4(t,e){return d4(t,(r,i,n,s)=>{const o=e==null?void 0:e(r,i,n,s);if(o!=null)return o;if(typeof t=="object")switch(Object.prototype.toString.call(t)){case p0:case d0:case g0:{const a=new t.constructor(t==null?void 0:t.valueOf());return Zr(a,t),a}case y0:{const a={};return Zr(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function yf(t){return g4(t)}function wf(t){return t!==null&&typeof t=="object"&&f0(t)==="[object Arguments]"}function mf(t){return typeof t=="object"&&t!==null}function y4(){}function w4(t){return nu(t)}function m4(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 b4(t){if(iu(t))return t;if(Array.isArray(t)||nu(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 v4(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let n=t;for(let s=0;s<r.length;s++){const o=r[s];n=lc(n,o,i,new Map)}return n}function lc(t,e,r,i){if(iu(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return b4(i.get(e));if(i.set(e,t),Array.isArray(e)){e=e.slice();for(let s=0;s<e.length;s++)e[s]=e[s]??void 0}const n=[...Object.keys(e),...h0(e)];for(let s=0;s<n.length;s++){const o=n[s];let a=e[o],c=t[o];if(wf(a)&&(a={...a}),wf(c)&&(c={...c}),typeof re<"u"&&re.isBuffer(a)&&(a=yf(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],h=Reflect.ownKeys(c);for(let f=0;f<h.length;f++){const d=h[f];l[d]=c[d]}c=l}else c=[];const u=r(c,a,o,t,e,i);u!=null?t[o]=u:Array.isArray(a)||mf(c)&&mf(a)?t[o]=lc(c,a,r,i):c==null&&m4(a)?t[o]=lc({},a,r,i):c==null&&w4(a)?t[o]=yf(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function E4(t,...e){return v4(t,...e,y4)}const bf="error",x4="wss://relay.walletconnect.org",_4="wc",w0="universal_provider",ss=`${_4}@2:${w0}:`,m0="https://rpc.walletconnect.org/v1/",b0="generic",I4=`${m0}bundler`,Ti="call_status",S4=86400,su={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var $4=Object.defineProperty,O4=Object.defineProperties,D4=Object.getOwnPropertyDescriptors,vf=Object.getOwnPropertySymbols,A4=Object.prototype.hasOwnProperty,P4=Object.prototype.propertyIsEnumerable,Ef=(t,e,r)=>e in t?$4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,os=(t,e)=>{for(var r in e||(e={}))A4.call(e,r)&&Ef(t,r,e[r]);if(vf)for(var r of vf(e))P4.call(e,r)&&Ef(t,r,e[r]);return t},C4=(t,e)=>O4(t,D4(e));function v0(t,e,r){var i;const n=cr(t);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${m0}?chainId=${n.namespace}:${n.reference}&projectId=${r}`}function B4(t){return t.includes(":")?t.split(":")[1]:t}function E0(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function T4(t,e){const r=Object.keys(e.namespaces).filter(n=>n.includes(t));if(!r.length)return[];const i=[];return r.forEach(n=>{const s=e.namespaces[n].accounts;i.push(...s)}),i}function xf(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>{var i,n;return((i=r==null?void 0:r.chains)==null?void 0:i.length)&&((n=r==null?void 0:r.chains)==null?void 0:n.length)>0}))}function as(t={},e={}){const r=xf(_f(t)),i=xf(_f(e));return E4(r,i)}function _f(t){var e,r,i,n,s;const o={};if(!Ht(t))return o;for(const[a,c]of Object.entries(t)){const u=oo(a)?[a]:c.chains,l=c.methods||[],h=c.events||[],f=c.rpcMap||{},d=Oi(a);o[d]=C4(os(os({},o[d]),c),{chains:Vt(u,(e=o[d])==null?void 0:e.chains),methods:Vt(l,(r=o[d])==null?void 0:r.methods),events:Vt(h,(i=o[d])==null?void 0:i.events)}),(Ht(f)||Ht(((n=o[d])==null?void 0:n.rpcMap)||{}))&&(o[d].rpcMap=os(os({},f),(s=o[d])==null?void 0:s.rpcMap))}return o}function If(t){return t.includes(":")?t.split(":")[2]:t}function Sf(t){const e={};for(const[r,i]of Object.entries(t)){const n=i.methods||[],s=i.events||[],o=i.accounts||[],a=oo(r)?[r]:i.chains?i.chains:E0(i.accounts);e[r]={chains:a,methods:n,events:s,accounts:o}}return e}function ua(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 R4(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const x0={},Ri=t=>x0[t],la=(t,e)=>{x0[t]=e};var F4=Object.defineProperty,$f=Object.getOwnPropertySymbols,N4=Object.prototype.hasOwnProperty,U4=Object.prototype.propertyIsEnumerable,Of=(t,e,r)=>e in t?F4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Df=(t,e)=>{for(var r in e||(e={}))N4.call(e,r)&&Of(t,r,e[r]);if($f)for(var r of $f(e))U4.call(e,r)&&Of(t,r,e[r]);return t};const Af="eip155",k4=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],j4=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,ha=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,Pf=t=>Object.keys(t).filter(e=>k4.includes(e)).reduce((e,r)=>(e[r]=L4(t[r]),e),{}),L4=t=>typeof t=="string"&&R4(t)?JSON.parse(t):t,M4=(t,e,r)=>{const{sessionProperties:i={},scopedProperties:n={}}=t,s={};if(!Ht(n)&&!Ht(i))return;const o=Pf(i);for(const a of r){const c=j4(a);if(!c)continue;s[ha(c)]=o;const u=n==null?void 0:n[`${Af}:${c}`];if(u){const l=u==null?void 0:u[`${Af}:${c}:${e}`];s[ha(c)]=Df(Df({},s[ha(c)]),Pf(l||u))}}for(const[a,c]of Object.entries(s))Object.keys(c).length===0&&delete s[a];return Object.keys(s).length>0?s:void 0};var q4=Object.defineProperty,z4=(t,e,r)=>e in t?q4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,V4=(t,e,r)=>z4(t,typeof e!="symbol"?e+"":e,r);let fa,H4=class _0{constructor(e){V4(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 fa||(fa=new _0(e)),fa}};var K4=Object.defineProperty,W4=Object.defineProperties,G4=Object.getOwnPropertyDescriptors,Cf=Object.getOwnPropertySymbols,Y4=Object.prototype.hasOwnProperty,Z4=Object.prototype.propertyIsEnumerable,Bf=(t,e,r)=>e in t?K4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,J4=(t,e)=>{for(var r in e||(e={}))Y4.call(e,r)&&Bf(t,r,e[r]);if(Cf)for(var r of Cf(e))Z4.call(e,r)&&Bf(t,r,e[r]);return t},X4=(t,e)=>W4(t,G4(e));async function Q4(t,e){const r=cr(t.result.capabilities.caip345.caip2),i=t.result.capabilities.caip345.transactionHashes,n=await Promise.allSettled(i.map(h=>eP(r.reference,h,e))),s=n.filter(h=>h.status==="fulfilled").map(h=>h.value).filter(h=>h);n.filter(h=>h.status==="rejected").forEach(h=>console.warn("Failed to fetch transaction receipt:",h.reason));const o=!s.length||s.some(h=>!h),a=s.every(h=>(h==null?void 0:h.status)==="0x1"),c=s.every(h=>(h==null?void 0:h.status)==="0x0"),u=s.some(h=>(h==null?void 0:h.status)==="0x0");let l;return o?l=100:a?l=200:c?l=500:u&&(l=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:s,status:l}}async function eP(t,e,r){return await r(parseInt(t)).request(Ct("eth_getTransactionReceipt",[e]))}async function tP({sendCalls:t,storage:e}){const r=await e.getItem(Ti);await e.setItem(Ti,X4(J4({},r),{[t.result.id]:{request:t.request,result:t.result,expiry:we(S4)}}))}async function rP({resultId:t,storage:e}){const r=await e.getItem(Ti);if(r){delete r[t],await e.setItem(Ti,r);for(const i in r)qt(r[i].expiry)&&delete r[i];await e.setItem(Ti,r)}}async function iP({resultId:t,storage:e}){const r=await e.getItem(Ti),i=r==null?void 0:r[t];if(i&&!qt(i.expiry))return i;await rP({resultId:t,storage:e})}var nP=Object.defineProperty,sP=Object.defineProperties,oP=Object.getOwnPropertyDescriptors,Tf=Object.getOwnPropertySymbols,aP=Object.prototype.hasOwnProperty,cP=Object.prototype.propertyIsEnumerable,hc=(t,e,r)=>e in t?nP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,da=(t,e)=>{for(var r in e||(e={}))aP.call(e,r)&&hc(t,r,e[r]);if(Tf)for(var r of Tf(e))cP.call(e,r)&&hc(t,r,e[r]);return t},pa=(t,e)=>sP(t,oP(e)),Hr=(t,e,r)=>hc(t,typeof e!="symbol"?e+"":e,r);class uP{constructor(e){Hr(this,"name","eip155"),Hr(this,"client"),Hr(this,"chainId"),Hr(this,"namespace"),Hr(this,"httpProviders"),Hr(this,"events"),Hr(this,"storage"),this.namespace=e.namespace,this.events=Ri("events"),this.client=Ri("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=H4.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(su.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||v0(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new eu(new l0(i,Ri("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=parseInt(B4(r));e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(e){const r=e||this.chainId;return this.httpProviders[r]||(this.httpProviders=pa(da({},this.httpProviders),{[r]:this.createHttpProvider(r)}),this.httpProviders[r])}async handleSwitchChain(e){var r,i;let n=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";n=n.startsWith("0x")?n:`0x${n}`;const s=parseInt(n,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:n}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var r,i,n,s,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0],c=((s=(n=e.request)==null?void 0:n.params)==null?void 0:s[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const u=this.client.session.get(e.topic),l=((o=u==null?void 0:u.sessionProperties)==null?void 0:o.capabilities)||{},h=`${a}${c.join(",")}`,f=l==null?void 0:l[h];if(f)return f;let d;try{d=M4(u,a,c)}catch(g){console.warn("Failed to extract capabilities from session",g)}if(d)return d;const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:pa(da({},u.sessionProperties||{}),{capabilities:pa(da({},l||{}),{[h]:p})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return p}async getCallStatus(e){var r,i,n;const s=this.client.session.get(e.topic),o=(r=s.sessionProperties)==null?void 0:r.bundler_name;if(o){const u=this.getBundlerUrl(e.chainId,o);try{return await this.getUserOperationReceipt(u,e)}catch(l){console.warn("Failed to fetch call status from bundler",l,u)}}const a=(i=s.sessionProperties)==null?void 0:i.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(u){console.warn("Failed to fetch call status from custom bundler",u,a)}const c=await iP({resultId:(n=e.request.params)==null?void 0:n[0],storage:this.storage});if(c)try{return await Q4(c,this.getHttpProvider.bind(this))}catch(u){console.warn("Failed to fetch call status from stored send calls",u,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 n=new URL(e),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ct("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,r){return`${I4}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}async sendCalls(e){var r,i,n;const s=await this.client.request(e),o=(r=e.request.params)==null?void 0:r[0],a=s==null?void 0:s.id,c=(s==null?void 0:s.capabilities)||{},u=(i=c==null?void 0:c.caip345)==null?void 0:i.caip2,l=(n=c==null?void 0:c.caip345)==null?void 0:n.transactionHashes;return!a||!u||!(l!=null&&l.length)||await tP({sendCalls:{request:o,result:s},storage:this.storage}),s}}var lP=Object.defineProperty,hP=(t,e,r)=>e in t?lP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_i=(t,e,r)=>hP(t,typeof e!="symbol"?e+"":e,r);class fP{constructor(e){_i(this,"name",b0),_i(this,"client"),_i(this,"httpProviders"),_i(this,"events"),_i(this,"namespace"),_i(this,"chainId"),this.namespace=e.namespace,this.events=Ri("events"),this.client=Ri("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(su.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(n=>{var s,o;const a=cr(n),c=(o=(s=this.namespace)==null?void 0:s.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];i[a.reference]=this.createHttpProvider(n,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||v0(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new eu(new l0(i,Ri("disableProviderPing")))}}var dP=Object.defineProperty,pP=Object.defineProperties,gP=Object.getOwnPropertyDescriptors,Rf=Object.getOwnPropertySymbols,yP=Object.prototype.hasOwnProperty,wP=Object.prototype.propertyIsEnumerable,fc=(t,e,r)=>e in t?dP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sn=(t,e)=>{for(var r in e||(e={}))yP.call(e,r)&&fc(t,r,e[r]);if(Rf)for(var r of Rf(e))wP.call(e,r)&&fc(t,r,e[r]);return t},cs=(t,e)=>pP(t,gP(e)),at=(t,e,r)=>fc(t,typeof e!="symbol"?e+"":e,r);class ou{constructor(e){at(this,"client"),at(this,"namespaces"),at(this,"optionalNamespaces"),at(this,"sessionProperties"),at(this,"scopedProperties"),at(this,"events",new pc),at(this,"rpcProviders",{}),at(this,"session"),at(this,"providerOpts"),at(this,"logger"),at(this,"uri"),at(this,"disableProviderPing",!1),at(this,"connectParams");var r,i;this.providerOpts=e,this.logger=Jc({logger:(r=e.logger)!=null?r:bf,name:(i=this.providerOpts.name)!=null?i:w0}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const r=new ou(e);return await r.initialize(),r}async request(e,r,i){const[n,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:sn({},e),chainId:`${n}:${s}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,n){const s=new Date().getTime();this.request(e,i,n).then(o=>r(null,$n(s,o))).catch(o=>r(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:fe("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:n}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const s=await n();if(this.session=s.session,this.session){const o=Sf(this.session.namespaces);this.namespaces=as(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){var r,i;const{uri:n,approval:s}=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});n&&(this.uri=n,this.events.emit("display_uri",n));const o=await s();this.session=o;const a=Sf(o.namespaces);return this.namespaces=as(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,n]=this.validateChain(e);this.getProvider(i).setDefaultChain(n,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(!_t(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 MA.init({core:this.providerOpts.core,logger:this.providerOpts.logger||bf,relayUrl:this.providerOpts.relayUrl||x4,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=>Oi(r)))];la("client",this.client),la("events",this.events),la("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=T4(r,this.session);if((i==null?void 0:i.length)===0)return;const n=E0(i),s=as(this.namespaces,this.optionalNamespaces),o=cs(sn({},s[r]),{accounts:i,chains:n});switch(r){case"eip155":this.rpcProviders[r]=new uP({namespace:o});break;default:this.rpcProviders[r]=new fP({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var r;const{topic:i}=e;i===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:i,topic:n}=e;if(n!==((r=this.session)==null?void 0:r.topic))return;const{event:s}=i;if(s.name==="accountsChanged"){const o=s.data;o&&_t(o)&&this.events.emit("accountsChanged",o.map(If))}else if(s.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=Oi(o),u=ua(o)!==ua(a)?`${c}:${ua(a)}`:o;this.onChainChanged({currentCaipChainId:u})}else this.events.emit(s.name,s.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var i,n;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:s}=r,o=(n=this.client)==null?void 0:n.session.get(e);this.session=cs(sn({},o),{namespaces:s}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{var r;e.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",cs(sn({},fe("USER_DISCONNECTED")),{data:e.topic})))}),this.on(su.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(cs(sn({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[b0]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r={},optionalNamespaces:i={},sessionProperties:n,scopedProperties:s}=e;this.optionalNamespaces=as(r,i),this.sessionProperties=n,this.scopedProperties=s}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=>Oi(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const n=Oi(Object.keys(this.namespaces)[0]),s=this.rpcProviders[n].getDefaultChain();return[n,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:r,internal:i=!1}){if(!this.namespaces)return;const[n,s]=this.validateChain(e);s&&(this.updateNamespaceChain(n,s),i?(this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:n,currentCaipChainId:e,previousCaipChainId:r})):this.getProvider(n).setDefaultChain(s),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:r,previousCaipChainId:i}){var n,s;try{if(i===r)return;const o=(s=(n=this.session)==null?void 0:n.namespaces[e])==null?void 0:s.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${r}:`)).map(If);if(!_t(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}`,n={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=n}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.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 n=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${ss}/${e}${n}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${ss}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${ss}/${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(ss)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn(r,"Failed to cleanup storage")}}}const mP=ou,bP="wc",vP="ethereum_provider",EP=`${bP}@2:${vP}:`,xP="https://rpc.walletconnect.org/v1/",ks=["eth_sendTransaction","personal_sign"],I0=["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"],js=["chainChanged","accountsChanged"],S0=["chainChanged","accountsChanged","message","disconnect","connect"],_P=async()=>{const{createAppKit:t}=await F0(()=>import("./core-a0883ed5.js").then(e=>e.ad),["assets/core-a0883ed5.js","assets/index-aa7d7c43.js","assets/index-4bb952a7.css"]);return t};var IP=Object.defineProperty,SP=Object.defineProperties,$P=Object.getOwnPropertyDescriptors,Ff=Object.getOwnPropertySymbols,OP=Object.prototype.hasOwnProperty,DP=Object.prototype.propertyIsEnumerable,dc=(t,e,r)=>e in t?IP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wr=(t,e)=>{for(var r in e||(e={}))OP.call(e,r)&&dc(t,r,e[r]);if(Ff)for(var r of Ff(e))DP.call(e,r)&&dc(t,r,e[r]);return t},on=(t,e)=>SP(t,$P(e)),ct=(t,e,r)=>dc(t,typeof e!="symbol"?e+"":e,r);function Ls(t){return Number(t[0].split(":")[1])}function us(t){return`0x${t.toString(16)}`}function AP(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:n,events:s,optionalEvents:o,rpcMap:a}=t;if(!_t(e))throw new Error("Invalid chains");const c={chains:e,methods:i||ks,events:s||js,rpcMap:Wr({},e.length?{[Ls(e)]:a[Ls(e)]}:{})},u=s==null?void 0:s.filter(d=>!js.includes(d)),l=i==null?void 0:i.filter(d=>!ks.includes(d));if(!r&&!o&&!n&&!(u!=null&&u.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const h=(u==null?void 0:u.length)&&(l==null?void 0:l.length)||!r,f={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(n!=null&&n.length?n:I0))],events:[...new Set(c.events.concat(o!=null&&o.length?o:S0))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?f:void 0}}class ho{constructor(){ct(this,"events",new St.EventEmitter),ct(this,"namespace","eip155"),ct(this,"accounts",[]),ct(this,"signer"),ct(this,"chainId",1),ct(this,"modal"),ct(this,"rpc"),ct(this,"STORAGE_KEY",EP),ct(this,"on",(e,r)=>(this.events.on(e,r),this)),ct(this,"once",(e,r)=>(this.events.once(e,r),this)),ct(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),ct(this,"off",(e,r)=>(this.events.off(e,r),this)),ct(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new ho;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:n}=AP(this.rpc);try{const s=await new Promise(async(a,c)=>{var u,l;this.rpc.showQrModal&&((u=this.modal)==null||u.open(),(l=this.modal)==null||l.subscribeState(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(on(Wr({namespaces:Wr({},i&&{[this.namespace]:i})},n&&{optionalNamespaces:{[this.namespace]:n}}),{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(!s)return;const o=Il(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:us(this.chainId)})}catch(s){throw this.signer.logger.error(s),s}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const n=await new Promise(async(o,a)=>{var c,u;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(u=this.modal)==null||u.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(on(Wr({},e),{chains:this.rpc.chains}),r).then(l=>{o(l)}).catch(l=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),s=n.session;if(s){const o=Il(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:us(this.chainId)})}return n}catch(n){throw this.signer.logger.error(n),n}finally{(i=this.modal)==null||i.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:i}=r;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",us(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",on(Wr({},fe("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",us(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,i,n]=e.split(":");return{chainId:`${r}:${i}`,address:n}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,i;const n=(r=e==null?void 0:e.chains)!=null?r:[],s=(i=e==null?void 0:e.optionalChains)!=null?i:[],o=n.concat(s);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=n.length?(e==null?void 0:e.methods)||ks:[],c=n.length?(e==null?void 0:e.events)||js:[],u=(e==null?void 0:e.optionalMethods)||[],l=(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:n==null?void 0:n.map(d=>this.formatChainId(d)),optionalChains:s.map(d=>this.formatChainId(d)),methods:a,events:c,optionalMethods:u,optionalEvents:l,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:f,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(n=>{i[n]=this.getRpcUrl(n,r)}),i}async initialize(e){var r;if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Ls(this.rpc.chains):Ls(this.rpc.optionalChains),this.signer=await mP.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 n=await _P(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return LP}),o=s(on(Wr({},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=n(on(Wr({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((r=this.rpc.qrModalOptions)==null?void 0:r.enableMobileFullScreen)===!0}))}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(i)try{this.modal=i}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:n}=e;r&&_t(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)})),i&&_t(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(s=>this.formatChainId(s)),i.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${xP}?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 PP=ho;var CP=Object.defineProperty,BP=Object.defineProperties,TP=Object.getOwnPropertyDescriptors,Nf=Object.getOwnPropertySymbols,RP=Object.prototype.hasOwnProperty,FP=Object.prototype.propertyIsEnumerable,Uf=(t,e,r)=>e in t?CP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$0=(t,e)=>{for(var r in e||(e={}))RP.call(e,r)&&Uf(t,r,e[r]);if(Nf)for(var r of Nf(e))FP.call(e,r)&&Uf(t,r,e[r]);return t},NP=(t,e)=>BP(t,TP(e));function UP(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 kP=t=>{const[e,r]=t.split(":");return O0({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function jP(t){var e,r,i,n,s,o,a;const c=(e=t.chains)==null?void 0:e.map(kP).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const u=c.find(h=>{var f;return h.id===((f=t.defaultChain)==null?void 0:f.id)}),l={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:UP(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:u,metadata:NP($0({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((i=t.metadata)==null?void 0:i.description)||"Connect to WalletConnect-compatible wallets",url:((n=t.metadata)==null?void 0:n.url)||"https://walletconnect.org",icons:((s=t.metadata)==null?void 0:s.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:t.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(t.explorerRecommendedWalletIds)?t.explorerRecommendedWalletIds:[],excludeWalletIds:t.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(t.explorerExcludedWalletIds)?t.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=t.mobileWallets)!=null&&o.length||(a=t.desktopWallets)!=null&&a.length){const h=[...(t.mobileWallets||[]).map(p=>({id:p.id,name:p.name,links:p.links})),...(t.desktopWallets||[]).map(p=>({id:p.id,name:p.name,links:{native:p.links.native,universal:p.links.universal}}))],f=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],d=h.filter(p=>!f.includes(p.id));d.length&&(l.customWallets=d)}return l}function O0(t){return $0({formatters:void 0,fees:void 0,serializers:void 0},t)}var LP=Object.freeze({__proto__:null,convertWCMToAppKitOptions:jP,defineChain:O0});const P5=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:PP,OPTIONAL_EVENTS:S0,OPTIONAL_METHODS:I0,REQUIRED_EVENTS:js,REQUIRED_METHODS:ks,default:ho},Symbol.toStringTag,{value:"Module"}));export{D$ as A,Qc as B,dE as C,u3 as D,co as E,$n as F,hi as G,Ct as H,li as I,y2 as J,Rr as K,ao as L,Mt as M,vt as N,Lt as O,pl as P,sp as Q,l0 as R,P5 as S,dt as X,Dp as Y,n8 as a,s8 as b,Ng as c,is as d,o8 as e,si as f,Ih as g,qf as h,L as i,Et as j,c8 as k,ii as l,gc as m,An as n,_1 as o,p1 as p,SE as q,V0 as r,lr as s,nt as t,Mf as u,fn as v,Ca as w,st as x,jS as y,eu as z};
39
+ ***************************************************************************** */var Za=function(t,e){return Za=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var n in i)i.hasOwnProperty(n)&&(r[n]=i[n])},Za(t,e)};function W8(t,e){Za(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Ja=function(){return Ja=Object.assign||function(e){for(var r,i=1,n=arguments.length;i<n;i++){r=arguments[i];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},Ja.apply(this,arguments)};function G8(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 n=0,i=Object.getOwnPropertySymbols(t);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(r[i[n]]=t[i[n]]);return r}function Y8(t,e,r,i){var n=arguments.length,s=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(n<3?o(s):n>3?o(e,r,s):o(e,r))||s);return n>3&&s&&Object.defineProperty(e,r,s),s}function Z8(t,e){return function(r,i){e(r,i,t)}}function J8(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function X8(t,e,r,i){function n(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(l){try{u(i.next(l))}catch(h){o(h)}}function c(l){try{u(i.throw(l))}catch(h){o(h)}}function u(l){l.done?s(l.value):n(l.value).then(a,c)}u((i=i.apply(t,e||[])).next())})}function Q8(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,n&&(s=u[0]&2?n.return:u[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,u[1])).done)return s;switch(n=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,n=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],n=0}finally{i=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function e$(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function t$(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Xa(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 Mg(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function r$(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Mg(arguments[e]));return t}function i$(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),n=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,n++)i[n]=s[o];return i}function Sn(t){return this instanceof Sn?(this.v=t,this):new Sn(t)}function n$(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),n,s=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(f){i[f]&&(n[f]=function(d){return new Promise(function(p,g){s.push([f,d,p,g])>1||a(f,d)})})}function a(f,d){try{c(i[f](d))}catch(p){h(s[0][3],p)}}function c(f){f.value instanceof Sn?Promise.resolve(f.value.v).then(u,l):h(s[0][2],f)}function u(f){a("next",f)}function l(f){a("throw",f)}function h(f,d){f(d),s.shift(),s.length&&a(s[0][0],s[0][1])}}function s$(t){var e,r;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,s){e[n]=t[n]?function(o){return(r=!r)?{value:Sn(t[n](o)),done:n==="return"}:s?s(o):o}:s}}function o$(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 Xa=="function"?Xa(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),n(a,c,o.done,o.value)})}}function n(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function a$(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function c$(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 u$(t){return t&&t.__esModule?t:{default:t}}function l$(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function h$(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 f$=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Ja},__asyncDelegator:s$,__asyncGenerator:n$,__asyncValues:o$,__await:Sn,__awaiter:X8,__classPrivateFieldGet:l$,__classPrivateFieldSet:h$,__createBinding:e$,__decorate:Y8,__exportStar:t$,__extends:W8,__generator:Q8,__importDefault:u$,__importStar:c$,__makeTemplateObject:a$,__metadata:J8,__param:Z8,__read:Mg,__rest:G8,__spread:r$,__spreadArrays:i$,__values:Xa},Symbol.toStringTag,{value:"Module"})),d$=kf(f$);var Qt={},Ah;function p$(){if(Ah)return Qt;Ah=1,Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.isBrowserCryptoAvailable=Qt.getSubtleCrypto=Qt.getBrowerCrypto=void 0;function t(){return(pi===null||pi===void 0?void 0:pi.crypto)||(pi===null||pi===void 0?void 0:pi.msCrypto)||{}}Qt.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}Qt.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Qt.isBrowserCryptoAvailable=r,Qt}var er={},Ph;function g$(){if(Ph)return er;Ph=1,Object.defineProperty(er,"__esModule",{value:!0}),er.isBrowser=er.isNode=er.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}er.isReactNative=t;function e(){return typeof xt<"u"&&typeof xt.versions<"u"&&typeof xt.versions.node<"u"}er.isNode=e;function r(){return!t()&&!e()}return er.isBrowser=r,er}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=d$;e.__exportStar(p$(),t),e.__exportStar(g$(),t)})(Lg);function Lt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Rr(t=6){return BigInt(Lt(t))}function Ct(t,e,r){return{id:r||Lt(),jsonrpc:"2.0",method:t,params:e}}function $n(t,e){return{id:t,jsonrpc:"2.0",result:e}}function ao(t,e,r){return{id:t,jsonrpc:"2.0",error:y$(e,r)}}function y$(t,e){return typeof t>"u"?Dh(Ug):(typeof t=="string"&&(t=Object.assign(Object.assign({},Dh(Xc)),{message:t})),typeof e<"u"&&(t.data=e),H8(t.code)&&(t=K8(t.code)),t)}class w${}class m$ extends w${constructor(){super()}}class b$ extends m${constructor(e){super()}}const v$="^https?:",E$="^wss?:";function x$(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function qg(t,e){const r=x$(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Ch(t){return qg(t,v$)}function Bh(t){return qg(t,E$)}function _$(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function zg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Qc(t){return zg(t)&&"method"in t}function co(t){return zg(t)&&(Mt(t)||vt(t))}function Mt(t){return"result"in t}function vt(t){return"error"in t}class eu extends b${constructor(e){super(e),this.events=new St.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(Ct(e.method,e.params||[],e.id||Rr().toString()),r)}async requestStrict(e,r){return new Promise(async(i,n)=>{if(!this.connection.connected)try{await this.open()}catch(s){n(s)}this.events.on(`${e.id}`,s=>{vt(s)?n(s.error):i(s.result)});try{await this.connection.send(e,r)}catch(s){n(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),co(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}var ra,Th;function I$(){return Th||(Th=1,ra=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}),ra}const S$=()=>typeof WebSocket<"u"?WebSocket:typeof Y<"u"&&typeof Y.WebSocket<"u"?Y.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:I$(),$$=()=>typeof WebSocket<"u"||typeof Y<"u"&&typeof Y.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Rh=t=>t.split("?")[0],Fh=10,O$=S$();let D$=class{constructor(e){if(this.url=e,this.events=new St.EventEmitter,this.registering=!1,!Bh(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(lr(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Bh(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,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return n(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,i)=>{const n=Lg.isReactNative()?void 0:{rejectUnauthorized:!_$(e)},s=new O$(e,[],n);$$()?s.onerror=o=>{const a=o;i(this.emitError(a.error))}:s.on("error",o=>{i(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?si(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=ao(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return jg(e,Rh(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Fh&&this.events.setMaxListeners(Fh)}emitError(e){const r=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${Rh(this.url)}`));return this.events.emit("register_error",r),r}};const Vg="wc",Hg=2,Us="core",Kt=`${Vg}@2:${Us}:`,A$={name:Us,logger:"error"},P$={database:":memory:"},C$="crypto",Nh="client_ed25519_seed",B$=L.ONE_DAY,T$="keychain",R$="0.3",F$="messages",N$="0.3",U$=L.SIX_HOURS,k$="publisher",Kg="irn",j$="error",Wg="wss://relay.walletconnect.org",L$="relayer",me={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"},M$="_subscription",gt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},q$=.1,Qa="2.23.0",he={link_mode:"link_mode",relay:"relay"},ys={inbound:"inbound",outbound:"outbound"},z$="0.3",V$="WALLETCONNECT_CLIENT_ID",Uh="WALLETCONNECT_LINK_MODE_APPS",ut={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},H$="subscription",K$="0.3",W$="pairing",G$="0.3",en={wc_pairingDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:L.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:L.ONE_DAY,prompt:!1,tag:0},res:{ttl:L.ONE_DAY,prompt:!1,tag:0}}},Yr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ot={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Y$="history",Z$="0.3",J$="expirer",wt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},X$="0.3",Q$="verify-api",e6="https://verify.walletconnect.com",Gg="https://verify.walletconnect.org",gn=Gg,t6=`${gn}/v3`,r6=[e6,Gg],i6="echo",n6="https://echo.walletconnect.com",jt={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"},rr={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"},Dt={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"},zr={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"},Vr={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},tn={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},s6=.1,o6="event-client",a6=86400,c6="https://pulse.walletconnect.org/batch";function u6(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=n}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,w=0,I=0,C=p.length;I!==C&&p[I]===0;)I++,g++;for(var b=(C-I)*l+1>>>0,v=new Uint8Array(b);I!==C;){for(var D=p[I],P=0,T=b-1;(D!==0||P<w)&&T!==-1;T--,P++)D+=256*v[T]>>>0,v[T]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");w=P,I++}for(var R=b-w;R!==b&&v[R]===0;)R++;for(var A=c.repeat(g);R<b;++R)A+=t.charAt(v[R]);return A}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var w=0,I=0;p[g]===c;)w++,g++;for(var C=(p.length-g)*u+1>>>0,b=new Uint8Array(C);p[g];){var v=r[p.charCodeAt(g)];if(v===255)return;for(var D=0,P=C-1;(v!==0||D<I)&&P!==-1;P--,D++)v+=a*b[P]>>>0,b[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");I=D,g++}if(p[g]!==" "){for(var T=C-I;T!==C&&b[T]===0;)T++;for(var R=new Uint8Array(w+(C-T)),A=w;T!==C;)R[A++]=b[T++];return R}}}function d(p){var g=f(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var l6=u6,h6=l6;const Yg=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")},f6=t=>new TextEncoder().encode(t),d6=t=>new TextDecoder().decode(t);class p6{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 g6{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 Zg(this,e)}}class y6{constructor(e){this.decoders=e}or(e){return Zg(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 Zg=(t,e)=>new y6({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class w6{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new p6(e,r,i),this.decoder=new g6(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const uo=({name:t,prefix:e,encode:r,decode:i})=>new w6(t,e,r,i),kn=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=h6(r,e);return uo({prefix:t,name:e,encode:i,decode:s=>Yg(n(s))})},m6=(t,e,r,i)=>{const n={};for(let l=0;l<e.length;++l)n[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=n[t[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},b6=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[n&a>>o];if(o&&(s+=e[n&a<<r-o]),i)for(;s.length*r&7;)s+="=";return s},Ue=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>uo({prefix:e,name:t,encode(n){return b6(n,i,r)},decode(n){return m6(n,i,r,t)}}),v6=uo({prefix:"\0",name:"identity",encode:t=>d6(t),decode:t=>f6(t)});var E6=Object.freeze({__proto__:null,identity:v6});const x6=Ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var _6=Object.freeze({__proto__:null,base2:x6});const I6=Ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var S6=Object.freeze({__proto__:null,base8:I6});const $6=kn({prefix:"9",name:"base10",alphabet:"0123456789"});var O6=Object.freeze({__proto__:null,base10:$6});const D6=Ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),A6=Ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var P6=Object.freeze({__proto__:null,base16:D6,base16upper:A6});const C6=Ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),B6=Ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),T6=Ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),R6=Ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),F6=Ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),N6=Ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),U6=Ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),k6=Ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),j6=Ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var L6=Object.freeze({__proto__:null,base32:C6,base32upper:B6,base32pad:T6,base32padupper:R6,base32hex:F6,base32hexupper:N6,base32hexpad:U6,base32hexpadupper:k6,base32z:j6});const M6=kn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),q6=kn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var z6=Object.freeze({__proto__:null,base36:M6,base36upper:q6});const V6=kn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),H6=kn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var K6=Object.freeze({__proto__:null,base58btc:V6,base58flickr:H6});const W6=Ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),G6=Ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Y6=Ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Z6=Ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var J6=Object.freeze({__proto__:null,base64:W6,base64pad:G6,base64url:Y6,base64urlpad:Z6});const Jg=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),X6=Jg.reduce((t,e,r)=>(t[r]=e,t),[]),Q6=Jg.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function eO(t){return t.reduce((e,r)=>(e+=X6[r],e),"")}function tO(t){const e=[];for(const r of t){const i=Q6[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const rO=uo({prefix:"🚀",name:"base256emoji",encode:eO,decode:tO});var iO=Object.freeze({__proto__:null,base256emoji:rO}),nO=Xg,kh=128,sO=127,oO=~sO,aO=Math.pow(2,31);function Xg(t,e,r){e=e||[],r=r||0;for(var i=r;t>=aO;)e[r++]=t&255|kh,t/=128;for(;t&oO;)e[r++]=t&255|kh,t>>>=7;return e[r]=t|0,Xg.bytes=r-i+1,e}var cO=ec,uO=128,jh=127;function ec(t,i){var r=0,i=i||0,n=0,s=i,o,a=t.length;do{if(s>=a)throw ec.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=n<28?(o&jh)<<n:(o&jh)*Math.pow(2,n),n+=7}while(o>=uO);return ec.bytes=s-i,r}var lO=Math.pow(2,7),hO=Math.pow(2,14),fO=Math.pow(2,21),dO=Math.pow(2,28),pO=Math.pow(2,35),gO=Math.pow(2,42),yO=Math.pow(2,49),wO=Math.pow(2,56),mO=Math.pow(2,63),bO=function(t){return t<lO?1:t<hO?2:t<fO?3:t<dO?4:t<pO?5:t<gO?6:t<yO?7:t<wO?8:t<mO?9:10},vO={encode:nO,decode:cO,encodingLength:bO},Qg=vO;const Lh=(t,e,r=0)=>(Qg.encode(t,e,r),e),Mh=t=>Qg.encodingLength(t),tc=(t,e)=>{const r=e.byteLength,i=Mh(t),n=i+Mh(r),s=new Uint8Array(n+r);return Lh(t,s,0),Lh(r,s,i),s.set(e,n),new EO(t,r,e,s)};class EO{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const e0=({name:t,code:e,encode:r})=>new xO(t,e,r);class xO{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?tc(this.code,r):r.then(i=>tc(this.code,i))}else throw Error("Unknown type, must be binary type")}}const t0=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),_O=e0({name:"sha2-256",code:18,encode:t0("SHA-256")}),IO=e0({name:"sha2-512",code:19,encode:t0("SHA-512")});var SO=Object.freeze({__proto__:null,sha256:_O,sha512:IO});const r0=0,$O="identity",i0=Yg,OO=t=>tc(r0,i0(t)),DO={code:r0,name:$O,encode:i0,digest:OO};var AO=Object.freeze({__proto__:null,identity:DO});new TextEncoder,new TextDecoder;const qh={...E6,..._6,...S6,...O6,...P6,...L6,...z6,...K6,...J6,...iO};({...SO,...AO});function n0(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function PO(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?n0(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function s0(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const zh=s0("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ia=s0("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=PO(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),CO={utf8:zh,"utf-8":zh,hex:qh.base16,latin1:ia,ascii:ia,binary:ia,...qh};function BO(t,e="utf8"){const r=CO[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?n0(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var TO=Object.defineProperty,RO=(t,e,r)=>e in t?TO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ut=(t,e,r)=>RO(t,typeof e!="symbol"?e+"":e,r);class FO{constructor(e,r){this.core=e,this.logger=r,Ut(this,"keychain",new Map),Ut(this,"name",T$),Ut(this,"version",R$),Ut(this,"initialized",!1),Ut(this,"storagePrefix",Kt),Ut(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Ut(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Ut(this,"set",async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()}),Ut(this,"get",i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=M("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n}),Ut(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=dt(r,this.name)}get context(){return st(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Fa(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Na(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var NO=Object.defineProperty,UO=(t,e,r)=>e in t?NO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Se=(t,e,r)=>UO(t,typeof e!="symbol"?e+"":e,r);class kO{constructor(e,r,i){this.core=e,this.logger=r,Se(this,"name",C$),Se(this,"keychain"),Se(this,"randomSessionIdentifier",Wa()),Se(this,"initialized",!1),Se(this,"clientId"),Se(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Se(this,"hasKeys",n=>(this.isInitialized(),this.keychain.has(n))),Se(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const n=await this.getClientSeed(),s=pl(n),o=sp(s.publicKey);return this.clientId=o,o}),Se(this,"generateKeyPair",()=>{this.isInitialized();const n=vI();return this.setPrivateKey(n.publicKey,n.privateKey)}),Se(this,"signJWT",async n=>{this.isInitialized();const s=await this.getClientSeed(),o=pl(s),a=this.randomSessionIdentifier;return await y2(a,n,B$,o)}),Se(this,"generateSharedKey",(n,s,o)=>{this.isInitialized();const a=this.getPrivateKey(n),c=EI(a,s);return this.setSymKey(c,o)}),Se(this,"setSymKey",async(n,s)=>{this.isInitialized();const o=s||ds(n);return await this.keychain.set(o,n),o}),Se(this,"deleteKeyPair",async n=>{this.isInitialized(),await this.keychain.del(n)}),Se(this,"deleteSymKey",async n=>{this.isInitialized(),await this.keychain.del(n)}),Se(this,"encode",async(n,s,o)=>{this.isInitialized();const a=Cg(o),c=lr(s);if(ah(a))return II(c,o==null?void 0:o.encoding);if(oh(a)){const f=a.senderPublicKey,d=a.receiverPublicKey;n=await this.generateSharedKey(f,d)}const u=this.getSymKey(n),{type:l,senderPublicKey:h}=a;return xI({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o==null?void 0:o.encoding})}),Se(this,"decode",async(n,s,o)=>{this.isInitialized();const a=$I(s,o);if(ah(a)){const c=SI(s,o==null?void 0:o.encoding);return si(c)}if(oh(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;n=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(n),u=_I({symKey:c,encoded:s,encoding:o==null?void 0:o.encoding});return si(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Se(this,"getPayloadType",(n,s=tt)=>{const o=In({encoded:n,encoding:s});return ai(o.type)}),Se(this,"getPayloadSenderPublicKey",(n,s=tt)=>{const o=In({encoded:n,encoding:s});return o.senderPublicKey?nt(o.senderPublicKey,Ge):void 0}),this.core=e,this.logger=dt(r,this.name),this.keychain=i||new FO(this.core,this.logger)}get context(){return st(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(Nh)}catch{e=Wa(),await this.keychain.set(Nh,e)}return BO(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var jO=Object.defineProperty,LO=Object.defineProperties,MO=Object.getOwnPropertyDescriptors,Vh=Object.getOwnPropertySymbols,qO=Object.prototype.hasOwnProperty,zO=Object.prototype.propertyIsEnumerable,rc=(t,e,r)=>e in t?jO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,VO=(t,e)=>{for(var r in e||(e={}))qO.call(e,r)&&rc(t,r,e[r]);if(Vh)for(var r of Vh(e))zO.call(e,r)&&rc(t,r,e[r]);return t},HO=(t,e)=>LO(t,MO(e)),ot=(t,e,r)=>rc(t,typeof e!="symbol"?e+"":e,r);class KO extends O8{constructor(e,r){super(e,r),this.logger=e,this.core=r,ot(this,"messages",new Map),ot(this,"messagesWithoutClientAck",new Map),ot(this,"name",F$),ot(this,"version",N$),ot(this,"initialized",!1),ot(this,"storagePrefix",Kt),ot(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const n=await this.getRelayerMessagesWithoutClientAck();typeof n<"u"&&(this.messagesWithoutClientAck=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),ot(this,"set",async(i,n,s)=>{this.isInitialized();const o=bt(n);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=n,this.messages.set(i,a),s===ys.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,HO(VO({},c),{[o]:n}))}return await this.persist(),o}),ot(this,"get",i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n}),ot(this,"getWithoutAck",i=>{this.isInitialized();const n={};for(const s of i){const o=this.messagesWithoutClientAck.get(s)||{};n[s]=Object.values(o)}return n}),ot(this,"has",(i,n)=>{this.isInitialized();const s=this.get(i),o=bt(n);return typeof s[o]<"u"}),ot(this,"ack",async(i,n)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(i);if(typeof s>"u")return;const o=bt(n);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,s),await this.persist()}),ot(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=dt(e,this.name),this.core=r}get context(){return st(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,Fa(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Fa(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Na(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Na(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var WO=Object.defineProperty,GO=Object.defineProperties,YO=Object.getOwnPropertyDescriptors,Hh=Object.getOwnPropertySymbols,ZO=Object.prototype.hasOwnProperty,JO=Object.prototype.propertyIsEnumerable,ic=(t,e,r)=>e in t?WO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vi=(t,e)=>{for(var r in e||(e={}))ZO.call(e,r)&&ic(t,r,e[r]);if(Hh)for(var r of Hh(e))JO.call(e,r)&&ic(t,r,e[r]);return t},Kh=(t,e)=>GO(t,YO(e)),yt=(t,e,r)=>ic(t,typeof e!="symbol"?e+"":e,r);class XO extends D8{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,yt(this,"events",new St.EventEmitter),yt(this,"name",k$),yt(this,"queue",new Map),yt(this,"publishTimeout",L.toMiliseconds(L.ONE_MINUTE)),yt(this,"initialPublishTimeout",L.toMiliseconds(L.ONE_SECOND*15)),yt(this,"needsTransportRestart",!1),yt(this,"publish",async(i,n,s)=>{var o,a,c,u,l;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:s}});const h=(s==null?void 0:s.ttl)||U$,f=(s==null?void 0:s.prompt)||!1,d=(s==null?void 0:s.tag)||0,p=(s==null?void 0:s.id)||Rr().toString(),g=$i(Fs().protocol),w={id:p,method:(s==null?void 0:s.publishMethod)||g.publish,params:vi({topic:i,message:n,ttl:h,prompt:f,tag:d,attestation:s==null?void 0:s.attestation},s==null?void 0:s.tvf)},I=`Failed to publish payload, please try again. id:${p} tag:${d}`;try{_e((o=w.params)==null?void 0:o.prompt)&&((a=w.params)==null||delete a.prompt),_e((c=w.params)==null?void 0:c.tag)&&((u=w.params)==null||delete u.tag);const C=new Promise(async b=>{const v=({id:P})=>{var T;((T=w.id)==null?void 0:T.toString())===P.toString()&&(this.removeRequestFromQueue(P),this.relayer.events.removeListener(me.publish,v),b())};this.relayer.events.on(me.publish,v);const D=zt(new Promise((P,T)=>{this.rpcPublish(w,s).then(P).catch(R=>{this.logger.warn(R,R==null?void 0:R.message),T(R)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${d}`);try{await D,this.events.removeListener(me.publish,v)}catch(P){this.queue.set(p,{request:w,opts:s,attempt:1}),this.logger.warn(P,P==null?void 0:P.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:i,message:n,opts:s}}),await zt(C,this.publishTimeout,I)}catch(C){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(C),(l=s==null?void 0:s.internal)!=null&&l.throwOnFailedPublish)throw C}finally{this.queue.delete(p)}}),yt(this,"publishCustom",async i=>{var n,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:i});const{payload:u,opts:l={}}=i,{attestation:h,tvf:f,publishMethod:d,prompt:p,tag:g,ttl:w=L.FIVE_MINUTES}=l,I=l.id||Rr().toString(),C=$i(Fs().protocol),b=d||C.publish,v={id:I,method:b,params:vi(Kh(vi({},u),{ttl:w,prompt:p,tag:g,attestation:h}),f)},D=`Failed to publish custom payload, please try again. id:${I} tag:${g}`;try{_e((n=v.params)==null?void 0:n.prompt)&&((s=v.params)==null||delete s.prompt),_e((o=v.params)==null?void 0:o.tag)&&((a=v.params)==null||delete a.tag);const P=new Promise(async T=>{const R=({id:U})=>{var j;((j=v.id)==null?void 0:j.toString())===U.toString()&&(this.removeRequestFromQueue(U),this.relayer.events.removeListener(me.publish,R),T())};this.relayer.events.on(me.publish,R);const A=zt(new Promise((U,j)=>{this.rpcPublish(v,l).then(U).catch(B=>{this.logger.warn(B,B==null?void 0:B.message),j(B)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${b} id:${I} tag:${g}`);try{await A,this.events.removeListener(me.publish,R)}catch(U){this.queue.set(I,{request:v,opts:l,attempt:1}),this.logger.warn(U,U==null?void 0:U.message)}});this.logger.trace({type:"method",method:"publish",params:{id:I,payload:u,opts:l}}),await zt(P,this.publishTimeout,D)}catch(P){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(P),(c=l==null?void 0:l.internal)!=null&&c.throwOnFailedPublish)throw P}finally{this.queue.delete(I)}}),yt(this,"on",(i,n)=>{this.events.on(i,n)}),yt(this,"once",(i,n)=>{this.events.once(i,n)}),yt(this,"off",(i,n)=>{this.events.off(i,n)}),yt(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.relayer=e,this.logger=dt(r,this.name),this.registerEventListeners()}get context(){return st(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(me.publish,vi(vi({},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 n=e.attempt+1;this.queue.set(r,Kh(vi({},e),{attempt:n})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(i=e.request.params)==null?void 0:i.tag}, attempt: ${n}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(hi.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(me.connection_stalled);return}this.checkQueue()}),this.relayer.on(me.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var QO=Object.defineProperty,eD=(t,e,r)=>e in t?QO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ei=(t,e,r)=>eD(t,typeof e!="symbol"?e+"":e,r);class tD{constructor(){Ei(this,"map",new Map),Ei(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),Ei(this,"get",e=>this.map.get(e)||[]),Ei(this,"exists",(e,r)=>this.get(e).includes(r)),Ei(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,r))return;const n=i.filter(s=>s!==r);if(!n.length){this.map.delete(e);return}this.map.set(e,n)}),Ei(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var rD=Object.defineProperty,iD=Object.defineProperties,nD=Object.getOwnPropertyDescriptors,Wh=Object.getOwnPropertySymbols,sD=Object.prototype.hasOwnProperty,oD=Object.prototype.propertyIsEnumerable,nc=(t,e,r)=>e in t?rD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rn=(t,e)=>{for(var r in e||(e={}))sD.call(e,r)&&nc(t,r,e[r]);if(Wh)for(var r of Wh(e))oD.call(e,r)&&nc(t,r,e[r]);return t},na=(t,e)=>iD(t,nD(e)),ce=(t,e,r)=>nc(t,typeof e!="symbol"?e+"":e,r);class aD extends C8{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ce(this,"subscriptions",new Map),ce(this,"topicMap",new tD),ce(this,"events",new St.EventEmitter),ce(this,"name",H$),ce(this,"version",K$),ce(this,"pending",new Map),ce(this,"cached",[]),ce(this,"initialized",!1),ce(this,"storagePrefix",Kt),ce(this,"subscribeTimeout",L.toMiliseconds(L.ONE_MINUTE)),ce(this,"initialSubscribeTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ce(this,"clientId"),ce(this,"batchSubscribeTopicsLimit",500),ce(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ce(this,"subscribe",async(i,n)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const o=Fs(n),a={topic:i,relay:o,transportType:n==null?void 0:n.transportType};(s=n==null?void 0:n.internal)!=null&&s.skipSubscribe||this.pending.set(i,a);const c=await this.rpcSubscribe(i,o,n);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:n}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ce(this,"unsubscribe",async(i,n)=>{this.isInitialized(),typeof(n==null?void 0:n.id)<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)}),ce(this,"isSubscribed",i=>new Promise(n=>{n(this.topicMap.topics.includes(i))})),ce(this,"isKnownTopic",i=>new Promise(n=>{n(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(s=>s.topic===i))})),ce(this,"on",(i,n)=>{this.events.on(i,n)}),ce(this,"once",(i,n)=>{this.events.once(i,n)}),ce(this,"off",(i,n)=>{this.events.off(i,n)}),ce(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),ce(this,"start",async()=>{await this.onConnect()}),ce(this,"stop",async()=>{await this.onDisconnect()}),ce(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ce(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(n=>{i.push(n)}),await this.batchSubscribe(i)}),ce(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(hi.pulse,async()=>{await this.checkPending()}),this.events.on(ut.created,async i=>{const n=ut.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()}),this.events.on(ut.deleted,async i=>{const n=ut.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()})}),this.relayer=e,this.logger=dt(r,this.name),this.clientId=""}get context(){return st(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const i=this.topicMap.get(e);await Promise.all(i.map(async n=>await this.unsubscribeById(e,n,r)))}async unsubscribeById(e,r,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}});try{const n=Fs(i);await this.restartToComplete({topic:e,id:r,relay:n}),await this.rpcUnsubscribe(e,r,n);const s=fe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,r,i){var n,s;const o=await this.getSubscriptionId(e);if((n=i==null?void 0:i.internal)!=null&&n.skipSubscribe)return o;(!i||(i==null?void 0:i.transportType)===he.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=(s=i==null?void 0:i.internal)==null?void 0:s.throwOnFailedPublish;try{if((i==null?void 0:i.transportType)===he.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(h=>this.logger.warn(h))},L.toMiliseconds(L.ONE_SECOND)),o;const u=new Promise(async h=>{const f=d=>{d.topic===e&&(this.events.removeListener(ut.created,f),h(d.id))};this.events.on(ut.created,f);try{const d=await zt(new Promise((p,g)=>{this.relayer.request(a).catch(w=>{this.logger.warn(w,w==null?void 0:w.message),g(w)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(ut.created,f),h(d)}catch{}}),l=await zt(u,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return l?o:null}catch(u){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(me.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:$i(r.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await zt(new Promise(n=>{this.relayer.request(i).catch(s=>this.logger.warn(s)).then(n)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(me.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:$i(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let n;try{n=await await zt(new Promise((s,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(me.connection_stalled)}return n}rpcUnsubscribe(e,r,i){const n={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:n}),this.relayer.request(n)}onSubscribe(e,r){this.setSubscription(e,na(rn({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,rn({},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,rn({},r)),this.topicMap.set(r.topic,e),this.events.emit(ut.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}=M("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(ut.deleted,na(rn({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(ut.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<r;i++){const n=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}}this.events.emit(ut.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}=M("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=>na(rn({},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 j3(L.toMiliseconds(L.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}=M("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 bt(e+await this.getClientId())}}var cD=Object.defineProperty,Gh=Object.getOwnPropertySymbols,uD=Object.prototype.hasOwnProperty,lD=Object.prototype.propertyIsEnumerable,sc=(t,e,r)=>e in t?cD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yh=(t,e)=>{for(var r in e||(e={}))uD.call(e,r)&&sc(t,r,e[r]);if(Gh)for(var r of Gh(e))lD.call(e,r)&&sc(t,r,e[r]);return t},ne=(t,e,r)=>sc(t,typeof e!="symbol"?e+"":e,r);class hD extends A8{constructor(e){var r;super(e),ne(this,"protocol","wc"),ne(this,"version",2),ne(this,"core"),ne(this,"logger"),ne(this,"events",new St.EventEmitter),ne(this,"provider"),ne(this,"messages"),ne(this,"subscriber"),ne(this,"publisher"),ne(this,"name",L$),ne(this,"transportExplicitlyClosed",!1),ne(this,"initialized",!1),ne(this,"connectionAttemptInProgress",!1),ne(this,"relayUrl"),ne(this,"projectId"),ne(this,"packageName"),ne(this,"bundleId"),ne(this,"hasExperiencedNetworkDisruption",!1),ne(this,"pingTimeout"),ne(this,"heartBeatTimeout",L.toMiliseconds(L.THIRTY_SECONDS+L.FIVE_SECONDS)),ne(this,"reconnectTimeout"),ne(this,"connectPromise"),ne(this,"reconnectInProgress",!1),ne(this,"requestsInFlight",[]),ne(this,"connectTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ne(this,"request",async i=>{var n,s;this.logger.debug("Publishing Request Payload");const o=i.id||Rr().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:i.method,topic:(n=i.params)==null?void 0:n.topic},"relayer.request - publishing...");const a=`${o}:${((s=i.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(i);return this.requestsInFlight=this.requestsInFlight.filter(u=>u!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),ne(this,"resetPingTimeout",()=>{As()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var i,n,s,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(s=(n=(i=this.provider)==null?void 0:i.connection)==null?void 0:n.socket)==null?void 0:s.terminate)==null||o.call(s)}catch(a){this.logger.warn(a,a==null?void 0:a.message)}},this.heartBeatTimeout))}),ne(this,"onPayloadHandler",i=>{this.onProviderPayload(i),this.resetPingTimeout()}),ne(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(me.connect)}),ne(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),ne(this,"onProviderErrorHandler",i=>{this.logger.fatal(`Fatal socket error: ${i.message}`),this.events.emit(me.error,i),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ne(this,"registerProviderListeners",()=>{this.provider.on(gt.payload,this.onPayloadHandler),this.provider.on(gt.connect,this.onConnectHandler),this.provider.on(gt.disconnect,this.onDisconnectHandler),this.provider.on(gt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=Jc({logger:(r=e.logger)!=null?r:j$,name:this.name}),this.messages=new KO(this.logger,e.core),this.subscriber=new aD(this,this.logger),this.publisher=new XO(this,this.logger),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Wg,_3()?this.packageName=Dl():I3()&&(this.bundleId=Dl()),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 st(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:he.relay},ys.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,r){var i,n,s;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:(n=r==null?void 0:r.internal)==null?void 0:n.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(ut.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(ut.created,u)}),new Promise(async(l,h)=>{a=await this.subscriber.subscribe(e,Yh({internal:{throwOnFailedPublish:o}},r)).catch(f=>{o&&h(f)})||a,l()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await zt(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 vh())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,n)=>i.publishedAt-n.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n,"Error while processing batch message event: "+(n==null?void 0:n.message))}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const n=we(L.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,s)}this.events.emit(me.message,e),await this.recordMessageEvent(e,ys.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(i,n)=>{const s=()=>{n(new Error("Connection interrupted while trying to connect"))};this.provider.once(gt.disconnect,s),await zt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{n(o)}).finally(()=>{this.provider.off(gt.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{n(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(gt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(gt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const n=i;this.logger.warn({},n.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(i=>setTimeout(i,L.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,n,s;if(As())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(n=(i=this.provider)==null?void 0:i.connection)==null?void 0:n.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new eu(new D$(A3({sdkVersion:Qa,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,r){const{topic:i,message:n}=e;await this.messages.set(i,n,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const n=this.messages.has(r,i);return n&&this.logger.warn(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Qc(e)){if(!e.method.endsWith(M$))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:o}=r.data,a={topic:i,message:n,publishedAt:s,transportType:he.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Yh({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else co(e)&&this.events.emit(me.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,ys.inbound),this.events.emit(me.message,e))}async acknowledgePayload(e){const r=$n(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(gt.payload,this.onPayloadHandler),this.provider.off(gt.connect,this.onConnectHandler),this.provider.off(gt.disconnect,this.onDisconnectHandler),this.provider.off(gt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await vh();$S(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(hi.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&AS())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(me.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},L.toMiliseconds(q$)))))}isInitialized(){if(!this.initialized){const{message:e}=M("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 fD(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Zh(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Jh(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const dD="[object RegExp]",pD="[object String]",gD="[object Number]",yD="[object Boolean]",Xh="[object Arguments]",wD="[object Symbol]",mD="[object Date]",bD="[object Map]",vD="[object Set]",ED="[object Array]",xD="[object Function]",_D="[object ArrayBuffer]",sa="[object Object]",ID="[object Error]",SD="[object DataView]",$D="[object Uint8Array]",OD="[object Uint8ClampedArray]",DD="[object Uint16Array]",AD="[object Uint32Array]",PD="[object BigUint64Array]",CD="[object Int8Array]",BD="[object Int16Array]",TD="[object Int32Array]",RD="[object BigInt64Array]",FD="[object Float32Array]",ND="[object Float64Array]";function UD(){}function Qh(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 kD(t,e,r){return ln(t,e,void 0,void 0,void 0,void 0,r)}function ln(t,e,r,i,n,s,o){const a=o(t,e,r,i,n,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return yn(t,e,s,o)}return yn(t,e,s,o)}function yn(t,e,r,i){if(Object.is(t,e))return!0;let n=Jh(t),s=Jh(e);if(n===Xh&&(n=sa),s===Xh&&(s=sa),n!==s)return!1;switch(n){case pD:return t.toString()===e.toString();case gD:{const c=t.valueOf(),u=e.valueOf();return fD(c,u)}case yD:case mD:case wD:return Object.is(t.valueOf(),e.valueOf());case dD:return t.source===e.source&&t.flags===e.flags;case xD:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(n){case bD:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!ln(u,e.get(c),c,t,e,r,i))return!1;return!0}case vD:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let l=0;l<c.length;l++){const h=c[l],f=u.findIndex(d=>ln(h,d,void 0,t,e,r,i));if(f===-1)return!1;u.splice(f,1)}return!0}case ED:case $D:case OD:case DD:case AD:case PD:case CD:case BD:case TD:case RD:case FD:case ND:{if(typeof re<"u"&&re.isBuffer(t)!==re.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!ln(t[c],e[c],c,t,e,r,i))return!1;return!0}case _D:return t.byteLength!==e.byteLength?!1:yn(new Uint8Array(t),new Uint8Array(e),r,i);case SD:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:yn(new Uint8Array(t),new Uint8Array(e),r,i);case ID:return t.name===e.name&&t.message===e.message;case sa:{if(!(yn(t.constructor,e.constructor,r,i)||Qh(t)&&Qh(e)))return!1;const c=[...Object.keys(t),...Zh(t)],u=[...Object.keys(e),...Zh(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const h=c[l],f=t[h];if(!Object.hasOwn(e,h))return!1;const d=e[h];if(!ln(f,d,h,t,e,r,i))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function jD(t,e){return kD(t,e,UD)}var LD=Object.defineProperty,ef=Object.getOwnPropertySymbols,MD=Object.prototype.hasOwnProperty,qD=Object.prototype.propertyIsEnumerable,oc=(t,e,r)=>e in t?LD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,tf=(t,e)=>{for(var r in e||(e={}))MD.call(e,r)&&oc(t,r,e[r]);if(ef)for(var r of ef(e))qD.call(e,r)&&oc(t,r,e[r]);return t},Ze=(t,e,r)=>oc(t,typeof e!="symbol"?e+"":e,r);class di extends P8{constructor(e,r,i,n=Kt,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,Ze(this,"map",new Map),Ze(this,"version",z$),Ze(this,"cached",[]),Ze(this,"initialized",!1),Ze(this,"getKey"),Ze(this,"storagePrefix",Kt),Ze(this,"recentlyDeleted",[]),Ze(this,"recentlyDeletedLimit",200),Ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!_e(o)?this.map.set(this.getKey(o),o):iS(o)?this.map.set(o.id,o):nS(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Ze(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())}),Ze(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Ze(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>jD(a[c],o[c]))):this.values)),Ze(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=tf(tf({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Ze(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=dt(r,this.name),this.storagePrefix=n,this.getKey=s}get context(){return st(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:n}=M("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:i}=M("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}=M("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}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var zD=Object.defineProperty,VD=(t,e,r)=>e in t?zD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ee=(t,e,r)=>VD(t,typeof e!="symbol"?e+"":e,r);class HD{constructor(e,r){this.core=e,this.logger=r,ee(this,"name",W$),ee(this,"version",G$),ee(this,"events",new pc),ee(this,"pairings"),ee(this,"initialized",!1),ee(this,"storagePrefix",Kt),ee(this,"ignoredPayloadTypes",[ur]),ee(this,"registeredMethods",[]),ee(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),ee(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),ee(this,"create",async i=>{this.isInitialized();const n=Wa(),s=await this.core.crypto.setSymKey(n),o=we(L.FIVE_MINUTES),a={protocol:Kg},c={topic:s,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},u=hh({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(Yr.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:i==null?void 0:i.transportType,internal:i==null?void 0:i.internal}),{topic:s,uri:u}}),ee(this,"pair",async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[jt.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=lh(i.uri);n.props.properties.topic=s,n.addTrace(jt.pairing_uri_validation_success),n.addTrace(jt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),n.addTrace(jt.existing_pairing),l.active)throw n.setError(rr.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(jt.pairing_not_expired)}const h=c||we(L.FIVE_MINUTES),f={topic:s,relay:a,expiry:h,active:!1,methods:u};this.core.expirer.set(s,h),await this.pairings.set(s,f),n.addTrace(jt.store_new_pairing),i.activatePairing&&await this.activate({topic:s}),this.events.emit(Yr.create,f),n.addTrace(jt.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),n.addTrace(jt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(rr.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(d){throw n.setError(rr.subscribe_pairing_topic_failure),d}return n.addTrace(jt.subscribe_pairing_topic_success),f}),ee(this,"activate",async({topic:i})=>{this.isInitialized();const n=we(L.FIVE_MINUTES);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})}),ee(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:n}=i;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Kr();this.events.once(ae("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),ee(this,"updateExpiry",async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})}),ee(this,"updateMetadata",async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})}),ee(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ee(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:n}=i;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",fe("USER_DISCONNECTED")),await this.deletePairing(n))}),ee(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:n,relay:s,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(n);return hh({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),ee(this,"sendRequest",async(i,n,s)=>{const o=Ct(n,s),a=await this.core.crypto.encode(i,o),c=en[n].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),ee(this,"sendResult",async(i,n,s)=>{const o=$n(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,u=en[c].res;await this.core.relayer.publish(n,a,u),await this.core.history.resolve(o)}),ee(this,"sendError",async(i,n,s)=>{const o=ao(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,u=en[c]?en[c].res:en.unregistered_method.res;await this.core.relayer.publish(n,a,u),await this.core.history.resolve(o)}),ee(this,"deletePairing",async(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,fe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])}),ee(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(n=>qt(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))}),ee(this,"onRelayEventRequest",async i=>{const{topic:n,payload:s}=i;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(n,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(n,s);default:return await this.onUnknownRpcMethodRequest(n,s)}}),ee(this,"onRelayEventResponse",async i=>{const{topic:n,payload:s}=i,o=(await this.core.history.get(n,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(n,s);default:return this.onUnknownRpcMethodResponse(o)}}),ee(this,"onPairingPingRequest",async(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(Yr.ping,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),ee(this,"onPairingPingResponse",(i,n)=>{const{id:s}=n;setTimeout(()=>{Mt(n)?this.events.emit(ae("pairing_ping",s),{}):vt(n)&&this.events.emit(ae("pairing_ping",s),{error:n.error})},500)}),ee(this,"onPairingDeleteRequest",async(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Yr.delete,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),ee(this,"onUnknownRpcMethodRequest",async(i,n)=>{const{id:s,method:o}=n;try{if(this.registeredMethods.includes(o))return;const a=fe("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,i,a),this.logger.error(a)}catch(a){await this.sendError(s,i,a),this.logger.error(a)}}),ee(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(fe("WC_METHOD_UNSUPPORTED",i))}),ee(this,"isValidPair",(i,n)=>{var s;if(!Xe(i)){const{message:a}=M("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(rr.malformed_pairing_uri),new Error(a)}if(!rS(i.uri)){const{message:a}=M("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(rr.malformed_pairing_uri),new Error(a)}const o=lh(i==null?void 0:i.uri);if(!((s=o==null?void 0:o.relay)!=null&&s.protocol)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(rr.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(rr.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&L.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){n.setError(rr.pairing_expired);const{message:a}=M("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),ee(this,"isValidPing",async i=>{if(!Xe(i)){const{message:s}=M("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),ee(this,"isValidDisconnect",async i=>{if(!Xe(i)){const{message:s}=M("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),ee(this,"isValidPairingTopic",async i=>{if(!be(i,!1)){const{message:n}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(qt(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=M("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}}),this.core=e,this.logger=dt(r,this.name),this.pairings=new di(this.core,this.logger,this.name,this.storagePrefix)}get context(){return st(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(me.message,async e=>{const{topic:r,message:i,transportType:n}=e;if(this.pairings.keys.includes(r)&&n!==he.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const s=await this.core.crypto.decode(r,i);Qc(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):co(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,i)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(wt.expired,async e=>{const{topic:r}=Tp(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Yr.expire,{topic:r}))})}}var KD=Object.defineProperty,WD=(t,e,r)=>e in t?KD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Be=(t,e,r)=>WD(t,typeof e!="symbol"?e+"":e,r);class GD extends $8{constructor(e,r){super(e,r),this.core=e,this.logger=r,Be(this,"records",new Map),Be(this,"events",new St.EventEmitter),Be(this,"name",Y$),Be(this,"version",Z$),Be(this,"cached",[]),Be(this,"initialized",!1),Be(this,"storagePrefix",Kt),Be(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)}),Be(this,"set",(i,n,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:n,chainId:s}),this.records.has(n.id))return;const o={id:n.id,topic:i,request:{method:n.method,params:n.params||null},chainId:s,expiry:we(L.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Ot.created,o)}),Be(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const n=await this.getRecord(i.id);typeof n.response>"u"&&(n.response=vt(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(Ot.updated,n))}),Be(this,"get",async(i,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:n}),await this.getRecord(n))),Be(this,"delete",(i,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(s=>{if(s.topic===i){if(typeof n<"u"&&s.id!==n)return;this.records.delete(s.id),this.events.emit(Ot.deleted,s)}}),this.persist()}),Be(this,"exists",async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1)),Be(this,"on",(i,n)=>{this.events.on(i,n)}),Be(this,"once",(i,n)=>{this.events.once(i,n)}),Be(this,"off",(i,n)=>{this.events.off(i,n)}),Be(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=dt(r,this.name)}get context(){return st(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:Ct(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}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ot.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=M("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(Ot.created,e=>{const r=Ot.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Ot.updated,e=>{const r=Ot.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Ot.deleted,e=>{const r=Ot.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(hi.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{L.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Ot.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var YD=Object.defineProperty,ZD=(t,e,r)=>e in t?YD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ze=(t,e,r)=>ZD(t,typeof e!="symbol"?e+"":e,r);class JD extends B8{constructor(e,r){super(e,r),this.core=e,this.logger=r,ze(this,"expirations",new Map),ze(this,"events",new St.EventEmitter),ze(this,"name",J$),ze(this,"version",X$),ze(this,"cached",[]),ze(this,"initialized",!1),ze(this,"storagePrefix",Kt),ze(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)}),ze(this,"has",i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}}),ze(this,"set",(i,n)=>{this.isInitialized();const s=this.formatTarget(i),o={target:s,expiry:n};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(wt.created,{target:s,expiration:o})}),ze(this,"get",i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)}),ze(this,"del",i=>{if(this.isInitialized(),this.has(i)){const n=this.formatTarget(i),s=this.getExpiration(n);this.expirations.delete(n),this.events.emit(wt.deleted,{target:n,expiration:s})}}),ze(this,"on",(i,n)=>{this.events.on(i,n)}),ze(this,"once",(i,n)=>{this.events.once(i,n)}),ze(this,"off",(i,n)=>{this.events.off(i,n)}),ze(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=dt(r,this.name)}get context(){return st(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 P3(e);if(typeof e=="number")return C3(e);const{message:r}=M("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(wt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=M("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}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;L.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(wt.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(hi.pulse,()=>this.checkExpirations()),this.events.on(wt.created,e=>{const r=wt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(wt.expired,e=>{const r=wt.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(wt.deleted,e=>{const r=wt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var XD=Object.defineProperty,QD=(t,e,r)=>e in t?XD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ye=(t,e,r)=>QD(t,typeof e!="symbol"?e+"":e,r);class eA extends T8{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,ye(this,"name",Q$),ye(this,"abortController"),ye(this,"isDevEnv"),ye(this,"verifyUrlV3",t6),ye(this,"storagePrefix",Kt),ye(this,"version",Hg),ye(this,"publicKey"),ye(this,"fetchPromise"),ye(this,"init",async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&L.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ye(this,"register",async n=>{if(!Mi()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=n,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const u=ii(),l=this.startAbortTimer(L.ONE_SECOND*5),h=await new Promise((f,d)=>{const p=()=>{window.removeEventListener("message",w),u.body.removeChild(g),d("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=u.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const w=I=>{if(I.data&&typeof I.data=="string")try{const C=JSON.parse(I.data);if(C.type==="verify_attestation"){if(Ca(C.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",w),f(C.attestation===null?"":C.attestation)}}catch(C){this.logger.warn(C)}};u.body.appendChild(g),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug(h,"jwt attestation"),h}catch(u){this.logger.warn(u)}return""}),ye(this,"resolve",async n=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=n;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Ca(s).payload.id!==a)return;const u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!o)return;const c=this.getVerifyUrl(n==null?void 0:n.verifyUrl);return this.fetchAttestation(o,c)}),ye(this,"fetchAttestation",async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const o=this.startAbortTimer(L.ONE_SECOND*5),a=await fetch(`${s}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),ye(this,"getVerifyUrl",n=>{let s=n||gn;return r6.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${gn}`),s=gn),s}),ye(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(L.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(n),await s.json()}catch(n){this.logger.warn(n)}}),ye(this,"persistPublicKey",async n=>{this.logger.debug(n,"persisting public key to local storage"),await this.store.setItem(this.storeKey,n),this.publicKey=n}),ye(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ye(this,"isValidJwtAttestation",async n=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(n,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(n,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),ye(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ye(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const n=await this.fetchPromise;return this.fetchPromise=void 0,n}),ye(this,"validateAttestation",(n,s)=>{const o=DI(n,s.publicKey),a={hasExpired:L.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=dt(r,this.name),this.abortController=new AbortController,this.isDevEnv=Lc(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return st(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),L.toMiliseconds(e))}}var tA=Object.defineProperty,rA=(t,e,r)=>e in t?tA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rf=(t,e,r)=>rA(t,typeof e!="symbol"?e+"":e,r);class iA extends R8{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,rf(this,"context",i6),rf(this,"registerDeviceToken",async i=>{const{clientId:n,token:s,notificationType:o,enableEncrypted:a=!1}=i,c=`${n6}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:o,token:s,always_raw:a})})}),this.logger=dt(r,this.context)}}var nA=Object.defineProperty,nf=Object.getOwnPropertySymbols,sA=Object.prototype.hasOwnProperty,oA=Object.prototype.propertyIsEnumerable,ac=(t,e,r)=>e in t?nA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,nn=(t,e)=>{for(var r in e||(e={}))sA.call(e,r)&&ac(t,r,e[r]);if(nf)for(var r of nf(e))oA.call(e,r)&&ac(t,r,e[r]);return t},$e=(t,e,r)=>ac(t,typeof e!="symbol"?e+"":e,r);class aA extends F8{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,$e(this,"context",o6),$e(this,"storagePrefix",Kt),$e(this,"storageVersion",s6),$e(this,"events",new Map),$e(this,"shouldPersist",!1),$e(this,"init",async()=>{if(!Lc())try{const n={eventId:Pl(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Cp(this.core.relayer.protocol,this.core.relayer.version,Qa)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}}),$e(this,"createEvent",n=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=n,u=Pl(),l=this.core.projectId||"",h=Date.now(),f=nn({eventId:u,timestamp:h,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,f),this.shouldPersist=!0),f}),$e(this,"getEvent",n=>{const{eventId:s,topic:o}=n;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return nn(nn({},a),this.setMethods(a.eventId))}),$e(this,"deleteEvent",n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0}),$e(this,"setEventListeners",()=>{this.core.heartbeat.on(hi.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{L.fromMiliseconds(Date.now())-L.fromMiliseconds(n.timestamp)>a6&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})}),$e(this,"setMethods",n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)})),$e(this,"addTrace",(n,s)=>{const o=this.events.get(n);o&&(o.props.properties.trace.push(s),this.events.set(n,o),this.shouldPersist=!0)}),$e(this,"setError",(n,s)=>{const o=this.events.get(n);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(n,o),this.shouldPersist=!0)}),$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 n=await this.core.storage.getItem(this.storageKey)||[];if(!n.length)return;n.forEach(s=>{this.events.set(s.eventId,nn(nn({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}}),$e(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[s,o]of this.events)o.props.type&&n.push(o);if(n.length!==0)try{if((await this.sendEvent(n)).ok)for(const s of n)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),$e(this,"sendEvent",async n=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${c6}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Qa}${s}`,{method:"POST",body:JSON.stringify(n)})}),$e(this,"getAppDomain",()=>Pp().url),this.logger=dt(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 cA=Object.defineProperty,sf=Object.getOwnPropertySymbols,uA=Object.prototype.hasOwnProperty,lA=Object.prototype.propertyIsEnumerable,cc=(t,e,r)=>e in t?cA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,of=(t,e)=>{for(var r in e||(e={}))uA.call(e,r)&&cc(t,r,e[r]);if(sf)for(var r of sf(e))lA.call(e,r)&&cc(t,r,e[r]);return t},ue=(t,e,r)=>cc(t,typeof e!="symbol"?e+"":e,r);let hA=class o0 extends x8{constructor(e){var r;super(e),ue(this,"protocol",Vg),ue(this,"version",Hg),ue(this,"name",Us),ue(this,"relayUrl"),ue(this,"projectId"),ue(this,"customStoragePrefix"),ue(this,"events",new St.EventEmitter),ue(this,"logger"),ue(this,"heartbeat"),ue(this,"relayer"),ue(this,"crypto"),ue(this,"storage"),ue(this,"history"),ue(this,"expirer"),ue(this,"pairing"),ue(this,"verify"),ue(this,"echoClient"),ue(this,"linkModeSupportedApps"),ue(this,"eventClient"),ue(this,"initialized",!1),ue(this,"logChunkController"),ue(this,"on",(a,c)=>this.events.on(a,c)),ue(this,"once",(a,c)=>this.events.once(a,c)),ue(this,"off",(a,c)=>this.events.off(a,c)),ue(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ue(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:he.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});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)||Wg,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const n=u3({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:A$.logger,name:Us}),{logger:s,chunkLoggerController:o}=Dp({opts:n,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=dt(s,this.name),this.heartbeat=new jS,this.crypto=new kO(this,this.logger,e==null?void 0:e.keychain),this.history=new GD(this,this.logger),this.expirer=new JD(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new b8(of(of({},P$),e==null?void 0:e.storageOptions)),this.relayer=new hD({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new HD(this,this.logger),this.verify=new eA(this,this.logger,this.storage),this.echoClient=new iA(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new aA(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new o0(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(V$,i),r}get context(){return st(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(Uh,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(Uh)||[],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 xt<"u"&&{}.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const fA=hA,a0="wc",c0=2,u0="client",tu=`${a0}@${c0}:${u0}:`,oa={name:u0,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},af="WALLETCONNECT_DEEPLINK_CHOICE",dA="proposal",cf="Proposal expired",pA="session",xi=L.SEVEN_DAYS,gA="engine",Te={wc_sessionPropose:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1104},res:{ttl:L.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1106},res:{ttl:L.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1112},res:{ttl:L.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1114},res:{ttl:L.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:L.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:L.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1119}}},aa={min:L.FIVE_MINUTES,max:L.SEVEN_DAYS},kt={idle:"IDLE",active:"ACTIVE"},yA={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:""}},wA="request",mA=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],bA="wc",vA="auth",EA="authKeys",xA="pairingTopics",_A="requests",lo=`${bA}@${1.5}:${vA}:`,ws=`${lo}:PUB_KEY`;var IA=Object.defineProperty,SA=Object.defineProperties,$A=Object.getOwnPropertyDescriptors,uf=Object.getOwnPropertySymbols,OA=Object.prototype.hasOwnProperty,DA=Object.prototype.propertyIsEnumerable,uc=(t,e,r)=>e in t?IA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,oe=(t,e)=>{for(var r in e||(e={}))OA.call(e,r)&&uc(t,r,e[r]);if(uf)for(var r of uf(e))DA.call(e,r)&&uc(t,r,e[r]);return t},Re=(t,e)=>SA(t,$A(e)),k=(t,e,r)=>uc(t,typeof e!="symbol"?e+"":e,r);class AA extends j8{constructor(e){super(e),k(this,"name",gA),k(this,"events",new pc),k(this,"initialized",!1),k(this,"requestQueue",{state:kt.idle,queue:[]}),k(this,"sessionRequestQueue",{state:kt.idle,queue:[]}),k(this,"emittedSessionRequests",new L3({limit:500})),k(this,"requestQueueDelay",L.ONE_SECOND),k(this,"expectedPairingMethodMap",new Map),k(this,"recentlyDeletedMap",new Map),k(this,"recentlyDeletedLimit",200),k(this,"relayMessageCache",[]),k(this,"pendingSessions",new Map),k(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(Te)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay)))}),k(this,"connect",async r=>{var i;this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=Re(oe({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=JI(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:u,relays:l,authentication:h,walletPay:f}=n,d=((i=h==null?void 0:h[0])==null?void 0:i.ttl)||Te.wc_sessionPropose.req.ttl||L.FIVE_MINUTES;this.validateRequestExpiry(d);let p=s,g,w=!1;try{if(p){const A=this.client.core.pairing.pairings.get(p);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),w=A.active}}catch(A){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),A}if(!p||!w){const{topic:A,uri:U}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=A,g=U}if(!p){const{message:A}=M("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(A)}const I=await this.client.core.crypto.generateKeyPair(),C=we(d),b=oe(Re(oe(oe({requiredNamespaces:o,optionalNamespaces:a,relays:l??[{protocol:Kg}],proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:C,pairingTopic:p},c&&{sessionProperties:c}),u&&{scopedProperties:u}),{id:Lt()}),(h||f)&&{requests:{authentication:h==null?void 0:h.map(A=>{const{domain:U,chains:j,nonce:B,uri:_,exp:O,nbf:m,type:y,statement:x,requestId:$,resources:E,signatureTypes:S}=A;return{domain:U,chains:j,nonce:B,type:y??"caip122",aud:_,version:"1",iat:new Date().toISOString(),exp:O,nbf:m,statement:x,requestId:$,resources:E,signatureTypes:S}}),walletPay:f}}),v=ae("session_connect",b.id),{reject:D,resolve:P,done:T}=Kr(d,cf),R=({id:A})=>{A===b.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(b.id),this.events.emit(v,{error:{message:cf,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(v,({error:A,session:U})=>{this.client.events.off("proposal_expire",R),A?D(A):U&&P(U)}),await this.setProposal(b.id,b),await this.sendProposeSession({proposal:b,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:b.id}}}).catch(A=>{throw this.deleteProposal(b.id),A}),{uri:g,approval:T}}),k(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}}),k(this,"approve",async r=>{var i,n,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=r==null?void 0:r.id)==null?void 0:i.toString(),trace:[Dt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(U){throw o.setError(zr.no_internet_connection),U}try{await this.isValidProposalId(r==null?void 0:r.id)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${r==null?void 0:r.id}) failed`),o.setError(zr.proposal_not_found),U}try{await this.isValidApprove(r)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(zr.session_approve_namespace_validation_failure),U}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:w,requiredNamespaces:I,optionalNamespaces:C}=p;let b=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:g});b||(b=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Dt.session_approve_started,properties:{topic:g,trace:[Dt.session_approve_started,Dt.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),D=w.publicKey,P=await this.client.core.crypto.generateSharedKey(v,D),T=Re(oe(oe(oe({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:v,metadata:this.client.metadata},expiry:we(xi)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{proposalRequestsResponses:d}),R=he.relay;b.addTrace(Dt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:R,internal:{skipSubscribe:!0}})}catch(U){throw b.setError(zr.subscribe_session_topic_failure),U}b.addTrace(Dt.subscribe_session_topic_success);const A=Re(oe({},T),{topic:P,requiredNamespaces:I,optionalNamespaces:C,pairingTopic:g,acknowledged:!1,self:T.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:v,transportType:he.relay,authentication:d==null?void 0:d.authentication,walletPayResult:d==null?void 0:d.walletPay});await this.client.session.set(P,A),b.addTrace(Dt.store_session);try{await this.sendApproveSession({sessionTopic:P,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:v},sessionSettleRequest:T,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:oe({correlationId:a},this.getTVFApproveParams(A))}}),b.addTrace(Dt.session_approve_publish_success)}catch(U){throw this.client.logger.error(U),this.client.session.delete(P,fe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(P),U}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:w.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(P,we(xi)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),k(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:n}=r;let s;try{s=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}s&&await this.sendError({id:i,topic:s,error:n,rpcOpts:Te.wc_sessionPropose.reject}),await this.deleteProposal(i)}),k(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:i,namespaces:n}=r,{done:s,resolve:o,reject:a}=Kr(L.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Lt(),u=Rr().toString(),l=this.client.session.get(i).namespaces;return this.events.once(ae("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(h=>{this.client.logger.error(h),this.client.session.update(i,{namespaces:l}),a(h)}),{acknowledged:s}}),k(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=r,n=Lt(),{done:s,resolve:o,reject:a}=Kr(L.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(ae("session_extend",n),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,we(xi)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),k(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:i,request:n,topic:s,expiry:o=Te.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);(a==null?void 0:a.transportType)===he.relay&&await this.confirmOnlineStateOrThrow();const c=Lt(),u=Rr().toString(),{done:l,resolve:h,reject:f}=Kr(o,"Request expired. Please try again.");this.events.once(ae("session_request",c),({error:w,result:I})=>{w?f(w):h(I)});const d="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:d,params:{request:Re(oe({},n),{expiryTimestamp:we(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(w=>f(w)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),await l();const g={request:Re(oe({},n),{expiryTimestamp:we(o)}),chainId:i};return await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:d,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(I=>f(I)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),w()}),new Promise(async w=>{var I;if(!((I=a.sessionConfig)!=null&&I.disableDeepLink)){const C=await F3(this.client.core.storage,af);await B3({id:c,topic:s,wcDeepLink:C})}w()}),l()]).then(w=>w[2])}),k(this,"respond",async r=>{var i,n;this.isInitialized();const s=this.client.core.eventClient.createEvent({properties:{topic:(r==null?void 0:r.topic)||((n=(i=r==null?void 0:r.response)==null?void 0:i.id)==null?void 0:n.toString()),trace:[Dt.session_request_response_started]}});try{await this.isValidRespond(r)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zr.session_request_response_validation_failure),h}s.addTrace(Dt.session_request_response_validation_success);const{topic:o,response:a}=r,{id:c}=a,u=this.client.session.get(o);u.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const l=this.getAppLinkIfEnabled(u.peer.metadata,u.transportType);try{s.addTrace(Dt.session_request_response_publish_started),Mt(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:l}):vt(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:l}),this.cleanupAfterResponse(r)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zr.session_request_response_publish_failure),h}}),k(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:i}=r;if(this.client.session.keys.includes(i)){const n=Lt(),s=Rr().toString(),{done:o,resolve:a,reject:c}=Kr(L.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(ae("session_ping",n),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),k(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,o=Rr().toString(),a=Lt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),k(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:fe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=M("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}}),k(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>eS(i,r)))),k(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),k(this,"authenticate",async(r,i)=>{var n;this.isInitialized(),this.isValidAuthenticate(r);const s=i&&this.client.core.linkModeSupportedApps.includes(i)&&((n=this.client.metadata.redirect)==null?void 0:n.linkMode),o=s?he.link_mode:he.relay;o===he.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:h,type:f,exp:d,nbf:p,methods:g=[],expiry:w}=r,I=[...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 v=await this.client.core.crypto.generateKeyPair(),D=ds(v);if(await Promise.all([this.client.auth.authKeys.set(ws,{responseTopic:D,publicKey:v}),this.client.auth.pairingTopics.set(D,{topic:D,pairingTopic:C})]),await this.client.core.relayer.subscribe(D,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${C}`),g.length>0){const{namespace:E}=cr(a[0]);let S=Qx(E,"request",g);fs(I)&&(S=t_(S,I.pop())),I.push(S)}const P=w&&w>Te.wc_sessionAuthenticate.req.ttl?w:Te.wc_sessionAuthenticate.req.ttl,T={authPayload:{type:f??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:h,iat:new Date().toISOString(),exp:d,nbf:p,resources:I},requester:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:we(P)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},A={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:C,proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:we(Te.wc_sessionPropose.req.ttl),id:Lt()},{done:U,resolve:j,reject:B}=Kr(P,"Request expired"),_=Lt(),O=ae("session_connect",A.id),m=ae("session_request",_),y=async({error:E,session:S})=>{this.events.off(m,x),E?B(E):S&&j({session:S})},x=async E=>{var S,F,N;if(await this.deletePendingAuthRequest(_,{message:"fulfilled",code:0}),E.error){const W=fe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return E.error.code===W.code?void 0:(this.events.off(O,y),B(E.error.message))}await this.deleteProposal(A.id),this.events.off(O,y);const{cacaos:H,responder:z}=E.result,q=[],K=[];for(const W of H){await Ml({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),B(fe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Q}=W,pe=fs(Q.resources),ve=[Ua(Q.iss)],Ie=Cs(Q.iss);if(pe){const He=ql(pe),Wt=zl(pe);q.push(...He),ve.push(...Wt)}for(const He of ve)K.push(`${He}:${Ie}`)}const G=await this.client.core.crypto.generateSharedKey(v,z.publicKey);let X;q.length>0&&(X={topic:G,acknowledged:!0,self:{publicKey:v,metadata:this.client.metadata},peer:z,controller:z.publicKey,expiry:we(xi),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:C,namespaces:gh([...new Set(q)],[...new Set(K)]),transportType:o},await this.client.core.relayer.subscribe(G,{transportType:o}),await this.client.session.set(G,X),C&&await this.client.core.pairing.updateMetadata({topic:C,metadata:z.metadata}),X=this.client.session.get(G)),(S=this.client.metadata.redirect)!=null&&S.linkMode&&(F=z.metadata.redirect)!=null&&F.linkMode&&(N=z.metadata.redirect)!=null&&N.universal&&i&&(this.client.core.addLinkModeSupportedApp(z.metadata.redirect.universal),this.client.session.update(G,{transportType:he.link_mode})),j({auths:H,session:X})};this.events.once(O,y),this.events.once(m,x);let $;try{if(s){const E=Ct("wc_sessionAuthenticate",T,_);this.client.core.history.set(C,E);const S=await this.client.core.crypto.encode("",E,{type:Nn,encoding:Br});$=rs(i,C,S)}else await Promise.all([this.sendRequest({topic:C,method:"wc_sessionAuthenticate",params:T,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:_}),this.sendRequest({topic:C,method:"wc_sessionPropose",params:A,expiry:Te.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:A.id})])}catch(E){throw this.events.off(O,y),this.events.off(m,x),E}return await this.setProposal(A.id,A),await this.setAuthRequest(_,{request:Re(oe({},T),{verifyContext:{}}),pairingTopic:C,transportType:o}),{uri:$??b,response:U}}),k(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Vr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw s.setError(tn.no_internet_connection),w}const o=this.getPendingAuthRequest(i);if(!o)throw s.setError(tn.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||he.relay;a===he.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=ds(c),h={type:ur,receiverPublicKey:c,senderPublicKey:u},f=[],d=[];for(const w of n){if(!await Ml({cacao:w,projectId:this.client.core.projectId})){s.setError(tn.invalid_cacao);const D=fe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:l,error:D,encodeOpts:h}),new Error(D.message)}s.addTrace(Vr.cacaos_verified);const{p:I}=w,C=fs(I.resources),b=[Ua(I.iss)],v=Cs(I.iss);if(C){const D=ql(C),P=zl(C);f.push(...D),b.push(...P)}for(const D of b)d.push(`${D}:${v}`)}const p=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(Vr.create_authenticated_session_topic);let g;if((f==null?void 0:f.length)>0){g={topic:p,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:we(xi),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:gh([...new Set(f)],[...new Set(d)]),transportType:a},s.addTrace(Vr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(w){throw s.setError(tn.subscribe_authenticated_session_topic_failure),w}s.addTrace(Vr.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Vr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Vr.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:i,result:{cacaos:n,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw s.setError(tn.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:g}}),k(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:i,reason:n}=r,s=this.getPendingAuthRequest(i);if(!s)throw new Error(`Could not find pending auth request with id ${i}`);s.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ds(o),u={type:ur,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:n,encodeOpts:u,rpcOpts:Te.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.deleteProposal(i)}),k(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:n}=r;return Zp(i,n)}),k(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)}),k(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.pairingTopic),n=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==i.topic});if(n.length===0)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),k(this,"deleteSession",async r=>{var i;const{topic:n,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,fe("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),s||this.client.core.expirer.del(n),this.client.core.storage.removeItem(af).catch(u=>this.client.logger.warn(u)),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=kt.idle),await Promise.all(this.getPendingSessionRequests().filter(u=>u.topic===n).map(u=>this.deletePendingSessionRequest(u.id,fe("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:n})}),k(this,"deleteProposal",async(r,i)=>{if(i)try{const n=this.client.proposal.get(r),s=this.client.core.eventClient.getEvent({topic:n.pairingTopic});s==null||s.setError(zr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,fe("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),k(this,"deletePendingSessionRequest",async(r,i,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),n&&(this.sessionRequestQueue.state=kt.idle,this.client.events.emit("session_request_expire",{id:r}))}),k(this,"deletePendingAuthRequest",async(r,i,n=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)])}),k(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}))}),k(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,we(Te.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),k(this,"setAuthRequest",async(r,i)=>{const{request:n,pairingTopic:s,transportType:o=he.relay}=i;this.client.core.expirer.set(r,n.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:r,pairingTopic:s,verifyContext:n.verifyContext,transportType:o})}),k(this,"setPendingSessionRequest",async r=>{const{id:i,topic:n,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||we(Te.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:n,params:s,verifyContext:o})}),k(this,"sendRequest",async r=>{const{topic:i,method:n,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:h,publishOpts:f={}}=r,d=Ct(n,s,c);let p;const g=!!l;try{const C=g?Br:tt;p=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 w;if(mA.includes(n)){const C=bt(JSON.stringify(d)),b=bt(p);w=await this.client.core.verify.register({id:b,decryptedId:C})}const I=oe(oe({},Te[n].req),f);if(I.attestation=w,o&&(I.ttl=o),a&&(I.id=a),this.client.core.history.set(i,d),g){const C=rs(l,i,p);await Y.Linking.openURL(C,this.client.name)}else I.tvf=Re(oe({},h),{correlationId:d.id}),u?(I.internal=Re(oe({},I.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,p,I)):this.client.core.relayer.publish(i,p,I).catch(C=>this.client.logger.error(C));return d.id}),k(this,"sendProposeSession",async r=>{const{proposal:i,publishOpts:n}=r,s=Ct("wc_sessionPropose",i,i.id);this.client.core.history.set(i.pairingTopic,s);const o=await this.client.core.crypto.encode(i.pairingTopic,s,{encoding:tt}),a=bt(JSON.stringify(s)),c=bt(o),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:i.pairingTopic,sessionProposal:o},opts:Re(oe({},n),{publishMethod:"wc_proposeSession",attestation:u})})}),k(this,"sendApproveSession",async r=>{const{sessionTopic:i,pairingProposalResponse:n,proposal:s,sessionSettleRequest:o,publishOpts:a}=r,c=$n(s.id,n),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:tt}),l=Ct("wc_sessionSettle",o,a==null?void 0:a.id),h=await this.client.core.crypto.encode(i,l,{encoding:tt});this.client.core.history.set(i,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:i,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:h},opts:Re(oe({},a),{publishMethod:"wc_approveSession"})})}),k(this,"sendResult",async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,u=$n(i,s);let l;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const p=h?Br:tt;l=await this.client.core.crypto.encode(n,u,Re(oe({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),p}let f,d;try{f=await this.client.core.history.get(n,i);const p=f.request;try{d=this.getTVFParams(i,p.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g==null?void 0:g.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),p}if(h){const p=rs(c,n,l);await Y.Linking.openURL(p,this.client.name)}else{const p=f.request.method,g=Te[p].res;g.tvf=Re(oe({},d),{correlationId:i}),o?(g.internal=Re(oe({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,l,g)):this.client.core.relayer.publish(n,l,g).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(u)}),k(this,"sendError",async r=>{const{id:i,topic:n,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,u=ao(i,s);let l;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const d=h?Br:tt;l=await this.client.core.crypto.encode(n,u,Re(oe({},o||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),d}let f;try{f=await this.client.core.history.get(n,i)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),d}if(h){const d=rs(c,n,l);await Y.Linking.openURL(d,this.client.name)}else{const d=f.request.method,p=a||Te[d].res;this.client.core.relayer.publish(n,l,p)}await this.client.core.history.resolve(u)}),k(this,"cleanup",async()=>{const r=[],i=[];this.client.session.getAll().forEach(n=>{let s=!1;qt(n.expiry)&&(s=!0),this.client.core.crypto.keychain.has(n.topic)||(s=!0),s&&r.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{qt(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...r.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])}),k(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),k(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),k(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===kt.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=kt.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=kt.idle}),k(this,"processRequest",async r=>{const{topic:i,payload:n,attestation:s,transportType:o,encryptedId:a}=r,c=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),k(this,"onRelayEventResponse",async r=>{const{topic:i,payload:n,transportType:s}=r,o=(await this.client.core.history.get(i,n.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n,s);case"wc_sessionSettle":return this.onSessionSettleResponse(i,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,n);case"wc_sessionExtend":return this.onSessionExtendResponse(i,n);case"wc_sessionPing":return this.onSessionPingResponse(i,n);case"wc_sessionRequest":return this.onSessionRequestResponse(i,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,n);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),k(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:n}=M("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)}),k(this,"shouldIgnorePairingRequest",r=>{const{topic:i,requestMethod:n}=r,s=this.expectedPairingMethodMap.get(i);return!s||s.includes(n)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),k(this,"onSessionProposeRequest",async r=>{const{topic:i,payload:n,attestation:s,encryptedId:o}=r,{params:a,id:c}=n;try{const u=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u==null||u.setError(rr.proposal_listener_not_found)),this.isValidConnect(oe({},n.params));const l=a.expiryTimestamp||we(Te.wc_sessionPropose.req.ttl),h=oe({id:c,pairingTopic:i,expiryTimestamp:l,attestation:s,encryptedId:o},a);await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:s,hash:bt(JSON.stringify(n)),encryptedId:o,metadata:h.proposer.metadata});u==null||u.addTrace(jt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(u){await this.sendError({id:c,topic:i,error:u,rpcOpts:Te.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),k(this,"onSessionProposeResponse",async(r,i,n)=>{const{id:s}=i;if(Mt(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const l=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:l,pairingTopic:r,proposalId:s,publicKey:c});const h=await this.client.core.relayer.subscribe(l,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:r})}else if(vt(i)){await this.deleteProposal(s);const o=ae("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),k(this,"onSessionSettleRequest",async(r,i)=>{const{id:n,params:s}=i;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=i.params,p=[...this.pendingSessions.values()].find(I=>I.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const g=this.client.proposal.get(p.proposalId),w=Re(oe(oe(oe({topic:r,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{transportType:he.relay,authentication:d==null?void 0:d.authentication,walletPayResult:d==null?void 0:d.walletPay});await this.client.session.set(w.topic,w),await this.setExpiry(w.topic,w.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:w.peer.metadata}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(w),await this.sendResult({id:i.id,topic:r,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:w}),this.events.emit(ae("session_connect",p.proposalId),{session:w})}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"onSessionSettleResponse",async(r,i)=>{const{id:n}=i;Mt(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ae("session_approve",n),{})):vt(i)&&(await this.client.session.delete(r,fe("USER_DISCONNECTED")),this.events.emit(ae("session_approve",n),{error:i.error}))}),k(this,"onSessionUpdateRequest",async(r,i)=>{const{params:n,id:s}=i;try{const o=`${r}_session_update`,a=Qi.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:fe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(oe({topic:r},n));try{Qi.set(o,s),await this.client.session.update(r,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:r,result:!0})}catch(c){throw Qi.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:n})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),k(this,"onSessionUpdateResponse",(r,i)=>{const{id:n}=i,s=ae("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_update",n),{}):vt(i)&&this.events.emit(ae("session_update",n),{error:i.error})}),k(this,"onSessionExtendRequest",async(r,i)=>{const{id:n}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,we(xi)),await this.sendResult({id:n,topic:r,result:!0}),this.client.events.emit("session_extend",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),k(this,"onSessionExtendResponse",(r,i)=>{const{id:n}=i,s=ae("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_extend",n),{}):vt(i)&&this.events.emit(ae("session_extend",n),{error:i.error})}),k(this,"onSessionPingRequest",async(r,i)=>{const{id:n}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),k(this,"onSessionPingResponse",(r,i)=>{const{id:n}=i,s=ae("session_ping",n);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Mt(i)?this.events.emit(ae("session_ping",n),{}):vt(i)&&this.events.emit(ae("session_ping",n),{error:i.error})},500)}),k(this,"onSessionDeleteRequest",async(r,i)=>{const{id:n}=i;try{await this.isValidDisconnect({topic:r,reason:i.params}),this.cleanupPendingSentRequestsForTopic({topic:r,error:fe("USER_DISCONNECTED")}),await this.deleteSession({topic:r,id:n})}catch(s){this.client.logger.error(s)}}),k(this,"onSessionRequest",async r=>{var i,n,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=r,{id:h,params:f}=a;try{await this.isValidRequest(oe({topic:o},f));const d=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:bt(JSON.stringify(Ct("wc_sessionRequest",f,h))),encryptedId:u,metadata:d.peer.metadata,transportType:l}),g={id:h,topic:o,params:f,verifyContext:p};await this.setPendingSessionRequest(g),l===he.link_mode&&(i=d.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((n=d.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(d){await this.sendError({id:h,topic:o,error:d}),this.client.logger.error(d)}}),k(this,"onSessionRequestResponse",(r,i)=>{const{id:n}=i,s=ae("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_request",n),{result:i.result}):vt(i)&&this.events.emit(ae("session_request",n),{error:i.error})}),k(this,"onSessionEventRequest",async(r,i)=>{const{id:n,params:s}=i;try{const o=`${r}_session_event_${s.event.name}`,a=Qi.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(oe({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),Qi.set(o,n)}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),Mt(i)?this.events.emit(ae("session_request",n),{result:i.result}):vt(i)&&this.events.emit(ae("session_request",n),{error:i.error})}),k(this,"onSessionAuthenticateRequest",async r=>{var i;const{topic:n,payload:s,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:u,authPayload:l,expiryTimestamp:h}=s.params,f=await this.getVerifyContext({attestationId:o,hash:bt(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),d={requester:u,pairingTopic:n,id:s.id,authPayload:l,verifyContext:f,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:d,pairingTopic:n,transportType:c}),c===he.link_mode&&(i=u.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:s.params,id:s.id,verifyContext:f})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(s.params.requester.metadata,c),d={type:ur,receiverPublicKey:l,senderPublicKey:h};await this.sendError({id:s.id,topic:n,error:u,encodeOpts:d,rpcOpts:Te.wc_sessionAuthenticate.autoReject,appLink:f})}}),k(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),k(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=kt.idle,this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay))}),k(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:i})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(ae("session_request",s.request.id),{error:i})})}),k(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===kt.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)}}),k(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=kt.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),k(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(n=>n.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:Ct("wc_sessionPropose",Re(oe({},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})}),k(this,"isValidConnect",async r=>{if(!Xe(r)){const{message:u}=M("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=r;if(_e(i)||await this.isValidPairingTopic(i),!fS(c,!0)){const{message:u}=M("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(n&&!_e(n)&&Ht(n)!==0){const u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(n,"requiredNamespaces")}if(s&&!_e(s)&&Ht(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!_e(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!_e(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(n||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),k(this,"validateNamespaces",(r,i)=>{const n=hS(r,"connect()",i);if(n)throw new Error(n.message)}),k(this,"isValidApprove",async r=>{if(!Xe(r))throw new Error(M("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:n,relayProtocol:s,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),u=Xo(n,"approve()");if(u)throw new Error(u.message);const l=mh(c.requiredNamespaces,n,"approve()");if(l)throw new Error(l.message);if(!be(s,!0)){const{message:h}=M("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(o&&!_e(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!_e(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(n));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(", ")}`)}}),k(this,"isValidReject",async r=>{if(!Xe(r)){const{message:s}=M("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:i,reason:n}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!pS(n)){const{message:s}=M("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}}),k(this,"isValidSessionSettleRequest",r=>{if(!Xe(r)){const{message:u}=M("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}const{relay:i,controller:n,namespaces:s,expiry:o}=r;if(!Rg(i)){const{message:u}=M("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=sS(n,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Xo(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(qt(o)){const{message:u}=M("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),k(this,"isValidUpdate",async r=>{if(!Xe(r)){const{message:c}=M("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:i,namespaces:n}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),o=Xo(n,"update()");if(o)throw new Error(o.message);const a=mh(s.requiredNamespaces,n,"update()");if(a)throw new Error(a.message)}),k(this,"isValidExtend",async r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(n)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),k(this,"isValidRequest",async r=>{if(!Xe(r)){const{message:c}=M("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:i,request:n,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!wh(a,s)){const{message:c}=M("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!gS(n)){const{message:c}=M("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(c)}if(!mS(a,s,n.method)){const{message:c}=M("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),k(this,"isValidRespond",async r=>{var i;if(!Xe(r)){const{message:a}=M("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}const{topic:n,response:s}=r;try{await this.isValidSessionTopic(n)}catch(a){throw(i=r==null?void 0:r.response)!=null&&i.id&&this.cleanupAfterResponse(r),a}if(!yS(s)){const{message:a}=M("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}const o=this.client.pendingRequest.get(s.id);if(o.topic!==n){const{message:a}=M("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${o.topic}, received topic: ${n}`);throw new Error(a)}}),k(this,"isValidPing",async r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),k(this,"isValidEmit",async r=>{if(!Xe(r)){const{message:a}=M("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:i,event:n,chainId:s}=r;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!wh(o,s)){const{message:a}=M("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!wS(n)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}if(!bS(o,s,n.name)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}}),k(this,"isValidDisconnect",async r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),k(this,"isValidAuthenticate",r=>{const{chains:i,uri:n,domain:s,nonce:o}=r;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!be(n,!1))throw new Error("uri is required parameter");if(!be(s,!1))throw new Error("domain is required parameter");if(!be(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.")}),k(this,"getVerifyContext",async r=>{const{attestationId:i,hash:n,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||gn,validation:"UNKNOWN",origin:o.url||""}};try{if(a===he.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:i,hash:n,encryptedId:s,verifyUrl:o.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),k(this,"validateSessionProps",(r,i)=>{Object.values(r).forEach((n,s)=>{if(n==null){const{message:o}=M("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${n} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),k(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),k(this,"addToRecentlyDeleted",(r,i)=>{if(this.recentlyDeletedMap.set(r,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let n=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(n++>=s)break;this.recentlyDeletedMap.delete(o)}}}),k(this,"checkRecentlyDeleted",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:n}=M("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(n)}}),k(this,"isLinkModeEnabled",(r,i)=>{var n,s,o,a,c,u,l,h,f;return!r||i!==he.link_mode?!1:((s=(n=this.client.metadata)==null?void 0:n.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((l=r==null?void 0:r.redirect)==null?void 0:l.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(Y==null?void 0:Y.Linking)<"u"}),k(this,"getAppLinkIfEnabled",(r,i)=>{var n;return this.isLinkModeEnabled(r,i)?(n=r==null?void 0:r.redirect)==null?void 0:n.universal:void 0}),k(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Al(r,"topic")||"",n=decodeURIComponent(Al(r,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:he.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})}),k(this,"registerLinkModeListeners",async()=>{var r;if(Lc()||kr()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const i=Y==null?void 0:Y.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await i.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}),k(this,"getTVFApproveParams",r=>{try{const i=Bg(r.namespaces),n=KI(r.namespaces),s=WI(r.namespaces),o=r.sessionProperties,a=r.scopedProperties;return{approvedChains:i,approvedMethods:n,approvedEvents:s,sessionProperties:o,scopedProperties:a}}catch(i){return this.client.logger.warn(i,"Error getting TVF approve params"),{}}}),k(this,"getTVFParams",(r,i,n)=>{var s,o,a;if(!((s=i.request)!=null&&s.method))return{};const c={correlationId:r,rpcMethods:[i.request.method],chainId:i.chainId};try{const u=this.extractTxHashesFromResult(i.request,n);c.txHashes=u,c.contractAddresses=this.isValidContractData(i.request.params)?[(a=(o=i.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(u){this.client.logger.warn(u,"Error getting TVF params")}return c}),k(this,"isValidContractData",r=>{var i;if(!r)return!1;try{const n=(r==null?void 0:r.data)||((i=r==null?void 0:r[0])==null?void 0:i.data);if(!n.startsWith("0x"))return!1;const s=n.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),k(this,"extractTxHashesFromResult",(r,i)=>{var n;try{if(!i)return[];const s=r.method,o=yA[s];if(s==="sui_signTransaction")return[Rx(i.transactionBytes)];if(s==="near_signTransaction")return[Ul(i)];if(s==="near_signTransactions")return i.map(c=>Ul(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(n=i.tx_json)==null?void 0:n.hash];if(s==="polkadot_signTransaction")return[US({transaction:r.params.transactionPayload,signature:i.signature})];if(s==="algo_signTxn")return _t(i)?i.map(c=>kl(c)):[kl(i)];if(s==="cosmos_signDirect")return[Nx(i)];if(s==="wallet_sendCalls")return Ux(i);if(typeof i=="string")return[i];const a=i[o.key];if(_t(a))return s==="solana_signAllTransactions"?a.map(c=>Tx(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn(s,"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,n]of Object.entries(r))for(const s of n)try{await this.onProviderMessageEvent({topic:i,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${s}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(me.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:i,attestation:n,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(ws)?this.client.auth.authKeys.get(ws):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,i,{receiverPublicKey:o,encoding:s===he.link_mode?Br:tt});Qc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:n,transportType:s,encryptedId:bt(i)})):co(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s})),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(wt.expired,async e=>{const{topic:r,id:i}=Tp(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,M("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,M("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(Yr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Yr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!be(e,!1)){const{message:r}=M("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}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=M("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!be(e,!1)){const{message:r}=M("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}=M("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=M("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=M("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(be(e,!1)){const{message:r}=M("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=M("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!dS(e)){const{message:r}=M("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=M("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=M("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}validateRequestExpiry(e){if(e&&!xS(e,aa)){const{message:r}=M("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${aa.min} and ${aa.max}`);throw new Error(r)}}}class PA extends di{constructor(e,r){super(e,r,dA,tu),this.core=e,this.logger=r}}let CA=class extends di{constructor(e,r){super(e,r,pA,tu),this.core=e,this.logger=r}};class BA extends di{constructor(e,r){super(e,r,wA,tu,i=>i.id),this.core=e,this.logger=r}}class TA extends di{constructor(e,r){super(e,r,EA,lo,()=>ws),this.core=e,this.logger=r}}class RA extends di{constructor(e,r){super(e,r,xA,lo),this.core=e,this.logger=r}}class FA extends di{constructor(e,r){super(e,r,_A,lo,i=>i.id),this.core=e,this.logger=r}}var NA=Object.defineProperty,UA=(t,e,r)=>e in t?NA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ca=(t,e,r)=>UA(t,typeof e!="symbol"?e+"":e,r);class kA{constructor(e,r){this.core=e,this.logger=r,ca(this,"authKeys"),ca(this,"pairingTopics"),ca(this,"requests"),this.authKeys=new TA(this.core,this.logger),this.pairingTopics=new RA(this.core,this.logger),this.requests=new FA(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var jA=Object.defineProperty,LA=(t,e,r)=>e in t?jA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,te=(t,e,r)=>LA(t,typeof e!="symbol"?e+"":e,r);class ru extends k8{constructor(e){super(e),te(this,"protocol",a0),te(this,"version",c0),te(this,"name",oa.name),te(this,"metadata"),te(this,"core"),te(this,"logger"),te(this,"events",new St.EventEmitter),te(this,"engine"),te(this,"session"),te(this,"proposal"),te(this,"pendingRequest"),te(this,"auth"),te(this,"signConfig"),te(this,"on",(i,n)=>this.events.on(i,n)),te(this,"once",(i,n)=>this.events.once(i,n)),te(this,"off",(i,n)=>this.events.off(i,n)),te(this,"removeListener",(i,n)=>this.events.removeListener(i,n)),te(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),te(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"update",async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"request",async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"find",i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),te(this,"authenticate",async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}}),te(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),this.name=(e==null?void 0:e.name)||oa.name,this.metadata=$3(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const r=Jc({logger:(e==null?void 0:e.logger)||oa.logger,name:this.name});this.logger=r,this.core=(e==null?void 0:e.core)||new fA(e),this.session=new CA(this.core,this.logger),this.proposal=new PA(this.core,this.logger),this.pendingRequest=new BA(this.core,this.logger),this.engine=new AA(this),this.auth=new kA(this.core,this.logger)}static async init(e){const r=new ru(e);return await r.initialize(),r}get context(){return st(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 MA=ru;var qA=Object.defineProperty,zA=Object.defineProperties,VA=Object.getOwnPropertyDescriptors,lf=Object.getOwnPropertySymbols,HA=Object.prototype.hasOwnProperty,KA=Object.prototype.propertyIsEnumerable,hf=(t,e,r)=>e in t?qA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ff=(t,e)=>{for(var r in e||(e={}))HA.call(e,r)&&hf(t,r,e[r]);if(lf)for(var r of lf(e))KA.call(e,r)&&hf(t,r,e[r]);return t},df=(t,e)=>zA(t,VA(e));const WA={Accept:"application/json","Content-Type":"application/json"},GA="POST",pf={headers:WA,method:GA},gf=10;let l0=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new St.EventEmitter,this.isAvailable=!1,this.registering=!1,!Ch(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=lr(e),i=await(await pu(this.url,df(ff({},pf),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!Ch(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return n(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=lr({id:1,jsonrpc:"2.0",method:"test",params:[]});await pu(e,df(ff({},pf),{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"?si(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=ao(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return jg(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>gf&&this.events.setMaxListeners(gf)}};function iu(t){return t==null||typeof t!="object"&&typeof t!="function"}function h0(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function f0(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const YA="[object RegExp]",d0="[object String]",p0="[object Number]",g0="[object Boolean]",y0="[object Arguments]",ZA="[object Symbol]",JA="[object Date]",XA="[object Map]",QA="[object Set]",e4="[object Array]",t4="[object ArrayBuffer]",r4="[object Object]",i4="[object DataView]",n4="[object Uint8Array]",s4="[object Uint8ClampedArray]",o4="[object Uint16Array]",a4="[object Uint32Array]",c4="[object Int8Array]",u4="[object Int16Array]",l4="[object Int32Array]",h4="[object Float32Array]",f4="[object Float64Array]";function nu(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function d4(t,e){return Di(t,void 0,t,new Map,e)}function Di(t,e,r,i=new Map,n=void 0){const s=n==null?void 0:n(t,e,r,i);if(s!=null)return s;if(iu(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]=Di(t[a],a,r,i,n);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;i.set(t,o);for(const[a,c]of t)o.set(a,Di(c,a,r,i,n));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(Di(a,void 0,r,i,n));return o}if(typeof re<"u"&&re.isBuffer(t))return t.subarray();if(nu(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Di(t[a],a,r,i,n);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return i.set(t,o),Zr(o,t,r,i,n),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),Zr(o,t,r,i,n),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),Zr(o,t,r,i,n),o}if(t instanceof Error){const o=new t.constructor;return i.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Zr(o,t,r,i,n),o}if(typeof t=="object"&&p4(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),Zr(o,t,r,i,n),o}return t}function Zr(t,e,r=t,i,n){const s=[...Object.keys(e),...h0(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Di(e[a],a,r,i,n))}}function p4(t){switch(f0(t)){case y0:case e4:case t4:case i4:case g0:case JA:case h4:case f4:case c4:case u4:case l4:case XA:case p0:case r4:case YA:case QA:case d0:case ZA:case n4:case s4:case o4:case a4:return!0;default:return!1}}function g4(t,e){return d4(t,(r,i,n,s)=>{const o=e==null?void 0:e(r,i,n,s);if(o!=null)return o;if(typeof t=="object")switch(Object.prototype.toString.call(t)){case p0:case d0:case g0:{const a=new t.constructor(t==null?void 0:t.valueOf());return Zr(a,t),a}case y0:{const a={};return Zr(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function yf(t){return g4(t)}function wf(t){return t!==null&&typeof t=="object"&&f0(t)==="[object Arguments]"}function mf(t){return typeof t=="object"&&t!==null}function y4(){}function w4(t){return nu(t)}function m4(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 b4(t){if(iu(t))return t;if(Array.isArray(t)||nu(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 v4(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let n=t;for(let s=0;s<r.length;s++){const o=r[s];n=lc(n,o,i,new Map)}return n}function lc(t,e,r,i){if(iu(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return b4(i.get(e));if(i.set(e,t),Array.isArray(e)){e=e.slice();for(let s=0;s<e.length;s++)e[s]=e[s]??void 0}const n=[...Object.keys(e),...h0(e)];for(let s=0;s<n.length;s++){const o=n[s];let a=e[o],c=t[o];if(wf(a)&&(a={...a}),wf(c)&&(c={...c}),typeof re<"u"&&re.isBuffer(a)&&(a=yf(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],h=Reflect.ownKeys(c);for(let f=0;f<h.length;f++){const d=h[f];l[d]=c[d]}c=l}else c=[];const u=r(c,a,o,t,e,i);u!=null?t[o]=u:Array.isArray(a)||mf(c)&&mf(a)?t[o]=lc(c,a,r,i):c==null&&m4(a)?t[o]=lc({},a,r,i):c==null&&w4(a)?t[o]=yf(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function E4(t,...e){return v4(t,...e,y4)}const bf="error",x4="wss://relay.walletconnect.org",_4="wc",w0="universal_provider",ss=`${_4}@2:${w0}:`,m0="https://rpc.walletconnect.org/v1/",b0="generic",I4=`${m0}bundler`,Ti="call_status",S4=86400,su={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var $4=Object.defineProperty,O4=Object.defineProperties,D4=Object.getOwnPropertyDescriptors,vf=Object.getOwnPropertySymbols,A4=Object.prototype.hasOwnProperty,P4=Object.prototype.propertyIsEnumerable,Ef=(t,e,r)=>e in t?$4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,os=(t,e)=>{for(var r in e||(e={}))A4.call(e,r)&&Ef(t,r,e[r]);if(vf)for(var r of vf(e))P4.call(e,r)&&Ef(t,r,e[r]);return t},C4=(t,e)=>O4(t,D4(e));function v0(t,e,r){var i;const n=cr(t);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${m0}?chainId=${n.namespace}:${n.reference}&projectId=${r}`}function B4(t){return t.includes(":")?t.split(":")[1]:t}function E0(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function T4(t,e){const r=Object.keys(e.namespaces).filter(n=>n.includes(t));if(!r.length)return[];const i=[];return r.forEach(n=>{const s=e.namespaces[n].accounts;i.push(...s)}),i}function xf(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>{var i,n;return((i=r==null?void 0:r.chains)==null?void 0:i.length)&&((n=r==null?void 0:r.chains)==null?void 0:n.length)>0}))}function as(t={},e={}){const r=xf(_f(t)),i=xf(_f(e));return E4(r,i)}function _f(t){var e,r,i,n,s;const o={};if(!Ht(t))return o;for(const[a,c]of Object.entries(t)){const u=oo(a)?[a]:c.chains,l=c.methods||[],h=c.events||[],f=c.rpcMap||{},d=Oi(a);o[d]=C4(os(os({},o[d]),c),{chains:Vt(u,(e=o[d])==null?void 0:e.chains),methods:Vt(l,(r=o[d])==null?void 0:r.methods),events:Vt(h,(i=o[d])==null?void 0:i.events)}),(Ht(f)||Ht(((n=o[d])==null?void 0:n.rpcMap)||{}))&&(o[d].rpcMap=os(os({},f),(s=o[d])==null?void 0:s.rpcMap))}return o}function If(t){return t.includes(":")?t.split(":")[2]:t}function Sf(t){const e={};for(const[r,i]of Object.entries(t)){const n=i.methods||[],s=i.events||[],o=i.accounts||[],a=oo(r)?[r]:i.chains?i.chains:E0(i.accounts);e[r]={chains:a,methods:n,events:s,accounts:o}}return e}function ua(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 R4(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const x0={},Ri=t=>x0[t],la=(t,e)=>{x0[t]=e};var F4=Object.defineProperty,$f=Object.getOwnPropertySymbols,N4=Object.prototype.hasOwnProperty,U4=Object.prototype.propertyIsEnumerable,Of=(t,e,r)=>e in t?F4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Df=(t,e)=>{for(var r in e||(e={}))N4.call(e,r)&&Of(t,r,e[r]);if($f)for(var r of $f(e))U4.call(e,r)&&Of(t,r,e[r]);return t};const Af="eip155",k4=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],j4=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,ha=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,Pf=t=>Object.keys(t).filter(e=>k4.includes(e)).reduce((e,r)=>(e[r]=L4(t[r]),e),{}),L4=t=>typeof t=="string"&&R4(t)?JSON.parse(t):t,M4=(t,e,r)=>{const{sessionProperties:i={},scopedProperties:n={}}=t,s={};if(!Ht(n)&&!Ht(i))return;const o=Pf(i);for(const a of r){const c=j4(a);if(!c)continue;s[ha(c)]=o;const u=n==null?void 0:n[`${Af}:${c}`];if(u){const l=u==null?void 0:u[`${Af}:${c}:${e}`];s[ha(c)]=Df(Df({},s[ha(c)]),Pf(l||u))}}for(const[a,c]of Object.entries(s))Object.keys(c).length===0&&delete s[a];return Object.keys(s).length>0?s:void 0};var q4=Object.defineProperty,z4=(t,e,r)=>e in t?q4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,V4=(t,e,r)=>z4(t,typeof e!="symbol"?e+"":e,r);let fa,H4=class _0{constructor(e){V4(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 fa||(fa=new _0(e)),fa}};var K4=Object.defineProperty,W4=Object.defineProperties,G4=Object.getOwnPropertyDescriptors,Cf=Object.getOwnPropertySymbols,Y4=Object.prototype.hasOwnProperty,Z4=Object.prototype.propertyIsEnumerable,Bf=(t,e,r)=>e in t?K4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,J4=(t,e)=>{for(var r in e||(e={}))Y4.call(e,r)&&Bf(t,r,e[r]);if(Cf)for(var r of Cf(e))Z4.call(e,r)&&Bf(t,r,e[r]);return t},X4=(t,e)=>W4(t,G4(e));async function Q4(t,e){const r=cr(t.result.capabilities.caip345.caip2),i=t.result.capabilities.caip345.transactionHashes,n=await Promise.allSettled(i.map(h=>eP(r.reference,h,e))),s=n.filter(h=>h.status==="fulfilled").map(h=>h.value).filter(h=>h);n.filter(h=>h.status==="rejected").forEach(h=>console.warn("Failed to fetch transaction receipt:",h.reason));const o=!s.length||s.some(h=>!h),a=s.every(h=>(h==null?void 0:h.status)==="0x1"),c=s.every(h=>(h==null?void 0:h.status)==="0x0"),u=s.some(h=>(h==null?void 0:h.status)==="0x0");let l;return o?l=100:a?l=200:c?l=500:u&&(l=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:s,status:l}}async function eP(t,e,r){return await r(parseInt(t)).request(Ct("eth_getTransactionReceipt",[e]))}async function tP({sendCalls:t,storage:e}){const r=await e.getItem(Ti);await e.setItem(Ti,X4(J4({},r),{[t.result.id]:{request:t.request,result:t.result,expiry:we(S4)}}))}async function rP({resultId:t,storage:e}){const r=await e.getItem(Ti);if(r){delete r[t],await e.setItem(Ti,r);for(const i in r)qt(r[i].expiry)&&delete r[i];await e.setItem(Ti,r)}}async function iP({resultId:t,storage:e}){const r=await e.getItem(Ti),i=r==null?void 0:r[t];if(i&&!qt(i.expiry))return i;await rP({resultId:t,storage:e})}var nP=Object.defineProperty,sP=Object.defineProperties,oP=Object.getOwnPropertyDescriptors,Tf=Object.getOwnPropertySymbols,aP=Object.prototype.hasOwnProperty,cP=Object.prototype.propertyIsEnumerable,hc=(t,e,r)=>e in t?nP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,da=(t,e)=>{for(var r in e||(e={}))aP.call(e,r)&&hc(t,r,e[r]);if(Tf)for(var r of Tf(e))cP.call(e,r)&&hc(t,r,e[r]);return t},pa=(t,e)=>sP(t,oP(e)),Hr=(t,e,r)=>hc(t,typeof e!="symbol"?e+"":e,r);class uP{constructor(e){Hr(this,"name","eip155"),Hr(this,"client"),Hr(this,"chainId"),Hr(this,"namespace"),Hr(this,"httpProviders"),Hr(this,"events"),Hr(this,"storage"),this.namespace=e.namespace,this.events=Ri("events"),this.client=Ri("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=H4.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(su.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||v0(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new eu(new l0(i,Ri("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=parseInt(B4(r));e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(e){const r=e||this.chainId;return this.httpProviders[r]||(this.httpProviders=pa(da({},this.httpProviders),{[r]:this.createHttpProvider(r)}),this.httpProviders[r])}async handleSwitchChain(e){var r,i;let n=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";n=n.startsWith("0x")?n:`0x${n}`;const s=parseInt(n,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:n}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var r,i,n,s,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0],c=((s=(n=e.request)==null?void 0:n.params)==null?void 0:s[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const u=this.client.session.get(e.topic),l=((o=u==null?void 0:u.sessionProperties)==null?void 0:o.capabilities)||{},h=`${a}${c.join(",")}`,f=l==null?void 0:l[h];if(f)return f;let d;try{d=M4(u,a,c)}catch(g){console.warn("Failed to extract capabilities from session",g)}if(d)return d;const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:pa(da({},u.sessionProperties||{}),{capabilities:pa(da({},l||{}),{[h]:p})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return p}async getCallStatus(e){var r,i,n;const s=this.client.session.get(e.topic),o=(r=s.sessionProperties)==null?void 0:r.bundler_name;if(o){const u=this.getBundlerUrl(e.chainId,o);try{return await this.getUserOperationReceipt(u,e)}catch(l){console.warn("Failed to fetch call status from bundler",l,u)}}const a=(i=s.sessionProperties)==null?void 0:i.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(u){console.warn("Failed to fetch call status from custom bundler",u,a)}const c=await iP({resultId:(n=e.request.params)==null?void 0:n[0],storage:this.storage});if(c)try{return await Q4(c,this.getHttpProvider.bind(this))}catch(u){console.warn("Failed to fetch call status from stored send calls",u,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 n=new URL(e),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ct("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,r){return`${I4}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}async sendCalls(e){var r,i,n;const s=await this.client.request(e),o=(r=e.request.params)==null?void 0:r[0],a=s==null?void 0:s.id,c=(s==null?void 0:s.capabilities)||{},u=(i=c==null?void 0:c.caip345)==null?void 0:i.caip2,l=(n=c==null?void 0:c.caip345)==null?void 0:n.transactionHashes;return!a||!u||!(l!=null&&l.length)||await tP({sendCalls:{request:o,result:s},storage:this.storage}),s}}var lP=Object.defineProperty,hP=(t,e,r)=>e in t?lP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_i=(t,e,r)=>hP(t,typeof e!="symbol"?e+"":e,r);class fP{constructor(e){_i(this,"name",b0),_i(this,"client"),_i(this,"httpProviders"),_i(this,"events"),_i(this,"namespace"),_i(this,"chainId"),this.namespace=e.namespace,this.events=Ri("events"),this.client=Ri("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(su.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(n=>{var s,o;const a=cr(n),c=(o=(s=this.namespace)==null?void 0:s.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];i[a.reference]=this.createHttpProvider(n,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||v0(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new eu(new l0(i,Ri("disableProviderPing")))}}var dP=Object.defineProperty,pP=Object.defineProperties,gP=Object.getOwnPropertyDescriptors,Rf=Object.getOwnPropertySymbols,yP=Object.prototype.hasOwnProperty,wP=Object.prototype.propertyIsEnumerable,fc=(t,e,r)=>e in t?dP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sn=(t,e)=>{for(var r in e||(e={}))yP.call(e,r)&&fc(t,r,e[r]);if(Rf)for(var r of Rf(e))wP.call(e,r)&&fc(t,r,e[r]);return t},cs=(t,e)=>pP(t,gP(e)),at=(t,e,r)=>fc(t,typeof e!="symbol"?e+"":e,r);class ou{constructor(e){at(this,"client"),at(this,"namespaces"),at(this,"optionalNamespaces"),at(this,"sessionProperties"),at(this,"scopedProperties"),at(this,"events",new pc),at(this,"rpcProviders",{}),at(this,"session"),at(this,"providerOpts"),at(this,"logger"),at(this,"uri"),at(this,"disableProviderPing",!1),at(this,"connectParams");var r,i;this.providerOpts=e,this.logger=Jc({logger:(r=e.logger)!=null?r:bf,name:(i=this.providerOpts.name)!=null?i:w0}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const r=new ou(e);return await r.initialize(),r}async request(e,r,i){const[n,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:sn({},e),chainId:`${n}:${s}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,n){const s=new Date().getTime();this.request(e,i,n).then(o=>r(null,$n(s,o))).catch(o=>r(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:fe("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:n}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const s=await n();if(this.session=s.session,this.session){const o=Sf(this.session.namespaces);this.namespaces=as(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){var r,i;const{uri:n,approval:s}=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});n&&(this.uri=n,this.events.emit("display_uri",n));const o=await s();this.session=o;const a=Sf(o.namespaces);return this.namespaces=as(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,n]=this.validateChain(e);this.getProvider(i).setDefaultChain(n,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(!_t(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 MA.init({core:this.providerOpts.core,logger:this.providerOpts.logger||bf,relayUrl:this.providerOpts.relayUrl||x4,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=>Oi(r)))];la("client",this.client),la("events",this.events),la("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=T4(r,this.session);if((i==null?void 0:i.length)===0)return;const n=E0(i),s=as(this.namespaces,this.optionalNamespaces),o=cs(sn({},s[r]),{accounts:i,chains:n});switch(r){case"eip155":this.rpcProviders[r]=new uP({namespace:o});break;default:this.rpcProviders[r]=new fP({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var r;const{topic:i}=e;i===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:i,topic:n}=e;if(n!==((r=this.session)==null?void 0:r.topic))return;const{event:s}=i;if(s.name==="accountsChanged"){const o=s.data;o&&_t(o)&&this.events.emit("accountsChanged",o.map(If))}else if(s.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=Oi(o),u=ua(o)!==ua(a)?`${c}:${ua(a)}`:o;this.onChainChanged({currentCaipChainId:u})}else this.events.emit(s.name,s.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var i,n;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:s}=r,o=(n=this.client)==null?void 0:n.session.get(e);this.session=cs(sn({},o),{namespaces:s}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{var r;e.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",cs(sn({},fe("USER_DISCONNECTED")),{data:e.topic})))}),this.on(su.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(cs(sn({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[b0]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r={},optionalNamespaces:i={},sessionProperties:n,scopedProperties:s}=e;this.optionalNamespaces=as(r,i),this.sessionProperties=n,this.scopedProperties=s}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=>Oi(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const n=Oi(Object.keys(this.namespaces)[0]),s=this.rpcProviders[n].getDefaultChain();return[n,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:r,internal:i=!1}){if(!this.namespaces)return;const[n,s]=this.validateChain(e);s&&(this.updateNamespaceChain(n,s),i?(this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:n,currentCaipChainId:e,previousCaipChainId:r})):this.getProvider(n).setDefaultChain(s),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:r,previousCaipChainId:i}){var n,s;try{if(i===r)return;const o=(s=(n=this.session)==null?void 0:n.namespaces[e])==null?void 0:s.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${r}:`)).map(If);if(!_t(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}`,n={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=n}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.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 n=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${ss}/${e}${n}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${ss}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${ss}/${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(ss)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn(r,"Failed to cleanup storage")}}}const mP=ou,bP="wc",vP="ethereum_provider",EP=`${bP}@2:${vP}:`,xP="https://rpc.walletconnect.org/v1/",ks=["eth_sendTransaction","personal_sign"],I0=["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"],js=["chainChanged","accountsChanged"],S0=["chainChanged","accountsChanged","message","disconnect","connect"],_P=async()=>{const{createAppKit:t}=await F0(()=>import("./core-1eadecee.js").then(e=>e.ad),["assets/core-1eadecee.js","assets/index-76a72ce6.js","assets/index-471effde.css"]);return t};var IP=Object.defineProperty,SP=Object.defineProperties,$P=Object.getOwnPropertyDescriptors,Ff=Object.getOwnPropertySymbols,OP=Object.prototype.hasOwnProperty,DP=Object.prototype.propertyIsEnumerable,dc=(t,e,r)=>e in t?IP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wr=(t,e)=>{for(var r in e||(e={}))OP.call(e,r)&&dc(t,r,e[r]);if(Ff)for(var r of Ff(e))DP.call(e,r)&&dc(t,r,e[r]);return t},on=(t,e)=>SP(t,$P(e)),ct=(t,e,r)=>dc(t,typeof e!="symbol"?e+"":e,r);function Ls(t){return Number(t[0].split(":")[1])}function us(t){return`0x${t.toString(16)}`}function AP(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:n,events:s,optionalEvents:o,rpcMap:a}=t;if(!_t(e))throw new Error("Invalid chains");const c={chains:e,methods:i||ks,events:s||js,rpcMap:Wr({},e.length?{[Ls(e)]:a[Ls(e)]}:{})},u=s==null?void 0:s.filter(d=>!js.includes(d)),l=i==null?void 0:i.filter(d=>!ks.includes(d));if(!r&&!o&&!n&&!(u!=null&&u.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const h=(u==null?void 0:u.length)&&(l==null?void 0:l.length)||!r,f={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(n!=null&&n.length?n:I0))],events:[...new Set(c.events.concat(o!=null&&o.length?o:S0))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?f:void 0}}class ho{constructor(){ct(this,"events",new St.EventEmitter),ct(this,"namespace","eip155"),ct(this,"accounts",[]),ct(this,"signer"),ct(this,"chainId",1),ct(this,"modal"),ct(this,"rpc"),ct(this,"STORAGE_KEY",EP),ct(this,"on",(e,r)=>(this.events.on(e,r),this)),ct(this,"once",(e,r)=>(this.events.once(e,r),this)),ct(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),ct(this,"off",(e,r)=>(this.events.off(e,r),this)),ct(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new ho;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:n}=AP(this.rpc);try{const s=await new Promise(async(a,c)=>{var u,l;this.rpc.showQrModal&&((u=this.modal)==null||u.open(),(l=this.modal)==null||l.subscribeState(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(on(Wr({namespaces:Wr({},i&&{[this.namespace]:i})},n&&{optionalNamespaces:{[this.namespace]:n}}),{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(!s)return;const o=Il(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:us(this.chainId)})}catch(s){throw this.signer.logger.error(s),s}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const n=await new Promise(async(o,a)=>{var c,u;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(u=this.modal)==null||u.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(on(Wr({},e),{chains:this.rpc.chains}),r).then(l=>{o(l)}).catch(l=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),s=n.session;if(s){const o=Il(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:us(this.chainId)})}return n}catch(n){throw this.signer.logger.error(n),n}finally{(i=this.modal)==null||i.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:i}=r;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",us(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",on(Wr({},fe("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",us(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,i,n]=e.split(":");return{chainId:`${r}:${i}`,address:n}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,i;const n=(r=e==null?void 0:e.chains)!=null?r:[],s=(i=e==null?void 0:e.optionalChains)!=null?i:[],o=n.concat(s);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=n.length?(e==null?void 0:e.methods)||ks:[],c=n.length?(e==null?void 0:e.events)||js:[],u=(e==null?void 0:e.optionalMethods)||[],l=(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:n==null?void 0:n.map(d=>this.formatChainId(d)),optionalChains:s.map(d=>this.formatChainId(d)),methods:a,events:c,optionalMethods:u,optionalEvents:l,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:f,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(n=>{i[n]=this.getRpcUrl(n,r)}),i}async initialize(e){var r;if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Ls(this.rpc.chains):Ls(this.rpc.optionalChains),this.signer=await mP.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 n=await _P(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return LP}),o=s(on(Wr({},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=n(on(Wr({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((r=this.rpc.qrModalOptions)==null?void 0:r.enableMobileFullScreen)===!0}))}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(i)try{this.modal=i}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:n}=e;r&&_t(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)})),i&&_t(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(s=>this.formatChainId(s)),i.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${xP}?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 PP=ho;var CP=Object.defineProperty,BP=Object.defineProperties,TP=Object.getOwnPropertyDescriptors,Nf=Object.getOwnPropertySymbols,RP=Object.prototype.hasOwnProperty,FP=Object.prototype.propertyIsEnumerable,Uf=(t,e,r)=>e in t?CP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$0=(t,e)=>{for(var r in e||(e={}))RP.call(e,r)&&Uf(t,r,e[r]);if(Nf)for(var r of Nf(e))FP.call(e,r)&&Uf(t,r,e[r]);return t},NP=(t,e)=>BP(t,TP(e));function UP(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 kP=t=>{const[e,r]=t.split(":");return O0({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function jP(t){var e,r,i,n,s,o,a;const c=(e=t.chains)==null?void 0:e.map(kP).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const u=c.find(h=>{var f;return h.id===((f=t.defaultChain)==null?void 0:f.id)}),l={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:UP(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:u,metadata:NP($0({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((i=t.metadata)==null?void 0:i.description)||"Connect to WalletConnect-compatible wallets",url:((n=t.metadata)==null?void 0:n.url)||"https://walletconnect.org",icons:((s=t.metadata)==null?void 0:s.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:t.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(t.explorerRecommendedWalletIds)?t.explorerRecommendedWalletIds:[],excludeWalletIds:t.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(t.explorerExcludedWalletIds)?t.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=t.mobileWallets)!=null&&o.length||(a=t.desktopWallets)!=null&&a.length){const h=[...(t.mobileWallets||[]).map(p=>({id:p.id,name:p.name,links:p.links})),...(t.desktopWallets||[]).map(p=>({id:p.id,name:p.name,links:{native:p.links.native,universal:p.links.universal}}))],f=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],d=h.filter(p=>!f.includes(p.id));d.length&&(l.customWallets=d)}return l}function O0(t){return $0({formatters:void 0,fees:void 0,serializers:void 0},t)}var LP=Object.freeze({__proto__:null,convertWCMToAppKitOptions:jP,defineChain:O0});const P5=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:PP,OPTIONAL_EVENTS:S0,OPTIONAL_METHODS:I0,REQUIRED_EVENTS:js,REQUIRED_METHODS:ks,default:ho},Symbol.toStringTag,{value:"Module"}));export{D$ as A,Qc as B,dE as C,u3 as D,co as E,$n as F,hi as G,Ct as H,li as I,y2 as J,Rr as K,ao as L,Mt as M,vt as N,Lt as O,pl as P,sp as Q,l0 as R,P5 as S,dt as X,Dp as Y,n8 as a,s8 as b,Ng as c,is as d,o8 as e,si as f,Ih as g,qf as h,L as i,Et as j,c8 as k,ii as l,gc as m,An as n,_1 as o,p1 as p,SE as q,V0 as r,lr as s,nt as t,Mf as u,fn as v,Ca as w,st as x,jS as y,eu as z};