@walletconnect/ethereum-provider 2.10.1-665f0a23 → 2.10.1-c46eedfa

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -69,7 +69,7 @@
69
69
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
70
70
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
71
71
  PERFORMANCE OF THIS SOFTWARE.
72
- ***************************************************************************** */var ah=function(t,e){return ah=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},ah(t,e)};function p_(t,e){ah(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var ch=function(){return ch=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},ch.apply(this,arguments)};function g_(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function m_(t,e,r,n){var i=arguments.length,o=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,r,n);else for(var l=t.length-1;l>=0;l--)(c=t[l])&&(o=(i<3?c(o):i>3?c(e,r,o):c(e,r))||o);return i>3&&o&&Object.defineProperty(e,r,o),o}function v_(t,e){return function(r,n){e(r,n,t)}}function w_(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function y_(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function l(w){try{f(n.next(w))}catch(E){c(E)}}function h(w){try{f(n.throw(w))}catch(E){c(E)}}function f(w){w.done?o(w.value):i(w.value).then(l,h)}f((n=n.apply(t,e||[])).next())})}function b_(t,e){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,c;return c={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(c[Symbol.iterator]=function(){return this}),c;function l(f){return function(w){return h([f,w])}}function h(f){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(o=f[0]&2?i.return:f[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,f[1])).done)return o;switch(i=0,o&&(f=[f[0]&2,o.value]),f[0]){case 0:case 1:o=f;break;case 4:return r.label++,{value:f[1],done:!1};case 5:r.label++,i=f[1],f=[0];continue;case 7:f=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(f[0]===6||f[0]===2)){r=0;continue}if(f[0]===3&&(!o||f[1]>o[0]&&f[1]<o[3])){r.label=f[1];break}if(f[0]===6&&r.label<o[1]){r.label=o[1],o=f;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(f);break}o[2]&&r.ops.pop(),r.trys.pop();continue}f=e.call(t,r)}catch(w){f=[6,w],i=0}finally{n=o=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}}function __(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function E_(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function lh(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Dp(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],c;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(l){c={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(c)throw c.error}}return o}function x_(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Dp(arguments[e]));return t}function C_(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var o=arguments[e],c=0,l=o.length;c<l;c++,i++)n[i]=o[c];return n}function Ko(t){return this instanceof Ko?(this.v=t,this):new Ko(t)}function I_(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,o=[];return i={},c("next"),c("throw"),c("return"),i[Symbol.asyncIterator]=function(){return this},i;function c(_){n[_]&&(i[_]=function(S){return new Promise(function(P,j){o.push([_,S,P,j])>1||l(_,S)})})}function l(_,S){try{h(n[_](S))}catch(P){E(o[0][3],P)}}function h(_){_.value instanceof Ko?Promise.resolve(_.value.v).then(f,w):E(o[0][2],_)}function f(_){l("next",_)}function w(_){l("throw",_)}function E(_,S){_(S),o.shift(),o.length&&l(o[0][0],o[0][1])}}function S_(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,o){e[i]=t[i]?function(c){return(r=!r)?{value:Ko(t[i](c)),done:i==="return"}:o?o(c):c}:o}}function O_(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof lh=="function"?lh(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(o){r[o]=t[o]&&function(c){return new Promise(function(l,h){c=t[o](c),i(l,h,c.done,c.value)})}}function i(o,c,l,h){Promise.resolve(h).then(function(f){o({value:f,done:l})},c)}}function A_(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function D_(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function $_(t){return t&&t.__esModule?t:{default:t}}function P_(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function T_(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var R_=Object.freeze({__proto__:null,__extends:p_,get __assign(){return ch},__rest:g_,__decorate:m_,__param:v_,__metadata:w_,__awaiter:y_,__generator:b_,__createBinding:__,__exportStar:E_,__values:lh,__read:Dp,__spread:x_,__spreadArrays:C_,__await:Ko,__asyncGenerator:I_,__asyncDelegator:S_,__asyncValues:O_,__makeTemplateObject:A_,__importStar:D_,__importDefault:$_,__classPrivateFieldGet:P_,__classPrivateFieldSet:T_}),N_=Bi(R_),zn={},$p;function L_(){if($p)return zn;$p=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.isBrowserCryptoAvailable=zn.getSubtleCrypto=zn.getBrowerCrypto=void 0;function t(){return dr?.crypto||dr?.msCrypto||{}}zn.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}zn.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return zn.isBrowserCryptoAvailable=r,zn}var qn={},Pp;function M_(){if(Pp)return qn;Pp=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.isBrowser=qn.isNode=qn.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}qn.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}qn.isNode=e;function r(){return!t()&&!e()}return qn.isBrowser=r,qn}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=N_;e.__exportStar(L_(),t),e.__exportStar(M_(),t)})(Ap);function uh(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Tp(t=6){return BigInt(uh(t))}function Ls(t,e,r){return{id:r||uh(),jsonrpc:"2.0",method:t,params:e}}function hh(t,e){return{id:t,jsonrpc:"2.0",result:e}}function hc(t,e,r){return{id:t,jsonrpc:"2.0",error:U_(e,r)}}function U_(t,e){return typeof t>"u"?Sp(Cp):(typeof t=="string"&&(t=Object.assign(Object.assign({},Sp(oh)),{message:t})),typeof e<"u"&&(t.data=e),f_(t.code)&&(t=d_(t.code)),t)}class j_{}class F_ extends j_{constructor(){super()}}class B_ extends F_{constructor(e){super()}}const k_="^https?:",H_="^wss?:";function W_(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Rp(t,e){const r=W_(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Np(t){return Rp(t,k_)}function Lp(t){return Rp(t,H_)}function z_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Mp(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function fh(t){return Mp(t)&&"method"in t}function fc(t){return Mp(t)&&(Vn(t)||xn(t))}function Vn(t){return"result"in t}function xn(t){return"error"in t}class Kn extends B_{constructor(e){super(e),this.events=new yr.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Ls(e.method,e.params||[],e.id||Tp().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(o){i(o)}this.events.on(`${e.id}`,o=>{xn(o)?i(o.error):n(o.result)});try{await this.connection.send(e,r)}catch(o){i(o)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),fc(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const q_=()=>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"),V_=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Up=t=>t.split("?")[0],jp=10,K_=q_();class G_{constructor(e){if(this.url=e,this.events=new yr.exports.EventEmitter,this.registering=!1,!Lp(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e,r){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(qo(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!Lp(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",o=>{this.resetMaxListeners(),i(o)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=Ap.isReactNative()?void 0:{rejectUnauthorized:!z_(e)},o=new K_(e,[],i);V_()?o.onerror=c=>{const l=c;n(this.emitError(l.error))}:o.on("error",c=>{n(this.emitError(c))}),o.onopen=()=>{this.onOpen(o),r(o)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ih(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=hc(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return Op(e,Up(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>jp&&this.events.setMaxListeners(jp)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Up(this.url)}`));return this.events.emit("register_error",r),r}}var dh={exports:{}};(function(t,e){var r=200,n="__lodash_hash_undefined__",i=1,o=2,c=9007199254740991,l="[object Arguments]",h="[object Array]",f="[object AsyncFunction]",w="[object Boolean]",E="[object Date]",_="[object Error]",S="[object Function]",P="[object GeneratorFunction]",j="[object Map]",H="[object Number]",Z="[object Null]",N="[object Object]",L="[object Promise]",$="[object Proxy]",T="[object RegExp]",I="[object Set]",d="[object String]",x="[object Symbol]",J="[object Undefined]",W="[object WeakMap]",ee="[object ArrayBuffer]",de="[object DataView]",me="[object Float32Array]",O="[object Float64Array]",U="[object Int8Array]",ce="[object Int16Array]",le="[object Int32Array]",re="[object Uint8Array]",ne="[object Uint8ClampedArray]",ae="[object Uint16Array]",ie="[object Uint32Array]",Ae=/[\\^$.*+?()[\]{}|]/g,ge=/^\[object .+?Constructor\]$/,Be=/^(?:0|[1-9]\d*)$/,ye={};ye[me]=ye[O]=ye[U]=ye[ce]=ye[le]=ye[re]=ye[ne]=ye[ae]=ye[ie]=!0,ye[l]=ye[h]=ye[ee]=ye[w]=ye[de]=ye[E]=ye[_]=ye[S]=ye[j]=ye[H]=ye[N]=ye[T]=ye[I]=ye[d]=ye[W]=!1;var Me=typeof dr=="object"&&dr&&dr.Object===Object&&dr,Q=typeof self=="object"&&self&&self.Object===Object&&self,Y=Me||Q||Function("return this")(),z=e&&!e.nodeType&&e,v=z&&!0&&t&&!t.nodeType&&t,F=v&&v.exports===z,ve=F&&Me.process,we=function(){try{return ve&&ve.binding&&ve.binding("util")}catch{}}(),Ue=we&&we.isTypedArray;function nt(R,q){for(var fe=-1,Ce=R==null?0:R.length,It=0,Qe=[];++fe<Ce;){var Tt=R[fe];q(Tt,fe,R)&&(Qe[It++]=Tt)}return Qe}function at(R,q){for(var fe=-1,Ce=q.length,It=R.length;++fe<Ce;)R[It+fe]=q[fe];return R}function Ge(R,q){for(var fe=-1,Ce=R==null?0:R.length;++fe<Ce;)if(q(R[fe],fe,R))return!0;return!1}function Dt(R,q){for(var fe=-1,Ce=Array(R);++fe<R;)Ce[fe]=q(fe);return Ce}function $t(R){return function(q){return R(q)}}function Je(R,q){return R.has(q)}function He(R,q){return R?.[q]}function ke(R){var q=-1,fe=Array(R.size);return R.forEach(function(Ce,It){fe[++q]=[It,Ce]}),fe}function Ke(R,q){return function(fe){return R(q(fe))}}function rt(R){var q=-1,fe=Array(R.size);return R.forEach(function(Ce){fe[++q]=Ce}),fe}var je=Array.prototype,Ze=Function.prototype,b=Object.prototype,p=Y["__core-js_shared__"],m=Ze.toString,D=b.hasOwnProperty,B=function(){var R=/[^.]+$/.exec(p&&p.keys&&p.keys.IE_PROTO||"");return R?"Symbol(src)_1."+R:""}(),K=b.toString,X=RegExp("^"+m.call(D).replace(Ae,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ee=F?Y.Buffer:void 0,Re=Y.Symbol,st=Y.Uint8Array,ht=b.propertyIsEnumerable,lt=je.splice,Ur=Re?Re.toStringTag:void 0,ti=Object.getOwnPropertySymbols,Di=Ee?Ee.isBuffer:void 0,hs=Ke(Object.keys,Object),Wt=tn(Y,"DataView"),Mt=tn(Y,"Map"),zt=tn(Y,"Promise"),qt=tn(Y,"Set"),Bt=tn(Y,"WeakMap"),Ut=tn(Object,"create"),nr=ni(Wt),ir=ni(Mt),Vt=ni(zt),sr=ni(qt),Kt=ni(Bt),Jt=Re?Re.prototype:void 0,Gt=Jt?Jt.valueOf:void 0;function Pt(R){var q=-1,fe=R==null?0:R.length;for(this.clear();++q<fe;){var Ce=R[q];this.set(Ce[0],Ce[1])}}function or(){this.__data__=Ut?Ut(null):{},this.size=0}function ar(R){var q=this.has(R)&&delete this.__data__[R];return this.size-=q?1:0,q}function Gf(R){var q=this.__data__;if(Ut){var fe=q[R];return fe===n?void 0:fe}return D.call(q,R)?q[R]:void 0}function Zf(R){var q=this.__data__;return Ut?q[R]!==void 0:D.call(q,R)}function Yf(R,q){var fe=this.__data__;return this.size+=this.has(R)?0:1,fe[R]=Ut&&q===void 0?n:q,this}Pt.prototype.clear=or,Pt.prototype.delete=ar,Pt.prototype.get=Gf,Pt.prototype.has=Zf,Pt.prototype.set=Yf;function fn(R){var q=-1,fe=R==null?0:R.length;for(this.clear();++q<fe;){var Ce=R[q];this.set(Ce[0],Ce[1])}}function Jf(){this.__data__=[],this.size=0}function Qf(R){var q=this.__data__,fe=fs(q,R);if(fe<0)return!1;var Ce=q.length-1;return fe==Ce?q.pop():lt.call(q,fe,1),--this.size,!0}function Xf(R){var q=this.__data__,fe=fs(q,R);return fe<0?void 0:q[fe][1]}function e0(R){return fs(this.__data__,R)>-1}function t0(R,q){var fe=this.__data__,Ce=fs(fe,R);return Ce<0?(++this.size,fe.push([R,q])):fe[Ce][1]=q,this}fn.prototype.clear=Jf,fn.prototype.delete=Qf,fn.prototype.get=Xf,fn.prototype.has=e0,fn.prototype.set=t0;function ri(R){var q=-1,fe=R==null?0:R.length;for(this.clear();++q<fe;){var Ce=R[q];this.set(Ce[0],Ce[1])}}function no(){this.size=0,this.__data__={hash:new Pt,map:new(Mt||fn),string:new Pt}}function r0(R){var q=$i(this,R).delete(R);return this.size-=q?1:0,q}function io(R){return $i(this,R).get(R)}function n0(R){return $i(this,R).has(R)}function i0(R,q){var fe=$i(this,R),Ce=fe.size;return fe.set(R,q),this.size+=fe.size==Ce?0:1,this}ri.prototype.clear=no,ri.prototype.delete=r0,ri.prototype.get=io,ri.prototype.has=n0,ri.prototype.set=i0;function so(R){var q=-1,fe=R==null?0:R.length;for(this.__data__=new ri;++q<fe;)this.add(R[q])}function ol(R){return this.__data__.set(R,n),this}function al(R){return this.__data__.has(R)}so.prototype.add=so.prototype.push=ol,so.prototype.has=al;function Cn(R){var q=this.__data__=new fn(R);this.size=q.size}function s0(){this.__data__=new fn,this.size=0}function o0(R){var q=this.__data__,fe=q.delete(R);return this.size=q.size,fe}function a0(R){return this.__data__.get(R)}function c0(R){return this.__data__.has(R)}function cl(R,q){var fe=this.__data__;if(fe instanceof fn){var Ce=fe.__data__;if(!Mt||Ce.length<r-1)return Ce.push([R,q]),this.size=++fe.size,this;fe=this.__data__=new ri(Ce)}return fe.set(R,q),this.size=fe.size,this}Cn.prototype.clear=s0,Cn.prototype.delete=o0,Cn.prototype.get=a0,Cn.prototype.has=c0,Cn.prototype.set=cl;function ll(R,q){var fe=co(R),Ce=!fe&&_l(R),It=!fe&&!Ce&&Da(R),Qe=!fe&&!Ce&&!It&&Cl(R),Tt=fe||Ce||It||Qe,cr=Tt?Dt(R.length,String):[],mt=cr.length;for(var St in R)(q||D.call(R,St))&&!(Tt&&(St=="length"||It&&(St=="offset"||St=="parent")||Qe&&(St=="buffer"||St=="byteLength"||St=="byteOffset")||ml(St,mt)))&&cr.push(St);return cr}function fs(R,q){for(var fe=R.length;fe--;)if(bl(R[fe][0],q))return fe;return-1}function Oa(R,q,fe){var Ce=q(R);return co(R)?Ce:at(Ce,fe(R))}function ds(R){return R==null?R===void 0?J:Z:Ur&&Ur in Object(R)?pl(R):h0(R)}function Aa(R){return gs(R)&&ds(R)==l}function ps(R,q,fe,Ce,It){return R===q?!0:R==null||q==null||!gs(R)&&!gs(q)?R!==R&&q!==q:ul(R,q,fe,Ce,ps,It)}function ul(R,q,fe,Ce,It,Qe){var Tt=co(R),cr=co(q),mt=Tt?h:Fn(R),St=cr?h:Fn(q);mt=mt==l?N:mt,St=St==l?N:St;var Qt=mt==N,Vr=St==N,lr=mt==St;if(lr&&Da(R)){if(!Da(q))return!1;Tt=!0,Qt=!1}if(lr&&!Qt)return Qe||(Qe=new Cn),Tt||Cl(R)?oo(R,q,fe,Ce,It,Qe):u0(R,q,mt,fe,Ce,It,Qe);if(!(fe&i)){var Rt=Qt&&D.call(R,"__wrapped__"),jr=Vr&&D.call(q,"__wrapped__");if(Rt||jr){var In=Rt?R.value():R,dn=jr?q.value():q;return Qe||(Qe=new Cn),It(In,dn,fe,Ce,Qe)}}return lr?(Qe||(Qe=new Cn),dl(R,q,fe,Ce,It,Qe)):!1}function l0(R){if(!xl(R)||wl(R))return!1;var q=lo(R)?X:ge;return q.test(ni(R))}function hl(R){return gs(R)&&El(R.length)&&!!ye[ds(R)]}function fl(R){if(!yl(R))return hs(R);var q=[];for(var fe in Object(R))D.call(R,fe)&&fe!="constructor"&&q.push(fe);return q}function oo(R,q,fe,Ce,It,Qe){var Tt=fe&i,cr=R.length,mt=q.length;if(cr!=mt&&!(Tt&&mt>cr))return!1;var St=Qe.get(R);if(St&&Qe.get(q))return St==q;var Qt=-1,Vr=!0,lr=fe&o?new so:void 0;for(Qe.set(R,q),Qe.set(q,R);++Qt<cr;){var Rt=R[Qt],jr=q[Qt];if(Ce)var In=Tt?Ce(jr,Rt,Qt,q,R,Qe):Ce(Rt,jr,Qt,R,q,Qe);if(In!==void 0){if(In)continue;Vr=!1;break}if(lr){if(!Ge(q,function(dn,Bn){if(!Je(lr,Bn)&&(Rt===dn||It(Rt,dn,fe,Ce,Qe)))return lr.push(Bn)})){Vr=!1;break}}else if(!(Rt===jr||It(Rt,jr,fe,Ce,Qe))){Vr=!1;break}}return Qe.delete(R),Qe.delete(q),Vr}function u0(R,q,fe,Ce,It,Qe,Tt){switch(fe){case de:if(R.byteLength!=q.byteLength||R.byteOffset!=q.byteOffset)return!1;R=R.buffer,q=q.buffer;case ee:return!(R.byteLength!=q.byteLength||!Qe(new st(R),new st(q)));case w:case E:case H:return bl(+R,+q);case _:return R.name==q.name&&R.message==q.message;case T:case d:return R==q+"";case j:var cr=ke;case I:var mt=Ce&i;if(cr||(cr=rt),R.size!=q.size&&!mt)return!1;var St=Tt.get(R);if(St)return St==q;Ce|=o,Tt.set(R,q);var Qt=oo(cr(R),cr(q),Ce,It,Qe,Tt);return Tt.delete(R),Qt;case x:if(Gt)return Gt.call(R)==Gt.call(q)}return!1}function dl(R,q,fe,Ce,It,Qe){var Tt=fe&i,cr=ao(R),mt=cr.length,St=ao(q),Qt=St.length;if(mt!=Qt&&!Tt)return!1;for(var Vr=mt;Vr--;){var lr=cr[Vr];if(!(Tt?lr in q:D.call(q,lr)))return!1}var Rt=Qe.get(R);if(Rt&&Qe.get(q))return Rt==q;var jr=!0;Qe.set(R,q),Qe.set(q,R);for(var In=Tt;++Vr<mt;){lr=cr[Vr];var dn=R[lr],Bn=q[lr];if(Ce)var $a=Tt?Ce(Bn,dn,lr,q,R,Qe):Ce(dn,Bn,lr,R,q,Qe);if(!($a===void 0?dn===Bn||It(dn,Bn,fe,Ce,Qe):$a)){jr=!1;break}In||(In=lr=="constructor")}if(jr&&!In){var ms=R.constructor,vr=q.constructor;ms!=vr&&"constructor"in R&&"constructor"in q&&!(typeof ms=="function"&&ms instanceof ms&&typeof vr=="function"&&vr instanceof vr)&&(jr=!1)}return Qe.delete(R),Qe.delete(q),jr}function ao(R){return Oa(R,p0,gl)}function $i(R,q){var fe=R.__data__;return vl(q)?fe[typeof q=="string"?"string":"hash"]:fe.map}function tn(R,q){var fe=He(R,q);return l0(fe)?fe:void 0}function pl(R){var q=D.call(R,Ur),fe=R[Ur];try{R[Ur]=void 0;var Ce=!0}catch{}var It=K.call(R);return Ce&&(q?R[Ur]=fe:delete R[Ur]),It}var gl=ti?function(R){return R==null?[]:(R=Object(R),nt(ti(R),function(q){return ht.call(R,q)}))}:Ct,Fn=ds;(Wt&&Fn(new Wt(new ArrayBuffer(1)))!=de||Mt&&Fn(new Mt)!=j||zt&&Fn(zt.resolve())!=L||qt&&Fn(new qt)!=I||Bt&&Fn(new Bt)!=W)&&(Fn=function(R){var q=ds(R),fe=q==N?R.constructor:void 0,Ce=fe?ni(fe):"";if(Ce)switch(Ce){case nr:return de;case ir:return j;case Vt:return L;case sr:return I;case Kt:return W}return q});function ml(R,q){return q=q??c,!!q&&(typeof R=="number"||Be.test(R))&&R>-1&&R%1==0&&R<q}function vl(R){var q=typeof R;return q=="string"||q=="number"||q=="symbol"||q=="boolean"?R!=="__proto__":R===null}function wl(R){return!!B&&B in R}function yl(R){var q=R&&R.constructor,fe=typeof q=="function"&&q.prototype||b;return R===fe}function h0(R){return K.call(R)}function ni(R){if(R!=null){try{return m.call(R)}catch{}try{return R+""}catch{}}return""}function bl(R,q){return R===q||R!==R&&q!==q}var _l=Aa(function(){return arguments}())?Aa:function(R){return gs(R)&&D.call(R,"callee")&&!ht.call(R,"callee")},co=Array.isArray;function f0(R){return R!=null&&El(R.length)&&!lo(R)}var Da=Di||xt;function d0(R,q){return ps(R,q)}function lo(R){if(!xl(R))return!1;var q=ds(R);return q==S||q==P||q==f||q==$}function El(R){return typeof R=="number"&&R>-1&&R%1==0&&R<=c}function xl(R){var q=typeof R;return R!=null&&(q=="object"||q=="function")}function gs(R){return R!=null&&typeof R=="object"}var Cl=Ue?$t(Ue):hl;function p0(R){return f0(R)?ll(R):fl(R)}function Ct(){return[]}function xt(){return!1}t.exports=d0})(dh,dh.exports);var Z_=dh.exports,Y_=Object.defineProperty,Fp=Object.getOwnPropertySymbols,J_=Object.prototype.hasOwnProperty,Q_=Object.prototype.propertyIsEnumerable,Bp=(t,e,r)=>e in t?Y_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rr=(t,e)=>{for(var r in e||(e={}))J_.call(e,r)&&Bp(t,r,e[r]);if(Fp)for(var r of Fp(e))Q_.call(e,r)&&Bp(t,r,e[r]);return t};function X_(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),c=o.charCodeAt(0);if(r[c]!==255)throw new TypeError(o+" is ambiguous");r[c]=i}var l=t.length,h=t.charAt(0),f=Math.log(l)/Math.log(256),w=Math.log(256)/Math.log(l);function E(P){if(P instanceof Uint8Array||(ArrayBuffer.isView(P)?P=new Uint8Array(P.buffer,P.byteOffset,P.byteLength):Array.isArray(P)&&(P=Uint8Array.from(P))),!(P instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(P.length===0)return"";for(var j=0,H=0,Z=0,N=P.length;Z!==N&&P[Z]===0;)Z++,j++;for(var L=(N-Z)*w+1>>>0,$=new Uint8Array(L);Z!==N;){for(var T=P[Z],I=0,d=L-1;(T!==0||I<H)&&d!==-1;d--,I++)T+=256*$[d]>>>0,$[d]=T%l>>>0,T=T/l>>>0;if(T!==0)throw new Error("Non-zero carry");H=I,Z++}for(var x=L-H;x!==L&&$[x]===0;)x++;for(var J=h.repeat(j);x<L;++x)J+=t.charAt($[x]);return J}function _(P){if(typeof P!="string")throw new TypeError("Expected String");if(P.length===0)return new Uint8Array;var j=0;if(P[j]!==" "){for(var H=0,Z=0;P[j]===h;)H++,j++;for(var N=(P.length-j)*f+1>>>0,L=new Uint8Array(N);P[j];){var $=r[P.charCodeAt(j)];if($===255)return;for(var T=0,I=N-1;($!==0||T<Z)&&I!==-1;I--,T++)$+=l*L[I]>>>0,L[I]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");Z=T,j++}if(P[j]!==" "){for(var d=N-Z;d!==N&&L[d]===0;)d++;for(var x=new Uint8Array(H+(N-d)),J=H;d!==N;)x[J++]=L[d++];return x}}}function S(P){var j=_(P);if(j)return j;throw new Error(`Non-${e} character`)}return{encode:E,decodeUnsafe:_,decode:S}}var e8=X_,t8=e8;const kp=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},r8=t=>new TextEncoder().encode(t),n8=t=>new TextDecoder().decode(t);class i8{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class s8{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Hp(this,e)}}class o8{constructor(e){this.decoders=e}or(e){return Hp(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Hp=(t,e)=>new o8(Rr(Rr({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class a8{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new i8(e,r,n),this.decoder=new s8(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const dc=({name:t,prefix:e,encode:r,decode:n})=>new a8(t,e,r,n),Go=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=t8(r,e);return dc({prefix:t,name:e,encode:n,decode:o=>kp(i(o))})},c8=(t,e,r,n)=>{const i={};for(let w=0;w<e.length;++w)i[e[w]]=w;let o=t.length;for(;t[o-1]==="=";)--o;const c=new Uint8Array(o*r/8|0);let l=0,h=0,f=0;for(let w=0;w<o;++w){const E=i[t[w]];if(E===void 0)throw new SyntaxError(`Non-${n} character`);h=h<<r|E,l+=r,l>=8&&(l-=8,c[f++]=255&h>>l)}if(l>=r||255&h<<8-l)throw new SyntaxError("Unexpected end of data");return c},l8=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let o="",c=0,l=0;for(let h=0;h<t.length;++h)for(l=l<<8|t[h],c+=8;c>r;)c-=r,o+=e[i&l>>c];if(c&&(o+=e[i&l<<r-c]),n)for(;o.length*r&7;)o+="=";return o},_r=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>dc({prefix:e,name:t,encode(i){return l8(i,n,r)},decode(i){return c8(i,n,r,t)}}),u8=dc({prefix:"\0",name:"identity",encode:t=>n8(t),decode:t=>r8(t)});var h8=Object.freeze({__proto__:null,identity:u8});const f8=_r({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var d8=Object.freeze({__proto__:null,base2:f8});const p8=_r({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var g8=Object.freeze({__proto__:null,base8:p8});const m8=Go({prefix:"9",name:"base10",alphabet:"0123456789"});var v8=Object.freeze({__proto__:null,base10:m8});const w8=_r({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),y8=_r({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var b8=Object.freeze({__proto__:null,base16:w8,base16upper:y8});const _8=_r({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),E8=_r({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),x8=_r({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),C8=_r({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),I8=_r({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),S8=_r({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),O8=_r({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),A8=_r({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),D8=_r({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var $8=Object.freeze({__proto__:null,base32:_8,base32upper:E8,base32pad:x8,base32padupper:C8,base32hex:I8,base32hexupper:S8,base32hexpad:O8,base32hexpadupper:A8,base32z:D8});const P8=Go({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),T8=Go({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var R8=Object.freeze({__proto__:null,base36:P8,base36upper:T8});const N8=Go({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),L8=Go({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var M8=Object.freeze({__proto__:null,base58btc:N8,base58flickr:L8});const U8=_r({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),j8=_r({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),F8=_r({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),B8=_r({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var k8=Object.freeze({__proto__:null,base64:U8,base64pad:j8,base64url:F8,base64urlpad:B8});const Wp=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),H8=Wp.reduce((t,e,r)=>(t[r]=e,t),[]),W8=Wp.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function z8(t){return t.reduce((e,r)=>(e+=H8[r],e),"")}function q8(t){const e=[];for(const r of t){const n=W8[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const V8=dc({prefix:"\u{1F680}",name:"base256emoji",encode:z8,decode:q8});var K8=Object.freeze({__proto__:null,base256emoji:V8}),G8=qp,zp=128,Z8=127,Y8=~Z8,J8=Math.pow(2,31);function qp(t,e,r){e=e||[],r=r||0;for(var n=r;t>=J8;)e[r++]=t&255|zp,t/=128;for(;t&Y8;)e[r++]=t&255|zp,t>>>=7;return e[r]=t|0,qp.bytes=r-n+1,e}var Q8=ph,X8=128,Vp=127;function ph(t,n){var r=0,n=n||0,i=0,o=n,c,l=t.length;do{if(o>=l)throw ph.bytes=0,new RangeError("Could not decode varint");c=t[o++],r+=i<28?(c&Vp)<<i:(c&Vp)*Math.pow(2,i),i+=7}while(c>=X8);return ph.bytes=o-n,r}var eE=Math.pow(2,7),tE=Math.pow(2,14),rE=Math.pow(2,21),nE=Math.pow(2,28),iE=Math.pow(2,35),sE=Math.pow(2,42),oE=Math.pow(2,49),aE=Math.pow(2,56),cE=Math.pow(2,63),lE=function(t){return t<eE?1:t<tE?2:t<rE?3:t<nE?4:t<iE?5:t<sE?6:t<oE?7:t<aE?8:t<cE?9:10},uE={encode:G8,decode:Q8,encodingLength:lE},Kp=uE;const Gp=(t,e,r=0)=>(Kp.encode(t,e,r),e),Zp=t=>Kp.encodingLength(t),gh=(t,e)=>{const r=e.byteLength,n=Zp(t),i=n+Zp(r),o=new Uint8Array(i+r);return Gp(t,o,0),Gp(r,o,n),o.set(e,i),new hE(t,r,e,o)};class hE{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Yp=({name:t,code:e,encode:r})=>new fE(t,e,r);class fE{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?gh(this.code,r):r.then(n=>gh(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Jp=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),dE=Yp({name:"sha2-256",code:18,encode:Jp("SHA-256")}),pE=Yp({name:"sha2-512",code:19,encode:Jp("SHA-512")});var gE=Object.freeze({__proto__:null,sha256:dE,sha512:pE});const Qp=0,mE="identity",Xp=kp;var vE=Object.freeze({__proto__:null,identity:{code:Qp,name:mE,encode:Xp,digest:t=>gh(Qp,Xp(t))}});new TextEncoder,new TextDecoder;const eg=Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr({},h8),d8),g8),v8),b8),$8),R8),M8),k8),K8);Rr(Rr({},gE),vE);function tg(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function wE(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?tg(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function rg(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const ng=rg("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),mh=rg("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=wE(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),yE=Rr({utf8:ng,"utf-8":ng,hex:eg.base16,latin1:mh,ascii:mh,binary:mh},eg);function bE(t,e="utf8"){const r=yE[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?tg(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}const ig="wc",_E=2,vh="core",gi=`${ig}@2:${vh}:`,EE={name:vh,logger:"error"},xE={database:":memory:"},CE="crypto",sg="client_ed25519_seed",IE=Te.ONE_DAY,SE="keychain",OE="0.3",AE="messages",DE="0.3",$E=Te.SIX_HOURS,PE="publisher",og="irn",TE="error",ag="wss://relay.walletconnect.com",cg="wss://relay.walletconnect.org",RE="relayer",Ir={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},NE="_subscription",Gn={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},LE=Te.ONE_SECOND,ME="2.10.1-665f0a23",UE=1e4,jE="0.3",FE="WALLETCONNECT_CLIENT_ID",Tn={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},BE="subscription",kE="0.3",HE=Te.FIVE_SECONDS*1e3,WE="pairing",zE="0.3",Zo={wc_pairingDelete:{req:{ttl:Te.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:Te.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:Te.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:Te.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:Te.ONE_DAY,prompt:!1,tag:0},res:{ttl:Te.ONE_DAY,prompt:!1,tag:0}}},Yo={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Rn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},qE="history",VE="0.3",KE="expirer",cn={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},GE="0.3",wh="verify-api",pc="https://verify.walletconnect.com",lg="https://verify.walletconnect.org";class ZE{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=SE,this.version=OE,this.initialized=!1,this.storagePrefix=gi,this.init=async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:o}=_e("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(o)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=pt.generateChildLogger(r,this.name)}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,U1(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?j1(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class YE{constructor(e,r,n){this.core=e,this.logger=r,this.name=CE,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();const i=await this.getClientSeed(),o=xp(i);return Ep(o.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const i=J5();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const o=await this.getClientSeed(),c=xp(o),l=Uu();return await o_(l,i,IE,c)},this.generateSharedKey=(i,o,c)=>{this.isInitialized();const l=this.getPrivateKey(i),h=Q5(l,o);return this.setSymKey(h,c)},this.setSymKey=async(i,o)=>{this.isInitialized();const c=o||X5(i);return await this.keychain.set(c,i),c},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,o,c)=>{this.isInitialized();const l=T1(c),h=qo(o);if(R1(l)){const _=l.senderPublicKey,S=l.receiverPublicKey;i=await this.generateSharedKey(_,S)}const f=this.getSymKey(i),{type:w,senderPublicKey:E}=l;return tb({type:w,symKey:f,message:h,senderPublicKey:E})},this.decode=async(i,o,c)=>{this.isInitialized();const l=ib(o,c);if(R1(l)){const h=l.receiverPublicKey,f=l.senderPublicKey;i=await this.generateSharedKey(h,f)}try{const h=this.getSymKey(i),f=rb({symKey:h,encoded:o});return ih(f)}catch(h){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(h)}},this.getPayloadType=i=>{const o=nc(i);return $o(o.type)},this.getPayloadSenderPublicKey=i=>{const o=nc(i);return o.senderPublicKey?Dr(o.senderPublicKey,$r):void 0},this.core=e,this.logger=pt.generateChildLogger(r,this.name),this.keychain=n||new ZE(this.core,this.logger)}get context(){return pt.getLoggerContext(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(sg)}catch{e=Uu(),await this.keychain.set(sg,e)}return bE(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class JE extends M4{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=AE,this.version=DE,this.initialized=!1,this.storagePrefix=gi,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();const o=Ds(i);let c=this.messages.get(n);return typeof c>"u"&&(c={}),typeof c[o]<"u"||(c[o]=i,this.messages.set(n,c),await this.persist()),o},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();const o=this.get(n),c=Ds(i);return typeof o[c]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=pt.generateChildLogger(e,this.name),this.core=r}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,U1(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?j1(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class QE extends U4{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new yr.exports.EventEmitter,this.name=PE,this.queue=new Map,this.publishTimeout=Te.toMiliseconds(Te.TEN_SECONDS),this.needsTransportRestart=!1,this.publish=async(n,i,o)=>{var c;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:o}});try{const l=o?.ttl||$E,h=Bu(o),f=o?.prompt||!1,w=o?.tag||0,E=o?.id||Tp().toString(),_={topic:n,message:i,opts:{ttl:l,relay:h,prompt:f,tag:w,id:E}},S=setTimeout(()=>this.queue.set(E,_),this.publishTimeout);try{await await No(this.rpcPublish(n,i,l,h,f,w,E),this.publishTimeout,"Failed to publish payload, please try again."),this.removeRequestFromQueue(E),this.relayer.events.emit(Ir.publish,_)}catch(P){if(this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0,(c=o?.internal)!=null&&c.throwOnFailedPublish)throw this.removeRequestFromQueue(E),P;return}finally{clearTimeout(S)}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:o}})}catch(l){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(l),l}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=pt.generateChildLogger(r,this.name),this.registerEventListeners()}get context(){return pt.getLoggerContext(this.logger)}rpcPublish(e,r,n,i,o,c,l){var h,f,w,E;const _={method:ic(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:o,tag:c},id:l};return Pr((h=_.params)==null?void 0:h.prompt)&&((f=_.params)==null||delete f.prompt),Pr((w=_.params)==null?void 0:w.tag)&&((E=_.params)==null||delete E.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:_}),this.relayer.request(_)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(Ns.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Ir.connection_stalled);return}this.checkQueue()}),this.relayer.on(Ir.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class XE{constructor(){this.map=new Map,this.set=(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(o=>o!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var e7=Object.defineProperty,t7=Object.defineProperties,r7=Object.getOwnPropertyDescriptors,ug=Object.getOwnPropertySymbols,n7=Object.prototype.hasOwnProperty,i7=Object.prototype.propertyIsEnumerable,hg=(t,e,r)=>e in t?e7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Jo=(t,e)=>{for(var r in e||(e={}))n7.call(e,r)&&hg(t,r,e[r]);if(ug)for(var r of ug(e))i7.call(e,r)&&hg(t,r,e[r]);return t},yh=(t,e)=>t7(t,r7(e));class s7 extends B4{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new XE,this.events=new yr.exports.EventEmitter,this.name=BE,this.version=kE,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=gi,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(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const o=Bu(i),c={topic:n,relay:o};this.pending.set(n,c);const l=await this.rpcSubscribe(n,o);return this.onSubscribe(l,c),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}}),l}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>this.topics.includes(n)?!0:await new Promise((i,o)=>{const c=new Te.Watch;c.start(this.pendingSubscriptionWatchLabel);const l=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(l),c.stop(this.pendingSubscriptionWatchLabel),i(!0)),c.elapsed(this.pendingSubscriptionWatchLabel)>=HE&&(clearInterval(l),c.stop(this.pendingSubscriptionWatchLabel),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=pt.generateChildLogger(r,this.name),this.clientId=""}get context(){return pt.getLoggerContext(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(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=Bu(n);await this.rpcUnsubscribe(e,r,i);const o=Yt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,o),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){const n={method:ic(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await No(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Ir.connection_stalled)}return Ds(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:ic(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await No(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(Ir.connection_stalled)}}rpcUnsubscribe(e,r,n){const i={method:ic(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,yh(Jo({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Jo({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r))}addSubscription(e,r){this.subscriptions.set(e,Jo({},r)),this.topicMap.set(r.topic,e),this.events.emit(Tn.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(Tn.deleted,yh(Jo({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Tn.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<e;r++){const n=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}}this.events.emit(Tn.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;const r=await this.rpcBatchSubscribe(e);Pn(r)&&this.onBatchSubscribe(r.map((n,i)=>yh(Jo({},e[i]),{id:n})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(Ns.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(Ir.connect,async()=>{await this.onConnect()}),this.relayer.on(Ir.disconnect,()=>{this.onDisconnect()}),this.events.on(Tn.created,async e=>{const r=Tn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(Tn.deleted,async e=>{const r=Tn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}}var o7=Object.defineProperty,fg=Object.getOwnPropertySymbols,a7=Object.prototype.hasOwnProperty,c7=Object.prototype.propertyIsEnumerable,dg=(t,e,r)=>e in t?o7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,l7=(t,e)=>{for(var r in e||(e={}))a7.call(e,r)&&dg(t,r,e[r]);if(fg)for(var r of fg(e))c7.call(e,r)&&dg(t,r,e[r]);return t};class u7 extends j4{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new yr.exports.EventEmitter,this.name=RE,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(n){throw this.logger.debug("Failed to Publish Request"),this.logger.error(n),n}},this.onPayloadHandler=r=>{this.onProviderPayload(r)},this.onConnectHandler=()=>{this.events.emit(Ir.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(Ir.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(Gn.payload,this.onPayloadHandler),this.provider.on(Gn.connect,this.onConnectHandler),this.provider.on(Gn.disconnect,this.onDisconnectHandler),this.provider.on(Gn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?pt.generateChildLogger(e.logger,this.name):pt.pino(pt.getDefaultLoggerOptions({level:e.logger||TE})),this.messages=new JE(this.logger,e.core),this.subscriber=new s7(this,this.logger),this.publisher=new QE(this,this.logger),this.relayUrl=e?.relayUrl||ag,this.projectId=e.projectId,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 ${cg}...`),await this.restartTransport(cg)}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)},UE)}get context(){return pt.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"";return i||(await Promise.all([new Promise(o=>{this.subscriber.once(Tn.created,c=>{c.topic===e&&o()})}),new Promise(async o=>{i=await this.subscriber.subscribe(e,r),o()})]),i)}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportClose(){this.transportExplicitlyClosed=!0,this.hasExperiencedNetworkDisruption&&this.connected?await No(this.provider.disconnect(),1e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.connected&&await this.provider.disconnect()}async transportOpen(e){if(this.transportExplicitlyClosed=!1,await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress){e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportClose(),await this.createProvider()),this.connectionAttemptInProgress=!0;try{await Promise.all([new Promise(r=>{if(!this.initialized)return r();this.subscriber.once(Tn.resubscribed,()=>{r()})}),new Promise(async(r,n)=>{try{await No(this.provider.connect(),1e4,`Socket stalled when trying to connect to ${this.relayUrl}`)}catch(i){n(i);return}r()})])}catch(r){this.logger.error(r);const n=r;if(!this.isConnectionStalled(n.message))throw r;this.provider.events.emit(Gn.disconnect)}finally{this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1}}}async restartTransport(e){await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Z1())throw new Error("No internet connection detected. Please restart your network and try again.")}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Kn(new G_(gb({sdkVersion:ME,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;const i=this.messages.has(r,n);return i&&this.logger.debug(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),fh(e)){if(!e.method.endsWith(NE))return;const r=e.params,{topic:n,message:i,publishedAt:o}=r.data,c={topic:n,message:i,publishedAt:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(l7({type:"event",event:r.id},c)),this.events.emit(r.id,c),await this.acknowledgePayload(e),await this.onMessageEvent(c)}else fc(e)&&this.events.emit(Ir.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Ir.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=hh(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Gn.payload,this.onPayloadHandler),this.provider.off(Gn.connect,this.onConnectHandler),this.provider.off(Gn.disconnect,this.onDisconnectHandler),this.provider.off(Gn.error,this.onProviderErrorHandler)}async registerEventListeners(){this.events.on(Ir.connection_stalled,()=>{this.restartTransport().catch(r=>this.logger.error(r))});let e=await Z1();a6(async r=>{this.initialized&&e!==r&&(e=r,r?await this.restartTransport().catch(n=>this.logger.error(n)):(this.hasExperiencedNetworkDisruption=!0,await this.transportClose().catch(n=>this.logger.error(n))))})}onProviderDisconnect(){this.events.emit(Ir.disconnect),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||(this.logger.info("attemptToReconnect called. Connecting..."),setTimeout(async()=>{await this.restartTransport().catch(e=>this.logger.error(e))},Te.toMiliseconds(LE)))}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectionAttemptInProgress)return await new Promise(e=>{const r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)});await this.restartTransport()}}}var h7=Object.defineProperty,pg=Object.getOwnPropertySymbols,f7=Object.prototype.hasOwnProperty,d7=Object.prototype.propertyIsEnumerable,gg=(t,e,r)=>e in t?h7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,mg=(t,e)=>{for(var r in e||(e={}))f7.call(e,r)&&gg(t,r,e[r]);if(pg)for(var r of pg(e))d7.call(e,r)&&gg(t,r,e[r]);return t};class gc extends F4{constructor(e,r,n,i=gi,o=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=jE,this.cached=[],this.initialized=!1,this.storagePrefix=gi,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(c=>{this.getKey&&c!==null&&!Pr(c)?this.map.set(this.getKey(c),c):jb(c)?this.map.set(c.id,c):Fb(c)&&this.map.set(c.topic,c)}),this.cached=[],this.initialized=!0)},this.set=async(c,l)=>{this.isInitialized(),this.map.has(c)?await this.update(c,l):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:c,value:l}),this.map.set(c,l),await this.persist())},this.get=c=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:c}),this.getData(c)),this.getAll=c=>(this.isInitialized(),c?this.values.filter(l=>Object.keys(c).every(h=>Z_(l[h],c[h]))):this.values),this.update=async(c,l)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:c,update:l});const h=mg(mg({},this.getData(c)),l);this.map.set(c,h),await this.persist()},this.delete=async(c,l)=>{this.isInitialized(),this.map.has(c)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:c,reason:l}),this.map.delete(c),await this.persist())},this.logger=pt.generateChildLogger(r,this.name),this.storagePrefix=i,this.getKey=o}get context(){return pt.getLoggerContext(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(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){const{message:n}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class p7{constructor(e,r){this.core=e,this.logger=r,this.name=WE,this.version=zE,this.events=new yr.exports,this.initialized=!1,this.storagePrefix=gi,this.ignoredPayloadTypes=[zi],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:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async()=>{this.isInitialized();const n=Uu(),i=await this.core.crypto.setSymKey(n),o=En(Te.FIVE_MINUTES),c={protocol:og},l={topic:i,expiry:o,relay:c,active:!1},h=Ab({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:n,relay:c});return await this.pairings.set(i,l),await this.core.relayer.subscribe(i),this.core.expirer.set(i,o),{topic:i,uri:h}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);const{topic:i,symKey:o,relay:c}=Ib(n.uri);let l;if(this.pairings.keys.includes(i)&&(l=this.pairings.get(i),l.active))throw new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);this.core.crypto.keychain.has(i)||(await this.core.crypto.setSymKey(o,i),await this.core.relayer.subscribe(i,{relay:c}));const h=En(Te.FIVE_MINUTES),f={topic:i,relay:c,expiry:h,active:!1};return await this.pairings.set(i,f),this.core.expirer.set(i,h),n.activatePairing&&await this.activate({topic:i}),this.events.emit(Yo.create,f),f},this.activate=async({topic:n})=>{this.isInitialized();const i=En(Te.THIRTY_DAYS);await this.pairings.update(n,{active:!0,expiry:i}),this.core.expirer.set(n,i)},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);const{topic:i}=n;if(this.pairings.keys.includes(i)){const o=await this.sendRequest(i,"wc_pairingPing",{}),{done:c,resolve:l,reject:h}=$s();this.events.once(tr("pairing_ping",o),({error:f})=>{f?h(f):l()}),await c()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",Yt("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,o)=>{const c=Ls(i,o),l=await this.core.crypto.encode(n,c),h=Zo[i].req;return this.core.history.set(n,c),this.core.relayer.publish(n,l,h),c.id},this.sendResult=async(n,i,o)=>{const c=hh(n,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,n),f=Zo[h.request.method].res;await this.core.relayer.publish(i,l,f),await this.core.history.resolve(c)},this.sendError=async(n,i,o)=>{const c=hc(n,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,n),f=Zo[h.request.method]?Zo[h.request.method].res:Zo.unregistered_method.res;await this.core.relayer.publish(i,l,f),await this.core.history.resolve(c)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Yt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{const n=this.pairings.getAll().filter(i=>pi(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{const{topic:i,payload:o}=n;switch(o.method){case"wc_pairingPing":return this.onPairingPingRequest(i,o);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,o);default:return this.onUnknownRpcMethodRequest(i,o)}},this.onRelayEventResponse=async n=>{const{topic:i,payload:o}=n,c=(await this.core.history.get(i,o.id)).request.method;switch(c){case"wc_pairingPing":return this.onPairingPingResponse(i,o);default:return this.onUnknownRpcMethodResponse(c)}},this.onPairingPingRequest=async(n,i)=>{const{id:o}=i;try{this.isValidPing({topic:n}),await this.sendResult(o,n,!0),this.events.emit(Yo.ping,{id:o,topic:n})}catch(c){await this.sendError(o,n,c),this.logger.error(c)}},this.onPairingPingResponse=(n,i)=>{const{id:o}=i;setTimeout(()=>{Vn(i)?this.events.emit(tr("pairing_ping",o),{}):xn(i)&&this.events.emit(tr("pairing_ping",o),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{const{id:o}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(Yo.delete,{id:o,topic:n})}catch(c){await this.sendError(o,n,c),this.logger.error(c)}},this.onUnknownRpcMethodRequest=async(n,i)=>{const{id:o,method:c}=i;try{if(this.registeredMethods.includes(c))return;const l=Yt("WC_METHOD_UNSUPPORTED",c);await this.sendError(o,n,l),this.logger.error(l)}catch(l){await this.sendError(o,n,l),this.logger.error(l)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(Yt("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{if(!Wr(n)){const{message:i}=_e("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(i)}if(!Ub(n.uri)){const{message:i}=_e("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(i)}},this.isValidPing=async n=>{if(!Wr(n)){const{message:o}=_e("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(o)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!Wr(n)){const{message:o}=_e("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(o)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!pr(n,!1)){const{message:i}=_e("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=_e("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(pi(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=_e("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=pt.generateChildLogger(r,this.name),this.pairings=new gc(this.core,this.logger,this.name,this.storagePrefix)}get context(){return pt.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Ir.message,async e=>{const{topic:r,message:n}=e;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;const i=await this.core.crypto.decode(r,n);try{fh(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):fc(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.core.history.delete(r,i.id))}catch(o){this.logger.error(o)}})}registerExpirerEvents(){this.core.expirer.on(cn.expired,async e=>{const{topic:r}=B1(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Yo.expire,{topic:r}))})}}class g7 extends L4{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new yr.exports.EventEmitter,this.name=qE,this.version=VE,this.cached=[],this.initialized=!1,this.storagePrefix=gi,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,o)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:o}),this.records.has(i.id))return;const c={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:o,expiry:En(Te.THIRTY_DAYS)};this.records.set(c.id,c),this.events.emit(Rn.created,c)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=xn(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.events.emit(Rn.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(o=>{if(o.topic===n){if(typeof i<"u"&&o.id!==i)return;this.records.delete(o.id),this.events.emit(Rn.deleted,o)}})},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=pt.generateChildLogger(r,this.name)}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:Ls(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:n}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Rn.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Rn.created,e=>{const r=Rn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(Rn.updated,e=>{const r=Rn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(Rn.deleted,e=>{const r=Rn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.core.heartbeat.on(Ns.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.records.forEach(e=>{Te.toMiliseconds(e.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${e.id}`),this.delete(e.topic,e.id))})}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class m7 extends k4{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new yr.exports.EventEmitter,this.name=KE,this.version=GE,this.cached=[],this.initialized=!1,this.storagePrefix=gi,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();const o=this.formatTarget(n),c={target:o,expiry:i};this.expirations.set(o,c),this.checkExpiry(o,c),this.events.emit(cn.created,{target:o,expiration:c})},this.get=n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),o=this.getExpiration(i);this.expirations.delete(i),this.events.emit(cn.deleted,{target:i,expiration:o})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=pt.generateChildLogger(r,this.name)}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return mb(e);if(typeof e=="number")return vb(e);const{message:r}=_e("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(cn.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:n}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;Te.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(cn.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Ns.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(cn.created,e=>{const r=cn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(cn.expired,e=>{const r=cn.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(cn.deleted,e=>{const r=cn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class v7 extends H4{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=wh,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async n=>{if(this.verifyDisabled||Po()||!To())return;const i=n?.verifyUrl||pc;this.verifyUrl!==i&&this.removeIframe(),this.verifyUrl=i;try{await this.createIframe()}catch(o){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(o)}if(!this.initialized){this.removeIframe(),this.verifyUrl=lg;try{await this.createIframe()}catch(o){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(o),this.verifyDisabled=!0}}},this.register=async n=>{this.initialized?this.sendPost(n.attestationId):(this.addToQueue(n.attestationId),await this.init())},this.resolve=async n=>{if(this.isDevEnv)return"";const i=n?.verifyUrl||pc;let o;try{o=await this.fetchAttestation(n.attestationId,i)}catch(c){this.logger.info(`failed to resolve attestation: ${n.attestationId} from url: ${i}`),this.logger.info(c),o=await this.fetchAttestation(n.attestationId,lg)}return o},this.fetchAttestation=async(n,i)=>{this.logger.info(`resolving attestation: ${n} from url: ${i}`);const o=this.startAbortTimer(Te.ONE_SECOND*2),c=await fetch(`${i}/attestation/${n}`,{signal:this.abortController.signal});return clearTimeout(o),c.status===200?await c.json():void 0},this.addToQueue=n=>{this.queue.push(n)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(n=>this.sendPost(n)),this.queue=[])},this.sendPost=n=>{var i;try{if(!this.iframe)return;(i=this.iframe.contentWindow)==null||i.postMessage(n,"*"),this.logger.info(`postMessage sent: ${n} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let n;const i=o=>{o.data==="verify_ready"&&(this.initialized=!0,this.processQueue(),window.removeEventListener("message",i),n())};await Promise.race([new Promise(o=>{if(document.getElementById(wh))return o();window.addEventListener("message",i);const c=document.createElement("iframe");c.id=wh,c.src=`${this.verifyUrl}/${this.projectId}`,c.style.display="none",document.body.append(c),this.iframe=c,n=o}),new Promise((o,c)=>setTimeout(()=>{window.removeEventListener("message",i),c("verify iframe load timeout")},Te.toMiliseconds(Te.FIVE_SECONDS)))])},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.logger=pt.generateChildLogger(r,this.name),this.verifyUrl=pc,this.abortController=new AbortController,this.isDevEnv=ju()&&process.env.IS_VITEST}get context(){return pt.getLoggerContext(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),Te.toMiliseconds(e))}}var w7=Object.defineProperty,vg=Object.getOwnPropertySymbols,y7=Object.prototype.hasOwnProperty,b7=Object.prototype.propertyIsEnumerable,wg=(t,e,r)=>e in t?w7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yg=(t,e)=>{for(var r in e||(e={}))y7.call(e,r)&&wg(t,r,e[r]);if(vg)for(var r of vg(e))b7.call(e,r)&&wg(t,r,e[r]);return t};class bh extends N4{constructor(e){super(e),this.protocol=ig,this.version=_E,this.name=vh,this.events=new yr.exports.EventEmitter,this.initialized=!1,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||ag,this.customStoragePrefix=e?.customStoragePrefix||"";const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||EE.logger}));this.logger=pt.generateChildLogger(r,this.name),this.heartbeat=new Ns.HeartBeat,this.crypto=new YE(this,this.logger,e?.keychain),this.history=new g7(this,this.logger),this.expirer=new m7(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new j6(yg(yg({},xE),e?.storageOptions)),this.relayer=new u7({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new p7(this,this.logger),this.verify=new v7(this.projectId||"",this.logger)}static async init(e){const r=new bh(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(FE,n),r}get context(){return pt.getLoggerContext(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(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const _7=bh,bg="wc",_g=2,Eg="client",_h=`${bg}@${_g}:${Eg}:`,Eh={name:Eg,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},xg="WALLETCONNECT_DEEPLINK_CHOICE",E7="proposal",Cg="Proposal expired",x7="session",mc=Te.SEVEN_DAYS,C7="engine",Qo={wc_sessionPropose:{req:{ttl:Te.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Te.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:Te.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Te.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Te.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Te.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Te.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Te.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Te.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Te.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Te.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Te.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Te.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Te.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Te.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:Te.THIRTY_SECONDS,prompt:!1,tag:1115}}},xh={min:Te.FIVE_MINUTES,max:Te.SEVEN_DAYS},Zn={idle:"IDLE",active:"ACTIVE"},I7="request",S7=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var O7=Object.defineProperty,A7=Object.defineProperties,D7=Object.getOwnPropertyDescriptors,Ig=Object.getOwnPropertySymbols,$7=Object.prototype.hasOwnProperty,P7=Object.prototype.propertyIsEnumerable,Sg=(t,e,r)=>e in t?O7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zr=(t,e)=>{for(var r in e||(e={}))$7.call(e,r)&&Sg(t,r,e[r]);if(Ig)for(var r of Ig(e))P7.call(e,r)&&Sg(t,r,e[r]);return t},Xo=(t,e)=>A7(t,D7(e));class T7 extends z4{constructor(e){super(e),this.name=C7,this.events=new yr.exports,this.initialized=!1,this.ignoredPayloadTypes=[zi],this.requestQueue={state:Zn.idle,queue:[]},this.sessionRequestQueue={state:Zn.idle,queue:[]},this.requestQueueDelay=Te.ONE_SECOND,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(Qo)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},Te.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{await this.isInitialized();const n=Xo(zr({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:o,optionalNamespaces:c,sessionProperties:l,relays:h}=n;let f=i,w,E=!1;if(f&&(E=this.client.core.pairing.pairings.get(f).active),!f||!E){const{topic:L,uri:$}=await this.client.core.pairing.create();f=L,w=$}const _=await this.client.core.crypto.generateKeyPair(),S=zr({requiredNamespaces:o,optionalNamespaces:c,relays:h??[{protocol:og}],proposer:{publicKey:_,metadata:this.client.metadata}},l&&{sessionProperties:l}),{reject:P,resolve:j,done:H}=$s(Te.FIVE_MINUTES,Cg);if(this.events.once(tr("session_connect"),async({error:L,session:$})=>{if(L)P(L);else if($){$.self.publicKey=_;const T=Xo(zr({},$),{requiredNamespaces:$.requiredNamespaces,optionalNamespaces:$.optionalNamespaces});await this.client.session.set($.topic,T),await this.setExpiry($.topic,$.expiry),f&&await this.client.core.pairing.updateMetadata({topic:f,metadata:$.peer.metadata}),j(T)}}),!f){const{message:L}=_e("NO_MATCHING_KEY",`connect() pairing topic: ${f}`);throw new Error(L)}const Z=await this.sendRequest({topic:f,method:"wc_sessionPropose",params:S}),N=En(Te.FIVE_MINUTES);return await this.setProposal(Z,zr({id:Z,expiry:N},S)),{uri:w,approval:H}},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:n,relayProtocol:i,namespaces:o,sessionProperties:c}=r,l=this.client.proposal.get(n);let{pairingTopic:h,proposer:f,requiredNamespaces:w,optionalNamespaces:E}=l;h=h||"",Ts(w)||(w=Tb(o,"approve()"));const _=await this.client.core.crypto.generateKeyPair(),S=f.publicKey,P=await this.client.core.crypto.generateSharedKey(_,S);h&&n&&(await this.client.core.pairing.updateMetadata({topic:h,metadata:f.metadata}),await this.sendResult({id:n,topic:h,result:{relay:{protocol:i??"irn"},responderPublicKey:_}}),await this.client.proposal.delete(n,Yt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:h}));const j=zr({relay:{protocol:i??"irn"},namespaces:o,requiredNamespaces:w,optionalNamespaces:E,pairingTopic:h,controller:{publicKey:_,metadata:this.client.metadata},expiry:En(mc)},c&&{sessionProperties:c});await this.client.core.relayer.subscribe(P),await this.sendRequest({topic:P,method:"wc_sessionSettle",params:j,throwOnFailedPublish:!0});const H=Xo(zr({},j),{topic:P,pairingTopic:h,acknowledged:!1,self:j.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:_});return await this.client.session.set(P,H),await this.setExpiry(P,En(mc)),{topic:P,acknowledged:()=>new Promise(Z=>setTimeout(()=>Z(this.client.session.get(P)),500))}},this.reject=async r=>{await this.isInitialized(),await this.isValidReject(r);const{id:n,reason:i}=r,{pairingTopic:o}=this.client.proposal.get(n);o&&(await this.sendError(n,o,i),await this.client.proposal.delete(n,Yt("USER_DISCONNECTED")))},this.update=async r=>{await this.isInitialized(),await this.isValidUpdate(r);const{topic:n,namespaces:i}=r,o=await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i}}),{done:c,resolve:l,reject:h}=$s();return this.events.once(tr("session_update",o),({error:f})=>{f?h(f):l()}),await this.client.session.update(n,{namespaces:i}),{acknowledged:c}},this.extend=async r=>{await this.isInitialized(),await this.isValidExtend(r);const{topic:n}=r,i=await this.sendRequest({topic:n,method:"wc_sessionExtend",params:{}}),{done:o,resolve:c,reject:l}=$s();return this.events.once(tr("session_extend",i),({error:h})=>{h?l(h):c()}),await this.setExpiry(n,En(mc)),{acknowledged:o}},this.request=async r=>{await this.isInitialized(),await this.isValidRequest(r);const{chainId:n,request:i,topic:o,expiry:c}=r,l=uh(),{done:h,resolve:f,reject:w}=$s(c);return this.events.once(tr("session_request",l),({error:E,result:_})=>{E?w(E):f(_)}),await Promise.all([new Promise(async E=>{await this.sendRequest({clientRpcId:l,topic:o,method:"wc_sessionRequest",params:{request:i,chainId:n},expiry:c,throwOnFailedPublish:!0}).catch(_=>w(_)),this.client.events.emit("session_request_sent",{topic:o,request:i,chainId:n,id:l}),E()}),new Promise(async E=>{const _=await this.client.core.storage.getItem(xg);wb({id:l,topic:o,wcDeepLink:_}),E()}),h()]).then(E=>E[2])},this.respond=async r=>{await this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:o}=i;Vn(i)?await this.sendResult({id:o,topic:n,result:i.result,throwOnFailedPublish:!0}):xn(i)&&await this.sendError(o,n,i.error),this.cleanupAfterResponse(r)},this.ping=async r=>{await this.isInitialized(),await this.isValidPing(r);const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=await this.sendRequest({topic:n,method:"wc_sessionPing",params:{}}),{done:o,resolve:c,reject:l}=$s();this.events.once(tr("session_ping",i),({error:h})=>{h?l(h):c()}),await o()}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{await this.isInitialized(),await this.isValidEmit(r);const{topic:n,event:i,chainId:o}=r;await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:o}})},this.disconnect=async r=>{await this.isInitialized(),await this.isValidDisconnect(r);const{topic:n}=r;this.client.session.keys.includes(n)?(await this.sendRequest({topic:n,method:"wc_sessionDelete",params:Yt("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession(n)):await this.client.core.pairing.disconnect({topic:n})},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>Lb(n,r))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{const n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(o=>{var c,l;return((c=o.peerMetadata)==null?void 0:c.url)&&((l=o.peerMetadata)==null?void 0:l.url)===r.peer.metadata.url&&o.topic&&o.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(o=>this.client.core.pairing.disconnect({topic:o.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async(r,n)=>{const{self:i}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),this.client.session.delete(r,Yt("USER_DISCONNECTED")),this.client.core.crypto.keychain.has(i.publicKey)&&await this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(xg).catch(o=>this.client.logger.warn(o))},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,Yt("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(o=>o.id!==r),i&&(this.sessionRequestQueue.state=Zn.idle)},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:n}),this.client.core.expirer.set(r,n)},this.setProposal=async(r,n)=>{await this.client.proposal.set(r,n),this.client.core.expirer.set(r,n.expiry)},this.setPendingSessionRequest=async r=>{const n=Qo.wc_sessionRequest.req.ttl,{id:i,topic:o,params:c,verifyContext:l}=r;await this.client.pendingRequest.set(i,{id:i,topic:o,params:c,verifyContext:l}),n&&this.client.core.expirer.set(i,En(n))},this.sendRequest=async r=>{const{topic:n,method:i,params:o,expiry:c,relayRpcId:l,clientRpcId:h,throwOnFailedPublish:f}=r,w=Ls(i,o,h);if(To()&&S7.includes(i)){const S=Ds(JSON.stringify(w));this.client.core.verify.register({attestationId:S})}const E=await this.client.core.crypto.encode(n,w),_=Qo[i].req;return c&&(_.ttl=c),l&&(_.id=l),this.client.core.history.set(n,w),f?(_.internal=Xo(zr({},_.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,E,_)):this.client.core.relayer.publish(n,E,_).catch(S=>this.client.logger.error(S)),w.id},this.sendResult=async r=>{const{id:n,topic:i,result:o,throwOnFailedPublish:c}=r,l=hh(n,o),h=await this.client.core.crypto.encode(i,l),f=await this.client.core.history.get(i,n),w=Qo[f.request.method].res;c?(w.internal=Xo(zr({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,h,w)):this.client.core.relayer.publish(i,h,w).catch(E=>this.client.logger.error(E)),await this.client.core.history.resolve(l)},this.sendError=async(r,n,i)=>{const o=hc(r,i),c=await this.client.core.crypto.encode(n,o),l=await this.client.core.history.get(n,r),h=Qo[l.request.method].res;this.client.core.relayer.publish(n,c,h),await this.client.core.history.resolve(o)},this.cleanup=async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{pi(i.expiry)&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{pi(i.expiry)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession(i)),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===Zn.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=Zn.active;const r=this.requestQueue.queue.shift();if(r)try{this.processRequest(r),await new Promise(n=>setTimeout(n,300))}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Zn.idle},this.processRequest=r=>{const{topic:n,payload:i}=r,o=i.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${o}`)}},this.onRelayEventResponse=async r=>{const{topic:n,payload:i}=r,o=(await this.client.core.history.get(n,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}},this.onRelayEventUnknownPayload=r=>{const{topic:n}=r,{message:i}=_e("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.onSessionProposeRequest=async(r,n)=>{const{params:i,id:o}=n;try{this.isValidConnect(zr({},n.params));const c=En(Te.FIVE_MINUTES),l=zr({id:o,pairingTopic:r,expiry:c},i);await this.setProposal(o,l);const h=Ds(JSON.stringify(n)),f=await this.getVerifyContext(h,l.proposer.metadata);this.client.events.emit("session_proposal",{id:o,params:l,verifyContext:f})}catch(c){await this.sendError(o,r,c),this.client.logger.error(c)}},this.onSessionProposeResponse=async(r,n)=>{const{id:i}=n;if(Vn(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const c=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:c});const l=c.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:l});const h=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const f=await this.client.core.crypto.generateSharedKey(l,h);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:f});const w=await this.client.core.relayer.subscribe(f);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:w}),await this.client.core.pairing.activate({topic:r})}else xn(n)&&(await this.client.proposal.delete(i,Yt("USER_DISCONNECTED")),this.events.emit(tr("session_connect"),{error:n.error}))},this.onSessionSettleRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidSessionSettleRequest(o);const{relay:c,controller:l,expiry:h,namespaces:f,requiredNamespaces:w,optionalNamespaces:E,sessionProperties:_,pairingTopic:S}=n.params,P=zr({topic:r,relay:c,expiry:h,namespaces:f,acknowledged:!0,pairingTopic:S,requiredNamespaces:w,optionalNamespaces:E,controller:l.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:l.publicKey,metadata:l.metadata}},_&&{sessionProperties:_});await this.sendResult({id:n.id,topic:r,result:!0}),this.events.emit(tr("session_connect"),{session:P}),this.cleanupDuplicatePairings(P)}catch(c){await this.sendError(i,r,c),this.client.logger.error(c)}},this.onSessionSettleResponse=async(r,n)=>{const{id:i}=n;Vn(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(tr("session_approve",i),{})):xn(n)&&(await this.client.session.delete(r,Yt("USER_DISCONNECTED")),this.events.emit(tr("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{const{params:i,id:o}=n;try{const c=`${r}_session_update`,l=ac.get(c);if(l&&this.isRequestOutOfSync(l,o)){this.client.logger.info(`Discarding out of sync request - ${o}`);return}this.isValidUpdate(zr({topic:r},i)),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:o,topic:r,result:!0}),this.client.events.emit("session_update",{id:o,topic:r,params:i}),ac.set(c,o)}catch(c){await this.sendError(o,r,c),this.client.logger.error(c)}},this.isRequestOutOfSync=(r,n)=>parseInt(n.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,n)=>{const{id:i}=n;Vn(n)?this.events.emit(tr("session_update",i),{}):xn(n)&&this.events.emit(tr("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,En(mc)),await this.sendResult({id:i,topic:r,result:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionExtendResponse=(r,n)=>{const{id:i}=n;Vn(n)?this.events.emit(tr("session_extend",i),{}):xn(n)&&this.events.emit(tr("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionPingResponse=(r,n)=>{const{id:i}=n;setTimeout(()=>{Vn(n)?this.events.emit(tr("session_ping",i),{}):xn(n)&&this.events.emit(tr("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(o=>{this.client.core.relayer.once(Ir.publish,async()=>{o(await this.deleteSession(r))})}),this.sendResult({id:i,topic:r,result:!0})]),this.client.events.emit("session_delete",{id:i,topic:r})}catch(o){this.client.logger.error(o)}},this.onSessionRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidRequest(zr({topic:r},o));const c=Ds(JSON.stringify(Ls("wc_sessionRequest",o,i))),l=this.client.session.get(r),h=await this.getVerifyContext(c,l.peer.metadata),f={id:i,topic:r,params:o,verifyContext:h};await this.setPendingSessionRequest(f),this.addSessionRequestToSessionRequestQueue(f),this.processSessionRequestQueue()}catch(c){await this.sendError(i,r,c),this.client.logger.error(c)}},this.onSessionRequestResponse=(r,n)=>{const{id:i}=n;Vn(n)?this.events.emit(tr("session_request",i),{result:n.result}):xn(n)&&this.events.emit(tr("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{const{id:i,params:o}=n;try{const c=`${r}_session_event_${o.event.name}`,l=ac.get(c);if(l&&this.isRequestOutOfSync(l,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(zr({topic:r},o)),this.client.events.emit("session_event",{id:i,topic:r,params:o}),ac.set(c,i)}catch(c){await this.sendError(i,r,c),this.client.logger.error(c)}},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Zn.idle,this.processSessionRequestQueue()},Te.toMiliseconds(this.requestQueueDelay))},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===Zn.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=Zn.active,this.client.events.emit("session_request",r)}catch(n){this.client.logger.error(n)}},this.onPairingCreated=r=>{if(r.active)return;const n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest(r.topic,Ls("wc_sessionPropose",{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer},n.id))},this.isValidConnect=async r=>{if(!Wr(r)){const{message:h}=_e("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(h)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:c,relays:l}=r;if(Pr(n)||await this.isValidPairingTopic(n),!Kb(l,!0)){const{message:h}=_e("MISSING_OR_INVALID",`connect() relays: ${l}`);throw new Error(h)}!Pr(i)&&Ts(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Pr(o)&&Ts(o)!==0&&this.validateNamespaces(o,"optionalNamespaces"),Pr(c)||this.validateSessionProps(c,"sessionProperties")},this.validateNamespaces=(r,n)=>{const i=Vb(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!Wr(r))throw new Error(_e("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:o,sessionProperties:c}=r;await this.isValidProposalId(n);const l=this.client.proposal.get(n),h=oc(i,"approve()");if(h)throw new Error(h.message);const f=K1(l.requiredNamespaces,i,"approve()");if(f)throw new Error(f.message);if(!pr(o,!0)){const{message:w}=_e("MISSING_OR_INVALID",`approve() relayProtocol: ${o}`);throw new Error(w)}Pr(c)||this.validateSessionProps(c,"sessionProperties")},this.isValidReject=async r=>{if(!Wr(r)){const{message:o}=_e("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(o)}const{id:n,reason:i}=r;if(await this.isValidProposalId(n),!Zb(i)){const{message:o}=_e("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidSessionSettleRequest=r=>{if(!Wr(r)){const{message:f}=_e("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(f)}const{relay:n,controller:i,namespaces:o,expiry:c}=r;if(!q1(n)){const{message:f}=_e("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(f)}const l=Bb(i,"onSessionSettleRequest()");if(l)throw new Error(l.message);const h=oc(o,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(pi(c)){const{message:f}=_e("EXPIRED","onSessionSettleRequest()");throw new Error(f)}},this.isValidUpdate=async r=>{if(!Wr(r)){const{message:h}=_e("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(h)}const{topic:n,namespaces:i}=r;await this.isValidSessionTopic(n);const o=this.client.session.get(n),c=oc(i,"update()");if(c)throw new Error(c.message);const l=K1(o.requiredNamespaces,i,"update()");if(l)throw new Error(l.message)},this.isValidExtend=async r=>{if(!Wr(r)){const{message:i}=_e("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!Wr(r)){const{message:h}=_e("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(h)}const{topic:n,request:i,chainId:o,expiry:c}=r;await this.isValidSessionTopic(n);const{namespaces:l}=this.client.session.get(n);if(!V1(l,o)){const{message:h}=_e("MISSING_OR_INVALID",`request() chainId: ${o}`);throw new Error(h)}if(!Yb(i)){const{message:h}=_e("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(h)}if(!Xb(l,o,i.method)){const{message:h}=_e("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(h)}if(c&&!n6(c,xh)){const{message:h}=_e("MISSING_OR_INVALID",`request() expiry: ${c}. Expiry must be a number (in seconds) between ${xh.min} and ${xh.max}`);throw new Error(h)}},this.isValidRespond=async r=>{if(!Wr(r)){const{message:o}=_e("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:n,response:i}=r;if(await this.isValidSessionTopic(n),!Jb(i)){const{message:o}=_e("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidPing=async r=>{if(!Wr(r)){const{message:i}=_e("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!Wr(r)){const{message:l}=_e("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(l)}const{topic:n,event:i,chainId:o}=r;await this.isValidSessionTopic(n);const{namespaces:c}=this.client.session.get(n);if(!V1(c,o)){const{message:l}=_e("MISSING_OR_INVALID",`emit() chainId: ${o}`);throw new Error(l)}if(!Qb(i)){const{message:l}=_e("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}if(!e6(c,o,i.name)){const{message:l}=_e("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}},this.isValidDisconnect=async r=>{if(!Wr(r)){const{message:i}=_e("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.getVerifyContext=async(r,n)=>{const i={verified:{verifyUrl:n.verifyUrl||pc,validation:"UNKNOWN",origin:n.url||""}};try{const o=await this.client.core.verify.resolve({attestationId:r,verifyUrl:n.verifyUrl});o&&(i.verified.origin=o.origin,i.verified.isScam=o.isScam,i.verified.validation=o.origin===new URL(n.url).origin?"VALID":"INVALID")}catch(o){this.client.logger.info(o)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!pr(i,!1)){const{message:o}=_e("MISSING_OR_INVALID",`${n} must be in Record<string, string> format. Received: ${JSON.stringify(i)}`);throw new Error(o)}})}}async isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ir.message,async e=>{const{topic:r,message:n}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(n)))return;const i=await this.client.core.crypto.decode(r,n);try{fh(i)?(this.client.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):fc(i)?(await this.client.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.client.core.history.delete(r,i.id)):this.onRelayEventUnknownPayload({topic:r,payload:i})}catch(o){this.client.logger.error(o)}})}registerExpirerEvents(){this.client.core.expirer.on(cn.expired,async e=>{const{topic:r,id:n}=B1(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,_e("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession(r,!0),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(Yo.create,e=>this.onPairingCreated(e))}isValidPairingTopic(e){if(!pr(e,!1)){const{message:r}=_e("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=_e("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(pi(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=_e("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!pr(e,!1)){const{message:r}=_e("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(!this.client.session.keys.includes(e)){const{message:r}=_e("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(pi(this.client.session.get(e).expiry)){await this.deleteSession(e);const{message:r}=_e("EXPIRED",`session topic: ${e}`);throw new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(pr(e,!1)){const{message:r}=_e("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=_e("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!Gb(e)){const{message:r}=_e("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=_e("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(pi(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:r}=_e("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class R7 extends gc{constructor(e,r){super(e,r,E7,_h),this.core=e,this.logger=r}}class N7 extends gc{constructor(e,r){super(e,r,x7,_h),this.core=e,this.logger=r}}class L7 extends gc{constructor(e,r){super(e,r,I7,_h,n=>n.id),this.core=e,this.logger=r}}class Ch extends W4{constructor(e){super(e),this.protocol=bg,this.version=_g,this.name=Eh.name,this.events=new yr.exports.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.name=e?.name||Eh.name,this.metadata=e?.metadata||hb();const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||Eh.logger}));this.core=e?.core||new _7(e),this.logger=pt.generateChildLogger(r,this.name),this.session=new N7(this.core,this.logger),this.proposal=new R7(this.core,this.logger),this.pendingRequest=new L7(this.core,this.logger),this.engine=new T7(this)}static async init(e){const r=new Ch(e);return await r.initialize(),r}get context(){return pt.getLoggerContext(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(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var Ih={exports:{}};(function(t,e){var r=typeof self<"u"?self:dr,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(c){var l={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function h(O){return O&&DataView.prototype.isPrototypeOf(O)}if(l.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],w=ArrayBuffer.isView||function(O){return O&&f.indexOf(Object.prototype.toString.call(O))>-1};function E(O){if(typeof O!="string"&&(O=String(O)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(O))throw new TypeError("Invalid character in header field name");return O.toLowerCase()}function _(O){return typeof O!="string"&&(O=String(O)),O}function S(O){var U={next:function(){var ce=O.shift();return{done:ce===void 0,value:ce}}};return l.iterable&&(U[Symbol.iterator]=function(){return U}),U}function P(O){this.map={},O instanceof P?O.forEach(function(U,ce){this.append(ce,U)},this):Array.isArray(O)?O.forEach(function(U){this.append(U[0],U[1])},this):O&&Object.getOwnPropertyNames(O).forEach(function(U){this.append(U,O[U])},this)}P.prototype.append=function(O,U){O=E(O),U=_(U);var ce=this.map[O];this.map[O]=ce?ce+", "+U:U},P.prototype.delete=function(O){delete this.map[E(O)]},P.prototype.get=function(O){return O=E(O),this.has(O)?this.map[O]:null},P.prototype.has=function(O){return this.map.hasOwnProperty(E(O))},P.prototype.set=function(O,U){this.map[E(O)]=_(U)},P.prototype.forEach=function(O,U){for(var ce in this.map)this.map.hasOwnProperty(ce)&&O.call(U,this.map[ce],ce,this)},P.prototype.keys=function(){var O=[];return this.forEach(function(U,ce){O.push(ce)}),S(O)},P.prototype.values=function(){var O=[];return this.forEach(function(U){O.push(U)}),S(O)},P.prototype.entries=function(){var O=[];return this.forEach(function(U,ce){O.push([ce,U])}),S(O)},l.iterable&&(P.prototype[Symbol.iterator]=P.prototype.entries);function j(O){if(O.bodyUsed)return Promise.reject(new TypeError("Already read"));O.bodyUsed=!0}function H(O){return new Promise(function(U,ce){O.onload=function(){U(O.result)},O.onerror=function(){ce(O.error)}})}function Z(O){var U=new FileReader,ce=H(U);return U.readAsArrayBuffer(O),ce}function N(O){var U=new FileReader,ce=H(U);return U.readAsText(O),ce}function L(O){for(var U=new Uint8Array(O),ce=new Array(U.length),le=0;le<U.length;le++)ce[le]=String.fromCharCode(U[le]);return ce.join("")}function $(O){if(O.slice)return O.slice(0);var U=new Uint8Array(O.byteLength);return U.set(new Uint8Array(O)),U.buffer}function T(){return this.bodyUsed=!1,this._initBody=function(O){this._bodyInit=O,O?typeof O=="string"?this._bodyText=O:l.blob&&Blob.prototype.isPrototypeOf(O)?this._bodyBlob=O:l.formData&&FormData.prototype.isPrototypeOf(O)?this._bodyFormData=O:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(O)?this._bodyText=O.toString():l.arrayBuffer&&l.blob&&h(O)?(this._bodyArrayBuffer=$(O.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(O)||w(O))?this._bodyArrayBuffer=$(O):this._bodyText=O=Object.prototype.toString.call(O):this._bodyText="",this.headers.get("content-type")||(typeof O=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):l.searchParams&&URLSearchParams.prototype.isPrototypeOf(O)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var O=j(this);if(O)return O;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?j(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(Z)}),this.text=function(){var O=j(this);if(O)return O;if(this._bodyBlob)return N(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(L(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},l.formData&&(this.formData=function(){return this.text().then(J)}),this.json=function(){return this.text().then(JSON.parse)},this}var I=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function d(O){var U=O.toUpperCase();return I.indexOf(U)>-1?U:O}function x(O,U){U=U||{};var ce=U.body;if(O instanceof x){if(O.bodyUsed)throw new TypeError("Already read");this.url=O.url,this.credentials=O.credentials,U.headers||(this.headers=new P(O.headers)),this.method=O.method,this.mode=O.mode,this.signal=O.signal,!ce&&O._bodyInit!=null&&(ce=O._bodyInit,O.bodyUsed=!0)}else this.url=String(O);if(this.credentials=U.credentials||this.credentials||"same-origin",(U.headers||!this.headers)&&(this.headers=new P(U.headers)),this.method=d(U.method||this.method||"GET"),this.mode=U.mode||this.mode||null,this.signal=U.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&ce)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(ce)}x.prototype.clone=function(){return new x(this,{body:this._bodyInit})};function J(O){var U=new FormData;return O.trim().split("&").forEach(function(ce){if(ce){var le=ce.split("="),re=le.shift().replace(/\+/g," "),ne=le.join("=").replace(/\+/g," ");U.append(decodeURIComponent(re),decodeURIComponent(ne))}}),U}function W(O){var U=new P,ce=O.replace(/\r?\n[\t ]+/g," ");return ce.split(/\r?\n/).forEach(function(le){var re=le.split(":"),ne=re.shift().trim();if(ne){var ae=re.join(":").trim();U.append(ne,ae)}}),U}T.call(x.prototype);function ee(O,U){U||(U={}),this.type="default",this.status=U.status===void 0?200:U.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in U?U.statusText:"OK",this.headers=new P(U.headers),this.url=U.url||"",this._initBody(O)}T.call(ee.prototype),ee.prototype.clone=function(){return new ee(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new P(this.headers),url:this.url})},ee.error=function(){var O=new ee(null,{status:0,statusText:""});return O.type="error",O};var de=[301,302,303,307,308];ee.redirect=function(O,U){if(de.indexOf(U)===-1)throw new RangeError("Invalid status code");return new ee(null,{status:U,headers:{location:O}})},c.DOMException=o.DOMException;try{new c.DOMException}catch{c.DOMException=function(U,ce){this.message=U,this.name=ce;var le=Error(U);this.stack=le.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function me(O,U){return new Promise(function(ce,le){var re=new x(O,U);if(re.signal&&re.signal.aborted)return le(new c.DOMException("Aborted","AbortError"));var ne=new XMLHttpRequest;function ae(){ne.abort()}ne.onload=function(){var ie={status:ne.status,statusText:ne.statusText,headers:W(ne.getAllResponseHeaders()||"")};ie.url="responseURL"in ne?ne.responseURL:ie.headers.get("X-Request-URL");var Ae="response"in ne?ne.response:ne.responseText;ce(new ee(Ae,ie))},ne.onerror=function(){le(new TypeError("Network request failed"))},ne.ontimeout=function(){le(new TypeError("Network request failed"))},ne.onabort=function(){le(new c.DOMException("Aborted","AbortError"))},ne.open(re.method,re.url,!0),re.credentials==="include"?ne.withCredentials=!0:re.credentials==="omit"&&(ne.withCredentials=!1),"responseType"in ne&&l.blob&&(ne.responseType="blob"),re.headers.forEach(function(ie,Ae){ne.setRequestHeader(Ae,ie)}),re.signal&&(re.signal.addEventListener("abort",ae),ne.onreadystatechange=function(){ne.readyState===4&&re.signal.removeEventListener("abort",ae)}),ne.send(typeof re._bodyInit>"u"?null:re._bodyInit)})}return me.polyfill=!0,o.fetch||(o.fetch=me,o.Headers=P,o.Request=x,o.Response=ee),c.Headers=P,c.Request=x,c.Response=ee,c.fetch=me,Object.defineProperty(c,"__esModule",{value:!0}),c})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(Ih,Ih.exports);var Og=Sv(Ih.exports);const Ag={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},Dg=10;class mi{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new yr.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!Np(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e,r){this.isAvailable||await this.register();try{const n=qo(e),o=await(await Og(this.url,Object.assign(Object.assign({},Ag),{body:n}))).json();this.onPayload({data:o})}catch(n){this.onError(e.id,n)}}async register(e=this.url){if(!Np(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",o=>{this.resetMaxListeners(),i(o)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));n()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=qo({id:1,jsonrpc:"2.0",method:"test",params:[]});await Og(e,Object.assign(Object.assign({},Ag),{body:r}))}this.onOpen()}catch(r){const n=this.parseError(r);throw this.events.emit("register_error",n),this.onClose(),n}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ih(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=hc(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return Op(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Dg&&this.events.setMaxListeners(Dg)}}const $g="error",M7="wss://relay.walletconnect.com",U7="wc",j7="universal_provider",Pg=`${U7}@2:${j7}:`,F7="https://rpc.walletconnect.com/v1/",Yn={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var ea=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Sh={exports:{}};/**
72
+ ***************************************************************************** */var ah=function(t,e){return ah=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},ah(t,e)};function p_(t,e){ah(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var ch=function(){return ch=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},ch.apply(this,arguments)};function g_(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function m_(t,e,r,n){var i=arguments.length,o=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,r,n);else for(var l=t.length-1;l>=0;l--)(c=t[l])&&(o=(i<3?c(o):i>3?c(e,r,o):c(e,r))||o);return i>3&&o&&Object.defineProperty(e,r,o),o}function v_(t,e){return function(r,n){e(r,n,t)}}function w_(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function y_(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function l(w){try{f(n.next(w))}catch(E){c(E)}}function h(w){try{f(n.throw(w))}catch(E){c(E)}}function f(w){w.done?o(w.value):i(w.value).then(l,h)}f((n=n.apply(t,e||[])).next())})}function b_(t,e){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,c;return c={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(c[Symbol.iterator]=function(){return this}),c;function l(f){return function(w){return h([f,w])}}function h(f){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(o=f[0]&2?i.return:f[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,f[1])).done)return o;switch(i=0,o&&(f=[f[0]&2,o.value]),f[0]){case 0:case 1:o=f;break;case 4:return r.label++,{value:f[1],done:!1};case 5:r.label++,i=f[1],f=[0];continue;case 7:f=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(f[0]===6||f[0]===2)){r=0;continue}if(f[0]===3&&(!o||f[1]>o[0]&&f[1]<o[3])){r.label=f[1];break}if(f[0]===6&&r.label<o[1]){r.label=o[1],o=f;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(f);break}o[2]&&r.ops.pop(),r.trys.pop();continue}f=e.call(t,r)}catch(w){f=[6,w],i=0}finally{n=o=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}}function __(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function E_(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function lh(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Dp(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],c;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(l){c={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(c)throw c.error}}return o}function x_(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Dp(arguments[e]));return t}function C_(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var o=arguments[e],c=0,l=o.length;c<l;c++,i++)n[i]=o[c];return n}function Ko(t){return this instanceof Ko?(this.v=t,this):new Ko(t)}function I_(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,o=[];return i={},c("next"),c("throw"),c("return"),i[Symbol.asyncIterator]=function(){return this},i;function c(_){n[_]&&(i[_]=function(S){return new Promise(function(P,j){o.push([_,S,P,j])>1||l(_,S)})})}function l(_,S){try{h(n[_](S))}catch(P){E(o[0][3],P)}}function h(_){_.value instanceof Ko?Promise.resolve(_.value.v).then(f,w):E(o[0][2],_)}function f(_){l("next",_)}function w(_){l("throw",_)}function E(_,S){_(S),o.shift(),o.length&&l(o[0][0],o[0][1])}}function S_(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,o){e[i]=t[i]?function(c){return(r=!r)?{value:Ko(t[i](c)),done:i==="return"}:o?o(c):c}:o}}function O_(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof lh=="function"?lh(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(o){r[o]=t[o]&&function(c){return new Promise(function(l,h){c=t[o](c),i(l,h,c.done,c.value)})}}function i(o,c,l,h){Promise.resolve(h).then(function(f){o({value:f,done:l})},c)}}function A_(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function D_(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function $_(t){return t&&t.__esModule?t:{default:t}}function P_(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function T_(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var R_=Object.freeze({__proto__:null,__extends:p_,get __assign(){return ch},__rest:g_,__decorate:m_,__param:v_,__metadata:w_,__awaiter:y_,__generator:b_,__createBinding:__,__exportStar:E_,__values:lh,__read:Dp,__spread:x_,__spreadArrays:C_,__await:Ko,__asyncGenerator:I_,__asyncDelegator:S_,__asyncValues:O_,__makeTemplateObject:A_,__importStar:D_,__importDefault:$_,__classPrivateFieldGet:P_,__classPrivateFieldSet:T_}),N_=Bi(R_),zn={},$p;function L_(){if($p)return zn;$p=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.isBrowserCryptoAvailable=zn.getSubtleCrypto=zn.getBrowerCrypto=void 0;function t(){return dr?.crypto||dr?.msCrypto||{}}zn.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}zn.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return zn.isBrowserCryptoAvailable=r,zn}var qn={},Pp;function M_(){if(Pp)return qn;Pp=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.isBrowser=qn.isNode=qn.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}qn.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}qn.isNode=e;function r(){return!t()&&!e()}return qn.isBrowser=r,qn}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=N_;e.__exportStar(L_(),t),e.__exportStar(M_(),t)})(Ap);function uh(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Tp(t=6){return BigInt(uh(t))}function Ls(t,e,r){return{id:r||uh(),jsonrpc:"2.0",method:t,params:e}}function hh(t,e){return{id:t,jsonrpc:"2.0",result:e}}function hc(t,e,r){return{id:t,jsonrpc:"2.0",error:U_(e,r)}}function U_(t,e){return typeof t>"u"?Sp(Cp):(typeof t=="string"&&(t=Object.assign(Object.assign({},Sp(oh)),{message:t})),typeof e<"u"&&(t.data=e),f_(t.code)&&(t=d_(t.code)),t)}class j_{}class F_ extends j_{constructor(){super()}}class B_ extends F_{constructor(e){super()}}const k_="^https?:",H_="^wss?:";function W_(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Rp(t,e){const r=W_(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Np(t){return Rp(t,k_)}function Lp(t){return Rp(t,H_)}function z_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Mp(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function fh(t){return Mp(t)&&"method"in t}function fc(t){return Mp(t)&&(Vn(t)||xn(t))}function Vn(t){return"result"in t}function xn(t){return"error"in t}class Kn extends B_{constructor(e){super(e),this.events=new yr.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Ls(e.method,e.params||[],e.id||Tp().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(o){i(o)}this.events.on(`${e.id}`,o=>{xn(o)?i(o.error):n(o.result)});try{await this.connection.send(e,r)}catch(o){i(o)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),fc(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const q_=()=>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"),V_=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Up=t=>t.split("?")[0],jp=10,K_=q_();class G_{constructor(e){if(this.url=e,this.events=new yr.exports.EventEmitter,this.registering=!1,!Lp(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e,r){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(qo(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!Lp(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",o=>{this.resetMaxListeners(),i(o)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=Ap.isReactNative()?void 0:{rejectUnauthorized:!z_(e)},o=new K_(e,[],i);V_()?o.onerror=c=>{const l=c;n(this.emitError(l.error))}:o.on("error",c=>{n(this.emitError(c))}),o.onopen=()=>{this.onOpen(o),r(o)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ih(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=hc(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return Op(e,Up(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>jp&&this.events.setMaxListeners(jp)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Up(this.url)}`));return this.events.emit("register_error",r),r}}var dh={exports:{}};(function(t,e){var r=200,n="__lodash_hash_undefined__",i=1,o=2,c=9007199254740991,l="[object Arguments]",h="[object Array]",f="[object AsyncFunction]",w="[object Boolean]",E="[object Date]",_="[object Error]",S="[object Function]",P="[object GeneratorFunction]",j="[object Map]",H="[object Number]",Z="[object Null]",N="[object Object]",L="[object Promise]",$="[object Proxy]",T="[object RegExp]",I="[object Set]",d="[object String]",x="[object Symbol]",J="[object Undefined]",W="[object WeakMap]",ee="[object ArrayBuffer]",de="[object DataView]",me="[object Float32Array]",O="[object Float64Array]",U="[object Int8Array]",ce="[object Int16Array]",le="[object Int32Array]",re="[object Uint8Array]",ne="[object Uint8ClampedArray]",ae="[object Uint16Array]",ie="[object Uint32Array]",Ae=/[\\^$.*+?()[\]{}|]/g,ge=/^\[object .+?Constructor\]$/,Be=/^(?:0|[1-9]\d*)$/,ye={};ye[me]=ye[O]=ye[U]=ye[ce]=ye[le]=ye[re]=ye[ne]=ye[ae]=ye[ie]=!0,ye[l]=ye[h]=ye[ee]=ye[w]=ye[de]=ye[E]=ye[_]=ye[S]=ye[j]=ye[H]=ye[N]=ye[T]=ye[I]=ye[d]=ye[W]=!1;var Me=typeof dr=="object"&&dr&&dr.Object===Object&&dr,Q=typeof self=="object"&&self&&self.Object===Object&&self,Y=Me||Q||Function("return this")(),z=e&&!e.nodeType&&e,v=z&&!0&&t&&!t.nodeType&&t,F=v&&v.exports===z,ve=F&&Me.process,we=function(){try{return ve&&ve.binding&&ve.binding("util")}catch{}}(),Ue=we&&we.isTypedArray;function nt(R,q){for(var fe=-1,Ce=R==null?0:R.length,It=0,Qe=[];++fe<Ce;){var Tt=R[fe];q(Tt,fe,R)&&(Qe[It++]=Tt)}return Qe}function at(R,q){for(var fe=-1,Ce=q.length,It=R.length;++fe<Ce;)R[It+fe]=q[fe];return R}function Ge(R,q){for(var fe=-1,Ce=R==null?0:R.length;++fe<Ce;)if(q(R[fe],fe,R))return!0;return!1}function Dt(R,q){for(var fe=-1,Ce=Array(R);++fe<R;)Ce[fe]=q(fe);return Ce}function $t(R){return function(q){return R(q)}}function Je(R,q){return R.has(q)}function He(R,q){return R?.[q]}function ke(R){var q=-1,fe=Array(R.size);return R.forEach(function(Ce,It){fe[++q]=[It,Ce]}),fe}function Ke(R,q){return function(fe){return R(q(fe))}}function rt(R){var q=-1,fe=Array(R.size);return R.forEach(function(Ce){fe[++q]=Ce}),fe}var je=Array.prototype,Ze=Function.prototype,b=Object.prototype,p=Y["__core-js_shared__"],m=Ze.toString,D=b.hasOwnProperty,B=function(){var R=/[^.]+$/.exec(p&&p.keys&&p.keys.IE_PROTO||"");return R?"Symbol(src)_1."+R:""}(),K=b.toString,X=RegExp("^"+m.call(D).replace(Ae,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ee=F?Y.Buffer:void 0,Re=Y.Symbol,st=Y.Uint8Array,ht=b.propertyIsEnumerable,lt=je.splice,Ur=Re?Re.toStringTag:void 0,ti=Object.getOwnPropertySymbols,Di=Ee?Ee.isBuffer:void 0,hs=Ke(Object.keys,Object),Wt=tn(Y,"DataView"),Mt=tn(Y,"Map"),zt=tn(Y,"Promise"),qt=tn(Y,"Set"),Bt=tn(Y,"WeakMap"),Ut=tn(Object,"create"),nr=ni(Wt),ir=ni(Mt),Vt=ni(zt),sr=ni(qt),Kt=ni(Bt),Jt=Re?Re.prototype:void 0,Gt=Jt?Jt.valueOf:void 0;function Pt(R){var q=-1,fe=R==null?0:R.length;for(this.clear();++q<fe;){var Ce=R[q];this.set(Ce[0],Ce[1])}}function or(){this.__data__=Ut?Ut(null):{},this.size=0}function ar(R){var q=this.has(R)&&delete this.__data__[R];return this.size-=q?1:0,q}function Gf(R){var q=this.__data__;if(Ut){var fe=q[R];return fe===n?void 0:fe}return D.call(q,R)?q[R]:void 0}function Zf(R){var q=this.__data__;return Ut?q[R]!==void 0:D.call(q,R)}function Yf(R,q){var fe=this.__data__;return this.size+=this.has(R)?0:1,fe[R]=Ut&&q===void 0?n:q,this}Pt.prototype.clear=or,Pt.prototype.delete=ar,Pt.prototype.get=Gf,Pt.prototype.has=Zf,Pt.prototype.set=Yf;function fn(R){var q=-1,fe=R==null?0:R.length;for(this.clear();++q<fe;){var Ce=R[q];this.set(Ce[0],Ce[1])}}function Jf(){this.__data__=[],this.size=0}function Qf(R){var q=this.__data__,fe=fs(q,R);if(fe<0)return!1;var Ce=q.length-1;return fe==Ce?q.pop():lt.call(q,fe,1),--this.size,!0}function Xf(R){var q=this.__data__,fe=fs(q,R);return fe<0?void 0:q[fe][1]}function e0(R){return fs(this.__data__,R)>-1}function t0(R,q){var fe=this.__data__,Ce=fs(fe,R);return Ce<0?(++this.size,fe.push([R,q])):fe[Ce][1]=q,this}fn.prototype.clear=Jf,fn.prototype.delete=Qf,fn.prototype.get=Xf,fn.prototype.has=e0,fn.prototype.set=t0;function ri(R){var q=-1,fe=R==null?0:R.length;for(this.clear();++q<fe;){var Ce=R[q];this.set(Ce[0],Ce[1])}}function no(){this.size=0,this.__data__={hash:new Pt,map:new(Mt||fn),string:new Pt}}function r0(R){var q=$i(this,R).delete(R);return this.size-=q?1:0,q}function io(R){return $i(this,R).get(R)}function n0(R){return $i(this,R).has(R)}function i0(R,q){var fe=$i(this,R),Ce=fe.size;return fe.set(R,q),this.size+=fe.size==Ce?0:1,this}ri.prototype.clear=no,ri.prototype.delete=r0,ri.prototype.get=io,ri.prototype.has=n0,ri.prototype.set=i0;function so(R){var q=-1,fe=R==null?0:R.length;for(this.__data__=new ri;++q<fe;)this.add(R[q])}function ol(R){return this.__data__.set(R,n),this}function al(R){return this.__data__.has(R)}so.prototype.add=so.prototype.push=ol,so.prototype.has=al;function Cn(R){var q=this.__data__=new fn(R);this.size=q.size}function s0(){this.__data__=new fn,this.size=0}function o0(R){var q=this.__data__,fe=q.delete(R);return this.size=q.size,fe}function a0(R){return this.__data__.get(R)}function c0(R){return this.__data__.has(R)}function cl(R,q){var fe=this.__data__;if(fe instanceof fn){var Ce=fe.__data__;if(!Mt||Ce.length<r-1)return Ce.push([R,q]),this.size=++fe.size,this;fe=this.__data__=new ri(Ce)}return fe.set(R,q),this.size=fe.size,this}Cn.prototype.clear=s0,Cn.prototype.delete=o0,Cn.prototype.get=a0,Cn.prototype.has=c0,Cn.prototype.set=cl;function ll(R,q){var fe=co(R),Ce=!fe&&_l(R),It=!fe&&!Ce&&Da(R),Qe=!fe&&!Ce&&!It&&Cl(R),Tt=fe||Ce||It||Qe,cr=Tt?Dt(R.length,String):[],mt=cr.length;for(var St in R)(q||D.call(R,St))&&!(Tt&&(St=="length"||It&&(St=="offset"||St=="parent")||Qe&&(St=="buffer"||St=="byteLength"||St=="byteOffset")||ml(St,mt)))&&cr.push(St);return cr}function fs(R,q){for(var fe=R.length;fe--;)if(bl(R[fe][0],q))return fe;return-1}function Oa(R,q,fe){var Ce=q(R);return co(R)?Ce:at(Ce,fe(R))}function ds(R){return R==null?R===void 0?J:Z:Ur&&Ur in Object(R)?pl(R):h0(R)}function Aa(R){return gs(R)&&ds(R)==l}function ps(R,q,fe,Ce,It){return R===q?!0:R==null||q==null||!gs(R)&&!gs(q)?R!==R&&q!==q:ul(R,q,fe,Ce,ps,It)}function ul(R,q,fe,Ce,It,Qe){var Tt=co(R),cr=co(q),mt=Tt?h:Fn(R),St=cr?h:Fn(q);mt=mt==l?N:mt,St=St==l?N:St;var Qt=mt==N,Vr=St==N,lr=mt==St;if(lr&&Da(R)){if(!Da(q))return!1;Tt=!0,Qt=!1}if(lr&&!Qt)return Qe||(Qe=new Cn),Tt||Cl(R)?oo(R,q,fe,Ce,It,Qe):u0(R,q,mt,fe,Ce,It,Qe);if(!(fe&i)){var Rt=Qt&&D.call(R,"__wrapped__"),jr=Vr&&D.call(q,"__wrapped__");if(Rt||jr){var In=Rt?R.value():R,dn=jr?q.value():q;return Qe||(Qe=new Cn),It(In,dn,fe,Ce,Qe)}}return lr?(Qe||(Qe=new Cn),dl(R,q,fe,Ce,It,Qe)):!1}function l0(R){if(!xl(R)||wl(R))return!1;var q=lo(R)?X:ge;return q.test(ni(R))}function hl(R){return gs(R)&&El(R.length)&&!!ye[ds(R)]}function fl(R){if(!yl(R))return hs(R);var q=[];for(var fe in Object(R))D.call(R,fe)&&fe!="constructor"&&q.push(fe);return q}function oo(R,q,fe,Ce,It,Qe){var Tt=fe&i,cr=R.length,mt=q.length;if(cr!=mt&&!(Tt&&mt>cr))return!1;var St=Qe.get(R);if(St&&Qe.get(q))return St==q;var Qt=-1,Vr=!0,lr=fe&o?new so:void 0;for(Qe.set(R,q),Qe.set(q,R);++Qt<cr;){var Rt=R[Qt],jr=q[Qt];if(Ce)var In=Tt?Ce(jr,Rt,Qt,q,R,Qe):Ce(Rt,jr,Qt,R,q,Qe);if(In!==void 0){if(In)continue;Vr=!1;break}if(lr){if(!Ge(q,function(dn,Bn){if(!Je(lr,Bn)&&(Rt===dn||It(Rt,dn,fe,Ce,Qe)))return lr.push(Bn)})){Vr=!1;break}}else if(!(Rt===jr||It(Rt,jr,fe,Ce,Qe))){Vr=!1;break}}return Qe.delete(R),Qe.delete(q),Vr}function u0(R,q,fe,Ce,It,Qe,Tt){switch(fe){case de:if(R.byteLength!=q.byteLength||R.byteOffset!=q.byteOffset)return!1;R=R.buffer,q=q.buffer;case ee:return!(R.byteLength!=q.byteLength||!Qe(new st(R),new st(q)));case w:case E:case H:return bl(+R,+q);case _:return R.name==q.name&&R.message==q.message;case T:case d:return R==q+"";case j:var cr=ke;case I:var mt=Ce&i;if(cr||(cr=rt),R.size!=q.size&&!mt)return!1;var St=Tt.get(R);if(St)return St==q;Ce|=o,Tt.set(R,q);var Qt=oo(cr(R),cr(q),Ce,It,Qe,Tt);return Tt.delete(R),Qt;case x:if(Gt)return Gt.call(R)==Gt.call(q)}return!1}function dl(R,q,fe,Ce,It,Qe){var Tt=fe&i,cr=ao(R),mt=cr.length,St=ao(q),Qt=St.length;if(mt!=Qt&&!Tt)return!1;for(var Vr=mt;Vr--;){var lr=cr[Vr];if(!(Tt?lr in q:D.call(q,lr)))return!1}var Rt=Qe.get(R);if(Rt&&Qe.get(q))return Rt==q;var jr=!0;Qe.set(R,q),Qe.set(q,R);for(var In=Tt;++Vr<mt;){lr=cr[Vr];var dn=R[lr],Bn=q[lr];if(Ce)var $a=Tt?Ce(Bn,dn,lr,q,R,Qe):Ce(dn,Bn,lr,R,q,Qe);if(!($a===void 0?dn===Bn||It(dn,Bn,fe,Ce,Qe):$a)){jr=!1;break}In||(In=lr=="constructor")}if(jr&&!In){var ms=R.constructor,vr=q.constructor;ms!=vr&&"constructor"in R&&"constructor"in q&&!(typeof ms=="function"&&ms instanceof ms&&typeof vr=="function"&&vr instanceof vr)&&(jr=!1)}return Qe.delete(R),Qe.delete(q),jr}function ao(R){return Oa(R,p0,gl)}function $i(R,q){var fe=R.__data__;return vl(q)?fe[typeof q=="string"?"string":"hash"]:fe.map}function tn(R,q){var fe=He(R,q);return l0(fe)?fe:void 0}function pl(R){var q=D.call(R,Ur),fe=R[Ur];try{R[Ur]=void 0;var Ce=!0}catch{}var It=K.call(R);return Ce&&(q?R[Ur]=fe:delete R[Ur]),It}var gl=ti?function(R){return R==null?[]:(R=Object(R),nt(ti(R),function(q){return ht.call(R,q)}))}:Ct,Fn=ds;(Wt&&Fn(new Wt(new ArrayBuffer(1)))!=de||Mt&&Fn(new Mt)!=j||zt&&Fn(zt.resolve())!=L||qt&&Fn(new qt)!=I||Bt&&Fn(new Bt)!=W)&&(Fn=function(R){var q=ds(R),fe=q==N?R.constructor:void 0,Ce=fe?ni(fe):"";if(Ce)switch(Ce){case nr:return de;case ir:return j;case Vt:return L;case sr:return I;case Kt:return W}return q});function ml(R,q){return q=q??c,!!q&&(typeof R=="number"||Be.test(R))&&R>-1&&R%1==0&&R<q}function vl(R){var q=typeof R;return q=="string"||q=="number"||q=="symbol"||q=="boolean"?R!=="__proto__":R===null}function wl(R){return!!B&&B in R}function yl(R){var q=R&&R.constructor,fe=typeof q=="function"&&q.prototype||b;return R===fe}function h0(R){return K.call(R)}function ni(R){if(R!=null){try{return m.call(R)}catch{}try{return R+""}catch{}}return""}function bl(R,q){return R===q||R!==R&&q!==q}var _l=Aa(function(){return arguments}())?Aa:function(R){return gs(R)&&D.call(R,"callee")&&!ht.call(R,"callee")},co=Array.isArray;function f0(R){return R!=null&&El(R.length)&&!lo(R)}var Da=Di||xt;function d0(R,q){return ps(R,q)}function lo(R){if(!xl(R))return!1;var q=ds(R);return q==S||q==P||q==f||q==$}function El(R){return typeof R=="number"&&R>-1&&R%1==0&&R<=c}function xl(R){var q=typeof R;return R!=null&&(q=="object"||q=="function")}function gs(R){return R!=null&&typeof R=="object"}var Cl=Ue?$t(Ue):hl;function p0(R){return f0(R)?ll(R):fl(R)}function Ct(){return[]}function xt(){return!1}t.exports=d0})(dh,dh.exports);var Z_=dh.exports,Y_=Object.defineProperty,Fp=Object.getOwnPropertySymbols,J_=Object.prototype.hasOwnProperty,Q_=Object.prototype.propertyIsEnumerable,Bp=(t,e,r)=>e in t?Y_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rr=(t,e)=>{for(var r in e||(e={}))J_.call(e,r)&&Bp(t,r,e[r]);if(Fp)for(var r of Fp(e))Q_.call(e,r)&&Bp(t,r,e[r]);return t};function X_(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),c=o.charCodeAt(0);if(r[c]!==255)throw new TypeError(o+" is ambiguous");r[c]=i}var l=t.length,h=t.charAt(0),f=Math.log(l)/Math.log(256),w=Math.log(256)/Math.log(l);function E(P){if(P instanceof Uint8Array||(ArrayBuffer.isView(P)?P=new Uint8Array(P.buffer,P.byteOffset,P.byteLength):Array.isArray(P)&&(P=Uint8Array.from(P))),!(P instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(P.length===0)return"";for(var j=0,H=0,Z=0,N=P.length;Z!==N&&P[Z]===0;)Z++,j++;for(var L=(N-Z)*w+1>>>0,$=new Uint8Array(L);Z!==N;){for(var T=P[Z],I=0,d=L-1;(T!==0||I<H)&&d!==-1;d--,I++)T+=256*$[d]>>>0,$[d]=T%l>>>0,T=T/l>>>0;if(T!==0)throw new Error("Non-zero carry");H=I,Z++}for(var x=L-H;x!==L&&$[x]===0;)x++;for(var J=h.repeat(j);x<L;++x)J+=t.charAt($[x]);return J}function _(P){if(typeof P!="string")throw new TypeError("Expected String");if(P.length===0)return new Uint8Array;var j=0;if(P[j]!==" "){for(var H=0,Z=0;P[j]===h;)H++,j++;for(var N=(P.length-j)*f+1>>>0,L=new Uint8Array(N);P[j];){var $=r[P.charCodeAt(j)];if($===255)return;for(var T=0,I=N-1;($!==0||T<Z)&&I!==-1;I--,T++)$+=l*L[I]>>>0,L[I]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");Z=T,j++}if(P[j]!==" "){for(var d=N-Z;d!==N&&L[d]===0;)d++;for(var x=new Uint8Array(H+(N-d)),J=H;d!==N;)x[J++]=L[d++];return x}}}function S(P){var j=_(P);if(j)return j;throw new Error(`Non-${e} character`)}return{encode:E,decodeUnsafe:_,decode:S}}var e8=X_,t8=e8;const kp=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},r8=t=>new TextEncoder().encode(t),n8=t=>new TextDecoder().decode(t);class i8{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class s8{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Hp(this,e)}}class o8{constructor(e){this.decoders=e}or(e){return Hp(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Hp=(t,e)=>new o8(Rr(Rr({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class a8{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new i8(e,r,n),this.decoder=new s8(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const dc=({name:t,prefix:e,encode:r,decode:n})=>new a8(t,e,r,n),Go=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=t8(r,e);return dc({prefix:t,name:e,encode:n,decode:o=>kp(i(o))})},c8=(t,e,r,n)=>{const i={};for(let w=0;w<e.length;++w)i[e[w]]=w;let o=t.length;for(;t[o-1]==="=";)--o;const c=new Uint8Array(o*r/8|0);let l=0,h=0,f=0;for(let w=0;w<o;++w){const E=i[t[w]];if(E===void 0)throw new SyntaxError(`Non-${n} character`);h=h<<r|E,l+=r,l>=8&&(l-=8,c[f++]=255&h>>l)}if(l>=r||255&h<<8-l)throw new SyntaxError("Unexpected end of data");return c},l8=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let o="",c=0,l=0;for(let h=0;h<t.length;++h)for(l=l<<8|t[h],c+=8;c>r;)c-=r,o+=e[i&l>>c];if(c&&(o+=e[i&l<<r-c]),n)for(;o.length*r&7;)o+="=";return o},_r=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>dc({prefix:e,name:t,encode(i){return l8(i,n,r)},decode(i){return c8(i,n,r,t)}}),u8=dc({prefix:"\0",name:"identity",encode:t=>n8(t),decode:t=>r8(t)});var h8=Object.freeze({__proto__:null,identity:u8});const f8=_r({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var d8=Object.freeze({__proto__:null,base2:f8});const p8=_r({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var g8=Object.freeze({__proto__:null,base8:p8});const m8=Go({prefix:"9",name:"base10",alphabet:"0123456789"});var v8=Object.freeze({__proto__:null,base10:m8});const w8=_r({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),y8=_r({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var b8=Object.freeze({__proto__:null,base16:w8,base16upper:y8});const _8=_r({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),E8=_r({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),x8=_r({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),C8=_r({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),I8=_r({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),S8=_r({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),O8=_r({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),A8=_r({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),D8=_r({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var $8=Object.freeze({__proto__:null,base32:_8,base32upper:E8,base32pad:x8,base32padupper:C8,base32hex:I8,base32hexupper:S8,base32hexpad:O8,base32hexpadupper:A8,base32z:D8});const P8=Go({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),T8=Go({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var R8=Object.freeze({__proto__:null,base36:P8,base36upper:T8});const N8=Go({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),L8=Go({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var M8=Object.freeze({__proto__:null,base58btc:N8,base58flickr:L8});const U8=_r({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),j8=_r({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),F8=_r({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),B8=_r({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var k8=Object.freeze({__proto__:null,base64:U8,base64pad:j8,base64url:F8,base64urlpad:B8});const Wp=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),H8=Wp.reduce((t,e,r)=>(t[r]=e,t),[]),W8=Wp.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function z8(t){return t.reduce((e,r)=>(e+=H8[r],e),"")}function q8(t){const e=[];for(const r of t){const n=W8[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const V8=dc({prefix:"\u{1F680}",name:"base256emoji",encode:z8,decode:q8});var K8=Object.freeze({__proto__:null,base256emoji:V8}),G8=qp,zp=128,Z8=127,Y8=~Z8,J8=Math.pow(2,31);function qp(t,e,r){e=e||[],r=r||0;for(var n=r;t>=J8;)e[r++]=t&255|zp,t/=128;for(;t&Y8;)e[r++]=t&255|zp,t>>>=7;return e[r]=t|0,qp.bytes=r-n+1,e}var Q8=ph,X8=128,Vp=127;function ph(t,n){var r=0,n=n||0,i=0,o=n,c,l=t.length;do{if(o>=l)throw ph.bytes=0,new RangeError("Could not decode varint");c=t[o++],r+=i<28?(c&Vp)<<i:(c&Vp)*Math.pow(2,i),i+=7}while(c>=X8);return ph.bytes=o-n,r}var eE=Math.pow(2,7),tE=Math.pow(2,14),rE=Math.pow(2,21),nE=Math.pow(2,28),iE=Math.pow(2,35),sE=Math.pow(2,42),oE=Math.pow(2,49),aE=Math.pow(2,56),cE=Math.pow(2,63),lE=function(t){return t<eE?1:t<tE?2:t<rE?3:t<nE?4:t<iE?5:t<sE?6:t<oE?7:t<aE?8:t<cE?9:10},uE={encode:G8,decode:Q8,encodingLength:lE},Kp=uE;const Gp=(t,e,r=0)=>(Kp.encode(t,e,r),e),Zp=t=>Kp.encodingLength(t),gh=(t,e)=>{const r=e.byteLength,n=Zp(t),i=n+Zp(r),o=new Uint8Array(i+r);return Gp(t,o,0),Gp(r,o,n),o.set(e,i),new hE(t,r,e,o)};class hE{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Yp=({name:t,code:e,encode:r})=>new fE(t,e,r);class fE{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?gh(this.code,r):r.then(n=>gh(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Jp=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),dE=Yp({name:"sha2-256",code:18,encode:Jp("SHA-256")}),pE=Yp({name:"sha2-512",code:19,encode:Jp("SHA-512")});var gE=Object.freeze({__proto__:null,sha256:dE,sha512:pE});const Qp=0,mE="identity",Xp=kp;var vE=Object.freeze({__proto__:null,identity:{code:Qp,name:mE,encode:Xp,digest:t=>gh(Qp,Xp(t))}});new TextEncoder,new TextDecoder;const eg=Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr({},h8),d8),g8),v8),b8),$8),R8),M8),k8),K8);Rr(Rr({},gE),vE);function tg(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function wE(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?tg(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function rg(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const ng=rg("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),mh=rg("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=wE(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),yE=Rr({utf8:ng,"utf-8":ng,hex:eg.base16,latin1:mh,ascii:mh,binary:mh},eg);function bE(t,e="utf8"){const r=yE[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?tg(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}const ig="wc",_E=2,vh="core",gi=`${ig}@2:${vh}:`,EE={name:vh,logger:"error"},xE={database:":memory:"},CE="crypto",sg="client_ed25519_seed",IE=Te.ONE_DAY,SE="keychain",OE="0.3",AE="messages",DE="0.3",$E=Te.SIX_HOURS,PE="publisher",og="irn",TE="error",ag="wss://relay.walletconnect.com",cg="wss://relay.walletconnect.org",RE="relayer",Ir={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},NE="_subscription",Gn={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},LE=Te.ONE_SECOND,ME="2.10.1-c46eedfa",UE=1e4,jE="0.3",FE="WALLETCONNECT_CLIENT_ID",Tn={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},BE="subscription",kE="0.3",HE=Te.FIVE_SECONDS*1e3,WE="pairing",zE="0.3",Zo={wc_pairingDelete:{req:{ttl:Te.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:Te.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:Te.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:Te.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:Te.ONE_DAY,prompt:!1,tag:0},res:{ttl:Te.ONE_DAY,prompt:!1,tag:0}}},Yo={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Rn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},qE="history",VE="0.3",KE="expirer",cn={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},GE="0.3",wh="verify-api",pc="https://verify.walletconnect.com",lg="https://verify.walletconnect.org";class ZE{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=SE,this.version=OE,this.initialized=!1,this.storagePrefix=gi,this.init=async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:o}=_e("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(o)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=pt.generateChildLogger(r,this.name)}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,U1(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?j1(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class YE{constructor(e,r,n){this.core=e,this.logger=r,this.name=CE,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();const i=await this.getClientSeed(),o=xp(i);return Ep(o.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const i=J5();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const o=await this.getClientSeed(),c=xp(o),l=Uu();return await o_(l,i,IE,c)},this.generateSharedKey=(i,o,c)=>{this.isInitialized();const l=this.getPrivateKey(i),h=Q5(l,o);return this.setSymKey(h,c)},this.setSymKey=async(i,o)=>{this.isInitialized();const c=o||X5(i);return await this.keychain.set(c,i),c},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,o,c)=>{this.isInitialized();const l=T1(c),h=qo(o);if(R1(l)){const _=l.senderPublicKey,S=l.receiverPublicKey;i=await this.generateSharedKey(_,S)}const f=this.getSymKey(i),{type:w,senderPublicKey:E}=l;return tb({type:w,symKey:f,message:h,senderPublicKey:E})},this.decode=async(i,o,c)=>{this.isInitialized();const l=ib(o,c);if(R1(l)){const h=l.receiverPublicKey,f=l.senderPublicKey;i=await this.generateSharedKey(h,f)}try{const h=this.getSymKey(i),f=rb({symKey:h,encoded:o});return ih(f)}catch(h){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(h)}},this.getPayloadType=i=>{const o=nc(i);return $o(o.type)},this.getPayloadSenderPublicKey=i=>{const o=nc(i);return o.senderPublicKey?Dr(o.senderPublicKey,$r):void 0},this.core=e,this.logger=pt.generateChildLogger(r,this.name),this.keychain=n||new ZE(this.core,this.logger)}get context(){return pt.getLoggerContext(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(sg)}catch{e=Uu(),await this.keychain.set(sg,e)}return bE(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class JE extends M4{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=AE,this.version=DE,this.initialized=!1,this.storagePrefix=gi,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();const o=Ds(i);let c=this.messages.get(n);return typeof c>"u"&&(c={}),typeof c[o]<"u"||(c[o]=i,this.messages.set(n,c),await this.persist()),o},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();const o=this.get(n),c=Ds(i);return typeof o[c]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=pt.generateChildLogger(e,this.name),this.core=r}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,U1(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?j1(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class QE extends U4{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new yr.exports.EventEmitter,this.name=PE,this.queue=new Map,this.publishTimeout=Te.toMiliseconds(Te.TEN_SECONDS),this.needsTransportRestart=!1,this.publish=async(n,i,o)=>{var c;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:o}});try{const l=o?.ttl||$E,h=Bu(o),f=o?.prompt||!1,w=o?.tag||0,E=o?.id||Tp().toString(),_={topic:n,message:i,opts:{ttl:l,relay:h,prompt:f,tag:w,id:E}},S=setTimeout(()=>this.queue.set(E,_),this.publishTimeout);try{await await No(this.rpcPublish(n,i,l,h,f,w,E),this.publishTimeout,"Failed to publish payload, please try again."),this.removeRequestFromQueue(E),this.relayer.events.emit(Ir.publish,_)}catch(P){if(this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0,(c=o?.internal)!=null&&c.throwOnFailedPublish)throw this.removeRequestFromQueue(E),P;return}finally{clearTimeout(S)}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:o}})}catch(l){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(l),l}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=pt.generateChildLogger(r,this.name),this.registerEventListeners()}get context(){return pt.getLoggerContext(this.logger)}rpcPublish(e,r,n,i,o,c,l){var h,f,w,E;const _={method:ic(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:o,tag:c},id:l};return Pr((h=_.params)==null?void 0:h.prompt)&&((f=_.params)==null||delete f.prompt),Pr((w=_.params)==null?void 0:w.tag)&&((E=_.params)==null||delete E.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:_}),this.relayer.request(_)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(Ns.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Ir.connection_stalled);return}this.checkQueue()}),this.relayer.on(Ir.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class XE{constructor(){this.map=new Map,this.set=(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(o=>o!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var e7=Object.defineProperty,t7=Object.defineProperties,r7=Object.getOwnPropertyDescriptors,ug=Object.getOwnPropertySymbols,n7=Object.prototype.hasOwnProperty,i7=Object.prototype.propertyIsEnumerable,hg=(t,e,r)=>e in t?e7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Jo=(t,e)=>{for(var r in e||(e={}))n7.call(e,r)&&hg(t,r,e[r]);if(ug)for(var r of ug(e))i7.call(e,r)&&hg(t,r,e[r]);return t},yh=(t,e)=>t7(t,r7(e));class s7 extends B4{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new XE,this.events=new yr.exports.EventEmitter,this.name=BE,this.version=kE,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=gi,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(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const o=Bu(i),c={topic:n,relay:o};this.pending.set(n,c);const l=await this.rpcSubscribe(n,o);return this.onSubscribe(l,c),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}}),l}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>this.topics.includes(n)?!0:await new Promise((i,o)=>{const c=new Te.Watch;c.start(this.pendingSubscriptionWatchLabel);const l=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(l),c.stop(this.pendingSubscriptionWatchLabel),i(!0)),c.elapsed(this.pendingSubscriptionWatchLabel)>=HE&&(clearInterval(l),c.stop(this.pendingSubscriptionWatchLabel),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=pt.generateChildLogger(r,this.name),this.clientId=""}get context(){return pt.getLoggerContext(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(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=Bu(n);await this.rpcUnsubscribe(e,r,i);const o=Yt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,o),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){const n={method:ic(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await No(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Ir.connection_stalled)}return Ds(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:ic(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await No(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(Ir.connection_stalled)}}rpcUnsubscribe(e,r,n){const i={method:ic(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,yh(Jo({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Jo({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r))}addSubscription(e,r){this.subscriptions.set(e,Jo({},r)),this.topicMap.set(r.topic,e),this.events.emit(Tn.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(Tn.deleted,yh(Jo({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Tn.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<e;r++){const n=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}}this.events.emit(Tn.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;const r=await this.rpcBatchSubscribe(e);Pn(r)&&this.onBatchSubscribe(r.map((n,i)=>yh(Jo({},e[i]),{id:n})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(Ns.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(Ir.connect,async()=>{await this.onConnect()}),this.relayer.on(Ir.disconnect,()=>{this.onDisconnect()}),this.events.on(Tn.created,async e=>{const r=Tn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(Tn.deleted,async e=>{const r=Tn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}}var o7=Object.defineProperty,fg=Object.getOwnPropertySymbols,a7=Object.prototype.hasOwnProperty,c7=Object.prototype.propertyIsEnumerable,dg=(t,e,r)=>e in t?o7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,l7=(t,e)=>{for(var r in e||(e={}))a7.call(e,r)&&dg(t,r,e[r]);if(fg)for(var r of fg(e))c7.call(e,r)&&dg(t,r,e[r]);return t};class u7 extends j4{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new yr.exports.EventEmitter,this.name=RE,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(n){throw this.logger.debug("Failed to Publish Request"),this.logger.error(n),n}},this.onPayloadHandler=r=>{this.onProviderPayload(r)},this.onConnectHandler=()=>{this.events.emit(Ir.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(Ir.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(Gn.payload,this.onPayloadHandler),this.provider.on(Gn.connect,this.onConnectHandler),this.provider.on(Gn.disconnect,this.onDisconnectHandler),this.provider.on(Gn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?pt.generateChildLogger(e.logger,this.name):pt.pino(pt.getDefaultLoggerOptions({level:e.logger||TE})),this.messages=new JE(this.logger,e.core),this.subscriber=new s7(this,this.logger),this.publisher=new QE(this,this.logger),this.relayUrl=e?.relayUrl||ag,this.projectId=e.projectId,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 ${cg}...`),await this.restartTransport(cg)}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)},UE)}get context(){return pt.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"";return i||(await Promise.all([new Promise(o=>{this.subscriber.once(Tn.created,c=>{c.topic===e&&o()})}),new Promise(async o=>{i=await this.subscriber.subscribe(e,r),o()})]),i)}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportClose(){this.transportExplicitlyClosed=!0,this.hasExperiencedNetworkDisruption&&this.connected?await No(this.provider.disconnect(),1e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.connected&&await this.provider.disconnect()}async transportOpen(e){if(this.transportExplicitlyClosed=!1,await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress){e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportClose(),await this.createProvider()),this.connectionAttemptInProgress=!0;try{await Promise.all([new Promise(r=>{if(!this.initialized)return r();this.subscriber.once(Tn.resubscribed,()=>{r()})}),new Promise(async(r,n)=>{try{await No(this.provider.connect(),1e4,`Socket stalled when trying to connect to ${this.relayUrl}`)}catch(i){n(i);return}r()})])}catch(r){this.logger.error(r);const n=r;if(!this.isConnectionStalled(n.message))throw r;this.provider.events.emit(Gn.disconnect)}finally{this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1}}}async restartTransport(e){await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Z1())throw new Error("No internet connection detected. Please restart your network and try again.")}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Kn(new G_(gb({sdkVersion:ME,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;const i=this.messages.has(r,n);return i&&this.logger.debug(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),fh(e)){if(!e.method.endsWith(NE))return;const r=e.params,{topic:n,message:i,publishedAt:o}=r.data,c={topic:n,message:i,publishedAt:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(l7({type:"event",event:r.id},c)),this.events.emit(r.id,c),await this.acknowledgePayload(e),await this.onMessageEvent(c)}else fc(e)&&this.events.emit(Ir.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Ir.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=hh(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Gn.payload,this.onPayloadHandler),this.provider.off(Gn.connect,this.onConnectHandler),this.provider.off(Gn.disconnect,this.onDisconnectHandler),this.provider.off(Gn.error,this.onProviderErrorHandler)}async registerEventListeners(){this.events.on(Ir.connection_stalled,()=>{this.restartTransport().catch(r=>this.logger.error(r))});let e=await Z1();a6(async r=>{this.initialized&&e!==r&&(e=r,r?await this.restartTransport().catch(n=>this.logger.error(n)):(this.hasExperiencedNetworkDisruption=!0,await this.transportClose().catch(n=>this.logger.error(n))))})}onProviderDisconnect(){this.events.emit(Ir.disconnect),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||(this.logger.info("attemptToReconnect called. Connecting..."),setTimeout(async()=>{await this.restartTransport().catch(e=>this.logger.error(e))},Te.toMiliseconds(LE)))}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectionAttemptInProgress)return await new Promise(e=>{const r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)});await this.restartTransport()}}}var h7=Object.defineProperty,pg=Object.getOwnPropertySymbols,f7=Object.prototype.hasOwnProperty,d7=Object.prototype.propertyIsEnumerable,gg=(t,e,r)=>e in t?h7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,mg=(t,e)=>{for(var r in e||(e={}))f7.call(e,r)&&gg(t,r,e[r]);if(pg)for(var r of pg(e))d7.call(e,r)&&gg(t,r,e[r]);return t};class gc extends F4{constructor(e,r,n,i=gi,o=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=jE,this.cached=[],this.initialized=!1,this.storagePrefix=gi,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(c=>{this.getKey&&c!==null&&!Pr(c)?this.map.set(this.getKey(c),c):jb(c)?this.map.set(c.id,c):Fb(c)&&this.map.set(c.topic,c)}),this.cached=[],this.initialized=!0)},this.set=async(c,l)=>{this.isInitialized(),this.map.has(c)?await this.update(c,l):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:c,value:l}),this.map.set(c,l),await this.persist())},this.get=c=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:c}),this.getData(c)),this.getAll=c=>(this.isInitialized(),c?this.values.filter(l=>Object.keys(c).every(h=>Z_(l[h],c[h]))):this.values),this.update=async(c,l)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:c,update:l});const h=mg(mg({},this.getData(c)),l);this.map.set(c,h),await this.persist()},this.delete=async(c,l)=>{this.isInitialized(),this.map.has(c)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:c,reason:l}),this.map.delete(c),await this.persist())},this.logger=pt.generateChildLogger(r,this.name),this.storagePrefix=i,this.getKey=o}get context(){return pt.getLoggerContext(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(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){const{message:n}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class p7{constructor(e,r){this.core=e,this.logger=r,this.name=WE,this.version=zE,this.events=new yr.exports,this.initialized=!1,this.storagePrefix=gi,this.ignoredPayloadTypes=[zi],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:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async()=>{this.isInitialized();const n=Uu(),i=await this.core.crypto.setSymKey(n),o=En(Te.FIVE_MINUTES),c={protocol:og},l={topic:i,expiry:o,relay:c,active:!1},h=Ab({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:n,relay:c});return await this.pairings.set(i,l),await this.core.relayer.subscribe(i),this.core.expirer.set(i,o),{topic:i,uri:h}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);const{topic:i,symKey:o,relay:c}=Ib(n.uri);let l;if(this.pairings.keys.includes(i)&&(l=this.pairings.get(i),l.active))throw new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);this.core.crypto.keychain.has(i)||(await this.core.crypto.setSymKey(o,i),await this.core.relayer.subscribe(i,{relay:c}));const h=En(Te.FIVE_MINUTES),f={topic:i,relay:c,expiry:h,active:!1};return await this.pairings.set(i,f),this.core.expirer.set(i,h),n.activatePairing&&await this.activate({topic:i}),this.events.emit(Yo.create,f),f},this.activate=async({topic:n})=>{this.isInitialized();const i=En(Te.THIRTY_DAYS);await this.pairings.update(n,{active:!0,expiry:i}),this.core.expirer.set(n,i)},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);const{topic:i}=n;if(this.pairings.keys.includes(i)){const o=await this.sendRequest(i,"wc_pairingPing",{}),{done:c,resolve:l,reject:h}=$s();this.events.once(tr("pairing_ping",o),({error:f})=>{f?h(f):l()}),await c()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",Yt("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,o)=>{const c=Ls(i,o),l=await this.core.crypto.encode(n,c),h=Zo[i].req;return this.core.history.set(n,c),this.core.relayer.publish(n,l,h),c.id},this.sendResult=async(n,i,o)=>{const c=hh(n,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,n),f=Zo[h.request.method].res;await this.core.relayer.publish(i,l,f),await this.core.history.resolve(c)},this.sendError=async(n,i,o)=>{const c=hc(n,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,n),f=Zo[h.request.method]?Zo[h.request.method].res:Zo.unregistered_method.res;await this.core.relayer.publish(i,l,f),await this.core.history.resolve(c)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Yt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{const n=this.pairings.getAll().filter(i=>pi(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{const{topic:i,payload:o}=n;switch(o.method){case"wc_pairingPing":return this.onPairingPingRequest(i,o);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,o);default:return this.onUnknownRpcMethodRequest(i,o)}},this.onRelayEventResponse=async n=>{const{topic:i,payload:o}=n,c=(await this.core.history.get(i,o.id)).request.method;switch(c){case"wc_pairingPing":return this.onPairingPingResponse(i,o);default:return this.onUnknownRpcMethodResponse(c)}},this.onPairingPingRequest=async(n,i)=>{const{id:o}=i;try{this.isValidPing({topic:n}),await this.sendResult(o,n,!0),this.events.emit(Yo.ping,{id:o,topic:n})}catch(c){await this.sendError(o,n,c),this.logger.error(c)}},this.onPairingPingResponse=(n,i)=>{const{id:o}=i;setTimeout(()=>{Vn(i)?this.events.emit(tr("pairing_ping",o),{}):xn(i)&&this.events.emit(tr("pairing_ping",o),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{const{id:o}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(Yo.delete,{id:o,topic:n})}catch(c){await this.sendError(o,n,c),this.logger.error(c)}},this.onUnknownRpcMethodRequest=async(n,i)=>{const{id:o,method:c}=i;try{if(this.registeredMethods.includes(c))return;const l=Yt("WC_METHOD_UNSUPPORTED",c);await this.sendError(o,n,l),this.logger.error(l)}catch(l){await this.sendError(o,n,l),this.logger.error(l)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(Yt("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{if(!Wr(n)){const{message:i}=_e("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(i)}if(!Ub(n.uri)){const{message:i}=_e("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(i)}},this.isValidPing=async n=>{if(!Wr(n)){const{message:o}=_e("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(o)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!Wr(n)){const{message:o}=_e("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(o)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!pr(n,!1)){const{message:i}=_e("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=_e("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(pi(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=_e("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=pt.generateChildLogger(r,this.name),this.pairings=new gc(this.core,this.logger,this.name,this.storagePrefix)}get context(){return pt.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Ir.message,async e=>{const{topic:r,message:n}=e;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;const i=await this.core.crypto.decode(r,n);try{fh(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):fc(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.core.history.delete(r,i.id))}catch(o){this.logger.error(o)}})}registerExpirerEvents(){this.core.expirer.on(cn.expired,async e=>{const{topic:r}=B1(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Yo.expire,{topic:r}))})}}class g7 extends L4{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new yr.exports.EventEmitter,this.name=qE,this.version=VE,this.cached=[],this.initialized=!1,this.storagePrefix=gi,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,o)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:o}),this.records.has(i.id))return;const c={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:o,expiry:En(Te.THIRTY_DAYS)};this.records.set(c.id,c),this.events.emit(Rn.created,c)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=xn(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.events.emit(Rn.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(o=>{if(o.topic===n){if(typeof i<"u"&&o.id!==i)return;this.records.delete(o.id),this.events.emit(Rn.deleted,o)}})},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=pt.generateChildLogger(r,this.name)}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:Ls(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:n}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Rn.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Rn.created,e=>{const r=Rn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(Rn.updated,e=>{const r=Rn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(Rn.deleted,e=>{const r=Rn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.core.heartbeat.on(Ns.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.records.forEach(e=>{Te.toMiliseconds(e.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${e.id}`),this.delete(e.topic,e.id))})}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class m7 extends k4{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new yr.exports.EventEmitter,this.name=KE,this.version=GE,this.cached=[],this.initialized=!1,this.storagePrefix=gi,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();const o=this.formatTarget(n),c={target:o,expiry:i};this.expirations.set(o,c),this.checkExpiry(o,c),this.events.emit(cn.created,{target:o,expiration:c})},this.get=n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),o=this.getExpiration(i);this.expirations.delete(i),this.events.emit(cn.deleted,{target:i,expiration:o})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=pt.generateChildLogger(r,this.name)}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return mb(e);if(typeof e=="number")return vb(e);const{message:r}=_e("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(cn.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:n}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;Te.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(cn.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Ns.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(cn.created,e=>{const r=cn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(cn.expired,e=>{const r=cn.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(cn.deleted,e=>{const r=cn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class v7 extends H4{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=wh,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async n=>{if(this.verifyDisabled||Po()||!To())return;const i=n?.verifyUrl||pc;this.verifyUrl!==i&&this.removeIframe(),this.verifyUrl=i;try{await this.createIframe()}catch(o){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(o)}if(!this.initialized){this.removeIframe(),this.verifyUrl=lg;try{await this.createIframe()}catch(o){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(o),this.verifyDisabled=!0}}},this.register=async n=>{this.initialized?this.sendPost(n.attestationId):(this.addToQueue(n.attestationId),await this.init())},this.resolve=async n=>{if(this.isDevEnv)return"";const i=n?.verifyUrl||pc;let o;try{o=await this.fetchAttestation(n.attestationId,i)}catch(c){this.logger.info(`failed to resolve attestation: ${n.attestationId} from url: ${i}`),this.logger.info(c),o=await this.fetchAttestation(n.attestationId,lg)}return o},this.fetchAttestation=async(n,i)=>{this.logger.info(`resolving attestation: ${n} from url: ${i}`);const o=this.startAbortTimer(Te.ONE_SECOND*2),c=await fetch(`${i}/attestation/${n}`,{signal:this.abortController.signal});return clearTimeout(o),c.status===200?await c.json():void 0},this.addToQueue=n=>{this.queue.push(n)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(n=>this.sendPost(n)),this.queue=[])},this.sendPost=n=>{var i;try{if(!this.iframe)return;(i=this.iframe.contentWindow)==null||i.postMessage(n,"*"),this.logger.info(`postMessage sent: ${n} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let n;const i=o=>{o.data==="verify_ready"&&(this.initialized=!0,this.processQueue(),window.removeEventListener("message",i),n())};await Promise.race([new Promise(o=>{if(document.getElementById(wh))return o();window.addEventListener("message",i);const c=document.createElement("iframe");c.id=wh,c.src=`${this.verifyUrl}/${this.projectId}`,c.style.display="none",document.body.append(c),this.iframe=c,n=o}),new Promise((o,c)=>setTimeout(()=>{window.removeEventListener("message",i),c("verify iframe load timeout")},Te.toMiliseconds(Te.FIVE_SECONDS)))])},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.logger=pt.generateChildLogger(r,this.name),this.verifyUrl=pc,this.abortController=new AbortController,this.isDevEnv=ju()&&process.env.IS_VITEST}get context(){return pt.getLoggerContext(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),Te.toMiliseconds(e))}}var w7=Object.defineProperty,vg=Object.getOwnPropertySymbols,y7=Object.prototype.hasOwnProperty,b7=Object.prototype.propertyIsEnumerable,wg=(t,e,r)=>e in t?w7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yg=(t,e)=>{for(var r in e||(e={}))y7.call(e,r)&&wg(t,r,e[r]);if(vg)for(var r of vg(e))b7.call(e,r)&&wg(t,r,e[r]);return t};class bh extends N4{constructor(e){super(e),this.protocol=ig,this.version=_E,this.name=vh,this.events=new yr.exports.EventEmitter,this.initialized=!1,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||ag,this.customStoragePrefix=e?.customStoragePrefix||"";const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||EE.logger}));this.logger=pt.generateChildLogger(r,this.name),this.heartbeat=new Ns.HeartBeat,this.crypto=new YE(this,this.logger,e?.keychain),this.history=new g7(this,this.logger),this.expirer=new m7(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new j6(yg(yg({},xE),e?.storageOptions)),this.relayer=new u7({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new p7(this,this.logger),this.verify=new v7(this.projectId||"",this.logger)}static async init(e){const r=new bh(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(FE,n),r}get context(){return pt.getLoggerContext(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(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const _7=bh,bg="wc",_g=2,Eg="client",_h=`${bg}@${_g}:${Eg}:`,Eh={name:Eg,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},xg="WALLETCONNECT_DEEPLINK_CHOICE",E7="proposal",Cg="Proposal expired",x7="session",mc=Te.SEVEN_DAYS,C7="engine",Qo={wc_sessionPropose:{req:{ttl:Te.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Te.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:Te.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Te.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Te.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Te.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Te.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Te.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Te.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Te.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Te.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Te.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Te.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Te.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Te.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:Te.THIRTY_SECONDS,prompt:!1,tag:1115}}},xh={min:Te.FIVE_MINUTES,max:Te.SEVEN_DAYS},Zn={idle:"IDLE",active:"ACTIVE"},I7="request",S7=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var O7=Object.defineProperty,A7=Object.defineProperties,D7=Object.getOwnPropertyDescriptors,Ig=Object.getOwnPropertySymbols,$7=Object.prototype.hasOwnProperty,P7=Object.prototype.propertyIsEnumerable,Sg=(t,e,r)=>e in t?O7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zr=(t,e)=>{for(var r in e||(e={}))$7.call(e,r)&&Sg(t,r,e[r]);if(Ig)for(var r of Ig(e))P7.call(e,r)&&Sg(t,r,e[r]);return t},Xo=(t,e)=>A7(t,D7(e));class T7 extends z4{constructor(e){super(e),this.name=C7,this.events=new yr.exports,this.initialized=!1,this.ignoredPayloadTypes=[zi],this.requestQueue={state:Zn.idle,queue:[]},this.sessionRequestQueue={state:Zn.idle,queue:[]},this.requestQueueDelay=Te.ONE_SECOND,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(Qo)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},Te.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{await this.isInitialized();const n=Xo(zr({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:o,optionalNamespaces:c,sessionProperties:l,relays:h}=n;let f=i,w,E=!1;if(f&&(E=this.client.core.pairing.pairings.get(f).active),!f||!E){const{topic:L,uri:$}=await this.client.core.pairing.create();f=L,w=$}const _=await this.client.core.crypto.generateKeyPair(),S=zr({requiredNamespaces:o,optionalNamespaces:c,relays:h??[{protocol:og}],proposer:{publicKey:_,metadata:this.client.metadata}},l&&{sessionProperties:l}),{reject:P,resolve:j,done:H}=$s(Te.FIVE_MINUTES,Cg);if(this.events.once(tr("session_connect"),async({error:L,session:$})=>{if(L)P(L);else if($){$.self.publicKey=_;const T=Xo(zr({},$),{requiredNamespaces:$.requiredNamespaces,optionalNamespaces:$.optionalNamespaces});await this.client.session.set($.topic,T),await this.setExpiry($.topic,$.expiry),f&&await this.client.core.pairing.updateMetadata({topic:f,metadata:$.peer.metadata}),j(T)}}),!f){const{message:L}=_e("NO_MATCHING_KEY",`connect() pairing topic: ${f}`);throw new Error(L)}const Z=await this.sendRequest({topic:f,method:"wc_sessionPropose",params:S}),N=En(Te.FIVE_MINUTES);return await this.setProposal(Z,zr({id:Z,expiry:N},S)),{uri:w,approval:H}},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:n,relayProtocol:i,namespaces:o,sessionProperties:c}=r,l=this.client.proposal.get(n);let{pairingTopic:h,proposer:f,requiredNamespaces:w,optionalNamespaces:E}=l;h=h||"",Ts(w)||(w=Tb(o,"approve()"));const _=await this.client.core.crypto.generateKeyPair(),S=f.publicKey,P=await this.client.core.crypto.generateSharedKey(_,S);h&&n&&(await this.client.core.pairing.updateMetadata({topic:h,metadata:f.metadata}),await this.sendResult({id:n,topic:h,result:{relay:{protocol:i??"irn"},responderPublicKey:_}}),await this.client.proposal.delete(n,Yt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:h}));const j=zr({relay:{protocol:i??"irn"},namespaces:o,requiredNamespaces:w,optionalNamespaces:E,pairingTopic:h,controller:{publicKey:_,metadata:this.client.metadata},expiry:En(mc)},c&&{sessionProperties:c});await this.client.core.relayer.subscribe(P),await this.sendRequest({topic:P,method:"wc_sessionSettle",params:j,throwOnFailedPublish:!0});const H=Xo(zr({},j),{topic:P,pairingTopic:h,acknowledged:!1,self:j.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:_});return await this.client.session.set(P,H),await this.setExpiry(P,En(mc)),{topic:P,acknowledged:()=>new Promise(Z=>setTimeout(()=>Z(this.client.session.get(P)),500))}},this.reject=async r=>{await this.isInitialized(),await this.isValidReject(r);const{id:n,reason:i}=r,{pairingTopic:o}=this.client.proposal.get(n);o&&(await this.sendError(n,o,i),await this.client.proposal.delete(n,Yt("USER_DISCONNECTED")))},this.update=async r=>{await this.isInitialized(),await this.isValidUpdate(r);const{topic:n,namespaces:i}=r,o=await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i}}),{done:c,resolve:l,reject:h}=$s();return this.events.once(tr("session_update",o),({error:f})=>{f?h(f):l()}),await this.client.session.update(n,{namespaces:i}),{acknowledged:c}},this.extend=async r=>{await this.isInitialized(),await this.isValidExtend(r);const{topic:n}=r,i=await this.sendRequest({topic:n,method:"wc_sessionExtend",params:{}}),{done:o,resolve:c,reject:l}=$s();return this.events.once(tr("session_extend",i),({error:h})=>{h?l(h):c()}),await this.setExpiry(n,En(mc)),{acknowledged:o}},this.request=async r=>{await this.isInitialized(),await this.isValidRequest(r);const{chainId:n,request:i,topic:o,expiry:c}=r,l=uh(),{done:h,resolve:f,reject:w}=$s(c);return this.events.once(tr("session_request",l),({error:E,result:_})=>{E?w(E):f(_)}),await Promise.all([new Promise(async E=>{await this.sendRequest({clientRpcId:l,topic:o,method:"wc_sessionRequest",params:{request:i,chainId:n},expiry:c,throwOnFailedPublish:!0}).catch(_=>w(_)),this.client.events.emit("session_request_sent",{topic:o,request:i,chainId:n,id:l}),E()}),new Promise(async E=>{const _=await this.client.core.storage.getItem(xg);wb({id:l,topic:o,wcDeepLink:_}),E()}),h()]).then(E=>E[2])},this.respond=async r=>{await this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:o}=i;Vn(i)?await this.sendResult({id:o,topic:n,result:i.result,throwOnFailedPublish:!0}):xn(i)&&await this.sendError(o,n,i.error),this.cleanupAfterResponse(r)},this.ping=async r=>{await this.isInitialized(),await this.isValidPing(r);const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=await this.sendRequest({topic:n,method:"wc_sessionPing",params:{}}),{done:o,resolve:c,reject:l}=$s();this.events.once(tr("session_ping",i),({error:h})=>{h?l(h):c()}),await o()}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{await this.isInitialized(),await this.isValidEmit(r);const{topic:n,event:i,chainId:o}=r;await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:o}})},this.disconnect=async r=>{await this.isInitialized(),await this.isValidDisconnect(r);const{topic:n}=r;this.client.session.keys.includes(n)?(await this.sendRequest({topic:n,method:"wc_sessionDelete",params:Yt("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession(n)):await this.client.core.pairing.disconnect({topic:n})},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>Lb(n,r))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{const n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(o=>{var c,l;return((c=o.peerMetadata)==null?void 0:c.url)&&((l=o.peerMetadata)==null?void 0:l.url)===r.peer.metadata.url&&o.topic&&o.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(o=>this.client.core.pairing.disconnect({topic:o.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async(r,n)=>{const{self:i}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),this.client.session.delete(r,Yt("USER_DISCONNECTED")),this.client.core.crypto.keychain.has(i.publicKey)&&await this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(xg).catch(o=>this.client.logger.warn(o))},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,Yt("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(o=>o.id!==r),i&&(this.sessionRequestQueue.state=Zn.idle)},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:n}),this.client.core.expirer.set(r,n)},this.setProposal=async(r,n)=>{await this.client.proposal.set(r,n),this.client.core.expirer.set(r,n.expiry)},this.setPendingSessionRequest=async r=>{const n=Qo.wc_sessionRequest.req.ttl,{id:i,topic:o,params:c,verifyContext:l}=r;await this.client.pendingRequest.set(i,{id:i,topic:o,params:c,verifyContext:l}),n&&this.client.core.expirer.set(i,En(n))},this.sendRequest=async r=>{const{topic:n,method:i,params:o,expiry:c,relayRpcId:l,clientRpcId:h,throwOnFailedPublish:f}=r,w=Ls(i,o,h);if(To()&&S7.includes(i)){const S=Ds(JSON.stringify(w));this.client.core.verify.register({attestationId:S})}const E=await this.client.core.crypto.encode(n,w),_=Qo[i].req;return c&&(_.ttl=c),l&&(_.id=l),this.client.core.history.set(n,w),f?(_.internal=Xo(zr({},_.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,E,_)):this.client.core.relayer.publish(n,E,_).catch(S=>this.client.logger.error(S)),w.id},this.sendResult=async r=>{const{id:n,topic:i,result:o,throwOnFailedPublish:c}=r,l=hh(n,o),h=await this.client.core.crypto.encode(i,l),f=await this.client.core.history.get(i,n),w=Qo[f.request.method].res;c?(w.internal=Xo(zr({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,h,w)):this.client.core.relayer.publish(i,h,w).catch(E=>this.client.logger.error(E)),await this.client.core.history.resolve(l)},this.sendError=async(r,n,i)=>{const o=hc(r,i),c=await this.client.core.crypto.encode(n,o),l=await this.client.core.history.get(n,r),h=Qo[l.request.method].res;this.client.core.relayer.publish(n,c,h),await this.client.core.history.resolve(o)},this.cleanup=async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{pi(i.expiry)&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{pi(i.expiry)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession(i)),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===Zn.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=Zn.active;const r=this.requestQueue.queue.shift();if(r)try{this.processRequest(r),await new Promise(n=>setTimeout(n,300))}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Zn.idle},this.processRequest=r=>{const{topic:n,payload:i}=r,o=i.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${o}`)}},this.onRelayEventResponse=async r=>{const{topic:n,payload:i}=r,o=(await this.client.core.history.get(n,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}},this.onRelayEventUnknownPayload=r=>{const{topic:n}=r,{message:i}=_e("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.onSessionProposeRequest=async(r,n)=>{const{params:i,id:o}=n;try{this.isValidConnect(zr({},n.params));const c=En(Te.FIVE_MINUTES),l=zr({id:o,pairingTopic:r,expiry:c},i);await this.setProposal(o,l);const h=Ds(JSON.stringify(n)),f=await this.getVerifyContext(h,l.proposer.metadata);this.client.events.emit("session_proposal",{id:o,params:l,verifyContext:f})}catch(c){await this.sendError(o,r,c),this.client.logger.error(c)}},this.onSessionProposeResponse=async(r,n)=>{const{id:i}=n;if(Vn(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const c=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:c});const l=c.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:l});const h=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const f=await this.client.core.crypto.generateSharedKey(l,h);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:f});const w=await this.client.core.relayer.subscribe(f);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:w}),await this.client.core.pairing.activate({topic:r})}else xn(n)&&(await this.client.proposal.delete(i,Yt("USER_DISCONNECTED")),this.events.emit(tr("session_connect"),{error:n.error}))},this.onSessionSettleRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidSessionSettleRequest(o);const{relay:c,controller:l,expiry:h,namespaces:f,requiredNamespaces:w,optionalNamespaces:E,sessionProperties:_,pairingTopic:S}=n.params,P=zr({topic:r,relay:c,expiry:h,namespaces:f,acknowledged:!0,pairingTopic:S,requiredNamespaces:w,optionalNamespaces:E,controller:l.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:l.publicKey,metadata:l.metadata}},_&&{sessionProperties:_});await this.sendResult({id:n.id,topic:r,result:!0}),this.events.emit(tr("session_connect"),{session:P}),this.cleanupDuplicatePairings(P)}catch(c){await this.sendError(i,r,c),this.client.logger.error(c)}},this.onSessionSettleResponse=async(r,n)=>{const{id:i}=n;Vn(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(tr("session_approve",i),{})):xn(n)&&(await this.client.session.delete(r,Yt("USER_DISCONNECTED")),this.events.emit(tr("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{const{params:i,id:o}=n;try{const c=`${r}_session_update`,l=ac.get(c);if(l&&this.isRequestOutOfSync(l,o)){this.client.logger.info(`Discarding out of sync request - ${o}`);return}this.isValidUpdate(zr({topic:r},i)),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:o,topic:r,result:!0}),this.client.events.emit("session_update",{id:o,topic:r,params:i}),ac.set(c,o)}catch(c){await this.sendError(o,r,c),this.client.logger.error(c)}},this.isRequestOutOfSync=(r,n)=>parseInt(n.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,n)=>{const{id:i}=n;Vn(n)?this.events.emit(tr("session_update",i),{}):xn(n)&&this.events.emit(tr("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,En(mc)),await this.sendResult({id:i,topic:r,result:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionExtendResponse=(r,n)=>{const{id:i}=n;Vn(n)?this.events.emit(tr("session_extend",i),{}):xn(n)&&this.events.emit(tr("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionPingResponse=(r,n)=>{const{id:i}=n;setTimeout(()=>{Vn(n)?this.events.emit(tr("session_ping",i),{}):xn(n)&&this.events.emit(tr("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(o=>{this.client.core.relayer.once(Ir.publish,async()=>{o(await this.deleteSession(r))})}),this.sendResult({id:i,topic:r,result:!0})]),this.client.events.emit("session_delete",{id:i,topic:r})}catch(o){this.client.logger.error(o)}},this.onSessionRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidRequest(zr({topic:r},o));const c=Ds(JSON.stringify(Ls("wc_sessionRequest",o,i))),l=this.client.session.get(r),h=await this.getVerifyContext(c,l.peer.metadata),f={id:i,topic:r,params:o,verifyContext:h};await this.setPendingSessionRequest(f),this.addSessionRequestToSessionRequestQueue(f),this.processSessionRequestQueue()}catch(c){await this.sendError(i,r,c),this.client.logger.error(c)}},this.onSessionRequestResponse=(r,n)=>{const{id:i}=n;Vn(n)?this.events.emit(tr("session_request",i),{result:n.result}):xn(n)&&this.events.emit(tr("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{const{id:i,params:o}=n;try{const c=`${r}_session_event_${o.event.name}`,l=ac.get(c);if(l&&this.isRequestOutOfSync(l,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(zr({topic:r},o)),this.client.events.emit("session_event",{id:i,topic:r,params:o}),ac.set(c,i)}catch(c){await this.sendError(i,r,c),this.client.logger.error(c)}},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Zn.idle,this.processSessionRequestQueue()},Te.toMiliseconds(this.requestQueueDelay))},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===Zn.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=Zn.active,this.client.events.emit("session_request",r)}catch(n){this.client.logger.error(n)}},this.onPairingCreated=r=>{if(r.active)return;const n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest(r.topic,Ls("wc_sessionPropose",{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer},n.id))},this.isValidConnect=async r=>{if(!Wr(r)){const{message:h}=_e("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(h)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:c,relays:l}=r;if(Pr(n)||await this.isValidPairingTopic(n),!Kb(l,!0)){const{message:h}=_e("MISSING_OR_INVALID",`connect() relays: ${l}`);throw new Error(h)}!Pr(i)&&Ts(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Pr(o)&&Ts(o)!==0&&this.validateNamespaces(o,"optionalNamespaces"),Pr(c)||this.validateSessionProps(c,"sessionProperties")},this.validateNamespaces=(r,n)=>{const i=Vb(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!Wr(r))throw new Error(_e("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:o,sessionProperties:c}=r;await this.isValidProposalId(n);const l=this.client.proposal.get(n),h=oc(i,"approve()");if(h)throw new Error(h.message);const f=K1(l.requiredNamespaces,i,"approve()");if(f)throw new Error(f.message);if(!pr(o,!0)){const{message:w}=_e("MISSING_OR_INVALID",`approve() relayProtocol: ${o}`);throw new Error(w)}Pr(c)||this.validateSessionProps(c,"sessionProperties")},this.isValidReject=async r=>{if(!Wr(r)){const{message:o}=_e("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(o)}const{id:n,reason:i}=r;if(await this.isValidProposalId(n),!Zb(i)){const{message:o}=_e("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidSessionSettleRequest=r=>{if(!Wr(r)){const{message:f}=_e("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(f)}const{relay:n,controller:i,namespaces:o,expiry:c}=r;if(!q1(n)){const{message:f}=_e("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(f)}const l=Bb(i,"onSessionSettleRequest()");if(l)throw new Error(l.message);const h=oc(o,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(pi(c)){const{message:f}=_e("EXPIRED","onSessionSettleRequest()");throw new Error(f)}},this.isValidUpdate=async r=>{if(!Wr(r)){const{message:h}=_e("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(h)}const{topic:n,namespaces:i}=r;await this.isValidSessionTopic(n);const o=this.client.session.get(n),c=oc(i,"update()");if(c)throw new Error(c.message);const l=K1(o.requiredNamespaces,i,"update()");if(l)throw new Error(l.message)},this.isValidExtend=async r=>{if(!Wr(r)){const{message:i}=_e("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!Wr(r)){const{message:h}=_e("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(h)}const{topic:n,request:i,chainId:o,expiry:c}=r;await this.isValidSessionTopic(n);const{namespaces:l}=this.client.session.get(n);if(!V1(l,o)){const{message:h}=_e("MISSING_OR_INVALID",`request() chainId: ${o}`);throw new Error(h)}if(!Yb(i)){const{message:h}=_e("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(h)}if(!Xb(l,o,i.method)){const{message:h}=_e("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(h)}if(c&&!n6(c,xh)){const{message:h}=_e("MISSING_OR_INVALID",`request() expiry: ${c}. Expiry must be a number (in seconds) between ${xh.min} and ${xh.max}`);throw new Error(h)}},this.isValidRespond=async r=>{if(!Wr(r)){const{message:o}=_e("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:n,response:i}=r;if(await this.isValidSessionTopic(n),!Jb(i)){const{message:o}=_e("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidPing=async r=>{if(!Wr(r)){const{message:i}=_e("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!Wr(r)){const{message:l}=_e("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(l)}const{topic:n,event:i,chainId:o}=r;await this.isValidSessionTopic(n);const{namespaces:c}=this.client.session.get(n);if(!V1(c,o)){const{message:l}=_e("MISSING_OR_INVALID",`emit() chainId: ${o}`);throw new Error(l)}if(!Qb(i)){const{message:l}=_e("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}if(!e6(c,o,i.name)){const{message:l}=_e("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}},this.isValidDisconnect=async r=>{if(!Wr(r)){const{message:i}=_e("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.getVerifyContext=async(r,n)=>{const i={verified:{verifyUrl:n.verifyUrl||pc,validation:"UNKNOWN",origin:n.url||""}};try{const o=await this.client.core.verify.resolve({attestationId:r,verifyUrl:n.verifyUrl});o&&(i.verified.origin=o.origin,i.verified.isScam=o.isScam,i.verified.validation=o.origin===new URL(n.url).origin?"VALID":"INVALID")}catch(o){this.client.logger.info(o)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!pr(i,!1)){const{message:o}=_e("MISSING_OR_INVALID",`${n} must be in Record<string, string> format. Received: ${JSON.stringify(i)}`);throw new Error(o)}})}}async isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ir.message,async e=>{const{topic:r,message:n}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(n)))return;const i=await this.client.core.crypto.decode(r,n);try{fh(i)?(this.client.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):fc(i)?(await this.client.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.client.core.history.delete(r,i.id)):this.onRelayEventUnknownPayload({topic:r,payload:i})}catch(o){this.client.logger.error(o)}})}registerExpirerEvents(){this.client.core.expirer.on(cn.expired,async e=>{const{topic:r,id:n}=B1(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,_e("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession(r,!0),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(Yo.create,e=>this.onPairingCreated(e))}isValidPairingTopic(e){if(!pr(e,!1)){const{message:r}=_e("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=_e("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(pi(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=_e("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!pr(e,!1)){const{message:r}=_e("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(!this.client.session.keys.includes(e)){const{message:r}=_e("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(pi(this.client.session.get(e).expiry)){await this.deleteSession(e);const{message:r}=_e("EXPIRED",`session topic: ${e}`);throw new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(pr(e,!1)){const{message:r}=_e("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=_e("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!Gb(e)){const{message:r}=_e("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=_e("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(pi(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:r}=_e("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class R7 extends gc{constructor(e,r){super(e,r,E7,_h),this.core=e,this.logger=r}}class N7 extends gc{constructor(e,r){super(e,r,x7,_h),this.core=e,this.logger=r}}class L7 extends gc{constructor(e,r){super(e,r,I7,_h,n=>n.id),this.core=e,this.logger=r}}class Ch extends W4{constructor(e){super(e),this.protocol=bg,this.version=_g,this.name=Eh.name,this.events=new yr.exports.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.name=e?.name||Eh.name,this.metadata=e?.metadata||hb();const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||Eh.logger}));this.core=e?.core||new _7(e),this.logger=pt.generateChildLogger(r,this.name),this.session=new N7(this.core,this.logger),this.proposal=new R7(this.core,this.logger),this.pendingRequest=new L7(this.core,this.logger),this.engine=new T7(this)}static async init(e){const r=new Ch(e);return await r.initialize(),r}get context(){return pt.getLoggerContext(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(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var Ih={exports:{}};(function(t,e){var r=typeof self<"u"?self:dr,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(c){var l={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function h(O){return O&&DataView.prototype.isPrototypeOf(O)}if(l.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],w=ArrayBuffer.isView||function(O){return O&&f.indexOf(Object.prototype.toString.call(O))>-1};function E(O){if(typeof O!="string"&&(O=String(O)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(O))throw new TypeError("Invalid character in header field name");return O.toLowerCase()}function _(O){return typeof O!="string"&&(O=String(O)),O}function S(O){var U={next:function(){var ce=O.shift();return{done:ce===void 0,value:ce}}};return l.iterable&&(U[Symbol.iterator]=function(){return U}),U}function P(O){this.map={},O instanceof P?O.forEach(function(U,ce){this.append(ce,U)},this):Array.isArray(O)?O.forEach(function(U){this.append(U[0],U[1])},this):O&&Object.getOwnPropertyNames(O).forEach(function(U){this.append(U,O[U])},this)}P.prototype.append=function(O,U){O=E(O),U=_(U);var ce=this.map[O];this.map[O]=ce?ce+", "+U:U},P.prototype.delete=function(O){delete this.map[E(O)]},P.prototype.get=function(O){return O=E(O),this.has(O)?this.map[O]:null},P.prototype.has=function(O){return this.map.hasOwnProperty(E(O))},P.prototype.set=function(O,U){this.map[E(O)]=_(U)},P.prototype.forEach=function(O,U){for(var ce in this.map)this.map.hasOwnProperty(ce)&&O.call(U,this.map[ce],ce,this)},P.prototype.keys=function(){var O=[];return this.forEach(function(U,ce){O.push(ce)}),S(O)},P.prototype.values=function(){var O=[];return this.forEach(function(U){O.push(U)}),S(O)},P.prototype.entries=function(){var O=[];return this.forEach(function(U,ce){O.push([ce,U])}),S(O)},l.iterable&&(P.prototype[Symbol.iterator]=P.prototype.entries);function j(O){if(O.bodyUsed)return Promise.reject(new TypeError("Already read"));O.bodyUsed=!0}function H(O){return new Promise(function(U,ce){O.onload=function(){U(O.result)},O.onerror=function(){ce(O.error)}})}function Z(O){var U=new FileReader,ce=H(U);return U.readAsArrayBuffer(O),ce}function N(O){var U=new FileReader,ce=H(U);return U.readAsText(O),ce}function L(O){for(var U=new Uint8Array(O),ce=new Array(U.length),le=0;le<U.length;le++)ce[le]=String.fromCharCode(U[le]);return ce.join("")}function $(O){if(O.slice)return O.slice(0);var U=new Uint8Array(O.byteLength);return U.set(new Uint8Array(O)),U.buffer}function T(){return this.bodyUsed=!1,this._initBody=function(O){this._bodyInit=O,O?typeof O=="string"?this._bodyText=O:l.blob&&Blob.prototype.isPrototypeOf(O)?this._bodyBlob=O:l.formData&&FormData.prototype.isPrototypeOf(O)?this._bodyFormData=O:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(O)?this._bodyText=O.toString():l.arrayBuffer&&l.blob&&h(O)?(this._bodyArrayBuffer=$(O.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(O)||w(O))?this._bodyArrayBuffer=$(O):this._bodyText=O=Object.prototype.toString.call(O):this._bodyText="",this.headers.get("content-type")||(typeof O=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):l.searchParams&&URLSearchParams.prototype.isPrototypeOf(O)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var O=j(this);if(O)return O;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?j(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(Z)}),this.text=function(){var O=j(this);if(O)return O;if(this._bodyBlob)return N(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(L(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},l.formData&&(this.formData=function(){return this.text().then(J)}),this.json=function(){return this.text().then(JSON.parse)},this}var I=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function d(O){var U=O.toUpperCase();return I.indexOf(U)>-1?U:O}function x(O,U){U=U||{};var ce=U.body;if(O instanceof x){if(O.bodyUsed)throw new TypeError("Already read");this.url=O.url,this.credentials=O.credentials,U.headers||(this.headers=new P(O.headers)),this.method=O.method,this.mode=O.mode,this.signal=O.signal,!ce&&O._bodyInit!=null&&(ce=O._bodyInit,O.bodyUsed=!0)}else this.url=String(O);if(this.credentials=U.credentials||this.credentials||"same-origin",(U.headers||!this.headers)&&(this.headers=new P(U.headers)),this.method=d(U.method||this.method||"GET"),this.mode=U.mode||this.mode||null,this.signal=U.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&ce)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(ce)}x.prototype.clone=function(){return new x(this,{body:this._bodyInit})};function J(O){var U=new FormData;return O.trim().split("&").forEach(function(ce){if(ce){var le=ce.split("="),re=le.shift().replace(/\+/g," "),ne=le.join("=").replace(/\+/g," ");U.append(decodeURIComponent(re),decodeURIComponent(ne))}}),U}function W(O){var U=new P,ce=O.replace(/\r?\n[\t ]+/g," ");return ce.split(/\r?\n/).forEach(function(le){var re=le.split(":"),ne=re.shift().trim();if(ne){var ae=re.join(":").trim();U.append(ne,ae)}}),U}T.call(x.prototype);function ee(O,U){U||(U={}),this.type="default",this.status=U.status===void 0?200:U.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in U?U.statusText:"OK",this.headers=new P(U.headers),this.url=U.url||"",this._initBody(O)}T.call(ee.prototype),ee.prototype.clone=function(){return new ee(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new P(this.headers),url:this.url})},ee.error=function(){var O=new ee(null,{status:0,statusText:""});return O.type="error",O};var de=[301,302,303,307,308];ee.redirect=function(O,U){if(de.indexOf(U)===-1)throw new RangeError("Invalid status code");return new ee(null,{status:U,headers:{location:O}})},c.DOMException=o.DOMException;try{new c.DOMException}catch{c.DOMException=function(U,ce){this.message=U,this.name=ce;var le=Error(U);this.stack=le.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function me(O,U){return new Promise(function(ce,le){var re=new x(O,U);if(re.signal&&re.signal.aborted)return le(new c.DOMException("Aborted","AbortError"));var ne=new XMLHttpRequest;function ae(){ne.abort()}ne.onload=function(){var ie={status:ne.status,statusText:ne.statusText,headers:W(ne.getAllResponseHeaders()||"")};ie.url="responseURL"in ne?ne.responseURL:ie.headers.get("X-Request-URL");var Ae="response"in ne?ne.response:ne.responseText;ce(new ee(Ae,ie))},ne.onerror=function(){le(new TypeError("Network request failed"))},ne.ontimeout=function(){le(new TypeError("Network request failed"))},ne.onabort=function(){le(new c.DOMException("Aborted","AbortError"))},ne.open(re.method,re.url,!0),re.credentials==="include"?ne.withCredentials=!0:re.credentials==="omit"&&(ne.withCredentials=!1),"responseType"in ne&&l.blob&&(ne.responseType="blob"),re.headers.forEach(function(ie,Ae){ne.setRequestHeader(Ae,ie)}),re.signal&&(re.signal.addEventListener("abort",ae),ne.onreadystatechange=function(){ne.readyState===4&&re.signal.removeEventListener("abort",ae)}),ne.send(typeof re._bodyInit>"u"?null:re._bodyInit)})}return me.polyfill=!0,o.fetch||(o.fetch=me,o.Headers=P,o.Request=x,o.Response=ee),c.Headers=P,c.Request=x,c.Response=ee,c.fetch=me,Object.defineProperty(c,"__esModule",{value:!0}),c})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(Ih,Ih.exports);var Og=Sv(Ih.exports);const Ag={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},Dg=10;class mi{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new yr.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!Np(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e,r){this.isAvailable||await this.register();try{const n=qo(e),o=await(await Og(this.url,Object.assign(Object.assign({},Ag),{body:n}))).json();this.onPayload({data:o})}catch(n){this.onError(e.id,n)}}async register(e=this.url){if(!Np(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",o=>{this.resetMaxListeners(),i(o)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));n()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=qo({id:1,jsonrpc:"2.0",method:"test",params:[]});await Og(e,Object.assign(Object.assign({},Ag),{body:r}))}this.onOpen()}catch(r){const n=this.parseError(r);throw this.events.emit("register_error",n),this.onClose(),n}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ih(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=hc(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return Op(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Dg&&this.events.setMaxListeners(Dg)}}const $g="error",M7="wss://relay.walletconnect.com",U7="wc",j7="universal_provider",Pg=`${U7}@2:${j7}:`,F7="https://rpc.walletconnect.com/v1/",Yn={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var ea=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Sh={exports:{}};/**
73
73
  * @license
74
74
  * Lodash <https://lodash.com/>
75
75
  * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>