const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CsgMMSKv.js","assets/index-CXyQ5sGC.js","assets/lodash-CQGrF3PQ.js","assets/index-D5c7CNr0.css","assets/index-Vmx-EkLq.js"])))=>i.map(i=>d[i]); import{_ as j0}from"./index-CXyQ5sGC.js";import{e as ar,$ as Oa}from"./events-C8x43ppJ.js";import{c as Q,b as q0,w as Il,r as xl,f as Ra,t as Sn,a as L0,d as Qr,V as M0,M as z0,N as K,k as U0,e as ha,g as k0,K as H0,A as K0,q as lh,x as V0,H as B0,F as F0,h as fh,$ as G0,p as W0,J as J0,u as gs,i as ph,X as Q0,n as Y0,_ as Pl,j as dr,I as Z0,l as dh,m as Di,y as We,U as St,o as Jr,s as Ut,v as X0,z as ji,B as Sl,C as ew,D as tw,E as rw,G as Ol,L as iw,O as Rl,P as Al,Q as Li,R as la,S as bn,T as zi,W as sw,Y as _n,Z as nw,a0 as ow,a1 as aw,a2 as cw,a3 as pn,a4 as uw,a5 as hw,a6 as Wo,a7 as gh,a8 as lw,a9 as fw,aa as pw,ab as yh,ac as dw,ad as gw,ae as yw,af as vw,ag as mw,ah as ww,ai as bw,aj as ls,ak as Cl,al as Jo,am as _w,an as Ew}from"./WagmiConf-Z8jx5cTB.js";import{O as On,g as Aa,F as li,$ as Iw}from"./lodash-CQGrF3PQ.js";import"./index-Vmx-EkLq.js";import"./index-FnRUSmLt.js";import"./___vite-browser-external_commonjs-proxy-DoZ_vOnO.js";import"./walletConnect-CiycSUBb.js";const xw=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,Pw=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,Sw=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function Ow(a,t){if(a==="__proto__"||a==="constructor"&&t&&typeof t=="object"&&"prototype"in t){Rw(a);return}return t}function Rw(a){console.warn(`[destr] Dropping "${a}" key to prevent prototype pollution.`)}function dn(a,t={}){if(typeof a!="string")return a;const r=a.trim();if(a[0]==='"'&&a.endsWith('"')&&!a.includes("\\"))return r.slice(1,-1);if(r.length<=9){const s=r.toLowerCase();if(s==="true")return!0;if(s==="false")return!1;if(s==="undefined")return;if(s==="null")return null;if(s==="nan")return Number.NaN;if(s==="infinity")return Number.POSITIVE_INFINITY;if(s==="-infinity")return Number.NEGATIVE_INFINITY}if(!Sw.test(a)){if(t.strict)throw new SyntaxError("[destr] Invalid JSON");return a}try{if(xw.test(a)||Pw.test(a)){if(t.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(a,Ow)}return JSON.parse(a)}catch(s){if(t.strict)throw s;return a}}function Aw(a){return!a||typeof a.then!="function"?Promise.resolve(a):a}function mt(a,...t){try{return Aw(a(...t))}catch(r){return Promise.reject(r)}}function Cw(a){const t=typeof a;return a===null||t!=="object"&&t!=="function"}function $w(a){const t=Object.getPrototypeOf(a);return!t||t.isPrototypeOf(Object)}function En(a){if(Cw(a))return String(a);if($w(a)||Array.isArray(a))return JSON.stringify(a);if(typeof a.toJSON=="function")return En(a.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function $l(){if(typeof Buffer>"u")throw new TypeError("[unstorage] Buffer is not supported!")}const fa="base64:";function Tw(a){if(typeof a=="string")return a;$l();const t=Buffer.from(a).toString("base64");return fa+t}function Nw(a){return typeof a!="string"||!a.startsWith(fa)?a:($l(),Buffer.from(a.slice(fa.length),"base64"))}function zt(a){return a?a.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function Dw(...a){return zt(a.join(":"))}function gn(a){return a=zt(a),a?a+":":""}const jw="memory",qw=()=>{const a=new Map;return{name:jw,getInstance:()=>a,hasItem(t){return a.has(t)},getItem(t){return a.get(t)??null},getItemRaw(t){return a.get(t)??null},setItem(t,r){a.set(t,r)},setItemRaw(t,r){a.set(t,r)},removeItem(t){a.delete(t)},getKeys(){return[...a.keys()]},clear(){a.clear()},dispose(){a.clear()}}};function Lw(a={}){const t={mounts:{"":a.driver||qw()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=p=>{for(const w of t.mountpoints)if(p.startsWith(w))return{base:w,relativeKey:p.slice(w.length),driver:t.mounts[w]};return{base:"",relativeKey:p,driver:t.mounts[""]}},s=(p,w)=>t.mountpoints.filter(I=>I.startsWith(p)||w&&p.startsWith(I)).map(I=>({relativeBase:p.length>I.length?p.slice(I.length):void 0,mountpoint:I,driver:t.mounts[I]})),o=(p,w)=>{if(t.watching){w=zt(w);for(const I of t.watchListeners)I(p,w)}},u=async()=>{if(!t.watching){t.watching=!0;for(const p in t.mounts)t.unwatch[p]=await vh(t.mounts[p],o,p)}},f=async()=>{if(t.watching){for(const p in t.unwatch)await t.unwatch[p]();t.unwatch={},t.watching=!1}},y=(p,w,I)=>{const R=new Map,$=O=>{let B=R.get(O.base);return B||(B={driver:O.driver,base:O.base,items:[]},R.set(O.base,B)),B};for(const O of p){const B=typeof O=="string",X=zt(B?O:O.key),ie=B?void 0:O.value,he=B||!O.options?w:{...w,...O.options},re=r(X);$(re).items.push({key:X,value:ie,relativeKey:re.relativeKey,options:he})}return Promise.all([...R.values()].map(O=>I(O))).then(O=>O.flat())},v={hasItem(p,w={}){p=zt(p);const{relativeKey:I,driver:R}=r(p);return mt(R.hasItem,I,w)},getItem(p,w={}){p=zt(p);const{relativeKey:I,driver:R}=r(p);return mt(R.getItem,I,w).then($=>dn($))},getItems(p,w){return y(p,w,I=>I.driver.getItems?mt(I.driver.getItems,I.items.map(R=>({key:R.relativeKey,options:R.options})),w).then(R=>R.map($=>({key:Dw(I.base,$.key),value:dn($.value)}))):Promise.all(I.items.map(R=>mt(I.driver.getItem,R.relativeKey,R.options).then($=>({key:R.key,value:dn($)})))))},getItemRaw(p,w={}){p=zt(p);const{relativeKey:I,driver:R}=r(p);return R.getItemRaw?mt(R.getItemRaw,I,w):mt(R.getItem,I,w).then($=>Nw($))},async setItem(p,w,I={}){if(w===void 0)return v.removeItem(p);p=zt(p);const{relativeKey:R,driver:$}=r(p);$.setItem&&(await mt($.setItem,R,En(w),I),$.watch||o("update",p))},async setItems(p,w){await y(p,w,async I=>{if(I.driver.setItems)return mt(I.driver.setItems,I.items.map(R=>({key:R.relativeKey,value:En(R.value),options:R.options})),w);I.driver.setItem&&await Promise.all(I.items.map(R=>mt(I.driver.setItem,R.relativeKey,En(R.value),R.options)))})},async setItemRaw(p,w,I={}){if(w===void 0)return v.removeItem(p,I);p=zt(p);const{relativeKey:R,driver:$}=r(p);if($.setItemRaw)await mt($.setItemRaw,R,w,I);else if($.setItem)await mt($.setItem,R,Tw(w),I);else return;$.watch||o("update",p)},async removeItem(p,w={}){typeof w=="boolean"&&(w={removeMeta:w}),p=zt(p);const{relativeKey:I,driver:R}=r(p);R.removeItem&&(await mt(R.removeItem,I,w),(w.removeMeta||w.removeMata)&&await mt(R.removeItem,I+"$",w),R.watch||o("remove",p))},async getMeta(p,w={}){typeof w=="boolean"&&(w={nativeOnly:w}),p=zt(p);const{relativeKey:I,driver:R}=r(p),$=Object.create(null);if(R.getMeta&&Object.assign($,await mt(R.getMeta,I,w)),!w.nativeOnly){const O=await mt(R.getItem,I+"$",w).then(B=>dn(B));O&&typeof O=="object"&&(typeof O.atime=="string"&&(O.atime=new Date(O.atime)),typeof O.mtime=="string"&&(O.mtime=new Date(O.mtime)),Object.assign($,O))}return $},setMeta(p,w,I={}){return this.setItem(p+"$",w,I)},removeMeta(p,w={}){return this.removeItem(p+"$",w)},async getKeys(p,w={}){p=gn(p);const I=s(p,!0);let R=[];const $=[];for(const O of I){const B=await mt(O.driver.getKeys,O.relativeBase,w);for(const X of B){const ie=O.mountpoint+zt(X);R.some(he=>ie.startsWith(he))||$.push(ie)}R=[O.mountpoint,...R.filter(X=>!X.startsWith(O.mountpoint))]}return p?$.filter(O=>O.startsWith(p)&&O[O.length-1]!=="$"):$.filter(O=>O[O.length-1]!=="$")},async clear(p,w={}){p=gn(p),await Promise.all(s(p,!1).map(async I=>{if(I.driver.clear)return mt(I.driver.clear,I.relativeBase,w);if(I.driver.removeItem){const R=await I.driver.getKeys(I.relativeBase||"",w);return Promise.all(R.map($=>I.driver.removeItem($,w)))}}))},async dispose(){await Promise.all(Object.values(t.mounts).map(p=>mh(p)))},async watch(p){return await u(),t.watchListeners.push(p),async()=>{t.watchListeners=t.watchListeners.filter(w=>w!==p),t.watchListeners.length===0&&await f()}},async unwatch(){t.watchListeners=[],await f()},mount(p,w){if(p=gn(p),p&&t.mounts[p])throw new Error(`already mounted at ${p}`);return p&&(t.mountpoints.push(p),t.mountpoints.sort((I,R)=>R.length-I.length)),t.mounts[p]=w,t.watching&&Promise.resolve(vh(w,o,p)).then(I=>{t.unwatch[p]=I}).catch(console.error),v},async unmount(p,w=!0){p=gn(p),!(!p||!t.mounts[p])&&(t.watching&&p in t.unwatch&&(t.unwatch[p](),delete t.unwatch[p]),w&&await mh(t.mounts[p]),t.mountpoints=t.mountpoints.filter(I=>I!==p),delete t.mounts[p])},getMount(p=""){p=zt(p)+":";const w=r(p);return{driver:w.driver,base:w.base}},getMounts(p="",w={}){return p=zt(p),s(p,w.parents).map(R=>({driver:R.driver,base:R.mountpoint}))},keys:(p,w={})=>v.getKeys(p,w),get:(p,w={})=>v.getItem(p,w),set:(p,w,I={})=>v.setItem(p,w,I),has:(p,w={})=>v.hasItem(p,w),del:(p,w={})=>v.removeItem(p,w),remove:(p,w={})=>v.removeItem(p,w)};return v}function vh(a,t,r){return a.watch?a.watch((s,o)=>t(s,r+o)):()=>{}}async function mh(a){typeof a.dispose=="function"&&await mt(a.dispose)}function pi(a){return new Promise((t,r)=>{a.oncomplete=a.onsuccess=()=>t(a.result),a.onabort=a.onerror=()=>r(a.error)})}function Tl(a,t){const r=indexedDB.open(a);r.onupgradeneeded=()=>r.result.createObjectStore(t);const s=pi(r);return(o,u)=>s.then(f=>u(f.transaction(t,o).objectStore(t)))}let Qo;function bs(){return Qo||(Qo=Tl("keyval-store","keyval")),Qo}function wh(a,t=bs()){return t("readonly",r=>pi(r.get(a)))}function Mw(a,t,r=bs()){return r("readwrite",s=>(s.put(t,a),pi(s.transaction)))}function zw(a,t=bs()){return t("readwrite",r=>(r.delete(a),pi(r.transaction)))}function Uw(a=bs()){return a("readwrite",t=>(t.clear(),pi(t.transaction)))}function kw(a,t){return a.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},pi(a.transaction)}function Hw(a=bs()){return a("readonly",t=>{if(t.getAllKeys)return pi(t.getAllKeys());const r=[];return kw(t,s=>r.push(s.key)).then(()=>r)})}const Kw=a=>JSON.stringify(a,(t,r)=>typeof r=="bigint"?r.toString()+"n":r),Vw=a=>{const t=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=a.replace(t,'$1"$2n"$3');return JSON.parse(r,(s,o)=>typeof o=="string"&&o.match(/^\d+n$/)?BigInt(o.substring(0,o.length-1)):o)};function _s(a){if(typeof a!="string")throw new Error(`Cannot safe json parse value of type ${typeof a}`);try{return Vw(a)}catch{return a}}function fi(a){return typeof a=="string"?a:Kw(a)||""}const Bw="idb-keyval";var Fw=(a={})=>{const t=a.base&&a.base.length>0?`${a.base}:`:"",r=o=>t+o;let s;return a.dbName&&a.storeName&&(s=Tl(a.dbName,a.storeName)),{name:Bw,options:a,async hasItem(o){return!(typeof await wh(r(o),s)>"u")},async getItem(o){return await wh(r(o),s)??null},setItem(o,u){return Mw(r(o),u,s)},removeItem(o){return zw(r(o),s)},getKeys(){return Hw(s)},clear(){return Uw(s)}}};const Gw="WALLET_CONNECT_V2_INDEXED_DB",Ww="keyvaluestorage";let Jw=class{constructor(){this.indexedDb=Lw({driver:Fw({dbName:Gw,storeName:Ww})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(t=>[t.key,t.value])}async getItem(t){const r=await this.indexedDb.getItem(t);if(r!==null)return r}async setItem(t,r){await this.indexedDb.setItem(t,fi(r))}async removeItem(t){await this.indexedDb.removeItem(t)}};var Yo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},In={exports:{}};(function(){let a;function t(){}a=t,a.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},a.prototype.setItem=function(r,s){this[r]=String(s)},a.prototype.removeItem=function(r){delete this[r]},a.prototype.clear=function(){const r=this;Object.keys(r).forEach(function(s){r[s]=void 0,delete r[s]})},a.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},a.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof Yo<"u"&&Yo.localStorage?In.exports=Yo.localStorage:typeof window<"u"&&window.localStorage?In.exports=window.localStorage:In.exports=new t})();function Qw(a){var t;return[a[0],_s((t=a[1])!=null?t:"")]}class Yw{constructor(){this.localStorage=In.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(Qw)}async getItem(t){const r=this.localStorage.getItem(t);if(r!==null)return _s(r)}async setItem(t,r){this.localStorage.setItem(t,fi(r))}async removeItem(t){this.localStorage.removeItem(t)}}const Zw="wc_storage_version",bh=1,Xw=async(a,t,r)=>{const s=Zw,o=await t.getItem(s);if(o&&o>=bh){r(t);return}const u=await a.getKeys();if(!u.length){r(t);return}const f=[];for(;u.length;){const y=u.shift();if(!y)continue;const v=y.toLowerCase();if(v.includes("wc@")||v.includes("walletconnect")||v.includes("wc_")||v.includes("wallet_connect")){const p=await a.getItem(y);await t.setItem(y,p),f.push(y)}}await t.setItem(s,bh),r(t),eb(a,f)},eb=async(a,t)=>{t.length&&t.forEach(async r=>{await a.removeItem(r)})};let tb=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const t=new Yw;this.storage=t;try{const r=new Jw;Xw(t,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(t){return await this.initialize(),this.storage.getItem(t)}async setItem(t,r){return await this.initialize(),this.storage.setItem(t,r)}async removeItem(t){return await this.initialize(),this.storage.removeItem(t)}async initialize(){this.initialized||await new Promise(t=>{const r=setInterval(()=>{this.initialized&&(clearInterval(r),t())},20)})}};var Ui={};/*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */var pa=function(a,t){return pa=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)s.hasOwnProperty(o)&&(r[o]=s[o])},pa(a,t)};function rb(a,t){pa(a,t);function r(){this.constructor=a}a.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}var da=function(){return da=Object.assign||function(t){for(var r,s=1,o=arguments.length;s=0;y--)(f=a[y])&&(u=(o<3?f(u):o>3?f(t,r,u):f(t,r))||u);return o>3&&u&&Object.defineProperty(t,r,u),u}function nb(a,t){return function(r,s){t(r,s,a)}}function ob(a,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(a,t)}function ab(a,t,r,s){function o(u){return u instanceof r?u:new r(function(f){f(u)})}return new(r||(r=Promise))(function(u,f){function y(w){try{p(s.next(w))}catch(I){f(I)}}function v(w){try{p(s.throw(w))}catch(I){f(I)}}function p(w){w.done?u(w.value):o(w.value).then(y,v)}p((s=s.apply(a,t||[])).next())})}function cb(a,t){var r={label:0,sent:function(){if(u[0]&1)throw u[1];return u[1]},trys:[],ops:[]},s,o,u,f;return f={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(f[Symbol.iterator]=function(){return this}),f;function y(p){return function(w){return v([p,w])}}function v(p){if(s)throw new TypeError("Generator is already executing.");for(;r;)try{if(s=1,o&&(u=p[0]&2?o.return:p[0]?o.throw||((u=o.return)&&u.call(o),0):o.next)&&!(u=u.call(o,p[1])).done)return u;switch(o=0,u&&(p=[p[0]&2,u.value]),p[0]){case 0:case 1:u=p;break;case 4:return r.label++,{value:p[1],done:!1};case 5:r.label++,o=p[1],p=[0];continue;case 7:p=r.ops.pop(),r.trys.pop();continue;default:if(u=r.trys,!(u=u.length>0&&u[u.length-1])&&(p[0]===6||p[0]===2)){r=0;continue}if(p[0]===3&&(!u||p[1]>u[0]&&p[1]=a.length&&(a=void 0),{value:a&&a[s++],done:!a}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Nl(a,t){var r=typeof Symbol=="function"&&a[Symbol.iterator];if(!r)return a;var s=r.call(a),o,u=[],f;try{for(;(t===void 0||t-- >0)&&!(o=s.next()).done;)u.push(o.value)}catch(y){f={error:y}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(f)throw f.error}}return u}function lb(){for(var a=[],t=0;t1||y(R,$)})})}function y(R,$){try{v(s[R]($))}catch(O){I(u[0][3],O)}}function v(R){R.value instanceof ys?Promise.resolve(R.value.v).then(p,w):I(u[0][2],R)}function p(R){y("next",R)}function w(R){y("throw",R)}function I(R,$){R($),u.shift(),u.length&&y(u[0][0],u[0][1])}}function db(a){var t,r;return t={},s("next"),s("throw",function(o){throw o}),s("return"),t[Symbol.iterator]=function(){return this},t;function s(o,u){t[o]=a[o]?function(f){return(r=!r)?{value:ys(a[o](f)),done:o==="return"}:u?u(f):f}:u}}function gb(a){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=a[Symbol.asyncIterator],r;return t?t.call(a):(a=typeof ga=="function"?ga(a):a[Symbol.iterator](),r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r);function s(u){r[u]=a[u]&&function(f){return new Promise(function(y,v){f=a[u](f),o(y,v,f.done,f.value)})}}function o(u,f,y,v){Promise.resolve(v).then(function(p){u({value:p,done:y})},f)}}function yb(a,t){return Object.defineProperty?Object.defineProperty(a,"raw",{value:t}):a.raw=t,a}function vb(a){if(a&&a.__esModule)return a;var t={};if(a!=null)for(var r in a)Object.hasOwnProperty.call(a,r)&&(t[r]=a[r]);return t.default=a,t}function mb(a){return a&&a.__esModule?a:{default:a}}function wb(a,t){if(!t.has(a))throw new TypeError("attempted to get private field on non-instance");return t.get(a)}function bb(a,t,r){if(!t.has(a))throw new TypeError("attempted to set private field on non-instance");return t.set(a,r),r}const _b=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return da},__asyncDelegator:db,__asyncGenerator:pb,__asyncValues:gb,__await:ys,__awaiter:ab,__classPrivateFieldGet:wb,__classPrivateFieldSet:bb,__createBinding:ub,__decorate:sb,__exportStar:hb,__extends:rb,__generator:cb,__importDefault:mb,__importStar:vb,__makeTemplateObject:yb,__metadata:ob,__param:nb,__read:Nl,__rest:ib,__spread:lb,__spreadArrays:fb,__values:ga},Symbol.toStringTag,{value:"Module"})),Rn=On(_b);var ss={},Zo={},ns={};class di{}const Eb=Object.freeze(Object.defineProperty({__proto__:null,IEvents:di},Symbol.toStringTag,{value:"Module"})),Ib=On(Eb);var _h;function xb(){if(_h)return ns;_h=1,Object.defineProperty(ns,"__esModule",{value:!0}),ns.IHeartBeat=void 0;const a=Ib;class t extends a.IEvents{constructor(s){super()}}return ns.IHeartBeat=t,ns}var Eh;function Dl(){return Eh||(Eh=1,function(a){Object.defineProperty(a,"__esModule",{value:!0}),Rn.__exportStar(xb(),a)}(Zo)),Zo}var Xo={},hi={},Ih;function Pb(){if(Ih)return hi;Ih=1,Object.defineProperty(hi,"__esModule",{value:!0}),hi.HEARTBEAT_EVENTS=hi.HEARTBEAT_INTERVAL=void 0;const a=Q;return hi.HEARTBEAT_INTERVAL=a.FIVE_SECONDS,hi.HEARTBEAT_EVENTS={pulse:"heartbeat_pulse"},hi}var xh;function jl(){return xh||(xh=1,function(a){Object.defineProperty(a,"__esModule",{value:!0}),Rn.__exportStar(Pb(),a)}(Xo)),Xo}var Ph;function Sb(){if(Ph)return ss;Ph=1,Object.defineProperty(ss,"__esModule",{value:!0}),ss.HeartBeat=void 0;const a=Rn,t=ar,r=Q,s=Dl(),o=jl();class u extends s.IHeartBeat{constructor(y){super(y),this.events=new t.EventEmitter,this.interval=o.HEARTBEAT_INTERVAL,this.interval=(y==null?void 0:y.interval)||o.HEARTBEAT_INTERVAL}static init(y){return a.__awaiter(this,void 0,void 0,function*(){const v=new u(y);return yield v.init(),v})}init(){return a.__awaiter(this,void 0,void 0,function*(){yield this.initialize()})}stop(){clearInterval(this.intervalRef)}on(y,v){this.events.on(y,v)}once(y,v){this.events.once(y,v)}off(y,v){this.events.off(y,v)}removeListener(y,v){this.events.removeListener(y,v)}initialize(){return a.__awaiter(this,void 0,void 0,function*(){this.intervalRef=setInterval(()=>this.pulse(),r.toMiliseconds(this.interval))})}pulse(){this.events.emit(o.HEARTBEAT_EVENTS.pulse)}}return ss.HeartBeat=u,ss}(function(a){Object.defineProperty(a,"__esModule",{value:!0});const t=Rn;t.__exportStar(Sb(),a),t.__exportStar(Dl(),a),t.__exportStar(jl(),a)})(Ui);function Ob(a){try{return JSON.stringify(a)}catch{return'"[Circular]"'}}var Rb=Ab;function Ab(a,t,r){var s=r&&r.stringify||Ob,o=1;if(typeof a=="object"&&a!==null){var u=t.length+o;if(u===1)return a;var f=new Array(u);f[0]=s(a);for(var y=1;y-1?I:0,a.charCodeAt($+1)){case 100:case 102:if(w>=v||t[w]==null)break;I<$&&(p+=a.slice(I,$)),p+=Number(t[w]),I=$+2,$++;break;case 105:if(w>=v||t[w]==null)break;I<$&&(p+=a.slice(I,$)),p+=Math.floor(Number(t[w])),I=$+2,$++;break;case 79:case 111:case 106:if(w>=v||t[w]===void 0)break;I<$&&(p+=a.slice(I,$));var O=typeof t[w];if(O==="string"){p+="'"+t[w]+"'",I=$+2,$++;break}if(O==="function"){p+=t[w].name||"",I=$+2,$++;break}p+=s(t[w]),I=$+2,$++;break;case 115:if(w>=v)break;I<$&&(p+=a.slice(I,$)),p+=String(t[w]),I=$+2,$++;break;case 37:I<$&&(p+=a.slice(I,$)),p+="%",I=$+2,$++,w--;break}++w}++$}return I===-1?a:(I-1&&(u=!1);const f=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),a.enabled===!1&&(a.level="silent");const y=a.level||"info",v=Object.create(r);v.log||(v.log=ms),Object.defineProperty(v,"levelVal",{get:w}),Object.defineProperty(v,"level",{get:I,set:R});const p={transmit:t,serialize:o,asObject:a.browser.asObject,levels:f,timestamp:Lb(a)};v.levels=_r.levels,v.level=y,v.setMaxListeners=v.getMaxListeners=v.emit=v.addListener=v.on=v.prependListener=v.once=v.prependOnceListener=v.removeListener=v.removeAllListeners=v.listeners=v.listenerCount=v.eventNames=v.write=v.flush=ms,v.serializers=s,v._serialize=o,v._stdErrSerialize=u,v.child=$,t&&(v._logEvent=ya());function w(){return this.level==="silent"?1/0:this.levels.values[this.level]}function I(){return this._level}function R(O){if(O!=="silent"&&!this.levels.values[O])throw Error("unknown level "+O);this._level=O,Ti(p,v,"error","log"),Ti(p,v,"fatal","error"),Ti(p,v,"warn","error"),Ti(p,v,"info","log"),Ti(p,v,"debug","log"),Ti(p,v,"trace","log")}function $(O,B){if(!O)throw new Error("missing bindings for child Pino");B=B||{},o&&O.serializers&&(B.serializers=O.serializers);const X=B.serializers;if(o&&X){var ie=Object.assign({},s,X),he=a.browser.serialize===!0?Object.keys(ie):o;delete O.serializers,An([O],he,ie,this._stdErrSerialize)}function re(Y){this._childLevel=(Y._childLevel|0)+1,this.error=Ni(Y,O,"error"),this.fatal=Ni(Y,O,"fatal"),this.warn=Ni(Y,O,"warn"),this.info=Ni(Y,O,"info"),this.debug=Ni(Y,O,"debug"),this.trace=Ni(Y,O,"trace"),ie&&(this.serializers=ie,this._serialize=he),t&&(this._logEvent=ya([].concat(Y._logEvent.bindings,O)))}return re.prototype=this,new re(this)}return v}_r.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}};_r.stdSerializers=$b;_r.stdTimeFunctions=Object.assign({},{nullTime:ql,epochTime:Ll,unixTime:Mb,isoTime:zb});function Ti(a,t,r,s){const o=Object.getPrototypeOf(t);t[r]=t.levelVal>t.levels.values[r]?ms:o[r]?o[r]:vs[r]||vs[s]||ms,Nb(a,t,r)}function Nb(a,t,r){!a.transmit&&t[r]===ms||(t[r]=function(s){return function(){const u=a.timestamp(),f=new Array(arguments.length),y=Object.getPrototypeOf&&Object.getPrototypeOf(this)===vs?vs:this;for(var v=0;v-1&&u in r&&(a[o][u]=r[u](a[o][u]))}function Ni(a,t,r){return function(){const s=new Array(1+arguments.length);s[0]=t;for(var o=1;ot in a?Hb(a,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):a[t]=r,Gb=(a,t)=>{for(var r in t||(t={}))Bb.call(t,r)&&Rh(a,r,t[r]);if(Oh)for(var r of Oh(t))Fb.call(t,r)&&Rh(a,r,t[r]);return a},Wb=(a,t)=>Kb(a,Vb(t));function $n(a){return Wb(Gb({},a),{level:(a==null?void 0:a.level)||kb.level})}function Jb(a,t=Es){return a[t]||""}function Qb(a,t,r=Es){return a[r]=t,a}function kt(a,t=Es){let r="";return typeof a.bindings>"u"?r=Jb(a,t):r=a.bindings().context||"",r}function Yb(a,t,r=Es){const s=kt(a,r);return s.trim()?`${s}/${t}`:t}function Ht(a,t,r=Es){const s=Yb(a,t,r),o=a.child({context:s});return Qb(o,s,r)}let Zb=class extends di{constructor(t){super(),this.opts=t,this.protocol="wc",this.version=2}},Xb=class extends di{constructor(t,r){super(),this.core=t,this.logger=r,this.records=new Map}},e_=class{constructor(t,r){this.logger=t,this.core=r}},t_=class extends di{constructor(t,r){super(),this.relayer=t,this.logger=r}},r_=class extends di{constructor(t){super()}},i_=class{constructor(t,r,s,o){this.core=t,this.logger=r,this.name=s}},s_=class extends di{constructor(t,r){super(),this.relayer=t,this.logger=r}},n_=class extends di{constructor(t,r){super(),this.core=t,this.logger=r}},o_=class{constructor(t,r){this.projectId=t,this.logger=r}},a_=class{constructor(t,r){this.projectId=t,this.logger=r}},c_=class{constructor(t){this.opts=t,this.protocol="wc",this.version=2}},u_=class{constructor(t){this.client=t}};var Ca={},Ml={};(function(a){Object.defineProperty(a,"__esModule",{value:!0});var t=q0,r=Il;a.DIGEST_LENGTH=64,a.BLOCK_SIZE=128;var s=function(){function y(){this.digestLength=a.DIGEST_LENGTH,this.blockSize=a.BLOCK_SIZE,this._stateHi=new Int32Array(8),this._stateLo=new Int32Array(8),this._tempHi=new Int32Array(16),this._tempLo=new Int32Array(16),this._buffer=new Uint8Array(256),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this.reset()}return y.prototype._initState=function(){this._stateHi[0]=1779033703,this._stateHi[1]=3144134277,this._stateHi[2]=1013904242,this._stateHi[3]=2773480762,this._stateHi[4]=1359893119,this._stateHi[5]=2600822924,this._stateHi[6]=528734635,this._stateHi[7]=1541459225,this._stateLo[0]=4089235720,this._stateLo[1]=2227873595,this._stateLo[2]=4271175723,this._stateLo[3]=1595750129,this._stateLo[4]=2917565137,this._stateLo[5]=725511199,this._stateLo[6]=4215389547,this._stateLo[7]=327033209},y.prototype.reset=function(){return this._initState(),this._bufferLength=0,this._bytesHashed=0,this._finished=!1,this},y.prototype.clean=function(){r.wipe(this._buffer),r.wipe(this._tempHi),r.wipe(this._tempLo),this.reset()},y.prototype.update=function(v,p){if(p===void 0&&(p=v.length),this._finished)throw new Error("SHA512: can't update because hash was finished.");var w=0;if(this._bytesHashed+=p,this._bufferLength>0){for(;this._bufferLength0;)this._buffer[this._bufferLength++]=v[w++],p--;this._bufferLength===this.blockSize&&(u(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,this.blockSize),this._bufferLength=0)}for(p>=this.blockSize&&(w=u(this._tempHi,this._tempLo,this._stateHi,this._stateLo,v,w,p),p%=this.blockSize);p>0;)this._buffer[this._bufferLength++]=v[w++],p--;return this},y.prototype.finish=function(v){if(!this._finished){var p=this._bytesHashed,w=this._bufferLength,I=p/536870912|0,R=p<<3,$=p%128<112?128:256;this._buffer[w]=128;for(var O=w+1;O<$-8;O++)this._buffer[O]=0;t.writeUint32BE(I,this._buffer,$-8),t.writeUint32BE(R,this._buffer,$-4),u(this._tempHi,this._tempLo,this._stateHi,this._stateLo,this._buffer,0,$),this._finished=!0}for(var O=0;O0?new Uint8Array(this._buffer):void 0,bufferLength:this._bufferLength,bytesHashed:this._bytesHashed}},y.prototype.restoreState=function(v){return this._stateHi.set(v.stateHi),this._stateLo.set(v.stateLo),this._bufferLength=v.bufferLength,v.buffer&&this._buffer.set(v.buffer),this._bytesHashed=v.bytesHashed,this._finished=!1,this},y.prototype.cleanSavedState=function(v){r.wipe(v.stateHi),r.wipe(v.stateLo),v.buffer&&r.wipe(v.buffer),v.bufferLength=0,v.bytesHashed=0},y}();a.SHA512=s;var o=new Int32Array([1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591]);function u(y,v,p,w,I,R,$){for(var O=p[0],B=p[1],X=p[2],ie=p[3],he=p[4],re=p[5],Y=p[6],ce=p[7],pe=w[0],W=w[1],de=w[2],et=w[3],tt=w[4],Me=w[5],Qt=w[6],Rt=w[7],b,S,F,ae,z,M,U,k;$>=128;){for(var Ue=0;Ue<16;Ue++){var Be=8*Ue+R;y[Ue]=t.readUint32BE(I,Be),v[Ue]=t.readUint32BE(I,Be+4)}for(var Ue=0;Ue<80;Ue++){var ki=O,yr=B,Mr=X,T=ie,N=he,A=re,h=Y,E=ce,J=pe,ne=W,ge=de,_e=et,Ie=tt,we=Me,rt=Qt,Je=Rt;if(b=ce,S=Rt,z=S&65535,M=S>>>16,U=b&65535,k=b>>>16,b=(he>>>14|tt<<18)^(he>>>18|tt<<14)^(tt>>>9|he<<23),S=(tt>>>14|he<<18)^(tt>>>18|he<<14)^(he>>>9|tt<<23),z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,b=he&re^~he&Y,S=tt&Me^~tt&Qt,z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,b=o[Ue*2],S=o[Ue*2+1],z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,b=y[Ue%16],S=v[Ue%16],z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,M+=z>>>16,U+=M>>>16,k+=U>>>16,F=U&65535|k<<16,ae=z&65535|M<<16,b=F,S=ae,z=S&65535,M=S>>>16,U=b&65535,k=b>>>16,b=(O>>>28|pe<<4)^(pe>>>2|O<<30)^(pe>>>7|O<<25),S=(pe>>>28|O<<4)^(O>>>2|pe<<30)^(O>>>7|pe<<25),z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,b=O&B^O&X^B&X,S=pe&W^pe&de^W&de,z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,M+=z>>>16,U+=M>>>16,k+=U>>>16,E=U&65535|k<<16,Je=z&65535|M<<16,b=T,S=_e,z=S&65535,M=S>>>16,U=b&65535,k=b>>>16,b=F,S=ae,z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,M+=z>>>16,U+=M>>>16,k+=U>>>16,T=U&65535|k<<16,_e=z&65535|M<<16,B=ki,X=yr,ie=Mr,he=T,re=N,Y=A,ce=h,O=E,W=J,de=ne,et=ge,tt=_e,Me=Ie,Qt=we,Rt=rt,pe=Je,Ue%16===15)for(var Be=0;Be<16;Be++)b=y[Be],S=v[Be],z=S&65535,M=S>>>16,U=b&65535,k=b>>>16,b=y[(Be+9)%16],S=v[(Be+9)%16],z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,F=y[(Be+1)%16],ae=v[(Be+1)%16],b=(F>>>1|ae<<31)^(F>>>8|ae<<24)^F>>>7,S=(ae>>>1|F<<31)^(ae>>>8|F<<24)^(ae>>>7|F<<25),z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,F=y[(Be+14)%16],ae=v[(Be+14)%16],b=(F>>>19|ae<<13)^(ae>>>29|F<<3)^F>>>6,S=(ae>>>19|F<<13)^(F>>>29|ae<<3)^(ae>>>6|F<<26),z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,M+=z>>>16,U+=M>>>16,k+=U>>>16,y[Be]=U&65535|k<<16,v[Be]=z&65535|M<<16}b=O,S=pe,z=S&65535,M=S>>>16,U=b&65535,k=b>>>16,b=p[0],S=w[0],z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,M+=z>>>16,U+=M>>>16,k+=U>>>16,p[0]=O=U&65535|k<<16,w[0]=pe=z&65535|M<<16,b=B,S=W,z=S&65535,M=S>>>16,U=b&65535,k=b>>>16,b=p[1],S=w[1],z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,M+=z>>>16,U+=M>>>16,k+=U>>>16,p[1]=B=U&65535|k<<16,w[1]=W=z&65535|M<<16,b=X,S=de,z=S&65535,M=S>>>16,U=b&65535,k=b>>>16,b=p[2],S=w[2],z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,M+=z>>>16,U+=M>>>16,k+=U>>>16,p[2]=X=U&65535|k<<16,w[2]=de=z&65535|M<<16,b=ie,S=et,z=S&65535,M=S>>>16,U=b&65535,k=b>>>16,b=p[3],S=w[3],z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,M+=z>>>16,U+=M>>>16,k+=U>>>16,p[3]=ie=U&65535|k<<16,w[3]=et=z&65535|M<<16,b=he,S=tt,z=S&65535,M=S>>>16,U=b&65535,k=b>>>16,b=p[4],S=w[4],z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,M+=z>>>16,U+=M>>>16,k+=U>>>16,p[4]=he=U&65535|k<<16,w[4]=tt=z&65535|M<<16,b=re,S=Me,z=S&65535,M=S>>>16,U=b&65535,k=b>>>16,b=p[5],S=w[5],z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,M+=z>>>16,U+=M>>>16,k+=U>>>16,p[5]=re=U&65535|k<<16,w[5]=Me=z&65535|M<<16,b=Y,S=Qt,z=S&65535,M=S>>>16,U=b&65535,k=b>>>16,b=p[6],S=w[6],z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,M+=z>>>16,U+=M>>>16,k+=U>>>16,p[6]=Y=U&65535|k<<16,w[6]=Qt=z&65535|M<<16,b=ce,S=Rt,z=S&65535,M=S>>>16,U=b&65535,k=b>>>16,b=p[7],S=w[7],z+=S&65535,M+=S>>>16,U+=b&65535,k+=b>>>16,M+=z>>>16,U+=M>>>16,k+=U>>>16,p[7]=ce=U&65535|k<<16,w[7]=Rt=z&65535|M<<16,R+=128,$-=128}return R}function f(y){var v=new s;v.update(y);var p=v.digest();return v.clean(),p}a.hash=f})(Ml);(function(a){Object.defineProperty(a,"__esModule",{value:!0}),a.convertSecretKeyToX25519=a.convertPublicKeyToX25519=a.verify=a.sign=a.extractPublicKeyFromSecretKey=a.generateKeyPair=a.generateKeyPairFromSeed=a.SEED_LENGTH=a.SECRET_KEY_LENGTH=a.PUBLIC_KEY_LENGTH=a.SIGNATURE_LENGTH=void 0;const t=xl,r=Ml,s=Il;a.SIGNATURE_LENGTH=64,a.PUBLIC_KEY_LENGTH=32,a.SECRET_KEY_LENGTH=64,a.SEED_LENGTH=32;function o(T){const N=new Float64Array(16);if(T)for(let A=0;A>16&1),A[ne-1]&=65535;A[15]=h[15]-32767-(A[14]>>16&1);const J=A[15]>>16&1;A[14]&=65535,B(h,A,1-J)}for(let E=0;E<16;E++)T[2*E]=h[E]&255,T[2*E+1]=h[E]>>8}function ie(T,N){let A=0;for(let h=0;h<32;h++)A|=T[h]^N[h];return(1&A-1>>>8)-1}function he(T,N){const A=new Uint8Array(32),h=new Uint8Array(32);return X(A,T),X(h,N),ie(A,h)}function re(T){const N=new Uint8Array(32);return X(N,T),N[0]&1}function Y(T,N){for(let A=0;A<16;A++)T[A]=N[2*A]+(N[2*A+1]<<8);T[15]&=32767}function ce(T,N,A){for(let h=0;h<16;h++)T[h]=N[h]+A[h]}function pe(T,N,A){for(let h=0;h<16;h++)T[h]=N[h]-A[h]}function W(T,N,A){let h,E,J=0,ne=0,ge=0,_e=0,Ie=0,we=0,rt=0,Je=0,ke=0,Pe=0,Ne=0,De=0,He=0,Re=0,je=0,Se=0,qe=0,Qe=0,it=0,wt=0,It=0,At=0,Nt=0,Kt=0,Yt=0,cr=0,zr=0,ei=0,yi=0,vi=0,Hi=0,st=A[0],nt=A[1],ot=A[2],at=A[3],Ye=A[4],ct=A[5],ut=A[6],ht=A[7],Fe=A[8],lt=A[9],Ge=A[10],ft=A[11],pt=A[12],dt=A[13],gt=A[14],yt=A[15];h=N[0],J+=h*st,ne+=h*nt,ge+=h*ot,_e+=h*at,Ie+=h*Ye,we+=h*ct,rt+=h*ut,Je+=h*ht,ke+=h*Fe,Pe+=h*lt,Ne+=h*Ge,De+=h*ft,He+=h*pt,Re+=h*dt,je+=h*gt,Se+=h*yt,h=N[1],ne+=h*st,ge+=h*nt,_e+=h*ot,Ie+=h*at,we+=h*Ye,rt+=h*ct,Je+=h*ut,ke+=h*ht,Pe+=h*Fe,Ne+=h*lt,De+=h*Ge,He+=h*ft,Re+=h*pt,je+=h*dt,Se+=h*gt,qe+=h*yt,h=N[2],ge+=h*st,_e+=h*nt,Ie+=h*ot,we+=h*at,rt+=h*Ye,Je+=h*ct,ke+=h*ut,Pe+=h*ht,Ne+=h*Fe,De+=h*lt,He+=h*Ge,Re+=h*ft,je+=h*pt,Se+=h*dt,qe+=h*gt,Qe+=h*yt,h=N[3],_e+=h*st,Ie+=h*nt,we+=h*ot,rt+=h*at,Je+=h*Ye,ke+=h*ct,Pe+=h*ut,Ne+=h*ht,De+=h*Fe,He+=h*lt,Re+=h*Ge,je+=h*ft,Se+=h*pt,qe+=h*dt,Qe+=h*gt,it+=h*yt,h=N[4],Ie+=h*st,we+=h*nt,rt+=h*ot,Je+=h*at,ke+=h*Ye,Pe+=h*ct,Ne+=h*ut,De+=h*ht,He+=h*Fe,Re+=h*lt,je+=h*Ge,Se+=h*ft,qe+=h*pt,Qe+=h*dt,it+=h*gt,wt+=h*yt,h=N[5],we+=h*st,rt+=h*nt,Je+=h*ot,ke+=h*at,Pe+=h*Ye,Ne+=h*ct,De+=h*ut,He+=h*ht,Re+=h*Fe,je+=h*lt,Se+=h*Ge,qe+=h*ft,Qe+=h*pt,it+=h*dt,wt+=h*gt,It+=h*yt,h=N[6],rt+=h*st,Je+=h*nt,ke+=h*ot,Pe+=h*at,Ne+=h*Ye,De+=h*ct,He+=h*ut,Re+=h*ht,je+=h*Fe,Se+=h*lt,qe+=h*Ge,Qe+=h*ft,it+=h*pt,wt+=h*dt,It+=h*gt,At+=h*yt,h=N[7],Je+=h*st,ke+=h*nt,Pe+=h*ot,Ne+=h*at,De+=h*Ye,He+=h*ct,Re+=h*ut,je+=h*ht,Se+=h*Fe,qe+=h*lt,Qe+=h*Ge,it+=h*ft,wt+=h*pt,It+=h*dt,At+=h*gt,Nt+=h*yt,h=N[8],ke+=h*st,Pe+=h*nt,Ne+=h*ot,De+=h*at,He+=h*Ye,Re+=h*ct,je+=h*ut,Se+=h*ht,qe+=h*Fe,Qe+=h*lt,it+=h*Ge,wt+=h*ft,It+=h*pt,At+=h*dt,Nt+=h*gt,Kt+=h*yt,h=N[9],Pe+=h*st,Ne+=h*nt,De+=h*ot,He+=h*at,Re+=h*Ye,je+=h*ct,Se+=h*ut,qe+=h*ht,Qe+=h*Fe,it+=h*lt,wt+=h*Ge,It+=h*ft,At+=h*pt,Nt+=h*dt,Kt+=h*gt,Yt+=h*yt,h=N[10],Ne+=h*st,De+=h*nt,He+=h*ot,Re+=h*at,je+=h*Ye,Se+=h*ct,qe+=h*ut,Qe+=h*ht,it+=h*Fe,wt+=h*lt,It+=h*Ge,At+=h*ft,Nt+=h*pt,Kt+=h*dt,Yt+=h*gt,cr+=h*yt,h=N[11],De+=h*st,He+=h*nt,Re+=h*ot,je+=h*at,Se+=h*Ye,qe+=h*ct,Qe+=h*ut,it+=h*ht,wt+=h*Fe,It+=h*lt,At+=h*Ge,Nt+=h*ft,Kt+=h*pt,Yt+=h*dt,cr+=h*gt,zr+=h*yt,h=N[12],He+=h*st,Re+=h*nt,je+=h*ot,Se+=h*at,qe+=h*Ye,Qe+=h*ct,it+=h*ut,wt+=h*ht,It+=h*Fe,At+=h*lt,Nt+=h*Ge,Kt+=h*ft,Yt+=h*pt,cr+=h*dt,zr+=h*gt,ei+=h*yt,h=N[13],Re+=h*st,je+=h*nt,Se+=h*ot,qe+=h*at,Qe+=h*Ye,it+=h*ct,wt+=h*ut,It+=h*ht,At+=h*Fe,Nt+=h*lt,Kt+=h*Ge,Yt+=h*ft,cr+=h*pt,zr+=h*dt,ei+=h*gt,yi+=h*yt,h=N[14],je+=h*st,Se+=h*nt,qe+=h*ot,Qe+=h*at,it+=h*Ye,wt+=h*ct,It+=h*ut,At+=h*ht,Nt+=h*Fe,Kt+=h*lt,Yt+=h*Ge,cr+=h*ft,zr+=h*pt,ei+=h*dt,yi+=h*gt,vi+=h*yt,h=N[15],Se+=h*st,qe+=h*nt,Qe+=h*ot,it+=h*at,wt+=h*Ye,It+=h*ct,At+=h*ut,Nt+=h*ht,Kt+=h*Fe,Yt+=h*lt,cr+=h*Ge,zr+=h*ft,ei+=h*pt,yi+=h*dt,vi+=h*gt,Hi+=h*yt,J+=38*qe,ne+=38*Qe,ge+=38*it,_e+=38*wt,Ie+=38*It,we+=38*At,rt+=38*Nt,Je+=38*Kt,ke+=38*Yt,Pe+=38*cr,Ne+=38*zr,De+=38*ei,He+=38*yi,Re+=38*vi,je+=38*Hi,E=1,h=J+E+65535,E=Math.floor(h/65536),J=h-E*65536,h=ne+E+65535,E=Math.floor(h/65536),ne=h-E*65536,h=ge+E+65535,E=Math.floor(h/65536),ge=h-E*65536,h=_e+E+65535,E=Math.floor(h/65536),_e=h-E*65536,h=Ie+E+65535,E=Math.floor(h/65536),Ie=h-E*65536,h=we+E+65535,E=Math.floor(h/65536),we=h-E*65536,h=rt+E+65535,E=Math.floor(h/65536),rt=h-E*65536,h=Je+E+65535,E=Math.floor(h/65536),Je=h-E*65536,h=ke+E+65535,E=Math.floor(h/65536),ke=h-E*65536,h=Pe+E+65535,E=Math.floor(h/65536),Pe=h-E*65536,h=Ne+E+65535,E=Math.floor(h/65536),Ne=h-E*65536,h=De+E+65535,E=Math.floor(h/65536),De=h-E*65536,h=He+E+65535,E=Math.floor(h/65536),He=h-E*65536,h=Re+E+65535,E=Math.floor(h/65536),Re=h-E*65536,h=je+E+65535,E=Math.floor(h/65536),je=h-E*65536,h=Se+E+65535,E=Math.floor(h/65536),Se=h-E*65536,J+=E-1+37*(E-1),E=1,h=J+E+65535,E=Math.floor(h/65536),J=h-E*65536,h=ne+E+65535,E=Math.floor(h/65536),ne=h-E*65536,h=ge+E+65535,E=Math.floor(h/65536),ge=h-E*65536,h=_e+E+65535,E=Math.floor(h/65536),_e=h-E*65536,h=Ie+E+65535,E=Math.floor(h/65536),Ie=h-E*65536,h=we+E+65535,E=Math.floor(h/65536),we=h-E*65536,h=rt+E+65535,E=Math.floor(h/65536),rt=h-E*65536,h=Je+E+65535,E=Math.floor(h/65536),Je=h-E*65536,h=ke+E+65535,E=Math.floor(h/65536),ke=h-E*65536,h=Pe+E+65535,E=Math.floor(h/65536),Pe=h-E*65536,h=Ne+E+65535,E=Math.floor(h/65536),Ne=h-E*65536,h=De+E+65535,E=Math.floor(h/65536),De=h-E*65536,h=He+E+65535,E=Math.floor(h/65536),He=h-E*65536,h=Re+E+65535,E=Math.floor(h/65536),Re=h-E*65536,h=je+E+65535,E=Math.floor(h/65536),je=h-E*65536,h=Se+E+65535,E=Math.floor(h/65536),Se=h-E*65536,J+=E-1+37*(E-1),T[0]=J,T[1]=ne,T[2]=ge,T[3]=_e,T[4]=Ie,T[5]=we,T[6]=rt,T[7]=Je,T[8]=ke,T[9]=Pe,T[10]=Ne,T[11]=De,T[12]=He,T[13]=Re,T[14]=je,T[15]=Se}function de(T,N){W(T,N,N)}function et(T,N){const A=o();let h;for(h=0;h<16;h++)A[h]=N[h];for(h=253;h>=0;h--)de(A,A),h!==2&&h!==4&&W(A,A,N);for(h=0;h<16;h++)T[h]=A[h]}function tt(T,N){const A=o();let h;for(h=0;h<16;h++)A[h]=N[h];for(h=250;h>=0;h--)de(A,A),h!==1&&W(A,A,N);for(h=0;h<16;h++)T[h]=A[h]}function Me(T,N){const A=o(),h=o(),E=o(),J=o(),ne=o(),ge=o(),_e=o(),Ie=o(),we=o();pe(A,T[1],T[0]),pe(we,N[1],N[0]),W(A,A,we),ce(h,T[0],T[1]),ce(we,N[0],N[1]),W(h,h,we),W(E,T[3],N[3]),W(E,E,p),W(J,T[2],N[2]),ce(J,J,J),pe(ne,h,A),pe(ge,J,E),ce(_e,J,E),ce(Ie,h,A),W(T[0],ne,ge),W(T[1],Ie,_e),W(T[2],_e,ge),W(T[3],ne,Ie)}function Qt(T,N,A){for(let h=0;h<4;h++)B(T[h],N[h],A)}function Rt(T,N){const A=o(),h=o(),E=o();et(E,N[2]),W(A,N[0],E),W(h,N[1],E),X(T,h),T[31]^=re(A)<<7}function b(T,N,A){$(T[0],f),$(T[1],y),$(T[2],y),$(T[3],f);for(let h=255;h>=0;--h){const E=A[h/8|0]>>(h&7)&1;Qt(T,N,E),Me(N,T),Me(T,T),Qt(T,N,E)}}function S(T,N){const A=[o(),o(),o(),o()];$(A[0],w),$(A[1],I),$(A[2],y),W(A[3],w,I),b(T,A,N)}function F(T){if(T.length!==a.SEED_LENGTH)throw new Error(`ed25519: seed must be ${a.SEED_LENGTH} bytes`);const N=(0,r.hash)(T);N[0]&=248,N[31]&=127,N[31]|=64;const A=new Uint8Array(32),h=[o(),o(),o(),o()];S(h,N),Rt(A,h);const E=new Uint8Array(64);return E.set(T),E.set(A,32),{publicKey:A,secretKey:E}}a.generateKeyPairFromSeed=F;function ae(T){const N=(0,t.randomBytes)(32,T),A=F(N);return(0,s.wipe)(N),A}a.generateKeyPair=ae;function z(T){if(T.length!==a.SECRET_KEY_LENGTH)throw new Error(`ed25519: secret key must be ${a.SECRET_KEY_LENGTH} bytes`);return new Uint8Array(T.subarray(32))}a.extractPublicKeyFromSecretKey=z;const M=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function U(T,N){let A,h,E,J;for(h=63;h>=32;--h){for(A=0,E=h-32,J=h-12;E>4)*M[E],A=N[E]>>8,N[E]&=255;for(E=0;E<32;E++)N[E]-=A*M[E];for(h=0;h<32;h++)N[h+1]+=N[h]>>8,T[h]=N[h]&255}function k(T){const N=new Float64Array(64);for(let A=0;A<64;A++)N[A]=T[A];for(let A=0;A<64;A++)T[A]=0;U(T,N)}function Ue(T,N){const A=new Float64Array(64),h=[o(),o(),o(),o()],E=(0,r.hash)(T.subarray(0,32));E[0]&=248,E[31]&=127,E[31]|=64;const J=new Uint8Array(64);J.set(E.subarray(32),32);const ne=new r.SHA512;ne.update(J.subarray(32)),ne.update(N);const ge=ne.digest();ne.clean(),k(ge),S(h,ge),Rt(J,h),ne.reset(),ne.update(J.subarray(0,32)),ne.update(T.subarray(32)),ne.update(N);const _e=ne.digest();k(_e);for(let Ie=0;Ie<32;Ie++)A[Ie]=ge[Ie];for(let Ie=0;Ie<32;Ie++)for(let we=0;we<32;we++)A[Ie+we]+=_e[Ie]*E[we];return U(J.subarray(32),A),J}a.sign=Ue;function Be(T,N){const A=o(),h=o(),E=o(),J=o(),ne=o(),ge=o(),_e=o();return $(T[2],y),Y(T[1],N),de(E,T[1]),W(J,E,v),pe(E,E,T[2]),ce(J,T[2],J),de(ne,J),de(ge,ne),W(_e,ge,ne),W(A,_e,E),W(A,A,J),tt(A,A),W(A,A,E),W(A,A,J),W(A,A,J),W(T[0],A,J),de(h,T[0]),W(h,h,J),he(h,E)&&W(T[0],T[0],R),de(h,T[0]),W(h,h,J),he(h,E)?-1:(re(T[0])===N[31]>>7&&pe(T[0],f,T[0]),W(T[3],T[0],T[1]),0)}function ki(T,N,A){const h=new Uint8Array(32),E=[o(),o(),o(),o()],J=[o(),o(),o(),o()];if(A.length!==a.SIGNATURE_LENGTH)throw new Error(`ed25519: signature must be ${a.SIGNATURE_LENGTH} bytes`);if(Be(J,T))return!1;const ne=new r.SHA512;ne.update(A.subarray(0,32)),ne.update(T),ne.update(N);const ge=ne.digest();return k(ge),b(E,J,ge),S(J,A.subarray(32)),Me(E,J),Rt(h,E),!ie(A,h)}a.verify=ki;function yr(T){let N=[o(),o(),o(),o()];if(Be(N,T))throw new Error("Ed25519: invalid public key");let A=o(),h=o(),E=N[1];ce(A,y,E),pe(h,y,E),et(h,h),W(A,A,h);let J=new Uint8Array(32);return X(J,A),J}a.convertPublicKeyToX25519=yr;function Mr(T){const N=(0,r.hash)(T.subarray(0,32));N[0]&=248,N[31]&=127,N[31]|=64;const A=new Uint8Array(N.subarray(0,32));return(0,s.wipe)(N),A}a.convertSecretKeyToX25519=Mr})(Ca);const h_="EdDSA",l_="JWT",zl=".",Ul="base64url",f_="utf8",p_="utf8",d_=":",g_="did",y_="key",Ah="base58btc",v_="z",m_="K36",w_=32;function xn(a){return Sn(Ra(fi(a),f_),Ul)}function kl(a){const t=Ra(m_,Ah),r=v_+Sn(L0([t,a]),Ah);return[g_,y_,r].join(d_)}function b_(a){return Sn(a,Ul)}function __(a){return Ra([xn(a.header),xn(a.payload)].join(zl),p_)}function E_(a){return[xn(a.header),xn(a.payload),b_(a.signature)].join(zl)}function Ch(a=xl.randomBytes(w_)){return Ca.generateKeyPairFromSeed(a)}async function I_(a,t,r,s,o=Q.fromMiliseconds(Date.now())){const u={alg:h_,typ:l_},f=kl(s.publicKey),y=o+r,v={iss:f,sub:a,aud:t,iat:o,exp:y},p=__({header:u,payload:v}),w=Ca.sign(s.secretKey,p);return E_({header:u,payload:v,signature:w})}const x_="PARSE_ERROR",P_="INVALID_REQUEST",S_="METHOD_NOT_FOUND",O_="INVALID_PARAMS",Hl="INTERNAL_ERROR",$a="SERVER_ERROR",R_=[-32700,-32600,-32601,-32602,-32603],ds={[x_]:{code:-32700,message:"Parse error"},[P_]:{code:-32600,message:"Invalid Request"},[S_]:{code:-32601,message:"Method not found"},[O_]:{code:-32602,message:"Invalid params"},[Hl]:{code:-32603,message:"Internal error"},[$a]:{code:-32e3,message:"Server error"}},Kl=$a;function A_(a){return R_.includes(a)}function $h(a){return Object.keys(ds).includes(a)?ds[a]:ds[Kl]}function C_(a){const t=Object.values(ds).find(r=>r.code===a);return t||ds[Kl]}function Vl(a,t,r){return a.message.includes("getaddrinfo ENOTFOUND")||a.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${t}`):a}var Bl={};/*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */var va=function(a,t){return va=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)s.hasOwnProperty(o)&&(r[o]=s[o])},va(a,t)};function $_(a,t){va(a,t);function r(){this.constructor=a}a.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}var ma=function(){return ma=Object.assign||function(t){for(var r,s=1,o=arguments.length;s=0;y--)(f=a[y])&&(u=(o<3?f(u):o>3?f(t,r,u):f(t,r))||u);return o>3&&u&&Object.defineProperty(t,r,u),u}function D_(a,t){return function(r,s){t(r,s,a)}}function j_(a,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(a,t)}function q_(a,t,r,s){function o(u){return u instanceof r?u:new r(function(f){f(u)})}return new(r||(r=Promise))(function(u,f){function y(w){try{p(s.next(w))}catch(I){f(I)}}function v(w){try{p(s.throw(w))}catch(I){f(I)}}function p(w){w.done?u(w.value):o(w.value).then(y,v)}p((s=s.apply(a,t||[])).next())})}function L_(a,t){var r={label:0,sent:function(){if(u[0]&1)throw u[1];return u[1]},trys:[],ops:[]},s,o,u,f;return f={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(f[Symbol.iterator]=function(){return this}),f;function y(p){return function(w){return v([p,w])}}function v(p){if(s)throw new TypeError("Generator is already executing.");for(;r;)try{if(s=1,o&&(u=p[0]&2?o.return:p[0]?o.throw||((u=o.return)&&u.call(o),0):o.next)&&!(u=u.call(o,p[1])).done)return u;switch(o=0,u&&(p=[p[0]&2,u.value]),p[0]){case 0:case 1:u=p;break;case 4:return r.label++,{value:p[1],done:!1};case 5:r.label++,o=p[1],p=[0];continue;case 7:p=r.ops.pop(),r.trys.pop();continue;default:if(u=r.trys,!(u=u.length>0&&u[u.length-1])&&(p[0]===6||p[0]===2)){r=0;continue}if(p[0]===3&&(!u||p[1]>u[0]&&p[1]=a.length&&(a=void 0),{value:a&&a[s++],done:!a}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Fl(a,t){var r=typeof Symbol=="function"&&a[Symbol.iterator];if(!r)return a;var s=r.call(a),o,u=[],f;try{for(;(t===void 0||t-- >0)&&!(o=s.next()).done;)u.push(o.value)}catch(y){f={error:y}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(f)throw f.error}}return u}function U_(){for(var a=[],t=0;t1||y(R,$)})})}function y(R,$){try{v(s[R]($))}catch(O){I(u[0][3],O)}}function v(R){R.value instanceof ws?Promise.resolve(R.value.v).then(p,w):I(u[0][2],R)}function p(R){y("next",R)}function w(R){y("throw",R)}function I(R,$){R($),u.shift(),u.length&&y(u[0][0],u[0][1])}}function K_(a){var t,r;return t={},s("next"),s("throw",function(o){throw o}),s("return"),t[Symbol.iterator]=function(){return this},t;function s(o,u){t[o]=a[o]?function(f){return(r=!r)?{value:ws(a[o](f)),done:o==="return"}:u?u(f):f}:u}}function V_(a){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=a[Symbol.asyncIterator],r;return t?t.call(a):(a=typeof wa=="function"?wa(a):a[Symbol.iterator](),r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r);function s(u){r[u]=a[u]&&function(f){return new Promise(function(y,v){f=a[u](f),o(y,v,f.done,f.value)})}}function o(u,f,y,v){Promise.resolve(v).then(function(p){u({value:p,done:y})},f)}}function B_(a,t){return Object.defineProperty?Object.defineProperty(a,"raw",{value:t}):a.raw=t,a}function F_(a){if(a&&a.__esModule)return a;var t={};if(a!=null)for(var r in a)Object.hasOwnProperty.call(a,r)&&(t[r]=a[r]);return t.default=a,t}function G_(a){return a&&a.__esModule?a:{default:a}}function W_(a,t){if(!t.has(a))throw new TypeError("attempted to get private field on non-instance");return t.get(a)}function J_(a,t,r){if(!t.has(a))throw new TypeError("attempted to set private field on non-instance");return t.set(a,r),r}const Q_=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return ma},__asyncDelegator:K_,__asyncGenerator:H_,__asyncValues:V_,__await:ws,__awaiter:q_,__classPrivateFieldGet:W_,__classPrivateFieldSet:J_,__createBinding:M_,__decorate:N_,__exportStar:z_,__extends:$_,__generator:L_,__importDefault:G_,__importStar:F_,__makeTemplateObject:B_,__metadata:j_,__param:D_,__read:Fl,__rest:T_,__spread:U_,__spreadArrays:k_,__values:wa},Symbol.toStringTag,{value:"Module"})),Y_=On(Q_);var $r={},Th;function Z_(){if(Th)return $r;Th=1,Object.defineProperty($r,"__esModule",{value:!0}),$r.isBrowserCryptoAvailable=$r.getSubtleCrypto=$r.getBrowerCrypto=void 0;function a(){return(li===null||li===void 0?void 0:li.crypto)||(li===null||li===void 0?void 0:li.msCrypto)||{}}$r.getBrowerCrypto=a;function t(){const s=a();return s.subtle||s.webkitSubtle}$r.getSubtleCrypto=t;function r(){return!!a()&&!!t()}return $r.isBrowserCryptoAvailable=r,$r}var Tr={},Nh;function X_(){if(Nh)return Tr;Nh=1,Object.defineProperty(Tr,"__esModule",{value:!0}),Tr.isBrowser=Tr.isNode=Tr.isReactNative=void 0;function a(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Tr.isReactNative=a;function t(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Tr.isNode=t;function r(){return!a()&&!t()}return Tr.isBrowser=r,Tr}(function(a){Object.defineProperty(a,"__esModule",{value:!0});const t=Y_;t.__exportStar(Z_(),a),t.__exportStar(X_(),a)})(Bl);function Ta(a=3){const t=Date.now()*Math.pow(10,a),r=Math.floor(Math.random()*Math.pow(10,a));return t+r}function Gl(a=6){return BigInt(Ta(a))}function Mi(a,t,r){return{id:r||Ta(),jsonrpc:"2.0",method:a,params:t}}function Tn(a,t){return{id:a,jsonrpc:"2.0",result:t}}function Nn(a,t,r){return{id:a,jsonrpc:"2.0",error:e1(t)}}function e1(a,t){return typeof a>"u"?$h(Hl):(typeof a=="string"&&(a=Object.assign(Object.assign({},$h($a)),{message:a})),A_(a.code)&&(a=C_(a.code)),a)}class t1{}class r1 extends t1{constructor(){super()}}class i1 extends r1{constructor(t){super()}}const s1="^https?:",n1="^wss?:";function o1(a){const t=a.match(new RegExp(/^\w+:/,"gi"));if(!(!t||!t.length))return t[0]}function Wl(a,t){const r=o1(a);return typeof r>"u"?!1:new RegExp(t).test(r)}function Dh(a){return Wl(a,s1)}function jh(a){return Wl(a,n1)}function a1(a){return new RegExp("wss?://localhost(:d{2,5})?").test(a)}function Jl(a){return typeof a=="object"&&"id"in a&&"jsonrpc"in a&&a.jsonrpc==="2.0"}function Na(a){return Jl(a)&&"method"in a}function Dn(a){return Jl(a)&&(jr(a)||gr(a))}function jr(a){return"result"in a}function gr(a){return"error"in a}class qr extends i1{constructor(t){super(t),this.events=new ar.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(t),this.connection.connected&&this.registerEventListeners()}async connect(t=this.connection){await this.open(t)}async disconnect(){await this.close()}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async request(t,r){return this.requestStrict(Mi(t.method,t.params||[],t.id||Gl().toString()),r)}async requestStrict(t,r){return new Promise(async(s,o)=>{if(!this.connection.connected)try{await this.open()}catch(u){o(u)}this.events.on(`${t.id}`,u=>{gr(u)?o(u.error):s(u.result)});try{await this.connection.send(t,r)}catch(u){o(u)}})}setConnection(t=this.connection){return t}onPayload(t){this.events.emit("payload",t),Dn(t)?this.events.emit(`${t.id}`,t):this.events.emit("message",{type:t.method,data:t.params})}onClose(t){t&&t.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${t.code} ${t.reason?`(${t.reason})`:""}`)),this.events.emit("disconnect")}async open(t=this.connection){this.connection===t&&this.connection.connected||(this.connection.connected&&this.close(),typeof t=="string"&&(await this.connection.open(t),t=this.connection),this.connection=this.setConnection(t),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",t=>this.onPayload(t)),this.connection.on("close",t=>this.onClose(t)),this.connection.on("error",t=>this.events.emit("error",t)),this.connection.on("register_error",t=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const c1=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),u1=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",qh=a=>a.split("?")[0],Lh=10,h1=c1();let l1=class{constructor(t){if(this.url=t,this.events=new ar.EventEmitter,this.registering=!1,!jh(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);this.url=t}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async open(t=this.url){await this.register(t)}async close(){return new Promise((t,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=s=>{this.onClose(s),t()},this.socket.close()})}async send(t){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(fi(t))}catch(r){this.onError(t.id,r)}}register(t=this.url){if(!jh(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);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((s,o)=>{this.events.once("register_error",u=>{this.resetMaxListeners(),o(u)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return o(new Error("WebSocket connection is missing or invalid"));s(this.socket)})})}return this.url=t,this.registering=!0,new Promise((r,s)=>{const o=new URLSearchParams(t).get("origin"),u=Bl.isReactNative()?{headers:{origin:o}}:{rejectUnauthorized:!a1(t)},f=new h1(t,[],u);u1()?f.onerror=y=>{const v=y;s(this.emitError(v.error))}:f.on("error",y=>{s(this.emitError(y))}),f.onopen=()=>{this.onOpen(f),r(f)}})}onOpen(t){t.onmessage=r=>this.onPayload(r),t.onclose=r=>this.onClose(r),this.socket=t,this.registering=!1,this.events.emit("open")}onClose(t){this.socket=void 0,this.registering=!1,this.events.emit("close",t)}onPayload(t){if(typeof t.data>"u")return;const r=typeof t.data=="string"?_s(t.data):t.data;this.events.emit("payload",r)}onError(t,r){const s=this.parseError(r),o=s.message||s.toString(),u=Nn(t,o);this.events.emit("payload",u)}parseError(t,r=this.url){return Vl(t,qh(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Lh&&this.events.setMaxListeners(Lh)}emitError(t){const r=this.parseError(new Error((t==null?void 0:t.message)||`WebSocket connection failed for host: ${qh(this.url)}`));return this.events.emit("register_error",r),r}};function f1(a,t){return t=t||{},new Promise(function(r,s){var o=new XMLHttpRequest,u=[],f=[],y={},v=function(){return{ok:(o.status/100|0)==2,statusText:o.statusText,status:o.status,url:o.responseURL,text:function(){return Promise.resolve(o.responseText)},json:function(){return Promise.resolve(o.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([o.response]))},clone:v,headers:{keys:function(){return u},entries:function(){return f},get:function(w){return y[w.toLowerCase()]},has:function(w){return w.toLowerCase()in y}}}};for(var p in o.open(t.method||"get",a,!0),o.onload=function(){o.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(w,I,R){u.push(I=I.toLowerCase()),f.push([I,R]),y[I]=y[I]?y[I]+","+R:R}),r(v())},o.onerror=s,o.withCredentials=t.credentials=="include",t.headers)o.setRequestHeader(p,t.headers[p]);o.send(t.body||null)})}const p1=Object.freeze(Object.defineProperty({__proto__:null,default:f1},Symbol.toStringTag,{value:"Module"})),Mh=On(p1);var d1=self.fetch||(self.fetch=Mh.default||Mh);const g1=Aa(d1);var y1={};function v1(a,t){if(a.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),s=0;s>>0,Y=new Uint8Array(re);ie!==he;){for(var ce=O[ie],pe=0,W=re-1;(ce!==0||pe>>0,Y[W]=ce%y>>>0,ce=ce/y>>>0;if(ce!==0)throw new Error("Non-zero carry");X=pe,ie++}for(var de=re-X;de!==re&&Y[de]===0;)de++;for(var et=v.repeat(B);de>>0,re=new Uint8Array(he);O[B];){var Y=r[O.charCodeAt(B)];if(Y===255)return;for(var ce=0,pe=he-1;(Y!==0||ce>>0,re[pe]=Y%256>>>0,Y=Y/256>>>0;if(Y!==0)throw new Error("Non-zero carry");ie=ce,B++}if(O[B]!==" "){for(var W=he-ie;W!==he&&re[W]===0;)W++;for(var de=new Uint8Array(X+(he-W)),et=X;W!==he;)de[et++]=re[W++];return de}}}function $(O){var B=R(O);if(B)return B;throw new Error(`Non-${t} character`)}return{encode:I,decodeUnsafe:R,decode:$}}var m1=v1,w1=m1;const Ql=a=>{if(a instanceof Uint8Array&&a.constructor.name==="Uint8Array")return a;if(a instanceof ArrayBuffer)return new Uint8Array(a);if(ArrayBuffer.isView(a))return new Uint8Array(a.buffer,a.byteOffset,a.byteLength);throw new Error("Unknown type, must be binary type")},b1=a=>new TextEncoder().encode(a),_1=a=>new TextDecoder().decode(a);class E1{constructor(t,r,s){this.name=t,this.prefix=r,this.baseEncode=s}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class I1{constructor(t,r,s){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=s}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Yl(this,t)}}class x1{constructor(t){this.decoders=t}or(t){return Yl(this,t)}decode(t){const r=t[0],s=this.decoders[r];if(s)return s.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Yl=(a,t)=>new x1({...a.decoders||{[a.prefix]:a},...t.decoders||{[t.prefix]:t}});class P1{constructor(t,r,s,o){this.name=t,this.prefix=r,this.baseEncode=s,this.baseDecode=o,this.encoder=new E1(t,r,s),this.decoder=new I1(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}const jn=({name:a,prefix:t,encode:r,decode:s})=>new P1(a,t,r,s),Is=({prefix:a,name:t,alphabet:r})=>{const{encode:s,decode:o}=w1(r,t);return jn({prefix:a,name:t,encode:s,decode:u=>Ql(o(u))})},S1=(a,t,r,s)=>{const o={};for(let w=0;w=8&&(y-=8,f[p++]=255&v>>y)}if(y>=r||255&v<<8-y)throw new SyntaxError("Unexpected end of data");return f},O1=(a,t,r)=>{const s=t[t.length-1]==="=",o=(1<r;)f-=r,u+=t[o&y>>f];if(f&&(u+=t[o&y<jn({prefix:t,name:a,encode(o){return O1(o,s,r)},decode(o){return S1(o,s,r,a)}}),R1=jn({prefix:"\0",name:"identity",encode:a=>_1(a),decode:a=>b1(a)});var A1=Object.freeze({__proto__:null,identity:R1});const C1=Et({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var $1=Object.freeze({__proto__:null,base2:C1});const T1=Et({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var N1=Object.freeze({__proto__:null,base8:T1});const D1=Is({prefix:"9",name:"base10",alphabet:"0123456789"});var j1=Object.freeze({__proto__:null,base10:D1});const q1=Et({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),L1=Et({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var M1=Object.freeze({__proto__:null,base16:q1,base16upper:L1});const z1=Et({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),U1=Et({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),k1=Et({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),H1=Et({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),K1=Et({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),V1=Et({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),B1=Et({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),F1=Et({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),G1=Et({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var W1=Object.freeze({__proto__:null,base32:z1,base32upper:U1,base32pad:k1,base32padupper:H1,base32hex:K1,base32hexupper:V1,base32hexpad:B1,base32hexpadupper:F1,base32z:G1});const J1=Is({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Q1=Is({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Y1=Object.freeze({__proto__:null,base36:J1,base36upper:Q1});const Z1=Is({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),X1=Is({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var eE=Object.freeze({__proto__:null,base58btc:Z1,base58flickr:X1});const tE=Et({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rE=Et({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),iE=Et({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),sE=Et({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var nE=Object.freeze({__proto__:null,base64:tE,base64pad:rE,base64url:iE,base64urlpad:sE});const Zl=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),oE=Zl.reduce((a,t,r)=>(a[r]=t,a),[]),aE=Zl.reduce((a,t,r)=>(a[t.codePointAt(0)]=r,a),[]);function cE(a){return a.reduce((t,r)=>(t+=oE[r],t),"")}function uE(a){const t=[];for(const r of a){const s=aE[r.codePointAt(0)];if(s===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(s)}return new Uint8Array(t)}const hE=jn({prefix:"🚀",name:"base256emoji",encode:cE,decode:uE});var lE=Object.freeze({__proto__:null,base256emoji:hE}),fE=Xl,zh=128,pE=127,dE=~pE,gE=Math.pow(2,31);function Xl(a,t,r){t=t||[],r=r||0;for(var s=r;a>=gE;)t[r++]=a&255|zh,a/=128;for(;a&dE;)t[r++]=a&255|zh,a>>>=7;return t[r]=a|0,Xl.bytes=r-s+1,t}var yE=ba,vE=128,Uh=127;function ba(a,s){var r=0,s=s||0,o=0,u=s,f,y=a.length;do{if(u>=y)throw ba.bytes=0,new RangeError("Could not decode varint");f=a[u++],r+=o<28?(f&Uh)<=vE);return ba.bytes=u-s,r}var mE=Math.pow(2,7),wE=Math.pow(2,14),bE=Math.pow(2,21),_E=Math.pow(2,28),EE=Math.pow(2,35),IE=Math.pow(2,42),xE=Math.pow(2,49),PE=Math.pow(2,56),SE=Math.pow(2,63),OE=function(a){return a(ef.encode(a,t,r),t),Hh=a=>ef.encodingLength(a),_a=(a,t)=>{const r=t.byteLength,s=Hh(a),o=s+Hh(r),u=new Uint8Array(o+r);return kh(a,u,0),kh(r,u,s),u.set(t,o),new AE(a,r,t,u)};class AE{constructor(t,r,s,o){this.code=t,this.size=r,this.digest=s,this.bytes=o}}const tf=({name:a,code:t,encode:r})=>new CE(a,t,r);class CE{constructor(t,r,s){this.name=t,this.code=r,this.encode=s}digest(t){if(t instanceof Uint8Array){const r=this.encode(t);return r instanceof Uint8Array?_a(this.code,r):r.then(s=>_a(this.code,s))}else throw Error("Unknown type, must be binary type")}}const rf=a=>async t=>new Uint8Array(await crypto.subtle.digest(a,t)),$E=tf({name:"sha2-256",code:18,encode:rf("SHA-256")}),TE=tf({name:"sha2-512",code:19,encode:rf("SHA-512")});var NE=Object.freeze({__proto__:null,sha256:$E,sha512:TE});const sf=0,DE="identity",nf=Ql,jE=a=>_a(sf,nf(a)),qE={code:sf,name:DE,encode:nf,digest:jE};var LE=Object.freeze({__proto__:null,identity:qE});new TextEncoder,new TextDecoder;const Kh={...A1,...$1,...N1,...j1,...M1,...W1,...Y1,...eE,...nE,...lE};({...NE,...LE});function of(a){return globalThis.Buffer!=null?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):a}function ME(a=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?of(globalThis.Buffer.allocUnsafe(a)):new Uint8Array(a)}function af(a,t,r,s){return{name:a,prefix:t,encoder:{name:a,prefix:t,encode:r},decoder:{decode:s}}}const Vh=af("utf8","u",a=>"u"+new TextDecoder("utf8").decode(a),a=>new TextEncoder().encode(a.substring(1))),ta=af("ascii","a",a=>{let t="a";for(let r=0;r{a=a.substring(1);const t=ME(a.length);for(let r=0;r{if(!this.initialized){const s=await this.getKeyChain();typeof s<"u"&&(this.keychain=s),this.initialized=!0}},this.has=s=>(this.isInitialized(),this.keychain.has(s)),this.set=async(s,o)=>{this.isInitialized(),this.keychain.set(s,o),await this.persist()},this.get=s=>{this.isInitialized();const o=this.keychain.get(s);if(typeof o>"u"){const{message:u}=K("NO_MATCHING_KEY",`${this.name}: ${s}`);throw new Error(u)}return o},this.del=async s=>{this.isInitialized(),this.keychain.delete(s),await this.persist()},this.core=t,this.logger=Ht(r,this.name)}get context(){return kt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(t){await this.core.storage.setItem(this.storageKey,Rl(t))}async getKeyChain(){const t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?Al(t):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:t}=K("NOT_INITIALIZED",this.name);throw new Error(t)}}}class wI{constructor(t,r,s){this.core=t,this.logger=r,this.name=VE,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=o=>(this.isInitialized(),this.keychain.has(o)),this.getClientId=async()=>{this.isInitialized();const o=await this.getClientSeed(),u=Ch(o);return kl(u.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const o=U0();return this.setPrivateKey(o.publicKey,o.privateKey)},this.signJWT=async o=>{this.isInitialized();const u=await this.getClientSeed(),f=Ch(u),y=ha();return await I_(y,o,BE,f)},this.generateSharedKey=(o,u,f)=>{this.isInitialized();const y=this.getPrivateKey(o),v=k0(y,u);return this.setSymKey(v,f)},this.setSymKey=async(o,u)=>{this.isInitialized();const f=u||H0(o);return await this.keychain.set(f,o),f},this.deleteKeyPair=async o=>{this.isInitialized(),await this.keychain.del(o)},this.deleteSymKey=async o=>{this.isInitialized(),await this.keychain.del(o)},this.encode=async(o,u,f)=>{this.isInitialized();const y=K0(f),v=fi(u);if(lh(y)){const R=y.senderPublicKey,$=y.receiverPublicKey;o=await this.generateSharedKey(R,$)}const p=this.getSymKey(o),{type:w,senderPublicKey:I}=y;return V0({type:w,symKey:p,message:v,senderPublicKey:I})},this.decode=async(o,u,f)=>{this.isInitialized();const y=B0(u,f);if(lh(y)){const v=y.receiverPublicKey,p=y.senderPublicKey;o=await this.generateSharedKey(v,p)}try{const v=this.getSymKey(o),p=F0({symKey:v,encoded:u});return _s(p)}catch(v){this.logger.error(`Failed to decode message from topic: '${o}', clientId: '${await this.getClientId()}'`),this.logger.error(v)}},this.getPayloadType=o=>{const u=fh(o);return G0(u.type)},this.getPayloadSenderPublicKey=o=>{const u=fh(o);return u.senderPublicKey?Sn(u.senderPublicKey,W0):void 0},this.core=t,this.logger=Ht(r,this.name),this.keychain=s||new mI(this.core,this.logger)}get context(){return kt(this.logger)}async setPrivateKey(t,r){return await this.keychain.set(t,r),t}getPrivateKey(t){return this.keychain.get(t)}async getClientSeed(){let t="";try{t=this.keychain.get(Bh)}catch{t=ha(),await this.keychain.set(Bh,t)}return UE(t,"base16")}getSymKey(t){return this.keychain.get(t)}isInitialized(){if(!this.initialized){const{message:t}=K("NOT_INITIALIZED",this.name);throw new Error(t)}}}class bI extends e_{constructor(t,r){super(t,r),this.logger=t,this.core=r,this.messages=new Map,this.name=WE,this.version=JE,this.initialized=!1,this.storagePrefix=Yr,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const s=await this.getRelayerMessages();typeof s<"u"&&(this.messages=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(s){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(s)}finally{this.initialized=!0}}},this.set=async(s,o)=>{this.isInitialized();const u=Li(o);let f=this.messages.get(s);return typeof f>"u"&&(f={}),typeof f[u]<"u"||(f[u]=o,this.messages.set(s,f),await this.persist()),u},this.get=s=>{this.isInitialized();let o=this.messages.get(s);return typeof o>"u"&&(o={}),o},this.has=(s,o)=>{this.isInitialized();const u=this.get(s),f=Li(o);return typeof u[f]<"u"},this.del=async s=>{this.isInitialized(),this.messages.delete(s),await this.persist()},this.logger=Ht(t,this.name),this.core=r}get context(){return kt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(t){await this.core.storage.setItem(this.storageKey,Rl(t))}async getRelayerMessages(){const t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?Al(t):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:t}=K("NOT_INITIALIZED",this.name);throw new Error(t)}}}class _I extends t_{constructor(t,r){super(t,r),this.relayer=t,this.logger=r,this.events=new ar.EventEmitter,this.name=YE,this.queue=new Map,this.publishTimeout=Q.toMiliseconds(Q.TEN_SECONDS),this.needsTransportRestart=!1,this.publish=async(s,o,u)=>{var f;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:s,message:o,opts:u}});try{const y=(u==null?void 0:u.ttl)||QE,v=la(u),p=(u==null?void 0:u.prompt)||!1,w=(u==null?void 0:u.tag)||0,I=(u==null?void 0:u.id)||Gl().toString(),R={topic:s,message:o,opts:{ttl:y,relay:v,prompt:p,tag:w,id:I}},$=setTimeout(()=>this.queue.set(I,R),this.publishTimeout);try{await await gs(this.rpcPublish(s,o,y,v,p,w,I),this.publishTimeout,"Failed to publish payload, please try again."),this.removeRequestFromQueue(I),this.relayer.events.emit(Ot.publish,R)}catch(O){if(this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0,(f=u==null?void 0:u.internal)!=null&&f.throwOnFailedPublish)throw this.removeRequestFromQueue(I),O;return}finally{clearTimeout($)}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:s,message:o,opts:u}})}catch(y){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(y),y}},this.on=(s,o)=>{this.events.on(s,o)},this.once=(s,o)=>{this.events.once(s,o)},this.off=(s,o)=>{this.events.off(s,o)},this.removeListener=(s,o)=>{this.events.removeListener(s,o)},this.relayer=t,this.logger=Ht(r,this.name),this.registerEventListeners()}get context(){return kt(this.logger)}rpcPublish(t,r,s,o,u,f,y){var v,p,w,I;const R={method:bn(o.protocol).publish,params:{topic:t,message:r,ttl:s,prompt:u,tag:f},id:y};return Qr((v=R.params)==null?void 0:v.prompt)&&((p=R.params)==null||delete p.prompt),Qr((w=R.params)==null?void 0:w.tag)&&((I=R.params)==null||delete I.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:R}),this.relayer.request(R)}removeRequestFromQueue(t){this.queue.delete(t)}checkQueue(){this.queue.forEach(async t=>{const{topic:r,message:s,opts:o}=t;await this.publish(r,s,o)})}registerEventListeners(){this.relayer.core.heartbeat.on(Ui.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Ot.connection_stalled);return}this.checkQueue()}),this.relayer.on(Ot.message_ack,t=>{this.removeRequestFromQueue(t.id.toString())})}}class EI{constructor(){this.map=new Map,this.set=(t,r)=>{const s=this.get(t);this.exists(t,r)||this.map.set(t,[...s,r])},this.get=t=>this.map.get(t)||[],this.exists=(t,r)=>this.get(t).includes(r),this.delete=(t,r)=>{if(typeof r>"u"){this.map.delete(t);return}if(!this.map.has(t))return;const s=this.get(t);if(!this.exists(t,r))return;const o=s.filter(u=>u!==r);if(!o.length){this.map.delete(t);return}this.map.set(t,o)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var II=Object.defineProperty,xI=Object.defineProperties,PI=Object.getOwnPropertyDescriptors,Gh=Object.getOwnPropertySymbols,SI=Object.prototype.hasOwnProperty,OI=Object.prototype.propertyIsEnumerable,Wh=(a,t,r)=>t in a?II(a,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):a[t]=r,as=(a,t)=>{for(var r in t||(t={}))SI.call(t,r)&&Wh(a,r,t[r]);if(Gh)for(var r of Gh(t))OI.call(t,r)&&Wh(a,r,t[r]);return a},ia=(a,t)=>xI(a,PI(t));class RI extends s_{constructor(t,r){super(t,r),this.relayer=t,this.logger=r,this.subscriptions=new Map,this.topicMap=new EI,this.events=new ar.EventEmitter,this.name=oI,this.version=aI,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=Yr,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(s,o)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:s,opts:o}});try{const u=la(o),f={topic:s,relay:u};this.pending.set(s,f);const y=await this.rpcSubscribe(s,u);return this.onSubscribe(y,f),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:s,opts:o}}),y}catch(u){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(u),u}},this.unsubscribe=async(s,o)=>{await this.restartToComplete(),this.isInitialized(),typeof(o==null?void 0:o.id)<"u"?await this.unsubscribeById(s,o.id,o):await this.unsubscribeByTopic(s,o)},this.isSubscribed=async s=>this.topics.includes(s)?!0:await new Promise((o,u)=>{const f=new Q.Watch;f.start(this.pendingSubscriptionWatchLabel);const y=setInterval(()=>{!this.pending.has(s)&&this.topics.includes(s)&&(clearInterval(y),f.stop(this.pendingSubscriptionWatchLabel),o(!0)),f.elapsed(this.pendingSubscriptionWatchLabel)>=cI&&(clearInterval(y),f.stop(this.pendingSubscriptionWatchLabel),u(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1),this.on=(s,o)=>{this.events.on(s,o)},this.once=(s,o)=>{this.events.once(s,o)},this.off=(s,o)=>{this.events.off(s,o)},this.removeListener=(s,o)=>{this.events.removeListener(s,o)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=t,this.logger=Ht(r,this.name),this.clientId=""}get context(){return kt(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}hasSubscription(t,r){let s=!1;try{s=this.getSubscription(t).topic===r}catch{}return s}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(t,r){const s=this.topicMap.get(t);await Promise.all(s.map(async o=>await this.unsubscribeById(t,o,r)))}async unsubscribeById(t,r,s){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:r,opts:s}});try{const o=la(s);await this.rpcUnsubscribe(t,r,o);const u=St("USER_DISCONNECTED",`${this.name}, ${t}`);await this.onUnsubscribe(t,r,u),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:r,opts:s}})}catch(o){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(o),o}}async rpcSubscribe(t,r){const s={method:bn(r.protocol).subscribe,params:{topic:t}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});try{await await gs(this.relayer.request(s),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Ot.connection_stalled)}return Li(t+this.clientId)}async rpcBatchSubscribe(t){if(!t.length)return;const r=t[0].relay,s={method:bn(r.protocol).batchSubscribe,params:{topics:t.map(o=>o.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});try{return await await gs(this.relayer.request(s),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(Ot.connection_stalled)}}rpcUnsubscribe(t,r,s){const o={method:bn(s.protocol).unsubscribe,params:{topic:t,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:o}),this.relayer.request(o)}onSubscribe(t,r){this.setSubscription(t,ia(as({},r),{id:t})),this.pending.delete(r.topic)}onBatchSubscribe(t){t.length&&t.forEach(r=>{this.setSubscription(r.id,as({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(t,r,s){this.events.removeAllListeners(r),this.hasSubscription(r,t)&&this.deleteSubscription(r,s),await this.relayer.messages.del(t)}async setRelayerSubscriptions(t){await this.relayer.core.storage.setItem(this.storageKey,t)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(t,r){this.subscriptions.has(t)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:t,subscription:r}),this.addSubscription(t,r))}addSubscription(t,r){this.subscriptions.set(t,as({},r)),this.topicMap.set(r.topic,t),this.events.emit(pr.created,r)}getSubscription(t){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:t});const r=this.subscriptions.get(t);if(!r){const{message:s}=K("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(s)}return r}deleteSubscription(t,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:t,reason:r});const s=this.getSubscription(t);this.subscriptions.delete(t),this.topicMap.delete(s.topic,t),this.events.emit(pr.deleted,ia(as({},s),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(pr.sync)}async reset(){if(this.cached.length){const t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r"u"||!t.length)return;if(this.subscriptions.size){const{message:r}=K("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(t){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(t)}}async batchSubscribe(t){if(!t.length)return;const r=await this.rpcBatchSubscribe(t);zi(r)&&this.onBatchSubscribe(r.map((s,o)=>ia(as({},t[o]),{id:s})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||this.relayer.transportExplicitlyClosed)return;const t=[];this.pending.forEach(r=>{t.push(r)}),await this.batchSubscribe(t)}registerEventListeners(){this.relayer.core.heartbeat.on(Ui.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(Ot.connect,async()=>{await this.onConnect()}),this.relayer.on(Ot.disconnect,()=>{this.onDisconnect()}),this.events.on(pr.created,async t=>{const r=pr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),await this.persist()}),this.events.on(pr.deleted,async t=>{const r=pr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:t}=K("NOT_INITIALIZED",this.name);throw new Error(t)}}async restartToComplete(){this.restartInProgress&&await new Promise(t=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),t())},this.pollingInterval)})}}var AI=Object.defineProperty,Jh=Object.getOwnPropertySymbols,CI=Object.prototype.hasOwnProperty,$I=Object.prototype.propertyIsEnumerable,Qh=(a,t,r)=>t in a?AI(a,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):a[t]=r,TI=(a,t)=>{for(var r in t||(t={}))CI.call(t,r)&&Qh(a,r,t[r]);if(Jh)for(var r of Jh(t))$I.call(t,r)&&Qh(a,r,t[r]);return a};class NI extends r_{constructor(t){super(t),this.protocol="wc",this.version=2,this.events=new ar.EventEmitter,this.name=XE,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],this.hasExperiencedNetworkDisruption=!1,this.request=async r=>{this.logger.debug("Publishing Request Payload");try{return await this.toEstablishConnection(),await this.provider.request(r)}catch(s){throw this.logger.debug("Failed to Publish Request"),this.logger.error(s),s}},this.onPayloadHandler=r=>{this.onProviderPayload(r)},this.onConnectHandler=()=>{this.events.emit(Ot.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(Ot.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(Nr.payload,this.onPayloadHandler),this.provider.on(Nr.connect,this.onConnectHandler),this.provider.on(Nr.disconnect,this.onDisconnectHandler),this.provider.on(Nr.error,this.onProviderErrorHandler)},this.core=t.core,this.logger=typeof t.logger<"u"&&typeof t.logger!="string"?Ht(t.logger,this.name):Cn($n({level:t.logger||ZE})),this.messages=new bI(this.logger,t.core),this.subscriber=new RI(this,this.logger),this.publisher=new _I(this,this.logger),this.relayUrl=(t==null?void 0:t.relayUrl)||hf,this.projectId=t.projectId,this.bundleId=J0(),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await this.createProvider(),await Promise.all([this.messages.init(),this.subscriber.init()]);try{await this.transportOpen()}catch{this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${Fh}...`),await this.restartTransport(Fh)}this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},iI)}get context(){return kt(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(t,r,s){this.isInitialized(),await this.publisher.publish(t,r,s),await this.recordMessageEvent({topic:t,message:r,publishedAt:Date.now()})}async subscribe(t,r){var s;this.isInitialized();let o=((s=this.subscriber.topicMap.get(t))==null?void 0:s[0])||"";if(o)return o;let u;const f=y=>{y.topic===t&&(this.subscriber.off(pr.created,f),u())};return await Promise.all([new Promise(y=>{u=y,this.subscriber.on(pr.created,f)}),new Promise(async y=>{o=await this.subscriber.subscribe(t,r),y()})]),o}async unsubscribe(t,r){this.isInitialized(),await this.subscriber.unsubscribe(t,r)}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async transportClose(){this.transportExplicitlyClosed=!0,this.hasExperiencedNetworkDisruption&&this.connected?await gs(this.provider.disconnect(),1e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.connected&&await this.provider.disconnect()}async transportOpen(t){if(this.transportExplicitlyClosed=!1,await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress){t&&t!==this.relayUrl&&(this.relayUrl=t,await this.transportClose(),await this.createProvider()),this.connectionAttemptInProgress=!0;try{await Promise.all([new Promise(r=>{if(!this.initialized)return r();this.subscriber.once(pr.resubscribed,()=>{r()})}),new Promise(async(r,s)=>{try{await gs(this.provider.connect(),1e4,`Socket stalled when trying to connect to ${this.relayUrl}`)}catch(o){s(o);return}r()})])}catch(r){this.logger.error(r);const s=r;if(!this.isConnectionStalled(s.message))throw r;this.provider.events.emit(Nr.disconnect)}finally{this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1}}}async restartTransport(t){await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress&&(this.relayUrl=t||this.relayUrl,await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await ph())throw new Error("No internet connection detected. Please restart your network and try again.")}isConnectionStalled(t){return this.staleConnectionErrors.some(r=>t.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const t=await this.core.crypto.signJWT(this.relayUrl);this.provider=new qr(new l1(Q0({sdkVersion:rI,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:t,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(t){const{topic:r,message:s}=t;await this.messages.set(r,s)}async shouldIgnoreMessageEvent(t){const{topic:r,message:s}=t;if(!s||s.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${s}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;const o=this.messages.has(r,s);return o&&this.logger.debug(`Ignoring duplicate message: ${s}`),o}async onProviderPayload(t){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:t}),Na(t)){if(!t.method.endsWith(eI))return;const r=t.params,{topic:s,message:o,publishedAt:u}=r.data,f={topic:s,message:o,publishedAt:u};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(TI({type:"event",event:r.id},f)),this.events.emit(r.id,f),await this.acknowledgePayload(t),await this.onMessageEvent(f)}else Dn(t)&&this.events.emit(Ot.message_ack,t)}async onMessageEvent(t){await this.shouldIgnoreMessageEvent(t)||(this.events.emit(Ot.message,t),await this.recordMessageEvent(t))}async acknowledgePayload(t){const r=Tn(t.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Nr.payload,this.onPayloadHandler),this.provider.off(Nr.connect,this.onConnectHandler),this.provider.off(Nr.disconnect,this.onDisconnectHandler),this.provider.off(Nr.error,this.onProviderErrorHandler)}async registerEventListeners(){this.events.on(Ot.connection_stalled,()=>{this.restartTransport().catch(r=>this.logger.error(r))});let t=await ph();Y0(async r=>{this.initialized&&t!==r&&(t=r,r?await this.restartTransport().catch(s=>this.logger.error(s)):(this.hasExperiencedNetworkDisruption=!0,await this.transportClose().catch(s=>this.logger.error(s))))})}onProviderDisconnect(){this.events.emit(Ot.disconnect),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||(this.logger.info("attemptToReconnect called. Connecting..."),setTimeout(async()=>{await this.restartTransport().catch(t=>this.logger.error(t))},Q.toMiliseconds(tI)))}isInitialized(){if(!this.initialized){const{message:t}=K("NOT_INITIALIZED",this.name);throw new Error(t)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectionAttemptInProgress)return await new Promise(t=>{const r=setInterval(()=>{this.connected&&(clearInterval(r),t())},this.connectionStatusPollingInterval)});await this.restartTransport()}}}var DI=Object.defineProperty,Yh=Object.getOwnPropertySymbols,jI=Object.prototype.hasOwnProperty,qI=Object.prototype.propertyIsEnumerable,Zh=(a,t,r)=>t in a?DI(a,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):a[t]=r,Xh=(a,t)=>{for(var r in t||(t={}))jI.call(t,r)&&Zh(a,r,t[r]);if(Yh)for(var r of Yh(t))qI.call(t,r)&&Zh(a,r,t[r]);return a};class qn extends i_{constructor(t,r,s,o=Yr,u=void 0){super(t,r,s,o),this.core=t,this.logger=r,this.name=s,this.map=new Map,this.version=sI,this.cached=[],this.initialized=!1,this.storagePrefix=Yr,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(f=>{this.getKey&&f!==null&&!Qr(f)?this.map.set(this.getKey(f),f):M0(f)?this.map.set(f.id,f):z0(f)&&this.map.set(f.topic,f)}),this.cached=[],this.initialized=!0)},this.set=async(f,y)=>{this.isInitialized(),this.map.has(f)?await this.update(f,y):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:f,value:y}),this.map.set(f,y),await this.persist())},this.get=f=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:f}),this.getData(f)),this.getAll=f=>(this.isInitialized(),f?this.values.filter(y=>Object.keys(f).every(v=>Iw(y[v],f[v]))):this.values),this.update=async(f,y)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:f,update:y});const v=Xh(Xh({},this.getData(f)),y);this.map.set(f,v),await this.persist()},this.delete=async(f,y)=>{this.isInitialized(),this.map.has(f)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:f,reason:y}),this.map.delete(f),await this.persist())},this.logger=Ht(r,this.name),this.storagePrefix=o,this.getKey=u}get context(){return kt(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())}async setDataStore(t){await this.core.storage.setItem(this.storageKey,t)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(t){const r=this.map.get(t);if(!r){const{message:s}=K("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.error(s),new Error(s)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const t=await this.getDataStore();if(typeof t>"u"||!t.length)return;if(this.map.size){const{message:r}=K("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(t){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(t)}}isInitialized(){if(!this.initialized){const{message:t}=K("NOT_INITIALIZED",this.name);throw new Error(t)}}}class LI{constructor(t,r){this.core=t,this.logger=r,this.name=uI,this.version=hI,this.events=new Oa,this.initialized=!1,this.storagePrefix=Yr,this.ignoredPayloadTypes=[Pl],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:s})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...s])]},this.create=async()=>{this.isInitialized();const s=ha(),o=await this.core.crypto.setSymKey(s),u=dr(Q.FIVE_MINUTES),f={protocol:uf},y={topic:o,expiry:u,relay:f,active:!1},v=Z0({protocol:this.core.protocol,version:this.core.version,topic:o,symKey:s,relay:f});return await this.pairings.set(o,y),await this.core.relayer.subscribe(o),this.core.expirer.set(o,u),{topic:o,uri:v}},this.pair=async s=>{this.isInitialized(),this.isValidPair(s);const{topic:o,symKey:u,relay:f}=dh(s.uri);let y;if(this.pairings.keys.includes(o)&&(y=this.pairings.get(o),y.active))throw new Error(`Pairing already exists: ${o}. Please try again with a new connection URI.`);const v=dr(Q.FIVE_MINUTES),p={topic:o,relay:f,expiry:v,active:!1};return await this.pairings.set(o,p),this.core.expirer.set(o,v),s.activatePairing&&await this.activate({topic:o}),this.events.emit(fs.create,p),this.core.crypto.keychain.has(o)||(await this.core.crypto.setSymKey(u,o),await this.core.relayer.subscribe(o,{relay:f})),p},this.activate=async({topic:s})=>{this.isInitialized();const o=dr(Q.THIRTY_DAYS);await this.pairings.update(s,{active:!0,expiry:o}),this.core.expirer.set(s,o)},this.ping=async s=>{this.isInitialized(),await this.isValidPing(s);const{topic:o}=s;if(this.pairings.keys.includes(o)){const u=await this.sendRequest(o,"wc_pairingPing",{}),{done:f,resolve:y,reject:v}=Di();this.events.once(We("pairing_ping",u),({error:p})=>{p?v(p):y()}),await f()}},this.updateExpiry=async({topic:s,expiry:o})=>{this.isInitialized(),await this.pairings.update(s,{expiry:o})},this.updateMetadata=async({topic:s,metadata:o})=>{this.isInitialized(),await this.pairings.update(s,{peerMetadata:o})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async s=>{this.isInitialized(),await this.isValidDisconnect(s);const{topic:o}=s;this.pairings.keys.includes(o)&&(await this.sendRequest(o,"wc_pairingDelete",St("USER_DISCONNECTED")),await this.deletePairing(o))},this.sendRequest=async(s,o,u)=>{const f=Mi(o,u),y=await this.core.crypto.encode(s,f),v=os[o].req;return this.core.history.set(s,f),this.core.relayer.publish(s,y,v),f.id},this.sendResult=async(s,o,u)=>{const f=Tn(s,u),y=await this.core.crypto.encode(o,f),v=await this.core.history.get(o,s),p=os[v.request.method].res;await this.core.relayer.publish(o,y,p),await this.core.history.resolve(f)},this.sendError=async(s,o,u)=>{const f=Nn(s,u),y=await this.core.crypto.encode(o,f),v=await this.core.history.get(o,s),p=os[v.request.method]?os[v.request.method].res:os.unregistered_method.res;await this.core.relayer.publish(o,y,p),await this.core.history.resolve(f)},this.deletePairing=async(s,o)=>{await this.core.relayer.unsubscribe(s),await Promise.all([this.pairings.delete(s,St("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(s),o?Promise.resolve():this.core.expirer.del(s)])},this.cleanup=async()=>{const s=this.pairings.getAll().filter(o=>Jr(o.expiry));await Promise.all(s.map(o=>this.deletePairing(o.topic)))},this.onRelayEventRequest=s=>{const{topic:o,payload:u}=s;switch(u.method){case"wc_pairingPing":return this.onPairingPingRequest(o,u);case"wc_pairingDelete":return this.onPairingDeleteRequest(o,u);default:return this.onUnknownRpcMethodRequest(o,u)}},this.onRelayEventResponse=async s=>{const{topic:o,payload:u}=s,f=(await this.core.history.get(o,u.id)).request.method;switch(f){case"wc_pairingPing":return this.onPairingPingResponse(o,u);default:return this.onUnknownRpcMethodResponse(f)}},this.onPairingPingRequest=async(s,o)=>{const{id:u}=o;try{this.isValidPing({topic:s}),await this.sendResult(u,s,!0),this.events.emit(fs.ping,{id:u,topic:s})}catch(f){await this.sendError(u,s,f),this.logger.error(f)}},this.onPairingPingResponse=(s,o)=>{const{id:u}=o;setTimeout(()=>{jr(o)?this.events.emit(We("pairing_ping",u),{}):gr(o)&&this.events.emit(We("pairing_ping",u),{error:o.error})},500)},this.onPairingDeleteRequest=async(s,o)=>{const{id:u}=o;try{this.isValidDisconnect({topic:s}),await this.deletePairing(s),this.events.emit(fs.delete,{id:u,topic:s})}catch(f){await this.sendError(u,s,f),this.logger.error(f)}},this.onUnknownRpcMethodRequest=async(s,o)=>{const{id:u,method:f}=o;try{if(this.registeredMethods.includes(f))return;const y=St("WC_METHOD_UNSUPPORTED",f);await this.sendError(u,s,y),this.logger.error(y)}catch(y){await this.sendError(u,s,y),this.logger.error(y)}},this.onUnknownRpcMethodResponse=s=>{this.registeredMethods.includes(s)||this.logger.error(St("WC_METHOD_UNSUPPORTED",s))},this.isValidPair=s=>{var o;if(!Ut(s)){const{message:f}=K("MISSING_OR_INVALID",`pair() params: ${s}`);throw new Error(f)}if(!X0(s.uri)){const{message:f}=K("MISSING_OR_INVALID",`pair() uri: ${s.uri}`);throw new Error(f)}const u=dh(s.uri);if(!((o=u==null?void 0:u.relay)!=null&&o.protocol)){const{message:f}=K("MISSING_OR_INVALID","pair() uri#relay-protocol");throw new Error(f)}if(!(u!=null&&u.symKey)){const{message:f}=K("MISSING_OR_INVALID","pair() uri#symKey");throw new Error(f)}},this.isValidPing=async s=>{if(!Ut(s)){const{message:u}=K("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(u)}const{topic:o}=s;await this.isValidPairingTopic(o)},this.isValidDisconnect=async s=>{if(!Ut(s)){const{message:u}=K("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(u)}const{topic:o}=s;await this.isValidPairingTopic(o)},this.isValidPairingTopic=async s=>{if(!ji(s,!1)){const{message:o}=K("MISSING_OR_INVALID",`pairing topic should be a string: ${s}`);throw new Error(o)}if(!this.pairings.keys.includes(s)){const{message:o}=K("NO_MATCHING_KEY",`pairing topic doesn't exist: ${s}`);throw new Error(o)}if(Jr(this.pairings.get(s).expiry)){await this.deletePairing(s);const{message:o}=K("EXPIRED",`pairing topic: ${s}`);throw new Error(o)}},this.core=t,this.logger=Ht(r,this.name),this.pairings=new qn(this.core,this.logger,this.name,this.storagePrefix)}get context(){return kt(this.logger)}isInitialized(){if(!this.initialized){const{message:t}=K("NOT_INITIALIZED",this.name);throw new Error(t)}}registerRelayerEvents(){this.core.relayer.on(Ot.message,async t=>{const{topic:r,message:s}=t;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))return;const o=await this.core.crypto.decode(r,s);try{Na(o)?(this.core.history.set(r,o),this.onRelayEventRequest({topic:r,payload:o})):Dn(o)&&(await this.core.history.resolve(o),await this.onRelayEventResponse({topic:r,payload:o}),this.core.history.delete(r,o.id))}catch(u){this.logger.error(u)}})}registerExpirerEvents(){this.core.expirer.on(or.expired,async t=>{const{topic:r}=Sl(t.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(fs.expire,{topic:r}))})}}class MI extends Xb{constructor(t,r){super(t,r),this.core=t,this.logger=r,this.records=new Map,this.events=new ar.EventEmitter,this.name=lI,this.version=fI,this.cached=[],this.initialized=!1,this.storagePrefix=Yr,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(s=>this.records.set(s.id,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(s,o,u)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:s,request:o,chainId:u}),this.records.has(o.id))return;const f={id:o.id,topic:s,request:{method:o.method,params:o.params||null},chainId:u,expiry:dr(Q.THIRTY_DAYS)};this.records.set(f.id,f),this.events.emit(br.created,f)},this.resolve=async s=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:s}),!this.records.has(s.id))return;const o=await this.getRecord(s.id);typeof o.response>"u"&&(o.response=gr(s)?{error:s.error}:{result:s.result},this.records.set(o.id,o),this.events.emit(br.updated,o))},this.get=async(s,o)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:s,id:o}),await this.getRecord(o)),this.delete=(s,o)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:o}),this.values.forEach(u=>{if(u.topic===s){if(typeof o<"u"&&u.id!==o)return;this.records.delete(u.id),this.events.emit(br.deleted,u)}})},this.exists=async(s,o)=>(this.isInitialized(),this.records.has(o)?(await this.getRecord(o)).topic===s:!1),this.on=(s,o)=>{this.events.on(s,o)},this.once=(s,o)=>{this.events.once(s,o)},this.off=(s,o)=>{this.events.off(s,o)},this.removeListener=(s,o)=>{this.events.removeListener(s,o)},this.logger=Ht(r,this.name)}get context(){return kt(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 t=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const s={topic:r.topic,request:Mi(r.request.method,r.request.params,r.id),chainId:r.chainId};return t.push(s)}),t}async setJsonRpcRecords(t){await this.core.storage.setItem(this.storageKey,t)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(t){this.isInitialized();const r=this.records.get(t);if(!r){const{message:s}=K("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(s)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(br.sync)}async restore(){try{const t=await this.getJsonRpcRecords();if(typeof t>"u"||!t.length)return;if(this.records.size){const{message:r}=K("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(t){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(t)}}registerEventListeners(){this.events.on(br.created,t=>{const r=br.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t}),this.persist()}),this.events.on(br.updated,t=>{const r=br.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t}),this.persist()}),this.events.on(br.deleted,t=>{const r=br.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t}),this.persist()}),this.core.heartbeat.on(Ui.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.records.forEach(t=>{Q.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.delete(t.topic,t.id))})}catch(t){this.logger.warn(t)}}isInitialized(){if(!this.initialized){const{message:t}=K("NOT_INITIALIZED",this.name);throw new Error(t)}}}class zI extends n_{constructor(t,r){super(t,r),this.core=t,this.logger=r,this.expirations=new Map,this.events=new ar.EventEmitter,this.name=pI,this.version=dI,this.cached=[],this.initialized=!1,this.storagePrefix=Yr,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(s=>this.expirations.set(s.target,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=s=>{try{const o=this.formatTarget(s);return typeof this.getExpiration(o)<"u"}catch{return!1}},this.set=(s,o)=>{this.isInitialized();const u=this.formatTarget(s),f={target:u,expiry:o};this.expirations.set(u,f),this.checkExpiry(u,f),this.events.emit(or.created,{target:u,expiration:f})},this.get=s=>{this.isInitialized();const o=this.formatTarget(s);return this.getExpiration(o)},this.del=s=>{if(this.isInitialized(),this.has(s)){const o=this.formatTarget(s),u=this.getExpiration(o);this.expirations.delete(o),this.events.emit(or.deleted,{target:o,expiration:u})}},this.on=(s,o)=>{this.events.on(s,o)},this.once=(s,o)=>{this.events.once(s,o)},this.off=(s,o)=>{this.events.off(s,o)},this.removeListener=(s,o)=>{this.events.removeListener(s,o)},this.logger=Ht(r,this.name)}get context(){return kt(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(t){if(typeof t=="string")return ew(t);if(typeof t=="number")return tw(t);const{message:r}=K("UNKNOWN_TYPE",`Target type: ${typeof t}`);throw new Error(r)}async setExpirations(t){await this.core.storage.setItem(this.storageKey,t)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(or.sync)}async restore(){try{const t=await this.getExpirations();if(typeof t>"u"||!t.length)return;if(this.expirations.size){const{message:r}=K("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(t){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(t)}}getExpiration(t){const r=this.expirations.get(t);if(!r){const{message:s}=K("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.error(s),new Error(s)}return r}checkExpiry(t,r){const{expiry:s}=r;Q.toMiliseconds(s)-Date.now()<=0&&this.expire(t,r)}expire(t,r){this.expirations.delete(t),this.events.emit(or.expired,{target:t,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((t,r)=>this.checkExpiry(r,t))}registerEventListeners(){this.core.heartbeat.on(Ui.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(or.created,t=>{const r=or.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()}),this.events.on(or.expired,t=>{const r=or.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()}),this.events.on(or.deleted,t=>{const r=or.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()})}isInitialized(){if(!this.initialized){const{message:t}=K("NOT_INITIALIZED",this.name);throw new Error(t)}}}class UI extends o_{constructor(t,r){super(t,r),this.projectId=t,this.logger=r,this.name=ra,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async s=>{if(this.verifyDisabled||rw()||!Ol())return;const o=this.getVerifyUrl(s==null?void 0:s.verifyUrl);this.verifyUrl!==o&&this.removeIframe(),this.verifyUrl=o;try{await this.createIframe()}catch(u){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(u)}if(!this.initialized){this.removeIframe(),this.verifyUrl=Ea;try{await this.createIframe()}catch(u){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(u),this.verifyDisabled=!0}}},this.register=async s=>{this.initialized?this.sendPost(s.attestationId):(this.addToQueue(s.attestationId),await this.init())},this.resolve=async s=>{if(this.isDevEnv)return"";const o=this.getVerifyUrl(s==null?void 0:s.verifyUrl);let u;try{u=await this.fetchAttestation(s.attestationId,o)}catch(f){this.logger.info(`failed to resolve attestation: ${s.attestationId} from url: ${o}`),this.logger.info(f),u=await this.fetchAttestation(s.attestationId,Ea)}return u},this.fetchAttestation=async(s,o)=>{this.logger.info(`resolving attestation: ${s} from url: ${o}`);const u=this.startAbortTimer(Q.ONE_SECOND*2),f=await fetch(`${o}/attestation/${s}`,{signal:this.abortController.signal});return clearTimeout(u),f.status===200?await f.json():void 0},this.addToQueue=s=>{this.queue.push(s)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(s=>this.sendPost(s)),this.queue=[])},this.sendPost=s=>{var o;try{if(!this.iframe)return;(o=this.iframe.contentWindow)==null||o.postMessage(s,"*"),this.logger.info(`postMessage sent: ${s} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let s;const o=u=>{u.data==="verify_ready"&&(this.initialized=!0,this.processQueue(),window.removeEventListener("message",o),s())};await Promise.race([new Promise(u=>{if(document.getElementById(ra))return u();window.addEventListener("message",o);const f=document.createElement("iframe");f.id=ra,f.src=`${this.verifyUrl}/${this.projectId}`,f.style.display="none",document.body.append(f),this.iframe=f,s=u}),new Promise((u,f)=>setTimeout(()=>{window.removeEventListener("message",o),f("verify iframe load timeout")},Q.toMiliseconds(Q.FIVE_SECONDS)))])},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.getVerifyUrl=s=>{let o=s||qi;return gI.includes(o)||(this.logger.info(`verify url: ${o}, not included in trusted list, assigning default: ${qi}`),o=qi),o},this.logger=Ht(r,this.name),this.verifyUrl=qi,this.abortController=new AbortController,this.isDevEnv=iw()&&y1.IS_VITEST}get context(){return kt(this.logger)}startAbortTimer(t){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),Q.toMiliseconds(t))}}class kI extends a_{constructor(t,r){super(t,r),this.projectId=t,this.logger=r,this.context=yI,this.registerDeviceToken=async s=>{const{clientId:o,token:u,notificationType:f,enableEncrypted:y=!1}=s,v=`${vI}/${this.projectId}/clients`;await g1(v,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:o,type:f,token:u,always_raw:y})})},this.logger=Ht(r,this.context)}}var HI=Object.defineProperty,el=Object.getOwnPropertySymbols,KI=Object.prototype.hasOwnProperty,VI=Object.prototype.propertyIsEnumerable,tl=(a,t,r)=>t in a?HI(a,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):a[t]=r,rl=(a,t)=>{for(var r in t||(t={}))KI.call(t,r)&&tl(a,r,t[r]);if(el)for(var r of el(t))VI.call(t,r)&&tl(a,r,t[r]);return a};class ja extends Zb{constructor(t){super(t),this.protocol=cf,this.version=kE,this.name=Da,this.events=new ar.EventEmitter,this.initialized=!1,this.on=(s,o)=>this.events.on(s,o),this.once=(s,o)=>this.events.once(s,o),this.off=(s,o)=>this.events.off(s,o),this.removeListener=(s,o)=>this.events.removeListener(s,o),this.projectId=t==null?void 0:t.projectId,this.relayUrl=(t==null?void 0:t.relayUrl)||hf,this.customStoragePrefix=t!=null&&t.customStoragePrefix?`:${t.customStoragePrefix}`:"";const r=typeof(t==null?void 0:t.logger)<"u"&&typeof(t==null?void 0:t.logger)!="string"?t.logger:Cn($n({level:(t==null?void 0:t.logger)||HE.logger}));this.logger=Ht(r,this.name),this.heartbeat=new Ui.HeartBeat,this.crypto=new wI(this,this.logger,t==null?void 0:t.keychain),this.history=new MI(this,this.logger),this.expirer=new zI(this,this.logger),this.storage=t!=null&&t.storage?t.storage:new tb(rl(rl({},KE),t==null?void 0:t.storageOptions)),this.relayer=new NI({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new LI(this,this.logger),this.verify=new UI(this.projectId||"",this.logger),this.echoClient=new kI(this.projectId||"",this.logger)}static async init(t){const r=new ja(t);await r.initialize();const s=await r.crypto.getClientId();return await r.storage.setItem(nI,s),r}get context(){return kt(this.logger)}async start(){this.initialized||await this.initialize()}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.initialized=!0,this.logger.info("Core Initialization Success")}catch(t){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,t),this.logger.error(t.message),t}}}const BI=ja,lf="wc",ff=2,pf="client",qa=`${lf}@${ff}:${pf}:`,sa={name:pf,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},il="WALLETCONNECT_DEEPLINK_CHOICE",FI="proposal",df="Proposal expired",GI="session",vn=Q.SEVEN_DAYS,WI="engine",cs={wc_sessionPropose:{req:{ttl:Q.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Q.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Q.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Q.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Q.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Q.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Q.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Q.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Q.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Q.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Q.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:Q.THIRTY_SECONDS,prompt:!1,tag:1115}}},na={min:Q.FIVE_MINUTES,max:Q.SEVEN_DAYS},Dr={idle:"IDLE",active:"ACTIVE"},JI="request",QI=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var YI=Object.defineProperty,ZI=Object.defineProperties,XI=Object.getOwnPropertyDescriptors,sl=Object.getOwnPropertySymbols,ex=Object.prototype.hasOwnProperty,tx=Object.prototype.propertyIsEnumerable,nl=(a,t,r)=>t in a?YI(a,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):a[t]=r,Mt=(a,t)=>{for(var r in t||(t={}))ex.call(t,r)&&nl(a,r,t[r]);if(sl)for(var r of sl(t))tx.call(t,r)&&nl(a,r,t[r]);return a},us=(a,t)=>ZI(a,XI(t));class rx extends u_{constructor(t){super(t),this.name=WI,this.events=new Oa,this.initialized=!1,this.ignoredPayloadTypes=[Pl],this.requestQueue={state:Dr.idle,queue:[]},this.sessionRequestQueue={state:Dr.idle,queue:[]},this.requestQueueDelay=Q.ONE_SECOND,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(cs)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},Q.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{await this.isInitialized();const s=us(Mt({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(s);const{pairingTopic:o,requiredNamespaces:u,optionalNamespaces:f,sessionProperties:y,relays:v}=s;let p=o,w,I=!1;if(p&&(I=this.client.core.pairing.pairings.get(p).active),!p||!I){const{topic:re,uri:Y}=await this.client.core.pairing.create();p=re,w=Y}const R=await this.client.core.crypto.generateKeyPair(),$=Mt({requiredNamespaces:u,optionalNamespaces:f,relays:v??[{protocol:uf}],proposer:{publicKey:R,metadata:this.client.metadata}},y&&{sessionProperties:y}),{reject:O,resolve:B,done:X}=Di(Q.FIVE_MINUTES,df);if(this.events.once(We("session_connect"),async({error:re,session:Y})=>{if(re)O(re);else if(Y){Y.self.publicKey=R;const ce=us(Mt({},Y),{requiredNamespaces:Y.requiredNamespaces,optionalNamespaces:Y.optionalNamespaces});await this.client.session.set(Y.topic,ce),await this.setExpiry(Y.topic,Y.expiry),p&&await this.client.core.pairing.updateMetadata({topic:p,metadata:Y.peer.metadata}),B(ce)}}),!p){const{message:re}=K("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(re)}const ie=await this.sendRequest({topic:p,method:"wc_sessionPropose",params:$}),he=dr(Q.FIVE_MINUTES);return await this.setProposal(ie,Mt({id:ie,expiry:he},$)),{uri:w,approval:X}},this.pair=async r=>(await this.isInitialized(),await this.client.core.pairing.pair(r)),this.approve=async r=>{await this.isInitialized(),await this.isValidApprove(r);const{id:s,relayProtocol:o,namespaces:u,sessionProperties:f}=r,y=this.client.proposal.get(s);let{pairingTopic:v,proposer:p,requiredNamespaces:w,optionalNamespaces:I}=y;v=v||"",_n(w)||(w=nw(u,"approve()"));const R=await this.client.core.crypto.generateKeyPair(),$=p.publicKey,O=await this.client.core.crypto.generateSharedKey(R,$);v&&s&&(await this.client.core.pairing.updateMetadata({topic:v,metadata:p.metadata}),await this.sendResult({id:s,topic:v,result:{relay:{protocol:o??"irn"},responderPublicKey:R}}),await this.client.proposal.delete(s,St("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:v}));const B=Mt({relay:{protocol:o??"irn"},namespaces:u,requiredNamespaces:w,optionalNamespaces:I,pairingTopic:v,controller:{publicKey:R,metadata:this.client.metadata},expiry:dr(vn)},f&&{sessionProperties:f});await this.client.core.relayer.subscribe(O),await this.sendRequest({topic:O,method:"wc_sessionSettle",params:B,throwOnFailedPublish:!0});const X=us(Mt({},B),{topic:O,pairingTopic:v,acknowledged:!1,self:B.controller,peer:{publicKey:p.publicKey,metadata:p.metadata},controller:R});return await this.client.session.set(O,X),await this.setExpiry(O,dr(vn)),{topic:O,acknowledged:()=>new Promise(ie=>setTimeout(()=>ie(this.client.session.get(O)),500))}},this.reject=async r=>{await this.isInitialized(),await this.isValidReject(r);const{id:s,reason:o}=r,{pairingTopic:u}=this.client.proposal.get(s);u&&(await this.sendError(s,u,o),await this.client.proposal.delete(s,St("USER_DISCONNECTED")))},this.update=async r=>{await this.isInitialized(),await this.isValidUpdate(r);const{topic:s,namespaces:o}=r,u=await this.sendRequest({topic:s,method:"wc_sessionUpdate",params:{namespaces:o}}),{done:f,resolve:y,reject:v}=Di();return this.events.once(We("session_update",u),({error:p})=>{p?v(p):y()}),await this.client.session.update(s,{namespaces:o}),{acknowledged:f}},this.extend=async r=>{await this.isInitialized(),await this.isValidExtend(r);const{topic:s}=r,o=await this.sendRequest({topic:s,method:"wc_sessionExtend",params:{}}),{done:u,resolve:f,reject:y}=Di();return this.events.once(We("session_extend",o),({error:v})=>{v?y(v):f()}),await this.setExpiry(s,dr(vn)),{acknowledged:u}},this.request=async r=>{await this.isInitialized(),await this.isValidRequest(r);const{chainId:s,request:o,topic:u,expiry:f}=r,y=Ta(),{done:v,resolve:p,reject:w}=Di(f,"Request expired. Please try again.");return this.events.once(We("session_request",y),({error:I,result:R})=>{I?w(I):p(R)}),await Promise.all([new Promise(async I=>{await this.sendRequest({clientRpcId:y,topic:u,method:"wc_sessionRequest",params:{request:o,chainId:s},expiry:f,throwOnFailedPublish:!0}).catch(R=>w(R)),this.client.events.emit("session_request_sent",{topic:u,request:o,chainId:s,id:y}),I()}),new Promise(async I=>{const R=await ow(this.client.core.storage,il);aw({id:y,topic:u,wcDeepLink:R}),I()}),v()]).then(I=>I[2])},this.respond=async r=>{await this.isInitialized(),await this.isValidRespond(r);const{topic:s,response:o}=r,{id:u}=o;jr(o)?await this.sendResult({id:u,topic:s,result:o.result,throwOnFailedPublish:!0}):gr(o)&&await this.sendError(u,s,o.error),this.cleanupAfterResponse(r)},this.ping=async r=>{await this.isInitialized(),await this.isValidPing(r);const{topic:s}=r;if(this.client.session.keys.includes(s)){const o=await this.sendRequest({topic:s,method:"wc_sessionPing",params:{}}),{done:u,resolve:f,reject:y}=Di();this.events.once(We("session_ping",o),({error:v})=>{v?y(v):f()}),await u()}else this.client.core.pairing.pairings.keys.includes(s)&&await this.client.core.pairing.ping({topic:s})},this.emit=async r=>{await this.isInitialized(),await this.isValidEmit(r);const{topic:s,event:o,chainId:u}=r;await this.sendRequest({topic:s,method:"wc_sessionEvent",params:{event:o,chainId:u}})},this.disconnect=async r=>{await this.isInitialized(),await this.isValidDisconnect(r);const{topic:s}=r;this.client.session.keys.includes(s)?(await this.sendRequest({topic:s,method:"wc_sessionDelete",params:St("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession(s)):await this.client.core.pairing.disconnect({topic:s})},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(s=>cw(s,r))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{const s=this.client.core.pairing.pairings.get(r.pairingTopic),o=this.client.core.pairing.pairings.getAll().filter(u=>{var f,y;return((f=u.peerMetadata)==null?void 0:f.url)&&((y=u.peerMetadata)==null?void 0:y.url)===r.peer.metadata.url&&u.topic&&u.topic!==s.topic});if(o.length===0)return;this.client.logger.info(`Cleaning up ${o.length} duplicate pairing(s)`),await Promise.all(o.map(u=>this.client.core.pairing.disconnect({topic:u.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(s){this.client.logger.error(s)}},this.deleteSession=async(r,s)=>{const{self:o}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),this.client.session.delete(r,St("USER_DISCONNECTED")),this.client.core.crypto.keychain.has(o.publicKey)&&await this.client.core.crypto.deleteKeyPair(o.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),s||this.client.core.expirer.del(r),this.client.core.storage.removeItem(il).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===r&&this.deletePendingSessionRequest(u.id,St("USER_DISCONNECTED"))})},this.deleteProposal=async(r,s)=>{await Promise.all([this.client.proposal.delete(r,St("USER_DISCONNECTED")),s?Promise.resolve():this.client.core.expirer.del(r)])},this.deletePendingSessionRequest=async(r,s,o=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,s),o?Promise.resolve():this.client.core.expirer.del(r)]),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(u=>u.id!==r),o&&(this.sessionRequestQueue.state=Dr.idle)},this.setExpiry=async(r,s)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:s}),this.client.core.expirer.set(r,s)},this.setProposal=async(r,s)=>{await this.client.proposal.set(r,s),this.client.core.expirer.set(r,s.expiry)},this.setPendingSessionRequest=async r=>{const s=cs.wc_sessionRequest.req.ttl,{id:o,topic:u,params:f,verifyContext:y}=r;await this.client.pendingRequest.set(o,{id:o,topic:u,params:f,verifyContext:y}),s&&this.client.core.expirer.set(o,dr(s))},this.sendRequest=async r=>{const{topic:s,method:o,params:u,expiry:f,relayRpcId:y,clientRpcId:v,throwOnFailedPublish:p}=r,w=Mi(o,u,v);if(Ol()&&QI.includes(o)){const $=Li(JSON.stringify(w));this.client.core.verify.register({attestationId:$})}const I=await this.client.core.crypto.encode(s,w),R=cs[o].req;return f&&(R.ttl=f),y&&(R.id=y),this.client.core.history.set(s,w),p?(R.internal=us(Mt({},R.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,I,R)):this.client.core.relayer.publish(s,I,R).catch($=>this.client.logger.error($)),w.id},this.sendResult=async r=>{const{id:s,topic:o,result:u,throwOnFailedPublish:f}=r,y=Tn(s,u),v=await this.client.core.crypto.encode(o,y),p=await this.client.core.history.get(o,s),w=cs[p.request.method].res;f?(w.internal=us(Mt({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(o,v,w)):this.client.core.relayer.publish(o,v,w).catch(I=>this.client.logger.error(I)),await this.client.core.history.resolve(y)},this.sendError=async(r,s,o)=>{const u=Nn(r,o),f=await this.client.core.crypto.encode(s,u),y=await this.client.core.history.get(s,r),v=cs[y.request.method].res;this.client.core.relayer.publish(s,f,v),await this.client.core.history.resolve(u)},this.cleanup=async()=>{const r=[],s=[];this.client.session.getAll().forEach(o=>{Jr(o.expiry)&&r.push(o.topic)}),this.client.proposal.getAll().forEach(o=>{Jr(o.expiry)&&s.push(o.id)}),await Promise.all([...r.map(o=>this.deleteSession(o)),...s.map(o=>this.deleteProposal(o))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===Dr.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=Dr.active;const r=this.requestQueue.queue.shift();if(r)try{this.processRequest(r),await new Promise(s=>setTimeout(s,300))}catch(s){this.client.logger.warn(s)}}this.requestQueue.state=Dr.idle},this.processRequest=r=>{const{topic:s,payload:o}=r,u=o.method;switch(u){case"wc_sessionPropose":return this.onSessionProposeRequest(s,o);case"wc_sessionSettle":return this.onSessionSettleRequest(s,o);case"wc_sessionUpdate":return this.onSessionUpdateRequest(s,o);case"wc_sessionExtend":return this.onSessionExtendRequest(s,o);case"wc_sessionPing":return this.onSessionPingRequest(s,o);case"wc_sessionDelete":return this.onSessionDeleteRequest(s,o);case"wc_sessionRequest":return this.onSessionRequest(s,o);case"wc_sessionEvent":return this.onSessionEventRequest(s,o);default:return this.client.logger.info(`Unsupported request method ${u}`)}},this.onRelayEventResponse=async r=>{const{topic:s,payload:o}=r,u=(await this.client.core.history.get(s,o.id)).request.method;switch(u){case"wc_sessionPropose":return this.onSessionProposeResponse(s,o);case"wc_sessionSettle":return this.onSessionSettleResponse(s,o);case"wc_sessionUpdate":return this.onSessionUpdateResponse(s,o);case"wc_sessionExtend":return this.onSessionExtendResponse(s,o);case"wc_sessionPing":return this.onSessionPingResponse(s,o);case"wc_sessionRequest":return this.onSessionRequestResponse(s,o);default:return this.client.logger.info(`Unsupported response method ${u}`)}},this.onRelayEventUnknownPayload=r=>{const{topic:s}=r,{message:o}=K("MISSING_OR_INVALID",`Decoded payload on topic ${s} is not identifiable as a JSON-RPC request or a response.`);throw new Error(o)},this.onSessionProposeRequest=async(r,s)=>{const{params:o,id:u}=s;try{this.isValidConnect(Mt({},s.params));const f=dr(Q.FIVE_MINUTES),y=Mt({id:u,pairingTopic:r,expiry:f},o);await this.setProposal(u,y);const v=Li(JSON.stringify(s)),p=await this.getVerifyContext(v,y.proposer.metadata);this.client.events.emit("session_proposal",{id:u,params:y,verifyContext:p})}catch(f){await this.sendError(u,r,f),this.client.logger.error(f)}},this.onSessionProposeResponse=async(r,s)=>{const{id:o}=s;if(jr(s)){const{result:u}=s;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:u});const f=this.client.proposal.get(o);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:f});const y=f.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:y});const v=u.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:v});const p=await this.client.core.crypto.generateSharedKey(y,v);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:p});const w=await this.client.core.relayer.subscribe(p);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:w}),await this.client.core.pairing.activate({topic:r})}else gr(s)&&(await this.client.proposal.delete(o,St("USER_DISCONNECTED")),this.events.emit(We("session_connect"),{error:s.error}))},this.onSessionSettleRequest=async(r,s)=>{const{id:o,params:u}=s;try{this.isValidSessionSettleRequest(u);const{relay:f,controller:y,expiry:v,namespaces:p,requiredNamespaces:w,optionalNamespaces:I,sessionProperties:R,pairingTopic:$}=s.params,O=Mt({topic:r,relay:f,expiry:v,namespaces:p,acknowledged:!0,pairingTopic:$,requiredNamespaces:w,optionalNamespaces:I,controller:y.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:y.publicKey,metadata:y.metadata}},R&&{sessionProperties:R});await this.sendResult({id:s.id,topic:r,result:!0}),this.events.emit(We("session_connect"),{session:O}),this.cleanupDuplicatePairings(O)}catch(f){await this.sendError(o,r,f),this.client.logger.error(f)}},this.onSessionSettleResponse=async(r,s)=>{const{id:o}=s;jr(s)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(We("session_approve",o),{})):gr(s)&&(await this.client.session.delete(r,St("USER_DISCONNECTED")),this.events.emit(We("session_approve",o),{error:s.error}))},this.onSessionUpdateRequest=async(r,s)=>{const{params:o,id:u}=s;try{const f=`${r}_session_update`,y=pn.get(f);if(y&&this.isRequestOutOfSync(y,u)){this.client.logger.info(`Discarding out of sync request - ${u}`);return}this.isValidUpdate(Mt({topic:r},o)),await this.client.session.update(r,{namespaces:o.namespaces}),await this.sendResult({id:u,topic:r,result:!0}),this.client.events.emit("session_update",{id:u,topic:r,params:o}),pn.set(f,u)}catch(f){await this.sendError(u,r,f),this.client.logger.error(f)}},this.isRequestOutOfSync=(r,s)=>parseInt(s.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,s)=>{const{id:o}=s;jr(s)?this.events.emit(We("session_update",o),{}):gr(s)&&this.events.emit(We("session_update",o),{error:s.error})},this.onSessionExtendRequest=async(r,s)=>{const{id:o}=s;try{this.isValidExtend({topic:r}),await this.setExpiry(r,dr(vn)),await this.sendResult({id:o,topic:r,result:!0}),this.client.events.emit("session_extend",{id:o,topic:r})}catch(u){await this.sendError(o,r,u),this.client.logger.error(u)}},this.onSessionExtendResponse=(r,s)=>{const{id:o}=s;jr(s)?this.events.emit(We("session_extend",o),{}):gr(s)&&this.events.emit(We("session_extend",o),{error:s.error})},this.onSessionPingRequest=async(r,s)=>{const{id:o}=s;try{this.isValidPing({topic:r}),await this.sendResult({id:o,topic:r,result:!0}),this.client.events.emit("session_ping",{id:o,topic:r})}catch(u){await this.sendError(o,r,u),this.client.logger.error(u)}},this.onSessionPingResponse=(r,s)=>{const{id:o}=s;setTimeout(()=>{jr(s)?this.events.emit(We("session_ping",o),{}):gr(s)&&this.events.emit(We("session_ping",o),{error:s.error})},500)},this.onSessionDeleteRequest=async(r,s)=>{const{id:o}=s;try{this.isValidDisconnect({topic:r,reason:s.params}),await Promise.all([new Promise(u=>{this.client.core.relayer.once(Ot.publish,async()=>{u(await this.deleteSession(r))})}),this.sendResult({id:o,topic:r,result:!0})]),this.client.events.emit("session_delete",{id:o,topic:r})}catch(u){this.client.logger.error(u)}},this.onSessionRequest=async(r,s)=>{const{id:o,params:u}=s;try{this.isValidRequest(Mt({topic:r},u));const f=Li(JSON.stringify(Mi("wc_sessionRequest",u,o))),y=this.client.session.get(r),v=await this.getVerifyContext(f,y.peer.metadata),p={id:o,topic:r,params:u,verifyContext:v};await this.setPendingSessionRequest(p),this.addSessionRequestToSessionRequestQueue(p),this.processSessionRequestQueue()}catch(f){await this.sendError(o,r,f),this.client.logger.error(f)}},this.onSessionRequestResponse=(r,s)=>{const{id:o}=s;jr(s)?this.events.emit(We("session_request",o),{result:s.result}):gr(s)&&this.events.emit(We("session_request",o),{error:s.error})},this.onSessionEventRequest=async(r,s)=>{const{id:o,params:u}=s;try{const f=`${r}_session_event_${u.event.name}`,y=pn.get(f);if(y&&this.isRequestOutOfSync(y,o)){this.client.logger.info(`Discarding out of sync request - ${o}`);return}this.isValidEmit(Mt({topic:r},u)),this.client.events.emit("session_event",{id:o,topic:r,params:u}),pn.set(f,o)}catch(f){await this.sendError(o,r,f),this.client.logger.error(f)}},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Dr.idle,this.processSessionRequestQueue()},Q.toMiliseconds(this.requestQueueDelay))},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===Dr.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Dr.active,this.client.events.emit("session_request",r)}catch(s){this.client.logger.error(s)}},this.onPairingCreated=r=>{if(r.active)return;const s=this.client.proposal.getAll().find(o=>o.pairingTopic===r.topic);s&&this.onSessionProposeRequest(r.topic,Mi("wc_sessionPropose",{requiredNamespaces:s.requiredNamespaces,optionalNamespaces:s.optionalNamespaces,relays:s.relays,proposer:s.proposer,sessionProperties:s.sessionProperties},s.id))},this.isValidConnect=async r=>{if(!Ut(r)){const{message:v}=K("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(v)}const{pairingTopic:s,requiredNamespaces:o,optionalNamespaces:u,sessionProperties:f,relays:y}=r;if(Qr(s)||await this.isValidPairingTopic(s),!uw(y)){const{message:v}=K("MISSING_OR_INVALID",`connect() relays: ${y}`);throw new Error(v)}!Qr(o)&&_n(o)!==0&&this.validateNamespaces(o,"requiredNamespaces"),!Qr(u)&&_n(u)!==0&&this.validateNamespaces(u,"optionalNamespaces"),Qr(f)||this.validateSessionProps(f,"sessionProperties")},this.validateNamespaces=(r,s)=>{const o=hw(r,"connect()",s);if(o)throw new Error(o.message)},this.isValidApprove=async r=>{if(!Ut(r))throw new Error(K("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:s,namespaces:o,relayProtocol:u,sessionProperties:f}=r;await this.isValidProposalId(s);const y=this.client.proposal.get(s),v=Wo(o,"approve()");if(v)throw new Error(v.message);const p=gh(y.requiredNamespaces,o,"approve()");if(p)throw new Error(p.message);if(!ji(u,!0)){const{message:w}=K("MISSING_OR_INVALID",`approve() relayProtocol: ${u}`);throw new Error(w)}Qr(f)||this.validateSessionProps(f,"sessionProperties")},this.isValidReject=async r=>{if(!Ut(r)){const{message:u}=K("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(u)}const{id:s,reason:o}=r;if(await this.isValidProposalId(s),!lw(o)){const{message:u}=K("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(o)}`);throw new Error(u)}},this.isValidSessionSettleRequest=r=>{if(!Ut(r)){const{message:p}=K("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(p)}const{relay:s,controller:o,namespaces:u,expiry:f}=r;if(!fw(s)){const{message:p}=K("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(p)}const y=pw(o,"onSessionSettleRequest()");if(y)throw new Error(y.message);const v=Wo(u,"onSessionSettleRequest()");if(v)throw new Error(v.message);if(Jr(f)){const{message:p}=K("EXPIRED","onSessionSettleRequest()");throw new Error(p)}},this.isValidUpdate=async r=>{if(!Ut(r)){const{message:v}=K("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(v)}const{topic:s,namespaces:o}=r;await this.isValidSessionTopic(s);const u=this.client.session.get(s),f=Wo(o,"update()");if(f)throw new Error(f.message);const y=gh(u.requiredNamespaces,o,"update()");if(y)throw new Error(y.message)},this.isValidExtend=async r=>{if(!Ut(r)){const{message:o}=K("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(o)}const{topic:s}=r;await this.isValidSessionTopic(s)},this.isValidRequest=async r=>{if(!Ut(r)){const{message:v}=K("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(v)}const{topic:s,request:o,chainId:u,expiry:f}=r;await this.isValidSessionTopic(s);const{namespaces:y}=this.client.session.get(s);if(!yh(y,u)){const{message:v}=K("MISSING_OR_INVALID",`request() chainId: ${u}`);throw new Error(v)}if(!dw(o)){const{message:v}=K("MISSING_OR_INVALID",`request() ${JSON.stringify(o)}`);throw new Error(v)}if(!gw(y,u,o.method)){const{message:v}=K("MISSING_OR_INVALID",`request() method: ${o.method}`);throw new Error(v)}if(f&&!yw(f,na)){const{message:v}=K("MISSING_OR_INVALID",`request() expiry: ${f}. Expiry must be a number (in seconds) between ${na.min} and ${na.max}`);throw new Error(v)}},this.isValidRespond=async r=>{var s;if(!Ut(r)){const{message:f}=K("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(f)}const{topic:o,response:u}=r;try{await this.isValidSessionTopic(o)}catch(f){throw(s=r==null?void 0:r.response)!=null&&s.id&&this.cleanupAfterResponse(r),f}if(!vw(u)){const{message:f}=K("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(u)}`);throw new Error(f)}},this.isValidPing=async r=>{if(!Ut(r)){const{message:o}=K("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(o)}const{topic:s}=r;await this.isValidSessionOrPairingTopic(s)},this.isValidEmit=async r=>{if(!Ut(r)){const{message:y}=K("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(y)}const{topic:s,event:o,chainId:u}=r;await this.isValidSessionTopic(s);const{namespaces:f}=this.client.session.get(s);if(!yh(f,u)){const{message:y}=K("MISSING_OR_INVALID",`emit() chainId: ${u}`);throw new Error(y)}if(!mw(o)){const{message:y}=K("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(y)}if(!ww(f,u,o.name)){const{message:y}=K("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(y)}},this.isValidDisconnect=async r=>{if(!Ut(r)){const{message:o}=K("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(o)}const{topic:s}=r;await this.isValidSessionOrPairingTopic(s)},this.getVerifyContext=async(r,s)=>{const o={verified:{verifyUrl:s.verifyUrl||qi,validation:"UNKNOWN",origin:s.url||""}};try{const u=await this.client.core.verify.resolve({attestationId:r,verifyUrl:s.verifyUrl});u&&(o.verified.origin=u.origin,o.verified.isScam=u.isScam,o.verified.validation=u.origin===new URL(s.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.info(u)}return this.client.logger.info(`Verify context: ${JSON.stringify(o)}`),o},this.validateSessionProps=(r,s)=>{Object.values(r).forEach(o=>{if(!ji(o,!1)){const{message:u}=K("MISSING_OR_INVALID",`${s} must be in Record format. Received: ${JSON.stringify(o)}`);throw new Error(u)}})}}async isInitialized(){if(!this.initialized){const{message:t}=K("NOT_INITIALIZED",this.name);throw new Error(t)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ot.message,async t=>{const{topic:r,message:s}=t;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(s)))return;const o=await this.client.core.crypto.decode(r,s);try{Na(o)?(this.client.core.history.set(r,o),this.onRelayEventRequest({topic:r,payload:o})):Dn(o)?(await this.client.core.history.resolve(o),await this.onRelayEventResponse({topic:r,payload:o}),this.client.core.history.delete(r,o.id)):this.onRelayEventUnknownPayload({topic:r,payload:o})}catch(u){this.client.logger.error(u)}})}registerExpirerEvents(){this.client.core.expirer.on(or.expired,async t=>{const{topic:r,id:s}=Sl(t.target);if(s&&this.client.pendingRequest.keys.includes(s))return await this.deletePendingSessionRequest(s,K("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession(r,!0),this.client.events.emit("session_expire",{topic:r})):s&&(await this.deleteProposal(s,!0),this.client.events.emit("proposal_expire",{id:s}))})}registerPairingEvents(){this.client.core.pairing.events.on(fs.create,t=>this.onPairingCreated(t))}isValidPairingTopic(t){if(!ji(t,!1)){const{message:r}=K("MISSING_OR_INVALID",`pairing topic should be a string: ${t}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(t)){const{message:r}=K("NO_MATCHING_KEY",`pairing topic doesn't exist: ${t}`);throw new Error(r)}if(Jr(this.client.core.pairing.pairings.get(t).expiry)){const{message:r}=K("EXPIRED",`pairing topic: ${t}`);throw new Error(r)}}async isValidSessionTopic(t){if(!ji(t,!1)){const{message:r}=K("MISSING_OR_INVALID",`session topic should be a string: ${t}`);throw new Error(r)}if(!this.client.session.keys.includes(t)){const{message:r}=K("NO_MATCHING_KEY",`session topic doesn't exist: ${t}`);throw new Error(r)}if(Jr(this.client.session.get(t).expiry)){await this.deleteSession(t);const{message:r}=K("EXPIRED",`session topic: ${t}`);throw new Error(r)}}async isValidSessionOrPairingTopic(t){if(this.client.session.keys.includes(t))await this.isValidSessionTopic(t);else if(this.client.core.pairing.pairings.keys.includes(t))this.isValidPairingTopic(t);else if(ji(t,!1)){const{message:r}=K("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${t}`);throw new Error(r)}else{const{message:r}=K("MISSING_OR_INVALID",`session or pairing topic should be a string: ${t}`);throw new Error(r)}}async isValidProposalId(t){if(!bw(t)){const{message:r}=K("MISSING_OR_INVALID",`proposal id should be a number: ${t}`);throw new Error(r)}if(!this.client.proposal.keys.includes(t)){const{message:r}=K("NO_MATCHING_KEY",`proposal id doesn't exist: ${t}`);throw new Error(r)}if(Jr(this.client.proposal.get(t).expiry)){await this.deleteProposal(t);const{message:r}=K("EXPIRED",`proposal id: ${t}`);throw new Error(r)}}}class ix extends qn{constructor(t,r){super(t,r,FI,qa),this.core=t,this.logger=r}}class sx extends qn{constructor(t,r){super(t,r,GI,qa),this.core=t,this.logger=r}}class nx extends qn{constructor(t,r){super(t,r,JI,qa,s=>s.id),this.core=t,this.logger=r}}let ox=class gf extends c_{constructor(t){super(t),this.protocol=lf,this.version=ff,this.name=sa.name,this.events=new ar.EventEmitter,this.on=(s,o)=>this.events.on(s,o),this.once=(s,o)=>this.events.once(s,o),this.off=(s,o)=>this.events.off(s,o),this.removeListener=(s,o)=>this.events.removeListener(s,o),this.removeAllListeners=s=>this.events.removeAllListeners(s),this.connect=async s=>{try{return await this.engine.connect(s)}catch(o){throw this.logger.error(o.message),o}},this.pair=async s=>{try{return await this.engine.pair(s)}catch(o){throw this.logger.error(o.message),o}},this.approve=async s=>{try{return await this.engine.approve(s)}catch(o){throw this.logger.error(o.message),o}},this.reject=async s=>{try{return await this.engine.reject(s)}catch(o){throw this.logger.error(o.message),o}},this.update=async s=>{try{return await this.engine.update(s)}catch(o){throw this.logger.error(o.message),o}},this.extend=async s=>{try{return await this.engine.extend(s)}catch(o){throw this.logger.error(o.message),o}},this.request=async s=>{try{return await this.engine.request(s)}catch(o){throw this.logger.error(o.message),o}},this.respond=async s=>{try{return await this.engine.respond(s)}catch(o){throw this.logger.error(o.message),o}},this.ping=async s=>{try{return await this.engine.ping(s)}catch(o){throw this.logger.error(o.message),o}},this.emit=async s=>{try{return await this.engine.emit(s)}catch(o){throw this.logger.error(o.message),o}},this.disconnect=async s=>{try{return await this.engine.disconnect(s)}catch(o){throw this.logger.error(o.message),o}},this.find=s=>{try{return this.engine.find(s)}catch(o){throw this.logger.error(o.message),o}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(s){throw this.logger.error(s.message),s}},this.name=(t==null?void 0:t.name)||sa.name,this.metadata=(t==null?void 0:t.metadata)||sw();const r=typeof(t==null?void 0:t.logger)<"u"&&typeof(t==null?void 0:t.logger)!="string"?t.logger:Cn($n({level:(t==null?void 0:t.logger)||sa.logger}));this.core=(t==null?void 0:t.core)||new BI(t),this.logger=Ht(r,this.name),this.session=new sx(this.core,this.logger),this.proposal=new ix(this.core,this.logger),this.pendingRequest=new nx(this.core,this.logger),this.engine=new rx(this)}static async init(t){const r=new gf(t);return await r.initialize(),r}get context(){return kt(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.engine.init(),this.core.verify.init({verifyUrl:this.metadata.verifyUrl}),this.logger.info("SignClient Initialization Success")}catch(t){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(t.message),t}}};var Ia={exports:{}};(function(a,t){var r=typeof self<"u"?self:li,s=function(){function u(){this.fetch=!1,this.DOMException=r.DOMException}return u.prototype=r,new u}();(function(u){(function(f){var y={searchParams:"URLSearchParams"in u,iterable:"Symbol"in u&&"iterator"in Symbol,blob:"FileReader"in u&&"Blob"in u&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in u,arrayBuffer:"ArrayBuffer"in u};function v(b){return b&&DataView.prototype.isPrototypeOf(b)}if(y.arrayBuffer)var p=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],w=ArrayBuffer.isView||function(b){return b&&p.indexOf(Object.prototype.toString.call(b))>-1};function I(b){if(typeof b!="string"&&(b=String(b)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(b))throw new TypeError("Invalid character in header field name");return b.toLowerCase()}function R(b){return typeof b!="string"&&(b=String(b)),b}function $(b){var S={next:function(){var F=b.shift();return{done:F===void 0,value:F}}};return y.iterable&&(S[Symbol.iterator]=function(){return S}),S}function O(b){this.map={},b instanceof O?b.forEach(function(S,F){this.append(F,S)},this):Array.isArray(b)?b.forEach(function(S){this.append(S[0],S[1])},this):b&&Object.getOwnPropertyNames(b).forEach(function(S){this.append(S,b[S])},this)}O.prototype.append=function(b,S){b=I(b),S=R(S);var F=this.map[b];this.map[b]=F?F+", "+S:S},O.prototype.delete=function(b){delete this.map[I(b)]},O.prototype.get=function(b){return b=I(b),this.has(b)?this.map[b]:null},O.prototype.has=function(b){return this.map.hasOwnProperty(I(b))},O.prototype.set=function(b,S){this.map[I(b)]=R(S)},O.prototype.forEach=function(b,S){for(var F in this.map)this.map.hasOwnProperty(F)&&b.call(S,this.map[F],F,this)},O.prototype.keys=function(){var b=[];return this.forEach(function(S,F){b.push(F)}),$(b)},O.prototype.values=function(){var b=[];return this.forEach(function(S){b.push(S)}),$(b)},O.prototype.entries=function(){var b=[];return this.forEach(function(S,F){b.push([F,S])}),$(b)},y.iterable&&(O.prototype[Symbol.iterator]=O.prototype.entries);function B(b){if(b.bodyUsed)return Promise.reject(new TypeError("Already read"));b.bodyUsed=!0}function X(b){return new Promise(function(S,F){b.onload=function(){S(b.result)},b.onerror=function(){F(b.error)}})}function ie(b){var S=new FileReader,F=X(S);return S.readAsArrayBuffer(b),F}function he(b){var S=new FileReader,F=X(S);return S.readAsText(b),F}function re(b){for(var S=new Uint8Array(b),F=new Array(S.length),ae=0;ae-1?S:b}function de(b,S){S=S||{};var F=S.body;if(b instanceof de){if(b.bodyUsed)throw new TypeError("Already read");this.url=b.url,this.credentials=b.credentials,S.headers||(this.headers=new O(b.headers)),this.method=b.method,this.mode=b.mode,this.signal=b.signal,!F&&b._bodyInit!=null&&(F=b._bodyInit,b.bodyUsed=!0)}else this.url=String(b);if(this.credentials=S.credentials||this.credentials||"same-origin",(S.headers||!this.headers)&&(this.headers=new O(S.headers)),this.method=W(S.method||this.method||"GET"),this.mode=S.mode||this.mode||null,this.signal=S.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&F)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(F)}de.prototype.clone=function(){return new de(this,{body:this._bodyInit})};function et(b){var S=new FormData;return b.trim().split("&").forEach(function(F){if(F){var ae=F.split("="),z=ae.shift().replace(/\+/g," "),M=ae.join("=").replace(/\+/g," ");S.append(decodeURIComponent(z),decodeURIComponent(M))}}),S}function tt(b){var S=new O,F=b.replace(/\r?\n[\t ]+/g," ");return F.split(/\r?\n/).forEach(function(ae){var z=ae.split(":"),M=z.shift().trim();if(M){var U=z.join(":").trim();S.append(M,U)}}),S}ce.call(de.prototype);function Me(b,S){S||(S={}),this.type="default",this.status=S.status===void 0?200:S.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in S?S.statusText:"OK",this.headers=new O(S.headers),this.url=S.url||"",this._initBody(b)}ce.call(Me.prototype),Me.prototype.clone=function(){return new Me(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new O(this.headers),url:this.url})},Me.error=function(){var b=new Me(null,{status:0,statusText:""});return b.type="error",b};var Qt=[301,302,303,307,308];Me.redirect=function(b,S){if(Qt.indexOf(S)===-1)throw new RangeError("Invalid status code");return new Me(null,{status:S,headers:{location:b}})},f.DOMException=u.DOMException;try{new f.DOMException}catch{f.DOMException=function(S,F){this.message=S,this.name=F;var ae=Error(S);this.stack=ae.stack},f.DOMException.prototype=Object.create(Error.prototype),f.DOMException.prototype.constructor=f.DOMException}function Rt(b,S){return new Promise(function(F,ae){var z=new de(b,S);if(z.signal&&z.signal.aborted)return ae(new f.DOMException("Aborted","AbortError"));var M=new XMLHttpRequest;function U(){M.abort()}M.onload=function(){var k={status:M.status,statusText:M.statusText,headers:tt(M.getAllResponseHeaders()||"")};k.url="responseURL"in M?M.responseURL:k.headers.get("X-Request-URL");var Ue="response"in M?M.response:M.responseText;F(new Me(Ue,k))},M.onerror=function(){ae(new TypeError("Network request failed"))},M.ontimeout=function(){ae(new TypeError("Network request failed"))},M.onabort=function(){ae(new f.DOMException("Aborted","AbortError"))},M.open(z.method,z.url,!0),z.credentials==="include"?M.withCredentials=!0:z.credentials==="omit"&&(M.withCredentials=!1),"responseType"in M&&y.blob&&(M.responseType="blob"),z.headers.forEach(function(k,Ue){M.setRequestHeader(Ue,k)}),z.signal&&(z.signal.addEventListener("abort",U),M.onreadystatechange=function(){M.readyState===4&&z.signal.removeEventListener("abort",U)}),M.send(typeof z._bodyInit>"u"?null:z._bodyInit)})}return Rt.polyfill=!0,u.fetch||(u.fetch=Rt,u.Headers=O,u.Request=de,u.Response=Me),f.Headers=O,f.Request=de,f.Response=Me,f.fetch=Rt,Object.defineProperty(f,"__esModule",{value:!0}),f})({})})(s),s.fetch.ponyfill=!0,delete s.fetch.polyfill;var o=s;t=o.fetch,t.default=o.fetch,t.fetch=o.fetch,t.Headers=o.Headers,t.Request=o.Request,t.Response=o.Response,a.exports=t})(Ia,Ia.exports);var ax=Ia.exports;const ol=Aa(ax);var cx=Object.defineProperty,ux=Object.defineProperties,hx=Object.getOwnPropertyDescriptors,al=Object.getOwnPropertySymbols,lx=Object.prototype.hasOwnProperty,fx=Object.prototype.propertyIsEnumerable,cl=(a,t,r)=>t in a?cx(a,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):a[t]=r,ul=(a,t)=>{for(var r in t||(t={}))lx.call(t,r)&&cl(a,r,t[r]);if(al)for(var r of al(t))fx.call(t,r)&&cl(a,r,t[r]);return a},hl=(a,t)=>ux(a,hx(t));const px={Accept:"application/json","Content-Type":"application/json"},dx="POST",ll={headers:px,method:dx},fl=10;let Xr=class{constructor(t,r=!1){if(this.url=t,this.disableProviderPing=r,this.events=new ar.EventEmitter,this.isAvailable=!1,this.registering=!1,!Dh(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);this.url=t,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async open(t=this.url){await this.register(t)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(t){this.isAvailable||await this.register();try{const r=fi(t),s=await(await ol(this.url,hl(ul({},ll),{body:r}))).json();this.onPayload({data:s})}catch(r){this.onError(t.id,r)}}async register(t=this.url){if(!Dh(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);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((s,o)=>{this.events.once("register_error",u=>{this.resetMaxListeners(),o(u)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return o(new Error("HTTP connection is missing or invalid"));s()})})}this.url=t,this.registering=!0;try{if(!this.disableProviderPing){const r=fi({id:1,jsonrpc:"2.0",method:"test",params:[]});await ol(t,hl(ul({},ll),{body:r}))}this.onOpen()}catch(r){const s=this.parseError(r);throw this.events.emit("register_error",s),this.onClose(),s}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(t){if(typeof t.data>"u")return;const r=typeof t.data=="string"?_s(t.data):t.data;this.events.emit("payload",r)}onError(t,r){const s=this.parseError(r),o=s.message||s.toString(),u=Nn(t,o);this.events.emit("payload",u)}parseError(t,r=this.url){return Vl(t,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>fl&&this.events.setMaxListeners(fl)}};const pl="error",gx="wss://relay.walletconnect.com",yx="wc",vx="universal_provider",dl=`${yx}@2:${vx}:`,mx="https://rpc.walletconnect.com/v1/",Lr={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var hs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},xa={exports:{}};/** * @license * Lodash * Copyright OpenJS Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */(function(a,t){(function(){var r,s="4.17.21",o=200,u="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",f="Expected a function",y="Invalid `variable` option passed into `_.template`",v="__lodash_hash_undefined__",p=500,w="__lodash_placeholder__",I=1,R=2,$=4,O=1,B=2,X=1,ie=2,he=4,re=8,Y=16,ce=32,pe=64,W=128,de=256,et=512,tt=30,Me="...",Qt=800,Rt=16,b=1,S=2,F=3,ae=1/0,z=9007199254740991,M=17976931348623157e292,U=NaN,k=4294967295,Ue=k-1,Be=k>>>1,ki=[["ary",W],["bind",X],["bindKey",ie],["curry",re],["curryRight",Y],["flip",et],["partial",ce],["partialRight",pe],["rearg",de]],yr="[object Arguments]",Mr="[object Array]",T="[object AsyncFunction]",N="[object Boolean]",A="[object Date]",h="[object DOMException]",E="[object Error]",J="[object Function]",ne="[object GeneratorFunction]",ge="[object Map]",_e="[object Number]",Ie="[object Null]",we="[object Object]",rt="[object Promise]",Je="[object Proxy]",ke="[object RegExp]",Pe="[object Set]",Ne="[object String]",De="[object Symbol]",He="[object Undefined]",Re="[object WeakMap]",je="[object WeakSet]",Se="[object ArrayBuffer]",qe="[object DataView]",Qe="[object Float32Array]",it="[object Float64Array]",wt="[object Int8Array]",It="[object Int16Array]",At="[object Int32Array]",Nt="[object Uint8Array]",Kt="[object Uint8ClampedArray]",Yt="[object Uint16Array]",cr="[object Uint32Array]",zr=/\b__p \+= '';/g,ei=/\b(__p \+=) '' \+/g,yi=/(__e\(.*?\)|\b__t\)) \+\n'';/g,vi=/&(?:amp|lt|gt|quot|#39);/g,Hi=/[&<>"']/g,st=RegExp(vi.source),nt=RegExp(Hi.source),ot=/<%-([\s\S]+?)%>/g,at=/<%([\s\S]+?)%>/g,Ye=/<%=([\s\S]+?)%>/g,ct=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ut=/^\w*$/,ht=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Fe=/[\\^$.*+?()[\]{}|]/g,lt=RegExp(Fe.source),Ge=/^\s+/,ft=/\s/,pt=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,dt=/\{\n\/\* \[wrapped with (.+)\] \*/,gt=/,? & /,yt=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,mf=/[()=,{}\[\]\/\s]/,wf=/\\(\\)?/g,bf=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,za=/\w*$/,_f=/^[-+]0x[0-9a-f]+$/i,Ef=/^0b[01]+$/i,If=/^\[object .+?Constructor\]$/,xf=/^0o[0-7]+$/i,Pf=/^(?:0|[1-9]\d*)$/,Sf=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,xs=/($^)/,Of=/['\n\r\u2028\u2029\\]/g,Ps="\\ud800-\\udfff",Rf="\\u0300-\\u036f",Af="\\ufe20-\\ufe2f",Cf="\\u20d0-\\u20ff",Ua=Rf+Af+Cf,ka="\\u2700-\\u27bf",Ha="a-z\\xdf-\\xf6\\xf8-\\xff",$f="\\xac\\xb1\\xd7\\xf7",Tf="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",Nf="\\u2000-\\u206f",Df=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Ka="A-Z\\xc0-\\xd6\\xd8-\\xde",Va="\\ufe0e\\ufe0f",Ba=$f+Tf+Nf+Df,Ln="['’]",jf="["+Ps+"]",Fa="["+Ba+"]",Ss="["+Ua+"]",Ga="\\d+",qf="["+ka+"]",Wa="["+Ha+"]",Ja="[^"+Ps+Ba+Ga+ka+Ha+Ka+"]",Mn="\\ud83c[\\udffb-\\udfff]",Lf="(?:"+Ss+"|"+Mn+")",Qa="[^"+Ps+"]",zn="(?:\\ud83c[\\udde6-\\uddff]){2}",Un="[\\ud800-\\udbff][\\udc00-\\udfff]",mi="["+Ka+"]",Ya="\\u200d",Za="(?:"+Wa+"|"+Ja+")",Mf="(?:"+mi+"|"+Ja+")",Xa="(?:"+Ln+"(?:d|ll|m|re|s|t|ve))?",ec="(?:"+Ln+"(?:D|LL|M|RE|S|T|VE))?",tc=Lf+"?",rc="["+Va+"]?",zf="(?:"+Ya+"(?:"+[Qa,zn,Un].join("|")+")"+rc+tc+")*",Uf="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",kf="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",ic=rc+tc+zf,Hf="(?:"+[qf,zn,Un].join("|")+")"+ic,Kf="(?:"+[Qa+Ss+"?",Ss,zn,Un,jf].join("|")+")",Vf=RegExp(Ln,"g"),Bf=RegExp(Ss,"g"),kn=RegExp(Mn+"(?="+Mn+")|"+Kf+ic,"g"),Ff=RegExp([mi+"?"+Wa+"+"+Xa+"(?="+[Fa,mi,"$"].join("|")+")",Mf+"+"+ec+"(?="+[Fa,mi+Za,"$"].join("|")+")",mi+"?"+Za+"+"+Xa,mi+"+"+ec,kf,Uf,Ga,Hf].join("|"),"g"),Gf=RegExp("["+Ya+Ps+Ua+Va+"]"),Wf=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Jf=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Qf=-1,Ce={};Ce[Qe]=Ce[it]=Ce[wt]=Ce[It]=Ce[At]=Ce[Nt]=Ce[Kt]=Ce[Yt]=Ce[cr]=!0,Ce[yr]=Ce[Mr]=Ce[Se]=Ce[N]=Ce[qe]=Ce[A]=Ce[E]=Ce[J]=Ce[ge]=Ce[_e]=Ce[we]=Ce[ke]=Ce[Pe]=Ce[Ne]=Ce[Re]=!1;var Ae={};Ae[yr]=Ae[Mr]=Ae[Se]=Ae[qe]=Ae[N]=Ae[A]=Ae[Qe]=Ae[it]=Ae[wt]=Ae[It]=Ae[At]=Ae[ge]=Ae[_e]=Ae[we]=Ae[ke]=Ae[Pe]=Ae[Ne]=Ae[De]=Ae[Nt]=Ae[Kt]=Ae[Yt]=Ae[cr]=!0,Ae[E]=Ae[J]=Ae[Re]=!1;var Yf={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},Zf={"&":"&","<":"<",">":">",'"':""","'":"'"},Xf={"&":"&","<":"<",">":">",""":'"',"'":"'"},ep={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},tp=parseFloat,rp=parseInt,sc=typeof hs=="object"&&hs&&hs.Object===Object&&hs,ip=typeof self=="object"&&self&&self.Object===Object&&self,bt=sc||ip||Function("return this")(),Hn=t&&!t.nodeType&&t,ti=Hn&&!0&&a&&!a.nodeType&&a,nc=ti&&ti.exports===Hn,Kn=nc&&sc.process,Zt=function(){try{var x=ti&&ti.require&&ti.require("util").types;return x||Kn&&Kn.binding&&Kn.binding("util")}catch{}}(),oc=Zt&&Zt.isArrayBuffer,ac=Zt&&Zt.isDate,cc=Zt&&Zt.isMap,uc=Zt&&Zt.isRegExp,hc=Zt&&Zt.isSet,lc=Zt&&Zt.isTypedArray;function Vt(x,D,C){switch(C.length){case 0:return x.call(D);case 1:return x.call(D,C[0]);case 2:return x.call(D,C[0],C[1]);case 3:return x.call(D,C[0],C[1],C[2])}return x.apply(D,C)}function sp(x,D,C,V){for(var se=-1,be=x==null?0:x.length;++se-1}function Vn(x,D,C){for(var V=-1,se=x==null?0:x.length;++V-1;);return C}function wc(x,D){for(var C=x.length;C--&&wi(D,x[C],0)>-1;);return C}function pp(x,D){for(var C=x.length,V=0;C--;)x[C]===D&&++V;return V}var dp=Wn(Yf),gp=Wn(Zf);function yp(x){return"\\"+ep[x]}function vp(x,D){return x==null?r:x[D]}function bi(x){return Gf.test(x)}function mp(x){return Wf.test(x)}function wp(x){for(var D,C=[];!(D=x.next()).done;)C.push(D.value);return C}function Zn(x){var D=-1,C=Array(x.size);return x.forEach(function(V,se){C[++D]=[se,V]}),C}function bc(x,D){return function(C){return x(D(C))}}function Hr(x,D){for(var C=-1,V=x.length,se=0,be=[];++C-1}function od(e,i){var n=this.__data__,c=Vs(n,e);return c<0?(++this.size,n.push([e,i])):n[c][1]=i,this}Er.prototype.clear=rd,Er.prototype.delete=id,Er.prototype.get=sd,Er.prototype.has=nd,Er.prototype.set=od;function Ir(e){var i=-1,n=e==null?0:e.length;for(this.clear();++i=i?e:i)),e}function rr(e,i,n,c,l,g){var m,_=i&I,P=i&R,j=i&$;if(n&&(m=l?n(e,c,l,g):n(e)),m!==r)return m;if(!Le(e))return e;var q=oe(e);if(q){if(m=hg(e),!_)return Dt(e,m)}else{var L=Pt(e),H=L==J||L==ne;if(Wr(e))return ru(e,_);if(L==we||L==yr||H&&!l){if(m=P||H?{}:_u(e),!_)return P?Xd(e,Ed(m,e)):Zd(e,Tc(m,e))}else{if(!Ae[L])return l?e:{};m=lg(e,L,_)}}g||(g=new hr);var G=g.get(e);if(G)return G;g.set(e,m),Qu(e)?e.forEach(function(te){m.add(rr(te,i,n,te,e,g))}):Wu(e)&&e.forEach(function(te,ye){m.set(ye,rr(te,i,n,ye,e,g))});var ee=j?P?Po:xo:P?qt:vt,le=q?r:ee(e);return Xt(le||e,function(te,ye){le&&(ye=te,te=e[ye]),Ji(m,ye,rr(te,i,n,ye,e,g))}),m}function Id(e){var i=vt(e);return function(n){return Nc(n,e,i)}}function Nc(e,i,n){var c=n.length;if(e==null)return!c;for(e=Oe(e);c--;){var l=n[c],g=i[l],m=e[l];if(m===r&&!(l in e)||!g(m))return!1}return!0}function Dc(e,i,n){if(typeof e!="function")throw new er(f);return rs(function(){e.apply(r,n)},i)}function Qi(e,i,n,c){var l=-1,g=Os,m=!0,_=e.length,P=[],j=i.length;if(!_)return P;n&&(i=$e(i,Bt(n))),c?(g=Vn,m=!1):i.length>=o&&(g=Ki,m=!1,i=new si(i));e:for(;++l<_;){var q=e[l],L=n==null?q:n(q);if(q=c||q!==0?q:0,m&&L===L){for(var H=j;H--;)if(i[H]===L)continue e;P.push(q)}else g(i,L,c)||P.push(q)}return P}var Vr=au(vr),jc=au(oo,!0);function xd(e,i){var n=!0;return Vr(e,function(c,l,g){return n=!!i(c,l,g),n}),n}function Bs(e,i,n){for(var c=-1,l=e.length;++cl?0:l+n),c=c===r||c>l?l:ue(c),c<0&&(c+=l),c=n>c?0:Zu(c);n0&&n(_)?i>1?_t(_,i-1,n,c,l):kr(l,_):c||(l[l.length]=_)}return l}var no=cu(),Lc=cu(!0);function vr(e,i){return e&&no(e,i,vt)}function oo(e,i){return e&&Lc(e,i,vt)}function Fs(e,i){return Ur(i,function(n){return Rr(e[n])})}function oi(e,i){i=Fr(i,e);for(var n=0,c=i.length;e!=null&&ni}function Sd(e,i){return e!=null&&xe.call(e,i)}function Od(e,i){return e!=null&&i in Oe(e)}function Rd(e,i,n){return e>=xt(i,n)&&e=120&&q.length>=120)?new si(m&&q):r}q=e[0];var L=-1,H=_[0];e:for(;++L-1;)_!==e&&Ls.call(_,P,1),Ls.call(e,P,1);return e}function Wc(e,i){for(var n=e?i.length:0,c=n-1;n--;){var l=i[n];if(n==c||l!==g){var g=l;Or(l)?Ls.call(e,l,1):vo(e,l)}}return e}function po(e,i){return e+Us(Rc()*(i-e+1))}function kd(e,i,n,c){for(var l=-1,g=Xe(zs((i-e)/(n||1)),0),m=C(g);g--;)m[c?g:++l]=e,e+=n;return m}function go(e,i){var n="";if(!e||i<1||i>z)return n;do i%2&&(n+=e),i=Us(i/2),i&&(e+=e);while(i);return n}function fe(e,i){return To(xu(e,i,Lt),e+"")}function Hd(e){return $c($i(e))}function Kd(e,i){var n=$i(e);return sn(n,ni(i,0,n.length))}function Xi(e,i,n,c){if(!Le(e))return e;i=Fr(i,e);for(var l=-1,g=i.length,m=g-1,_=e;_!=null&&++ll?0:l+i),n=n>l?l:n,n<0&&(n+=l),l=i>n?0:n-i>>>0,i>>>=0;for(var g=C(l);++c>>1,m=e[g];m!==null&&!Gt(m)&&(n?m<=i:m=o){var j=i?null:ig(e);if(j)return As(j);m=!1,l=Ki,P=new si}else P=i?[]:_;e:for(;++c=c?e:ir(e,i,n)}var tu=Dp||function(e){return bt.clearTimeout(e)};function ru(e,i){if(i)return e.slice();var n=e.length,c=Ic?Ic(n):new e.constructor(n);return e.copy(c),c}function _o(e){var i=new e.constructor(e.byteLength);return new js(i).set(new js(e)),i}function Wd(e,i){var n=i?_o(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}function Jd(e){var i=new e.constructor(e.source,za.exec(e));return i.lastIndex=e.lastIndex,i}function Qd(e){return Wi?Oe(Wi.call(e)):{}}function iu(e,i){var n=i?_o(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}function su(e,i){if(e!==i){var n=e!==r,c=e===null,l=e===e,g=Gt(e),m=i!==r,_=i===null,P=i===i,j=Gt(i);if(!_&&!j&&!g&&e>i||g&&m&&P&&!_&&!j||c&&m&&P||!n&&P||!l)return 1;if(!c&&!g&&!j&&e=_)return P;var j=n[c];return P*(j=="desc"?-1:1)}}return e.index-i.index}function nu(e,i,n,c){for(var l=-1,g=e.length,m=n.length,_=-1,P=i.length,j=Xe(g-m,0),q=C(P+j),L=!c;++_1?n[l-1]:r,m=l>2?n[2]:r;for(g=e.length>3&&typeof g=="function"?(l--,g):r,m&&$t(n[0],n[1],m)&&(g=l<3?r:g,l=1),i=Oe(i);++c-1?l[g?i[m]:m]:r}}function lu(e){return Sr(function(i){var n=i.length,c=n,l=tr.prototype.thru;for(e&&i.reverse();c--;){var g=i[c];if(typeof g!="function")throw new er(f);if(l&&!m&&tn(g)=="wrapper")var m=new tr([],!0)}for(c=m?c:n;++c1&&me.reverse(),q&&P_))return!1;var j=g.get(e),q=g.get(i);if(j&&q)return j==i&&q==e;var L=-1,H=!0,G=n&B?new si:r;for(g.set(e,i),g.set(i,e);++L<_;){var ee=e[L],le=i[L];if(c)var te=m?c(le,ee,L,i,e,g):c(ee,le,L,e,i,g);if(te!==r){if(te)continue;H=!1;break}if(G){if(!Fn(i,function(ye,me){if(!Ki(G,me)&&(ee===ye||l(ee,ye,n,c,g)))return G.push(me)})){H=!1;break}}else if(!(ee===le||l(ee,le,n,c,g))){H=!1;break}}return g.delete(e),g.delete(i),H}function ng(e,i,n,c,l,g,m){switch(n){case qe:if(e.byteLength!=i.byteLength||e.byteOffset!=i.byteOffset)return!1;e=e.buffer,i=i.buffer;case Se:return!(e.byteLength!=i.byteLength||!g(new js(e),new js(i)));case N:case A:case _e:return lr(+e,+i);case E:return e.name==i.name&&e.message==i.message;case ke:case Ne:return e==i+"";case ge:var _=Zn;case Pe:var P=c&O;if(_||(_=As),e.size!=i.size&&!P)return!1;var j=m.get(e);if(j)return j==i;c|=B,m.set(e,i);var q=mu(_(e),_(i),c,l,g,m);return m.delete(e),q;case De:if(Wi)return Wi.call(e)==Wi.call(i)}return!1}function og(e,i,n,c,l,g){var m=n&O,_=xo(e),P=_.length,j=xo(i),q=j.length;if(P!=q&&!m)return!1;for(var L=P;L--;){var H=_[L];if(!(m?H in i:xe.call(i,H)))return!1}var G=g.get(e),ee=g.get(i);if(G&&ee)return G==i&&ee==e;var le=!0;g.set(e,i),g.set(i,e);for(var te=m;++L1?"& ":"")+i[c],i=i.join(n>2?", ":" "),e.replace(pt,`{ /* [wrapped with `+i+`] */ `)}function pg(e){return oe(e)||ui(e)||!!(Sc&&e&&e[Sc])}function Or(e,i){var n=typeof e;return i=i??z,!!i&&(n=="number"||n!="symbol"&&Pf.test(e))&&e>-1&&e%1==0&&e0){if(++i>=Qt)return arguments[0]}else i=0;return e.apply(r,arguments)}}function sn(e,i){var n=-1,c=e.length,l=c-1;for(i=i===r?c:i;++n1?e[i-1]:r;return n=typeof n=="function"?(e.pop(),n):r,qu(e,n)});function Lu(e){var i=d(e);return i.__chain__=!0,i}function xy(e,i){return i(e),e}function nn(e,i){return i(e)}var Py=Sr(function(e){var i=e.length,n=i?e[0]:0,c=this.__wrapped__,l=function(g){return so(g,e)};return i>1||this.__actions__.length||!(c instanceof ve)||!Or(n)?this.thru(l):(c=c.slice(n,+n+(i?1:0)),c.__actions__.push({func:nn,args:[l],thisArg:r}),new tr(c,this.__chain__).thru(function(g){return i&&!g.length&&g.push(r),g}))});function Sy(){return Lu(this)}function Oy(){return new tr(this.value(),this.__chain__)}function Ry(){this.__values__===r&&(this.__values__=Yu(this.value()));var e=this.__index__>=this.__values__.length,i=e?r:this.__values__[this.__index__++];return{done:e,value:i}}function Ay(){return this}function Cy(e){for(var i,n=this;n instanceof Ks;){var c=Cu(n);c.__index__=0,c.__values__=r,i?l.__wrapped__=c:i=c;var l=c;n=n.__wrapped__}return l.__wrapped__=e,i}function $y(){var e=this.__wrapped__;if(e instanceof ve){var i=e;return this.__actions__.length&&(i=new ve(this)),i=i.reverse(),i.__actions__.push({func:nn,args:[No],thisArg:r}),new tr(i,this.__chain__)}return this.thru(No)}function Ty(){return Xc(this.__wrapped__,this.__actions__)}var Ny=Qs(function(e,i,n){xe.call(e,n)?++e[n]:xr(e,n,1)});function Dy(e,i,n){var c=oe(e)?fc:xd;return n&&$t(e,i,n)&&(i=r),c(e,Z(i,3))}function jy(e,i){var n=oe(e)?Ur:qc;return n(e,Z(i,3))}var qy=hu($u),Ly=hu(Tu);function My(e,i){return _t(on(e,i),1)}function zy(e,i){return _t(on(e,i),ae)}function Uy(e,i,n){return n=n===r?1:ue(n),_t(on(e,i),n)}function Mu(e,i){var n=oe(e)?Xt:Vr;return n(e,Z(i,3))}function zu(e,i){var n=oe(e)?np:jc;return n(e,Z(i,3))}var ky=Qs(function(e,i,n){xe.call(e,n)?e[n].push(i):xr(e,n,[i])});function Hy(e,i,n,c){e=jt(e)?e:$i(e),n=n&&!c?ue(n):0;var l=e.length;return n<0&&(n=Xe(l+n,0)),ln(e)?n<=l&&e.indexOf(i,n)>-1:!!l&&wi(e,i,n)>-1}var Ky=fe(function(e,i,n){var c=-1,l=typeof i=="function",g=jt(e)?C(e.length):[];return Vr(e,function(m){g[++c]=l?Vt(i,m,n):Yi(m,i,n)}),g}),Vy=Qs(function(e,i,n){xr(e,n,i)});function on(e,i){var n=oe(e)?$e:Hc;return n(e,Z(i,3))}function By(e,i,n,c){return e==null?[]:(oe(i)||(i=i==null?[]:[i]),n=c?r:n,oe(n)||(n=n==null?[]:[n]),Fc(e,i,n))}var Fy=Qs(function(e,i,n){e[n?0:1].push(i)},function(){return[[],[]]});function Gy(e,i,n){var c=oe(e)?Bn:yc,l=arguments.length<3;return c(e,Z(i,4),n,l,Vr)}function Wy(e,i,n){var c=oe(e)?op:yc,l=arguments.length<3;return c(e,Z(i,4),n,l,jc)}function Jy(e,i){var n=oe(e)?Ur:qc;return n(e,un(Z(i,3)))}function Qy(e){var i=oe(e)?$c:Hd;return i(e)}function Yy(e,i,n){(n?$t(e,i,n):i===r)?i=1:i=ue(i);var c=oe(e)?wd:Kd;return c(e,i)}function Zy(e){var i=oe(e)?bd:Bd;return i(e)}function Xy(e){if(e==null)return 0;if(jt(e))return ln(e)?_i(e):e.length;var i=Pt(e);return i==ge||i==Pe?e.size:ho(e).length}function ev(e,i,n){var c=oe(e)?Fn:Fd;return n&&$t(e,i,n)&&(i=r),c(e,Z(i,3))}var tv=fe(function(e,i){if(e==null)return[];var n=i.length;return n>1&&$t(e,i[0],i[1])?i=[]:n>2&&$t(i[0],i[1],i[2])&&(i=[i[0]]),Fc(e,_t(i,1),[])}),an=jp||function(){return bt.Date.now()};function rv(e,i){if(typeof i!="function")throw new er(f);return e=ue(e),function(){if(--e<1)return i.apply(this,arguments)}}function Uu(e,i,n){return i=n?r:i,i=e&&i==null?e.length:i,Pr(e,W,r,r,r,r,i)}function ku(e,i){var n;if(typeof i!="function")throw new er(f);return e=ue(e),function(){return--e>0&&(n=i.apply(this,arguments)),e<=1&&(i=r),n}}var jo=fe(function(e,i,n){var c=X;if(n.length){var l=Hr(n,Ai(jo));c|=ce}return Pr(e,c,i,n,l)}),Hu=fe(function(e,i,n){var c=X|ie;if(n.length){var l=Hr(n,Ai(Hu));c|=ce}return Pr(i,c,e,n,l)});function Ku(e,i,n){i=n?r:i;var c=Pr(e,re,r,r,r,r,r,i);return c.placeholder=Ku.placeholder,c}function Vu(e,i,n){i=n?r:i;var c=Pr(e,Y,r,r,r,r,r,i);return c.placeholder=Vu.placeholder,c}function Bu(e,i,n){var c,l,g,m,_,P,j=0,q=!1,L=!1,H=!0;if(typeof e!="function")throw new er(f);i=nr(i)||0,Le(n)&&(q=!!n.leading,L="maxWait"in n,g=L?Xe(nr(n.maxWait)||0,i):g,H="trailing"in n?!!n.trailing:H);function G(Ve){var fr=c,Cr=l;return c=l=r,j=Ve,m=e.apply(Cr,fr),m}function ee(Ve){return j=Ve,_=rs(ye,i),q?G(Ve):m}function le(Ve){var fr=Ve-P,Cr=Ve-j,hh=i-fr;return L?xt(hh,g-Cr):hh}function te(Ve){var fr=Ve-P,Cr=Ve-j;return P===r||fr>=i||fr<0||L&&Cr>=g}function ye(){var Ve=an();if(te(Ve))return me(Ve);_=rs(ye,le(Ve))}function me(Ve){return _=r,H&&c?G(Ve):(c=l=r,m)}function Wt(){_!==r&&tu(_),j=0,c=P=l=_=r}function Tt(){return _===r?m:me(an())}function Jt(){var Ve=an(),fr=te(Ve);if(c=arguments,l=this,P=Ve,fr){if(_===r)return ee(P);if(L)return tu(_),_=rs(ye,i),G(P)}return _===r&&(_=rs(ye,i)),m}return Jt.cancel=Wt,Jt.flush=Tt,Jt}var iv=fe(function(e,i){return Dc(e,1,i)}),sv=fe(function(e,i,n){return Dc(e,nr(i)||0,n)});function nv(e){return Pr(e,et)}function cn(e,i){if(typeof e!="function"||i!=null&&typeof i!="function")throw new er(f);var n=function(){var c=arguments,l=i?i.apply(this,c):c[0],g=n.cache;if(g.has(l))return g.get(l);var m=e.apply(this,c);return n.cache=g.set(l,m)||g,m};return n.cache=new(cn.Cache||Ir),n}cn.Cache=Ir;function un(e){if(typeof e!="function")throw new er(f);return function(){var i=arguments;switch(i.length){case 0:return!e.call(this);case 1:return!e.call(this,i[0]);case 2:return!e.call(this,i[0],i[1]);case 3:return!e.call(this,i[0],i[1],i[2])}return!e.apply(this,i)}}function ov(e){return ku(2,e)}var av=Gd(function(e,i){i=i.length==1&&oe(i[0])?$e(i[0],Bt(Z())):$e(_t(i,1),Bt(Z()));var n=i.length;return fe(function(c){for(var l=-1,g=xt(c.length,n);++l=i}),ui=zc(function(){return arguments}())?zc:function(e){return ze(e)&&xe.call(e,"callee")&&!Pc.call(e,"callee")},oe=C.isArray,Ev=oc?Bt(oc):Cd;function jt(e){return e!=null&&hn(e.length)&&!Rr(e)}function Ke(e){return ze(e)&&jt(e)}function Iv(e){return e===!0||e===!1||ze(e)&&Ct(e)==N}var Wr=Lp||Go,xv=ac?Bt(ac):$d;function Pv(e){return ze(e)&&e.nodeType===1&&!is(e)}function Sv(e){if(e==null)return!0;if(jt(e)&&(oe(e)||typeof e=="string"||typeof e.splice=="function"||Wr(e)||Ci(e)||ui(e)))return!e.length;var i=Pt(e);if(i==ge||i==Pe)return!e.size;if(ts(e))return!ho(e).length;for(var n in e)if(xe.call(e,n))return!1;return!0}function Ov(e,i){return Zi(e,i)}function Rv(e,i,n){n=typeof n=="function"?n:r;var c=n?n(e,i):r;return c===r?Zi(e,i,r,n):!!c}function Lo(e){if(!ze(e))return!1;var i=Ct(e);return i==E||i==h||typeof e.message=="string"&&typeof e.name=="string"&&!is(e)}function Av(e){return typeof e=="number"&&Oc(e)}function Rr(e){if(!Le(e))return!1;var i=Ct(e);return i==J||i==ne||i==T||i==Je}function Gu(e){return typeof e=="number"&&e==ue(e)}function hn(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=z}function Le(e){var i=typeof e;return e!=null&&(i=="object"||i=="function")}function ze(e){return e!=null&&typeof e=="object"}var Wu=cc?Bt(cc):Nd;function Cv(e,i){return e===i||uo(e,i,Oo(i))}function $v(e,i,n){return n=typeof n=="function"?n:r,uo(e,i,Oo(i),n)}function Tv(e){return Ju(e)&&e!=+e}function Nv(e){if(yg(e))throw new se(u);return Uc(e)}function Dv(e){return e===null}function jv(e){return e==null}function Ju(e){return typeof e=="number"||ze(e)&&Ct(e)==_e}function is(e){if(!ze(e)||Ct(e)!=we)return!1;var i=qs(e);if(i===null)return!0;var n=xe.call(i,"constructor")&&i.constructor;return typeof n=="function"&&n instanceof n&&Ts.call(n)==$p}var Mo=uc?Bt(uc):Dd;function qv(e){return Gu(e)&&e>=-z&&e<=z}var Qu=hc?Bt(hc):jd;function ln(e){return typeof e=="string"||!oe(e)&&ze(e)&&Ct(e)==Ne}function Gt(e){return typeof e=="symbol"||ze(e)&&Ct(e)==De}var Ci=lc?Bt(lc):qd;function Lv(e){return e===r}function Mv(e){return ze(e)&&Pt(e)==Re}function zv(e){return ze(e)&&Ct(e)==je}var Uv=en(lo),kv=en(function(e,i){return e<=i});function Yu(e){if(!e)return[];if(jt(e))return ln(e)?ur(e):Dt(e);if(Vi&&e[Vi])return wp(e[Vi]());var i=Pt(e),n=i==ge?Zn:i==Pe?As:$i;return n(e)}function Ar(e){if(!e)return e===0?e:0;if(e=nr(e),e===ae||e===-ae){var i=e<0?-1:1;return i*M}return e===e?e:0}function ue(e){var i=Ar(e),n=i%1;return i===i?n?i-n:i:0}function Zu(e){return e?ni(ue(e),0,k):0}function nr(e){if(typeof e=="number")return e;if(Gt(e))return U;if(Le(e)){var i=typeof e.valueOf=="function"?e.valueOf():e;e=Le(i)?i+"":i}if(typeof e!="string")return e===0?e:+e;e=vc(e);var n=Ef.test(e);return n||xf.test(e)?rp(e.slice(2),n?2:8):_f.test(e)?U:+e}function Xu(e){return mr(e,qt(e))}function Hv(e){return e?ni(ue(e),-z,z):e===0?e:0}function Ee(e){return e==null?"":Ft(e)}var Kv=Oi(function(e,i){if(ts(i)||jt(i)){mr(i,vt(i),e);return}for(var n in i)xe.call(i,n)&&Ji(e,n,i[n])}),eh=Oi(function(e,i){mr(i,qt(i),e)}),fn=Oi(function(e,i,n,c){mr(i,qt(i),e,c)}),Vv=Oi(function(e,i,n,c){mr(i,vt(i),e,c)}),Bv=Sr(so);function Fv(e,i){var n=Si(e);return i==null?n:Tc(n,i)}var Gv=fe(function(e,i){e=Oe(e);var n=-1,c=i.length,l=c>2?i[2]:r;for(l&&$t(i[0],i[1],l)&&(c=1);++n1),g}),mr(e,Po(e),n),c&&(n=rr(n,I|R|$,sg));for(var l=i.length;l--;)vo(n,i[l]);return n});function lm(e,i){return rh(e,un(Z(i)))}var fm=Sr(function(e,i){return e==null?{}:zd(e,i)});function rh(e,i){if(e==null)return{};var n=$e(Po(e),function(c){return[c]});return i=Z(i),Gc(e,n,function(c,l){return i(c,l[0])})}function pm(e,i,n){i=Fr(i,e);var c=-1,l=i.length;for(l||(l=1,e=r);++ci){var c=e;e=i,i=c}if(n||e%1||i%1){var l=Rc();return xt(e+l*(i-e+tp("1e-"+((l+"").length-1))),i)}return po(e,i)}var xm=Ri(function(e,i,n){return i=i.toLowerCase(),e+(n?nh(i):i)});function nh(e){return ko(Ee(e).toLowerCase())}function oh(e){return e=Ee(e),e&&e.replace(Sf,dp).replace(Bf,"")}function Pm(e,i,n){e=Ee(e),i=Ft(i);var c=e.length;n=n===r?c:ni(ue(n),0,c);var l=n;return n-=i.length,n>=0&&e.slice(n,l)==i}function Sm(e){return e=Ee(e),e&&nt.test(e)?e.replace(Hi,gp):e}function Om(e){return e=Ee(e),e&<.test(e)?e.replace(Fe,"\\$&"):e}var Rm=Ri(function(e,i,n){return e+(n?"-":"")+i.toLowerCase()}),Am=Ri(function(e,i,n){return e+(n?" ":"")+i.toLowerCase()}),Cm=uu("toLowerCase");function $m(e,i,n){e=Ee(e),i=ue(i);var c=i?_i(e):0;if(!i||c>=i)return e;var l=(i-c)/2;return Xs(Us(l),n)+e+Xs(zs(l),n)}function Tm(e,i,n){e=Ee(e),i=ue(i);var c=i?_i(e):0;return i&&c>>0,n?(e=Ee(e),e&&(typeof i=="string"||i!=null&&!Mo(i))&&(i=Ft(i),!i&&bi(e))?Gr(ur(e),0,n):e.split(i,n)):[]}var zm=Ri(function(e,i,n){return e+(n?" ":"")+ko(i)});function Um(e,i,n){return e=Ee(e),n=n==null?0:ni(ue(n),0,e.length),i=Ft(i),e.slice(n,n+i.length)==i}function km(e,i,n){var c=d.templateSettings;n&&$t(e,i,n)&&(i=r),e=Ee(e),i=fn({},i,c,yu);var l=fn({},i.imports,c.imports,yu),g=vt(l),m=Yn(l,g),_,P,j=0,q=i.interpolate||xs,L="__p += '",H=Xn((i.escape||xs).source+"|"+q.source+"|"+(q===Ye?bf:xs).source+"|"+(i.evaluate||xs).source+"|$","g"),G="//# sourceURL="+(xe.call(i,"sourceURL")?(i.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++Qf+"]")+` `;e.replace(H,function(te,ye,me,Wt,Tt,Jt){return me||(me=Wt),L+=e.slice(j,Jt).replace(Of,yp),ye&&(_=!0,L+=`' + __e(`+ye+`) + '`),Tt&&(P=!0,L+=`'; `+Tt+`; __p += '`),me&&(L+=`' + ((__t = (`+me+`)) == null ? '' : __t) + '`),j=Jt+te.length,te}),L+=`'; `;var ee=xe.call(i,"variable")&&i.variable;if(!ee)L=`with (obj) { `+L+` } `;else if(mf.test(ee))throw new se(y);L=(P?L.replace(zr,""):L).replace(ei,"$1").replace(yi,"$1;"),L="function("+(ee||"obj")+`) { `+(ee?"":`obj || (obj = {}); `)+"var __t, __p = ''"+(_?", __e = _.escape":"")+(P?`, __j = Array.prototype.join; function print() { __p += __j.call(arguments, '') } `:`; `)+L+`return __p }`;var le=ch(function(){return be(g,G+"return "+L).apply(r,m)});if(le.source=L,Lo(le))throw le;return le}function Hm(e){return Ee(e).toLowerCase()}function Km(e){return Ee(e).toUpperCase()}function Vm(e,i,n){if(e=Ee(e),e&&(n||i===r))return vc(e);if(!e||!(i=Ft(i)))return e;var c=ur(e),l=ur(i),g=mc(c,l),m=wc(c,l)+1;return Gr(c,g,m).join("")}function Bm(e,i,n){if(e=Ee(e),e&&(n||i===r))return e.slice(0,_c(e)+1);if(!e||!(i=Ft(i)))return e;var c=ur(e),l=wc(c,ur(i))+1;return Gr(c,0,l).join("")}function Fm(e,i,n){if(e=Ee(e),e&&(n||i===r))return e.replace(Ge,"");if(!e||!(i=Ft(i)))return e;var c=ur(e),l=mc(c,ur(i));return Gr(c,l).join("")}function Gm(e,i){var n=tt,c=Me;if(Le(i)){var l="separator"in i?i.separator:l;n="length"in i?ue(i.length):n,c="omission"in i?Ft(i.omission):c}e=Ee(e);var g=e.length;if(bi(e)){var m=ur(e);g=m.length}if(n>=g)return e;var _=n-_i(c);if(_<1)return c;var P=m?Gr(m,0,_).join(""):e.slice(0,_);if(l===r)return P+c;if(m&&(_+=P.length-_),Mo(l)){if(e.slice(_).search(l)){var j,q=P;for(l.global||(l=Xn(l.source,Ee(za.exec(l))+"g")),l.lastIndex=0;j=l.exec(q);)var L=j.index;P=P.slice(0,L===r?_:L)}}else if(e.indexOf(Ft(l),_)!=_){var H=P.lastIndexOf(l);H>-1&&(P=P.slice(0,H))}return P+c}function Wm(e){return e=Ee(e),e&&st.test(e)?e.replace(vi,Ip):e}var Jm=Ri(function(e,i,n){return e+(n?" ":"")+i.toUpperCase()}),ko=uu("toUpperCase");function ah(e,i,n){return e=Ee(e),i=n?r:i,i===r?mp(e)?Sp(e):up(e):e.match(i)||[]}var ch=fe(function(e,i){try{return Vt(e,r,i)}catch(n){return Lo(n)?n:new se(n)}}),Qm=Sr(function(e,i){return Xt(i,function(n){n=wr(n),xr(e,n,jo(e[n],e))}),e});function Ym(e){var i=e==null?0:e.length,n=Z();return e=i?$e(e,function(c){if(typeof c[1]!="function")throw new er(f);return[n(c[0]),c[1]]}):[],fe(function(c){for(var l=-1;++lz)return[];var n=k,c=xt(e,k);i=Z(i),e-=k;for(var l=Qn(c,i);++n0||i<0)?new ve(n):(e<0?n=n.takeRight(-e):e&&(n=n.drop(e)),i!==r&&(i=ue(i),n=i<0?n.dropRight(-i):n.take(i-e)),n)},ve.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},ve.prototype.toArray=function(){return this.take(k)},vr(ve.prototype,function(e,i){var n=/^(?:filter|find|map|reject)|While$/.test(i),c=/^(?:head|last)$/.test(i),l=d[c?"take"+(i=="last"?"Right":""):i],g=c||/^find/.test(i);l&&(d.prototype[i]=function(){var m=this.__wrapped__,_=c?[1]:arguments,P=m instanceof ve,j=_[0],q=P||oe(m),L=function(ye){var me=l.apply(d,kr([ye],_));return c&&H?me[0]:me};q&&n&&typeof j=="function"&&j.length!=1&&(P=q=!1);var H=this.__chain__,G=!!this.__actions__.length,ee=g&&!H,le=P&&!G;if(!g&&q){m=le?m:new ve(this);var te=e.apply(m,_);return te.__actions__.push({func:nn,args:[L],thisArg:r}),new tr(te,H)}return ee&&le?e.apply(this,_):(te=this.thru(L),ee?c?te.value()[0]:te.value():te)})}),Xt(["pop","push","shift","sort","splice","unshift"],function(e){var i=Cs[e],n=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",c=/^(?:pop|shift)$/.test(e);d.prototype[e]=function(){var l=arguments;if(c&&!this.__chain__){var g=this.value();return i.apply(oe(g)?g:[],l)}return this[n](function(m){return i.apply(oe(m)?m:[],l)})}}),vr(ve.prototype,function(e,i){var n=d[i];if(n){var c=n.name+"";xe.call(Pi,c)||(Pi[c]=[]),Pi[c].push({name:i,func:n})}}),Pi[Ys(r,ie).name]=[{name:"wrapper",func:r}],ve.prototype.clone=Wp,ve.prototype.reverse=Jp,ve.prototype.value=Qp,d.prototype.at=Py,d.prototype.chain=Sy,d.prototype.commit=Oy,d.prototype.next=Ry,d.prototype.plant=Cy,d.prototype.reverse=$y,d.prototype.toJSON=d.prototype.valueOf=d.prototype.value=Ty,d.prototype.first=d.prototype.head,Vi&&(d.prototype[Vi]=Ay),d},Ei=Op();ti?((ti.exports=Ei)._=Ei,Hn._=Ei):bt._=Ei}).call(hs)})(xa,xa.exports);var wx=Object.defineProperty,bx=Object.defineProperties,_x=Object.getOwnPropertyDescriptors,gl=Object.getOwnPropertySymbols,Ex=Object.prototype.hasOwnProperty,Ix=Object.prototype.propertyIsEnumerable,yl=(a,t,r)=>t in a?wx(a,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):a[t]=r,mn=(a,t)=>{for(var r in t||(t={}))Ex.call(t,r)&&yl(a,r,t[r]);if(gl)for(var r of gl(t))Ix.call(t,r)&&yl(a,r,t[r]);return a},xx=(a,t)=>bx(a,_x(t));function Zr(a,t,r){var s;const o=_w(a);return((s=t.rpcMap)==null?void 0:s[o.reference])||`${mx}?chainId=${o.namespace}:${o.reference}&projectId=${r}`}function gi(a){return a.includes(":")?a.split(":")[1]:a}function yf(a){return a.map(t=>`${t.split(":")[0]}:${t.split(":")[1]}`)}function Px(a,t){const r=Object.keys(t.namespaces).filter(o=>o.includes(a));if(!r.length)return[];const s=[];return r.forEach(o=>{const u=t.namespaces[o].accounts;s.push(...u)}),s}function Sx(a={},t={}){const r=vl(a),s=vl(t);return xa.exports.merge(r,s)}function vl(a){var t,r,s,o;const u={};if(!_n(a))return u;for(const[f,y]of Object.entries(a)){const v=Cl(f)?[f]:y.chains,p=y.methods||[],w=y.events||[],I=y.rpcMap||{},R=ls(f);u[R]=xx(mn(mn({},u[R]),y),{chains:Jo(v,(t=u[R])==null?void 0:t.chains),methods:Jo(p,(r=u[R])==null?void 0:r.methods),events:Jo(w,(s=u[R])==null?void 0:s.events),rpcMap:mn(mn({},I),(o=u[R])==null?void 0:o.rpcMap)})}return u}function Ox(a){return a.includes(":")?a.split(":")[2]:a}function Rx(a){const t={};for(const[r,s]of Object.entries(a)){const o=s.methods||[],u=s.events||[],f=s.accounts||[],y=Cl(r)?[r]:s.chains?s.chains:yf(s.accounts);t[r]={chains:y,methods:o,events:u,accounts:f}}return t}function oa(a){return typeof a=="number"?a:a.includes("0x")?parseInt(a,16):a.includes(":")?Number(a.split(":")[1]):Number(a)}const vf={},Te=a=>vf[a],aa=(a,t)=>{vf[a]=t};class Ax{constructor(t){this.name="polkadot",this.namespace=t.namespace,this.events=Te("events"),this.client=Te("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(t,r),this.chainId=t,this.events.emit(Lr.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}getAccounts(){const t=this.namespace.accounts;return t?t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(r=>{var s;const o=gi(r);t[o]=this.createHttpProvider(o,(s=this.namespace.rpcMap)==null?void 0:s[r])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,r=this.httpProviders[t];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return r}setHttpProvider(t,r){const s=this.createHttpProvider(t,r);s&&(this.httpProviders[t]=s)}createHttpProvider(t,r){const s=r||Zr(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new qr(new Xr(s,Te("disableProviderPing")))}}class Cx{constructor(t){this.name="eip155",this.namespace=t.namespace,this.events=Te("events"),this.client=Te("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(t){switch(t.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(t);case"eth_chainId":return parseInt(this.getDefaultChain())}return this.namespace.methods.includes(t.request.method)?await this.client.request(t):this.getHttpProvider().request(t.request)}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(parseInt(t),r),this.chainId=parseInt(t),this.events.emit(Lr.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}createHttpProvider(t,r){const s=r||Zr(`${this.name}:${t}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new qr(new Xr(s,Te("disableProviderPing")))}setHttpProvider(t,r){const s=this.createHttpProvider(t,r);s&&(this.httpProviders[t]=s)}createHttpProviders(){const t={};return this.namespace.chains.forEach(r=>{var s;const o=parseInt(gi(r));t[o]=this.createHttpProvider(o,(s=this.namespace.rpcMap)==null?void 0:s[r])}),t}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const t=this.chainId,r=this.httpProviders[t];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return r}async handleSwitchChain(t){var r,s;let o=t.request.params?(r=t.request.params[0])==null?void 0:r.chainId:"0x0";o=o.startsWith("0x")?o:`0x${o}`;const u=parseInt(o,16);if(this.isChainApproved(u))this.setDefaultChain(`${u}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:t.topic,request:{method:t.request.method,params:[{chainId:o}]},chainId:(s=this.namespace.chains)==null?void 0:s[0]}),this.setDefaultChain(`${u}`);else throw new Error(`Failed to switch to chain 'eip155:${u}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(t){return this.namespace.chains.includes(`${this.name}:${t}`)}}class $x{constructor(t){this.name="solana",this.namespace=t.namespace,this.events=Te("events"),this.client=Te("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(t,r),this.chainId=t,this.events.emit(Lr.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(r=>{var s;const o=gi(r);t[o]=this.createHttpProvider(o,(s=this.namespace.rpcMap)==null?void 0:s[r])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,r=this.httpProviders[t];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return r}setHttpProvider(t,r){const s=this.createHttpProvider(t,r);s&&(this.httpProviders[t]=s)}createHttpProvider(t,r){const s=r||Zr(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new qr(new Xr(s,Te("disableProviderPing")))}}class Tx{constructor(t){this.name="cosmos",this.namespace=t.namespace,this.events=Te("events"),this.client=Te("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(t,r),this.chainId=t,this.events.emit(Lr.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(r=>{var s;const o=gi(r);t[o]=this.createHttpProvider(o,(s=this.namespace.rpcMap)==null?void 0:s[r])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,r=this.httpProviders[t];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return r}setHttpProvider(t,r){const s=this.createHttpProvider(t,r);s&&(this.httpProviders[t]=s)}createHttpProvider(t,r){const s=r||Zr(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new qr(new Xr(s,Te("disableProviderPing")))}}class Nx{constructor(t){this.name="cip34",this.namespace=t.namespace,this.events=Te("events"),this.client=Te("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(t,r),this.chainId=t,this.events.emit(Lr.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(r=>{const s=this.getCardanoRPCUrl(r),o=gi(r);t[o]=this.createHttpProvider(o,s)}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,r=this.httpProviders[t];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return r}getCardanoRPCUrl(t){const r=this.namespace.rpcMap;if(r)return r[t]}setHttpProvider(t,r){const s=this.createHttpProvider(t,r);s&&(this.httpProviders[t]=s)}createHttpProvider(t,r){const s=r||this.getCardanoRPCUrl(t);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new qr(new Xr(s,Te("disableProviderPing")))}}class Dx{constructor(t){this.name="elrond",this.namespace=t.namespace,this.events=Te("events"),this.client=Te("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(t,r),this.chainId=t,this.events.emit(Lr.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(r=>{var s;const o=gi(r);t[o]=this.createHttpProvider(o,(s=this.namespace.rpcMap)==null?void 0:s[r])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,r=this.httpProviders[t];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return r}setHttpProvider(t,r){const s=this.createHttpProvider(t,r);s&&(this.httpProviders[t]=s)}createHttpProvider(t,r){const s=r||Zr(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new qr(new Xr(s,Te("disableProviderPing")))}}class jx{constructor(t){this.name="multiversx",this.namespace=t.namespace,this.events=Te("events"),this.client=Te("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(t,r),this.chainId=t,this.events.emit(Lr.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(r=>{var s;const o=gi(r);t[o]=this.createHttpProvider(o,(s=this.namespace.rpcMap)==null?void 0:s[r])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,r=this.httpProviders[t];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return r}setHttpProvider(t,r){const s=this.createHttpProvider(t,r);s&&(this.httpProviders[t]=s)}createHttpProvider(t,r){const s=r||Zr(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new qr(new Xr(s,Te("disableProviderPing")))}}class qx{constructor(t){this.name="near",this.namespace=t.namespace,this.events=Te("events"),this.client=Te("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,r){if(this.chainId=t,!this.httpProviders[t]){const s=r||Zr(`${this.name}:${t}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);this.setHttpProvider(t,s)}this.events.emit(Lr.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const t=this.namespace.accounts;return t?t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(r=>{var s;t[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[r])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,r=this.httpProviders[t];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return r}setHttpProvider(t,r){const s=this.createHttpProvider(t,r);s&&(this.httpProviders[t]=s)}createHttpProvider(t,r){const s=r||Zr(t,this.namespace);return typeof s>"u"?void 0:new qr(new Xr(s,Te("disableProviderPing")))}}var Lx=Object.defineProperty,Mx=Object.defineProperties,zx=Object.getOwnPropertyDescriptors,ml=Object.getOwnPropertySymbols,Ux=Object.prototype.hasOwnProperty,kx=Object.prototype.propertyIsEnumerable,wl=(a,t,r)=>t in a?Lx(a,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):a[t]=r,wn=(a,t)=>{for(var r in t||(t={}))Ux.call(t,r)&&wl(a,r,t[r]);if(ml)for(var r of ml(t))kx.call(t,r)&&wl(a,r,t[r]);return a},ca=(a,t)=>Mx(a,zx(t));class La{constructor(t){this.events=new Oa,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=t,this.logger=typeof(t==null?void 0:t.logger)<"u"&&typeof(t==null?void 0:t.logger)!="string"?t.logger:Cn($n({level:(t==null?void 0:t.logger)||pl})),this.disableProviderPing=(t==null?void 0:t.disableProviderPing)||!1}static async init(t){const r=new La(t);return await r.initialize(),r}async request(t,r){const[s,o]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:wn({},t),chainId:`${s}:${o}`,topic:this.session.topic})}sendAsync(t,r,s){const o=new Date().getTime();this.request(t,s).then(u=>r(null,Tn(o,u))).catch(u=>r(u,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}),await this.requestAccounts()}async disconnect(){var t;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(t=this.session)==null?void 0:t.topic,reason:St("USER_DISCONNECTED")}),await this.cleanup()}async connect(t){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(t),await this.cleanupPendingPairings(),!t.skipPairing)return await this.pair(t.pairingTopic)}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}removeListener(t,r){this.events.removeListener(t,r)}off(t,r){this.events.off(t,r)}get isWalletConnect(){return!0}async pair(t){this.shouldAbortPairingAttempt=!1;let r=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(r>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:s,approval:o}=await this.client.connect({pairingTopic:t,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});s&&(this.uri=s,this.events.emit("display_uri",s)),await o().then(u=>{this.session=u,this.namespaces||(this.namespaces=Rx(u.namespaces),this.persist("namespaces",this.namespaces))}).catch(u=>{if(u.message!==df)throw u;r++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(t,r){try{if(!this.session)return;const[s,o]=this.validateChain(t);this.getProvider(s).setDefaultChain(o,r)}catch(s){if(!/Please call connect/.test(s.message))throw s}}async cleanupPendingPairings(t={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(zi(r)){for(const s of r)t.deletePairings?this.client.core.expirer.set(s.topic,0):await this.client.core.relayer.subscriber.unsubscribe(s.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const t=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[t]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await ox.init({logger:this.providerOpts.logger||pl,relayUrl:this.providerOpts.relayUrl||gx,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name}),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 t=[...new Set(Object.keys(this.session.namespaces).map(r=>ls(r)))];aa("client",this.client),aa("events",this.events),aa("disableProviderPing",this.disableProviderPing),t.forEach(r=>{if(!this.session)return;const s=Px(r,this.session),o=yf(s),u=Sx(this.namespaces,this.optionalNamespaces),f=ca(wn({},u[r]),{accounts:s,chains:o});switch(r){case"eip155":this.rpcProviders[r]=new Cx({namespace:f});break;case"solana":this.rpcProviders[r]=new $x({namespace:f});break;case"cosmos":this.rpcProviders[r]=new Tx({namespace:f});break;case"polkadot":this.rpcProviders[r]=new Ax({namespace:f});break;case"cip34":this.rpcProviders[r]=new Nx({namespace:f});break;case"elrond":this.rpcProviders[r]=new Dx({namespace:f});break;case"multiversx":this.rpcProviders[r]=new jx({namespace:f});break;case"near":this.rpcProviders[r]=new qx({namespace:f});break}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",t=>{this.events.emit("session_ping",t)}),this.client.on("session_event",t=>{const{params:r}=t,{event:s}=r;if(s.name==="accountsChanged"){const o=s.data;o&&zi(o)&&this.events.emit("accountsChanged",o.map(Ox))}else if(s.name==="chainChanged"){const o=r.chainId,u=r.event.data,f=ls(o),y=oa(o)!==oa(u)?`${f}:${oa(u)}`:o;this.onChainChanged(y)}else this.events.emit(s.name,s.data);this.events.emit("session_event",t)}),this.client.on("session_update",({topic:t,params:r})=>{var s;const{namespaces:o}=r,u=(s=this.client)==null?void 0:s.session.get(t);this.session=ca(wn({},u),{namespaces:o}),this.onSessionUpdate(),this.events.emit("session_update",{topic:t,params:r})}),this.client.on("session_delete",async t=>{await this.cleanup(),this.events.emit("session_delete",t),this.events.emit("disconnect",ca(wn({},St("USER_DISCONNECTED")),{data:t.topic}))}),this.on(Lr.DEFAULT_CHAIN_CHANGED,t=>{this.onChainChanged(t,!0)})}getProvider(t){if(!this.rpcProviders[t])throw new Error(`Provider not found: ${t}`);return this.rpcProviders[t]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(t=>{var r;this.getProvider(t).updateNamespace((r=this.session)==null?void 0:r.namespaces[t])})}setNamespaces(t){const{namespaces:r,optionalNamespaces:s,sessionProperties:o}=t;r&&Object.keys(r).length&&(this.namespaces=r),s&&Object.keys(s).length&&(this.optionalNamespaces=s),this.sessionProperties=o,this.persist("namespaces",r),this.persist("optionalNamespaces",s)}validateChain(t){const[r,s]=(t==null?void 0:t.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,s];if(r&&!Object.keys(this.namespaces||{}).map(f=>ls(f)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&s)return[r,s];const o=ls(Object.keys(this.namespaces)[0]),u=this.rpcProviders[o].getDefaultChain();return[o,u]}async requestAccounts(){const[t]=this.validateChain();return await this.getProvider(t).requestAccounts()}onChainChanged(t,r=!1){var s;if(!this.namespaces)return;const[o,u]=this.validateChain(t);r||this.getProvider(o).setDefaultChain(u),((s=this.namespaces[o])!=null?s:this.namespaces[`${o}:${u}`]).defaultChain=u,this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",u)}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(t,r){this.client.core.storage.setItem(`${dl}/${t}`,r)}async getFromStore(t){return await this.client.core.storage.getItem(`${dl}/${t}`)}}const Hx=La,Kx="wc",Vx="ethereum_provider",Bx=`${Kx}@2:${Vx}:`,Fx="https://rpc.walletconnect.com/v1/",Pa=["eth_sendTransaction","personal_sign"],Gx=["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"],Sa=["chainChanged","accountsChanged"],Wx=["chainChanged","accountsChanged","message","disconnect","connect"];var Jx=Object.defineProperty,Qx=Object.defineProperties,Yx=Object.getOwnPropertyDescriptors,bl=Object.getOwnPropertySymbols,Zx=Object.prototype.hasOwnProperty,Xx=Object.prototype.propertyIsEnumerable,_l=(a,t,r)=>t in a?Jx(a,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):a[t]=r,ps=(a,t)=>{for(var r in t||(t={}))Zx.call(t,r)&&_l(a,r,t[r]);if(bl)for(var r of bl(t))Xx.call(t,r)&&_l(a,r,t[r]);return a},El=(a,t)=>Qx(a,Yx(t));function Pn(a){return Number(a[0].split(":")[1])}function ua(a){return`0x${a.toString(16)}`}function eP(a){const{chains:t,optionalChains:r,methods:s,optionalMethods:o,events:u,optionalEvents:f,rpcMap:y}=a;if(!zi(t))throw new Error("Invalid chains");const v={chains:t,methods:s||Pa,events:u||Sa,rpcMap:ps({},t.length?{[Pn(t)]:y[Pn(t)]}:{})},p=u==null?void 0:u.filter($=>!Sa.includes($)),w=s==null?void 0:s.filter($=>!Pa.includes($));if(!r&&!f&&!o&&!(p!=null&&p.length)&&!(w!=null&&w.length))return{required:t.length?v:void 0};const I=(p==null?void 0:p.length)&&(w==null?void 0:w.length)||!r,R={chains:[...new Set(I?v.chains.concat(r||[]):r)],methods:[...new Set(v.methods.concat(o!=null&&o.length?o:Gx))],events:[...new Set(v.events.concat(f!=null&&f.length?f:Wx))],rpcMap:y};return{required:t.length?v:void 0,optional:r.length?R:void 0}}class Ma{constructor(){this.events=new ar.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=Bx,this.on=(t,r)=>(this.events.on(t,r),this),this.once=(t,r)=>(this.events.once(t,r),this),this.removeListener=(t,r)=>(this.events.removeListener(t,r),this),this.off=(t,r)=>(this.events.off(t,r),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){const r=new Ma;return await r.initialize(t),r}async request(t){return await this.signer.request(t,this.formatChainId(this.chainId))}sendAsync(t,r){this.signer.sendAsync(t,r,this.formatChainId(this.chainId))}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(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:r,optional:s}=eP(this.rpc);try{const o=await new Promise(async(f,y)=>{var v;this.rpc.showQrModal&&((v=this.modal)==null||v.subscribeModal(p=>{!p.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),y(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(El(ps({namespaces:ps({},r&&{[this.namespace]:r})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:t==null?void 0:t.pairingTopic})).then(p=>{f(p)}).catch(p=>{y(new Error(p.message))})});if(!o)return;const u=Ew(o.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:u),this.setAccounts(u),this.events.emit("connect",{chainId:ua(this.chainId)})}catch(o){throw this.signer.logger.error(o),o}finally{this.modal&&this.modal.closeModal()}}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",t=>{const{params:r}=t,{event:s}=r;s.name==="accountsChanged"?(this.accounts=this.parseAccounts(s.data),this.events.emit("accountsChanged",this.accounts)):s.name==="chainChanged"?this.setChainId(this.formatChainId(s.data)):this.events.emit(s.name,s.data),this.events.emit("session_event",t)}),this.signer.on("chainChanged",t=>{const r=parseInt(t);this.chainId=r,this.events.emit("chainChanged",ua(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",El(ps({},St("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{var r,s;this.rpc.showQrModal&&((r=this.modal)==null||r.closeModal(),(s=this.modal)==null||s.openModal({uri:t})),this.events.emit("display_uri",t)})}switchEthereumChain(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const r=t.filter(s=>this.isCompatibleChainId(s)).map(s=>this.parseChainId(s));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",ua(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const r=this.parseChainId(t);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(t){const[r,s,o]=t.split(":");return{chainId:`${r}:${s}`,address:o}}setAccounts(t){this.accounts=t.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var r,s;const o=(r=t==null?void 0:t.chains)!=null?r:[],u=(s=t==null?void 0:t.optionalChains)!=null?s:[],f=o.concat(u);if(!f.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const y=o.length?(t==null?void 0:t.methods)||Pa:[],v=o.length?(t==null?void 0:t.events)||Sa:[],p=(t==null?void 0:t.optionalMethods)||[],w=(t==null?void 0:t.optionalEvents)||[],I=(t==null?void 0:t.rpcMap)||this.buildRpcMap(f,t.projectId),R=(t==null?void 0:t.qrModalOptions)||void 0;return{chains:o==null?void 0:o.map($=>this.formatChainId($)),optionalChains:u.map($=>this.formatChainId($)),methods:y,events:v,optionalMethods:p,optionalEvents:w,rpcMap:I,showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:R,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,r){const s={};return t.forEach(o=>{s[o]=this.getRpcUrl(o,r)}),s}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=this.rpc.chains.length?Pn(this.rpc.chains):Pn(this.rpc.optionalChains),this.signer=await Hx.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing,relayUrl:t.relayUrl,storageOptions:t.storageOptions}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const{WalletConnectModal:s}=await j0(()=>import("./index-CsgMMSKv.js").then(o=>o.i),__vite__mapDeps([0,1,2,3,4]));r=s}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(r)try{this.modal=new r(ps({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:r,optionalChains:s,rpcMap:o}=t;r&&zi(r)&&(this.rpc.chains=r.map(u=>this.formatChainId(u)),r.forEach(u=>{this.rpc.rpcMap[u]=(o==null?void 0:o[u])||this.getRpcUrl(u)})),s&&zi(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s==null?void 0:s.map(u=>this.formatChainId(u)),s.forEach(u=>{this.rpc.rpcMap[u]=(o==null?void 0:o[u])||this.getRpcUrl(u)}))}getRpcUrl(t,r){var s;return((s=this.rpc.rpcMap)==null?void 0:s[t])||`${Fx}?chainId=eip155:${t}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${t}`]?this.session.namespaces[`${this.namespace}:${t}`]:this.session.namespaces[this.namespace];this.setChainIds(t?[this.formatChainId(t)]:r==null?void 0:r.accounts),this.setAccounts(r==null?void 0:r.accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(r=>this.parseAccount(r))}}const PP=Ma;export{PP as EthereumProvider,Wx as OPTIONAL_EVENTS,Gx as OPTIONAL_METHODS,Sa as REQUIRED_EVENTS,Pa as REQUIRED_METHODS,Ma as default};