@walletconnect/ethereum-provider 2.7.6 → 2.7.7

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 Yu=function(t,e){return Yu=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])},Yu(t,e)};function G4(t,e){Yu(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Ju=function(){return Ju=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},Ju.apply(this,arguments)};function Z4(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 Y4(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 J4(t,e){return function(r,n){e(r,n,t)}}function X4(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Q4(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(v){try{d(n.next(v))}catch(E){c(E)}}function h(v){try{d(n.throw(v))}catch(E){c(E)}}function d(v){v.done?o(v.value):i(v.value).then(l,h)}d((n=n.apply(t,e||[])).next())})}function e_(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(d){return function(v){return h([d,v])}}function h(d){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(o=d[0]&2?i.return:d[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,d[1])).done)return o;switch(i=0,o&&(d=[d[0]&2,o.value]),d[0]){case 0:case 1:o=d;break;case 4:return r.label++,{value:d[1],done:!1};case 5:r.label++,i=d[1],d=[0];continue;case 7:d=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(d[0]===6||d[0]===2)){r=0;continue}if(d[0]===3&&(!o||d[1]>o[0]&&d[1]<o[3])){r.label=d[1];break}if(d[0]===6&&r.label<o[1]){r.label=o[1],o=d;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(d);break}o[2]&&r.ops.pop(),r.trys.pop();continue}d=e.call(t,r)}catch(v){d=[6,v],i=0}finally{n=o=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}function t_(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function r_(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Xu(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 Ep(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 n_(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Ep(arguments[e]));return t}function i_(){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 Fo(t){return this instanceof Fo?(this.v=t,this):new Fo(t)}function s_(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(A){return new Promise(function(P,U){o.push([_,A,P,U])>1||l(_,A)})})}function l(_,A){try{h(n[_](A))}catch(P){E(o[0][3],P)}}function h(_){_.value instanceof Fo?Promise.resolve(_.value.v).then(d,v):E(o[0][2],_)}function d(_){l("next",_)}function v(_){l("throw",_)}function E(_,A){_(A),o.shift(),o.length&&l(o[0][0],o[0][1])}}function o_(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:Fo(t[i](c)),done:i==="return"}:o?o(c):c}:o}}function a_(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 Xu=="function"?Xu(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(d){o({value:d,done:l})},c)}}function c_(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function l_(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function u_(t){return t&&t.__esModule?t:{default:t}}function h_(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function f_(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 d_=Object.freeze({__proto__:null,__extends:G4,get __assign(){return Ju},__rest:Z4,__decorate:Y4,__param:J4,__metadata:X4,__awaiter:Q4,__generator:e_,__createBinding:t_,__exportStar:r_,__values:Xu,__read:Ep,__spread:n_,__spreadArrays:i_,__await:Fo,__asyncGenerator:s_,__asyncDelegator:o_,__asyncValues:a_,__makeTemplateObject:c_,__importStar:l_,__importDefault:u_,__classPrivateFieldGet:h_,__classPrivateFieldSet:f_}),p_=Mi(d_),Wn={},xp;function g_(){if(xp)return Wn;xp=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.isBrowserCryptoAvailable=Wn.getSubtleCrypto=Wn.getBrowerCrypto=void 0;function t(){return pr?.crypto||pr?.msCrypto||{}}Wn.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}Wn.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Wn.isBrowserCryptoAvailable=r,Wn}var qn={},Cp;function m_(){if(Cp)return qn;Cp=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=p_;e.__exportStar(g_(),t),e.__exportStar(m_(),t)})(_p);function Ip(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Op(t=6){return BigInt(Ip(t))}function tc(t,e,r){return{id:r||Ip(),jsonrpc:"2.0",method:t,params:e}}function Qu(t,e){return{id:t,jsonrpc:"2.0",result:e}}function rc(t,e,r){return{id:t,jsonrpc:"2.0",error:w_(e,r)}}function w_(t,e){return typeof t>"u"?yp(wp):(typeof t=="string"&&(t=Object.assign(Object.assign({},yp(Zu)),{message:t})),typeof e<"u"&&(t.data=e),V4(t.code)&&(t=K4(t.code)),t)}class v_{}class y_ extends v_{constructor(){super()}}class b_ extends y_{constructor(e){super()}}const __="^https?:",E_="^wss?:";function x_(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Ap(t,e){const r=x_(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Sp(t){return Ap(t,__)}function Dp(t){return Ap(t,E_)}function C_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function $p(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function eh(t){return $p(t)&&"method"in t}function nc(t){return $p(t)&&(Vn(t)||En(t))}function Vn(t){return"result"in t}function En(t){return"error"in t}class hi extends b_{constructor(e){super(e),this.events=new br.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(tc(e.method,e.params||[],e.id||Op().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=>{En(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),nc(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 Pp=10,I_=()=>typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:require("ws"),O_=()=>typeof window<"u",A_=I_();class S_{constructor(e){if(this.url=e,this.events=new br.exports.EventEmitter,this.registering=!1,!Dp(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(Uo(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!Dp(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=_p.isReactNative()?void 0:{rejectUnauthorized:!C_(e)},o=new A_(e,[],i);O_()?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"?Ku(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=rc(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return bp(e,r,"WS")}resetMaxListeners(){this.events.getMaxListeners()>Pp&&this.events.setMaxListeners(Pp)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for URL: ${this.url}`));return this.events.emit("register_error",r),r}}var th={exports:{}};(function(t,e){var r=200,n="__lodash_hash_undefined__",i=1,o=2,c=9007199254740991,l="[object Arguments]",h="[object Array]",d="[object AsyncFunction]",v="[object Boolean]",E="[object Date]",_="[object Error]",A="[object Function]",P="[object GeneratorFunction]",U="[object Map]",H="[object Number]",G="[object Null]",N="[object Object]",L="[object Promise]",$="[object Proxy]",T="[object RegExp]",I="[object Set]",f="[object String]",x="[object Symbol]",J="[object Undefined]",z="[object WeakMap]",ee="[object ArrayBuffer]",de="[object DataView]",me="[object Float32Array]",O="[object Float64Array]",j="[object Int8Array]",ce="[object Int16Array]",le="[object Int32Array]",re="[object Uint8Array]",ne="[object Uint8ClampedArray]",ae="[object Uint16Array]",ie="[object Uint32Array]",Se=/[\\^$.*+?()[\]{}|]/g,ge=/^\[object .+?Constructor\]$/,Fe=/^(?:0|[1-9]\d*)$/,ye={};ye[me]=ye[O]=ye[j]=ye[ce]=ye[le]=ye[re]=ye[ne]=ye[ae]=ye[ie]=!0,ye[l]=ye[h]=ye[ee]=ye[v]=ye[de]=ye[E]=ye[_]=ye[A]=ye[U]=ye[H]=ye[N]=ye[T]=ye[I]=ye[f]=ye[z]=!1;var Le=typeof pr=="object"&&pr&&pr.Object===Object&&pr,X=typeof self=="object"&&self&&self.Object===Object&&self,Y=Le||X||Function("return this")(),W=e&&!e.nodeType&&e,w=W&&!0&&t&&!t.nodeType&&t,F=w&&w.exports===W,we=F&&Le.process,ve=function(){try{return we&&we.binding&&we.binding("util")}catch{}}(),Me=ve&&ve.isTypedArray;function nt(R,q){for(var fe=-1,Ce=R==null?0:R.length,It=0,Xe=[];++fe<Ce;){var Tt=R[fe];q(Tt,fe,R)&&(Xe[It++]=Tt)}return Xe}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 Be(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 Ue=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,Q=RegExp("^"+m.call(D).replace(Se,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ee=F?Y.Buffer:void 0,Te=Y.Symbol,st=Y.Uint8Array,ht=b.propertyIsEnumerable,lt=Ue.splice,Ur=Te?Te.toStringTag:void 0,Jn=Object.getOwnPropertySymbols,Ii=Ee?Ee.isBuffer:void 0,ls=Ke(Object.keys,Object),Ht=Qr(Y,"DataView"),Lt=Qr(Y,"Map"),zt=Qr(Y,"Promise"),Wt=Qr(Y,"Set"),Ft=Qr(Y,"WeakMap"),Mt=Qr(Object,"create"),ir=Qn(Ht),sr=Qn(Lt),qt=Qn(zt),or=Qn(Wt),Vt=Qn(Ft),Jt=Te?Te.prototype:void 0,Kt=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 ar(){this.__data__=Mt?Mt(null):{},this.size=0}function cr(R){var q=this.has(R)&&delete this.__data__[R];return this.size-=q?1:0,q}function Ff(R){var q=this.__data__;if(Mt){var fe=q[R];return fe===n?void 0:fe}return D.call(q,R)?q[R]:void 0}function Bf(R){var q=this.__data__;return Mt?q[R]!==void 0:D.call(q,R)}function kf(R,q){var fe=this.__data__;return this.size+=this.has(R)?0:1,fe[R]=Mt&&q===void 0?n:q,this}Pt.prototype.clear=ar,Pt.prototype.delete=cr,Pt.prototype.get=Ff,Pt.prototype.has=Bf,Pt.prototype.set=kf;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 Hf(){this.__data__=[],this.size=0}function zf(R){var q=this.__data__,fe=us(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 Wf(R){var q=this.__data__,fe=us(q,R);return fe<0?void 0:q[fe][1]}function qf(R){return us(this.__data__,R)>-1}function Vf(R,q){var fe=this.__data__,Ce=us(fe,R);return Ce<0?(++this.size,fe.push([R,q])):fe[Ce][1]=q,this}fn.prototype.clear=Hf,fn.prototype.delete=zf,fn.prototype.get=Wf,fn.prototype.has=qf,fn.prototype.set=Vf;function Xn(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 Qs(){this.size=0,this.__data__={hash:new Pt,map:new(Lt||fn),string:new Pt}}function Kf(R){var q=Oi(this,R).delete(R);return this.size-=q?1:0,q}function eo(R){return Oi(this,R).get(R)}function Gf(R){return Oi(this,R).has(R)}function Zf(R,q){var fe=Oi(this,R),Ce=fe.size;return fe.set(R,q),this.size+=fe.size==Ce?0:1,this}Xn.prototype.clear=Qs,Xn.prototype.delete=Kf,Xn.prototype.get=eo,Xn.prototype.has=Gf,Xn.prototype.set=Zf;function to(R){var q=-1,fe=R==null?0:R.length;for(this.__data__=new Xn;++q<fe;)this.add(R[q])}function Zc(R){return this.__data__.set(R,n),this}function Yc(R){return this.__data__.has(R)}to.prototype.add=to.prototype.push=Zc,to.prototype.has=Yc;function xn(R){var q=this.__data__=new fn(R);this.size=q.size}function Yf(){this.__data__=new fn,this.size=0}function Jf(R){var q=this.__data__,fe=q.delete(R);return this.size=q.size,fe}function Xf(R){return this.__data__.get(R)}function Qf(R){return this.__data__.has(R)}function Jc(R,q){var fe=this.__data__;if(fe instanceof fn){var Ce=fe.__data__;if(!Lt||Ce.length<r-1)return Ce.push([R,q]),this.size=++fe.size,this;fe=this.__data__=new Xn(Ce)}return fe.set(R,q),this.size=fe.size,this}xn.prototype.clear=Yf,xn.prototype.delete=Jf,xn.prototype.get=Xf,xn.prototype.has=Qf,xn.prototype.set=Jc;function Xc(R,q){var fe=io(R),Ce=!fe&&ul(R),It=!fe&&!Ce&&ya(R),Xe=!fe&&!Ce&&!It&&dl(R),Tt=fe||Ce||It||Xe,lr=Tt?Dt(R.length,String):[],mt=lr.length;for(var Ot in R)(q||D.call(R,Ot))&&!(Tt&&(Ot=="length"||It&&(Ot=="offset"||Ot=="parent")||Xe&&(Ot=="buffer"||Ot=="byteLength"||Ot=="byteOffset")||sl(Ot,mt)))&&lr.push(Ot);return lr}function us(R,q){for(var fe=R.length;fe--;)if(ll(R[fe][0],q))return fe;return-1}function wa(R,q,fe){var Ce=q(R);return io(R)?Ce:at(Ce,fe(R))}function hs(R){return R==null?R===void 0?J:G:Ur&&Ur in Object(R)?nl(R):r0(R)}function va(R){return ds(R)&&hs(R)==l}function fs(R,q,fe,Ce,It){return R===q?!0:R==null||q==null||!ds(R)&&!ds(q)?R!==R&&q!==q:Qc(R,q,fe,Ce,fs,It)}function Qc(R,q,fe,Ce,It,Xe){var Tt=io(R),lr=io(q),mt=Tt?h:jn(R),Ot=lr?h:jn(q);mt=mt==l?N:mt,Ot=Ot==l?N:Ot;var Xt=mt==N,qr=Ot==N,ur=mt==Ot;if(ur&&ya(R)){if(!ya(q))return!1;Tt=!0,Xt=!1}if(ur&&!Xt)return Xe||(Xe=new xn),Tt||dl(R)?ro(R,q,fe,Ce,It,Xe):t0(R,q,mt,fe,Ce,It,Xe);if(!(fe&i)){var Rt=Xt&&D.call(R,"__wrapped__"),jr=qr&&D.call(q,"__wrapped__");if(Rt||jr){var Cn=Rt?R.value():R,dn=jr?q.value():q;return Xe||(Xe=new xn),It(Cn,dn,fe,Ce,Xe)}}return ur?(Xe||(Xe=new xn),rl(R,q,fe,Ce,It,Xe)):!1}function e0(R){if(!fl(R)||al(R))return!1;var q=so(R)?Q:ge;return q.test(Qn(R))}function el(R){return ds(R)&&hl(R.length)&&!!ye[hs(R)]}function tl(R){if(!cl(R))return ls(R);var q=[];for(var fe in Object(R))D.call(R,fe)&&fe!="constructor"&&q.push(fe);return q}function ro(R,q,fe,Ce,It,Xe){var Tt=fe&i,lr=R.length,mt=q.length;if(lr!=mt&&!(Tt&&mt>lr))return!1;var Ot=Xe.get(R);if(Ot&&Xe.get(q))return Ot==q;var Xt=-1,qr=!0,ur=fe&o?new to:void 0;for(Xe.set(R,q),Xe.set(q,R);++Xt<lr;){var Rt=R[Xt],jr=q[Xt];if(Ce)var Cn=Tt?Ce(jr,Rt,Xt,q,R,Xe):Ce(Rt,jr,Xt,R,q,Xe);if(Cn!==void 0){if(Cn)continue;qr=!1;break}if(ur){if(!Ge(q,function(dn,Fn){if(!Je(ur,Fn)&&(Rt===dn||It(Rt,dn,fe,Ce,Xe)))return ur.push(Fn)})){qr=!1;break}}else if(!(Rt===jr||It(Rt,jr,fe,Ce,Xe))){qr=!1;break}}return Xe.delete(R),Xe.delete(q),qr}function t0(R,q,fe,Ce,It,Xe,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||!Xe(new st(R),new st(q)));case v:case E:case H:return ll(+R,+q);case _:return R.name==q.name&&R.message==q.message;case T:case f:return R==q+"";case U:var lr=Be;case I:var mt=Ce&i;if(lr||(lr=rt),R.size!=q.size&&!mt)return!1;var Ot=Tt.get(R);if(Ot)return Ot==q;Ce|=o,Tt.set(R,q);var Xt=ro(lr(R),lr(q),Ce,It,Xe,Tt);return Tt.delete(R),Xt;case x:if(Kt)return Kt.call(R)==Kt.call(q)}return!1}function rl(R,q,fe,Ce,It,Xe){var Tt=fe&i,lr=no(R),mt=lr.length,Ot=no(q),Xt=Ot.length;if(mt!=Xt&&!Tt)return!1;for(var qr=mt;qr--;){var ur=lr[qr];if(!(Tt?ur in q:D.call(q,ur)))return!1}var Rt=Xe.get(R);if(Rt&&Xe.get(q))return Rt==q;var jr=!0;Xe.set(R,q),Xe.set(q,R);for(var Cn=Tt;++qr<mt;){ur=lr[qr];var dn=R[ur],Fn=q[ur];if(Ce)var ba=Tt?Ce(Fn,dn,ur,q,R,Xe):Ce(dn,Fn,ur,R,q,Xe);if(!(ba===void 0?dn===Fn||It(dn,Fn,fe,Ce,Xe):ba)){jr=!1;break}Cn||(Cn=ur=="constructor")}if(jr&&!Cn){var ps=R.constructor,vr=q.constructor;ps!=vr&&"constructor"in R&&"constructor"in q&&!(typeof ps=="function"&&ps instanceof ps&&typeof vr=="function"&&vr instanceof vr)&&(jr=!1)}return Xe.delete(R),Xe.delete(q),jr}function no(R){return wa(R,s0,il)}function Oi(R,q){var fe=R.__data__;return ol(q)?fe[typeof q=="string"?"string":"hash"]:fe.map}function Qr(R,q){var fe=He(R,q);return e0(fe)?fe:void 0}function nl(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 il=Jn?function(R){return R==null?[]:(R=Object(R),nt(Jn(R),function(q){return ht.call(R,q)}))}:Ct,jn=hs;(Ht&&jn(new Ht(new ArrayBuffer(1)))!=de||Lt&&jn(new Lt)!=U||zt&&jn(zt.resolve())!=L||Wt&&jn(new Wt)!=I||Ft&&jn(new Ft)!=z)&&(jn=function(R){var q=hs(R),fe=q==N?R.constructor:void 0,Ce=fe?Qn(fe):"";if(Ce)switch(Ce){case ir:return de;case sr:return U;case qt:return L;case or:return I;case Vt:return z}return q});function sl(R,q){return q=q??c,!!q&&(typeof R=="number"||Fe.test(R))&&R>-1&&R%1==0&&R<q}function ol(R){var q=typeof R;return q=="string"||q=="number"||q=="symbol"||q=="boolean"?R!=="__proto__":R===null}function al(R){return!!B&&B in R}function cl(R){var q=R&&R.constructor,fe=typeof q=="function"&&q.prototype||b;return R===fe}function r0(R){return K.call(R)}function Qn(R){if(R!=null){try{return m.call(R)}catch{}try{return R+""}catch{}}return""}function ll(R,q){return R===q||R!==R&&q!==q}var ul=va(function(){return arguments}())?va:function(R){return ds(R)&&D.call(R,"callee")&&!ht.call(R,"callee")},io=Array.isArray;function n0(R){return R!=null&&hl(R.length)&&!so(R)}var ya=Ii||xt;function i0(R,q){return fs(R,q)}function so(R){if(!fl(R))return!1;var q=hs(R);return q==A||q==P||q==d||q==$}function hl(R){return typeof R=="number"&&R>-1&&R%1==0&&R<=c}function fl(R){var q=typeof R;return R!=null&&(q=="object"||q=="function")}function ds(R){return R!=null&&typeof R=="object"}var dl=Me?$t(Me):el;function s0(R){return n0(R)?Xc(R):tl(R)}function Ct(){return[]}function xt(){return!1}t.exports=i0})(th,th.exports);var D_=th.exports,$_=Object.defineProperty,Tp=Object.getOwnPropertySymbols,P_=Object.prototype.hasOwnProperty,T_=Object.prototype.propertyIsEnumerable,Rp=(t,e,r)=>e in t?$_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rr=(t,e)=>{for(var r in e||(e={}))P_.call(e,r)&&Rp(t,r,e[r]);if(Tp)for(var r of Tp(e))T_.call(e,r)&&Rp(t,r,e[r]);return t};function R_(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),d=Math.log(l)/Math.log(256),v=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 U=0,H=0,G=0,N=P.length;G!==N&&P[G]===0;)G++,U++;for(var L=(N-G)*v+1>>>0,$=new Uint8Array(L);G!==N;){for(var T=P[G],I=0,f=L-1;(T!==0||I<H)&&f!==-1;f--,I++)T+=256*$[f]>>>0,$[f]=T%l>>>0,T=T/l>>>0;if(T!==0)throw new Error("Non-zero carry");H=I,G++}for(var x=L-H;x!==L&&$[x]===0;)x++;for(var J=h.repeat(U);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 U=0;if(P[U]!==" "){for(var H=0,G=0;P[U]===h;)H++,U++;for(var N=(P.length-U)*d+1>>>0,L=new Uint8Array(N);P[U];){var $=r[P.charCodeAt(U)];if($===255)return;for(var T=0,I=N-1;($!==0||T<G)&&I!==-1;I--,T++)$+=l*L[I]>>>0,L[I]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");G=T,U++}if(P[U]!==" "){for(var f=N-G;f!==N&&L[f]===0;)f++;for(var x=new Uint8Array(H+(N-f)),J=H;f!==N;)x[J++]=L[f++];return x}}}function A(P){var U=_(P);if(U)return U;throw new Error(`Non-${e} character`)}return{encode:E,decodeUnsafe:_,decode:A}}var N_=R_,L_=N_;const Np=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")},M_=t=>new TextEncoder().encode(t),U_=t=>new TextDecoder().decode(t);class j_{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 F_{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 Lp(this,e)}}class B_{constructor(e){this.decoders=e}or(e){return Lp(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 Lp=(t,e)=>new B_(Rr(Rr({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class k_{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new j_(e,r,n),this.decoder=new F_(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ic=({name:t,prefix:e,encode:r,decode:n})=>new k_(t,e,r,n),Bo=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=L_(r,e);return ic({prefix:t,name:e,encode:n,decode:o=>Np(i(o))})},H_=(t,e,r,n)=>{const i={};for(let v=0;v<e.length;++v)i[e[v]]=v;let o=t.length;for(;t[o-1]==="=";)--o;const c=new Uint8Array(o*r/8|0);let l=0,h=0,d=0;for(let v=0;v<o;++v){const E=i[t[v]];if(E===void 0)throw new SyntaxError(`Non-${n} character`);h=h<<r|E,l+=r,l>=8&&(l-=8,c[d++]=255&h>>l)}if(l>=r||255&h<<8-l)throw new SyntaxError("Unexpected end of data");return c},z_=(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},Er=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>ic({prefix:e,name:t,encode(i){return z_(i,n,r)},decode(i){return H_(i,n,r,t)}}),W_=ic({prefix:"\0",name:"identity",encode:t=>U_(t),decode:t=>M_(t)});var q_=Object.freeze({__proto__:null,identity:W_});const V_=Er({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var K_=Object.freeze({__proto__:null,base2:V_});const G_=Er({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Z_=Object.freeze({__proto__:null,base8:G_});const Y_=Bo({prefix:"9",name:"base10",alphabet:"0123456789"});var J_=Object.freeze({__proto__:null,base10:Y_});const X_=Er({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Q_=Er({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var e8=Object.freeze({__proto__:null,base16:X_,base16upper:Q_});const t8=Er({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),r8=Er({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),n8=Er({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),i8=Er({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),s8=Er({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),o8=Er({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),a8=Er({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),c8=Er({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),l8=Er({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var u8=Object.freeze({__proto__:null,base32:t8,base32upper:r8,base32pad:n8,base32padupper:i8,base32hex:s8,base32hexupper:o8,base32hexpad:a8,base32hexpadupper:c8,base32z:l8});const h8=Bo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),f8=Bo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var d8=Object.freeze({__proto__:null,base36:h8,base36upper:f8});const p8=Bo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),g8=Bo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var m8=Object.freeze({__proto__:null,base58btc:p8,base58flickr:g8});const w8=Er({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),v8=Er({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),y8=Er({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),b8=Er({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var _8=Object.freeze({__proto__:null,base64:w8,base64pad:v8,base64url:y8,base64urlpad:b8});const Mp=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}"),E8=Mp.reduce((t,e,r)=>(t[r]=e,t),[]),x8=Mp.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function C8(t){return t.reduce((e,r)=>(e+=E8[r],e),"")}function I8(t){const e=[];for(const r of t){const n=x8[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const O8=ic({prefix:"\u{1F680}",name:"base256emoji",encode:C8,decode:I8});var A8=Object.freeze({__proto__:null,base256emoji:O8}),S8=jp,Up=128,D8=127,$8=~D8,P8=Math.pow(2,31);function jp(t,e,r){e=e||[],r=r||0;for(var n=r;t>=P8;)e[r++]=t&255|Up,t/=128;for(;t&$8;)e[r++]=t&255|Up,t>>>=7;return e[r]=t|0,jp.bytes=r-n+1,e}var T8=rh,R8=128,Fp=127;function rh(t,n){var r=0,n=n||0,i=0,o=n,c,l=t.length;do{if(o>=l)throw rh.bytes=0,new RangeError("Could not decode varint");c=t[o++],r+=i<28?(c&Fp)<<i:(c&Fp)*Math.pow(2,i),i+=7}while(c>=R8);return rh.bytes=o-n,r}var N8=Math.pow(2,7),L8=Math.pow(2,14),M8=Math.pow(2,21),U8=Math.pow(2,28),j8=Math.pow(2,35),F8=Math.pow(2,42),B8=Math.pow(2,49),k8=Math.pow(2,56),H8=Math.pow(2,63),z8=function(t){return t<N8?1:t<L8?2:t<M8?3:t<U8?4:t<j8?5:t<F8?6:t<B8?7:t<k8?8:t<H8?9:10},W8={encode:S8,decode:T8,encodingLength:z8},Bp=W8;const kp=(t,e,r=0)=>(Bp.encode(t,e,r),e),Hp=t=>Bp.encodingLength(t),nh=(t,e)=>{const r=e.byteLength,n=Hp(t),i=n+Hp(r),o=new Uint8Array(i+r);return kp(t,o,0),kp(r,o,n),o.set(e,i),new q8(t,r,e,o)};class q8{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const zp=({name:t,code:e,encode:r})=>new V8(t,e,r);class V8{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?nh(this.code,r):r.then(n=>nh(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Wp=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),K8=zp({name:"sha2-256",code:18,encode:Wp("SHA-256")}),G8=zp({name:"sha2-512",code:19,encode:Wp("SHA-512")});var Z8=Object.freeze({__proto__:null,sha256:K8,sha512:G8});const qp=0,Y8="identity",Vp=Np;var J8=Object.freeze({__proto__:null,identity:{code:qp,name:Y8,encode:Vp,digest:t=>nh(qp,Vp(t))}});new TextEncoder,new TextDecoder;const Kp=Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr({},q_),K_),Z_),J_),e8),u8),d8),m8),_8),A8);Rr(Rr({},Z8),J8);function Gp(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function X8(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Gp(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Zp(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Yp=Zp("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ih=Zp("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=X8(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Q8=Rr({utf8:Yp,"utf-8":Yp,hex:Kp.base16,latin1:ih,ascii:ih,binary:ih},Kp);function eE(t,e="utf8"){const r=Q8[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Gp(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}const Jp="wc",tE=2,sh="core",fi=`${Jp}@${2}:${sh}:`,rE={name:sh,logger:"error"},nE={database:":memory:"},iE="crypto",Xp="client_ed25519_seed",sE=ke.ONE_DAY,oE="keychain",aE="0.3",cE="messages",lE="0.3",uE=ke.SIX_HOURS,hE="publisher",Qp="irn",fE="error",eg="wss://relay.walletconnect.com",dE="relayer",rr={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"},pE="_subscription",ko={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},gE=ke.ONE_SECOND/2,mE="2.7.6",wE=1e4,vE="0.3",Pn={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},yE="subscription",bE="0.3",_E=ke.FIVE_SECONDS*1e3,EE="pairing",xE="0.3",Ho={wc_pairingDelete:{req:{ttl:ke.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:ke.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:ke.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:ke.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:ke.ONE_DAY,prompt:!1,tag:0},res:{ttl:ke.ONE_DAY,prompt:!1,tag:0}}},Tn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},CE="history",IE="0.3",OE="expirer",on={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},AE="0.3",oh="verify-api",tg="https://verify.walletconnect.com";class SE{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=oE,this.version=aE,this.initialized=!1,this.storagePrefix=fi,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.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,$1(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?P1(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 DE{constructor(e,r,n){this.core=e,this.logger=r,this.name=iE,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=mp(i);return gp(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=mp(o),l=Ou();return await B4(l,i,sE,c)},this.generateSharedKey=(i,o,c)=>{this.isInitialized();const l=this.getPrivateKey(i),h=F5(l,o);return this.setSymKey(h,c)},this.setSymKey=async(i,o)=>{this.isInitialized();const c=o||B5(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=x1(c),h=Uo(o);if(C1(l)){const _=l.senderPublicKey,A=l.receiverPublicKey;i=await this.generateSharedKey(_,A)}const d=this.getSymKey(i),{type:v,senderPublicKey:E}=l;return H5({type:v,symKey:d,message:h,senderPublicKey:E})},this.decode=async(i,o,c)=>{this.isInitialized();const l=q5(o,c);if(C1(l)){const v=l.receiverPublicKey,E=l.senderPublicKey;i=await this.generateSharedKey(v,E)}const h=this.getSymKey(i),d=z5({symKey:h,encoded:o});return Ku(d)},this.getPayloadType=i=>{const o=Ka(i);return Oo(o.type)},this.getPayloadSenderPublicKey=i=>{const o=Ka(i);return o.senderPublicKey?Dr(o.senderPublicKey,$r):void 0},this.core=e,this.logger=pt.generateChildLogger(r,this.name),this.keychain=n||new SE(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(Xp)}catch{e=Ou(),await this.keychain.set(Xp,e)}return eE(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 $E extends m4{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=cE,this.version=lE,this.initialized=!1,this.storagePrefix=fi,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=As(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=As(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.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,$1(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?P1(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 PE extends w4{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new br.exports.EventEmitter,this.name=hE,this.queue=new Map,this.publishTimeout=1e4,this.publish=async(n,i,o)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:o}});try{const c=o?.ttl||uE,l=$u(o),h=o?.prompt||!1,d=o?.tag||0,v=o?.id||Op().toString(),E={topic:n,message:i,opts:{ttl:c,relay:l,prompt:h,tag:d,id:v}};this.queue.set(v,E);try{await await Ga(this.rpcPublish(n,i,c,l,h,d,v),this.publishTimeout),this.relayer.events.emit(rr.publish,E)}catch{this.logger.debug("Publishing Payload stalled"),this.relayer.events.emit(rr.connection_stalled);return}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:o}})}catch(c){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(c),c}},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,d,v,E;const _={method:Za(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)&&((d=_.params)==null||delete d.prompt),Pr((v=_.params)==null?void 0:v.tag)&&((E=_.params)==null||delete E.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:_}),this.relayer.request(_)}onPublish(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(To.HEARTBEAT_EVENTS.pulse,()=>{this.checkQueue()}),this.relayer.on(rr.message_ack,e=>{this.onPublish(e.id.toString())})}}class TE{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 RE=Object.defineProperty,NE=Object.defineProperties,LE=Object.getOwnPropertyDescriptors,rg=Object.getOwnPropertySymbols,ME=Object.prototype.hasOwnProperty,UE=Object.prototype.propertyIsEnumerable,ng=(t,e,r)=>e in t?RE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zo=(t,e)=>{for(var r in e||(e={}))ME.call(e,r)&&ng(t,r,e[r]);if(rg)for(var r of rg(e))UE.call(e,r)&&ng(t,r,e[r]);return t},ah=(t,e)=>NE(t,LE(e));class jE extends b4{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new TE,this.events=new br.exports.EventEmitter,this.name=yE,this.version=bE,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=fi,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restart(),this.registerEventListeners(),this.onEnable(),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=$u(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 ke.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)>=_E&&(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.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=$u(n);await this.rpcUnsubscribe(e,r,i);const o=Zt("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:Za(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await Ga(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(rr.connection_stalled)}return As(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Za(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 Ga(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(rr.connection_stalled)}}rpcUnsubscribe(e,r,n){const i={method:Za(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,ah(zo({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,zo({},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,zo({},r)),this.topicMap.set(r.topic,e),this.events.emit(Pn.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(Pn.deleted,ah(zo({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Pn.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(Pn.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);zn(r)&&this.onBatchSubscribe(r.map((n,i)=>ah(zo({},e[i]),{id:n})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(To.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(rr.connect,async()=>{await this.onConnect()}),this.relayer.on(rr.disconnect,()=>{this.onDisconnect()}),this.events.on(Pn.created,async e=>{const r=Pn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(Pn.deleted,async e=>{const r=Pn.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 FE=Object.defineProperty,ig=Object.getOwnPropertySymbols,BE=Object.prototype.hasOwnProperty,kE=Object.prototype.propertyIsEnumerable,sg=(t,e,r)=>e in t?FE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,HE=(t,e)=>{for(var r in e||(e={}))BE.call(e,r)&&sg(t,r,e[r]);if(ig)for(var r of ig(e))kE.call(e,r)&&sg(t,r,e[r]);return t};class zE extends v4{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new br.exports.EventEmitter,this.name=dE,this.transportExplicitlyClosed=!1,this.initialized=!1,this.reconnecting=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],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.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||fE})),this.messages=new $E(this.logger,e.core),this.subscriber=new jE(this,this.logger),this.publisher=new PE(this,this.logger),this.relayUrl=e?.relayUrl||eg,this.projectId=e.projectId,this.provider={}}async init(){this.logger.trace("Initialized"),await this.createProvider(),await Promise.all([this.messages.init(),this.transportOpen(),this.subscriber.init()]),this.registerEventListeners(),this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&(this.logger.info("No topics subscribted to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},wE)}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){this.isInitialized();let n="";return await Promise.all([new Promise(i=>{this.subscriber.once(Pn.created,o=>{o.topic===e&&i()})}),new Promise(async i=>{n=await this.subscriber.subscribe(e,r),i()})]),n}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.connected&&(await this.provider.disconnect(),this.events.emit(rr.transport_closed))}async transportOpen(e){if(this.transportExplicitlyClosed=!1,!this.reconnecting){this.relayUrl=e||this.relayUrl,this.reconnecting=!0;try{await Promise.all([new Promise(r=>{this.initialized||r(),this.subscriber.once(Pn.resubscribed,()=>{r()})}),await Promise.race([new Promise(async(r,n)=>{await Ga(this.provider.connect(),5e3,"socket stalled").catch(i=>n(i)).then(()=>r()).finally(()=>this.removeListener(rr.transport_closed,this.rejectTransportOpen))}),new Promise(r=>this.once(rr.transport_closed,this.rejectTransportOpen))])])}catch(r){this.logger.error(r);const n=r;if(!this.isConnectionStalled(n.message))throw r;this.events.emit(rr.transport_closed)}finally{this.reconnecting=!1}}}async restartTransport(e){this.transportExplicitlyClosed||(this.relayUrl=e||this.relayUrl,this.connected&&await Promise.all([new Promise(r=>{this.provider.once(ko.disconnect,()=>{r()})}),this.transportClose()]),await this.createProvider(),await this.transportOpen())}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}rejectTransportOpen(){throw new Error("closeTransport called before connection was established")}async createProvider(){const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new hi(new S_(rb({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;return await this.subscriber.isSubscribed(r)?this.messages.has(r,n):!0}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),eh(e)){if(!e.method.endsWith(pE))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(HE({type:"event",event:r.id},c)),this.events.emit(r.id,c),await this.acknowledgePayload(e),await this.onMessageEvent(c)}else nc(e)&&this.events.emit(rr.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(rr.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=Qu(e.id,!0);await this.provider.connection.send(r)}registerProviderListeners(){this.provider.on(ko.payload,e=>this.onProviderPayload(e)),this.provider.on(ko.connect,()=>{this.events.emit(rr.connect)}),this.provider.on(ko.disconnect,()=>{this.onProviderDisconnect()}),this.provider.on(ko.error,e=>{this.logger.error(e),this.events.emit(rr.error,e)})}registerEventListeners(){this.events.on(rr.connection_stalled,async()=>{await this.restartTransport()})}onProviderDisconnect(){this.events.emit(rr.disconnect),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||setTimeout(async()=>{await this.restartTransport()},ke.toMiliseconds(gE))}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(!this.connected){if(this.connecting)return await new Promise(e=>{const r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)});await this.restartTransport()}}}var WE=Object.defineProperty,og=Object.getOwnPropertySymbols,qE=Object.prototype.hasOwnProperty,VE=Object.prototype.propertyIsEnumerable,ag=(t,e,r)=>e in t?WE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,cg=(t,e)=>{for(var r in e||(e={}))qE.call(e,r)&&ag(t,r,e[r]);if(og)for(var r of og(e))VE.call(e,r)&&ag(t,r,e[r]);return t};class sc extends y4{constructor(e,r,n,i=fi,o=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=vE,this.cached=[],this.initialized=!1,this.storagePrefix=fi,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):Cb(c)?this.map.set(c.id,c):Ib(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=>D_(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=cg(cg({},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.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 KE{constructor(e,r){this.core=e,this.logger=r,this.name=EE,this.version=xE,this.events=new br.exports,this.initialized=!1,this.storagePrefix=fi,this.ignoredPayloadTypes=[Bi],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=Ou(),i=await this.core.crypto.setSymKey(n),o=$n(ke.FIVE_MINUTES),c={protocol:Qp},l={topic:i,expiry:o,relay:c,active:!1},h=pb({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}=hb(n.uri);if(this.pairings.keys.includes(i))throw new Error(`Pairing already exists: ${i}`);if(this.core.crypto.hasKeys(i))throw new Error(`Keychain already exists: ${i}`);const l=$n(ke.FIVE_MINUTES),h={topic:i,relay:c,expiry:l,active:!1};return await this.pairings.set(i,h),await this.core.crypto.setSymKey(o,i),await this.core.relayer.subscribe(i,{relay:c}),this.core.expirer.set(i,l),n.activatePairing&&await this.activate({topic:i}),h},this.activate=async({topic:n})=>{this.isInitialized();const i=$n(ke.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}=Ss();this.events.once(tr("pairing_ping",o),({error:d})=>{d?h(d):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",Zt("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,o)=>{const c=tc(i,o),l=await this.core.crypto.encode(n,c),h=Ho[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=Qu(n,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,n),d=Ho[h.request.method].res;await this.core.relayer.publish(i,l,d),await this.core.history.resolve(c)},this.sendError=async(n,i,o)=>{const c=rc(n,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,n),d=Ho[h.request.method]?Ho[h.request.method].res:Ho.unregistered_method.res;await this.core.relayer.publish(i,l,d),await this.core.history.resolve(c)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Zt("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=>ui(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{const{topic:i,payload:o}=n,c=o.method;if(this.pairings.keys.includes(i))switch(c){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;if(this.pairings.keys.includes(i))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("pairing_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),{}):En(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("pairing_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=Zt("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(Zt("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{if(!zr(n)){const{message:i}=_e("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(i)}if(!xb(n.uri)){const{message:i}=_e("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(i)}},this.isValidPing=async n=>{if(!zr(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(!zr(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(!gr(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(ui(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 sc(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(rr.message,async e=>{const{topic:r,message:n}=e;if(this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;const i=await this.core.crypto.decode(r,n);eh(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):nc(i)&&(await this.core.history.resolve(i),this.onRelayEventResponse({topic:r,payload:i}))})}registerExpirerEvents(){this.core.expirer.on(on.expired,async e=>{const{topic:r}=R1(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit("pairing_expire",{topic:r}))})}}class GE extends g4{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new br.exports.EventEmitter,this.name=CE,this.version=IE,this.cached=[],this.initialized=!1,this.storagePrefix=fi,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};this.records.set(c.id,c),this.events.emit(Tn.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=En(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.events.emit(Tn.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(Tn.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.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:tc(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(Tn.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(Tn.created,e=>{const r=Tn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(Tn.updated,e=>{const r=Tn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(Tn.deleted,e=>{const r=Tn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class ZE extends _4{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new br.exports.EventEmitter,this.name=OE,this.version=AE,this.cached=[],this.initialized=!1,this.storagePrefix=fi,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(on.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(on.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.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 nb(e);if(typeof e=="number")return ib(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(on.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;ke.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(on.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(To.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(on.created,e=>{const r=on.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(on.expired,e=>{const r=on.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(on.deleted,e=>{const r=on.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 YE extends E4{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=oh,this.initialized=!1,this.init=async n=>{S1()||!Su()||(this.verifyUrl=n?.verifyUrl||tg,await this.createIframe())},this.register=async n=>{var i;this.initialized||await this.init(),this.iframe&&((i=this.iframe.contentWindow)==null||i.postMessage(n.attestationId,this.verifyUrl),this.logger.info(`postMessage sent: ${n.attestationId} ${this.verifyUrl}`))},this.resolve=async n=>{var i;if(this.isDevEnv)return"";this.logger.info(`resolving attestation: ${n.attestationId}`);const o=this.startAbortTimer(ke.FIVE_SECONDS),c=await fetch(`${this.verifyUrl}/attestation/${n.attestationId}`,{signal:this.abortController.signal});return clearTimeout(o),c.status===200?(i=await c.json())==null?void 0:i.origin:""},this.createIframe=async()=>{try{await Promise.race([new Promise((n,i)=>{if(document.getElementById(oh))return n();const o=document.createElement("iframe");o.setAttribute("id",oh),o.setAttribute("src",`${this.verifyUrl}/${this.projectId}`),o.style.display="none",o.addEventListener("load",()=>{this.initialized=!0,n()}),o.addEventListener("error",c=>{i(c)}),document.body.append(o),this.iframe=o}),new Promise(n=>{setTimeout(()=>n("iframe load timeout"),ke.toMiliseconds(ke.ONE_SECOND/2))})])}catch(n){this.logger.error(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.error(n)}},this.logger=pt.generateChildLogger(r,this.name),this.verifyUrl=tg,this.abortController=new AbortController,this.isDevEnv=Au()&&process.env.IS_VITEST}get context(){return pt.getLoggerContext(this.logger)}startAbortTimer(e){return setTimeout(()=>this.abortController.abort(),ke.toMiliseconds(e))}}var JE=Object.defineProperty,lg=Object.getOwnPropertySymbols,XE=Object.prototype.hasOwnProperty,QE=Object.prototype.propertyIsEnumerable,ug=(t,e,r)=>e in t?JE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hg=(t,e)=>{for(var r in e||(e={}))XE.call(e,r)&&ug(t,r,e[r]);if(lg)for(var r of lg(e))QE.call(e,r)&&ug(t,r,e[r]);return t};class ch extends p4{constructor(e){super(e),this.protocol=Jp,this.version=tE,this.name=sh,this.events=new br.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||eg;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||rE.logger}));this.logger=pt.generateChildLogger(r,this.name),this.heartbeat=new To.HeartBeat,this.crypto=new DE(this,this.logger,e?.keychain),this.history=new GE(this,this.logger),this.expirer=new ZE(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new v6(hg(hg({},nE),e?.storageOptions)),this.relayer=new zE({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new KE(this,this.logger),this.verify=new YE(this.projectId||"",this.logger)}static async init(e){const r=new ch(e);return await r.initialize(),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 e7=ch,fg="wc",dg=2,pg="client",lh=`${fg}@${dg}:${pg}:`,uh={name:pg,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},t7="proposal",gg="Proposal expired",r7="session",oc=ke.SEVEN_DAYS,n7="engine",Wo={wc_sessionPropose:{req:{ttl:ke.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:ke.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:ke.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:ke.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:ke.ONE_DAY,prompt:!1,tag:1104},res:{ttl:ke.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:ke.ONE_DAY,prompt:!1,tag:1106},res:{ttl:ke.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:ke.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:ke.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:ke.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:ke.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:ke.ONE_DAY,prompt:!1,tag:1112},res:{ttl:ke.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:ke.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:ke.THIRTY_SECONDS,prompt:!1,tag:1115}}},hh={min:ke.FIVE_MINUTES,max:ke.SEVEN_DAYS},i7="request",s7=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var o7=Object.defineProperty,a7=Object.defineProperties,c7=Object.getOwnPropertyDescriptors,mg=Object.getOwnPropertySymbols,l7=Object.prototype.hasOwnProperty,u7=Object.prototype.propertyIsEnumerable,wg=(t,e,r)=>e in t?o7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,an=(t,e)=>{for(var r in e||(e={}))l7.call(e,r)&&wg(t,r,e[r]);if(mg)for(var r of mg(e))u7.call(e,r)&&wg(t,r,e[r]);return t},fh=(t,e)=>a7(t,c7(e));class h7 extends C4{constructor(e){super(e),this.name=n7,this.events=new br.exports,this.initialized=!1,this.ignoredPayloadTypes=[Bi],this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.client.core.pairing.register({methods:Object.keys(Wo)}),this.initialized=!0)},this.connect=async r=>{this.isInitialized();const n=fh(an({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:o,optionalNamespaces:c,sessionProperties:l,relays:h}=n;let d=i,v,E=!1;if(d&&(E=this.client.core.pairing.pairings.get(d).active),!d||!E){const{topic:L,uri:$}=await this.client.core.pairing.create();d=L,v=$}const _=await this.client.core.crypto.generateKeyPair(),A=an({requiredNamespaces:o,optionalNamespaces:c,relays:h??[{protocol:Qp}],proposer:{publicKey:_,metadata:this.client.metadata}},l&&{sessionProperties:l}),{reject:P,resolve:U,done:H}=Ss(ke.FIVE_MINUTES,gg);if(this.events.once(tr("session_connect"),async({error:L,session:$})=>{if(L)P(L);else if($){$.self.publicKey=_;const T=fh(an({},$),{requiredNamespaces:$.requiredNamespaces,optionalNamespaces:$.optionalNamespaces});await this.client.session.set($.topic,T),await this.setExpiry($.topic,$.expiry),d&&await this.client.core.pairing.updateMetadata({topic:d,metadata:$.peer.metadata}),U(T)}}),!d){const{message:L}=_e("NO_MATCHING_KEY",`connect() pairing topic: ${d}`);throw new Error(L)}const G=await this.sendRequest(d,"wc_sessionPropose",A),N=$n(ke.FIVE_MINUTES);return await this.setProposal(G,an({id:G,expiry:N},A)),{uri:v,approval:H}},this.pair=async r=>(this.isInitialized(),await this.client.core.pairing.pair(r)),this.approve=async r=>{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:d,requiredNamespaces:v,optionalNamespaces:E}=l;h=h||"",$s(v)||(v=vb(o,"approve()"));const _=await this.client.core.crypto.generateKeyPair(),A=d.publicKey,P=await this.client.core.crypto.generateSharedKey(_,A);h&&n&&(await this.client.core.pairing.updateMetadata({topic:h,metadata:d.metadata}),await this.sendResult(n,h,{relay:{protocol:i??"irn"},responderPublicKey:_}),await this.client.proposal.delete(n,Zt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:h}));const U=an({relay:{protocol:i??"irn"},namespaces:o,requiredNamespaces:v,optionalNamespaces:E,pairingTopic:h,controller:{publicKey:_,metadata:this.client.metadata},expiry:$n(oc)},c&&{sessionProperties:c});await this.client.core.relayer.subscribe(P),await this.sendRequest(P,"wc_sessionSettle",U);const H=fh(an({},U),{topic:P,pairingTopic:h,acknowledged:!1,self:U.controller,peer:{publicKey:d.publicKey,metadata:d.metadata},controller:_});return await this.client.session.set(P,H),await this.setExpiry(P,$n(oc)),{topic:P,acknowledged:()=>new Promise(G=>setTimeout(()=>G(this.client.session.get(P)),500))}},this.reject=async r=>{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,Zt("USER_DISCONNECTED")))},this.update=async r=>{this.isInitialized(),await this.isValidUpdate(r);const{topic:n,namespaces:i}=r,o=await this.sendRequest(n,"wc_sessionUpdate",{namespaces:i}),{done:c,resolve:l,reject:h}=Ss();return this.events.once(tr("session_update",o),({error:d})=>{d?h(d):l()}),await this.client.session.update(n,{namespaces:i}),{acknowledged:c}},this.extend=async r=>{this.isInitialized(),await this.isValidExtend(r);const{topic:n}=r,i=await this.sendRequest(n,"wc_sessionExtend",{}),{done:o,resolve:c,reject:l}=Ss();return this.events.once(tr("session_extend",i),({error:h})=>{h?l(h):c()}),await this.setExpiry(n,$n(oc)),{acknowledged:o}},this.request=async r=>{this.isInitialized(),await this.isValidRequest(r);const{chainId:n,request:i,topic:o,expiry:c}=r,l=await this.sendRequest(o,"wc_sessionRequest",{request:i,chainId:n},c),{done:h,resolve:d,reject:v}=Ss(c);return this.events.once(tr("session_request",l),({error:E,result:_})=>{E?v(E):d(_)}),this.client.events.emit("session_request_sent",{topic:o,request:i,chainId:n,id:l}),await h()},this.respond=async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:o}=i;Vn(i)?await this.sendResult(o,n,i.result):En(i)&&await this.sendError(o,n,i.error),this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0})},this.ping=async r=>{this.isInitialized(),await this.isValidPing(r);const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=await this.sendRequest(n,"wc_sessionPing",{}),{done:o,resolve:c,reject:l}=Ss();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=>{this.isInitialized(),await this.isValidEmit(r);const{topic:n,event:i,chainId:o}=r;await this.sendRequest(n,"wc_sessionEvent",{event:i,chainId:o})},this.disconnect=async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:n}=r;this.client.session.keys.includes(n)?(await this.sendRequest(n,"wc_sessionDelete",Zt("USER_DISCONNECTED")),await this.deleteSession(n)):await this.client.core.pairing.disconnect({topic:n})},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>_b(n,r))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async r=>{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.self.metadata.url&&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),await Promise.all([this.client.session.delete(r,Zt("USER_DISCONNECTED")),this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.deleteSymKey(r),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,Zt("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.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=Wo.wc_sessionRequest.req.ttl,{id:i,topic:o,params:c}=r;await this.client.pendingRequest.set(i,{id:i,topic:o,params:c}),n&&this.client.core.expirer.set(i,$n(n))},this.sendRequest=async(r,n,i,o)=>{const c=tc(n,i);if(Su()&&s7.includes(n)){const d=As(JSON.stringify(c));await this.client.core.verify.register({attestationId:d})}const l=await this.client.core.crypto.encode(r,c),h=Wo[n].req;return o&&(h.ttl=o),this.client.core.history.set(r,c),this.client.core.relayer.publish(r,l,h),c.id},this.sendResult=async(r,n,i)=>{const o=Qu(r,i),c=await this.client.core.crypto.encode(n,o),l=await this.client.core.history.get(n,r),h=Wo[l.request.method].res;this.client.core.relayer.publish(n,c,h),await this.client.core.history.resolve(o)},this.sendError=async(r,n,i)=>{const o=rc(r,i),c=await this.client.core.crypto.encode(n,o),l=await this.client.core.history.get(n,r),h=Wo[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=>{ui(i.expiry)&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{ui(i.expiry)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession(i)),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=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.onSessionProposeRequest=async(r,n)=>{const{params:i,id:o}=n;try{this.isValidConnect(an({},n.params));const c=$n(ke.FIVE_MINUTES),l=an({id:o,pairingTopic:r,expiry:c},i);await this.setProposal(o,l);const h=As(JSON.stringify(n)),d=await this.getVerifyContext(h,l.proposer.metadata);this.client.events.emit("session_proposal",{id:o,params:l,verifyContext:d})}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 d=await this.client.core.crypto.generateSharedKey(l,h);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:d});const v=await this.client.core.relayer.subscribe(d);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:v}),await this.client.core.pairing.activate({topic:r})}else En(n)&&(await this.client.proposal.delete(i,Zt("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:d,requiredNamespaces:v,optionalNamespaces:E,sessionProperties:_,pairingTopic:A}=n.params,P=an({topic:r,relay:c,expiry:h,namespaces:d,acknowledged:!0,pairingTopic:A,requiredNamespaces:v,optionalNamespaces:E,controller:l.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:l.publicKey,metadata:l.metadata}},_&&{sessionProperties:_});await this.sendResult(n.id,r,!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),{})):En(n)&&(await this.client.session.delete(r,Zt("USER_DISCONNECTED")),this.events.emit(tr("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{const{params:i,id:o}=n;try{this.isValidUpdate(an({topic:r},i)),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult(o,r,!0),this.client.events.emit("session_update",{id:o,topic:r,params:i})}catch(c){await this.sendError(o,r,c),this.client.logger.error(c)}},this.onSessionUpdateResponse=(r,n)=>{const{id:i}=n;Vn(n)?this.events.emit(tr("session_update",i),{}):En(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,$n(oc)),await this.sendResult(i,r,!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),{}):En(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(i,r,!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),{}):En(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(rr.publish,async()=>{o(await this.deleteSession(r))})}),this.sendResult(i,r,!0)]),this.client.events.emit("session_delete",{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidRequest(an({topic:r},o)),await this.setPendingSessionRequest({id:i,topic:r,params:o});const c=As(JSON.stringify(n)),l=this.client.session.get(r),h=await this.getVerifyContext(c,l.peer.metadata);this.client.events.emit("session_request",{id:i,topic:r,params:o,verifyContext:h})}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}):En(n)&&this.events.emit(tr("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidEmit(an({topic:r},o)),this.client.events.emit("session_event",{id:i,topic:r,params:o})}catch(c){await this.sendError(i,r,c),this.client.logger.error(c)}},this.isValidConnect=async r=>{if(!zr(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),!Rb(l,!0)){const{message:h}=_e("MISSING_OR_INVALID",`connect() relays: ${l}`);throw new Error(h)}!Pr(i)&&$s(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Pr(o)&&$s(o)!==0&&this.validateNamespaces(o,"optionalNamespaces"),Pr(c)||this.validateSessionProps(c,"sessionProperties")},this.validateNamespaces=(r,n)=>{const i=Tb(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!zr(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=Ja(i,"approve()");if(h)throw new Error(h.message);const d=k1(l.requiredNamespaces,i,"approve()");if(d)throw new Error(d.message);if(!gr(o,!0)){const{message:v}=_e("MISSING_OR_INVALID",`approve() relayProtocol: ${o}`);throw new Error(v)}Pr(c)||this.validateSessionProps(c,"sessionProperties")},this.isValidReject=async r=>{if(!zr(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),!Lb(i)){const{message:o}=_e("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidSessionSettleRequest=r=>{if(!zr(r)){const{message:d}=_e("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(d)}const{relay:n,controller:i,namespaces:o,expiry:c}=r;if(!F1(n)){const{message:d}=_e("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(d)}const l=Ob(i,"onSessionSettleRequest()");if(l)throw new Error(l.message);const h=Ja(o,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(ui(c)){const{message:d}=_e("EXPIRED","onSessionSettleRequest()");throw new Error(d)}},this.isValidUpdate=async r=>{if(!zr(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=Ja(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(!zr(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(!zr(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(!B1(l,o)){const{message:h}=_e("MISSING_OR_INVALID",`request() chainId: ${o}`);throw new Error(h)}if(!Mb(i)){const{message:h}=_e("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(h)}if(!Fb(l,o,i.method)){const{message:h}=_e("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(h)}if(c&&!zb(c,hh)){const{message:h}=_e("MISSING_OR_INVALID",`request() expiry: ${c}. Expiry must be a number (in seconds) between ${hh.min} and ${hh.max}`);throw new Error(h)}},this.isValidRespond=async r=>{if(!zr(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),!Ub(i)){const{message:o}=_e("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidPing=async r=>{if(!zr(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(!zr(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(!B1(c,o)){const{message:l}=_e("MISSING_OR_INVALID",`emit() chainId: ${o}`);throw new Error(l)}if(!jb(i)){const{message:l}=_e("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}if(!Bb(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(!zr(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||"",validation:"UNKNOWN",origin:n.url||""}};try{const o=await this.client.core.verify.resolve({attestationId:r,verifyUrl:n.verifyUrl});o&&(i.verified.origin=o,i.verified.validation=o===n.url?"VALID":"INVALID")}catch(o){this.client.logger.error(o)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!gr(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)}})}}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.client.core.relayer.on(rr.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);eh(i)?(this.client.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):nc(i)&&(await this.client.core.history.resolve(i),this.onRelayEventResponse({topic:r,payload:i}))})}registerExpirerEvents(){this.client.core.expirer.on(on.expired,async e=>{const{topic:r,id:n}=R1(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}))})}isValidPairingTopic(e){if(!gr(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(ui(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=_e("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!gr(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(ui(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(gr(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(!Nb(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(ui(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:r}=_e("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class f7 extends sc{constructor(e,r){super(e,r,t7,lh),this.core=e,this.logger=r}}class d7 extends sc{constructor(e,r){super(e,r,r7,lh),this.core=e,this.logger=r}}class p7 extends sc{constructor(e,r){super(e,r,i7,lh,n=>n.id),this.core=e,this.logger=r}}class dh extends x4{constructor(e){super(e),this.protocol=fg,this.version=dg,this.name=uh.name,this.events=new br.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||uh.name,this.metadata=e?.metadata||X5();const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||uh.logger}));this.core=e?.core||new e7(e),this.logger=pt.generateChildLogger(r,this.name),this.session=new d7(this.core,this.logger),this.proposal=new f7(this.core,this.logger),this.pendingRequest=new p7(this.core,this.logger),this.engine=new h7(this)}static async init(e){const r=new dh(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 ph={exports:{}};(function(t,e){var r=typeof self<"u"?self:pr,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 d=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],v=ArrayBuffer.isView||function(O){return O&&d.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 A(O){var j={next:function(){var ce=O.shift();return{done:ce===void 0,value:ce}}};return l.iterable&&(j[Symbol.iterator]=function(){return j}),j}function P(O){this.map={},O instanceof P?O.forEach(function(j,ce){this.append(ce,j)},this):Array.isArray(O)?O.forEach(function(j){this.append(j[0],j[1])},this):O&&Object.getOwnPropertyNames(O).forEach(function(j){this.append(j,O[j])},this)}P.prototype.append=function(O,j){O=E(O),j=_(j);var ce=this.map[O];this.map[O]=ce?ce+", "+j:j},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,j){this.map[E(O)]=_(j)},P.prototype.forEach=function(O,j){for(var ce in this.map)this.map.hasOwnProperty(ce)&&O.call(j,this.map[ce],ce,this)},P.prototype.keys=function(){var O=[];return this.forEach(function(j,ce){O.push(ce)}),A(O)},P.prototype.values=function(){var O=[];return this.forEach(function(j){O.push(j)}),A(O)},P.prototype.entries=function(){var O=[];return this.forEach(function(j,ce){O.push([ce,j])}),A(O)},l.iterable&&(P.prototype[Symbol.iterator]=P.prototype.entries);function U(O){if(O.bodyUsed)return Promise.reject(new TypeError("Already read"));O.bodyUsed=!0}function H(O){return new Promise(function(j,ce){O.onload=function(){j(O.result)},O.onerror=function(){ce(O.error)}})}function G(O){var j=new FileReader,ce=H(j);return j.readAsArrayBuffer(O),ce}function N(O){var j=new FileReader,ce=H(j);return j.readAsText(O),ce}function L(O){for(var j=new Uint8Array(O),ce=new Array(j.length),le=0;le<j.length;le++)ce[le]=String.fromCharCode(j[le]);return ce.join("")}function $(O){if(O.slice)return O.slice(0);var j=new Uint8Array(O.byteLength);return j.set(new Uint8Array(O)),j.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)||v(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=U(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?U(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(G)}),this.text=function(){var O=U(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 f(O){var j=O.toUpperCase();return I.indexOf(j)>-1?j:O}function x(O,j){j=j||{};var ce=j.body;if(O instanceof x){if(O.bodyUsed)throw new TypeError("Already read");this.url=O.url,this.credentials=O.credentials,j.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=j.credentials||this.credentials||"same-origin",(j.headers||!this.headers)&&(this.headers=new P(j.headers)),this.method=f(j.method||this.method||"GET"),this.mode=j.mode||this.mode||null,this.signal=j.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 j=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," ");j.append(decodeURIComponent(re),decodeURIComponent(ne))}}),j}function z(O){var j=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();j.append(ne,ae)}}),j}T.call(x.prototype);function ee(O,j){j||(j={}),this.type="default",this.status=j.status===void 0?200:j.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in j?j.statusText:"OK",this.headers=new P(j.headers),this.url=j.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,j){if(de.indexOf(j)===-1)throw new RangeError("Invalid status code");return new ee(null,{status:j,headers:{location:O}})},c.DOMException=o.DOMException;try{new c.DOMException}catch{c.DOMException=function(j,ce){this.message=j,this.name=ce;var le=Error(j);this.stack=le.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function me(O,j){return new Promise(function(ce,le){var re=new x(O,j);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:z(ne.getAllResponseHeaders()||"")};ie.url="responseURL"in ne?ne.responseURL:ie.headers.get("X-Request-URL");var Se="response"in ne?ne.response:ne.responseText;ce(new ee(Se,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,Se){ne.setRequestHeader(Se,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})(ph,ph.exports);var vg=gw(ph.exports);const yg={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},bg=10;class Vi{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new br.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!Sp(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=Uo(e),o=await(await vg(this.url,Object.assign(Object.assign({},yg),{body:n}))).json();this.onPayload({data:o})}catch(n){this.onError(e.id,n)}}async register(e=this.url){if(!Sp(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=Uo({id:1,jsonrpc:"2.0",method:"test",params:[]});await vg(e,Object.assign(Object.assign({},yg),{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"?Ku(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=rc(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return bp(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>bg&&this.events.setMaxListeners(bg)}}const _g="error",g7="wss://relay.walletconnect.com",m7="wc",w7="universal_provider",Eg=`${m7}@${2}:${w7}:`,v7="https://rpc.walletconnect.com/v1",di={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var qo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},gh={exports:{}};/**
72
+ ***************************************************************************** */var Yu=function(t,e){return Yu=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])},Yu(t,e)};function G4(t,e){Yu(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Ju=function(){return Ju=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},Ju.apply(this,arguments)};function Z4(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 Y4(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 J4(t,e){return function(r,n){e(r,n,t)}}function X4(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Q4(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(v){try{d(n.next(v))}catch(E){c(E)}}function h(v){try{d(n.throw(v))}catch(E){c(E)}}function d(v){v.done?o(v.value):i(v.value).then(l,h)}d((n=n.apply(t,e||[])).next())})}function e_(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(d){return function(v){return h([d,v])}}function h(d){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(o=d[0]&2?i.return:d[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,d[1])).done)return o;switch(i=0,o&&(d=[d[0]&2,o.value]),d[0]){case 0:case 1:o=d;break;case 4:return r.label++,{value:d[1],done:!1};case 5:r.label++,i=d[1],d=[0];continue;case 7:d=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(d[0]===6||d[0]===2)){r=0;continue}if(d[0]===3&&(!o||d[1]>o[0]&&d[1]<o[3])){r.label=d[1];break}if(d[0]===6&&r.label<o[1]){r.label=o[1],o=d;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(d);break}o[2]&&r.ops.pop(),r.trys.pop();continue}d=e.call(t,r)}catch(v){d=[6,v],i=0}finally{n=o=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}function t_(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function r_(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Xu(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 Ep(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 n_(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Ep(arguments[e]));return t}function i_(){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 Fo(t){return this instanceof Fo?(this.v=t,this):new Fo(t)}function s_(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(A){return new Promise(function(P,U){o.push([_,A,P,U])>1||l(_,A)})})}function l(_,A){try{h(n[_](A))}catch(P){E(o[0][3],P)}}function h(_){_.value instanceof Fo?Promise.resolve(_.value.v).then(d,v):E(o[0][2],_)}function d(_){l("next",_)}function v(_){l("throw",_)}function E(_,A){_(A),o.shift(),o.length&&l(o[0][0],o[0][1])}}function o_(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:Fo(t[i](c)),done:i==="return"}:o?o(c):c}:o}}function a_(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 Xu=="function"?Xu(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(d){o({value:d,done:l})},c)}}function c_(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function l_(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function u_(t){return t&&t.__esModule?t:{default:t}}function h_(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function f_(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 d_=Object.freeze({__proto__:null,__extends:G4,get __assign(){return Ju},__rest:Z4,__decorate:Y4,__param:J4,__metadata:X4,__awaiter:Q4,__generator:e_,__createBinding:t_,__exportStar:r_,__values:Xu,__read:Ep,__spread:n_,__spreadArrays:i_,__await:Fo,__asyncGenerator:s_,__asyncDelegator:o_,__asyncValues:a_,__makeTemplateObject:c_,__importStar:l_,__importDefault:u_,__classPrivateFieldGet:h_,__classPrivateFieldSet:f_}),p_=Mi(d_),Wn={},xp;function g_(){if(xp)return Wn;xp=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.isBrowserCryptoAvailable=Wn.getSubtleCrypto=Wn.getBrowerCrypto=void 0;function t(){return pr?.crypto||pr?.msCrypto||{}}Wn.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}Wn.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Wn.isBrowserCryptoAvailable=r,Wn}var qn={},Cp;function m_(){if(Cp)return qn;Cp=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=p_;e.__exportStar(g_(),t),e.__exportStar(m_(),t)})(_p);function Ip(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Op(t=6){return BigInt(Ip(t))}function tc(t,e,r){return{id:r||Ip(),jsonrpc:"2.0",method:t,params:e}}function Qu(t,e){return{id:t,jsonrpc:"2.0",result:e}}function rc(t,e,r){return{id:t,jsonrpc:"2.0",error:w_(e,r)}}function w_(t,e){return typeof t>"u"?yp(wp):(typeof t=="string"&&(t=Object.assign(Object.assign({},yp(Zu)),{message:t})),typeof e<"u"&&(t.data=e),V4(t.code)&&(t=K4(t.code)),t)}class v_{}class y_ extends v_{constructor(){super()}}class b_ extends y_{constructor(e){super()}}const __="^https?:",E_="^wss?:";function x_(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Ap(t,e){const r=x_(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Sp(t){return Ap(t,__)}function Dp(t){return Ap(t,E_)}function C_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function $p(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function eh(t){return $p(t)&&"method"in t}function nc(t){return $p(t)&&(Vn(t)||En(t))}function Vn(t){return"result"in t}function En(t){return"error"in t}class hi extends b_{constructor(e){super(e),this.events=new br.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(tc(e.method,e.params||[],e.id||Op().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=>{En(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),nc(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 Pp=10,I_=()=>typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:require("ws"),O_=()=>typeof window<"u",A_=I_();class S_{constructor(e){if(this.url=e,this.events=new br.exports.EventEmitter,this.registering=!1,!Dp(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(Uo(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!Dp(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=_p.isReactNative()?void 0:{rejectUnauthorized:!C_(e)},o=new A_(e,[],i);O_()?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"?Ku(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=rc(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return bp(e,r,"WS")}resetMaxListeners(){this.events.getMaxListeners()>Pp&&this.events.setMaxListeners(Pp)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for URL: ${this.url}`));return this.events.emit("register_error",r),r}}var th={exports:{}};(function(t,e){var r=200,n="__lodash_hash_undefined__",i=1,o=2,c=9007199254740991,l="[object Arguments]",h="[object Array]",d="[object AsyncFunction]",v="[object Boolean]",E="[object Date]",_="[object Error]",A="[object Function]",P="[object GeneratorFunction]",U="[object Map]",H="[object Number]",G="[object Null]",N="[object Object]",L="[object Promise]",$="[object Proxy]",T="[object RegExp]",I="[object Set]",f="[object String]",x="[object Symbol]",J="[object Undefined]",z="[object WeakMap]",ee="[object ArrayBuffer]",de="[object DataView]",me="[object Float32Array]",O="[object Float64Array]",j="[object Int8Array]",ce="[object Int16Array]",le="[object Int32Array]",re="[object Uint8Array]",ne="[object Uint8ClampedArray]",ae="[object Uint16Array]",ie="[object Uint32Array]",Se=/[\\^$.*+?()[\]{}|]/g,ge=/^\[object .+?Constructor\]$/,Fe=/^(?:0|[1-9]\d*)$/,ye={};ye[me]=ye[O]=ye[j]=ye[ce]=ye[le]=ye[re]=ye[ne]=ye[ae]=ye[ie]=!0,ye[l]=ye[h]=ye[ee]=ye[v]=ye[de]=ye[E]=ye[_]=ye[A]=ye[U]=ye[H]=ye[N]=ye[T]=ye[I]=ye[f]=ye[z]=!1;var Le=typeof pr=="object"&&pr&&pr.Object===Object&&pr,X=typeof self=="object"&&self&&self.Object===Object&&self,Y=Le||X||Function("return this")(),W=e&&!e.nodeType&&e,w=W&&!0&&t&&!t.nodeType&&t,F=w&&w.exports===W,we=F&&Le.process,ve=function(){try{return we&&we.binding&&we.binding("util")}catch{}}(),Me=ve&&ve.isTypedArray;function nt(R,q){for(var fe=-1,Ce=R==null?0:R.length,It=0,Xe=[];++fe<Ce;){var Tt=R[fe];q(Tt,fe,R)&&(Xe[It++]=Tt)}return Xe}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 Be(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 Ue=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,Q=RegExp("^"+m.call(D).replace(Se,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ee=F?Y.Buffer:void 0,Te=Y.Symbol,st=Y.Uint8Array,ht=b.propertyIsEnumerable,lt=Ue.splice,Ur=Te?Te.toStringTag:void 0,Jn=Object.getOwnPropertySymbols,Ii=Ee?Ee.isBuffer:void 0,ls=Ke(Object.keys,Object),Ht=Qr(Y,"DataView"),Lt=Qr(Y,"Map"),zt=Qr(Y,"Promise"),Wt=Qr(Y,"Set"),Ft=Qr(Y,"WeakMap"),Mt=Qr(Object,"create"),ir=Qn(Ht),sr=Qn(Lt),qt=Qn(zt),or=Qn(Wt),Vt=Qn(Ft),Jt=Te?Te.prototype:void 0,Kt=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 ar(){this.__data__=Mt?Mt(null):{},this.size=0}function cr(R){var q=this.has(R)&&delete this.__data__[R];return this.size-=q?1:0,q}function Ff(R){var q=this.__data__;if(Mt){var fe=q[R];return fe===n?void 0:fe}return D.call(q,R)?q[R]:void 0}function Bf(R){var q=this.__data__;return Mt?q[R]!==void 0:D.call(q,R)}function kf(R,q){var fe=this.__data__;return this.size+=this.has(R)?0:1,fe[R]=Mt&&q===void 0?n:q,this}Pt.prototype.clear=ar,Pt.prototype.delete=cr,Pt.prototype.get=Ff,Pt.prototype.has=Bf,Pt.prototype.set=kf;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 Hf(){this.__data__=[],this.size=0}function zf(R){var q=this.__data__,fe=us(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 Wf(R){var q=this.__data__,fe=us(q,R);return fe<0?void 0:q[fe][1]}function qf(R){return us(this.__data__,R)>-1}function Vf(R,q){var fe=this.__data__,Ce=us(fe,R);return Ce<0?(++this.size,fe.push([R,q])):fe[Ce][1]=q,this}fn.prototype.clear=Hf,fn.prototype.delete=zf,fn.prototype.get=Wf,fn.prototype.has=qf,fn.prototype.set=Vf;function Xn(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 Qs(){this.size=0,this.__data__={hash:new Pt,map:new(Lt||fn),string:new Pt}}function Kf(R){var q=Oi(this,R).delete(R);return this.size-=q?1:0,q}function eo(R){return Oi(this,R).get(R)}function Gf(R){return Oi(this,R).has(R)}function Zf(R,q){var fe=Oi(this,R),Ce=fe.size;return fe.set(R,q),this.size+=fe.size==Ce?0:1,this}Xn.prototype.clear=Qs,Xn.prototype.delete=Kf,Xn.prototype.get=eo,Xn.prototype.has=Gf,Xn.prototype.set=Zf;function to(R){var q=-1,fe=R==null?0:R.length;for(this.__data__=new Xn;++q<fe;)this.add(R[q])}function Zc(R){return this.__data__.set(R,n),this}function Yc(R){return this.__data__.has(R)}to.prototype.add=to.prototype.push=Zc,to.prototype.has=Yc;function xn(R){var q=this.__data__=new fn(R);this.size=q.size}function Yf(){this.__data__=new fn,this.size=0}function Jf(R){var q=this.__data__,fe=q.delete(R);return this.size=q.size,fe}function Xf(R){return this.__data__.get(R)}function Qf(R){return this.__data__.has(R)}function Jc(R,q){var fe=this.__data__;if(fe instanceof fn){var Ce=fe.__data__;if(!Lt||Ce.length<r-1)return Ce.push([R,q]),this.size=++fe.size,this;fe=this.__data__=new Xn(Ce)}return fe.set(R,q),this.size=fe.size,this}xn.prototype.clear=Yf,xn.prototype.delete=Jf,xn.prototype.get=Xf,xn.prototype.has=Qf,xn.prototype.set=Jc;function Xc(R,q){var fe=io(R),Ce=!fe&&ul(R),It=!fe&&!Ce&&ya(R),Xe=!fe&&!Ce&&!It&&dl(R),Tt=fe||Ce||It||Xe,lr=Tt?Dt(R.length,String):[],mt=lr.length;for(var Ot in R)(q||D.call(R,Ot))&&!(Tt&&(Ot=="length"||It&&(Ot=="offset"||Ot=="parent")||Xe&&(Ot=="buffer"||Ot=="byteLength"||Ot=="byteOffset")||sl(Ot,mt)))&&lr.push(Ot);return lr}function us(R,q){for(var fe=R.length;fe--;)if(ll(R[fe][0],q))return fe;return-1}function wa(R,q,fe){var Ce=q(R);return io(R)?Ce:at(Ce,fe(R))}function hs(R){return R==null?R===void 0?J:G:Ur&&Ur in Object(R)?nl(R):r0(R)}function va(R){return ds(R)&&hs(R)==l}function fs(R,q,fe,Ce,It){return R===q?!0:R==null||q==null||!ds(R)&&!ds(q)?R!==R&&q!==q:Qc(R,q,fe,Ce,fs,It)}function Qc(R,q,fe,Ce,It,Xe){var Tt=io(R),lr=io(q),mt=Tt?h:jn(R),Ot=lr?h:jn(q);mt=mt==l?N:mt,Ot=Ot==l?N:Ot;var Xt=mt==N,qr=Ot==N,ur=mt==Ot;if(ur&&ya(R)){if(!ya(q))return!1;Tt=!0,Xt=!1}if(ur&&!Xt)return Xe||(Xe=new xn),Tt||dl(R)?ro(R,q,fe,Ce,It,Xe):t0(R,q,mt,fe,Ce,It,Xe);if(!(fe&i)){var Rt=Xt&&D.call(R,"__wrapped__"),jr=qr&&D.call(q,"__wrapped__");if(Rt||jr){var Cn=Rt?R.value():R,dn=jr?q.value():q;return Xe||(Xe=new xn),It(Cn,dn,fe,Ce,Xe)}}return ur?(Xe||(Xe=new xn),rl(R,q,fe,Ce,It,Xe)):!1}function e0(R){if(!fl(R)||al(R))return!1;var q=so(R)?Q:ge;return q.test(Qn(R))}function el(R){return ds(R)&&hl(R.length)&&!!ye[hs(R)]}function tl(R){if(!cl(R))return ls(R);var q=[];for(var fe in Object(R))D.call(R,fe)&&fe!="constructor"&&q.push(fe);return q}function ro(R,q,fe,Ce,It,Xe){var Tt=fe&i,lr=R.length,mt=q.length;if(lr!=mt&&!(Tt&&mt>lr))return!1;var Ot=Xe.get(R);if(Ot&&Xe.get(q))return Ot==q;var Xt=-1,qr=!0,ur=fe&o?new to:void 0;for(Xe.set(R,q),Xe.set(q,R);++Xt<lr;){var Rt=R[Xt],jr=q[Xt];if(Ce)var Cn=Tt?Ce(jr,Rt,Xt,q,R,Xe):Ce(Rt,jr,Xt,R,q,Xe);if(Cn!==void 0){if(Cn)continue;qr=!1;break}if(ur){if(!Ge(q,function(dn,Fn){if(!Je(ur,Fn)&&(Rt===dn||It(Rt,dn,fe,Ce,Xe)))return ur.push(Fn)})){qr=!1;break}}else if(!(Rt===jr||It(Rt,jr,fe,Ce,Xe))){qr=!1;break}}return Xe.delete(R),Xe.delete(q),qr}function t0(R,q,fe,Ce,It,Xe,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||!Xe(new st(R),new st(q)));case v:case E:case H:return ll(+R,+q);case _:return R.name==q.name&&R.message==q.message;case T:case f:return R==q+"";case U:var lr=Be;case I:var mt=Ce&i;if(lr||(lr=rt),R.size!=q.size&&!mt)return!1;var Ot=Tt.get(R);if(Ot)return Ot==q;Ce|=o,Tt.set(R,q);var Xt=ro(lr(R),lr(q),Ce,It,Xe,Tt);return Tt.delete(R),Xt;case x:if(Kt)return Kt.call(R)==Kt.call(q)}return!1}function rl(R,q,fe,Ce,It,Xe){var Tt=fe&i,lr=no(R),mt=lr.length,Ot=no(q),Xt=Ot.length;if(mt!=Xt&&!Tt)return!1;for(var qr=mt;qr--;){var ur=lr[qr];if(!(Tt?ur in q:D.call(q,ur)))return!1}var Rt=Xe.get(R);if(Rt&&Xe.get(q))return Rt==q;var jr=!0;Xe.set(R,q),Xe.set(q,R);for(var Cn=Tt;++qr<mt;){ur=lr[qr];var dn=R[ur],Fn=q[ur];if(Ce)var ba=Tt?Ce(Fn,dn,ur,q,R,Xe):Ce(dn,Fn,ur,R,q,Xe);if(!(ba===void 0?dn===Fn||It(dn,Fn,fe,Ce,Xe):ba)){jr=!1;break}Cn||(Cn=ur=="constructor")}if(jr&&!Cn){var ps=R.constructor,vr=q.constructor;ps!=vr&&"constructor"in R&&"constructor"in q&&!(typeof ps=="function"&&ps instanceof ps&&typeof vr=="function"&&vr instanceof vr)&&(jr=!1)}return Xe.delete(R),Xe.delete(q),jr}function no(R){return wa(R,s0,il)}function Oi(R,q){var fe=R.__data__;return ol(q)?fe[typeof q=="string"?"string":"hash"]:fe.map}function Qr(R,q){var fe=He(R,q);return e0(fe)?fe:void 0}function nl(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 il=Jn?function(R){return R==null?[]:(R=Object(R),nt(Jn(R),function(q){return ht.call(R,q)}))}:Ct,jn=hs;(Ht&&jn(new Ht(new ArrayBuffer(1)))!=de||Lt&&jn(new Lt)!=U||zt&&jn(zt.resolve())!=L||Wt&&jn(new Wt)!=I||Ft&&jn(new Ft)!=z)&&(jn=function(R){var q=hs(R),fe=q==N?R.constructor:void 0,Ce=fe?Qn(fe):"";if(Ce)switch(Ce){case ir:return de;case sr:return U;case qt:return L;case or:return I;case Vt:return z}return q});function sl(R,q){return q=q??c,!!q&&(typeof R=="number"||Fe.test(R))&&R>-1&&R%1==0&&R<q}function ol(R){var q=typeof R;return q=="string"||q=="number"||q=="symbol"||q=="boolean"?R!=="__proto__":R===null}function al(R){return!!B&&B in R}function cl(R){var q=R&&R.constructor,fe=typeof q=="function"&&q.prototype||b;return R===fe}function r0(R){return K.call(R)}function Qn(R){if(R!=null){try{return m.call(R)}catch{}try{return R+""}catch{}}return""}function ll(R,q){return R===q||R!==R&&q!==q}var ul=va(function(){return arguments}())?va:function(R){return ds(R)&&D.call(R,"callee")&&!ht.call(R,"callee")},io=Array.isArray;function n0(R){return R!=null&&hl(R.length)&&!so(R)}var ya=Ii||xt;function i0(R,q){return fs(R,q)}function so(R){if(!fl(R))return!1;var q=hs(R);return q==A||q==P||q==d||q==$}function hl(R){return typeof R=="number"&&R>-1&&R%1==0&&R<=c}function fl(R){var q=typeof R;return R!=null&&(q=="object"||q=="function")}function ds(R){return R!=null&&typeof R=="object"}var dl=Me?$t(Me):el;function s0(R){return n0(R)?Xc(R):tl(R)}function Ct(){return[]}function xt(){return!1}t.exports=i0})(th,th.exports);var D_=th.exports,$_=Object.defineProperty,Tp=Object.getOwnPropertySymbols,P_=Object.prototype.hasOwnProperty,T_=Object.prototype.propertyIsEnumerable,Rp=(t,e,r)=>e in t?$_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rr=(t,e)=>{for(var r in e||(e={}))P_.call(e,r)&&Rp(t,r,e[r]);if(Tp)for(var r of Tp(e))T_.call(e,r)&&Rp(t,r,e[r]);return t};function R_(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),d=Math.log(l)/Math.log(256),v=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 U=0,H=0,G=0,N=P.length;G!==N&&P[G]===0;)G++,U++;for(var L=(N-G)*v+1>>>0,$=new Uint8Array(L);G!==N;){for(var T=P[G],I=0,f=L-1;(T!==0||I<H)&&f!==-1;f--,I++)T+=256*$[f]>>>0,$[f]=T%l>>>0,T=T/l>>>0;if(T!==0)throw new Error("Non-zero carry");H=I,G++}for(var x=L-H;x!==L&&$[x]===0;)x++;for(var J=h.repeat(U);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 U=0;if(P[U]!==" "){for(var H=0,G=0;P[U]===h;)H++,U++;for(var N=(P.length-U)*d+1>>>0,L=new Uint8Array(N);P[U];){var $=r[P.charCodeAt(U)];if($===255)return;for(var T=0,I=N-1;($!==0||T<G)&&I!==-1;I--,T++)$+=l*L[I]>>>0,L[I]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");G=T,U++}if(P[U]!==" "){for(var f=N-G;f!==N&&L[f]===0;)f++;for(var x=new Uint8Array(H+(N-f)),J=H;f!==N;)x[J++]=L[f++];return x}}}function A(P){var U=_(P);if(U)return U;throw new Error(`Non-${e} character`)}return{encode:E,decodeUnsafe:_,decode:A}}var N_=R_,L_=N_;const Np=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")},M_=t=>new TextEncoder().encode(t),U_=t=>new TextDecoder().decode(t);class j_{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 F_{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 Lp(this,e)}}class B_{constructor(e){this.decoders=e}or(e){return Lp(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 Lp=(t,e)=>new B_(Rr(Rr({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class k_{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new j_(e,r,n),this.decoder=new F_(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ic=({name:t,prefix:e,encode:r,decode:n})=>new k_(t,e,r,n),Bo=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=L_(r,e);return ic({prefix:t,name:e,encode:n,decode:o=>Np(i(o))})},H_=(t,e,r,n)=>{const i={};for(let v=0;v<e.length;++v)i[e[v]]=v;let o=t.length;for(;t[o-1]==="=";)--o;const c=new Uint8Array(o*r/8|0);let l=0,h=0,d=0;for(let v=0;v<o;++v){const E=i[t[v]];if(E===void 0)throw new SyntaxError(`Non-${n} character`);h=h<<r|E,l+=r,l>=8&&(l-=8,c[d++]=255&h>>l)}if(l>=r||255&h<<8-l)throw new SyntaxError("Unexpected end of data");return c},z_=(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},Er=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>ic({prefix:e,name:t,encode(i){return z_(i,n,r)},decode(i){return H_(i,n,r,t)}}),W_=ic({prefix:"\0",name:"identity",encode:t=>U_(t),decode:t=>M_(t)});var q_=Object.freeze({__proto__:null,identity:W_});const V_=Er({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var K_=Object.freeze({__proto__:null,base2:V_});const G_=Er({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Z_=Object.freeze({__proto__:null,base8:G_});const Y_=Bo({prefix:"9",name:"base10",alphabet:"0123456789"});var J_=Object.freeze({__proto__:null,base10:Y_});const X_=Er({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Q_=Er({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var e8=Object.freeze({__proto__:null,base16:X_,base16upper:Q_});const t8=Er({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),r8=Er({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),n8=Er({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),i8=Er({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),s8=Er({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),o8=Er({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),a8=Er({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),c8=Er({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),l8=Er({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var u8=Object.freeze({__proto__:null,base32:t8,base32upper:r8,base32pad:n8,base32padupper:i8,base32hex:s8,base32hexupper:o8,base32hexpad:a8,base32hexpadupper:c8,base32z:l8});const h8=Bo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),f8=Bo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var d8=Object.freeze({__proto__:null,base36:h8,base36upper:f8});const p8=Bo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),g8=Bo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var m8=Object.freeze({__proto__:null,base58btc:p8,base58flickr:g8});const w8=Er({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),v8=Er({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),y8=Er({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),b8=Er({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var _8=Object.freeze({__proto__:null,base64:w8,base64pad:v8,base64url:y8,base64urlpad:b8});const Mp=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}"),E8=Mp.reduce((t,e,r)=>(t[r]=e,t),[]),x8=Mp.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function C8(t){return t.reduce((e,r)=>(e+=E8[r],e),"")}function I8(t){const e=[];for(const r of t){const n=x8[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const O8=ic({prefix:"\u{1F680}",name:"base256emoji",encode:C8,decode:I8});var A8=Object.freeze({__proto__:null,base256emoji:O8}),S8=jp,Up=128,D8=127,$8=~D8,P8=Math.pow(2,31);function jp(t,e,r){e=e||[],r=r||0;for(var n=r;t>=P8;)e[r++]=t&255|Up,t/=128;for(;t&$8;)e[r++]=t&255|Up,t>>>=7;return e[r]=t|0,jp.bytes=r-n+1,e}var T8=rh,R8=128,Fp=127;function rh(t,n){var r=0,n=n||0,i=0,o=n,c,l=t.length;do{if(o>=l)throw rh.bytes=0,new RangeError("Could not decode varint");c=t[o++],r+=i<28?(c&Fp)<<i:(c&Fp)*Math.pow(2,i),i+=7}while(c>=R8);return rh.bytes=o-n,r}var N8=Math.pow(2,7),L8=Math.pow(2,14),M8=Math.pow(2,21),U8=Math.pow(2,28),j8=Math.pow(2,35),F8=Math.pow(2,42),B8=Math.pow(2,49),k8=Math.pow(2,56),H8=Math.pow(2,63),z8=function(t){return t<N8?1:t<L8?2:t<M8?3:t<U8?4:t<j8?5:t<F8?6:t<B8?7:t<k8?8:t<H8?9:10},W8={encode:S8,decode:T8,encodingLength:z8},Bp=W8;const kp=(t,e,r=0)=>(Bp.encode(t,e,r),e),Hp=t=>Bp.encodingLength(t),nh=(t,e)=>{const r=e.byteLength,n=Hp(t),i=n+Hp(r),o=new Uint8Array(i+r);return kp(t,o,0),kp(r,o,n),o.set(e,i),new q8(t,r,e,o)};class q8{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const zp=({name:t,code:e,encode:r})=>new V8(t,e,r);class V8{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?nh(this.code,r):r.then(n=>nh(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Wp=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),K8=zp({name:"sha2-256",code:18,encode:Wp("SHA-256")}),G8=zp({name:"sha2-512",code:19,encode:Wp("SHA-512")});var Z8=Object.freeze({__proto__:null,sha256:K8,sha512:G8});const qp=0,Y8="identity",Vp=Np;var J8=Object.freeze({__proto__:null,identity:{code:qp,name:Y8,encode:Vp,digest:t=>nh(qp,Vp(t))}});new TextEncoder,new TextDecoder;const Kp=Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr({},q_),K_),Z_),J_),e8),u8),d8),m8),_8),A8);Rr(Rr({},Z8),J8);function Gp(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function X8(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Gp(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Zp(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Yp=Zp("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ih=Zp("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=X8(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Q8=Rr({utf8:Yp,"utf-8":Yp,hex:Kp.base16,latin1:ih,ascii:ih,binary:ih},Kp);function eE(t,e="utf8"){const r=Q8[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Gp(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}const Jp="wc",tE=2,sh="core",fi=`${Jp}@${2}:${sh}:`,rE={name:sh,logger:"error"},nE={database:":memory:"},iE="crypto",Xp="client_ed25519_seed",sE=ke.ONE_DAY,oE="keychain",aE="0.3",cE="messages",lE="0.3",uE=ke.SIX_HOURS,hE="publisher",Qp="irn",fE="error",eg="wss://relay.walletconnect.com",dE="relayer",rr={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"},pE="_subscription",ko={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},gE=ke.ONE_SECOND/2,mE="y",wE=1e4,vE="0.3",Pn={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},yE="subscription",bE="0.3",_E=ke.FIVE_SECONDS*1e3,EE="pairing",xE="0.3",Ho={wc_pairingDelete:{req:{ttl:ke.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:ke.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:ke.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:ke.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:ke.ONE_DAY,prompt:!1,tag:0},res:{ttl:ke.ONE_DAY,prompt:!1,tag:0}}},Tn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},CE="history",IE="0.3",OE="expirer",on={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},AE="0.3",oh="verify-api",tg="https://verify.walletconnect.com";class SE{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=oE,this.version=aE,this.initialized=!1,this.storagePrefix=fi,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.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,$1(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?P1(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 DE{constructor(e,r,n){this.core=e,this.logger=r,this.name=iE,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=mp(i);return gp(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=mp(o),l=Ou();return await B4(l,i,sE,c)},this.generateSharedKey=(i,o,c)=>{this.isInitialized();const l=this.getPrivateKey(i),h=F5(l,o);return this.setSymKey(h,c)},this.setSymKey=async(i,o)=>{this.isInitialized();const c=o||B5(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=x1(c),h=Uo(o);if(C1(l)){const _=l.senderPublicKey,A=l.receiverPublicKey;i=await this.generateSharedKey(_,A)}const d=this.getSymKey(i),{type:v,senderPublicKey:E}=l;return H5({type:v,symKey:d,message:h,senderPublicKey:E})},this.decode=async(i,o,c)=>{this.isInitialized();const l=q5(o,c);if(C1(l)){const v=l.receiverPublicKey,E=l.senderPublicKey;i=await this.generateSharedKey(v,E)}const h=this.getSymKey(i),d=z5({symKey:h,encoded:o});return Ku(d)},this.getPayloadType=i=>{const o=Ka(i);return Oo(o.type)},this.getPayloadSenderPublicKey=i=>{const o=Ka(i);return o.senderPublicKey?Dr(o.senderPublicKey,$r):void 0},this.core=e,this.logger=pt.generateChildLogger(r,this.name),this.keychain=n||new SE(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(Xp)}catch{e=Ou(),await this.keychain.set(Xp,e)}return eE(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 $E extends m4{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=cE,this.version=lE,this.initialized=!1,this.storagePrefix=fi,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=As(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=As(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.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,$1(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?P1(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 PE extends w4{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new br.exports.EventEmitter,this.name=hE,this.queue=new Map,this.publishTimeout=1e4,this.publish=async(n,i,o)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:o}});try{const c=o?.ttl||uE,l=$u(o),h=o?.prompt||!1,d=o?.tag||0,v=o?.id||Op().toString(),E={topic:n,message:i,opts:{ttl:c,relay:l,prompt:h,tag:d,id:v}};this.queue.set(v,E);try{await await Ga(this.rpcPublish(n,i,c,l,h,d,v),this.publishTimeout),this.relayer.events.emit(rr.publish,E)}catch{this.logger.debug("Publishing Payload stalled"),this.relayer.events.emit(rr.connection_stalled);return}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:o}})}catch(c){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(c),c}},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,d,v,E;const _={method:Za(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)&&((d=_.params)==null||delete d.prompt),Pr((v=_.params)==null?void 0:v.tag)&&((E=_.params)==null||delete E.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:_}),this.relayer.request(_)}onPublish(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(To.HEARTBEAT_EVENTS.pulse,()=>{this.checkQueue()}),this.relayer.on(rr.message_ack,e=>{this.onPublish(e.id.toString())})}}class TE{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 RE=Object.defineProperty,NE=Object.defineProperties,LE=Object.getOwnPropertyDescriptors,rg=Object.getOwnPropertySymbols,ME=Object.prototype.hasOwnProperty,UE=Object.prototype.propertyIsEnumerable,ng=(t,e,r)=>e in t?RE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zo=(t,e)=>{for(var r in e||(e={}))ME.call(e,r)&&ng(t,r,e[r]);if(rg)for(var r of rg(e))UE.call(e,r)&&ng(t,r,e[r]);return t},ah=(t,e)=>NE(t,LE(e));class jE extends b4{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new TE,this.events=new br.exports.EventEmitter,this.name=yE,this.version=bE,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=fi,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restart(),this.registerEventListeners(),this.onEnable(),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=$u(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 ke.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)>=_E&&(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.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=$u(n);await this.rpcUnsubscribe(e,r,i);const o=Zt("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:Za(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await Ga(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(rr.connection_stalled)}return As(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Za(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 Ga(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(rr.connection_stalled)}}rpcUnsubscribe(e,r,n){const i={method:Za(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,ah(zo({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,zo({},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,zo({},r)),this.topicMap.set(r.topic,e),this.events.emit(Pn.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(Pn.deleted,ah(zo({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Pn.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(Pn.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);zn(r)&&this.onBatchSubscribe(r.map((n,i)=>ah(zo({},e[i]),{id:n})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(To.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(rr.connect,async()=>{await this.onConnect()}),this.relayer.on(rr.disconnect,()=>{this.onDisconnect()}),this.events.on(Pn.created,async e=>{const r=Pn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(Pn.deleted,async e=>{const r=Pn.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 FE=Object.defineProperty,ig=Object.getOwnPropertySymbols,BE=Object.prototype.hasOwnProperty,kE=Object.prototype.propertyIsEnumerable,sg=(t,e,r)=>e in t?FE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,HE=(t,e)=>{for(var r in e||(e={}))BE.call(e,r)&&sg(t,r,e[r]);if(ig)for(var r of ig(e))kE.call(e,r)&&sg(t,r,e[r]);return t};class zE extends v4{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new br.exports.EventEmitter,this.name=dE,this.transportExplicitlyClosed=!1,this.initialized=!1,this.reconnecting=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],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.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||fE})),this.messages=new $E(this.logger,e.core),this.subscriber=new jE(this,this.logger),this.publisher=new PE(this,this.logger),this.relayUrl=e?.relayUrl||eg,this.projectId=e.projectId,this.provider={}}async init(){this.logger.trace("Initialized"),await this.createProvider(),await Promise.all([this.messages.init(),this.transportOpen(),this.subscriber.init()]),this.registerEventListeners(),this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&(this.logger.info("No topics subscribted to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},wE)}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){this.isInitialized();let n="";return await Promise.all([new Promise(i=>{this.subscriber.once(Pn.created,o=>{o.topic===e&&i()})}),new Promise(async i=>{n=await this.subscriber.subscribe(e,r),i()})]),n}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.connected&&(await this.provider.disconnect(),this.events.emit(rr.transport_closed))}async transportOpen(e){if(this.transportExplicitlyClosed=!1,!this.reconnecting){this.relayUrl=e||this.relayUrl,this.reconnecting=!0;try{await Promise.all([new Promise(r=>{this.initialized||r(),this.subscriber.once(Pn.resubscribed,()=>{r()})}),await Promise.race([new Promise(async(r,n)=>{await Ga(this.provider.connect(),5e3,"socket stalled").catch(i=>n(i)).then(()=>r()).finally(()=>this.removeListener(rr.transport_closed,this.rejectTransportOpen))}),new Promise(r=>this.once(rr.transport_closed,this.rejectTransportOpen))])])}catch(r){this.logger.error(r);const n=r;if(!this.isConnectionStalled(n.message))throw r;this.events.emit(rr.transport_closed)}finally{this.reconnecting=!1}}}async restartTransport(e){this.transportExplicitlyClosed||(this.relayUrl=e||this.relayUrl,this.connected&&await Promise.all([new Promise(r=>{this.provider.once(ko.disconnect,()=>{r()})}),this.transportClose()]),await this.createProvider(),await this.transportOpen())}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}rejectTransportOpen(){throw new Error("closeTransport called before connection was established")}async createProvider(){const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new hi(new S_(rb({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;return await this.subscriber.isSubscribed(r)?this.messages.has(r,n):!0}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),eh(e)){if(!e.method.endsWith(pE))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(HE({type:"event",event:r.id},c)),this.events.emit(r.id,c),await this.acknowledgePayload(e),await this.onMessageEvent(c)}else nc(e)&&this.events.emit(rr.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(rr.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=Qu(e.id,!0);await this.provider.connection.send(r)}registerProviderListeners(){this.provider.on(ko.payload,e=>this.onProviderPayload(e)),this.provider.on(ko.connect,()=>{this.events.emit(rr.connect)}),this.provider.on(ko.disconnect,()=>{this.onProviderDisconnect()}),this.provider.on(ko.error,e=>{this.logger.error(e),this.events.emit(rr.error,e)})}registerEventListeners(){this.events.on(rr.connection_stalled,async()=>{await this.restartTransport()})}onProviderDisconnect(){this.events.emit(rr.disconnect),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||setTimeout(async()=>{await this.restartTransport()},ke.toMiliseconds(gE))}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(!this.connected){if(this.connecting)return await new Promise(e=>{const r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)});await this.restartTransport()}}}var WE=Object.defineProperty,og=Object.getOwnPropertySymbols,qE=Object.prototype.hasOwnProperty,VE=Object.prototype.propertyIsEnumerable,ag=(t,e,r)=>e in t?WE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,cg=(t,e)=>{for(var r in e||(e={}))qE.call(e,r)&&ag(t,r,e[r]);if(og)for(var r of og(e))VE.call(e,r)&&ag(t,r,e[r]);return t};class sc extends y4{constructor(e,r,n,i=fi,o=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=vE,this.cached=[],this.initialized=!1,this.storagePrefix=fi,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):Cb(c)?this.map.set(c.id,c):Ib(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=>D_(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=cg(cg({},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.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 KE{constructor(e,r){this.core=e,this.logger=r,this.name=EE,this.version=xE,this.events=new br.exports,this.initialized=!1,this.storagePrefix=fi,this.ignoredPayloadTypes=[Bi],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=Ou(),i=await this.core.crypto.setSymKey(n),o=$n(ke.FIVE_MINUTES),c={protocol:Qp},l={topic:i,expiry:o,relay:c,active:!1},h=pb({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}=hb(n.uri);if(this.pairings.keys.includes(i))throw new Error(`Pairing already exists: ${i}`);if(this.core.crypto.hasKeys(i))throw new Error(`Keychain already exists: ${i}`);const l=$n(ke.FIVE_MINUTES),h={topic:i,relay:c,expiry:l,active:!1};return await this.pairings.set(i,h),await this.core.crypto.setSymKey(o,i),await this.core.relayer.subscribe(i,{relay:c}),this.core.expirer.set(i,l),n.activatePairing&&await this.activate({topic:i}),h},this.activate=async({topic:n})=>{this.isInitialized();const i=$n(ke.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}=Ss();this.events.once(tr("pairing_ping",o),({error:d})=>{d?h(d):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",Zt("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,o)=>{const c=tc(i,o),l=await this.core.crypto.encode(n,c),h=Ho[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=Qu(n,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,n),d=Ho[h.request.method].res;await this.core.relayer.publish(i,l,d),await this.core.history.resolve(c)},this.sendError=async(n,i,o)=>{const c=rc(n,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,n),d=Ho[h.request.method]?Ho[h.request.method].res:Ho.unregistered_method.res;await this.core.relayer.publish(i,l,d),await this.core.history.resolve(c)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Zt("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=>ui(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{const{topic:i,payload:o}=n,c=o.method;if(this.pairings.keys.includes(i))switch(c){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;if(this.pairings.keys.includes(i))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("pairing_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),{}):En(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("pairing_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=Zt("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(Zt("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{if(!zr(n)){const{message:i}=_e("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(i)}if(!xb(n.uri)){const{message:i}=_e("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(i)}},this.isValidPing=async n=>{if(!zr(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(!zr(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(!gr(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(ui(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 sc(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(rr.message,async e=>{const{topic:r,message:n}=e;if(this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;const i=await this.core.crypto.decode(r,n);eh(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):nc(i)&&(await this.core.history.resolve(i),this.onRelayEventResponse({topic:r,payload:i}))})}registerExpirerEvents(){this.core.expirer.on(on.expired,async e=>{const{topic:r}=R1(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit("pairing_expire",{topic:r}))})}}class GE extends g4{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new br.exports.EventEmitter,this.name=CE,this.version=IE,this.cached=[],this.initialized=!1,this.storagePrefix=fi,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};this.records.set(c.id,c),this.events.emit(Tn.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=En(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.events.emit(Tn.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(Tn.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.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:tc(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(Tn.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(Tn.created,e=>{const r=Tn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(Tn.updated,e=>{const r=Tn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(Tn.deleted,e=>{const r=Tn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class ZE extends _4{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new br.exports.EventEmitter,this.name=OE,this.version=AE,this.cached=[],this.initialized=!1,this.storagePrefix=fi,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(on.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(on.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.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 nb(e);if(typeof e=="number")return ib(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(on.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;ke.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(on.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(To.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(on.created,e=>{const r=on.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(on.expired,e=>{const r=on.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(on.deleted,e=>{const r=on.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 YE extends E4{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=oh,this.initialized=!1,this.init=async n=>{S1()||!Su()||(this.verifyUrl=n?.verifyUrl||tg,await this.createIframe())},this.register=async n=>{var i;this.initialized||await this.init(),this.iframe&&((i=this.iframe.contentWindow)==null||i.postMessage(n.attestationId,this.verifyUrl),this.logger.info(`postMessage sent: ${n.attestationId} ${this.verifyUrl}`))},this.resolve=async n=>{var i;if(this.isDevEnv)return"";this.logger.info(`resolving attestation: ${n.attestationId}`);const o=this.startAbortTimer(ke.FIVE_SECONDS),c=await fetch(`${this.verifyUrl}/attestation/${n.attestationId}`,{signal:this.abortController.signal});return clearTimeout(o),c.status===200?(i=await c.json())==null?void 0:i.origin:""},this.createIframe=async()=>{try{await Promise.race([new Promise((n,i)=>{if(document.getElementById(oh))return n();const o=document.createElement("iframe");o.setAttribute("id",oh),o.setAttribute("src",`${this.verifyUrl}/${this.projectId}`),o.style.display="none",o.addEventListener("load",()=>{this.initialized=!0,n()}),o.addEventListener("error",c=>{i(c)}),document.body.append(o),this.iframe=o}),new Promise(n=>{setTimeout(()=>n("iframe load timeout"),ke.toMiliseconds(ke.ONE_SECOND/2))})])}catch(n){this.logger.error(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.error(n)}},this.logger=pt.generateChildLogger(r,this.name),this.verifyUrl=tg,this.abortController=new AbortController,this.isDevEnv=Au()&&process.env.IS_VITEST}get context(){return pt.getLoggerContext(this.logger)}startAbortTimer(e){return setTimeout(()=>this.abortController.abort(),ke.toMiliseconds(e))}}var JE=Object.defineProperty,lg=Object.getOwnPropertySymbols,XE=Object.prototype.hasOwnProperty,QE=Object.prototype.propertyIsEnumerable,ug=(t,e,r)=>e in t?JE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hg=(t,e)=>{for(var r in e||(e={}))XE.call(e,r)&&ug(t,r,e[r]);if(lg)for(var r of lg(e))QE.call(e,r)&&ug(t,r,e[r]);return t};class ch extends p4{constructor(e){super(e),this.protocol=Jp,this.version=tE,this.name=sh,this.events=new br.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||eg;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||rE.logger}));this.logger=pt.generateChildLogger(r,this.name),this.heartbeat=new To.HeartBeat,this.crypto=new DE(this,this.logger,e?.keychain),this.history=new GE(this,this.logger),this.expirer=new ZE(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new v6(hg(hg({},nE),e?.storageOptions)),this.relayer=new zE({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new KE(this,this.logger),this.verify=new YE(this.projectId||"",this.logger)}static async init(e){const r=new ch(e);return await r.initialize(),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 e7=ch,fg="wc",dg=2,pg="client",lh=`${fg}@${dg}:${pg}:`,uh={name:pg,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},t7="proposal",gg="Proposal expired",r7="session",oc=ke.SEVEN_DAYS,n7="engine",Wo={wc_sessionPropose:{req:{ttl:ke.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:ke.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:ke.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:ke.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:ke.ONE_DAY,prompt:!1,tag:1104},res:{ttl:ke.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:ke.ONE_DAY,prompt:!1,tag:1106},res:{ttl:ke.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:ke.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:ke.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:ke.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:ke.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:ke.ONE_DAY,prompt:!1,tag:1112},res:{ttl:ke.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:ke.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:ke.THIRTY_SECONDS,prompt:!1,tag:1115}}},hh={min:ke.FIVE_MINUTES,max:ke.SEVEN_DAYS},i7="request",s7=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var o7=Object.defineProperty,a7=Object.defineProperties,c7=Object.getOwnPropertyDescriptors,mg=Object.getOwnPropertySymbols,l7=Object.prototype.hasOwnProperty,u7=Object.prototype.propertyIsEnumerable,wg=(t,e,r)=>e in t?o7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,an=(t,e)=>{for(var r in e||(e={}))l7.call(e,r)&&wg(t,r,e[r]);if(mg)for(var r of mg(e))u7.call(e,r)&&wg(t,r,e[r]);return t},fh=(t,e)=>a7(t,c7(e));class h7 extends C4{constructor(e){super(e),this.name=n7,this.events=new br.exports,this.initialized=!1,this.ignoredPayloadTypes=[Bi],this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.client.core.pairing.register({methods:Object.keys(Wo)}),this.initialized=!0)},this.connect=async r=>{this.isInitialized();const n=fh(an({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:o,optionalNamespaces:c,sessionProperties:l,relays:h}=n;let d=i,v,E=!1;if(d&&(E=this.client.core.pairing.pairings.get(d).active),!d||!E){const{topic:L,uri:$}=await this.client.core.pairing.create();d=L,v=$}const _=await this.client.core.crypto.generateKeyPair(),A=an({requiredNamespaces:o,optionalNamespaces:c,relays:h??[{protocol:Qp}],proposer:{publicKey:_,metadata:this.client.metadata}},l&&{sessionProperties:l}),{reject:P,resolve:U,done:H}=Ss(ke.FIVE_MINUTES,gg);if(this.events.once(tr("session_connect"),async({error:L,session:$})=>{if(L)P(L);else if($){$.self.publicKey=_;const T=fh(an({},$),{requiredNamespaces:$.requiredNamespaces,optionalNamespaces:$.optionalNamespaces});await this.client.session.set($.topic,T),await this.setExpiry($.topic,$.expiry),d&&await this.client.core.pairing.updateMetadata({topic:d,metadata:$.peer.metadata}),U(T)}}),!d){const{message:L}=_e("NO_MATCHING_KEY",`connect() pairing topic: ${d}`);throw new Error(L)}const G=await this.sendRequest(d,"wc_sessionPropose",A),N=$n(ke.FIVE_MINUTES);return await this.setProposal(G,an({id:G,expiry:N},A)),{uri:v,approval:H}},this.pair=async r=>(this.isInitialized(),await this.client.core.pairing.pair(r)),this.approve=async r=>{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:d,requiredNamespaces:v,optionalNamespaces:E}=l;h=h||"",$s(v)||(v=vb(o,"approve()"));const _=await this.client.core.crypto.generateKeyPair(),A=d.publicKey,P=await this.client.core.crypto.generateSharedKey(_,A);h&&n&&(await this.client.core.pairing.updateMetadata({topic:h,metadata:d.metadata}),await this.sendResult(n,h,{relay:{protocol:i??"irn"},responderPublicKey:_}),await this.client.proposal.delete(n,Zt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:h}));const U=an({relay:{protocol:i??"irn"},namespaces:o,requiredNamespaces:v,optionalNamespaces:E,pairingTopic:h,controller:{publicKey:_,metadata:this.client.metadata},expiry:$n(oc)},c&&{sessionProperties:c});await this.client.core.relayer.subscribe(P),await this.sendRequest(P,"wc_sessionSettle",U);const H=fh(an({},U),{topic:P,pairingTopic:h,acknowledged:!1,self:U.controller,peer:{publicKey:d.publicKey,metadata:d.metadata},controller:_});return await this.client.session.set(P,H),await this.setExpiry(P,$n(oc)),{topic:P,acknowledged:()=>new Promise(G=>setTimeout(()=>G(this.client.session.get(P)),500))}},this.reject=async r=>{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,Zt("USER_DISCONNECTED")))},this.update=async r=>{this.isInitialized(),await this.isValidUpdate(r);const{topic:n,namespaces:i}=r,o=await this.sendRequest(n,"wc_sessionUpdate",{namespaces:i}),{done:c,resolve:l,reject:h}=Ss();return this.events.once(tr("session_update",o),({error:d})=>{d?h(d):l()}),await this.client.session.update(n,{namespaces:i}),{acknowledged:c}},this.extend=async r=>{this.isInitialized(),await this.isValidExtend(r);const{topic:n}=r,i=await this.sendRequest(n,"wc_sessionExtend",{}),{done:o,resolve:c,reject:l}=Ss();return this.events.once(tr("session_extend",i),({error:h})=>{h?l(h):c()}),await this.setExpiry(n,$n(oc)),{acknowledged:o}},this.request=async r=>{this.isInitialized(),await this.isValidRequest(r);const{chainId:n,request:i,topic:o,expiry:c}=r,l=await this.sendRequest(o,"wc_sessionRequest",{request:i,chainId:n},c),{done:h,resolve:d,reject:v}=Ss(c);return this.events.once(tr("session_request",l),({error:E,result:_})=>{E?v(E):d(_)}),this.client.events.emit("session_request_sent",{topic:o,request:i,chainId:n,id:l}),await h()},this.respond=async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:o}=i;Vn(i)?await this.sendResult(o,n,i.result):En(i)&&await this.sendError(o,n,i.error),this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0})},this.ping=async r=>{this.isInitialized(),await this.isValidPing(r);const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=await this.sendRequest(n,"wc_sessionPing",{}),{done:o,resolve:c,reject:l}=Ss();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=>{this.isInitialized(),await this.isValidEmit(r);const{topic:n,event:i,chainId:o}=r;await this.sendRequest(n,"wc_sessionEvent",{event:i,chainId:o})},this.disconnect=async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:n}=r;this.client.session.keys.includes(n)?(await this.sendRequest(n,"wc_sessionDelete",Zt("USER_DISCONNECTED")),await this.deleteSession(n)):await this.client.core.pairing.disconnect({topic:n})},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>_b(n,r))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async r=>{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.self.metadata.url&&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),await Promise.all([this.client.session.delete(r,Zt("USER_DISCONNECTED")),this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.deleteSymKey(r),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,Zt("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.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=Wo.wc_sessionRequest.req.ttl,{id:i,topic:o,params:c}=r;await this.client.pendingRequest.set(i,{id:i,topic:o,params:c}),n&&this.client.core.expirer.set(i,$n(n))},this.sendRequest=async(r,n,i,o)=>{const c=tc(n,i);if(Su()&&s7.includes(n)){const d=As(JSON.stringify(c));await this.client.core.verify.register({attestationId:d})}const l=await this.client.core.crypto.encode(r,c),h=Wo[n].req;return o&&(h.ttl=o),this.client.core.history.set(r,c),this.client.core.relayer.publish(r,l,h),c.id},this.sendResult=async(r,n,i)=>{const o=Qu(r,i),c=await this.client.core.crypto.encode(n,o),l=await this.client.core.history.get(n,r),h=Wo[l.request.method].res;this.client.core.relayer.publish(n,c,h),await this.client.core.history.resolve(o)},this.sendError=async(r,n,i)=>{const o=rc(r,i),c=await this.client.core.crypto.encode(n,o),l=await this.client.core.history.get(n,r),h=Wo[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=>{ui(i.expiry)&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{ui(i.expiry)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession(i)),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=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.onSessionProposeRequest=async(r,n)=>{const{params:i,id:o}=n;try{this.isValidConnect(an({},n.params));const c=$n(ke.FIVE_MINUTES),l=an({id:o,pairingTopic:r,expiry:c},i);await this.setProposal(o,l);const h=As(JSON.stringify(n)),d=await this.getVerifyContext(h,l.proposer.metadata);this.client.events.emit("session_proposal",{id:o,params:l,verifyContext:d})}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 d=await this.client.core.crypto.generateSharedKey(l,h);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:d});const v=await this.client.core.relayer.subscribe(d);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:v}),await this.client.core.pairing.activate({topic:r})}else En(n)&&(await this.client.proposal.delete(i,Zt("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:d,requiredNamespaces:v,optionalNamespaces:E,sessionProperties:_,pairingTopic:A}=n.params,P=an({topic:r,relay:c,expiry:h,namespaces:d,acknowledged:!0,pairingTopic:A,requiredNamespaces:v,optionalNamespaces:E,controller:l.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:l.publicKey,metadata:l.metadata}},_&&{sessionProperties:_});await this.sendResult(n.id,r,!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),{})):En(n)&&(await this.client.session.delete(r,Zt("USER_DISCONNECTED")),this.events.emit(tr("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{const{params:i,id:o}=n;try{this.isValidUpdate(an({topic:r},i)),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult(o,r,!0),this.client.events.emit("session_update",{id:o,topic:r,params:i})}catch(c){await this.sendError(o,r,c),this.client.logger.error(c)}},this.onSessionUpdateResponse=(r,n)=>{const{id:i}=n;Vn(n)?this.events.emit(tr("session_update",i),{}):En(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,$n(oc)),await this.sendResult(i,r,!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),{}):En(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(i,r,!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),{}):En(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(rr.publish,async()=>{o(await this.deleteSession(r))})}),this.sendResult(i,r,!0)]),this.client.events.emit("session_delete",{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidRequest(an({topic:r},o)),await this.setPendingSessionRequest({id:i,topic:r,params:o});const c=As(JSON.stringify(n)),l=this.client.session.get(r),h=await this.getVerifyContext(c,l.peer.metadata);this.client.events.emit("session_request",{id:i,topic:r,params:o,verifyContext:h})}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}):En(n)&&this.events.emit(tr("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidEmit(an({topic:r},o)),this.client.events.emit("session_event",{id:i,topic:r,params:o})}catch(c){await this.sendError(i,r,c),this.client.logger.error(c)}},this.isValidConnect=async r=>{if(!zr(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),!Rb(l,!0)){const{message:h}=_e("MISSING_OR_INVALID",`connect() relays: ${l}`);throw new Error(h)}!Pr(i)&&$s(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Pr(o)&&$s(o)!==0&&this.validateNamespaces(o,"optionalNamespaces"),Pr(c)||this.validateSessionProps(c,"sessionProperties")},this.validateNamespaces=(r,n)=>{const i=Tb(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!zr(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=Ja(i,"approve()");if(h)throw new Error(h.message);const d=k1(l.requiredNamespaces,i,"approve()");if(d)throw new Error(d.message);if(!gr(o,!0)){const{message:v}=_e("MISSING_OR_INVALID",`approve() relayProtocol: ${o}`);throw new Error(v)}Pr(c)||this.validateSessionProps(c,"sessionProperties")},this.isValidReject=async r=>{if(!zr(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),!Lb(i)){const{message:o}=_e("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidSessionSettleRequest=r=>{if(!zr(r)){const{message:d}=_e("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(d)}const{relay:n,controller:i,namespaces:o,expiry:c}=r;if(!F1(n)){const{message:d}=_e("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(d)}const l=Ob(i,"onSessionSettleRequest()");if(l)throw new Error(l.message);const h=Ja(o,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(ui(c)){const{message:d}=_e("EXPIRED","onSessionSettleRequest()");throw new Error(d)}},this.isValidUpdate=async r=>{if(!zr(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=Ja(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(!zr(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(!zr(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(!B1(l,o)){const{message:h}=_e("MISSING_OR_INVALID",`request() chainId: ${o}`);throw new Error(h)}if(!Mb(i)){const{message:h}=_e("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(h)}if(!Fb(l,o,i.method)){const{message:h}=_e("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(h)}if(c&&!zb(c,hh)){const{message:h}=_e("MISSING_OR_INVALID",`request() expiry: ${c}. Expiry must be a number (in seconds) between ${hh.min} and ${hh.max}`);throw new Error(h)}},this.isValidRespond=async r=>{if(!zr(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),!Ub(i)){const{message:o}=_e("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidPing=async r=>{if(!zr(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(!zr(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(!B1(c,o)){const{message:l}=_e("MISSING_OR_INVALID",`emit() chainId: ${o}`);throw new Error(l)}if(!jb(i)){const{message:l}=_e("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}if(!Bb(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(!zr(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||"",validation:"UNKNOWN",origin:n.url||""}};try{const o=await this.client.core.verify.resolve({attestationId:r,verifyUrl:n.verifyUrl});o&&(i.verified.origin=o,i.verified.validation=o===n.url?"VALID":"INVALID")}catch(o){this.client.logger.error(o)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!gr(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)}})}}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.client.core.relayer.on(rr.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);eh(i)?(this.client.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):nc(i)&&(await this.client.core.history.resolve(i),this.onRelayEventResponse({topic:r,payload:i}))})}registerExpirerEvents(){this.client.core.expirer.on(on.expired,async e=>{const{topic:r,id:n}=R1(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}))})}isValidPairingTopic(e){if(!gr(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(ui(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=_e("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!gr(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(ui(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(gr(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(!Nb(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(ui(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:r}=_e("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class f7 extends sc{constructor(e,r){super(e,r,t7,lh),this.core=e,this.logger=r}}class d7 extends sc{constructor(e,r){super(e,r,r7,lh),this.core=e,this.logger=r}}class p7 extends sc{constructor(e,r){super(e,r,i7,lh,n=>n.id),this.core=e,this.logger=r}}class dh extends x4{constructor(e){super(e),this.protocol=fg,this.version=dg,this.name=uh.name,this.events=new br.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||uh.name,this.metadata=e?.metadata||X5();const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||uh.logger}));this.core=e?.core||new e7(e),this.logger=pt.generateChildLogger(r,this.name),this.session=new d7(this.core,this.logger),this.proposal=new f7(this.core,this.logger),this.pendingRequest=new p7(this.core,this.logger),this.engine=new h7(this)}static async init(e){const r=new dh(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 ph={exports:{}};(function(t,e){var r=typeof self<"u"?self:pr,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 d=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],v=ArrayBuffer.isView||function(O){return O&&d.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 A(O){var j={next:function(){var ce=O.shift();return{done:ce===void 0,value:ce}}};return l.iterable&&(j[Symbol.iterator]=function(){return j}),j}function P(O){this.map={},O instanceof P?O.forEach(function(j,ce){this.append(ce,j)},this):Array.isArray(O)?O.forEach(function(j){this.append(j[0],j[1])},this):O&&Object.getOwnPropertyNames(O).forEach(function(j){this.append(j,O[j])},this)}P.prototype.append=function(O,j){O=E(O),j=_(j);var ce=this.map[O];this.map[O]=ce?ce+", "+j:j},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,j){this.map[E(O)]=_(j)},P.prototype.forEach=function(O,j){for(var ce in this.map)this.map.hasOwnProperty(ce)&&O.call(j,this.map[ce],ce,this)},P.prototype.keys=function(){var O=[];return this.forEach(function(j,ce){O.push(ce)}),A(O)},P.prototype.values=function(){var O=[];return this.forEach(function(j){O.push(j)}),A(O)},P.prototype.entries=function(){var O=[];return this.forEach(function(j,ce){O.push([ce,j])}),A(O)},l.iterable&&(P.prototype[Symbol.iterator]=P.prototype.entries);function U(O){if(O.bodyUsed)return Promise.reject(new TypeError("Already read"));O.bodyUsed=!0}function H(O){return new Promise(function(j,ce){O.onload=function(){j(O.result)},O.onerror=function(){ce(O.error)}})}function G(O){var j=new FileReader,ce=H(j);return j.readAsArrayBuffer(O),ce}function N(O){var j=new FileReader,ce=H(j);return j.readAsText(O),ce}function L(O){for(var j=new Uint8Array(O),ce=new Array(j.length),le=0;le<j.length;le++)ce[le]=String.fromCharCode(j[le]);return ce.join("")}function $(O){if(O.slice)return O.slice(0);var j=new Uint8Array(O.byteLength);return j.set(new Uint8Array(O)),j.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)||v(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=U(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?U(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(G)}),this.text=function(){var O=U(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 f(O){var j=O.toUpperCase();return I.indexOf(j)>-1?j:O}function x(O,j){j=j||{};var ce=j.body;if(O instanceof x){if(O.bodyUsed)throw new TypeError("Already read");this.url=O.url,this.credentials=O.credentials,j.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=j.credentials||this.credentials||"same-origin",(j.headers||!this.headers)&&(this.headers=new P(j.headers)),this.method=f(j.method||this.method||"GET"),this.mode=j.mode||this.mode||null,this.signal=j.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 j=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," ");j.append(decodeURIComponent(re),decodeURIComponent(ne))}}),j}function z(O){var j=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();j.append(ne,ae)}}),j}T.call(x.prototype);function ee(O,j){j||(j={}),this.type="default",this.status=j.status===void 0?200:j.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in j?j.statusText:"OK",this.headers=new P(j.headers),this.url=j.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,j){if(de.indexOf(j)===-1)throw new RangeError("Invalid status code");return new ee(null,{status:j,headers:{location:O}})},c.DOMException=o.DOMException;try{new c.DOMException}catch{c.DOMException=function(j,ce){this.message=j,this.name=ce;var le=Error(j);this.stack=le.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function me(O,j){return new Promise(function(ce,le){var re=new x(O,j);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:z(ne.getAllResponseHeaders()||"")};ie.url="responseURL"in ne?ne.responseURL:ie.headers.get("X-Request-URL");var Se="response"in ne?ne.response:ne.responseText;ce(new ee(Se,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,Se){ne.setRequestHeader(Se,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})(ph,ph.exports);var vg=gw(ph.exports);const yg={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},bg=10;class Vi{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new br.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!Sp(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=Uo(e),o=await(await vg(this.url,Object.assign(Object.assign({},yg),{body:n}))).json();this.onPayload({data:o})}catch(n){this.onError(e.id,n)}}async register(e=this.url){if(!Sp(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=Uo({id:1,jsonrpc:"2.0",method:"test",params:[]});await vg(e,Object.assign(Object.assign({},yg),{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"?Ku(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=rc(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return bp(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>bg&&this.events.setMaxListeners(bg)}}const _g="error",g7="wss://relay.walletconnect.com",m7="wc",w7="universal_provider",Eg=`${m7}@${2}:${w7}:`,v7="https://rpc.walletconnect.com/v1",di={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var qo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},gh={exports:{}};/**
73
73
  * @license
74
74
  * Lodash <https://lodash.com/>
75
75
  * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>