@walletconnect/ethereum-provider 2.8.2 → 2.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 Zu=function(t,e){return Zu=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])},Zu(t,e)};function K4(t,e){Zu(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Yu=function(){return Yu=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},Yu.apply(this,arguments)};function G4(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 Z4(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 Y4(t,e){return function(r,n){e(r,n,t)}}function J4(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function X4(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(x){c(x)}}function h(v){try{d(n.throw(v))}catch(x){c(x)}}function d(v){v.done?o(v.value):i(v.value).then(l,h)}d((n=n.apply(t,e||[])).next())})}function Q4(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 e_(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function t_(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Ju(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 r_(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Ep(arguments[e]));return t}function n_(){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 jo(t){return this instanceof jo?(this.v=t,this):new jo(t)}function i_(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,o=[];return i={},c("next"),c("throw"),c("return"),i[Symbol.asyncIterator]=function(){return this},i;function c(_){n[_]&&(i[_]=function(O){return new Promise(function(P,U){o.push([_,O,P,U])>1||l(_,O)})})}function l(_,O){try{h(n[_](O))}catch(P){x(o[0][3],P)}}function h(_){_.value instanceof jo?Promise.resolve(_.value.v).then(d,v):x(o[0][2],_)}function d(_){l("next",_)}function v(_){l("throw",_)}function x(_,O){_(O),o.shift(),o.length&&l(o[0][0],o[0][1])}}function s_(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,o){e[i]=t[i]?function(c){return(r=!r)?{value:jo(t[i](c)),done:i==="return"}:o?o(c):c}:o}}function o_(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Ju=="function"?Ju(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 a_(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function c_(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function l_(t){return t&&t.__esModule?t:{default:t}}function u_(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function h_(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var f_=Object.freeze({__proto__:null,__extends:K4,get __assign(){return Yu},__rest:G4,__decorate:Z4,__param:Y4,__metadata:J4,__awaiter:X4,__generator:Q4,__createBinding:e_,__exportStar:t_,__values:Ju,__read:Ep,__spread:r_,__spreadArrays:n_,__await:jo,__asyncGenerator:i_,__asyncDelegator:s_,__asyncValues:o_,__makeTemplateObject:a_,__importStar:c_,__importDefault:l_,__classPrivateFieldGet:u_,__classPrivateFieldSet:h_}),d_=Mi(f_),Wn={},xp;function p_(){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 g_(){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=d_;e.__exportStar(p_(),t),e.__exportStar(g_(),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 Xu(t=6){return BigInt(Ip(t))}function ec(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 tc(t,e,r){return{id:t,jsonrpc:"2.0",error:m_(e,r)}}function m_(t,e){return typeof t>"u"?yp(wp):(typeof t=="string"&&(t=Object.assign(Object.assign({},yp(Gu)),{message:t})),typeof e<"u"&&(t.data=e),q4(t.code)&&(t=V4(t.code)),t)}class w_{}class v_ extends w_{constructor(){super()}}class y_ extends v_{constructor(e){super()}}const b_="^https?:",__="^wss?:";function E_(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Op(t,e){const r=E_(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Ap(t){return Op(t,b_)}function Sp(t){return Op(t,__)}function x_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Dp(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function eh(t){return Dp(t)&&"method"in t}function rc(t){return Dp(t)&&(Vn(t)||En(t))}function Vn(t){return"result"in t}function En(t){return"error"in t}class hi extends y_{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(ec(e.method,e.params||[],e.id||Xu().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),rc(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 $p=10,C_=()=>typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:require("ws"),I_=()=>typeof window<"u",O_=C_();class A_{constructor(e){if(this.url=e,this.events=new br.exports.EventEmitter,this.registering=!1,!Sp(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(Mo(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!Sp(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:!x_(e)},o=new O_(e,[],i);I_()?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"?Vu(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=tc(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return bp(e,r,"WS")}resetMaxListeners(){this.events.getMaxListeners()>$p&&this.events.setMaxListeners($p)}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]",x="[object Date]",_="[object Error]",O="[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]",E="[object Symbol]",J="[object Undefined]",z="[object WeakMap]",ee="[object ArrayBuffer]",de="[object DataView]",me="[object Float32Array]",A="[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\]$/,Be=/^(?:0|[1-9]\d*)$/,ye={};ye[me]=ye[A]=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[x]=ye[_]=ye[O]=ye[U]=ye[H]=ye[N]=ye[T]=ye[I]=ye[f]=ye[z]=!1;var Me=typeof pr=="object"&&pr&&pr.Object===Object&&pr,X=typeof self=="object"&&self&&self.Object===Object&&self,Y=Me||X||Function("return this")(),W=e&&!e.nodeType&&e,w=W&&!0&&t&&!t.nodeType&&t,F=w&&w.exports===W,we=F&&Me.process,ve=function(){try{return we&&we.binding&&we.binding("util")}catch{}}(),Ue=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 ke(R){var q=-1,fe=Array(R.size);return R.forEach(function(Ce,It){fe[++q]=[It,Ce]}),fe}function Ke(R,q){return function(fe){return R(q(fe))}}function rt(R){var q=-1,fe=Array(R.size);return R.forEach(function(Ce){fe[++q]=Ce}),fe}var je=Array.prototype,Ze=Function.prototype,b=Object.prototype,p=Y["__core-js_shared__"],m=Ze.toString,D=b.hasOwnProperty,B=function(){var R=/[^.]+$/.exec(p&&p.keys&&p.keys.IE_PROTO||"");return R?"Symbol(src)_1."+R:""}(),K=b.toString,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=je.splice,Ur=Te?Te.toStringTag:void 0,Jn=Object.getOwnPropertySymbols,Ii=Ee?Ee.isBuffer:void 0,cs=Ke(Object.keys,Object),zt=Qr(Y,"DataView"),Lt=Qr(Y,"Map"),Wt=Qr(Y,"Promise"),qt=Qr(Y,"Set"),Ft=Qr(Y,"WeakMap"),Mt=Qr(Object,"create"),ir=Qn(zt),sr=Qn(Lt),Vt=Qn(Wt),or=Qn(qt),Kt=Qn(Ft),Xt=Te?Te.prototype:void 0,Gt=Xt?Xt.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=ls(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=ls(q,R);return fe<0?void 0:q[fe][1]}function qf(R){return ls(this.__data__,R)>-1}function Vf(R,q){var fe=this.__data__,Ce=ls(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 Xs(){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 Qs(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=Xs,Xn.prototype.delete=Kf,Xn.prototype.get=Qs,Xn.prototype.has=Gf,Xn.prototype.set=Zf;function eo(R){var q=-1,fe=R==null?0:R.length;for(this.__data__=new Xn;++q<fe;)this.add(R[q])}function Gc(R){return this.__data__.set(R,n),this}function Zc(R){return this.__data__.has(R)}eo.prototype.add=eo.prototype.push=Gc,eo.prototype.has=Zc;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 Yc(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=Yc;function Jc(R,q){var fe=no(R),Ce=!fe&&ll(R),It=!fe&&!Ce&&va(R),Xe=!fe&&!Ce&&!It&&fl(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")||il(Ot,mt)))&&lr.push(Ot);return lr}function ls(R,q){for(var fe=R.length;fe--;)if(cl(R[fe][0],q))return fe;return-1}function ma(R,q,fe){var Ce=q(R);return no(R)?Ce:at(Ce,fe(R))}function us(R){return R==null?R===void 0?J:G:Ur&&Ur in Object(R)?rl(R):r0(R)}function wa(R){return fs(R)&&us(R)==l}function hs(R,q,fe,Ce,It){return R===q?!0:R==null||q==null||!fs(R)&&!fs(q)?R!==R&&q!==q:Xc(R,q,fe,Ce,hs,It)}function Xc(R,q,fe,Ce,It,Xe){var Tt=no(R),lr=no(q),mt=Tt?h:jn(R),Ot=lr?h:jn(q);mt=mt==l?N:mt,Ot=Ot==l?N:Ot;var Qt=mt==N,qr=Ot==N,ur=mt==Ot;if(ur&&va(R)){if(!va(q))return!1;Tt=!0,Qt=!1}if(ur&&!Qt)return Xe||(Xe=new xn),Tt||fl(R)?to(R,q,fe,Ce,It,Xe):t0(R,q,mt,fe,Ce,It,Xe);if(!(fe&i)){var Rt=Qt&&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),tl(R,q,fe,Ce,It,Xe)):!1}function e0(R){if(!hl(R)||ol(R))return!1;var q=io(R)?Q:ge;return q.test(Qn(R))}function Qc(R){return fs(R)&&ul(R.length)&&!!ye[us(R)]}function el(R){if(!al(R))return cs(R);var q=[];for(var fe in Object(R))D.call(R,fe)&&fe!="constructor"&&q.push(fe);return q}function to(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 Qt=-1,qr=!0,ur=fe&o?new eo:void 0;for(Xe.set(R,q),Xe.set(q,R);++Qt<lr;){var Rt=R[Qt],jr=q[Qt];if(Ce)var Cn=Tt?Ce(jr,Rt,Qt,q,R,Xe):Ce(Rt,jr,Qt,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 x:case H:return cl(+R,+q);case _:return R.name==q.name&&R.message==q.message;case T:case f:return R==q+"";case U:var lr=ke;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 Qt=to(lr(R),lr(q),Ce,It,Xe,Tt);return Tt.delete(R),Qt;case E:if(Gt)return Gt.call(R)==Gt.call(q)}return!1}function tl(R,q,fe,Ce,It,Xe){var Tt=fe&i,lr=ro(R),mt=lr.length,Ot=ro(q),Qt=Ot.length;if(mt!=Qt&&!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 ya=Tt?Ce(Fn,dn,ur,q,R,Xe):Ce(dn,Fn,ur,R,q,Xe);if(!(ya===void 0?dn===Fn||It(dn,Fn,fe,Ce,Xe):ya)){jr=!1;break}Cn||(Cn=ur=="constructor")}if(jr&&!Cn){var ds=R.constructor,vr=q.constructor;ds!=vr&&"constructor"in R&&"constructor"in q&&!(typeof ds=="function"&&ds instanceof ds&&typeof vr=="function"&&vr instanceof vr)&&(jr=!1)}return Xe.delete(R),Xe.delete(q),jr}function ro(R){return ma(R,s0,nl)}function Oi(R,q){var fe=R.__data__;return sl(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 rl(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 nl=Jn?function(R){return R==null?[]:(R=Object(R),nt(Jn(R),function(q){return ht.call(R,q)}))}:Ct,jn=us;(zt&&jn(new zt(new ArrayBuffer(1)))!=de||Lt&&jn(new Lt)!=U||Wt&&jn(Wt.resolve())!=L||qt&&jn(new qt)!=I||Ft&&jn(new Ft)!=z)&&(jn=function(R){var q=us(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 Vt:return L;case or:return I;case Kt:return z}return q});function il(R,q){return q=q??c,!!q&&(typeof R=="number"||Be.test(R))&&R>-1&&R%1==0&&R<q}function sl(R){var q=typeof R;return q=="string"||q=="number"||q=="symbol"||q=="boolean"?R!=="__proto__":R===null}function ol(R){return!!B&&B in R}function al(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 cl(R,q){return R===q||R!==R&&q!==q}var ll=wa(function(){return arguments}())?wa:function(R){return fs(R)&&D.call(R,"callee")&&!ht.call(R,"callee")},no=Array.isArray;function n0(R){return R!=null&&ul(R.length)&&!io(R)}var va=Ii||xt;function i0(R,q){return hs(R,q)}function io(R){if(!hl(R))return!1;var q=us(R);return q==O||q==P||q==d||q==$}function ul(R){return typeof R=="number"&&R>-1&&R%1==0&&R<=c}function hl(R){var q=typeof R;return R!=null&&(q=="object"||q=="function")}function fs(R){return R!=null&&typeof R=="object"}var fl=Ue?$t(Ue):Qc;function s0(R){return n0(R)?Jc(R):el(R)}function Ct(){return[]}function xt(){return!1}t.exports=i0})(th,th.exports);var S_=th.exports,D_=Object.defineProperty,Pp=Object.getOwnPropertySymbols,$_=Object.prototype.hasOwnProperty,P_=Object.prototype.propertyIsEnumerable,Tp=(t,e,r)=>e in t?D_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rr=(t,e)=>{for(var r in e||(e={}))$_.call(e,r)&&Tp(t,r,e[r]);if(Pp)for(var r of Pp(e))P_.call(e,r)&&Tp(t,r,e[r]);return t};function T_(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 x(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 E=L-H;E!==L&&$[E]===0;)E++;for(var J=h.repeat(U);E<L;++E)J+=t.charAt($[E]);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 E=new Uint8Array(H+(N-f)),J=H;f!==N;)E[J++]=L[f++];return E}}}function O(P){var U=_(P);if(U)return U;throw new Error(`Non-${e} character`)}return{encode:x,decodeUnsafe:_,decode:O}}var R_=T_,N_=R_;const Rp=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")},L_=t=>new TextEncoder().encode(t),M_=t=>new TextDecoder().decode(t);class U_{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 j_{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 Np(this,e)}}class F_{constructor(e){this.decoders=e}or(e){return Np(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 Np=(t,e)=>new F_(Rr(Rr({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class B_{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new U_(e,r,n),this.decoder=new j_(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const nc=({name:t,prefix:e,encode:r,decode:n})=>new B_(t,e,r,n),Fo=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=N_(r,e);return nc({prefix:t,name:e,encode:n,decode:o=>Rp(i(o))})},k_=(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 x=i[t[v]];if(x===void 0)throw new SyntaxError(`Non-${n} character`);h=h<<r|x,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},H_=(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})=>nc({prefix:e,name:t,encode(i){return H_(i,n,r)},decode(i){return k_(i,n,r,t)}}),z_=nc({prefix:"\0",name:"identity",encode:t=>M_(t),decode:t=>L_(t)});var W_=Object.freeze({__proto__:null,identity:z_});const q_=Er({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var V_=Object.freeze({__proto__:null,base2:q_});const K_=Er({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var G_=Object.freeze({__proto__:null,base8:K_});const Z_=Fo({prefix:"9",name:"base10",alphabet:"0123456789"});var Y_=Object.freeze({__proto__:null,base10:Z_});const J_=Er({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),X_=Er({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Q_=Object.freeze({__proto__:null,base16:J_,base16upper:X_});const e8=Er({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),t8=Er({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),r8=Er({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),n8=Er({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),i8=Er({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),s8=Er({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),o8=Er({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),a8=Er({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),c8=Er({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var l8=Object.freeze({__proto__:null,base32:e8,base32upper:t8,base32pad:r8,base32padupper:n8,base32hex:i8,base32hexupper:s8,base32hexpad:o8,base32hexpadupper:a8,base32z:c8});const u8=Fo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),h8=Fo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var f8=Object.freeze({__proto__:null,base36:u8,base36upper:h8});const d8=Fo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),p8=Fo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var g8=Object.freeze({__proto__:null,base58btc:d8,base58flickr:p8});const m8=Er({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),w8=Er({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),v8=Er({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),y8=Er({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var b8=Object.freeze({__proto__:null,base64:m8,base64pad:w8,base64url:v8,base64urlpad:y8});const Lp=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}"),_8=Lp.reduce((t,e,r)=>(t[r]=e,t),[]),E8=Lp.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function x8(t){return t.reduce((e,r)=>(e+=_8[r],e),"")}function C8(t){const e=[];for(const r of t){const n=E8[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const I8=nc({prefix:"\u{1F680}",name:"base256emoji",encode:x8,decode:C8});var O8=Object.freeze({__proto__:null,base256emoji:I8}),A8=Up,Mp=128,S8=127,D8=~S8,$8=Math.pow(2,31);function Up(t,e,r){e=e||[],r=r||0;for(var n=r;t>=$8;)e[r++]=t&255|Mp,t/=128;for(;t&D8;)e[r++]=t&255|Mp,t>>>=7;return e[r]=t|0,Up.bytes=r-n+1,e}var P8=rh,T8=128,jp=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&jp)<<i:(c&jp)*Math.pow(2,i),i+=7}while(c>=T8);return rh.bytes=o-n,r}var R8=Math.pow(2,7),N8=Math.pow(2,14),L8=Math.pow(2,21),M8=Math.pow(2,28),U8=Math.pow(2,35),j8=Math.pow(2,42),F8=Math.pow(2,49),B8=Math.pow(2,56),k8=Math.pow(2,63),H8=function(t){return t<R8?1:t<N8?2:t<L8?3:t<M8?4:t<U8?5:t<j8?6:t<F8?7:t<B8?8:t<k8?9:10},z8={encode:A8,decode:P8,encodingLength:H8},Fp=z8;const Bp=(t,e,r=0)=>(Fp.encode(t,e,r),e),kp=t=>Fp.encodingLength(t),nh=(t,e)=>{const r=e.byteLength,n=kp(t),i=n+kp(r),o=new Uint8Array(i+r);return Bp(t,o,0),Bp(r,o,n),o.set(e,i),new W8(t,r,e,o)};class W8{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Hp=({name:t,code:e,encode:r})=>new q8(t,e,r);class q8{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 zp=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),V8=Hp({name:"sha2-256",code:18,encode:zp("SHA-256")}),K8=Hp({name:"sha2-512",code:19,encode:zp("SHA-512")});var G8=Object.freeze({__proto__:null,sha256:V8,sha512:K8});const Wp=0,Z8="identity",qp=Rp;var Y8=Object.freeze({__proto__:null,identity:{code:Wp,name:Z8,encode:qp,digest:t=>nh(Wp,qp(t))}});new TextEncoder,new TextDecoder;const Vp=Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr({},W_),V_),G_),Y_),Q_),l8),f8),g8),b8),O8);Rr(Rr({},G8),Y8);function Kp(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function J8(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Kp(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Gp(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Zp=Gp("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ih=Gp("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=J8(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),X8=Rr({utf8:Zp,"utf-8":Zp,hex:Vp.base16,latin1:ih,ascii:ih,binary:ih},Vp);function Q8(t,e="utf8"){const r=X8[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Kp(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}const Yp="wc",eE=2,sh="core",fi=`${Yp}@2:${sh}:`,tE={name:sh,logger:"error"},rE={database:":memory:"},nE="crypto",Jp="client_ed25519_seed",iE=Re.ONE_DAY,sE="keychain",oE="0.3",aE="messages",cE="0.3",lE=Re.SIX_HOURS,uE="publisher",Xp="irn",hE="error",Qp="wss://relay.walletconnect.com",fE="relayer",kt={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"},dE="_subscription",Bo={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},pE=Re.ONE_SECOND/2,gE="2.8.2",mE=1e4,wE="0.3",vE="WALLETCONNECT_CLIENT_ID",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=Re.FIVE_SECONDS*1e3,EE="pairing",xE="0.3",ko={wc_pairingDelete:{req:{ttl:Re.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:Re.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:Re.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:Re.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:Re.ONE_DAY,prompt:!1,tag:0},res:{ttl:Re.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",eg="https://verify.walletconnect.com";class SE{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=sE,this.version=oE,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=nE,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=M5();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const o=await this.getClientSeed(),c=mp(o),l=Iu();return await F4(l,i,iE,c)},this.generateSharedKey=(i,o,c)=>{this.isInitialized();const l=this.getPrivateKey(i),h=U5(l,o);return this.setSymKey(h,c)},this.setSymKey=async(i,o)=>{this.isInitialized();const c=o||j5(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=Mo(o);if(C1(l)){const _=l.senderPublicKey,O=l.receiverPublicKey;i=await this.generateSharedKey(_,O)}const d=this.getSymKey(i),{type:v,senderPublicKey:x}=l;return B5({type:v,symKey:d,message:h,senderPublicKey:x})},this.decode=async(i,o,c)=>{this.isInitialized();const l=z5(o,c);if(C1(l)){const v=l.receiverPublicKey,x=l.senderPublicKey;i=await this.generateSharedKey(v,x)}const h=this.getSymKey(i),d=k5({symKey:h,encoded:o});return Vu(d)},this.getPayloadType=i=>{const o=Va(i);return Io(o.type)},this.getPayloadSenderPublicKey=i=>{const o=Va(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(Jp)}catch{e=Iu(),await this.keychain.set(Jp,e)}return Q8(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 g4{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=aE,this.version=cE,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=Os(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=Os(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 m4{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new br.exports.EventEmitter,this.name=uE,this.queue=new Map,this.publishTimeout=Re.toMiliseconds(Re.TEN_SECONDS),this.queueTimeout=Re.toMiliseconds(Re.FIVE_SECONDS),this.needsTransportRestart=!1,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||lE,l=Du(o),h=o?.prompt||!1,d=o?.tag||0,v=o?.id||Xu().toString(),x={topic:n,message:i,opts:{ttl:c,relay:l,prompt:h,tag:d,id:v}},_=setTimeout(()=>this.queue.set(v,x),this.queueTimeout);try{await await Ka(this.rpcPublish(n,i,c,l,h,d,v),this.publishTimeout),clearTimeout(_),this.relayer.events.emit(kt.publish,x)}catch{this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0;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,x;const _={method:Ga(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)&&((x=_.params)==null||delete x.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(Po.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(kt.connection_stalled);return}this.checkQueue()}),this.relayer.on(kt.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,tg=Object.getOwnPropertySymbols,ME=Object.prototype.hasOwnProperty,UE=Object.prototype.propertyIsEnumerable,rg=(t,e,r)=>e in t?RE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ho=(t,e)=>{for(var r in e||(e={}))ME.call(e,r)&&rg(t,r,e[r]);if(tg)for(var r of tg(e))UE.call(e,r)&&rg(t,r,e[r]);return t},ah=(t,e)=>NE(t,LE(e));class jE extends y4{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=Du(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 Re.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=Du(n);await this.rpcUnsubscribe(e,r,i);const o=Yt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,o),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){const n={method:Ga(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await Ka(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(kt.connection_stalled)}return Os(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Ga(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 Ka(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(kt.connection_stalled)}}rpcUnsubscribe(e,r,n){const i={method:Ga(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(Ho({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Ho({},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,Ho({},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(Ho({},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(Ho({},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(Po.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(kt.connect,async()=>{await this.onConnect()}),this.relayer.on(kt.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,ng=Object.getOwnPropertySymbols,BE=Object.prototype.hasOwnProperty,kE=Object.prototype.propertyIsEnumerable,ig=(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)&&ig(t,r,e[r]);if(ng)for(var r of ng(e))kE.call(e,r)&&ig(t,r,e[r]);return t};class zE extends w4{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new br.exports.EventEmitter,this.name=fE,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||hE})),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||Qp,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)},mE)}get context(){return pt.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"";return i||(await Promise.all([new Promise(o=>{this.subscriber.once(Pn.created,c=>{c.topic===e&&o()})}),new Promise(async o=>{i=await this.subscriber.subscribe(e,r),o()})]),i)}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportClose(){this.transportExplicitlyClosed=!0,this.connected&&(await this.provider.disconnect(),this.events.emit(kt.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 Ka(this.provider.connect(),5e3,"socket stalled").catch(i=>n(i)).then(()=>r()).finally(()=>this.removeListener(kt.transport_closed,this.rejectTransportOpen))}),new Promise(r=>this.once(kt.transport_closed,this.rejectTransportOpen))])])}catch(r){this.logger.error(r);const n=r;if(!this.isConnectionStalled(n.message))throw r;this.events.emit(kt.transport_closed)}finally{this.reconnecting=!1}}}async restartTransport(e){this.transportExplicitlyClosed||this.reconnecting||(this.relayUrl=e||this.relayUrl,this.connected&&await Promise.all([new Promise(r=>{this.provider.once(Bo.disconnect,()=>{r()})}),this.transportClose()]),await this.createProvider(),await this.transportOpen())}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}rejectTransportOpen(){throw new Error("Attempt to connect to relay via `transportOpen` has stalled. Retrying...")}async createProvider(){const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new hi(new A_(eb({sdkVersion:gE,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(dE))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 rc(e)&&this.events.emit(kt.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(kt.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(Bo.payload,e=>this.onProviderPayload(e)),this.provider.on(Bo.connect,()=>{this.events.emit(kt.connect)}),this.provider.on(Bo.disconnect,()=>{this.onProviderDisconnect()}),this.provider.on(Bo.error,e=>{this.logger.error(e),this.events.emit(kt.error,e)})}registerEventListeners(){this.events.on(kt.connection_stalled,async()=>{await this.restartTransport()})}onProviderDisconnect(){this.events.emit(kt.disconnect),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||setTimeout(async()=>{await this.restartTransport()},Re.toMiliseconds(pE))}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,sg=Object.getOwnPropertySymbols,qE=Object.prototype.hasOwnProperty,VE=Object.prototype.propertyIsEnumerable,og=(t,e,r)=>e in t?WE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ag=(t,e)=>{for(var r in e||(e={}))qE.call(e,r)&&og(t,r,e[r]);if(sg)for(var r of sg(e))VE.call(e,r)&&og(t,r,e[r]);return t};class ic extends v4{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=wE,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):xb(c)?this.map.set(c.id,c):Cb(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=>S_(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=ag(ag({},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=Iu(),i=await this.core.crypto.setSymKey(n),o=$n(Re.FIVE_MINUTES),c={protocol:Xp},l={topic:i,expiry:o,relay:c,active:!1},h=db({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}=ub(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(Re.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(Re.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}=As();this.events.once(rr("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",Yt("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,o)=>{const c=ec(i,o),l=await this.core.crypto.encode(n,c),h=ko[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=ko[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=tc(n,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,n),d=ko[h.request.method]?ko[h.request.method].res:ko.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,Yt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{const n=this.pairings.getAll().filter(i=>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(rr("pairing_ping",o),{}):En(i)&&this.events.emit(rr("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=Yt("WC_METHOD_UNSUPPORTED",c);await this.sendError(o,n,l),this.logger.error(l)}catch(l){await this.sendError(o,n,l),this.logger.error(l)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(Yt("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{if(!zr(n)){const{message:i}=_e("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(i)}if(!Eb(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 ic(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(kt.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})):rc(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 p4{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:ec(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 b4{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 tb(e);if(typeof e=="number")return rb(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;Re.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(Po.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 _4{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=oh,this.initialized=!1,this.init=async n=>{S1()||!Au()||(this.verifyUrl=n?.verifyUrl||eg,await this.createIframe())},this.register=async n=>{var i;if(this.initialized||await this.init(),!!this.iframe)try{(i=this.iframe.contentWindow)==null||i.postMessage(n.attestationId,this.verifyUrl),this.logger.info(`postMessage sent: ${n.attestationId} ${this.verifyUrl}`)}catch{}},this.resolve=async n=>{var i;if(this.isDevEnv)return"";this.logger.info(`resolving attestation: ${n.attestationId}`);const o=this.startAbortTimer(Re.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"),Re.toMiliseconds(Re.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=eg,this.abortController=new AbortController,this.isDevEnv=Ou()&&process.env.IS_VITEST}get context(){return pt.getLoggerContext(this.logger)}startAbortTimer(e){return setTimeout(()=>this.abortController.abort(),Re.toMiliseconds(e))}}var JE=Object.defineProperty,cg=Object.getOwnPropertySymbols,XE=Object.prototype.hasOwnProperty,QE=Object.prototype.propertyIsEnumerable,lg=(t,e,r)=>e in t?JE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ug=(t,e)=>{for(var r in e||(e={}))XE.call(e,r)&&lg(t,r,e[r]);if(cg)for(var r of cg(e))QE.call(e,r)&&lg(t,r,e[r]);return t};class ch extends d4{constructor(e){super(e),this.protocol=Yp,this.version=eE,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||Qp;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||tE.logger}));this.logger=pt.generateChildLogger(r,this.name),this.heartbeat=new Po.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 w6(ug(ug({},rE),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);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(vE,n),r}get context(){return pt.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const e7=ch,hg="wc",fg=2,dg="client",lh=`${hg}@${fg}:${dg}:`,uh={name:dg,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},t7="WALLETCONNECT_DEEPLINK_CHOICE",r7="proposal",pg="Proposal expired",n7="session",sc=Re.SEVEN_DAYS,i7="engine",zo={wc_sessionPropose:{req:{ttl:Re.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Re.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:Re.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Re.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Re.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Re.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Re.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Re.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Re.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Re.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Re.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Re.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Re.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Re.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Re.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:Re.THIRTY_SECONDS,prompt:!1,tag:1115}}},hh={min:Re.FIVE_MINUTES,max:Re.SEVEN_DAYS},s7="request",o7=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var a7=Object.defineProperty,c7=Object.defineProperties,l7=Object.getOwnPropertyDescriptors,gg=Object.getOwnPropertySymbols,u7=Object.prototype.hasOwnProperty,h7=Object.prototype.propertyIsEnumerable,mg=(t,e,r)=>e in t?a7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,an=(t,e)=>{for(var r in e||(e={}))u7.call(e,r)&&mg(t,r,e[r]);if(gg)for(var r of gg(e))h7.call(e,r)&&mg(t,r,e[r]);return t},fh=(t,e)=>c7(t,l7(e));class f7 extends x4{constructor(e){super(e),this.name=i7,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(zo)}),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,x=!1;if(d&&(x=this.client.core.pairing.pairings.get(d).active),!d||!x){const{topic:L,uri:$}=await this.client.core.pairing.create();d=L,v=$}const _=await this.client.core.crypto.generateKeyPair(),O=an({requiredNamespaces:o,optionalNamespaces:c,relays:h??[{protocol:Xp}],proposer:{publicKey:_,metadata:this.client.metadata}},l&&{sessionProperties:l}),{reject:P,resolve:U,done:H}=As(Re.FIVE_MINUTES,pg);if(this.events.once(rr("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",O),N=$n(Re.FIVE_MINUTES);return await this.setProposal(G,an({id:G,expiry:N},O)),{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:x}=l;h=h||"",Ds(v)||(v=wb(o,"approve()"));const _=await this.client.core.crypto.generateKeyPair(),O=d.publicKey,P=await this.client.core.crypto.generateSharedKey(_,O);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,Yt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:h}));const U=an({relay:{protocol:i??"irn"},namespaces:o,requiredNamespaces:v,optionalNamespaces:x,pairingTopic:h,controller:{publicKey:_,metadata:this.client.metadata},expiry:$n(sc)},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(sc)),{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,Yt("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}=As();return this.events.once(rr("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}=As();return this.events.once(rr("session_extend",i),({error:h})=>{h?l(h):c()}),await this.setExpiry(n,$n(sc)),{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}=As(c);this.events.once(rr("session_request",l),({error:_,result:O})=>{_?v(_):d(O)}),this.client.events.emit("session_request_sent",{topic:o,request:i,chainId:n,id:l});const x=await this.client.core.storage.getItem(t7);return nb({id:l,topic:o,wcDeepLink:x}),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}=As();this.events.once(rr("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;if(this.client.session.keys.includes(n)){const i=Xu().toString();let o;const c=l=>{l?.id.toString()===i&&(this.client.core.relayer.events.removeListener(kt.message_ack,c),o())};await Promise.all([new Promise(l=>{o=l,this.client.core.relayer.on(kt.message_ack,c)}),this.sendRequest(n,"wc_sessionDelete",Yt("USER_DISCONNECTED"),void 0,i)]),await this.deleteSession(n)}else await this.client.core.pairing.disconnect({topic:n})},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>bb(n,r))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{const n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(o=>{var c,l;return((c=o.peerMetadata)==null?void 0:c.url)&&((l=o.peerMetadata)==null?void 0:l.url)===r.peer.metadata.url&&o.topic&&o.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(o=>this.client.core.pairing.disconnect({topic:o.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async(r,n)=>{const{self:i}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),this.client.session.delete(r,Yt("USER_DISCONNECTED")),this.client.core.crypto.keychain.has(i.publicKey)&&await this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r)},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,Yt("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)])},this.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=zo.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,c)=>{const l=ec(n,i);if(Au()&&o7.includes(n)){const v=Os(JSON.stringify(l));await this.client.core.verify.register({attestationId:v})}const h=await this.client.core.crypto.encode(r,l),d=zo[n].req;return o&&(d.ttl=o),c&&(d.id=c),this.client.core.history.set(r,l),this.client.core.relayer.publish(r,h,d),l.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=zo[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=tc(r,i),c=await this.client.core.crypto.encode(n,o),l=await this.client.core.history.get(n,r),h=zo[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.onRelayEventUnknownPayload=r=>{const{topic:n}=r,{message:i}=_e("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.onSessionProposeRequest=async(r,n)=>{const{params:i,id:o}=n;try{this.isValidConnect(an({},n.params));const c=$n(Re.FIVE_MINUTES),l=an({id:o,pairingTopic:r,expiry:c},i);await this.setProposal(o,l);const h=Os(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,Yt("USER_DISCONNECTED")),this.events.emit(rr("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:x,sessionProperties:_,pairingTopic:O}=n.params,P=an({topic:r,relay:c,expiry:h,namespaces:d,acknowledged:!0,pairingTopic:O,requiredNamespaces:v,optionalNamespaces:x,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(rr("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(rr("session_approve",i),{})):En(n)&&(await this.client.session.delete(r,Yt("USER_DISCONNECTED")),this.events.emit(rr("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(rr("session_update",i),{}):En(n)&&this.events.emit(rr("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(sc)),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(rr("session_extend",i),{}):En(n)&&this.events.emit(rr("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(rr("session_ping",i),{}):En(n)&&this.events.emit(rr("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(kt.publish,async()=>{o(await this.deleteSession(r))})}),this.sendResult(i,r,!0)]),this.client.events.emit("session_delete",{id:i,topic:r})}catch(o){this.client.logger.error(o)}},this.onSessionRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidRequest(an({topic:r},o)),await this.setPendingSessionRequest({id:i,topic:r,params:o});const c=Os(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(rr("session_request",i),{result:n.result}):En(n)&&this.events.emit(rr("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),!Tb(l,!0)){const{message:h}=_e("MISSING_OR_INVALID",`connect() relays: ${l}`);throw new Error(h)}!Pr(i)&&Ds(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Pr(o)&&Ds(o)!==0&&this.validateNamespaces(o,"optionalNamespaces"),Pr(c)||this.validateSessionProps(c,"sessionProperties")},this.validateNamespaces=(r,n)=>{const i=Pb(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=Ya(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),!Nb(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=Ib(i,"onSessionSettleRequest()");if(l)throw new Error(l.message);const h=Ya(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=Ya(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(!Lb(i)){const{message:h}=_e("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(h)}if(!jb(l,o,i.method)){const{message:h}=_e("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(h)}if(c&&!Hb(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),!Mb(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(!Ub(i)){const{message:l}=_e("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}if(!Fb(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(kt.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})):rc(i)?(await this.client.core.history.resolve(i),this.onRelayEventResponse({topic:r,payload:i})):this.onRelayEventUnknownPayload({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(!Rb(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 d7 extends ic{constructor(e,r){super(e,r,r7,lh),this.core=e,this.logger=r}}class p7 extends ic{constructor(e,r){super(e,r,n7,lh),this.core=e,this.logger=r}}class g7 extends ic{constructor(e,r){super(e,r,s7,lh,n=>n.id),this.core=e,this.logger=r}}class dh extends E4{constructor(e){super(e),this.protocol=hg,this.version=fg,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||Y5();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 p7(this.core,this.logger),this.proposal=new d7(this.core,this.logger),this.pendingRequest=new g7(this.core,this.logger),this.engine=new f7(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(A){return A&&DataView.prototype.isPrototypeOf(A)}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(A){return A&&d.indexOf(Object.prototype.toString.call(A))>-1};function x(A){if(typeof A!="string"&&(A=String(A)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(A))throw new TypeError("Invalid character in header field name");return A.toLowerCase()}function _(A){return typeof A!="string"&&(A=String(A)),A}function O(A){var j={next:function(){var ce=A.shift();return{done:ce===void 0,value:ce}}};return l.iterable&&(j[Symbol.iterator]=function(){return j}),j}function P(A){this.map={},A instanceof P?A.forEach(function(j,ce){this.append(ce,j)},this):Array.isArray(A)?A.forEach(function(j){this.append(j[0],j[1])},this):A&&Object.getOwnPropertyNames(A).forEach(function(j){this.append(j,A[j])},this)}P.prototype.append=function(A,j){A=x(A),j=_(j);var ce=this.map[A];this.map[A]=ce?ce+", "+j:j},P.prototype.delete=function(A){delete this.map[x(A)]},P.prototype.get=function(A){return A=x(A),this.has(A)?this.map[A]:null},P.prototype.has=function(A){return this.map.hasOwnProperty(x(A))},P.prototype.set=function(A,j){this.map[x(A)]=_(j)},P.prototype.forEach=function(A,j){for(var ce in this.map)this.map.hasOwnProperty(ce)&&A.call(j,this.map[ce],ce,this)},P.prototype.keys=function(){var A=[];return this.forEach(function(j,ce){A.push(ce)}),O(A)},P.prototype.values=function(){var A=[];return this.forEach(function(j){A.push(j)}),O(A)},P.prototype.entries=function(){var A=[];return this.forEach(function(j,ce){A.push([ce,j])}),O(A)},l.iterable&&(P.prototype[Symbol.iterator]=P.prototype.entries);function U(A){if(A.bodyUsed)return Promise.reject(new TypeError("Already read"));A.bodyUsed=!0}function H(A){return new Promise(function(j,ce){A.onload=function(){j(A.result)},A.onerror=function(){ce(A.error)}})}function G(A){var j=new FileReader,ce=H(j);return j.readAsArrayBuffer(A),ce}function N(A){var j=new FileReader,ce=H(j);return j.readAsText(A),ce}function L(A){for(var j=new Uint8Array(A),ce=new Array(j.length),le=0;le<j.length;le++)ce[le]=String.fromCharCode(j[le]);return ce.join("")}function $(A){if(A.slice)return A.slice(0);var j=new Uint8Array(A.byteLength);return j.set(new Uint8Array(A)),j.buffer}function T(){return this.bodyUsed=!1,this._initBody=function(A){this._bodyInit=A,A?typeof A=="string"?this._bodyText=A:l.blob&&Blob.prototype.isPrototypeOf(A)?this._bodyBlob=A:l.formData&&FormData.prototype.isPrototypeOf(A)?this._bodyFormData=A:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(A)?this._bodyText=A.toString():l.arrayBuffer&&l.blob&&h(A)?(this._bodyArrayBuffer=$(A.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(A)||v(A))?this._bodyArrayBuffer=$(A):this._bodyText=A=Object.prototype.toString.call(A):this._bodyText="",this.headers.get("content-type")||(typeof A=="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(A)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var A=U(this);if(A)return A;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 A=U(this);if(A)return A;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(A){var j=A.toUpperCase();return I.indexOf(j)>-1?j:A}function E(A,j){j=j||{};var ce=j.body;if(A instanceof E){if(A.bodyUsed)throw new TypeError("Already read");this.url=A.url,this.credentials=A.credentials,j.headers||(this.headers=new P(A.headers)),this.method=A.method,this.mode=A.mode,this.signal=A.signal,!ce&&A._bodyInit!=null&&(ce=A._bodyInit,A.bodyUsed=!0)}else this.url=String(A);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)}E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function J(A){var j=new FormData;return A.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(A){var j=new P,ce=A.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(E.prototype);function ee(A,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(A)}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 A=new ee(null,{status:0,statusText:""});return A.type="error",A};var de=[301,302,303,307,308];ee.redirect=function(A,j){if(de.indexOf(j)===-1)throw new RangeError("Invalid status code");return new ee(null,{status:j,headers:{location:A}})},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(A,j){return new Promise(function(ce,le){var re=new E(A,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=E,o.Response=ee),c.Headers=P,c.Request=E,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 wg=dw(ph.exports);const vg={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},yg=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,!Ap(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=Mo(e),o=await(await wg(this.url,Object.assign(Object.assign({},vg),{body:n}))).json();this.onPayload({data:o})}catch(n){this.onError(e.id,n)}}async register(e=this.url){if(!Ap(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=Mo({id:1,jsonrpc:"2.0",method:"test",params:[]});await wg(e,Object.assign(Object.assign({},vg),{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"?Vu(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=tc(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return bp(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>yg&&this.events.setMaxListeners(yg)}}const bg="error",m7="wss://relay.walletconnect.com",w7="wc",v7="universal_provider",_g=`${w7}@2:${v7}:`,y7="https://rpc.walletconnect.com/v1",di={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Wo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},gh={exports:{}};/**
72
+ ***************************************************************************** */var Zu=function(t,e){return Zu=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])},Zu(t,e)};function K4(t,e){Zu(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Yu=function(){return Yu=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},Yu.apply(this,arguments)};function G4(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 Z4(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 Y4(t,e){return function(r,n){e(r,n,t)}}function J4(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function X4(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(x){c(x)}}function h(v){try{d(n.throw(v))}catch(x){c(x)}}function d(v){v.done?o(v.value):i(v.value).then(l,h)}d((n=n.apply(t,e||[])).next())})}function Q4(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 e_(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function t_(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Ju(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 r_(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Ep(arguments[e]));return t}function n_(){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 jo(t){return this instanceof jo?(this.v=t,this):new jo(t)}function i_(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,o=[];return i={},c("next"),c("throw"),c("return"),i[Symbol.asyncIterator]=function(){return this},i;function c(_){n[_]&&(i[_]=function(O){return new Promise(function(P,U){o.push([_,O,P,U])>1||l(_,O)})})}function l(_,O){try{h(n[_](O))}catch(P){x(o[0][3],P)}}function h(_){_.value instanceof jo?Promise.resolve(_.value.v).then(d,v):x(o[0][2],_)}function d(_){l("next",_)}function v(_){l("throw",_)}function x(_,O){_(O),o.shift(),o.length&&l(o[0][0],o[0][1])}}function s_(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,o){e[i]=t[i]?function(c){return(r=!r)?{value:jo(t[i](c)),done:i==="return"}:o?o(c):c}:o}}function o_(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Ju=="function"?Ju(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 a_(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function c_(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function l_(t){return t&&t.__esModule?t:{default:t}}function u_(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function h_(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var f_=Object.freeze({__proto__:null,__extends:K4,get __assign(){return Yu},__rest:G4,__decorate:Z4,__param:Y4,__metadata:J4,__awaiter:X4,__generator:Q4,__createBinding:e_,__exportStar:t_,__values:Ju,__read:Ep,__spread:r_,__spreadArrays:n_,__await:jo,__asyncGenerator:i_,__asyncDelegator:s_,__asyncValues:o_,__makeTemplateObject:a_,__importStar:c_,__importDefault:l_,__classPrivateFieldGet:u_,__classPrivateFieldSet:h_}),d_=Mi(f_),Wn={},xp;function p_(){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 g_(){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=d_;e.__exportStar(p_(),t),e.__exportStar(g_(),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 Xu(t=6){return BigInt(Ip(t))}function ec(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 tc(t,e,r){return{id:t,jsonrpc:"2.0",error:m_(e,r)}}function m_(t,e){return typeof t>"u"?yp(wp):(typeof t=="string"&&(t=Object.assign(Object.assign({},yp(Gu)),{message:t})),typeof e<"u"&&(t.data=e),q4(t.code)&&(t=V4(t.code)),t)}class w_{}class v_ extends w_{constructor(){super()}}class y_ extends v_{constructor(e){super()}}const b_="^https?:",__="^wss?:";function E_(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Op(t,e){const r=E_(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Ap(t){return Op(t,b_)}function Sp(t){return Op(t,__)}function x_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Dp(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function eh(t){return Dp(t)&&"method"in t}function rc(t){return Dp(t)&&(Vn(t)||En(t))}function Vn(t){return"result"in t}function En(t){return"error"in t}class hi extends y_{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(ec(e.method,e.params||[],e.id||Xu().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),rc(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 $p=10,C_=()=>typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:require("ws"),I_=()=>typeof window<"u",O_=C_();class A_{constructor(e){if(this.url=e,this.events=new br.exports.EventEmitter,this.registering=!1,!Sp(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(Mo(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!Sp(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:!x_(e)},o=new O_(e,[],i);I_()?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"?Vu(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=tc(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return bp(e,r,"WS")}resetMaxListeners(){this.events.getMaxListeners()>$p&&this.events.setMaxListeners($p)}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]",x="[object Date]",_="[object Error]",O="[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]",E="[object Symbol]",J="[object Undefined]",z="[object WeakMap]",ee="[object ArrayBuffer]",de="[object DataView]",me="[object Float32Array]",A="[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\]$/,Be=/^(?:0|[1-9]\d*)$/,ye={};ye[me]=ye[A]=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[x]=ye[_]=ye[O]=ye[U]=ye[H]=ye[N]=ye[T]=ye[I]=ye[f]=ye[z]=!1;var Me=typeof pr=="object"&&pr&&pr.Object===Object&&pr,X=typeof self=="object"&&self&&self.Object===Object&&self,Y=Me||X||Function("return this")(),W=e&&!e.nodeType&&e,w=W&&!0&&t&&!t.nodeType&&t,F=w&&w.exports===W,we=F&&Me.process,ve=function(){try{return we&&we.binding&&we.binding("util")}catch{}}(),Ue=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 ke(R){var q=-1,fe=Array(R.size);return R.forEach(function(Ce,It){fe[++q]=[It,Ce]}),fe}function Ke(R,q){return function(fe){return R(q(fe))}}function rt(R){var q=-1,fe=Array(R.size);return R.forEach(function(Ce){fe[++q]=Ce}),fe}var je=Array.prototype,Ze=Function.prototype,b=Object.prototype,p=Y["__core-js_shared__"],m=Ze.toString,D=b.hasOwnProperty,B=function(){var R=/[^.]+$/.exec(p&&p.keys&&p.keys.IE_PROTO||"");return R?"Symbol(src)_1."+R:""}(),K=b.toString,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=je.splice,Ur=Te?Te.toStringTag:void 0,Jn=Object.getOwnPropertySymbols,Ii=Ee?Ee.isBuffer:void 0,cs=Ke(Object.keys,Object),zt=Qr(Y,"DataView"),Lt=Qr(Y,"Map"),Wt=Qr(Y,"Promise"),qt=Qr(Y,"Set"),Ft=Qr(Y,"WeakMap"),Mt=Qr(Object,"create"),ir=Qn(zt),sr=Qn(Lt),Vt=Qn(Wt),or=Qn(qt),Kt=Qn(Ft),Xt=Te?Te.prototype:void 0,Gt=Xt?Xt.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=ls(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=ls(q,R);return fe<0?void 0:q[fe][1]}function qf(R){return ls(this.__data__,R)>-1}function Vf(R,q){var fe=this.__data__,Ce=ls(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 Xs(){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 Qs(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=Xs,Xn.prototype.delete=Kf,Xn.prototype.get=Qs,Xn.prototype.has=Gf,Xn.prototype.set=Zf;function eo(R){var q=-1,fe=R==null?0:R.length;for(this.__data__=new Xn;++q<fe;)this.add(R[q])}function Gc(R){return this.__data__.set(R,n),this}function Zc(R){return this.__data__.has(R)}eo.prototype.add=eo.prototype.push=Gc,eo.prototype.has=Zc;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 Yc(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=Yc;function Jc(R,q){var fe=no(R),Ce=!fe&&ll(R),It=!fe&&!Ce&&va(R),Xe=!fe&&!Ce&&!It&&fl(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")||il(Ot,mt)))&&lr.push(Ot);return lr}function ls(R,q){for(var fe=R.length;fe--;)if(cl(R[fe][0],q))return fe;return-1}function ma(R,q,fe){var Ce=q(R);return no(R)?Ce:at(Ce,fe(R))}function us(R){return R==null?R===void 0?J:G:Ur&&Ur in Object(R)?rl(R):r0(R)}function wa(R){return fs(R)&&us(R)==l}function hs(R,q,fe,Ce,It){return R===q?!0:R==null||q==null||!fs(R)&&!fs(q)?R!==R&&q!==q:Xc(R,q,fe,Ce,hs,It)}function Xc(R,q,fe,Ce,It,Xe){var Tt=no(R),lr=no(q),mt=Tt?h:jn(R),Ot=lr?h:jn(q);mt=mt==l?N:mt,Ot=Ot==l?N:Ot;var Qt=mt==N,qr=Ot==N,ur=mt==Ot;if(ur&&va(R)){if(!va(q))return!1;Tt=!0,Qt=!1}if(ur&&!Qt)return Xe||(Xe=new xn),Tt||fl(R)?to(R,q,fe,Ce,It,Xe):t0(R,q,mt,fe,Ce,It,Xe);if(!(fe&i)){var Rt=Qt&&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),tl(R,q,fe,Ce,It,Xe)):!1}function e0(R){if(!hl(R)||ol(R))return!1;var q=io(R)?Q:ge;return q.test(Qn(R))}function Qc(R){return fs(R)&&ul(R.length)&&!!ye[us(R)]}function el(R){if(!al(R))return cs(R);var q=[];for(var fe in Object(R))D.call(R,fe)&&fe!="constructor"&&q.push(fe);return q}function to(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 Qt=-1,qr=!0,ur=fe&o?new eo:void 0;for(Xe.set(R,q),Xe.set(q,R);++Qt<lr;){var Rt=R[Qt],jr=q[Qt];if(Ce)var Cn=Tt?Ce(jr,Rt,Qt,q,R,Xe):Ce(Rt,jr,Qt,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 x:case H:return cl(+R,+q);case _:return R.name==q.name&&R.message==q.message;case T:case f:return R==q+"";case U:var lr=ke;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 Qt=to(lr(R),lr(q),Ce,It,Xe,Tt);return Tt.delete(R),Qt;case E:if(Gt)return Gt.call(R)==Gt.call(q)}return!1}function tl(R,q,fe,Ce,It,Xe){var Tt=fe&i,lr=ro(R),mt=lr.length,Ot=ro(q),Qt=Ot.length;if(mt!=Qt&&!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 ya=Tt?Ce(Fn,dn,ur,q,R,Xe):Ce(dn,Fn,ur,R,q,Xe);if(!(ya===void 0?dn===Fn||It(dn,Fn,fe,Ce,Xe):ya)){jr=!1;break}Cn||(Cn=ur=="constructor")}if(jr&&!Cn){var ds=R.constructor,vr=q.constructor;ds!=vr&&"constructor"in R&&"constructor"in q&&!(typeof ds=="function"&&ds instanceof ds&&typeof vr=="function"&&vr instanceof vr)&&(jr=!1)}return Xe.delete(R),Xe.delete(q),jr}function ro(R){return ma(R,s0,nl)}function Oi(R,q){var fe=R.__data__;return sl(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 rl(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 nl=Jn?function(R){return R==null?[]:(R=Object(R),nt(Jn(R),function(q){return ht.call(R,q)}))}:Ct,jn=us;(zt&&jn(new zt(new ArrayBuffer(1)))!=de||Lt&&jn(new Lt)!=U||Wt&&jn(Wt.resolve())!=L||qt&&jn(new qt)!=I||Ft&&jn(new Ft)!=z)&&(jn=function(R){var q=us(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 Vt:return L;case or:return I;case Kt:return z}return q});function il(R,q){return q=q??c,!!q&&(typeof R=="number"||Be.test(R))&&R>-1&&R%1==0&&R<q}function sl(R){var q=typeof R;return q=="string"||q=="number"||q=="symbol"||q=="boolean"?R!=="__proto__":R===null}function ol(R){return!!B&&B in R}function al(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 cl(R,q){return R===q||R!==R&&q!==q}var ll=wa(function(){return arguments}())?wa:function(R){return fs(R)&&D.call(R,"callee")&&!ht.call(R,"callee")},no=Array.isArray;function n0(R){return R!=null&&ul(R.length)&&!io(R)}var va=Ii||xt;function i0(R,q){return hs(R,q)}function io(R){if(!hl(R))return!1;var q=us(R);return q==O||q==P||q==d||q==$}function ul(R){return typeof R=="number"&&R>-1&&R%1==0&&R<=c}function hl(R){var q=typeof R;return R!=null&&(q=="object"||q=="function")}function fs(R){return R!=null&&typeof R=="object"}var fl=Ue?$t(Ue):Qc;function s0(R){return n0(R)?Jc(R):el(R)}function Ct(){return[]}function xt(){return!1}t.exports=i0})(th,th.exports);var S_=th.exports,D_=Object.defineProperty,Pp=Object.getOwnPropertySymbols,$_=Object.prototype.hasOwnProperty,P_=Object.prototype.propertyIsEnumerable,Tp=(t,e,r)=>e in t?D_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rr=(t,e)=>{for(var r in e||(e={}))$_.call(e,r)&&Tp(t,r,e[r]);if(Pp)for(var r of Pp(e))P_.call(e,r)&&Tp(t,r,e[r]);return t};function T_(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 x(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 E=L-H;E!==L&&$[E]===0;)E++;for(var J=h.repeat(U);E<L;++E)J+=t.charAt($[E]);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 E=new Uint8Array(H+(N-f)),J=H;f!==N;)E[J++]=L[f++];return E}}}function O(P){var U=_(P);if(U)return U;throw new Error(`Non-${e} character`)}return{encode:x,decodeUnsafe:_,decode:O}}var R_=T_,N_=R_;const Rp=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")},L_=t=>new TextEncoder().encode(t),M_=t=>new TextDecoder().decode(t);class U_{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 j_{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 Np(this,e)}}class F_{constructor(e){this.decoders=e}or(e){return Np(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 Np=(t,e)=>new F_(Rr(Rr({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class B_{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new U_(e,r,n),this.decoder=new j_(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const nc=({name:t,prefix:e,encode:r,decode:n})=>new B_(t,e,r,n),Fo=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=N_(r,e);return nc({prefix:t,name:e,encode:n,decode:o=>Rp(i(o))})},k_=(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 x=i[t[v]];if(x===void 0)throw new SyntaxError(`Non-${n} character`);h=h<<r|x,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},H_=(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})=>nc({prefix:e,name:t,encode(i){return H_(i,n,r)},decode(i){return k_(i,n,r,t)}}),z_=nc({prefix:"\0",name:"identity",encode:t=>M_(t),decode:t=>L_(t)});var W_=Object.freeze({__proto__:null,identity:z_});const q_=Er({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var V_=Object.freeze({__proto__:null,base2:q_});const K_=Er({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var G_=Object.freeze({__proto__:null,base8:K_});const Z_=Fo({prefix:"9",name:"base10",alphabet:"0123456789"});var Y_=Object.freeze({__proto__:null,base10:Z_});const J_=Er({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),X_=Er({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Q_=Object.freeze({__proto__:null,base16:J_,base16upper:X_});const e8=Er({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),t8=Er({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),r8=Er({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),n8=Er({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),i8=Er({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),s8=Er({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),o8=Er({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),a8=Er({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),c8=Er({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var l8=Object.freeze({__proto__:null,base32:e8,base32upper:t8,base32pad:r8,base32padupper:n8,base32hex:i8,base32hexupper:s8,base32hexpad:o8,base32hexpadupper:a8,base32z:c8});const u8=Fo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),h8=Fo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var f8=Object.freeze({__proto__:null,base36:u8,base36upper:h8});const d8=Fo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),p8=Fo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var g8=Object.freeze({__proto__:null,base58btc:d8,base58flickr:p8});const m8=Er({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),w8=Er({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),v8=Er({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),y8=Er({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var b8=Object.freeze({__proto__:null,base64:m8,base64pad:w8,base64url:v8,base64urlpad:y8});const Lp=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}"),_8=Lp.reduce((t,e,r)=>(t[r]=e,t),[]),E8=Lp.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function x8(t){return t.reduce((e,r)=>(e+=_8[r],e),"")}function C8(t){const e=[];for(const r of t){const n=E8[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const I8=nc({prefix:"\u{1F680}",name:"base256emoji",encode:x8,decode:C8});var O8=Object.freeze({__proto__:null,base256emoji:I8}),A8=Up,Mp=128,S8=127,D8=~S8,$8=Math.pow(2,31);function Up(t,e,r){e=e||[],r=r||0;for(var n=r;t>=$8;)e[r++]=t&255|Mp,t/=128;for(;t&D8;)e[r++]=t&255|Mp,t>>>=7;return e[r]=t|0,Up.bytes=r-n+1,e}var P8=rh,T8=128,jp=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&jp)<<i:(c&jp)*Math.pow(2,i),i+=7}while(c>=T8);return rh.bytes=o-n,r}var R8=Math.pow(2,7),N8=Math.pow(2,14),L8=Math.pow(2,21),M8=Math.pow(2,28),U8=Math.pow(2,35),j8=Math.pow(2,42),F8=Math.pow(2,49),B8=Math.pow(2,56),k8=Math.pow(2,63),H8=function(t){return t<R8?1:t<N8?2:t<L8?3:t<M8?4:t<U8?5:t<j8?6:t<F8?7:t<B8?8:t<k8?9:10},z8={encode:A8,decode:P8,encodingLength:H8},Fp=z8;const Bp=(t,e,r=0)=>(Fp.encode(t,e,r),e),kp=t=>Fp.encodingLength(t),nh=(t,e)=>{const r=e.byteLength,n=kp(t),i=n+kp(r),o=new Uint8Array(i+r);return Bp(t,o,0),Bp(r,o,n),o.set(e,i),new W8(t,r,e,o)};class W8{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Hp=({name:t,code:e,encode:r})=>new q8(t,e,r);class q8{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 zp=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),V8=Hp({name:"sha2-256",code:18,encode:zp("SHA-256")}),K8=Hp({name:"sha2-512",code:19,encode:zp("SHA-512")});var G8=Object.freeze({__proto__:null,sha256:V8,sha512:K8});const Wp=0,Z8="identity",qp=Rp;var Y8=Object.freeze({__proto__:null,identity:{code:Wp,name:Z8,encode:qp,digest:t=>nh(Wp,qp(t))}});new TextEncoder,new TextDecoder;const Vp=Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr(Rr({},W_),V_),G_),Y_),Q_),l8),f8),g8),b8),O8);Rr(Rr({},G8),Y8);function Kp(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function J8(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Kp(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Gp(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Zp=Gp("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ih=Gp("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=J8(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),X8=Rr({utf8:Zp,"utf-8":Zp,hex:Vp.base16,latin1:ih,ascii:ih,binary:ih},Vp);function Q8(t,e="utf8"){const r=X8[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Kp(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}const Yp="wc",eE=2,sh="core",fi=`${Yp}@2:${sh}:`,tE={name:sh,logger:"error"},rE={database:":memory:"},nE="crypto",Jp="client_ed25519_seed",iE=Re.ONE_DAY,sE="keychain",oE="0.3",aE="messages",cE="0.3",lE=Re.SIX_HOURS,uE="publisher",Xp="irn",hE="error",Qp="wss://relay.walletconnect.com",fE="relayer",kt={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"},dE="_subscription",Bo={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},pE=Re.ONE_SECOND/2,gE="2.8.3",mE=1e4,wE="0.3",vE="WALLETCONNECT_CLIENT_ID",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=Re.FIVE_SECONDS*1e3,EE="pairing",xE="0.3",ko={wc_pairingDelete:{req:{ttl:Re.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:Re.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:Re.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:Re.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:Re.ONE_DAY,prompt:!1,tag:0},res:{ttl:Re.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",eg="https://verify.walletconnect.com";class SE{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=sE,this.version=oE,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=nE,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=M5();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const o=await this.getClientSeed(),c=mp(o),l=Iu();return await F4(l,i,iE,c)},this.generateSharedKey=(i,o,c)=>{this.isInitialized();const l=this.getPrivateKey(i),h=U5(l,o);return this.setSymKey(h,c)},this.setSymKey=async(i,o)=>{this.isInitialized();const c=o||j5(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=Mo(o);if(C1(l)){const _=l.senderPublicKey,O=l.receiverPublicKey;i=await this.generateSharedKey(_,O)}const d=this.getSymKey(i),{type:v,senderPublicKey:x}=l;return B5({type:v,symKey:d,message:h,senderPublicKey:x})},this.decode=async(i,o,c)=>{this.isInitialized();const l=z5(o,c);if(C1(l)){const v=l.receiverPublicKey,x=l.senderPublicKey;i=await this.generateSharedKey(v,x)}const h=this.getSymKey(i),d=k5({symKey:h,encoded:o});return Vu(d)},this.getPayloadType=i=>{const o=Va(i);return Io(o.type)},this.getPayloadSenderPublicKey=i=>{const o=Va(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(Jp)}catch{e=Iu(),await this.keychain.set(Jp,e)}return Q8(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 g4{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=aE,this.version=cE,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=Os(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=Os(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 m4{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new br.exports.EventEmitter,this.name=uE,this.queue=new Map,this.publishTimeout=Re.toMiliseconds(Re.TEN_SECONDS),this.queueTimeout=Re.toMiliseconds(Re.FIVE_SECONDS),this.needsTransportRestart=!1,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||lE,l=Du(o),h=o?.prompt||!1,d=o?.tag||0,v=o?.id||Xu().toString(),x={topic:n,message:i,opts:{ttl:c,relay:l,prompt:h,tag:d,id:v}},_=setTimeout(()=>this.queue.set(v,x),this.queueTimeout);try{await await Ka(this.rpcPublish(n,i,c,l,h,d,v),this.publishTimeout),clearTimeout(_),this.relayer.events.emit(kt.publish,x)}catch{this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0;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,x;const _={method:Ga(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)&&((x=_.params)==null||delete x.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(Po.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(kt.connection_stalled);return}this.checkQueue()}),this.relayer.on(kt.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,tg=Object.getOwnPropertySymbols,ME=Object.prototype.hasOwnProperty,UE=Object.prototype.propertyIsEnumerable,rg=(t,e,r)=>e in t?RE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ho=(t,e)=>{for(var r in e||(e={}))ME.call(e,r)&&rg(t,r,e[r]);if(tg)for(var r of tg(e))UE.call(e,r)&&rg(t,r,e[r]);return t},ah=(t,e)=>NE(t,LE(e));class jE extends y4{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=Du(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 Re.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=Du(n);await this.rpcUnsubscribe(e,r,i);const o=Yt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,o),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){const n={method:Ga(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await Ka(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(kt.connection_stalled)}return Os(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Ga(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 Ka(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(kt.connection_stalled)}}rpcUnsubscribe(e,r,n){const i={method:Ga(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(Ho({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Ho({},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,Ho({},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(Ho({},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(Ho({},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(Po.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(kt.connect,async()=>{await this.onConnect()}),this.relayer.on(kt.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,ng=Object.getOwnPropertySymbols,BE=Object.prototype.hasOwnProperty,kE=Object.prototype.propertyIsEnumerable,ig=(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)&&ig(t,r,e[r]);if(ng)for(var r of ng(e))kE.call(e,r)&&ig(t,r,e[r]);return t};class zE extends w4{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new br.exports.EventEmitter,this.name=fE,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||hE})),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||Qp,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)},mE)}get context(){return pt.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"";return i||(await Promise.all([new Promise(o=>{this.subscriber.once(Pn.created,c=>{c.topic===e&&o()})}),new Promise(async o=>{i=await this.subscriber.subscribe(e,r),o()})]),i)}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportClose(){this.transportExplicitlyClosed=!0,this.connected&&(await this.provider.disconnect(),this.events.emit(kt.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 Ka(this.provider.connect(),5e3,"socket stalled").catch(i=>n(i)).then(()=>r()).finally(()=>this.removeListener(kt.transport_closed,this.rejectTransportOpen))}),new Promise(r=>this.once(kt.transport_closed,this.rejectTransportOpen))])])}catch(r){this.logger.error(r);const n=r;if(!this.isConnectionStalled(n.message))throw r;this.events.emit(kt.transport_closed)}finally{this.reconnecting=!1}}}async restartTransport(e){this.transportExplicitlyClosed||this.reconnecting||(this.relayUrl=e||this.relayUrl,this.connected&&await Promise.all([new Promise(r=>{this.provider.once(Bo.disconnect,()=>{r()})}),this.transportClose()]),await this.createProvider(),await this.transportOpen())}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}rejectTransportOpen(){throw new Error("Attempt to connect to relay via `transportOpen` has stalled. Retrying...")}async createProvider(){const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new hi(new A_(eb({sdkVersion:gE,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(dE))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 rc(e)&&this.events.emit(kt.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(kt.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(Bo.payload,e=>this.onProviderPayload(e)),this.provider.on(Bo.connect,()=>{this.events.emit(kt.connect)}),this.provider.on(Bo.disconnect,()=>{this.onProviderDisconnect()}),this.provider.on(Bo.error,e=>{this.logger.error(e),this.events.emit(kt.error,e)})}registerEventListeners(){this.events.on(kt.connection_stalled,async()=>{await this.restartTransport()})}onProviderDisconnect(){this.events.emit(kt.disconnect),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||setTimeout(async()=>{await this.restartTransport()},Re.toMiliseconds(pE))}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,sg=Object.getOwnPropertySymbols,qE=Object.prototype.hasOwnProperty,VE=Object.prototype.propertyIsEnumerable,og=(t,e,r)=>e in t?WE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ag=(t,e)=>{for(var r in e||(e={}))qE.call(e,r)&&og(t,r,e[r]);if(sg)for(var r of sg(e))VE.call(e,r)&&og(t,r,e[r]);return t};class ic extends v4{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=wE,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):xb(c)?this.map.set(c.id,c):Cb(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=>S_(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=ag(ag({},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=Iu(),i=await this.core.crypto.setSymKey(n),o=$n(Re.FIVE_MINUTES),c={protocol:Xp},l={topic:i,expiry:o,relay:c,active:!1},h=db({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}=ub(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(Re.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(Re.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}=As();this.events.once(rr("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",Yt("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,o)=>{const c=ec(i,o),l=await this.core.crypto.encode(n,c),h=ko[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=ko[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=tc(n,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,n),d=ko[h.request.method]?ko[h.request.method].res:ko.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,Yt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{const n=this.pairings.getAll().filter(i=>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(rr("pairing_ping",o),{}):En(i)&&this.events.emit(rr("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=Yt("WC_METHOD_UNSUPPORTED",c);await this.sendError(o,n,l),this.logger.error(l)}catch(l){await this.sendError(o,n,l),this.logger.error(l)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(Yt("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{if(!zr(n)){const{message:i}=_e("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(i)}if(!Eb(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 ic(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(kt.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})):rc(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 p4{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:ec(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 b4{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 tb(e);if(typeof e=="number")return rb(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;Re.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(Po.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 _4{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=oh,this.initialized=!1,this.init=async n=>{S1()||!Au()||(this.verifyUrl=n?.verifyUrl||eg,await this.createIframe())},this.register=async n=>{var i;if(this.initialized||await this.init(),!!this.iframe)try{(i=this.iframe.contentWindow)==null||i.postMessage(n.attestationId,this.verifyUrl),this.logger.info(`postMessage sent: ${n.attestationId} ${this.verifyUrl}`)}catch{}},this.resolve=async n=>{var i;if(this.isDevEnv)return"";this.logger.info(`resolving attestation: ${n.attestationId}`);const o=this.startAbortTimer(Re.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"),Re.toMiliseconds(Re.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=eg,this.abortController=new AbortController,this.isDevEnv=Ou()&&process.env.IS_VITEST}get context(){return pt.getLoggerContext(this.logger)}startAbortTimer(e){return setTimeout(()=>this.abortController.abort(),Re.toMiliseconds(e))}}var JE=Object.defineProperty,cg=Object.getOwnPropertySymbols,XE=Object.prototype.hasOwnProperty,QE=Object.prototype.propertyIsEnumerable,lg=(t,e,r)=>e in t?JE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ug=(t,e)=>{for(var r in e||(e={}))XE.call(e,r)&&lg(t,r,e[r]);if(cg)for(var r of cg(e))QE.call(e,r)&&lg(t,r,e[r]);return t};class ch extends d4{constructor(e){super(e),this.protocol=Yp,this.version=eE,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||Qp;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||tE.logger}));this.logger=pt.generateChildLogger(r,this.name),this.heartbeat=new Po.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 w6(ug(ug({},rE),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);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(vE,n),r}get context(){return pt.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const e7=ch,hg="wc",fg=2,dg="client",lh=`${hg}@${fg}:${dg}:`,uh={name:dg,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},t7="WALLETCONNECT_DEEPLINK_CHOICE",r7="proposal",pg="Proposal expired",n7="session",sc=Re.SEVEN_DAYS,i7="engine",zo={wc_sessionPropose:{req:{ttl:Re.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Re.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:Re.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Re.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Re.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Re.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Re.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Re.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Re.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Re.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Re.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Re.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Re.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Re.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Re.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:Re.THIRTY_SECONDS,prompt:!1,tag:1115}}},hh={min:Re.FIVE_MINUTES,max:Re.SEVEN_DAYS},s7="request",o7=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var a7=Object.defineProperty,c7=Object.defineProperties,l7=Object.getOwnPropertyDescriptors,gg=Object.getOwnPropertySymbols,u7=Object.prototype.hasOwnProperty,h7=Object.prototype.propertyIsEnumerable,mg=(t,e,r)=>e in t?a7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,an=(t,e)=>{for(var r in e||(e={}))u7.call(e,r)&&mg(t,r,e[r]);if(gg)for(var r of gg(e))h7.call(e,r)&&mg(t,r,e[r]);return t},fh=(t,e)=>c7(t,l7(e));class f7 extends x4{constructor(e){super(e),this.name=i7,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(zo)}),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,x=!1;if(d&&(x=this.client.core.pairing.pairings.get(d).active),!d||!x){const{topic:L,uri:$}=await this.client.core.pairing.create();d=L,v=$}const _=await this.client.core.crypto.generateKeyPair(),O=an({requiredNamespaces:o,optionalNamespaces:c,relays:h??[{protocol:Xp}],proposer:{publicKey:_,metadata:this.client.metadata}},l&&{sessionProperties:l}),{reject:P,resolve:U,done:H}=As(Re.FIVE_MINUTES,pg);if(this.events.once(rr("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",O),N=$n(Re.FIVE_MINUTES);return await this.setProposal(G,an({id:G,expiry:N},O)),{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:x}=l;h=h||"",Ds(v)||(v=wb(o,"approve()"));const _=await this.client.core.crypto.generateKeyPair(),O=d.publicKey,P=await this.client.core.crypto.generateSharedKey(_,O);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,Yt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:h}));const U=an({relay:{protocol:i??"irn"},namespaces:o,requiredNamespaces:v,optionalNamespaces:x,pairingTopic:h,controller:{publicKey:_,metadata:this.client.metadata},expiry:$n(sc)},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(sc)),{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,Yt("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}=As();return this.events.once(rr("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}=As();return this.events.once(rr("session_extend",i),({error:h})=>{h?l(h):c()}),await this.setExpiry(n,$n(sc)),{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}=As(c);this.events.once(rr("session_request",l),({error:_,result:O})=>{_?v(_):d(O)}),this.client.events.emit("session_request_sent",{topic:o,request:i,chainId:n,id:l});const x=await this.client.core.storage.getItem(t7);return nb({id:l,topic:o,wcDeepLink:x}),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}=As();this.events.once(rr("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;if(this.client.session.keys.includes(n)){const i=Xu().toString();let o;const c=l=>{l?.id.toString()===i&&(this.client.core.relayer.events.removeListener(kt.message_ack,c),o())};await Promise.all([new Promise(l=>{o=l,this.client.core.relayer.on(kt.message_ack,c)}),this.sendRequest(n,"wc_sessionDelete",Yt("USER_DISCONNECTED"),void 0,i)]),await this.deleteSession(n)}else await this.client.core.pairing.disconnect({topic:n})},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>bb(n,r))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{const n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(o=>{var c,l;return((c=o.peerMetadata)==null?void 0:c.url)&&((l=o.peerMetadata)==null?void 0:l.url)===r.peer.metadata.url&&o.topic&&o.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(o=>this.client.core.pairing.disconnect({topic:o.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async(r,n)=>{const{self:i}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),this.client.session.delete(r,Yt("USER_DISCONNECTED")),this.client.core.crypto.keychain.has(i.publicKey)&&await this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r)},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,Yt("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)])},this.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=zo.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,c)=>{const l=ec(n,i);if(Au()&&o7.includes(n)){const v=Os(JSON.stringify(l));await this.client.core.verify.register({attestationId:v})}const h=await this.client.core.crypto.encode(r,l),d=zo[n].req;return o&&(d.ttl=o),c&&(d.id=c),this.client.core.history.set(r,l),this.client.core.relayer.publish(r,h,d),l.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=zo[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=tc(r,i),c=await this.client.core.crypto.encode(n,o),l=await this.client.core.history.get(n,r),h=zo[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.onRelayEventUnknownPayload=r=>{const{topic:n}=r,{message:i}=_e("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.onSessionProposeRequest=async(r,n)=>{const{params:i,id:o}=n;try{this.isValidConnect(an({},n.params));const c=$n(Re.FIVE_MINUTES),l=an({id:o,pairingTopic:r,expiry:c},i);await this.setProposal(o,l);const h=Os(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,Yt("USER_DISCONNECTED")),this.events.emit(rr("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:x,sessionProperties:_,pairingTopic:O}=n.params,P=an({topic:r,relay:c,expiry:h,namespaces:d,acknowledged:!0,pairingTopic:O,requiredNamespaces:v,optionalNamespaces:x,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(rr("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(rr("session_approve",i),{})):En(n)&&(await this.client.session.delete(r,Yt("USER_DISCONNECTED")),this.events.emit(rr("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(rr("session_update",i),{}):En(n)&&this.events.emit(rr("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(sc)),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(rr("session_extend",i),{}):En(n)&&this.events.emit(rr("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(rr("session_ping",i),{}):En(n)&&this.events.emit(rr("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(kt.publish,async()=>{o(await this.deleteSession(r))})}),this.sendResult(i,r,!0)]),this.client.events.emit("session_delete",{id:i,topic:r})}catch(o){this.client.logger.error(o)}},this.onSessionRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidRequest(an({topic:r},o)),await this.setPendingSessionRequest({id:i,topic:r,params:o});const c=Os(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(rr("session_request",i),{result:n.result}):En(n)&&this.events.emit(rr("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),!Tb(l,!0)){const{message:h}=_e("MISSING_OR_INVALID",`connect() relays: ${l}`);throw new Error(h)}!Pr(i)&&Ds(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Pr(o)&&Ds(o)!==0&&this.validateNamespaces(o,"optionalNamespaces"),Pr(c)||this.validateSessionProps(c,"sessionProperties")},this.validateNamespaces=(r,n)=>{const i=Pb(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=Ya(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),!Nb(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=Ib(i,"onSessionSettleRequest()");if(l)throw new Error(l.message);const h=Ya(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=Ya(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(!Lb(i)){const{message:h}=_e("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(h)}if(!jb(l,o,i.method)){const{message:h}=_e("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(h)}if(c&&!Hb(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),!Mb(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(!Ub(i)){const{message:l}=_e("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}if(!Fb(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(kt.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})):rc(i)?(await this.client.core.history.resolve(i),this.onRelayEventResponse({topic:r,payload:i})):this.onRelayEventUnknownPayload({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(!Rb(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 d7 extends ic{constructor(e,r){super(e,r,r7,lh),this.core=e,this.logger=r}}class p7 extends ic{constructor(e,r){super(e,r,n7,lh),this.core=e,this.logger=r}}class g7 extends ic{constructor(e,r){super(e,r,s7,lh,n=>n.id),this.core=e,this.logger=r}}class dh extends E4{constructor(e){super(e),this.protocol=hg,this.version=fg,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||Y5();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 p7(this.core,this.logger),this.proposal=new d7(this.core,this.logger),this.pendingRequest=new g7(this.core,this.logger),this.engine=new f7(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(A){return A&&DataView.prototype.isPrototypeOf(A)}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(A){return A&&d.indexOf(Object.prototype.toString.call(A))>-1};function x(A){if(typeof A!="string"&&(A=String(A)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(A))throw new TypeError("Invalid character in header field name");return A.toLowerCase()}function _(A){return typeof A!="string"&&(A=String(A)),A}function O(A){var j={next:function(){var ce=A.shift();return{done:ce===void 0,value:ce}}};return l.iterable&&(j[Symbol.iterator]=function(){return j}),j}function P(A){this.map={},A instanceof P?A.forEach(function(j,ce){this.append(ce,j)},this):Array.isArray(A)?A.forEach(function(j){this.append(j[0],j[1])},this):A&&Object.getOwnPropertyNames(A).forEach(function(j){this.append(j,A[j])},this)}P.prototype.append=function(A,j){A=x(A),j=_(j);var ce=this.map[A];this.map[A]=ce?ce+", "+j:j},P.prototype.delete=function(A){delete this.map[x(A)]},P.prototype.get=function(A){return A=x(A),this.has(A)?this.map[A]:null},P.prototype.has=function(A){return this.map.hasOwnProperty(x(A))},P.prototype.set=function(A,j){this.map[x(A)]=_(j)},P.prototype.forEach=function(A,j){for(var ce in this.map)this.map.hasOwnProperty(ce)&&A.call(j,this.map[ce],ce,this)},P.prototype.keys=function(){var A=[];return this.forEach(function(j,ce){A.push(ce)}),O(A)},P.prototype.values=function(){var A=[];return this.forEach(function(j){A.push(j)}),O(A)},P.prototype.entries=function(){var A=[];return this.forEach(function(j,ce){A.push([ce,j])}),O(A)},l.iterable&&(P.prototype[Symbol.iterator]=P.prototype.entries);function U(A){if(A.bodyUsed)return Promise.reject(new TypeError("Already read"));A.bodyUsed=!0}function H(A){return new Promise(function(j,ce){A.onload=function(){j(A.result)},A.onerror=function(){ce(A.error)}})}function G(A){var j=new FileReader,ce=H(j);return j.readAsArrayBuffer(A),ce}function N(A){var j=new FileReader,ce=H(j);return j.readAsText(A),ce}function L(A){for(var j=new Uint8Array(A),ce=new Array(j.length),le=0;le<j.length;le++)ce[le]=String.fromCharCode(j[le]);return ce.join("")}function $(A){if(A.slice)return A.slice(0);var j=new Uint8Array(A.byteLength);return j.set(new Uint8Array(A)),j.buffer}function T(){return this.bodyUsed=!1,this._initBody=function(A){this._bodyInit=A,A?typeof A=="string"?this._bodyText=A:l.blob&&Blob.prototype.isPrototypeOf(A)?this._bodyBlob=A:l.formData&&FormData.prototype.isPrototypeOf(A)?this._bodyFormData=A:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(A)?this._bodyText=A.toString():l.arrayBuffer&&l.blob&&h(A)?(this._bodyArrayBuffer=$(A.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(A)||v(A))?this._bodyArrayBuffer=$(A):this._bodyText=A=Object.prototype.toString.call(A):this._bodyText="",this.headers.get("content-type")||(typeof A=="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(A)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var A=U(this);if(A)return A;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 A=U(this);if(A)return A;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(A){var j=A.toUpperCase();return I.indexOf(j)>-1?j:A}function E(A,j){j=j||{};var ce=j.body;if(A instanceof E){if(A.bodyUsed)throw new TypeError("Already read");this.url=A.url,this.credentials=A.credentials,j.headers||(this.headers=new P(A.headers)),this.method=A.method,this.mode=A.mode,this.signal=A.signal,!ce&&A._bodyInit!=null&&(ce=A._bodyInit,A.bodyUsed=!0)}else this.url=String(A);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)}E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function J(A){var j=new FormData;return A.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(A){var j=new P,ce=A.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(E.prototype);function ee(A,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(A)}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 A=new ee(null,{status:0,statusText:""});return A.type="error",A};var de=[301,302,303,307,308];ee.redirect=function(A,j){if(de.indexOf(j)===-1)throw new RangeError("Invalid status code");return new ee(null,{status:j,headers:{location:A}})},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(A,j){return new Promise(function(ce,le){var re=new E(A,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=E,o.Response=ee),c.Headers=P,c.Request=E,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 wg=dw(ph.exports);const vg={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},yg=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,!Ap(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=Mo(e),o=await(await wg(this.url,Object.assign(Object.assign({},vg),{body:n}))).json();this.onPayload({data:o})}catch(n){this.onError(e.id,n)}}async register(e=this.url){if(!Ap(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=Mo({id:1,jsonrpc:"2.0",method:"test",params:[]});await wg(e,Object.assign(Object.assign({},vg),{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"?Vu(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=tc(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return bp(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>yg&&this.events.setMaxListeners(yg)}}const bg="error",m7="wss://relay.walletconnect.com",w7="wc",v7="universal_provider",_g=`${w7}@2:${v7}:`,y7="https://rpc.walletconnect.com/v1",di={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Wo=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/>