@walletconnect/ethereum-provider 2.7.0-rc-4 → 2.7.1

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
@@ -82,7 +82,7 @@
82
82
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
83
83
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
84
84
  PERFORMANCE OF THIS SOFTWARE.
85
- ***************************************************************************** */var Ku=function(t,e){return Ku=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},Ku(t,e)};function N_(t,e){Ku(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var Gu=function(){return Gu=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},Gu.apply(this,arguments)};function L_(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function M_(t,e,n,r){var i=arguments.length,o=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,n,r);else for(var l=t.length-1;l>=0;l--)(c=t[l])&&(o=(i<3?c(o):i>3?c(e,n,o):c(e,n))||o);return i>3&&o&&Object.defineProperty(e,n,o),o}function j_(t,e){return function(n,r){e(n,r,t)}}function U_(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function F_(t,e,n,r){function i(o){return o instanceof n?o:new n(function(c){c(o)})}return new(n||(n=Promise))(function(o,c){function l(v){try{f(r.next(v))}catch(E){c(E)}}function h(v){try{f(r.throw(v))}catch(E){c(E)}}function f(v){v.done?o(v.value):i(v.value).then(l,h)}f((r=r.apply(t,e||[])).next())})}function B_(t,e){var n={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,i,o,c;return c={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(c[Symbol.iterator]=function(){return this}),c;function l(f){return function(v){return h([f,v])}}function h(f){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(o=f[0]&2?i.return:f[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,f[1])).done)return o;switch(i=0,o&&(f=[f[0]&2,o.value]),f[0]){case 0:case 1:o=f;break;case 4:return n.label++,{value:f[1],done:!1};case 5:n.label++,i=f[1],f=[0];continue;case 7:f=n.ops.pop(),n.trys.pop();continue;default:if(o=n.trys,!(o=o.length>0&&o[o.length-1])&&(f[0]===6||f[0]===2)){n=0;continue}if(f[0]===3&&(!o||f[1]>o[0]&&f[1]<o[3])){n.label=f[1];break}if(f[0]===6&&n.label<o[1]){n.label=o[1],o=f;break}if(o&&n.label<o[2]){n.label=o[2],n.ops.push(f);break}o[2]&&n.ops.pop(),n.trys.pop();continue}f=e.call(t,n)}catch(v){f=[6,v],i=0}finally{r=o=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}}function k_(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function H_(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function Zu(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Rp(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,o=[],c;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(l){c={error:l}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(c)throw c.error}}return o}function z_(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Rp(arguments[e]));return t}function W_(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),i=0,e=0;e<n;e++)for(var o=arguments[e],c=0,l=o.length;c<l;c++,i++)r[i]=o[c];return r}function No(t){return this instanceof No?(this.v=t,this):new No(t)}function q_(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,o=[];return i={},c("next"),c("throw"),c("return"),i[Symbol.asyncIterator]=function(){return this},i;function c(b){r[b]&&(i[b]=function(C){return new Promise(function(P,M){o.push([b,C,P,M])>1||l(b,C)})})}function l(b,C){try{h(r[b](C))}catch(P){E(o[0][3],P)}}function h(b){b.value instanceof No?Promise.resolve(b.value.v).then(f,v):E(o[0][2],b)}function f(b){l("next",b)}function v(b){l("throw",b)}function E(b,C){b(C),o.shift(),o.length&&l(o[0][0],o[0][1])}}function V_(t){var e,n;return e={},r("next"),r("throw",function(i){throw i}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(i,o){e[i]=t[i]?function(c){return(n=!n)?{value:No(t[i](c)),done:i==="return"}:o?o(c):c}:o}}function K_(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof Zu=="function"?Zu(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(o){n[o]=t[o]&&function(c){return new Promise(function(l,h){c=t[o](c),i(l,h,c.done,c.value)})}}function i(o,c,l,h){Promise.resolve(h).then(function(f){o({value:f,done:l})},c)}}function G_(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function Z_(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function Y_(t){return t&&t.__esModule?t:{default:t}}function J_(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function X_(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}var Q_=Object.freeze({__proto__:null,__extends:N_,get __assign(){return Gu},__rest:L_,__decorate:M_,__param:j_,__metadata:U_,__awaiter:F_,__generator:B_,__createBinding:k_,__exportStar:H_,__values:Zu,__read:Rp,__spread:z_,__spreadArrays:W_,__await:No,__asyncGenerator:q_,__asyncDelegator:V_,__asyncValues:K_,__makeTemplateObject:G_,__importStar:Z_,__importDefault:Y_,__classPrivateFieldGet:J_,__classPrivateFieldSet:X_}),e8=si(Q_),Hr={},Np;function t8(){if(Np)return Hr;Np=1,Object.defineProperty(Hr,"__esModule",{value:!0}),Hr.isBrowserCryptoAvailable=Hr.getSubtleCrypto=Hr.getBrowerCrypto=void 0;function t(){return Lt?.crypto||Lt?.msCrypto||{}}Hr.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}Hr.getSubtleCrypto=e;function n(){return!!t()&&!!e()}return Hr.isBrowserCryptoAvailable=n,Hr}var zr={},Lp;function n8(){if(Lp)return zr;Lp=1,Object.defineProperty(zr,"__esModule",{value:!0}),zr.isBrowser=zr.isNode=zr.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}zr.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}zr.isNode=e;function n(){return!t()&&!e()}return zr.isBrowser=n,zr}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=e8;e.__exportStar(t8(),t),e.__exportStar(n8(),t)})(Tp);function r8(t=3){const e=Date.now()*Math.pow(10,t),n=Math.floor(Math.random()*Math.pow(10,t));return e+n}function Yu(t,e,n){return{id:n||r8(),jsonrpc:"2.0",method:t,params:e}}function Ju(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Qa(t,e,n){return{id:t,jsonrpc:"2.0",error:i8(e,n)}}function i8(t,e){return typeof t>"u"?$p(Dp):(typeof t=="string"&&(t=Object.assign(Object.assign({},$p(Vu)),{message:t})),typeof e<"u"&&(t.data=e),T_(t.code)&&(t=R_(t.code)),t)}const s8="^https?:",o8="^wss?:";function a8(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Mp(t,e){const n=a8(t);return typeof n>"u"?!1:new RegExp(e).test(n)}function jp(t){return Mp(t,s8)}function Up(t){return Mp(t,o8)}function c8(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Fp(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Xu(t){return Fp(t)&&"method"in t}function Bp(t){return Fp(t)&&(Wr(t)||Or(t))}function Wr(t){return"result"in t}function Or(t){return"error"in t}const kp=10,l8=()=>typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:require("ws"),u8=()=>typeof window<"u",h8=l8();class f8{constructor(e){if(this.url=e,this.events=new xn.exports.EventEmitter,this.registering=!1,!Up(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,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,n)=>{if(typeof this.socket>"u"){n(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),e()},this.socket.close()})}async send(e,n){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Po(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Up(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,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"));r(this.socket)})})}return this.url=e,this.registering=!0,new Promise((n,r)=>{const i=Tp.isReactNative()?void 0:{rejectUnauthorized:!c8(e)},o=new h8(e,[],i);u8()?o.onerror=c=>{const l=c;r(this.emitError(l.error))}:o.on("error",c=>{r(this.emitError(c))}),o.onopen=()=>{this.onOpen(o),n(o)}})}onOpen(e){e.onmessage=n=>this.onPayload(n),e.onclose=n=>this.onClose(n),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 n=typeof e.data=="string"?Bu(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),i=r.message||r.toString(),o=Qa(e,i);this.events.emit("payload",o)}parseError(e,n=this.url){return Pp(e,n,"WS")}resetMaxListeners(){this.events.getMaxListeners()>kp&&this.events.setMaxListeners(kp)}emitError(e){const n=this.parseError(new Error(e?.message||`WebSocket connection failed for URL: ${this.url}`));return this.events.emit("register_error",n),n}}var Qu={exports:{}};(function(t,e){var n=200,r="__lodash_hash_undefined__",i=1,o=2,c=9007199254740991,l="[object Arguments]",h="[object Array]",f="[object AsyncFunction]",v="[object Boolean]",E="[object Date]",b="[object Error]",C="[object Function]",P="[object GeneratorFunction]",M="[object Map]",k="[object Number]",q="[object Null]",T="[object Object]",L="[object Promise]",A="[object Proxy]",R="[object RegExp]",I="[object Set]",d="[object String]",x="[object Symbol]",J="[object Undefined]",z="[object WeakMap]",ee="[object ArrayBuffer]",de="[object DataView]",me="[object Float32Array]",O="[object Float64Array]",U="[object Int8Array]",ae="[object Int16Array]",le="[object Int32Array]",ne="[object Uint8Array]",re="[object Uint8ClampedArray]",oe="[object Uint16Array]",ie="[object Uint32Array]",Se=/[\\^$.*+?()[\]{}|]/g,ge=/^\[object .+?Constructor\]$/,Ne=/^(?:0|[1-9]\d*)$/,be={};be[me]=be[O]=be[U]=be[ae]=be[le]=be[ne]=be[re]=be[oe]=be[ie]=!0,be[l]=be[h]=be[ee]=be[v]=be[de]=be[E]=be[b]=be[C]=be[M]=be[k]=be[T]=be[R]=be[I]=be[d]=be[z]=!1;var Ae=typeof Lt=="object"&&Lt&&Lt.Object===Object&&Lt,X=typeof self=="object"&&self&&self.Object===Object&&self,Y=Ae||X||Function("return this")(),W=e&&!e.nodeType&&e,w=W&&!0&&t&&!t.nodeType&&t,F=w&&w.exports===W,we=F&&Ae.process,ve=function(){try{return we&&we.binding&&we.binding("util")}catch{}}(),Pe=ve&&ve.isTypedArray;function tt(N,V){for(var fe=-1,Ce=N==null?0:N.length,St=0,Je=[];++fe<Ce;){var Rt=N[fe];V(Rt,fe,N)&&(Je[St++]=Rt)}return Je}function ot(N,V){for(var fe=-1,Ce=V.length,St=N.length;++fe<Ce;)N[St+fe]=V[fe];return N}function qe(N,V){for(var fe=-1,Ce=N==null?0:N.length;++fe<Ce;)if(V(N[fe],fe,N))return!0;return!1}function $t(N,V){for(var fe=-1,Ce=Array(N);++fe<N;)Ce[fe]=V(fe);return Ce}function Pt(N){return function(V){return N(V)}}function Ye(N,V){return N.has(V)}function Me(N,V){return N?.[V]}function Le(N){var V=-1,fe=Array(N.size);return N.forEach(function(Ce,St){fe[++V]=[St,Ce]}),fe}function ze(N,V){return function(fe){return N(V(fe))}}function et(N){var V=-1,fe=Array(N.size);return N.forEach(function(Ce){fe[++V]=Ce}),fe}var Te=Array.prototype,Ve=Function.prototype,_=Object.prototype,p=Y["__core-js_shared__"],m=Ve.toString,$=_.hasOwnProperty,B=function(){var N=/[^.]+$/.exec(p&&p.keys&&p.keys.IE_PROTO||"");return N?"Symbol(src)_1."+N:""}(),G=_.toString,Q=RegExp("^"+m.call($).replace(Se,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),xe=F?Y.Buffer:void 0,De=Y.Symbol,it=Y.Uint8Array,ut=_.propertyIsEnumerable,ct=Te.splice,Ln=De?De.toStringTag:void 0,Kr=Object.getOwnPropertySymbols,vi=xe?xe.isBuffer:void 0,rs=ze(Object.keys,Object),zt=Xn(Y,"DataView"),jt=Xn(Y,"Map"),Wt=Xn(Y,"Promise"),qt=Xn(Y,"Set"),Bt=Xn(Y,"WeakMap"),Ut=Xn(Object,"create"),nn=Zr(zt),rn=Zr(jt),Vt=Zr(Wt),sn=Zr(qt),Kt=Zr(Bt),Jt=De?De.prototype:void 0,Gt=Jt?Jt.valueOf:void 0;function Tt(N){var V=-1,fe=N==null?0:N.length;for(this.clear();++V<fe;){var Ce=N[V];this.set(Ce[0],Ce[1])}}function on(){this.__data__=Ut?Ut(null):{},this.size=0}function an(N){var V=this.has(N)&&delete this.__data__[N];return this.size-=V?1:0,V}function Rf(N){var V=this.__data__;if(Ut){var fe=V[N];return fe===r?void 0:fe}return $.call(V,N)?V[N]:void 0}function Nf(N){var V=this.__data__;return Ut?V[N]!==void 0:$.call(V,N)}function Lf(N,V){var fe=this.__data__;return this.size+=this.has(N)?0:1,fe[N]=Ut&&V===void 0?r:V,this}Tt.prototype.clear=on,Tt.prototype.delete=an,Tt.prototype.get=Rf,Tt.prototype.has=Nf,Tt.prototype.set=Lf;function lr(N){var V=-1,fe=N==null?0:N.length;for(this.clear();++V<fe;){var Ce=N[V];this.set(Ce[0],Ce[1])}}function Mf(){this.__data__=[],this.size=0}function jf(N){var V=this.__data__,fe=is(V,N);if(fe<0)return!1;var Ce=V.length-1;return fe==Ce?V.pop():ct.call(V,fe,1),--this.size,!0}function Uf(N){var V=this.__data__,fe=is(V,N);return fe<0?void 0:V[fe][1]}function Ff(N){return is(this.__data__,N)>-1}function Bf(N,V){var fe=this.__data__,Ce=is(fe,N);return Ce<0?(++this.size,fe.push([N,V])):fe[Ce][1]=V,this}lr.prototype.clear=Mf,lr.prototype.delete=jf,lr.prototype.get=Uf,lr.prototype.has=Ff,lr.prototype.set=Bf;function Gr(N){var V=-1,fe=N==null?0:N.length;for(this.clear();++V<fe;){var Ce=N[V];this.set(Ce[0],Ce[1])}}function Ks(){this.size=0,this.__data__={hash:new Tt,map:new(jt||lr),string:new Tt}}function kf(N){var V=yi(this,N).delete(N);return this.size-=V?1:0,V}function Gs(N){return yi(this,N).get(N)}function Hf(N){return yi(this,N).has(N)}function zf(N,V){var fe=yi(this,N),Ce=fe.size;return fe.set(N,V),this.size+=fe.size==Ce?0:1,this}Gr.prototype.clear=Ks,Gr.prototype.delete=kf,Gr.prototype.get=Gs,Gr.prototype.has=Hf,Gr.prototype.set=zf;function Zs(N){var V=-1,fe=N==null?0:N.length;for(this.__data__=new Gr;++V<fe;)this.add(N[V])}function zc(N){return this.__data__.set(N,r),this}function Wc(N){return this.__data__.has(N)}Zs.prototype.add=Zs.prototype.push=zc,Zs.prototype.has=Wc;function br(N){var V=this.__data__=new lr(N);this.size=V.size}function Wf(){this.__data__=new lr,this.size=0}function qf(N){var V=this.__data__,fe=V.delete(N);return this.size=V.size,fe}function Vf(N){return this.__data__.get(N)}function Kf(N){return this.__data__.has(N)}function qc(N,V){var fe=this.__data__;if(fe instanceof lr){var Ce=fe.__data__;if(!jt||Ce.length<n-1)return Ce.push([N,V]),this.size=++fe.size,this;fe=this.__data__=new Gr(Ce)}return fe.set(N,V),this.size=fe.size,this}br.prototype.clear=Wf,br.prototype.delete=qf,br.prototype.get=Vf,br.prototype.has=Kf,br.prototype.set=qc;function Vc(N,V){var fe=Xs(N),Ce=!fe&&il(N),St=!fe&&!Ce&&ga(N),Je=!fe&&!Ce&&!St&&al(N),Rt=fe||Ce||St||Je,cn=Rt?$t(N.length,String):[],gt=cn.length;for(var Ot in N)(V||$.call(N,Ot))&&!(Rt&&(Ot=="length"||St&&(Ot=="offset"||Ot=="parent")||Je&&(Ot=="buffer"||Ot=="byteLength"||Ot=="byteOffset")||Qc(Ot,gt)))&&cn.push(Ot);return cn}function is(N,V){for(var fe=N.length;fe--;)if(rl(N[fe][0],V))return fe;return-1}function da(N,V,fe){var Ce=V(N);return Xs(N)?Ce:ot(Ce,fe(N))}function ss(N){return N==null?N===void 0?J:q:Ln&&Ln in Object(N)?Jc(N):Yf(N)}function pa(N){return as(N)&&ss(N)==l}function os(N,V,fe,Ce,St){return N===V?!0:N==null||V==null||!as(N)&&!as(V)?N!==N&&V!==V:Kc(N,V,fe,Ce,os,St)}function Kc(N,V,fe,Ce,St,Je){var Rt=Xs(N),cn=Xs(V),gt=Rt?h:Nr(N),Ot=cn?h:Nr(V);gt=gt==l?T:gt,Ot=Ot==l?T:Ot;var Xt=gt==T,Wn=Ot==T,ln=gt==Ot;if(ln&&ga(N)){if(!ga(V))return!1;Rt=!0,Xt=!1}if(ln&&!Xt)return Je||(Je=new br),Rt||al(N)?Ys(N,V,fe,Ce,St,Je):Zf(N,V,gt,fe,Ce,St,Je);if(!(fe&i)){var Nt=Xt&&$.call(N,"__wrapped__"),Mn=Wn&&$.call(V,"__wrapped__");if(Nt||Mn){var _r=Nt?N.value():N,ur=Mn?V.value():V;return Je||(Je=new br),St(_r,ur,fe,Ce,Je)}}return ln?(Je||(Je=new br),Yc(N,V,fe,Ce,St,Je)):!1}function Gf(N){if(!ol(N)||tl(N))return!1;var V=Qs(N)?Q:ge;return V.test(Zr(N))}function Gc(N){return as(N)&&sl(N.length)&&!!be[ss(N)]}function Zc(N){if(!nl(N))return rs(N);var V=[];for(var fe in Object(N))$.call(N,fe)&&fe!="constructor"&&V.push(fe);return V}function Ys(N,V,fe,Ce,St,Je){var Rt=fe&i,cn=N.length,gt=V.length;if(cn!=gt&&!(Rt&&gt>cn))return!1;var Ot=Je.get(N);if(Ot&&Je.get(V))return Ot==V;var Xt=-1,Wn=!0,ln=fe&o?new Zs:void 0;for(Je.set(N,V),Je.set(V,N);++Xt<cn;){var Nt=N[Xt],Mn=V[Xt];if(Ce)var _r=Rt?Ce(Mn,Nt,Xt,V,N,Je):Ce(Nt,Mn,Xt,N,V,Je);if(_r!==void 0){if(_r)continue;Wn=!1;break}if(ln){if(!qe(V,function(ur,Lr){if(!Ye(ln,Lr)&&(Nt===ur||St(Nt,ur,fe,Ce,Je)))return ln.push(Lr)})){Wn=!1;break}}else if(!(Nt===Mn||St(Nt,Mn,fe,Ce,Je))){Wn=!1;break}}return Je.delete(N),Je.delete(V),Wn}function Zf(N,V,fe,Ce,St,Je,Rt){switch(fe){case de:if(N.byteLength!=V.byteLength||N.byteOffset!=V.byteOffset)return!1;N=N.buffer,V=V.buffer;case ee:return!(N.byteLength!=V.byteLength||!Je(new it(N),new it(V)));case v:case E:case k:return rl(+N,+V);case b:return N.name==V.name&&N.message==V.message;case R:case d:return N==V+"";case M:var cn=Le;case I:var gt=Ce&i;if(cn||(cn=et),N.size!=V.size&&!gt)return!1;var Ot=Rt.get(N);if(Ot)return Ot==V;Ce|=o,Rt.set(N,V);var Xt=Ys(cn(N),cn(V),Ce,St,Je,Rt);return Rt.delete(N),Xt;case x:if(Gt)return Gt.call(N)==Gt.call(V)}return!1}function Yc(N,V,fe,Ce,St,Je){var Rt=fe&i,cn=Js(N),gt=cn.length,Ot=Js(V),Xt=Ot.length;if(gt!=Xt&&!Rt)return!1;for(var Wn=gt;Wn--;){var ln=cn[Wn];if(!(Rt?ln in V:$.call(V,ln)))return!1}var Nt=Je.get(N);if(Nt&&Je.get(V))return Nt==V;var Mn=!0;Je.set(N,V),Je.set(V,N);for(var _r=Rt;++Wn<gt;){ln=cn[Wn];var ur=N[ln],Lr=V[ln];if(Ce)var ma=Rt?Ce(Lr,ur,ln,V,N,Je):Ce(ur,Lr,ln,N,V,Je);if(!(ma===void 0?ur===Lr||St(ur,Lr,fe,Ce,Je):ma)){Mn=!1;break}_r||(_r=ln=="constructor")}if(Mn&&!_r){var cs=N.constructor,vn=V.constructor;cs!=vn&&"constructor"in N&&"constructor"in V&&!(typeof cs=="function"&&cs instanceof cs&&typeof vn=="function"&&vn instanceof vn)&&(Mn=!1)}return Je.delete(N),Je.delete(V),Mn}function Js(N){return da(N,Qf,Xc)}function yi(N,V){var fe=N.__data__;return el(V)?fe[typeof V=="string"?"string":"hash"]:fe.map}function Xn(N,V){var fe=Me(N,V);return Gf(fe)?fe:void 0}function Jc(N){var V=$.call(N,Ln),fe=N[Ln];try{N[Ln]=void 0;var Ce=!0}catch{}var St=G.call(N);return Ce&&(V?N[Ln]=fe:delete N[Ln]),St}var Xc=Kr?function(N){return N==null?[]:(N=Object(N),tt(Kr(N),function(V){return ut.call(N,V)}))}:It,Nr=ss;(zt&&Nr(new zt(new ArrayBuffer(1)))!=de||jt&&Nr(new jt)!=M||Wt&&Nr(Wt.resolve())!=L||qt&&Nr(new qt)!=I||Bt&&Nr(new Bt)!=z)&&(Nr=function(N){var V=ss(N),fe=V==T?N.constructor:void 0,Ce=fe?Zr(fe):"";if(Ce)switch(Ce){case nn:return de;case rn:return M;case Vt:return L;case sn:return I;case Kt:return z}return V});function Qc(N,V){return V=V??c,!!V&&(typeof N=="number"||Ne.test(N))&&N>-1&&N%1==0&&N<V}function el(N){var V=typeof N;return V=="string"||V=="number"||V=="symbol"||V=="boolean"?N!=="__proto__":N===null}function tl(N){return!!B&&B in N}function nl(N){var V=N&&N.constructor,fe=typeof V=="function"&&V.prototype||_;return N===fe}function Yf(N){return G.call(N)}function Zr(N){if(N!=null){try{return m.call(N)}catch{}try{return N+""}catch{}}return""}function rl(N,V){return N===V||N!==N&&V!==V}var il=pa(function(){return arguments}())?pa:function(N){return as(N)&&$.call(N,"callee")&&!ut.call(N,"callee")},Xs=Array.isArray;function Jf(N){return N!=null&&sl(N.length)&&!Qs(N)}var ga=vi||Ct;function Xf(N,V){return os(N,V)}function Qs(N){if(!ol(N))return!1;var V=ss(N);return V==C||V==P||V==f||V==A}function sl(N){return typeof N=="number"&&N>-1&&N%1==0&&N<=c}function ol(N){var V=typeof N;return N!=null&&(V=="object"||V=="function")}function as(N){return N!=null&&typeof N=="object"}var al=Pe?Pt(Pe):Gc;function Qf(N){return Jf(N)?Vc(N):Zc(N)}function It(){return[]}function Ct(){return!1}t.exports=Xf})(Qu,Qu.exports);var d8=Qu.exports,p8=Object.defineProperty,Hp=Object.getOwnPropertySymbols,g8=Object.prototype.hasOwnProperty,m8=Object.prototype.propertyIsEnumerable,zp=(t,e,n)=>e in t?p8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Tn=(t,e)=>{for(var n in e||(e={}))g8.call(e,n)&&zp(t,n,e[n]);if(Hp)for(var n of Hp(e))m8.call(e,n)&&zp(t,n,e[n]);return t};function w8(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),c=o.charCodeAt(0);if(n[c]!==255)throw new TypeError(o+" is ambiguous");n[c]=i}var l=t.length,h=t.charAt(0),f=Math.log(l)/Math.log(256),v=Math.log(256)/Math.log(l);function E(P){if(P instanceof Uint8Array||(ArrayBuffer.isView(P)?P=new Uint8Array(P.buffer,P.byteOffset,P.byteLength):Array.isArray(P)&&(P=Uint8Array.from(P))),!(P instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(P.length===0)return"";for(var M=0,k=0,q=0,T=P.length;q!==T&&P[q]===0;)q++,M++;for(var L=(T-q)*v+1>>>0,A=new Uint8Array(L);q!==T;){for(var R=P[q],I=0,d=L-1;(R!==0||I<k)&&d!==-1;d--,I++)R+=256*A[d]>>>0,A[d]=R%l>>>0,R=R/l>>>0;if(R!==0)throw new Error("Non-zero carry");k=I,q++}for(var x=L-k;x!==L&&A[x]===0;)x++;for(var J=h.repeat(M);x<L;++x)J+=t.charAt(A[x]);return J}function b(P){if(typeof P!="string")throw new TypeError("Expected String");if(P.length===0)return new Uint8Array;var M=0;if(P[M]!==" "){for(var k=0,q=0;P[M]===h;)k++,M++;for(var T=(P.length-M)*f+1>>>0,L=new Uint8Array(T);P[M];){var A=n[P.charCodeAt(M)];if(A===255)return;for(var R=0,I=T-1;(A!==0||R<q)&&I!==-1;I--,R++)A+=l*L[I]>>>0,L[I]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");q=R,M++}if(P[M]!==" "){for(var d=T-q;d!==T&&L[d]===0;)d++;for(var x=new Uint8Array(k+(T-d)),J=k;d!==T;)x[J++]=L[d++];return x}}}function C(P){var M=b(P);if(M)return M;throw new Error(`Non-${e} character`)}return{encode:E,decodeUnsafe:b,decode:C}}var v8=w8,y8=v8;const Wp=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")},b8=t=>new TextEncoder().encode(t),_8=t=>new TextDecoder().decode(t);class E8{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class x8{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}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 qp(this,e)}}class C8{constructor(e){this.decoders=e}or(e){return qp(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const qp=(t,e)=>new C8(Tn(Tn({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class I8{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new E8(e,n,r),this.decoder=new x8(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ec=({name:t,prefix:e,encode:n,decode:r})=>new I8(t,e,n,r),Lo=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=y8(n,e);return ec({prefix:t,name:e,encode:r,decode:o=>Wp(i(o))})},S8=(t,e,n,r)=>{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*n/8|0);let l=0,h=0,f=0;for(let v=0;v<o;++v){const E=i[t[v]];if(E===void 0)throw new SyntaxError(`Non-${r} character`);h=h<<n|E,l+=n,l>=8&&(l-=8,c[f++]=255&h>>l)}if(l>=n||255&h<<8-l)throw new SyntaxError("Unexpected end of data");return c},O8=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let o="",c=0,l=0;for(let h=0;h<t.length;++h)for(l=l<<8|t[h],c+=8;c>n;)c-=n,o+=e[i&l>>c];if(c&&(o+=e[i&l<<n-c]),r)for(;o.length*n&7;)o+="=";return o},_n=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>ec({prefix:e,name:t,encode(i){return O8(i,r,n)},decode(i){return S8(i,r,n,t)}}),D8=ec({prefix:"\0",name:"identity",encode:t=>_8(t),decode:t=>b8(t)});var A8=Object.freeze({__proto__:null,identity:D8});const $8=_n({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var P8=Object.freeze({__proto__:null,base2:$8});const T8=_n({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var R8=Object.freeze({__proto__:null,base8:T8});const N8=Lo({prefix:"9",name:"base10",alphabet:"0123456789"});var L8=Object.freeze({__proto__:null,base10:N8});const M8=_n({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),j8=_n({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var U8=Object.freeze({__proto__:null,base16:M8,base16upper:j8});const F8=_n({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),B8=_n({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),k8=_n({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),H8=_n({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),z8=_n({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),W8=_n({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),q8=_n({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),V8=_n({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),K8=_n({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var G8=Object.freeze({__proto__:null,base32:F8,base32upper:B8,base32pad:k8,base32padupper:H8,base32hex:z8,base32hexupper:W8,base32hexpad:q8,base32hexpadupper:V8,base32z:K8});const Z8=Lo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Y8=Lo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var J8=Object.freeze({__proto__:null,base36:Z8,base36upper:Y8});const X8=Lo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Q8=Lo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var eE=Object.freeze({__proto__:null,base58btc:X8,base58flickr:Q8});const tE=_n({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),nE=_n({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),rE=_n({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),iE=_n({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var sE=Object.freeze({__proto__:null,base64:tE,base64pad:nE,base64url:rE,base64urlpad:iE});const Vp=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}"),oE=Vp.reduce((t,e,n)=>(t[n]=e,t),[]),aE=Vp.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function cE(t){return t.reduce((e,n)=>(e+=oE[n],e),"")}function lE(t){const e=[];for(const n of t){const r=aE[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const uE=ec({prefix:"\u{1F680}",name:"base256emoji",encode:cE,decode:lE});var hE=Object.freeze({__proto__:null,base256emoji:uE}),fE=Gp,Kp=128,dE=127,pE=~dE,gE=Math.pow(2,31);function Gp(t,e,n){e=e||[],n=n||0;for(var r=n;t>=gE;)e[n++]=t&255|Kp,t/=128;for(;t&pE;)e[n++]=t&255|Kp,t>>>=7;return e[n]=t|0,Gp.bytes=n-r+1,e}var mE=eh,wE=128,Zp=127;function eh(t,r){var n=0,r=r||0,i=0,o=r,c,l=t.length;do{if(o>=l)throw eh.bytes=0,new RangeError("Could not decode varint");c=t[o++],n+=i<28?(c&Zp)<<i:(c&Zp)*Math.pow(2,i),i+=7}while(c>=wE);return eh.bytes=o-r,n}var vE=Math.pow(2,7),yE=Math.pow(2,14),bE=Math.pow(2,21),_E=Math.pow(2,28),EE=Math.pow(2,35),xE=Math.pow(2,42),CE=Math.pow(2,49),IE=Math.pow(2,56),SE=Math.pow(2,63),OE=function(t){return t<vE?1:t<yE?2:t<bE?3:t<_E?4:t<EE?5:t<xE?6:t<CE?7:t<IE?8:t<SE?9:10},DE={encode:fE,decode:mE,encodingLength:OE},Yp=DE;const Jp=(t,e,n=0)=>(Yp.encode(t,e,n),e),Xp=t=>Yp.encodingLength(t),th=(t,e)=>{const n=e.byteLength,r=Xp(t),i=r+Xp(n),o=new Uint8Array(i+n);return Jp(t,o,0),Jp(n,o,r),o.set(e,i),new AE(t,n,e,o)};class AE{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const Qp=({name:t,code:e,encode:n})=>new $E(t,e,n);class $E{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?th(this.code,n):n.then(r=>th(this.code,r))}else throw Error("Unknown type, must be binary type")}}const eg=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),PE=Qp({name:"sha2-256",code:18,encode:eg("SHA-256")}),TE=Qp({name:"sha2-512",code:19,encode:eg("SHA-512")});var RE=Object.freeze({__proto__:null,sha256:PE,sha512:TE});const tg=0,NE="identity",ng=Wp;var LE=Object.freeze({__proto__:null,identity:{code:tg,name:NE,encode:ng,digest:t=>th(tg,ng(t))}});new TextEncoder,new TextDecoder;const rg=Tn(Tn(Tn(Tn(Tn(Tn(Tn(Tn(Tn(Tn({},A8),P8),R8),L8),U8),G8),J8),eE),sE),hE);Tn(Tn({},RE),LE);function ME(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function ig(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const sg=ig("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),nh=ig("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=ME(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),jE=Tn({utf8:sg,"utf-8":sg,hex:rg.base16,latin1:nh,ascii:nh,binary:nh},rg);function UE(t,e="utf8"){const n=jE[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):n.decoder.decode(`${n.prefix}${t}`)}const og="wc",FE=2,rh="core",li=`${og}@${2}:${rh}:`,BE={name:rh,logger:"error"},kE={database:":memory:"},HE="crypto",ag="client_ed25519_seed",zE=Ue.ONE_DAY,WE="keychain",qE="0.3",VE="messages",KE="0.3",GE=Ue.SIX_HOURS,ZE="publisher",cg="irn",YE="error",lg="wss://relay.walletconnect.com",JE="relayer",wn={message:"relayer_message",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},XE="_subscription",Mo={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},QE=Ue.ONE_SECOND,e7="2.7.0-rc-4",t7="0.3",Dr={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},n7="subscription",r7="0.3",i7=Ue.FIVE_SECONDS*1e3,s7="pairing",o7="0.3",jo={wc_pairingDelete:{req:{ttl:Ue.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:Ue.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:Ue.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:Ue.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:Ue.ONE_DAY,prompt:!1,tag:0},res:{ttl:Ue.ONE_DAY,prompt:!1,tag:0}}},Ar={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},a7="history",c7="0.3",l7="expirer",ir={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},u7="0.3",ug="verify-api",hg="https://verify.walletconnect.com";class h7{constructor(e,n){this.core=e,this.logger=n,this.keychain=new Map,this.name=WE,this.version=qE,this.initialized=!1,this.storagePrefix=li,this.init=async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}},this.has=r=>(this.isInitialized(),this.keychain.has(r)),this.set=async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()},this.get=r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:o}=Ee("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(o)}return i},this.del=async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()},this.core=e,this.logger=pt.generateChildLogger(n,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,I1(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?S1(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class f7{constructor(e,n,r){this.core=e,this.logger=n,this.name=HE,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=hp(i);return up(o.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const i=H5();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const o=await this.getClientSeed(),c=hp(o),l=yu();return await z4(l,i,zE,c)},this.generateSharedKey=(i,o,c)=>{this.isInitialized();const l=this.getPrivateKey(i),h=z5(l,o);return this.setSymKey(h,c)},this.setSymKey=async(i,o)=>{this.isInitialized();const c=o||W5(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=v1(c),h=Po(o);if(y1(l)){const b=l.senderPublicKey,C=l.receiverPublicKey;i=await this.generateSharedKey(b,C)}const f=this.getSymKey(i),{type:v,senderPublicKey:E}=l;return V5({type:v,symKey:f,message:h,senderPublicKey:E})},this.decode=async(i,o,c)=>{this.isInitialized();const l=Z5(o,c);if(y1(l)){const v=l.receiverPublicKey,E=l.senderPublicKey;i=await this.generateSharedKey(v,E)}const h=this.getSymKey(i),f=K5({symKey:h,encoded:o});return Bu(f)},this.getPayloadType=i=>{const o=za(i);return bo(o.type)},this.getPayloadSenderPublicKey=i=>{const o=za(i);return o.senderPublicKey?Dn(o.senderPublicKey,An):void 0},this.core=e,this.logger=pt.generateChildLogger(n,this.name),this.keychain=r||new h7(this.core,this.logger)}get context(){return pt.getLoggerContext(this.logger)}async setPrivateKey(e,n){return await this.keychain.set(e,n),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(ag)}catch{e=yu(),await this.keychain.set(ag,e)}return UE(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class d7 extends y4{constructor(e,n){super(e,n),this.logger=e,this.core=n,this.messages=new Map,this.name=VE,this.version=KE,this.initialized=!1,this.storagePrefix=li,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}},this.set=async(r,i)=>{this.isInitialized();const o=Ri(i);let c=this.messages.get(r);return typeof c>"u"&&(c={}),typeof c[o]<"u"||(c[o]=i,this.messages.set(r,c),await this.persist()),o},this.get=r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i},this.has=(r,i)=>{this.isInitialized();const o=this.get(r),c=Ri(i);return typeof o[c]<"u"},this.del=async r=>{this.isInitialized(),this.messages.delete(r),await this.persist()},this.logger=pt.generateChildLogger(e,this.name),this.core=n}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,I1(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?S1(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class p7 extends b4{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,this.events=new xn.exports.EventEmitter,this.name=ZE,this.queue=new Map,this.publishTimeout=1e4,this.publish=async(r,i,o)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:o}});try{const c=o?.ttl||GE,l=xu(o),h=o?.prompt||!1,f=o?.tag||0,v={topic:r,message:i,opts:{ttl:c,relay:l,prompt:h,tag:f}},E=Ri(i);this.queue.set(E,v);try{await await Wa(this.rpcPublish(r,i,c,l,h,f),this.publishTimeout),this.relayer.events.emit(wn.publish,v)}catch{this.logger.debug("Publishing Payload stalled"),this.relayer.events.emit(wn.connection_stalled);return}this.onPublish(E,v),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:o}})}catch(c){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(c),c}},this.on=(r,i)=>{this.events.on(r,i)},this.once=(r,i)=>{this.events.once(r,i)},this.off=(r,i)=>{this.events.off(r,i)},this.removeListener=(r,i)=>{this.events.removeListener(r,i)},this.relayer=e,this.logger=pt.generateChildLogger(n,this.name),this.registerEventListeners()}get context(){return pt.getLoggerContext(this.logger)}rpcPublish(e,n,r,i,o,c){var l,h,f,v;const E={method:qa(i.protocol).publish,params:{topic:e,message:n,ttl:r,prompt:o,tag:c}};return $n((l=E.params)==null?void 0:l.prompt)&&((h=E.params)==null||delete h.prompt),$n((f=E.params)==null?void 0:f.tag)&&((v=E.params)==null||delete v.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:E}),this.relayer.request(E)}onPublish(e,n){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:n,message:r,opts:i}=e;await this.publish(n,r,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(So.HEARTBEAT_EVENTS.pulse,()=>{this.checkQueue()})}}class g7{constructor(){this.map=new Map,this.set=(e,n)=>{const r=this.get(e);this.exists(e,n)||this.map.set(e,[...r,n])},this.get=e=>this.map.get(e)||[],this.exists=(e,n)=>this.get(e).includes(n),this.delete=(e,n)=>{if(typeof n>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,n))return;const i=r.filter(o=>o!==n);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 m7=Object.defineProperty,w7=Object.defineProperties,v7=Object.getOwnPropertyDescriptors,fg=Object.getOwnPropertySymbols,y7=Object.prototype.hasOwnProperty,b7=Object.prototype.propertyIsEnumerable,dg=(t,e,n)=>e in t?m7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Uo=(t,e)=>{for(var n in e||(e={}))y7.call(e,n)&&dg(t,n,e[n]);if(fg)for(var n of fg(e))b7.call(e,n)&&dg(t,n,e[n]);return t},ih=(t,e)=>w7(t,v7(e));class _7 extends x4{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,this.subscriptions=new Map,this.topicMap=new g7,this.events=new xn.exports.EventEmitter,this.name=n7,this.version=r7,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=li,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(r,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}});try{const o=xu(i),c={topic:r,relay:o};this.pending.set(r,c);const l=await this.rpcSubscribe(r,o);return this.onSubscribe(l,c),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}}),l}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}},this.unsubscribe=async(r,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)},this.isSubscribed=async r=>this.topics.includes(r)?!0:await new Promise((i,o)=>{const c=new Ue.Watch;c.start(this.pendingSubscriptionWatchLabel);const l=setInterval(()=>{!this.pending.has(r)&&this.topics.includes(r)&&(clearInterval(l),c.stop(this.pendingSubscriptionWatchLabel),i(!0)),c.elapsed(this.pendingSubscriptionWatchLabel)>=i7&&(clearInterval(l),c.stop(this.pendingSubscriptionWatchLabel),o(!1))},this.pollingInterval)}),this.on=(r,i)=>{this.events.on(r,i)},this.once=(r,i)=>{this.events.once(r,i)},this.off=(r,i)=>{this.events.off(r,i)},this.removeListener=(r,i)=>{this.events.removeListener(r,i)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=pt.generateChildLogger(n,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,n){let r=!1;try{r=this.getSubscription(e).topic===n}catch{}return r}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,n){const r=this.topicMap.get(e);await Promise.all(r.map(async i=>await this.unsubscribeById(e,i,n)))}async unsubscribeById(e,n,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}});try{const i=xu(r);await this.rpcUnsubscribe(e,n,i);const o=Yt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,n,o),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,n){const r={method:qa(n.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await Wa(this.relayer.request(r),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(wn.connection_stalled)}return Ri(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const n=e[0].relay,r={method:qa(n.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{return await await Wa(this.relayer.request(r),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(wn.connection_stalled)}}rpcUnsubscribe(e,n,r){const i={method:qa(r.protocol).unsubscribe,params:{topic:e,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,n){this.setSubscription(e,ih(Uo({},n),{id:e})),this.pending.delete(n.topic)}onBatchSubscribe(e){e.length&&e.forEach(n=>{this.setSubscription(n.id,Uo({},n)),this.pending.delete(n.topic)})}async onUnsubscribe(e,n,r){this.events.removeAllListeners(n),this.hasSubscription(n,e)&&this.deleteSubscription(n,r),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,n){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:n}),this.addSubscription(e,n))}addSubscription(e,n){this.subscriptions.set(e,Uo({},n)),this.topicMap.set(n.topic,e),this.events.emit(Dr.created,n)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const n=this.subscriptions.get(e);if(!n){const{message:r}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}deleteSubscription(e,n){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:n});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(Dr.deleted,ih(Uo({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Dr.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<e;n++){const r=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(Dr.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:n}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(n)}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 n=await this.rpcBatchSubscribe(e);Fr(n)&&this.onBatchSubscribe(n.map((r,i)=>ih(Uo({},e[i]),{id:r})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach(n=>{e.push(n)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(So.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(wn.connect,async()=>{await this.onConnect()}),this.relayer.on(wn.disconnect,()=>{this.onDisconnect()}),this.events.on(Dr.created,async e=>{const n=Dr.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),await this.persist()}),this.events.on(Dr.deleted,async e=>{const n=Dr.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{const n=setInterval(()=>{this.restartInProgress||(clearInterval(n),e())},this.pollingInterval)})}}var E7=Object.defineProperty,pg=Object.getOwnPropertySymbols,x7=Object.prototype.hasOwnProperty,C7=Object.prototype.propertyIsEnumerable,gg=(t,e,n)=>e in t?E7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,I7=(t,e)=>{for(var n in e||(e={}))x7.call(e,n)&&gg(t,n,e[n]);if(pg)for(var n of pg(e))C7.call(e,n)&&gg(t,n,e[n]);return t};class S7 extends _4{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new xn.exports.EventEmitter,this.name=JE,this.transportExplicitlyClosed=!1,this.initialized=!1,this.reconnecting=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],this.request=async n=>{this.logger.debug("Publishing Request Payload");try{return await this.toEstablishConnection(),await this.provider.request(n)}catch(r){throw this.logger.debug("Failed to Publish Request"),this.logger.error(r),r}},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||YE})),this.messages=new d7(this.logger,e.core),this.subscriber=new _7(this,this.logger),this.publisher=new p7(this,this.logger),this.relayUrl=e?.relayUrl||lg,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}get context(){return pt.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,n,r){this.isInitialized(),await this.publisher.publish(e,n,r),await this.recordMessageEvent({topic:e,message:n,publishedAt:Date.now()})}async subscribe(e,n){this.isInitialized();let r="";return await Promise.all([new Promise(i=>{this.subscriber.once(Dr.created,o=>{o.topic===e&&i()})}),new Promise(async i=>{r=await this.subscriber.subscribe(e,n),i()})]),r}async unsubscribe(e,n){this.isInitialized(),await this.subscriber.unsubscribe(e,n)}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async transportClose(){this.transportExplicitlyClosed=!0,this.connected&&(await this.provider.disconnect(),this.events.emit(wn.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(n=>{this.initialized||n(),this.subscriber.once(Dr.resubscribed,()=>{n()})}),await Promise.race([new Promise(async(n,r)=>{await Wa(this.provider.connect(),5e3,"socket stalled").catch(i=>r(i)).then(()=>n()).finally(()=>this.removeListener(wn.transport_closed,this.rejectTransportOpen))}),new Promise(n=>this.once(wn.transport_closed,this.rejectTransportOpen))])])}catch(n){this.logger.error(n);const r=n;if(!this.isConnectionStalled(r.message))throw n;this.events.emit(wn.transport_closed)}finally{this.reconnecting=!1}}}async restartTransport(e){this.transportExplicitlyClosed||(this.relayUrl=e||this.relayUrl,this.connected&&await Promise.all([new Promise(n=>{this.provider.once(Mo.disconnect,()=>{n()})}),this.transportClose()]),await this.createProvider(),await this.transportOpen())}isConnectionStalled(e){return this.staleConnectionErrors.some(n=>e.includes(n))}rejectTransportOpen(){throw new Error("closeTransport called before connection was established")}async createProvider(){const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new ci(new f8(ob({sdkVersion:e7,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:n,message:r}=e;await this.messages.set(n,r)}async shouldIgnoreMessageEvent(e){const{topic:n,message:r}=e;return await this.subscriber.isSubscribed(n)?this.messages.has(n,r):!0}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Xu(e)){if(!e.method.endsWith(XE))return;const n=e.params,{topic:r,message:i,publishedAt:o}=n.data,c={topic:r,message:i,publishedAt:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(I7({type:"event",event:n.id},c)),this.events.emit(n.id,c),await this.acknowledgePayload(e),await this.onMessageEvent(c)}}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(wn.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const n=Ju(e.id,!0);await this.provider.connection.send(n)}registerProviderListeners(){this.provider.on(Mo.payload,e=>this.onProviderPayload(e)),this.provider.on(Mo.connect,()=>{this.events.emit(wn.connect)}),this.provider.on(Mo.disconnect,()=>{this.onProviderDisconnect()}),this.provider.on(Mo.error,e=>{this.logger.error(e),this.events.emit(wn.error,e)})}registerEventListeners(){this.events.on(wn.connection_stalled,async()=>{await this.restartTransport()})}onProviderDisconnect(){this.events.emit(wn.disconnect),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||setTimeout(async()=>{await this.restartTransport()},Ue.toMiliseconds(QE))}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(!this.connected){if(this.connecting)return await new Promise(e=>{const n=setInterval(()=>{this.connected&&(clearInterval(n),e())},this.connectionStatusPollingInterval)});await this.restartTransport()}}}var O7=Object.defineProperty,mg=Object.getOwnPropertySymbols,D7=Object.prototype.hasOwnProperty,A7=Object.prototype.propertyIsEnumerable,wg=(t,e,n)=>e in t?O7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,vg=(t,e)=>{for(var n in e||(e={}))D7.call(e,n)&&wg(t,n,e[n]);if(mg)for(var n of mg(e))A7.call(e,n)&&wg(t,n,e[n]);return t};class tc extends E4{constructor(e,n,r,i=li,o=void 0){super(e,n,r,i),this.core=e,this.logger=n,this.name=r,this.map=new Map,this.version=t7,this.cached=[],this.initialized=!1,this.storagePrefix=li,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(c=>{this.getKey&&c!==null&&!$n(c)?this.map.set(this.getKey(c),c):Ob(c)?this.map.set(c.id,c):Db(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=>d8(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=vg(vg({},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(n,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 n=this.map.get(e);if(!n){const{message:r}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return n}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:n}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}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}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class $7{constructor(e,n){this.core=e,this.logger=n,this.name=s7,this.version=o7,this.events=new xn.exports,this.initialized=!1,this.storagePrefix=li,this.ignoredPayloadTypes=[Ti],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:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]},this.create=async()=>{this.isInitialized();const r=yu(),i=await this.core.crypto.setSymKey(r),o=yr(Ue.FIVE_MINUTES),c={protocol:cg},l={topic:i,expiry:o,relay:c,active:!1},h=wb({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:r,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 r=>{this.isInitialized(),this.isValidPair(r);const{topic:i,symKey:o,relay:c}=gb(r.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=yr(Ue.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),r.activatePairing&&await this.activate({topic:i}),h},this.activate=async({topic:r})=>{this.isInitialized();const i=yr(Ue.THIRTY_DAYS);await this.pairings.update(r,{active:!0,expiry:i}),this.core.expirer.set(r,i)},this.ping=async r=>{this.isInitialized(),await this.isValidPing(r);const{topic:i}=r;if(this.pairings.keys.includes(i)){const o=await this.sendRequest(i,"wc_pairingPing",{}),{done:c,resolve:l,reject:h}=_s();this.events.once(tn("pairing_ping",o),({error:f})=>{f?h(f):l()}),await c()}},this.updateExpiry=async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})},this.updateMetadata=async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:i}=r;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",Yt("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(r,i,o)=>{const c=Yu(i,o),l=await this.core.crypto.encode(r,c),h=jo[i].req;return this.core.history.set(r,c),await this.core.relayer.publish(r,l,h),c.id},this.sendResult=async(r,i,o)=>{const c=Ju(r,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,r),f=jo[h.request.method].res;await this.core.relayer.publish(i,l,f),await this.core.history.resolve(c)},this.sendError=async(r,i,o)=>{const c=Qa(r,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,r),f=jo[h.request.method]?jo[h.request.method].res:jo.unregistered_method.res;await this.core.relayer.publish(i,l,f),await this.core.history.resolve(c)},this.deletePairing=async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,Yt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])},this.cleanup=async()=>{const r=this.pairings.getAll().filter(i=>ai(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=r=>{const{topic:i,payload:o}=r,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 r=>{const{topic:i,payload:o}=r,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(r,i)=>{const{id:o}=i;try{this.isValidPing({topic:r}),await this.sendResult(o,r,!0),this.events.emit("pairing_ping",{id:o,topic:r})}catch(c){await this.sendError(o,r,c),this.logger.error(c)}},this.onPairingPingResponse=(r,i)=>{const{id:o}=i;setTimeout(()=>{Wr(i)?this.events.emit(tn("pairing_ping",o),{}):Or(i)&&this.events.emit(tn("pairing_ping",o),{error:i.error})},500)},this.onPairingDeleteRequest=async(r,i)=>{const{id:o}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit("pairing_delete",{id:o,topic:r})}catch(c){await this.sendError(o,r,c),this.logger.error(c)}},this.onUnknownRpcMethodRequest=async(r,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,r,l),this.logger.error(l)}catch(l){await this.sendError(o,r,l),this.logger.error(l)}},this.onUnknownRpcMethodResponse=r=>{this.registeredMethods.includes(r)||this.logger.error(Yt("WC_METHOD_UNSUPPORTED",r))},this.isValidPair=r=>{if(!kn(r)){const{message:i}=Ee("MISSING_OR_INVALID",`pair() params: ${r}`);throw new Error(i)}if(!Sb(r.uri)){const{message:i}=Ee("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw new Error(i)}},this.isValidPing=async r=>{if(!kn(r)){const{message:o}=Ee("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(o)}const{topic:i}=r;await this.isValidPairingTopic(i)},this.isValidDisconnect=async r=>{if(!kn(r)){const{message:o}=Ee("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(o)}const{topic:i}=r;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async r=>{if(!mn(r,!1)){const{message:i}=Ee("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=Ee("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(ai(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=Ee("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}},this.core=e,this.logger=pt.generateChildLogger(n,this.name),this.pairings=new tc(this.core,this.logger,this.name,this.storagePrefix)}get context(){return pt.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(wn.message,async e=>{const{topic:n,message:r}=e;if(this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))return;const i=await this.core.crypto.decode(n,r);Xu(i)?(this.core.history.set(n,i),this.onRelayEventRequest({topic:n,payload:i})):Bp(i)&&(await this.core.history.resolve(i),this.onRelayEventResponse({topic:n,payload:i}))})}registerExpirerEvents(){this.core.expirer.on(ir.expired,async e=>{const{topic:n}=D1(e.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit("pairing_expire",{topic:n}))})}}class P7 extends v4{constructor(e,n){super(e,n),this.core=e,this.logger=n,this.records=new Map,this.events=new xn.exports.EventEmitter,this.name=a7,this.version=c7,this.cached=[],this.initialized=!1,this.storagePrefix=li,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(r,i,o)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:i,chainId:o}),this.records.has(i.id))return;const c={id:i.id,topic:r,request:{method:i.method,params:i.params||null},chainId:o};this.records.set(c.id,c),this.events.emit(Ar.created,c)},this.resolve=async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const i=await this.getRecord(r.id);typeof i.response>"u"&&(i.response=Or(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.events.emit(Ar.updated,i))},this.get=async(r,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:i}),await this.getRecord(i)),this.delete=(r,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(o=>{if(o.topic===r){if(typeof i<"u"&&o.id!==i)return;this.records.delete(o.id),this.events.emit(Ar.deleted,o)}})},this.exists=async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1),this.on=(r,i)=>{this.events.on(r,i)},this.once=(r,i)=>{this.events.once(r,i)},this.off=(r,i)=>{this.events.off(r,i)},this.removeListener=(r,i)=>{this.events.removeListener(r,i)},this.logger=pt.generateChildLogger(n,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(n=>{if(typeof n.response<"u")return;const r={topic:n.topic,request:Yu(n.request.method,n.request.params,n.id),chainId:n.chainId};return e.push(r)}),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 n=this.records.get(e);if(!n){const{message:r}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ar.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:n}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}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(Ar.created,e=>{const n=Ar.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e}),this.persist()}),this.events.on(Ar.updated,e=>{const n=Ar.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e}),this.persist()}),this.events.on(Ar.deleted,e=>{const n=Ar.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class T7 extends C4{constructor(e,n){super(e,n),this.core=e,this.logger=n,this.expirations=new Map,this.events=new xn.exports.EventEmitter,this.name=l7,this.version=u7,this.cached=[],this.initialized=!1,this.storagePrefix=li,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(r,i)=>{this.isInitialized();const o=this.formatTarget(r),c={target:o,expiry:i};this.expirations.set(o,c),this.checkExpiry(o,c),this.events.emit(ir.created,{target:o,expiration:c})},this.get=r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)},this.del=r=>{if(this.isInitialized(),this.has(r)){const i=this.formatTarget(r),o=this.getExpiration(i);this.expirations.delete(i),this.events.emit(ir.deleted,{target:i,expiration:o})}},this.on=(r,i)=>{this.events.on(r,i)},this.once=(r,i)=>{this.events.once(r,i)},this.off=(r,i)=>{this.events.off(r,i)},this.removeListener=(r,i)=>{this.events.removeListener(r,i)},this.logger=pt.generateChildLogger(n,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 ab(e);if(typeof e=="number")return cb(e);const{message:n}=Ee("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(n)}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(ir.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:n}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}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 n=this.expirations.get(e);if(!n){const{message:r}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return n}checkExpiry(e,n){const{expiry:r}=n;Ue.toMiliseconds(r)-Date.now()<=0&&this.expire(e,n)}expire(e,n){this.expirations.delete(e),this.events.emit(ir.expired,{target:e,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,n)=>this.checkExpiry(n,e))}registerEventListeners(){this.core.heartbeat.on(So.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(ir.created,e=>{const n=ir.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(ir.expired,e=>{const n=ir.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(ir.deleted,e=>{const n=ir.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class R7 extends I4{constructor(e,n){super(e,n),this.projectId=e,this.logger=n,this.name=ug,this.initialized=!1,this.init=async r=>{x1()||!_u()||(this.verifyUrl=r?.verifyUrl||hg,await this.createIframe())},this.register=async r=>{var i;this.initialized||await this.init(),this.iframe&&((i=this.iframe.contentWindow)==null||i.postMessage(r.attestationId,this.verifyUrl),this.logger.info(`postMessage sent: ${r.attestationId} ${this.verifyUrl}`))},this.resolve=async r=>{var i;if(this.isDevEnv)return"";this.logger.info(`resolving attestation: ${r.attestationId}`);const o=this.startAbortTimer(Ue.FIVE_SECONDS),c=await fetch(`${this.verifyUrl}/attestation/${r.attestationId}`,{signal:this.abortController.signal});return clearTimeout(o),((i=await c.json())==null?void 0:i.origin)||""},this.createIframe=async()=>{try{const r=this.startAbortTimer(Ue.FIVE_SECONDS);await Promise.race([new Promise((i,o)=>{const c=document.createElement("iframe");c.setAttribute("id",ug),c.setAttribute("src",`${this.verifyUrl}/${this.projectId}`),c.style.display="none",c.addEventListener("load",()=>{this.initialized=!0,clearTimeout(r),i()}),c.addEventListener("error",l=>{o(l)}),document.body.append(c),this.iframe=c}),new Promise(i=>{this.abortController.signal.addEventListener("abort",()=>{i("iframe load timeout")})})])}catch(r){this.logger.error(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.error(r)}},this.logger=pt.generateChildLogger(n,this.name),this.verifyUrl=hg,this.abortController=new AbortController,this.isDevEnv=bu()&&process.env.IS_VITEST}get context(){return pt.getLoggerContext(this.logger)}startAbortTimer(e){return setTimeout(()=>this.abortController.abort(),yr(e))}}var N7=Object.defineProperty,yg=Object.getOwnPropertySymbols,L7=Object.prototype.hasOwnProperty,M7=Object.prototype.propertyIsEnumerable,bg=(t,e,n)=>e in t?N7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_g=(t,e)=>{for(var n in e||(e={}))L7.call(e,n)&&bg(t,n,e[n]);if(yg)for(var n of yg(e))M7.call(e,n)&&bg(t,n,e[n]);return t};class sh extends w4{constructor(e){super(e),this.protocol=og,this.version=FE,this.name=rh,this.events=new xn.exports.EventEmitter,this.initialized=!1,this.on=(r,i)=>this.events.on(r,i),this.once=(r,i)=>this.events.once(r,i),this.off=(r,i)=>this.events.off(r,i),this.removeListener=(r,i)=>this.events.removeListener(r,i),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||lg;const n=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||BE.logger}));this.logger=pt.generateChildLogger(n,this.name),this.heartbeat=new So.HeartBeat,this.crypto=new f7(this,this.logger,e?.keychain),this.history=new P7(this,this.logger),this.expirer=new T7(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new _6(_g(_g({},kE),e?.storageOptions)),this.relayer=new S7({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new $7(this,this.logger),this.verify=new R7(this.projectId||"",this.logger)}static async init(e){const n=new sh(e);return await n.initialize(),n}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 j7=sh,Eg="wc",xg=2,Cg="client",oh=`${Eg}@${xg}:${Cg}:`,ah={name:Cg,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},U7="proposal",Ig="Proposal expired",F7="session",nc=Ue.SEVEN_DAYS,B7="engine",Fo={wc_sessionPropose:{req:{ttl:Ue.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Ue.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:Ue.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Ue.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Ue.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Ue.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Ue.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Ue.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Ue.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Ue.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Ue.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Ue.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Ue.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Ue.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Ue.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:Ue.THIRTY_SECONDS,prompt:!1,tag:1115}}},ch={min:Ue.FIVE_MINUTES,max:Ue.SEVEN_DAYS},k7="request",H7=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var z7=Object.defineProperty,W7=Object.defineProperties,q7=Object.getOwnPropertyDescriptors,Sg=Object.getOwnPropertySymbols,V7=Object.prototype.hasOwnProperty,K7=Object.prototype.propertyIsEnumerable,Og=(t,e,n)=>e in t?z7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,sr=(t,e)=>{for(var n in e||(e={}))V7.call(e,n)&&Og(t,n,e[n]);if(Sg)for(var n of Sg(e))K7.call(e,n)&&Og(t,n,e[n]);return t},lh=(t,e)=>W7(t,q7(e));class G7 extends O4{constructor(e){super(e),this.name=B7,this.events=new xn.exports,this.initialized=!1,this.ignoredPayloadTypes=[Ti],this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.client.core.pairing.register({methods:Object.keys(Fo)}),this.initialized=!0)},this.connect=async n=>{this.isInitialized();const r=lh(sr({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(r);const{pairingTopic:i,requiredNamespaces:o,optionalNamespaces:c,sessionProperties:l,relays:h}=r;let f=i,v,E=!1;if(f&&(E=this.client.core.pairing.pairings.get(f).active),!f||!E){const{topic:L,uri:A}=await this.client.core.pairing.create();f=L,v=A}const b=await this.client.core.crypto.generateKeyPair(),C=sr({requiredNamespaces:o,optionalNamespaces:c,relays:h??[{protocol:cg}],proposer:{publicKey:b,metadata:this.client.metadata}},l&&{sessionProperties:l}),{reject:P,resolve:M,done:k}=_s(Ue.FIVE_MINUTES,Ig);if(this.events.once(tn("session_connect"),async({error:L,session:A})=>{if(L)P(L);else if(A){A.self.publicKey=b;const R=lh(sr({},A),{requiredNamespaces:A.requiredNamespaces,optionalNamespaces:A.optionalNamespaces});await this.client.session.set(A.topic,R),await this.setExpiry(A.topic,A.expiry),f&&await this.client.core.pairing.updateMetadata({topic:f,metadata:A.peer.metadata}),M(R)}}),!f){const{message:L}=Ee("NO_MATCHING_KEY",`connect() pairing topic: ${f}`);throw new Error(L)}const q=await this.sendRequest(f,"wc_sessionPropose",C),T=yr(Ue.FIVE_MINUTES);return await this.setProposal(q,sr({id:q,expiry:T},C)),{uri:v,approval:k}},this.pair=async n=>(this.isInitialized(),await this.client.core.pairing.pair(n)),this.approve=async n=>{this.isInitialized(),await this.isValidApprove(n);const{id:r,relayProtocol:i,namespaces:o,sessionProperties:c}=n,l=this.client.proposal.get(r);let{pairingTopic:h,proposer:f,requiredNamespaces:v,optionalNamespaces:E}=l;h=h||"",xs(v)||(v=_b(o,"approve()"));const b=await this.client.core.crypto.generateKeyPair(),C=f.publicKey,P=await this.client.core.crypto.generateSharedKey(b,C);h&&r&&(await this.client.core.pairing.updateMetadata({topic:h,metadata:f.metadata}),await this.sendResult(r,h,{relay:{protocol:i??"irn"},responderPublicKey:b}),await this.client.proposal.delete(r,Yt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:h}));const M=sr({relay:{protocol:i??"irn"},namespaces:o,requiredNamespaces:v,optionalNamespaces:E,pairingTopic:h,controller:{publicKey:b,metadata:this.client.metadata},expiry:yr(nc)},c&&{sessionProperties:c});await this.client.core.relayer.subscribe(P),await this.sendRequest(P,"wc_sessionSettle",M);const k=lh(sr({},M),{topic:P,pairingTopic:h,acknowledged:!1,self:M.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:b});return await this.client.session.set(P,k),await this.setExpiry(P,yr(nc)),{topic:P,acknowledged:()=>new Promise(q=>q(this.client.session.get(P)))}},this.reject=async n=>{this.isInitialized(),await this.isValidReject(n);const{id:r,reason:i}=n,{pairingTopic:o}=this.client.proposal.get(r);o&&(await this.sendError(r,o,i),await this.client.proposal.delete(r,Yt("USER_DISCONNECTED")))},this.update=async n=>{this.isInitialized(),await this.isValidUpdate(n);const{topic:r,namespaces:i}=n,o=await this.sendRequest(r,"wc_sessionUpdate",{namespaces:i}),{done:c,resolve:l,reject:h}=_s();return this.events.once(tn("session_update",o),({error:f})=>{f?h(f):l()}),await this.client.session.update(r,{namespaces:i}),{acknowledged:c}},this.extend=async n=>{this.isInitialized(),await this.isValidExtend(n);const{topic:r}=n,i=await this.sendRequest(r,"wc_sessionExtend",{}),{done:o,resolve:c,reject:l}=_s();return this.events.once(tn("session_extend",i),({error:h})=>{h?l(h):c()}),await this.setExpiry(r,yr(nc)),{acknowledged:o}},this.request=async n=>{this.isInitialized(),await this.isValidRequest(n);const{chainId:r,request:i,topic:o,expiry:c}=n,l=await this.sendRequest(o,"wc_sessionRequest",{request:i,chainId:r},c),{done:h,resolve:f,reject:v}=_s(c);return this.events.once(tn("session_request",l),({error:E,result:b})=>{E?v(E):f(b)}),this.client.events.emit("session_request_sent",{topic:o,request:i,chainId:r,id:l}),await h()},this.respond=async n=>{this.isInitialized(),await this.isValidRespond(n);const{topic:r,response:i}=n,{id:o}=i;Wr(i)?await this.sendResult(o,r,i.result):Or(i)&&await this.sendError(o,r,i.error),this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0})},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);const{topic:r}=n;if(this.client.session.keys.includes(r)){const i=await this.sendRequest(r,"wc_sessionPing",{}),{done:o,resolve:c,reject:l}=_s();this.events.once(tn("session_ping",i),({error:h})=>{h?l(h):c()}),await o()}else this.client.core.pairing.pairings.keys.includes(r)&&await this.client.core.pairing.ping({topic:r})},this.emit=async n=>{this.isInitialized(),await this.isValidEmit(n);const{topic:r,event:i,chainId:o}=n;await this.sendRequest(r,"wc_sessionEvent",{event:i,chainId:o})},this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:r}=n;this.client.session.keys.includes(r)?(await this.sendRequest(r,"wc_sessionDelete",Yt("USER_DISCONNECTED")),await this.deleteSession(r)):await this.client.core.pairing.disconnect({topic:r})},this.find=n=>(this.isInitialized(),this.client.session.getAll().filter(r=>Cb(r,n))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.deleteSession=async(n,r)=>{const{self:i}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await Promise.all([this.client.session.delete(n,Yt("USER_DISCONNECTED")),this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.deleteSymKey(n),r?Promise.resolve():this.client.core.expirer.del(n)])},this.deleteProposal=async(n,r)=>{await Promise.all([this.client.proposal.delete(n,Yt("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)])},this.deletePendingSessionRequest=async(n,r,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)])},this.setExpiry=async(n,r)=>{this.client.session.keys.includes(n)&&await this.client.session.update(n,{expiry:r}),this.client.core.expirer.set(n,r)},this.setProposal=async(n,r)=>{await this.client.proposal.set(n,r),this.client.core.expirer.set(n,r.expiry)},this.setPendingSessionRequest=async n=>{const r=Fo.wc_sessionRequest.req.ttl,{id:i,topic:o,params:c}=n;await this.client.pendingRequest.set(i,{id:i,topic:o,params:c}),r&&this.client.core.expirer.set(i,yr(r))},this.sendRequest=async(n,r,i,o)=>{const c=Yu(r,i);if(_u()&&H7.includes(r)){const f=Ri(JSON.stringify(c));await this.client.core.verify.register({attestationId:f})}const l=await this.client.core.crypto.encode(n,c),h=Fo[r].req;return o&&(h.ttl=o),this.client.core.history.set(n,c),this.client.core.relayer.publish(n,l,h),c.id},this.sendResult=async(n,r,i)=>{const o=Ju(n,i),c=await this.client.core.crypto.encode(r,o),l=await this.client.core.history.get(r,n),h=Fo[l.request.method].res;this.client.core.relayer.publish(r,c,h),await this.client.core.history.resolve(o)},this.sendError=async(n,r,i)=>{const o=Qa(n,i),c=await this.client.core.crypto.encode(r,o),l=await this.client.core.history.get(r,n),h=Fo[l.request.method].res;this.client.core.relayer.publish(r,c,h),await this.client.core.history.resolve(o)},this.cleanup=async()=>{const n=[],r=[];this.client.session.getAll().forEach(i=>{ai(i.expiry)&&n.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{ai(i.expiry)&&r.push(i.id)}),await Promise.all([...n.map(i=>this.deleteSession(i)),...r.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=n=>{const{topic:r,payload:i}=n,o=i.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeRequest(r,i);case"wc_sessionSettle":return this.onSessionSettleRequest(r,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(r,i);case"wc_sessionExtend":return this.onSessionExtendRequest(r,i);case"wc_sessionPing":return this.onSessionPingRequest(r,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(r,i);case"wc_sessionRequest":return this.onSessionRequest(r,i);case"wc_sessionEvent":return this.onSessionEventRequest(r,i);default:return this.client.logger.info(`Unsupported request method ${o}`)}},this.onRelayEventResponse=async n=>{const{topic:r,payload:i}=n,o=(await this.client.core.history.get(r,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,i);case"wc_sessionSettle":return this.onSessionSettleResponse(r,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,i);case"wc_sessionExtend":return this.onSessionExtendResponse(r,i);case"wc_sessionPing":return this.onSessionPingResponse(r,i);case"wc_sessionRequest":return this.onSessionRequestResponse(r,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}},this.onSessionProposeRequest=async(n,r)=>{const{params:i,id:o}=r;try{this.isValidConnect(sr({},r.params));const c=yr(Ue.FIVE_MINUTES),l=sr({id:o,pairingTopic:n,expiry:c},i);await this.setProposal(o,l);const h=Ri(JSON.stringify(r)),f=await this.getVerifyContext(h,l.proposer.metadata);this.client.events.emit("session_proposal",{id:o,params:l,context:f})}catch(c){await this.sendError(o,n,c),this.client.logger.error(c)}},this.onSessionProposeResponse=async(n,r)=>{const{id:i}=r;if(Wr(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const c=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:c});const l=c.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:l});const h=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const f=await this.client.core.crypto.generateSharedKey(l,h);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:f});const v=await this.client.core.relayer.subscribe(f);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:v}),await this.client.core.pairing.activate({topic:n})}else Or(r)&&(await this.client.proposal.delete(i,Yt("USER_DISCONNECTED")),this.events.emit(tn("session_connect"),{error:r.error}))},this.onSessionSettleRequest=async(n,r)=>{const{id:i,params:o}=r;try{this.isValidSessionSettleRequest(o);const{relay:c,controller:l,expiry:h,namespaces:f,requiredNamespaces:v,optionalNamespaces:E,sessionProperties:b,pairingTopic:C}=r.params,P=sr({topic:n,relay:c,expiry:h,namespaces:f,acknowledged:!0,pairingTopic:C,requiredNamespaces:v,optionalNamespaces:E,controller:l.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:l.publicKey,metadata:l.metadata}},b&&{sessionProperties:b});await this.sendResult(r.id,n,!0),this.events.emit(tn("session_connect"),{session:P})}catch(c){await this.sendError(i,n,c),this.client.logger.error(c)}},this.onSessionSettleResponse=async(n,r)=>{const{id:i}=r;Wr(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(tn("session_approve",i),{})):Or(r)&&(await this.client.session.delete(n,Yt("USER_DISCONNECTED")),this.events.emit(tn("session_approve",i),{error:r.error}))},this.onSessionUpdateRequest=async(n,r)=>{const{params:i,id:o}=r;try{this.isValidUpdate(sr({topic:n},i)),await this.client.session.update(n,{namespaces:i.namespaces}),await this.sendResult(o,n,!0),this.client.events.emit("session_update",{id:o,topic:n,params:i})}catch(c){await this.sendError(o,n,c),this.client.logger.error(c)}},this.onSessionUpdateResponse=(n,r)=>{const{id:i}=r;Wr(r)?this.events.emit(tn("session_update",i),{}):Or(r)&&this.events.emit(tn("session_update",i),{error:r.error})},this.onSessionExtendRequest=async(n,r)=>{const{id:i}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,yr(nc)),await this.sendResult(i,n,!0),this.client.events.emit("session_extend",{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.client.logger.error(o)}},this.onSessionExtendResponse=(n,r)=>{const{id:i}=r;Wr(r)?this.events.emit(tn("session_extend",i),{}):Or(r)&&this.events.emit(tn("session_extend",i),{error:r.error})},this.onSessionPingRequest=async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult(i,n,!0),this.client.events.emit("session_ping",{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.client.logger.error(o)}},this.onSessionPingResponse=(n,r)=>{const{id:i}=r;setTimeout(()=>{Wr(r)?this.events.emit(tn("session_ping",i),{}):Or(r)&&this.events.emit(tn("session_ping",i),{error:r.error})},500)},this.onSessionDeleteRequest=async(n,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:n,reason:r.params}),await Promise.all([new Promise(o=>{this.client.core.relayer.once(wn.publish,async()=>{o(await this.deleteSession(n))})}),this.sendResult(i,n,!0)]),this.client.events.emit("session_delete",{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.client.logger.error(o)}},this.onSessionRequest=async(n,r)=>{const{id:i,params:o}=r;try{this.isValidRequest(sr({topic:n},o)),await this.setPendingSessionRequest({id:i,topic:n,params:o});const c=Ri(JSON.stringify(r)),l=this.client.session.get(n),h=await this.getVerifyContext(c,l.peer.metadata);this.client.events.emit("session_request",{id:i,topic:n,params:o,context:h})}catch(c){await this.sendError(i,n,c),this.client.logger.error(c)}},this.onSessionRequestResponse=(n,r)=>{const{id:i}=r;Wr(r)?this.events.emit(tn("session_request",i),{result:r.result}):Or(r)&&this.events.emit(tn("session_request",i),{error:r.error})},this.onSessionEventRequest=async(n,r)=>{const{id:i,params:o}=r;try{this.isValidEmit(sr({topic:n},o)),this.client.events.emit("session_event",{id:i,topic:n,params:o})}catch(c){await this.sendError(i,n,c),this.client.logger.error(c)}},this.isValidConnect=async n=>{if(!kn(n)){const{message:h}=Ee("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(h)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:c,relays:l}=n;if($n(r)||await this.isValidPairingTopic(r),!Mb(l,!0)){const{message:h}=Ee("MISSING_OR_INVALID",`connect() relays: ${l}`);throw new Error(h)}!$n(i)&&xs(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!$n(o)&&xs(o)!==0&&this.validateNamespaces(o,"optionalNamespaces"),$n(c)||this.validateSessionProps(c,"sessionProperties")},this.validateNamespaces=(n,r)=>{const i=Lb(n,"connect()",r);if(i)throw new Error(i.message)},this.isValidApprove=async n=>{if(!kn(n))throw new Error(Ee("MISSING_OR_INVALID",`approve() params: ${n}`).message);const{id:r,namespaces:i,relayProtocol:o,sessionProperties:c}=n;await this.isValidProposalId(r);const l=this.client.proposal.get(r),h=Ka(i,"approve()");if(h)throw new Error(h.message);const f=M1(l.requiredNamespaces,i,"approve()");if(f)throw new Error(f.message);if(!mn(o,!0)){const{message:v}=Ee("MISSING_OR_INVALID",`approve() relayProtocol: ${o}`);throw new Error(v)}$n(c)||this.validateSessionProps(c,"sessionProperties")},this.isValidReject=async n=>{if(!kn(n)){const{message:o}=Ee("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(o)}const{id:r,reason:i}=n;if(await this.isValidProposalId(r),!Ub(i)){const{message:o}=Ee("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidSessionSettleRequest=n=>{if(!kn(n)){const{message:f}=Ee("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(f)}const{relay:r,controller:i,namespaces:o,expiry:c}=n;if(!N1(r)){const{message:f}=Ee("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(f)}const l=Ab(i,"onSessionSettleRequest()");if(l)throw new Error(l.message);const h=Ka(o,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(ai(c)){const{message:f}=Ee("EXPIRED","onSessionSettleRequest()");throw new Error(f)}},this.isValidUpdate=async n=>{if(!kn(n)){const{message:h}=Ee("MISSING_OR_INVALID",`update() params: ${n}`);throw new Error(h)}const{topic:r,namespaces:i}=n;await this.isValidSessionTopic(r);const o=this.client.session.get(r),c=Ka(i,"update()");if(c)throw new Error(c.message);const l=M1(o.requiredNamespaces,i,"update()");if(l)throw new Error(l.message)},this.isValidExtend=async n=>{if(!kn(n)){const{message:i}=Ee("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionTopic(r)},this.isValidRequest=async n=>{if(!kn(n)){const{message:h}=Ee("MISSING_OR_INVALID",`request() params: ${n}`);throw new Error(h)}const{topic:r,request:i,chainId:o,expiry:c}=n;await this.isValidSessionTopic(r);const{namespaces:l}=this.client.session.get(r);if(!L1(l,o)){const{message:h}=Ee("MISSING_OR_INVALID",`request() chainId: ${o}`);throw new Error(h)}if(!Fb(i)){const{message:h}=Ee("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(h)}if(!Hb(l,o,i.method)){const{message:h}=Ee("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(h)}if(c&&!Vb(c,ch)){const{message:h}=Ee("MISSING_OR_INVALID",`request() expiry: ${c}. Expiry must be a number (in seconds) between ${ch.min} and ${ch.max}`);throw new Error(h)}},this.isValidRespond=async n=>{if(!kn(n)){const{message:o}=Ee("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(o)}const{topic:r,response:i}=n;if(await this.isValidSessionTopic(r),!Bb(i)){const{message:o}=Ee("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidPing=async n=>{if(!kn(n)){const{message:i}=Ee("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)},this.isValidEmit=async n=>{if(!kn(n)){const{message:l}=Ee("MISSING_OR_INVALID",`emit() params: ${n}`);throw new Error(l)}const{topic:r,event:i,chainId:o}=n;await this.isValidSessionTopic(r);const{namespaces:c}=this.client.session.get(r);if(!L1(c,o)){const{message:l}=Ee("MISSING_OR_INVALID",`emit() chainId: ${o}`);throw new Error(l)}if(!kb(i)){const{message:l}=Ee("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}if(!zb(c,o,i.name)){const{message:l}=Ee("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}},this.isValidDisconnect=async n=>{if(!kn(n)){const{message:i}=Ee("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)},this.getVerifyContext=async(n,r)=>{const i={verified:{verifyUrl:r.verifyUrl||"",validation:"UNKNOWN",origin:r.url||""}};try{const o=await this.client.core.verify.resolve({attestationId:n,verifyUrl:r.verifyUrl});o&&(i.verified.origin=o,i.verified.validation=o===r.url?"VALID":"INVALID")}catch(o){this.client.logger.error(o)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(n,r)=>{Object.values(n).forEach(i=>{if(!mn(i,!1)){const{message:o}=Ee("MISSING_OR_INVALID",`${r} must be in Record<string, string> format. Received: ${JSON.stringify(i)}`);throw new Error(o)}})}}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.client.core.relayer.on(wn.message,async e=>{const{topic:n,message:r}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(r)))return;const i=await this.client.core.crypto.decode(n,r);Xu(i)?(this.client.core.history.set(n,i),this.onRelayEventRequest({topic:n,payload:i})):Bp(i)&&(await this.client.core.history.resolve(i),this.onRelayEventResponse({topic:n,payload:i}))})}registerExpirerEvents(){this.client.core.expirer.on(ir.expired,async e=>{const{topic:n,id:r}=D1(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,Ee("EXPIRED"),!0);n?this.client.session.keys.includes(n)&&(await this.deleteSession(n,!0),this.client.events.emit("session_expire",{topic:n})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}isValidPairingTopic(e){if(!mn(e,!1)){const{message:n}=Ee("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(n)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:n}=Ee("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(n)}if(ai(this.client.core.pairing.pairings.get(e).expiry)){const{message:n}=Ee("EXPIRED",`pairing topic: ${e}`);throw new Error(n)}}async isValidSessionTopic(e){if(!mn(e,!1)){const{message:n}=Ee("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(n)}if(!this.client.session.keys.includes(e)){const{message:n}=Ee("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(n)}if(ai(this.client.session.get(e).expiry)){await this.deleteSession(e);const{message:n}=Ee("EXPIRED",`session topic: ${e}`);throw new Error(n)}}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(mn(e,!1)){const{message:n}=Ee("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(n)}else{const{message:n}=Ee("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(n)}}async isValidProposalId(e){if(!jb(e)){const{message:n}=Ee("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(n)}if(!this.client.proposal.keys.includes(e)){const{message:n}=Ee("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(n)}if(ai(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:n}=Ee("EXPIRED",`proposal id: ${e}`);throw new Error(n)}}}class Z7 extends tc{constructor(e,n){super(e,n,U7,oh),this.core=e,this.logger=n}}class Y7 extends tc{constructor(e,n){super(e,n,F7,oh),this.core=e,this.logger=n}}class J7 extends tc{constructor(e,n){super(e,n,k7,oh,r=>r.id),this.core=e,this.logger=n}}class uh extends S4{constructor(e){super(e),this.protocol=Eg,this.version=xg,this.name=ah.name,this.events=new xn.exports.EventEmitter,this.on=(r,i)=>this.events.on(r,i),this.once=(r,i)=>this.events.once(r,i),this.off=(r,i)=>this.events.off(r,i),this.removeListener=(r,i)=>this.events.removeListener(r,i),this.removeAllListeners=r=>this.events.removeAllListeners(r),this.connect=async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}},this.pair=async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}},this.approve=async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}},this.reject=async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}},this.update=async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}},this.extend=async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}},this.request=async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}},this.respond=async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}},this.ping=async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}},this.emit=async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}},this.find=r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}},this.name=e?.name||ah.name,this.metadata=e?.metadata||nb();const n=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||ah.logger}));this.core=e?.core||new j7(e),this.logger=pt.generateChildLogger(n,this.name),this.session=new Y7(this.core,this.logger),this.proposal=new Z7(this.core,this.logger),this.pendingRequest=new J7(this.core,this.logger),this.engine=new G7(this)}static async init(e){const n=new uh(e);return await n.initialize(),n}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 hh={exports:{}};(function(t,e){var n=typeof self<"u"?self:Lt,r=function(){function o(){this.fetch=!1,this.DOMException=n.DOMException}return o.prototype=n,new o}();(function(o){(function(c){var l={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function h(O){return O&&DataView.prototype.isPrototypeOf(O)}if(l.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],v=ArrayBuffer.isView||function(O){return O&&f.indexOf(Object.prototype.toString.call(O))>-1};function E(O){if(typeof O!="string"&&(O=String(O)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(O))throw new TypeError("Invalid character in header field name");return O.toLowerCase()}function b(O){return typeof O!="string"&&(O=String(O)),O}function C(O){var U={next:function(){var ae=O.shift();return{done:ae===void 0,value:ae}}};return l.iterable&&(U[Symbol.iterator]=function(){return U}),U}function P(O){this.map={},O instanceof P?O.forEach(function(U,ae){this.append(ae,U)},this):Array.isArray(O)?O.forEach(function(U){this.append(U[0],U[1])},this):O&&Object.getOwnPropertyNames(O).forEach(function(U){this.append(U,O[U])},this)}P.prototype.append=function(O,U){O=E(O),U=b(U);var ae=this.map[O];this.map[O]=ae?ae+", "+U:U},P.prototype.delete=function(O){delete this.map[E(O)]},P.prototype.get=function(O){return O=E(O),this.has(O)?this.map[O]:null},P.prototype.has=function(O){return this.map.hasOwnProperty(E(O))},P.prototype.set=function(O,U){this.map[E(O)]=b(U)},P.prototype.forEach=function(O,U){for(var ae in this.map)this.map.hasOwnProperty(ae)&&O.call(U,this.map[ae],ae,this)},P.prototype.keys=function(){var O=[];return this.forEach(function(U,ae){O.push(ae)}),C(O)},P.prototype.values=function(){var O=[];return this.forEach(function(U){O.push(U)}),C(O)},P.prototype.entries=function(){var O=[];return this.forEach(function(U,ae){O.push([ae,U])}),C(O)},l.iterable&&(P.prototype[Symbol.iterator]=P.prototype.entries);function M(O){if(O.bodyUsed)return Promise.reject(new TypeError("Already read"));O.bodyUsed=!0}function k(O){return new Promise(function(U,ae){O.onload=function(){U(O.result)},O.onerror=function(){ae(O.error)}})}function q(O){var U=new FileReader,ae=k(U);return U.readAsArrayBuffer(O),ae}function T(O){var U=new FileReader,ae=k(U);return U.readAsText(O),ae}function L(O){for(var U=new Uint8Array(O),ae=new Array(U.length),le=0;le<U.length;le++)ae[le]=String.fromCharCode(U[le]);return ae.join("")}function A(O){if(O.slice)return O.slice(0);var U=new Uint8Array(O.byteLength);return U.set(new Uint8Array(O)),U.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(O){this._bodyInit=O,O?typeof O=="string"?this._bodyText=O:l.blob&&Blob.prototype.isPrototypeOf(O)?this._bodyBlob=O:l.formData&&FormData.prototype.isPrototypeOf(O)?this._bodyFormData=O:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(O)?this._bodyText=O.toString():l.arrayBuffer&&l.blob&&h(O)?(this._bodyArrayBuffer=A(O.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(O)||v(O))?this._bodyArrayBuffer=A(O):this._bodyText=O=Object.prototype.toString.call(O):this._bodyText="",this.headers.get("content-type")||(typeof O=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):l.searchParams&&URLSearchParams.prototype.isPrototypeOf(O)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var O=M(this);if(O)return O;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?M(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(q)}),this.text=function(){var O=M(this);if(O)return O;if(this._bodyBlob)return T(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(L(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},l.formData&&(this.formData=function(){return this.text().then(J)}),this.json=function(){return this.text().then(JSON.parse)},this}var I=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function d(O){var U=O.toUpperCase();return I.indexOf(U)>-1?U:O}function x(O,U){U=U||{};var ae=U.body;if(O instanceof x){if(O.bodyUsed)throw new TypeError("Already read");this.url=O.url,this.credentials=O.credentials,U.headers||(this.headers=new P(O.headers)),this.method=O.method,this.mode=O.mode,this.signal=O.signal,!ae&&O._bodyInit!=null&&(ae=O._bodyInit,O.bodyUsed=!0)}else this.url=String(O);if(this.credentials=U.credentials||this.credentials||"same-origin",(U.headers||!this.headers)&&(this.headers=new P(U.headers)),this.method=d(U.method||this.method||"GET"),this.mode=U.mode||this.mode||null,this.signal=U.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&ae)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(ae)}x.prototype.clone=function(){return new x(this,{body:this._bodyInit})};function J(O){var U=new FormData;return O.trim().split("&").forEach(function(ae){if(ae){var le=ae.split("="),ne=le.shift().replace(/\+/g," "),re=le.join("=").replace(/\+/g," ");U.append(decodeURIComponent(ne),decodeURIComponent(re))}}),U}function z(O){var U=new P,ae=O.replace(/\r?\n[\t ]+/g," ");return ae.split(/\r?\n/).forEach(function(le){var ne=le.split(":"),re=ne.shift().trim();if(re){var oe=ne.join(":").trim();U.append(re,oe)}}),U}R.call(x.prototype);function ee(O,U){U||(U={}),this.type="default",this.status=U.status===void 0?200:U.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in U?U.statusText:"OK",this.headers=new P(U.headers),this.url=U.url||"",this._initBody(O)}R.call(ee.prototype),ee.prototype.clone=function(){return new ee(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new P(this.headers),url:this.url})},ee.error=function(){var O=new ee(null,{status:0,statusText:""});return O.type="error",O};var de=[301,302,303,307,308];ee.redirect=function(O,U){if(de.indexOf(U)===-1)throw new RangeError("Invalid status code");return new ee(null,{status:U,headers:{location:O}})},c.DOMException=o.DOMException;try{new c.DOMException}catch{c.DOMException=function(U,ae){this.message=U,this.name=ae;var le=Error(U);this.stack=le.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function me(O,U){return new Promise(function(ae,le){var ne=new x(O,U);if(ne.signal&&ne.signal.aborted)return le(new c.DOMException("Aborted","AbortError"));var re=new XMLHttpRequest;function oe(){re.abort()}re.onload=function(){var ie={status:re.status,statusText:re.statusText,headers:z(re.getAllResponseHeaders()||"")};ie.url="responseURL"in re?re.responseURL:ie.headers.get("X-Request-URL");var Se="response"in re?re.response:re.responseText;ae(new ee(Se,ie))},re.onerror=function(){le(new TypeError("Network request failed"))},re.ontimeout=function(){le(new TypeError("Network request failed"))},re.onabort=function(){le(new c.DOMException("Aborted","AbortError"))},re.open(ne.method,ne.url,!0),ne.credentials==="include"?re.withCredentials=!0:ne.credentials==="omit"&&(re.withCredentials=!1),"responseType"in re&&l.blob&&(re.responseType="blob"),ne.headers.forEach(function(ie,Se){re.setRequestHeader(Se,ie)}),ne.signal&&(ne.signal.addEventListener("abort",oe),re.onreadystatechange=function(){re.readyState===4&&ne.signal.removeEventListener("abort",oe)}),re.send(typeof ne._bodyInit>"u"?null:ne._bodyInit)})}return me.polyfill=!0,o.fetch||(o.fetch=me,o.Headers=P,o.Request=x,o.Response=ee),c.Headers=P,c.Request=x,c.Response=ee,c.fetch=me,Object.defineProperty(c,"__esModule",{value:!0}),c})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=r;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})(hh,hh.exports);var Dg=rd(hh.exports);const Ag={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},$g=10;class Fi{constructor(e){if(this.url=e,this.events=new xn.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!jp(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}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,n){this.isAvailable||await this.register();try{const r=Po(e),o=await(await Dg(this.url,Object.assign(Object.assign({},Ag),{body:r}))).json();this.onPayload({data:o})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!jp(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,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"));r()})})}this.url=e,this.registering=!0;try{const n=Po({id:1,jsonrpc:"2.0",method:"test",params:[]});await Dg(e,Object.assign(Object.assign({},Ag),{body:n})),this.onOpen()}catch(n){const r=this.parseError(n);throw this.events.emit("register_error",r),this.onClose(),r}}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 n=typeof e.data=="string"?Bu(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),i=r.message||r.toString(),o=Qa(e,i);this.events.emit("payload",o)}parseError(e,n=this.url){return Pp(e,n,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>$g&&this.events.setMaxListeners($g)}}const Pg="error",X7="wss://relay.walletconnect.com",Q7="wc",ex="universal_provider",Tg=`${Q7}@${2}:${ex}:`,tx="https://rpc.walletconnect.com/v1",ui={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Bo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},fh={exports:{}};/**
85
+ ***************************************************************************** */var Ku=function(t,e){return Ku=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},Ku(t,e)};function N_(t,e){Ku(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var Gu=function(){return Gu=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},Gu.apply(this,arguments)};function L_(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function M_(t,e,n,r){var i=arguments.length,o=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,n,r);else for(var l=t.length-1;l>=0;l--)(c=t[l])&&(o=(i<3?c(o):i>3?c(e,n,o):c(e,n))||o);return i>3&&o&&Object.defineProperty(e,n,o),o}function j_(t,e){return function(n,r){e(n,r,t)}}function U_(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function F_(t,e,n,r){function i(o){return o instanceof n?o:new n(function(c){c(o)})}return new(n||(n=Promise))(function(o,c){function l(v){try{f(r.next(v))}catch(E){c(E)}}function h(v){try{f(r.throw(v))}catch(E){c(E)}}function f(v){v.done?o(v.value):i(v.value).then(l,h)}f((r=r.apply(t,e||[])).next())})}function B_(t,e){var n={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,i,o,c;return c={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(c[Symbol.iterator]=function(){return this}),c;function l(f){return function(v){return h([f,v])}}function h(f){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(o=f[0]&2?i.return:f[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,f[1])).done)return o;switch(i=0,o&&(f=[f[0]&2,o.value]),f[0]){case 0:case 1:o=f;break;case 4:return n.label++,{value:f[1],done:!1};case 5:n.label++,i=f[1],f=[0];continue;case 7:f=n.ops.pop(),n.trys.pop();continue;default:if(o=n.trys,!(o=o.length>0&&o[o.length-1])&&(f[0]===6||f[0]===2)){n=0;continue}if(f[0]===3&&(!o||f[1]>o[0]&&f[1]<o[3])){n.label=f[1];break}if(f[0]===6&&n.label<o[1]){n.label=o[1],o=f;break}if(o&&n.label<o[2]){n.label=o[2],n.ops.push(f);break}o[2]&&n.ops.pop(),n.trys.pop();continue}f=e.call(t,n)}catch(v){f=[6,v],i=0}finally{r=o=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}}function k_(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function H_(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function Zu(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Rp(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,o=[],c;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(l){c={error:l}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(c)throw c.error}}return o}function z_(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Rp(arguments[e]));return t}function W_(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),i=0,e=0;e<n;e++)for(var o=arguments[e],c=0,l=o.length;c<l;c++,i++)r[i]=o[c];return r}function No(t){return this instanceof No?(this.v=t,this):new No(t)}function q_(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,o=[];return i={},c("next"),c("throw"),c("return"),i[Symbol.asyncIterator]=function(){return this},i;function c(b){r[b]&&(i[b]=function(C){return new Promise(function(P,M){o.push([b,C,P,M])>1||l(b,C)})})}function l(b,C){try{h(r[b](C))}catch(P){E(o[0][3],P)}}function h(b){b.value instanceof No?Promise.resolve(b.value.v).then(f,v):E(o[0][2],b)}function f(b){l("next",b)}function v(b){l("throw",b)}function E(b,C){b(C),o.shift(),o.length&&l(o[0][0],o[0][1])}}function V_(t){var e,n;return e={},r("next"),r("throw",function(i){throw i}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(i,o){e[i]=t[i]?function(c){return(n=!n)?{value:No(t[i](c)),done:i==="return"}:o?o(c):c}:o}}function K_(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof Zu=="function"?Zu(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(o){n[o]=t[o]&&function(c){return new Promise(function(l,h){c=t[o](c),i(l,h,c.done,c.value)})}}function i(o,c,l,h){Promise.resolve(h).then(function(f){o({value:f,done:l})},c)}}function G_(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function Z_(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function Y_(t){return t&&t.__esModule?t:{default:t}}function J_(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function X_(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}var Q_=Object.freeze({__proto__:null,__extends:N_,get __assign(){return Gu},__rest:L_,__decorate:M_,__param:j_,__metadata:U_,__awaiter:F_,__generator:B_,__createBinding:k_,__exportStar:H_,__values:Zu,__read:Rp,__spread:z_,__spreadArrays:W_,__await:No,__asyncGenerator:q_,__asyncDelegator:V_,__asyncValues:K_,__makeTemplateObject:G_,__importStar:Z_,__importDefault:Y_,__classPrivateFieldGet:J_,__classPrivateFieldSet:X_}),e8=si(Q_),Hr={},Np;function t8(){if(Np)return Hr;Np=1,Object.defineProperty(Hr,"__esModule",{value:!0}),Hr.isBrowserCryptoAvailable=Hr.getSubtleCrypto=Hr.getBrowerCrypto=void 0;function t(){return Lt?.crypto||Lt?.msCrypto||{}}Hr.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}Hr.getSubtleCrypto=e;function n(){return!!t()&&!!e()}return Hr.isBrowserCryptoAvailable=n,Hr}var zr={},Lp;function n8(){if(Lp)return zr;Lp=1,Object.defineProperty(zr,"__esModule",{value:!0}),zr.isBrowser=zr.isNode=zr.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}zr.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}zr.isNode=e;function n(){return!t()&&!e()}return zr.isBrowser=n,zr}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=e8;e.__exportStar(t8(),t),e.__exportStar(n8(),t)})(Tp);function r8(t=3){const e=Date.now()*Math.pow(10,t),n=Math.floor(Math.random()*Math.pow(10,t));return e+n}function Yu(t,e,n){return{id:n||r8(),jsonrpc:"2.0",method:t,params:e}}function Ju(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Qa(t,e,n){return{id:t,jsonrpc:"2.0",error:i8(e,n)}}function i8(t,e){return typeof t>"u"?$p(Dp):(typeof t=="string"&&(t=Object.assign(Object.assign({},$p(Vu)),{message:t})),typeof e<"u"&&(t.data=e),T_(t.code)&&(t=R_(t.code)),t)}const s8="^https?:",o8="^wss?:";function a8(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Mp(t,e){const n=a8(t);return typeof n>"u"?!1:new RegExp(e).test(n)}function jp(t){return Mp(t,s8)}function Up(t){return Mp(t,o8)}function c8(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Fp(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Xu(t){return Fp(t)&&"method"in t}function Bp(t){return Fp(t)&&(Wr(t)||Or(t))}function Wr(t){return"result"in t}function Or(t){return"error"in t}const kp=10,l8=()=>typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:require("ws"),u8=()=>typeof window<"u",h8=l8();class f8{constructor(e){if(this.url=e,this.events=new xn.exports.EventEmitter,this.registering=!1,!Up(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,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,n)=>{if(typeof this.socket>"u"){n(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),e()},this.socket.close()})}async send(e,n){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Po(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Up(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,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"));r(this.socket)})})}return this.url=e,this.registering=!0,new Promise((n,r)=>{const i=Tp.isReactNative()?void 0:{rejectUnauthorized:!c8(e)},o=new h8(e,[],i);u8()?o.onerror=c=>{const l=c;r(this.emitError(l.error))}:o.on("error",c=>{r(this.emitError(c))}),o.onopen=()=>{this.onOpen(o),n(o)}})}onOpen(e){e.onmessage=n=>this.onPayload(n),e.onclose=n=>this.onClose(n),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 n=typeof e.data=="string"?Bu(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),i=r.message||r.toString(),o=Qa(e,i);this.events.emit("payload",o)}parseError(e,n=this.url){return Pp(e,n,"WS")}resetMaxListeners(){this.events.getMaxListeners()>kp&&this.events.setMaxListeners(kp)}emitError(e){const n=this.parseError(new Error(e?.message||`WebSocket connection failed for URL: ${this.url}`));return this.events.emit("register_error",n),n}}var Qu={exports:{}};(function(t,e){var n=200,r="__lodash_hash_undefined__",i=1,o=2,c=9007199254740991,l="[object Arguments]",h="[object Array]",f="[object AsyncFunction]",v="[object Boolean]",E="[object Date]",b="[object Error]",C="[object Function]",P="[object GeneratorFunction]",M="[object Map]",k="[object Number]",q="[object Null]",T="[object Object]",L="[object Promise]",A="[object Proxy]",R="[object RegExp]",I="[object Set]",d="[object String]",x="[object Symbol]",J="[object Undefined]",z="[object WeakMap]",ee="[object ArrayBuffer]",de="[object DataView]",me="[object Float32Array]",O="[object Float64Array]",U="[object Int8Array]",ae="[object Int16Array]",le="[object Int32Array]",ne="[object Uint8Array]",re="[object Uint8ClampedArray]",oe="[object Uint16Array]",ie="[object Uint32Array]",Se=/[\\^$.*+?()[\]{}|]/g,ge=/^\[object .+?Constructor\]$/,Ne=/^(?:0|[1-9]\d*)$/,be={};be[me]=be[O]=be[U]=be[ae]=be[le]=be[ne]=be[re]=be[oe]=be[ie]=!0,be[l]=be[h]=be[ee]=be[v]=be[de]=be[E]=be[b]=be[C]=be[M]=be[k]=be[T]=be[R]=be[I]=be[d]=be[z]=!1;var Ae=typeof Lt=="object"&&Lt&&Lt.Object===Object&&Lt,X=typeof self=="object"&&self&&self.Object===Object&&self,Y=Ae||X||Function("return this")(),W=e&&!e.nodeType&&e,w=W&&!0&&t&&!t.nodeType&&t,F=w&&w.exports===W,we=F&&Ae.process,ve=function(){try{return we&&we.binding&&we.binding("util")}catch{}}(),Pe=ve&&ve.isTypedArray;function tt(N,V){for(var fe=-1,Ce=N==null?0:N.length,St=0,Je=[];++fe<Ce;){var Rt=N[fe];V(Rt,fe,N)&&(Je[St++]=Rt)}return Je}function ot(N,V){for(var fe=-1,Ce=V.length,St=N.length;++fe<Ce;)N[St+fe]=V[fe];return N}function qe(N,V){for(var fe=-1,Ce=N==null?0:N.length;++fe<Ce;)if(V(N[fe],fe,N))return!0;return!1}function $t(N,V){for(var fe=-1,Ce=Array(N);++fe<N;)Ce[fe]=V(fe);return Ce}function Pt(N){return function(V){return N(V)}}function Ye(N,V){return N.has(V)}function Me(N,V){return N?.[V]}function Le(N){var V=-1,fe=Array(N.size);return N.forEach(function(Ce,St){fe[++V]=[St,Ce]}),fe}function ze(N,V){return function(fe){return N(V(fe))}}function et(N){var V=-1,fe=Array(N.size);return N.forEach(function(Ce){fe[++V]=Ce}),fe}var Te=Array.prototype,Ve=Function.prototype,_=Object.prototype,p=Y["__core-js_shared__"],m=Ve.toString,$=_.hasOwnProperty,B=function(){var N=/[^.]+$/.exec(p&&p.keys&&p.keys.IE_PROTO||"");return N?"Symbol(src)_1."+N:""}(),G=_.toString,Q=RegExp("^"+m.call($).replace(Se,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),xe=F?Y.Buffer:void 0,De=Y.Symbol,it=Y.Uint8Array,ut=_.propertyIsEnumerable,ct=Te.splice,Ln=De?De.toStringTag:void 0,Kr=Object.getOwnPropertySymbols,vi=xe?xe.isBuffer:void 0,rs=ze(Object.keys,Object),zt=Xn(Y,"DataView"),jt=Xn(Y,"Map"),Wt=Xn(Y,"Promise"),qt=Xn(Y,"Set"),Bt=Xn(Y,"WeakMap"),Ut=Xn(Object,"create"),nn=Zr(zt),rn=Zr(jt),Vt=Zr(Wt),sn=Zr(qt),Kt=Zr(Bt),Jt=De?De.prototype:void 0,Gt=Jt?Jt.valueOf:void 0;function Tt(N){var V=-1,fe=N==null?0:N.length;for(this.clear();++V<fe;){var Ce=N[V];this.set(Ce[0],Ce[1])}}function on(){this.__data__=Ut?Ut(null):{},this.size=0}function an(N){var V=this.has(N)&&delete this.__data__[N];return this.size-=V?1:0,V}function Rf(N){var V=this.__data__;if(Ut){var fe=V[N];return fe===r?void 0:fe}return $.call(V,N)?V[N]:void 0}function Nf(N){var V=this.__data__;return Ut?V[N]!==void 0:$.call(V,N)}function Lf(N,V){var fe=this.__data__;return this.size+=this.has(N)?0:1,fe[N]=Ut&&V===void 0?r:V,this}Tt.prototype.clear=on,Tt.prototype.delete=an,Tt.prototype.get=Rf,Tt.prototype.has=Nf,Tt.prototype.set=Lf;function lr(N){var V=-1,fe=N==null?0:N.length;for(this.clear();++V<fe;){var Ce=N[V];this.set(Ce[0],Ce[1])}}function Mf(){this.__data__=[],this.size=0}function jf(N){var V=this.__data__,fe=is(V,N);if(fe<0)return!1;var Ce=V.length-1;return fe==Ce?V.pop():ct.call(V,fe,1),--this.size,!0}function Uf(N){var V=this.__data__,fe=is(V,N);return fe<0?void 0:V[fe][1]}function Ff(N){return is(this.__data__,N)>-1}function Bf(N,V){var fe=this.__data__,Ce=is(fe,N);return Ce<0?(++this.size,fe.push([N,V])):fe[Ce][1]=V,this}lr.prototype.clear=Mf,lr.prototype.delete=jf,lr.prototype.get=Uf,lr.prototype.has=Ff,lr.prototype.set=Bf;function Gr(N){var V=-1,fe=N==null?0:N.length;for(this.clear();++V<fe;){var Ce=N[V];this.set(Ce[0],Ce[1])}}function Ks(){this.size=0,this.__data__={hash:new Tt,map:new(jt||lr),string:new Tt}}function kf(N){var V=yi(this,N).delete(N);return this.size-=V?1:0,V}function Gs(N){return yi(this,N).get(N)}function Hf(N){return yi(this,N).has(N)}function zf(N,V){var fe=yi(this,N),Ce=fe.size;return fe.set(N,V),this.size+=fe.size==Ce?0:1,this}Gr.prototype.clear=Ks,Gr.prototype.delete=kf,Gr.prototype.get=Gs,Gr.prototype.has=Hf,Gr.prototype.set=zf;function Zs(N){var V=-1,fe=N==null?0:N.length;for(this.__data__=new Gr;++V<fe;)this.add(N[V])}function zc(N){return this.__data__.set(N,r),this}function Wc(N){return this.__data__.has(N)}Zs.prototype.add=Zs.prototype.push=zc,Zs.prototype.has=Wc;function br(N){var V=this.__data__=new lr(N);this.size=V.size}function Wf(){this.__data__=new lr,this.size=0}function qf(N){var V=this.__data__,fe=V.delete(N);return this.size=V.size,fe}function Vf(N){return this.__data__.get(N)}function Kf(N){return this.__data__.has(N)}function qc(N,V){var fe=this.__data__;if(fe instanceof lr){var Ce=fe.__data__;if(!jt||Ce.length<n-1)return Ce.push([N,V]),this.size=++fe.size,this;fe=this.__data__=new Gr(Ce)}return fe.set(N,V),this.size=fe.size,this}br.prototype.clear=Wf,br.prototype.delete=qf,br.prototype.get=Vf,br.prototype.has=Kf,br.prototype.set=qc;function Vc(N,V){var fe=Xs(N),Ce=!fe&&il(N),St=!fe&&!Ce&&ga(N),Je=!fe&&!Ce&&!St&&al(N),Rt=fe||Ce||St||Je,cn=Rt?$t(N.length,String):[],gt=cn.length;for(var Ot in N)(V||$.call(N,Ot))&&!(Rt&&(Ot=="length"||St&&(Ot=="offset"||Ot=="parent")||Je&&(Ot=="buffer"||Ot=="byteLength"||Ot=="byteOffset")||Qc(Ot,gt)))&&cn.push(Ot);return cn}function is(N,V){for(var fe=N.length;fe--;)if(rl(N[fe][0],V))return fe;return-1}function da(N,V,fe){var Ce=V(N);return Xs(N)?Ce:ot(Ce,fe(N))}function ss(N){return N==null?N===void 0?J:q:Ln&&Ln in Object(N)?Jc(N):Yf(N)}function pa(N){return as(N)&&ss(N)==l}function os(N,V,fe,Ce,St){return N===V?!0:N==null||V==null||!as(N)&&!as(V)?N!==N&&V!==V:Kc(N,V,fe,Ce,os,St)}function Kc(N,V,fe,Ce,St,Je){var Rt=Xs(N),cn=Xs(V),gt=Rt?h:Nr(N),Ot=cn?h:Nr(V);gt=gt==l?T:gt,Ot=Ot==l?T:Ot;var Xt=gt==T,Wn=Ot==T,ln=gt==Ot;if(ln&&ga(N)){if(!ga(V))return!1;Rt=!0,Xt=!1}if(ln&&!Xt)return Je||(Je=new br),Rt||al(N)?Ys(N,V,fe,Ce,St,Je):Zf(N,V,gt,fe,Ce,St,Je);if(!(fe&i)){var Nt=Xt&&$.call(N,"__wrapped__"),Mn=Wn&&$.call(V,"__wrapped__");if(Nt||Mn){var _r=Nt?N.value():N,ur=Mn?V.value():V;return Je||(Je=new br),St(_r,ur,fe,Ce,Je)}}return ln?(Je||(Je=new br),Yc(N,V,fe,Ce,St,Je)):!1}function Gf(N){if(!ol(N)||tl(N))return!1;var V=Qs(N)?Q:ge;return V.test(Zr(N))}function Gc(N){return as(N)&&sl(N.length)&&!!be[ss(N)]}function Zc(N){if(!nl(N))return rs(N);var V=[];for(var fe in Object(N))$.call(N,fe)&&fe!="constructor"&&V.push(fe);return V}function Ys(N,V,fe,Ce,St,Je){var Rt=fe&i,cn=N.length,gt=V.length;if(cn!=gt&&!(Rt&&gt>cn))return!1;var Ot=Je.get(N);if(Ot&&Je.get(V))return Ot==V;var Xt=-1,Wn=!0,ln=fe&o?new Zs:void 0;for(Je.set(N,V),Je.set(V,N);++Xt<cn;){var Nt=N[Xt],Mn=V[Xt];if(Ce)var _r=Rt?Ce(Mn,Nt,Xt,V,N,Je):Ce(Nt,Mn,Xt,N,V,Je);if(_r!==void 0){if(_r)continue;Wn=!1;break}if(ln){if(!qe(V,function(ur,Lr){if(!Ye(ln,Lr)&&(Nt===ur||St(Nt,ur,fe,Ce,Je)))return ln.push(Lr)})){Wn=!1;break}}else if(!(Nt===Mn||St(Nt,Mn,fe,Ce,Je))){Wn=!1;break}}return Je.delete(N),Je.delete(V),Wn}function Zf(N,V,fe,Ce,St,Je,Rt){switch(fe){case de:if(N.byteLength!=V.byteLength||N.byteOffset!=V.byteOffset)return!1;N=N.buffer,V=V.buffer;case ee:return!(N.byteLength!=V.byteLength||!Je(new it(N),new it(V)));case v:case E:case k:return rl(+N,+V);case b:return N.name==V.name&&N.message==V.message;case R:case d:return N==V+"";case M:var cn=Le;case I:var gt=Ce&i;if(cn||(cn=et),N.size!=V.size&&!gt)return!1;var Ot=Rt.get(N);if(Ot)return Ot==V;Ce|=o,Rt.set(N,V);var Xt=Ys(cn(N),cn(V),Ce,St,Je,Rt);return Rt.delete(N),Xt;case x:if(Gt)return Gt.call(N)==Gt.call(V)}return!1}function Yc(N,V,fe,Ce,St,Je){var Rt=fe&i,cn=Js(N),gt=cn.length,Ot=Js(V),Xt=Ot.length;if(gt!=Xt&&!Rt)return!1;for(var Wn=gt;Wn--;){var ln=cn[Wn];if(!(Rt?ln in V:$.call(V,ln)))return!1}var Nt=Je.get(N);if(Nt&&Je.get(V))return Nt==V;var Mn=!0;Je.set(N,V),Je.set(V,N);for(var _r=Rt;++Wn<gt;){ln=cn[Wn];var ur=N[ln],Lr=V[ln];if(Ce)var ma=Rt?Ce(Lr,ur,ln,V,N,Je):Ce(ur,Lr,ln,N,V,Je);if(!(ma===void 0?ur===Lr||St(ur,Lr,fe,Ce,Je):ma)){Mn=!1;break}_r||(_r=ln=="constructor")}if(Mn&&!_r){var cs=N.constructor,vn=V.constructor;cs!=vn&&"constructor"in N&&"constructor"in V&&!(typeof cs=="function"&&cs instanceof cs&&typeof vn=="function"&&vn instanceof vn)&&(Mn=!1)}return Je.delete(N),Je.delete(V),Mn}function Js(N){return da(N,Qf,Xc)}function yi(N,V){var fe=N.__data__;return el(V)?fe[typeof V=="string"?"string":"hash"]:fe.map}function Xn(N,V){var fe=Me(N,V);return Gf(fe)?fe:void 0}function Jc(N){var V=$.call(N,Ln),fe=N[Ln];try{N[Ln]=void 0;var Ce=!0}catch{}var St=G.call(N);return Ce&&(V?N[Ln]=fe:delete N[Ln]),St}var Xc=Kr?function(N){return N==null?[]:(N=Object(N),tt(Kr(N),function(V){return ut.call(N,V)}))}:It,Nr=ss;(zt&&Nr(new zt(new ArrayBuffer(1)))!=de||jt&&Nr(new jt)!=M||Wt&&Nr(Wt.resolve())!=L||qt&&Nr(new qt)!=I||Bt&&Nr(new Bt)!=z)&&(Nr=function(N){var V=ss(N),fe=V==T?N.constructor:void 0,Ce=fe?Zr(fe):"";if(Ce)switch(Ce){case nn:return de;case rn:return M;case Vt:return L;case sn:return I;case Kt:return z}return V});function Qc(N,V){return V=V??c,!!V&&(typeof N=="number"||Ne.test(N))&&N>-1&&N%1==0&&N<V}function el(N){var V=typeof N;return V=="string"||V=="number"||V=="symbol"||V=="boolean"?N!=="__proto__":N===null}function tl(N){return!!B&&B in N}function nl(N){var V=N&&N.constructor,fe=typeof V=="function"&&V.prototype||_;return N===fe}function Yf(N){return G.call(N)}function Zr(N){if(N!=null){try{return m.call(N)}catch{}try{return N+""}catch{}}return""}function rl(N,V){return N===V||N!==N&&V!==V}var il=pa(function(){return arguments}())?pa:function(N){return as(N)&&$.call(N,"callee")&&!ut.call(N,"callee")},Xs=Array.isArray;function Jf(N){return N!=null&&sl(N.length)&&!Qs(N)}var ga=vi||Ct;function Xf(N,V){return os(N,V)}function Qs(N){if(!ol(N))return!1;var V=ss(N);return V==C||V==P||V==f||V==A}function sl(N){return typeof N=="number"&&N>-1&&N%1==0&&N<=c}function ol(N){var V=typeof N;return N!=null&&(V=="object"||V=="function")}function as(N){return N!=null&&typeof N=="object"}var al=Pe?Pt(Pe):Gc;function Qf(N){return Jf(N)?Vc(N):Zc(N)}function It(){return[]}function Ct(){return!1}t.exports=Xf})(Qu,Qu.exports);var d8=Qu.exports,p8=Object.defineProperty,Hp=Object.getOwnPropertySymbols,g8=Object.prototype.hasOwnProperty,m8=Object.prototype.propertyIsEnumerable,zp=(t,e,n)=>e in t?p8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Tn=(t,e)=>{for(var n in e||(e={}))g8.call(e,n)&&zp(t,n,e[n]);if(Hp)for(var n of Hp(e))m8.call(e,n)&&zp(t,n,e[n]);return t};function w8(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),c=o.charCodeAt(0);if(n[c]!==255)throw new TypeError(o+" is ambiguous");n[c]=i}var l=t.length,h=t.charAt(0),f=Math.log(l)/Math.log(256),v=Math.log(256)/Math.log(l);function E(P){if(P instanceof Uint8Array||(ArrayBuffer.isView(P)?P=new Uint8Array(P.buffer,P.byteOffset,P.byteLength):Array.isArray(P)&&(P=Uint8Array.from(P))),!(P instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(P.length===0)return"";for(var M=0,k=0,q=0,T=P.length;q!==T&&P[q]===0;)q++,M++;for(var L=(T-q)*v+1>>>0,A=new Uint8Array(L);q!==T;){for(var R=P[q],I=0,d=L-1;(R!==0||I<k)&&d!==-1;d--,I++)R+=256*A[d]>>>0,A[d]=R%l>>>0,R=R/l>>>0;if(R!==0)throw new Error("Non-zero carry");k=I,q++}for(var x=L-k;x!==L&&A[x]===0;)x++;for(var J=h.repeat(M);x<L;++x)J+=t.charAt(A[x]);return J}function b(P){if(typeof P!="string")throw new TypeError("Expected String");if(P.length===0)return new Uint8Array;var M=0;if(P[M]!==" "){for(var k=0,q=0;P[M]===h;)k++,M++;for(var T=(P.length-M)*f+1>>>0,L=new Uint8Array(T);P[M];){var A=n[P.charCodeAt(M)];if(A===255)return;for(var R=0,I=T-1;(A!==0||R<q)&&I!==-1;I--,R++)A+=l*L[I]>>>0,L[I]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");q=R,M++}if(P[M]!==" "){for(var d=T-q;d!==T&&L[d]===0;)d++;for(var x=new Uint8Array(k+(T-d)),J=k;d!==T;)x[J++]=L[d++];return x}}}function C(P){var M=b(P);if(M)return M;throw new Error(`Non-${e} character`)}return{encode:E,decodeUnsafe:b,decode:C}}var v8=w8,y8=v8;const Wp=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")},b8=t=>new TextEncoder().encode(t),_8=t=>new TextDecoder().decode(t);class E8{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class x8{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}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 qp(this,e)}}class C8{constructor(e){this.decoders=e}or(e){return qp(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const qp=(t,e)=>new C8(Tn(Tn({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class I8{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new E8(e,n,r),this.decoder=new x8(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ec=({name:t,prefix:e,encode:n,decode:r})=>new I8(t,e,n,r),Lo=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=y8(n,e);return ec({prefix:t,name:e,encode:r,decode:o=>Wp(i(o))})},S8=(t,e,n,r)=>{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*n/8|0);let l=0,h=0,f=0;for(let v=0;v<o;++v){const E=i[t[v]];if(E===void 0)throw new SyntaxError(`Non-${r} character`);h=h<<n|E,l+=n,l>=8&&(l-=8,c[f++]=255&h>>l)}if(l>=n||255&h<<8-l)throw new SyntaxError("Unexpected end of data");return c},O8=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let o="",c=0,l=0;for(let h=0;h<t.length;++h)for(l=l<<8|t[h],c+=8;c>n;)c-=n,o+=e[i&l>>c];if(c&&(o+=e[i&l<<n-c]),r)for(;o.length*n&7;)o+="=";return o},_n=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>ec({prefix:e,name:t,encode(i){return O8(i,r,n)},decode(i){return S8(i,r,n,t)}}),D8=ec({prefix:"\0",name:"identity",encode:t=>_8(t),decode:t=>b8(t)});var A8=Object.freeze({__proto__:null,identity:D8});const $8=_n({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var P8=Object.freeze({__proto__:null,base2:$8});const T8=_n({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var R8=Object.freeze({__proto__:null,base8:T8});const N8=Lo({prefix:"9",name:"base10",alphabet:"0123456789"});var L8=Object.freeze({__proto__:null,base10:N8});const M8=_n({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),j8=_n({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var U8=Object.freeze({__proto__:null,base16:M8,base16upper:j8});const F8=_n({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),B8=_n({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),k8=_n({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),H8=_n({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),z8=_n({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),W8=_n({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),q8=_n({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),V8=_n({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),K8=_n({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var G8=Object.freeze({__proto__:null,base32:F8,base32upper:B8,base32pad:k8,base32padupper:H8,base32hex:z8,base32hexupper:W8,base32hexpad:q8,base32hexpadupper:V8,base32z:K8});const Z8=Lo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Y8=Lo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var J8=Object.freeze({__proto__:null,base36:Z8,base36upper:Y8});const X8=Lo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Q8=Lo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var eE=Object.freeze({__proto__:null,base58btc:X8,base58flickr:Q8});const tE=_n({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),nE=_n({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),rE=_n({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),iE=_n({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var sE=Object.freeze({__proto__:null,base64:tE,base64pad:nE,base64url:rE,base64urlpad:iE});const Vp=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}"),oE=Vp.reduce((t,e,n)=>(t[n]=e,t),[]),aE=Vp.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function cE(t){return t.reduce((e,n)=>(e+=oE[n],e),"")}function lE(t){const e=[];for(const n of t){const r=aE[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const uE=ec({prefix:"\u{1F680}",name:"base256emoji",encode:cE,decode:lE});var hE=Object.freeze({__proto__:null,base256emoji:uE}),fE=Gp,Kp=128,dE=127,pE=~dE,gE=Math.pow(2,31);function Gp(t,e,n){e=e||[],n=n||0;for(var r=n;t>=gE;)e[n++]=t&255|Kp,t/=128;for(;t&pE;)e[n++]=t&255|Kp,t>>>=7;return e[n]=t|0,Gp.bytes=n-r+1,e}var mE=eh,wE=128,Zp=127;function eh(t,r){var n=0,r=r||0,i=0,o=r,c,l=t.length;do{if(o>=l)throw eh.bytes=0,new RangeError("Could not decode varint");c=t[o++],n+=i<28?(c&Zp)<<i:(c&Zp)*Math.pow(2,i),i+=7}while(c>=wE);return eh.bytes=o-r,n}var vE=Math.pow(2,7),yE=Math.pow(2,14),bE=Math.pow(2,21),_E=Math.pow(2,28),EE=Math.pow(2,35),xE=Math.pow(2,42),CE=Math.pow(2,49),IE=Math.pow(2,56),SE=Math.pow(2,63),OE=function(t){return t<vE?1:t<yE?2:t<bE?3:t<_E?4:t<EE?5:t<xE?6:t<CE?7:t<IE?8:t<SE?9:10},DE={encode:fE,decode:mE,encodingLength:OE},Yp=DE;const Jp=(t,e,n=0)=>(Yp.encode(t,e,n),e),Xp=t=>Yp.encodingLength(t),th=(t,e)=>{const n=e.byteLength,r=Xp(t),i=r+Xp(n),o=new Uint8Array(i+n);return Jp(t,o,0),Jp(n,o,r),o.set(e,i),new AE(t,n,e,o)};class AE{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const Qp=({name:t,code:e,encode:n})=>new $E(t,e,n);class $E{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?th(this.code,n):n.then(r=>th(this.code,r))}else throw Error("Unknown type, must be binary type")}}const eg=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),PE=Qp({name:"sha2-256",code:18,encode:eg("SHA-256")}),TE=Qp({name:"sha2-512",code:19,encode:eg("SHA-512")});var RE=Object.freeze({__proto__:null,sha256:PE,sha512:TE});const tg=0,NE="identity",ng=Wp;var LE=Object.freeze({__proto__:null,identity:{code:tg,name:NE,encode:ng,digest:t=>th(tg,ng(t))}});new TextEncoder,new TextDecoder;const rg=Tn(Tn(Tn(Tn(Tn(Tn(Tn(Tn(Tn(Tn({},A8),P8),R8),L8),U8),G8),J8),eE),sE),hE);Tn(Tn({},RE),LE);function ME(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function ig(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const sg=ig("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),nh=ig("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=ME(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),jE=Tn({utf8:sg,"utf-8":sg,hex:rg.base16,latin1:nh,ascii:nh,binary:nh},rg);function UE(t,e="utf8"){const n=jE[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):n.decoder.decode(`${n.prefix}${t}`)}const og="wc",FE=2,rh="core",li=`${og}@${2}:${rh}:`,BE={name:rh,logger:"error"},kE={database:":memory:"},HE="crypto",ag="client_ed25519_seed",zE=Ue.ONE_DAY,WE="keychain",qE="0.3",VE="messages",KE="0.3",GE=Ue.SIX_HOURS,ZE="publisher",cg="irn",YE="error",lg="wss://relay.walletconnect.com",JE="relayer",wn={message:"relayer_message",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},XE="_subscription",Mo={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},QE=Ue.ONE_SECOND/2,e7="2.7.1",t7="0.3",Dr={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},n7="subscription",r7="0.3",i7=Ue.FIVE_SECONDS*1e3,s7="pairing",o7="0.3",jo={wc_pairingDelete:{req:{ttl:Ue.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:Ue.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:Ue.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:Ue.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:Ue.ONE_DAY,prompt:!1,tag:0},res:{ttl:Ue.ONE_DAY,prompt:!1,tag:0}}},Ar={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},a7="history",c7="0.3",l7="expirer",ir={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},u7="0.3",ug="verify-api",hg="https://verify.walletconnect.com";class h7{constructor(e,n){this.core=e,this.logger=n,this.keychain=new Map,this.name=WE,this.version=qE,this.initialized=!1,this.storagePrefix=li,this.init=async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}},this.has=r=>(this.isInitialized(),this.keychain.has(r)),this.set=async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()},this.get=r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:o}=Ee("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(o)}return i},this.del=async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()},this.core=e,this.logger=pt.generateChildLogger(n,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,I1(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?S1(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class f7{constructor(e,n,r){this.core=e,this.logger=n,this.name=HE,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=hp(i);return up(o.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const i=H5();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const o=await this.getClientSeed(),c=hp(o),l=yu();return await z4(l,i,zE,c)},this.generateSharedKey=(i,o,c)=>{this.isInitialized();const l=this.getPrivateKey(i),h=z5(l,o);return this.setSymKey(h,c)},this.setSymKey=async(i,o)=>{this.isInitialized();const c=o||W5(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=v1(c),h=Po(o);if(y1(l)){const b=l.senderPublicKey,C=l.receiverPublicKey;i=await this.generateSharedKey(b,C)}const f=this.getSymKey(i),{type:v,senderPublicKey:E}=l;return V5({type:v,symKey:f,message:h,senderPublicKey:E})},this.decode=async(i,o,c)=>{this.isInitialized();const l=Z5(o,c);if(y1(l)){const v=l.receiverPublicKey,E=l.senderPublicKey;i=await this.generateSharedKey(v,E)}const h=this.getSymKey(i),f=K5({symKey:h,encoded:o});return Bu(f)},this.getPayloadType=i=>{const o=za(i);return bo(o.type)},this.getPayloadSenderPublicKey=i=>{const o=za(i);return o.senderPublicKey?Dn(o.senderPublicKey,An):void 0},this.core=e,this.logger=pt.generateChildLogger(n,this.name),this.keychain=r||new h7(this.core,this.logger)}get context(){return pt.getLoggerContext(this.logger)}async setPrivateKey(e,n){return await this.keychain.set(e,n),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(ag)}catch{e=yu(),await this.keychain.set(ag,e)}return UE(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class d7 extends y4{constructor(e,n){super(e,n),this.logger=e,this.core=n,this.messages=new Map,this.name=VE,this.version=KE,this.initialized=!1,this.storagePrefix=li,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}},this.set=async(r,i)=>{this.isInitialized();const o=Ri(i);let c=this.messages.get(r);return typeof c>"u"&&(c={}),typeof c[o]<"u"||(c[o]=i,this.messages.set(r,c),await this.persist()),o},this.get=r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i},this.has=(r,i)=>{this.isInitialized();const o=this.get(r),c=Ri(i);return typeof o[c]<"u"},this.del=async r=>{this.isInitialized(),this.messages.delete(r),await this.persist()},this.logger=pt.generateChildLogger(e,this.name),this.core=n}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,I1(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?S1(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class p7 extends b4{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,this.events=new xn.exports.EventEmitter,this.name=ZE,this.queue=new Map,this.publishTimeout=1e4,this.publish=async(r,i,o)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:o}});try{const c=o?.ttl||GE,l=xu(o),h=o?.prompt||!1,f=o?.tag||0,v={topic:r,message:i,opts:{ttl:c,relay:l,prompt:h,tag:f}},E=Ri(i);this.queue.set(E,v);try{await await Wa(this.rpcPublish(r,i,c,l,h,f),this.publishTimeout),this.relayer.events.emit(wn.publish,v)}catch{this.logger.debug("Publishing Payload stalled"),this.relayer.events.emit(wn.connection_stalled);return}this.onPublish(E,v),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:o}})}catch(c){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(c),c}},this.on=(r,i)=>{this.events.on(r,i)},this.once=(r,i)=>{this.events.once(r,i)},this.off=(r,i)=>{this.events.off(r,i)},this.removeListener=(r,i)=>{this.events.removeListener(r,i)},this.relayer=e,this.logger=pt.generateChildLogger(n,this.name),this.registerEventListeners()}get context(){return pt.getLoggerContext(this.logger)}rpcPublish(e,n,r,i,o,c){var l,h,f,v;const E={method:qa(i.protocol).publish,params:{topic:e,message:n,ttl:r,prompt:o,tag:c}};return $n((l=E.params)==null?void 0:l.prompt)&&((h=E.params)==null||delete h.prompt),$n((f=E.params)==null?void 0:f.tag)&&((v=E.params)==null||delete v.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:E}),this.relayer.request(E)}onPublish(e,n){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:n,message:r,opts:i}=e;await this.publish(n,r,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(So.HEARTBEAT_EVENTS.pulse,()=>{this.checkQueue()})}}class g7{constructor(){this.map=new Map,this.set=(e,n)=>{const r=this.get(e);this.exists(e,n)||this.map.set(e,[...r,n])},this.get=e=>this.map.get(e)||[],this.exists=(e,n)=>this.get(e).includes(n),this.delete=(e,n)=>{if(typeof n>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,n))return;const i=r.filter(o=>o!==n);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 m7=Object.defineProperty,w7=Object.defineProperties,v7=Object.getOwnPropertyDescriptors,fg=Object.getOwnPropertySymbols,y7=Object.prototype.hasOwnProperty,b7=Object.prototype.propertyIsEnumerable,dg=(t,e,n)=>e in t?m7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Uo=(t,e)=>{for(var n in e||(e={}))y7.call(e,n)&&dg(t,n,e[n]);if(fg)for(var n of fg(e))b7.call(e,n)&&dg(t,n,e[n]);return t},ih=(t,e)=>w7(t,v7(e));class _7 extends x4{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,this.subscriptions=new Map,this.topicMap=new g7,this.events=new xn.exports.EventEmitter,this.name=n7,this.version=r7,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=li,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(r,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}});try{const o=xu(i),c={topic:r,relay:o};this.pending.set(r,c);const l=await this.rpcSubscribe(r,o);return this.onSubscribe(l,c),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}}),l}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}},this.unsubscribe=async(r,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)},this.isSubscribed=async r=>this.topics.includes(r)?!0:await new Promise((i,o)=>{const c=new Ue.Watch;c.start(this.pendingSubscriptionWatchLabel);const l=setInterval(()=>{!this.pending.has(r)&&this.topics.includes(r)&&(clearInterval(l),c.stop(this.pendingSubscriptionWatchLabel),i(!0)),c.elapsed(this.pendingSubscriptionWatchLabel)>=i7&&(clearInterval(l),c.stop(this.pendingSubscriptionWatchLabel),o(!1))},this.pollingInterval)}),this.on=(r,i)=>{this.events.on(r,i)},this.once=(r,i)=>{this.events.once(r,i)},this.off=(r,i)=>{this.events.off(r,i)},this.removeListener=(r,i)=>{this.events.removeListener(r,i)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=pt.generateChildLogger(n,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,n){let r=!1;try{r=this.getSubscription(e).topic===n}catch{}return r}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,n){const r=this.topicMap.get(e);await Promise.all(r.map(async i=>await this.unsubscribeById(e,i,n)))}async unsubscribeById(e,n,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}});try{const i=xu(r);await this.rpcUnsubscribe(e,n,i);const o=Yt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,n,o),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,n){const r={method:qa(n.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await Wa(this.relayer.request(r),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(wn.connection_stalled)}return Ri(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const n=e[0].relay,r={method:qa(n.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{return await await Wa(this.relayer.request(r),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(wn.connection_stalled)}}rpcUnsubscribe(e,n,r){const i={method:qa(r.protocol).unsubscribe,params:{topic:e,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,n){this.setSubscription(e,ih(Uo({},n),{id:e})),this.pending.delete(n.topic)}onBatchSubscribe(e){e.length&&e.forEach(n=>{this.setSubscription(n.id,Uo({},n)),this.pending.delete(n.topic)})}async onUnsubscribe(e,n,r){this.events.removeAllListeners(n),this.hasSubscription(n,e)&&this.deleteSubscription(n,r),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,n){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:n}),this.addSubscription(e,n))}addSubscription(e,n){this.subscriptions.set(e,Uo({},n)),this.topicMap.set(n.topic,e),this.events.emit(Dr.created,n)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const n=this.subscriptions.get(e);if(!n){const{message:r}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}deleteSubscription(e,n){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:n});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(Dr.deleted,ih(Uo({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Dr.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<e;n++){const r=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(Dr.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:n}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(n)}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 n=await this.rpcBatchSubscribe(e);Fr(n)&&this.onBatchSubscribe(n.map((r,i)=>ih(Uo({},e[i]),{id:r})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach(n=>{e.push(n)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(So.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(wn.connect,async()=>{await this.onConnect()}),this.relayer.on(wn.disconnect,()=>{this.onDisconnect()}),this.events.on(Dr.created,async e=>{const n=Dr.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),await this.persist()}),this.events.on(Dr.deleted,async e=>{const n=Dr.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{const n=setInterval(()=>{this.restartInProgress||(clearInterval(n),e())},this.pollingInterval)})}}var E7=Object.defineProperty,pg=Object.getOwnPropertySymbols,x7=Object.prototype.hasOwnProperty,C7=Object.prototype.propertyIsEnumerable,gg=(t,e,n)=>e in t?E7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,I7=(t,e)=>{for(var n in e||(e={}))x7.call(e,n)&&gg(t,n,e[n]);if(pg)for(var n of pg(e))C7.call(e,n)&&gg(t,n,e[n]);return t};class S7 extends _4{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new xn.exports.EventEmitter,this.name=JE,this.transportExplicitlyClosed=!1,this.initialized=!1,this.reconnecting=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],this.request=async n=>{this.logger.debug("Publishing Request Payload");try{return await this.toEstablishConnection(),await this.provider.request(n)}catch(r){throw this.logger.debug("Failed to Publish Request"),this.logger.error(r),r}},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||YE})),this.messages=new d7(this.logger,e.core),this.subscriber=new _7(this,this.logger),this.publisher=new p7(this,this.logger),this.relayUrl=e?.relayUrl||lg,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}get context(){return pt.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,n,r){this.isInitialized(),await this.publisher.publish(e,n,r),await this.recordMessageEvent({topic:e,message:n,publishedAt:Date.now()})}async subscribe(e,n){this.isInitialized();let r="";return await Promise.all([new Promise(i=>{this.subscriber.once(Dr.created,o=>{o.topic===e&&i()})}),new Promise(async i=>{r=await this.subscriber.subscribe(e,n),i()})]),r}async unsubscribe(e,n){this.isInitialized(),await this.subscriber.unsubscribe(e,n)}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async transportClose(){this.transportExplicitlyClosed=!0,this.connected&&(await this.provider.disconnect(),this.events.emit(wn.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(n=>{this.initialized||n(),this.subscriber.once(Dr.resubscribed,()=>{n()})}),await Promise.race([new Promise(async(n,r)=>{await Wa(this.provider.connect(),5e3,"socket stalled").catch(i=>r(i)).then(()=>n()).finally(()=>this.removeListener(wn.transport_closed,this.rejectTransportOpen))}),new Promise(n=>this.once(wn.transport_closed,this.rejectTransportOpen))])])}catch(n){this.logger.error(n);const r=n;if(!this.isConnectionStalled(r.message))throw n;this.events.emit(wn.transport_closed)}finally{this.reconnecting=!1}}}async restartTransport(e){this.transportExplicitlyClosed||(this.relayUrl=e||this.relayUrl,this.connected&&await Promise.all([new Promise(n=>{this.provider.once(Mo.disconnect,()=>{n()})}),this.transportClose()]),await this.createProvider(),await this.transportOpen())}isConnectionStalled(e){return this.staleConnectionErrors.some(n=>e.includes(n))}rejectTransportOpen(){throw new Error("closeTransport called before connection was established")}async createProvider(){const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new ci(new f8(ob({sdkVersion:e7,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:n,message:r}=e;await this.messages.set(n,r)}async shouldIgnoreMessageEvent(e){const{topic:n,message:r}=e;return await this.subscriber.isSubscribed(n)?this.messages.has(n,r):!0}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Xu(e)){if(!e.method.endsWith(XE))return;const n=e.params,{topic:r,message:i,publishedAt:o}=n.data,c={topic:r,message:i,publishedAt:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(I7({type:"event",event:n.id},c)),this.events.emit(n.id,c),await this.acknowledgePayload(e),await this.onMessageEvent(c)}}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(wn.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const n=Ju(e.id,!0);await this.provider.connection.send(n)}registerProviderListeners(){this.provider.on(Mo.payload,e=>this.onProviderPayload(e)),this.provider.on(Mo.connect,()=>{this.events.emit(wn.connect)}),this.provider.on(Mo.disconnect,()=>{this.onProviderDisconnect()}),this.provider.on(Mo.error,e=>{this.logger.error(e),this.events.emit(wn.error,e)})}registerEventListeners(){this.events.on(wn.connection_stalled,async()=>{await this.restartTransport()})}onProviderDisconnect(){this.events.emit(wn.disconnect),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||setTimeout(async()=>{await this.restartTransport()},Ue.toMiliseconds(QE))}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(!this.connected){if(this.connecting)return await new Promise(e=>{const n=setInterval(()=>{this.connected&&(clearInterval(n),e())},this.connectionStatusPollingInterval)});await this.restartTransport()}}}var O7=Object.defineProperty,mg=Object.getOwnPropertySymbols,D7=Object.prototype.hasOwnProperty,A7=Object.prototype.propertyIsEnumerable,wg=(t,e,n)=>e in t?O7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,vg=(t,e)=>{for(var n in e||(e={}))D7.call(e,n)&&wg(t,n,e[n]);if(mg)for(var n of mg(e))A7.call(e,n)&&wg(t,n,e[n]);return t};class tc extends E4{constructor(e,n,r,i=li,o=void 0){super(e,n,r,i),this.core=e,this.logger=n,this.name=r,this.map=new Map,this.version=t7,this.cached=[],this.initialized=!1,this.storagePrefix=li,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(c=>{this.getKey&&c!==null&&!$n(c)?this.map.set(this.getKey(c),c):Ob(c)?this.map.set(c.id,c):Db(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=>d8(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=vg(vg({},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(n,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 n=this.map.get(e);if(!n){const{message:r}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return n}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:n}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}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}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class $7{constructor(e,n){this.core=e,this.logger=n,this.name=s7,this.version=o7,this.events=new xn.exports,this.initialized=!1,this.storagePrefix=li,this.ignoredPayloadTypes=[Ti],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:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]},this.create=async()=>{this.isInitialized();const r=yu(),i=await this.core.crypto.setSymKey(r),o=yr(Ue.FIVE_MINUTES),c={protocol:cg},l={topic:i,expiry:o,relay:c,active:!1},h=wb({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:r,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 r=>{this.isInitialized(),this.isValidPair(r);const{topic:i,symKey:o,relay:c}=gb(r.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=yr(Ue.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),r.activatePairing&&await this.activate({topic:i}),h},this.activate=async({topic:r})=>{this.isInitialized();const i=yr(Ue.THIRTY_DAYS);await this.pairings.update(r,{active:!0,expiry:i}),this.core.expirer.set(r,i)},this.ping=async r=>{this.isInitialized(),await this.isValidPing(r);const{topic:i}=r;if(this.pairings.keys.includes(i)){const o=await this.sendRequest(i,"wc_pairingPing",{}),{done:c,resolve:l,reject:h}=_s();this.events.once(tn("pairing_ping",o),({error:f})=>{f?h(f):l()}),await c()}},this.updateExpiry=async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})},this.updateMetadata=async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:i}=r;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",Yt("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(r,i,o)=>{const c=Yu(i,o),l=await this.core.crypto.encode(r,c),h=jo[i].req;return this.core.history.set(r,c),await this.core.relayer.publish(r,l,h),c.id},this.sendResult=async(r,i,o)=>{const c=Ju(r,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,r),f=jo[h.request.method].res;await this.core.relayer.publish(i,l,f),await this.core.history.resolve(c)},this.sendError=async(r,i,o)=>{const c=Qa(r,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,r),f=jo[h.request.method]?jo[h.request.method].res:jo.unregistered_method.res;await this.core.relayer.publish(i,l,f),await this.core.history.resolve(c)},this.deletePairing=async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,Yt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])},this.cleanup=async()=>{const r=this.pairings.getAll().filter(i=>ai(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=r=>{const{topic:i,payload:o}=r,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 r=>{const{topic:i,payload:o}=r,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(r,i)=>{const{id:o}=i;try{this.isValidPing({topic:r}),await this.sendResult(o,r,!0),this.events.emit("pairing_ping",{id:o,topic:r})}catch(c){await this.sendError(o,r,c),this.logger.error(c)}},this.onPairingPingResponse=(r,i)=>{const{id:o}=i;setTimeout(()=>{Wr(i)?this.events.emit(tn("pairing_ping",o),{}):Or(i)&&this.events.emit(tn("pairing_ping",o),{error:i.error})},500)},this.onPairingDeleteRequest=async(r,i)=>{const{id:o}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit("pairing_delete",{id:o,topic:r})}catch(c){await this.sendError(o,r,c),this.logger.error(c)}},this.onUnknownRpcMethodRequest=async(r,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,r,l),this.logger.error(l)}catch(l){await this.sendError(o,r,l),this.logger.error(l)}},this.onUnknownRpcMethodResponse=r=>{this.registeredMethods.includes(r)||this.logger.error(Yt("WC_METHOD_UNSUPPORTED",r))},this.isValidPair=r=>{if(!kn(r)){const{message:i}=Ee("MISSING_OR_INVALID",`pair() params: ${r}`);throw new Error(i)}if(!Sb(r.uri)){const{message:i}=Ee("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw new Error(i)}},this.isValidPing=async r=>{if(!kn(r)){const{message:o}=Ee("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(o)}const{topic:i}=r;await this.isValidPairingTopic(i)},this.isValidDisconnect=async r=>{if(!kn(r)){const{message:o}=Ee("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(o)}const{topic:i}=r;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async r=>{if(!mn(r,!1)){const{message:i}=Ee("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=Ee("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(ai(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=Ee("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}},this.core=e,this.logger=pt.generateChildLogger(n,this.name),this.pairings=new tc(this.core,this.logger,this.name,this.storagePrefix)}get context(){return pt.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(wn.message,async e=>{const{topic:n,message:r}=e;if(this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))return;const i=await this.core.crypto.decode(n,r);Xu(i)?(this.core.history.set(n,i),this.onRelayEventRequest({topic:n,payload:i})):Bp(i)&&(await this.core.history.resolve(i),this.onRelayEventResponse({topic:n,payload:i}))})}registerExpirerEvents(){this.core.expirer.on(ir.expired,async e=>{const{topic:n}=D1(e.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit("pairing_expire",{topic:n}))})}}class P7 extends v4{constructor(e,n){super(e,n),this.core=e,this.logger=n,this.records=new Map,this.events=new xn.exports.EventEmitter,this.name=a7,this.version=c7,this.cached=[],this.initialized=!1,this.storagePrefix=li,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(r,i,o)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:i,chainId:o}),this.records.has(i.id))return;const c={id:i.id,topic:r,request:{method:i.method,params:i.params||null},chainId:o};this.records.set(c.id,c),this.events.emit(Ar.created,c)},this.resolve=async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const i=await this.getRecord(r.id);typeof i.response>"u"&&(i.response=Or(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.events.emit(Ar.updated,i))},this.get=async(r,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:i}),await this.getRecord(i)),this.delete=(r,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(o=>{if(o.topic===r){if(typeof i<"u"&&o.id!==i)return;this.records.delete(o.id),this.events.emit(Ar.deleted,o)}})},this.exists=async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1),this.on=(r,i)=>{this.events.on(r,i)},this.once=(r,i)=>{this.events.once(r,i)},this.off=(r,i)=>{this.events.off(r,i)},this.removeListener=(r,i)=>{this.events.removeListener(r,i)},this.logger=pt.generateChildLogger(n,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(n=>{if(typeof n.response<"u")return;const r={topic:n.topic,request:Yu(n.request.method,n.request.params,n.id),chainId:n.chainId};return e.push(r)}),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 n=this.records.get(e);if(!n){const{message:r}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ar.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:n}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}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(Ar.created,e=>{const n=Ar.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e}),this.persist()}),this.events.on(Ar.updated,e=>{const n=Ar.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e}),this.persist()}),this.events.on(Ar.deleted,e=>{const n=Ar.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class T7 extends C4{constructor(e,n){super(e,n),this.core=e,this.logger=n,this.expirations=new Map,this.events=new xn.exports.EventEmitter,this.name=l7,this.version=u7,this.cached=[],this.initialized=!1,this.storagePrefix=li,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(r,i)=>{this.isInitialized();const o=this.formatTarget(r),c={target:o,expiry:i};this.expirations.set(o,c),this.checkExpiry(o,c),this.events.emit(ir.created,{target:o,expiration:c})},this.get=r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)},this.del=r=>{if(this.isInitialized(),this.has(r)){const i=this.formatTarget(r),o=this.getExpiration(i);this.expirations.delete(i),this.events.emit(ir.deleted,{target:i,expiration:o})}},this.on=(r,i)=>{this.events.on(r,i)},this.once=(r,i)=>{this.events.once(r,i)},this.off=(r,i)=>{this.events.off(r,i)},this.removeListener=(r,i)=>{this.events.removeListener(r,i)},this.logger=pt.generateChildLogger(n,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 ab(e);if(typeof e=="number")return cb(e);const{message:n}=Ee("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(n)}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(ir.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:n}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}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 n=this.expirations.get(e);if(!n){const{message:r}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return n}checkExpiry(e,n){const{expiry:r}=n;Ue.toMiliseconds(r)-Date.now()<=0&&this.expire(e,n)}expire(e,n){this.expirations.delete(e),this.events.emit(ir.expired,{target:e,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,n)=>this.checkExpiry(n,e))}registerEventListeners(){this.core.heartbeat.on(So.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(ir.created,e=>{const n=ir.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(ir.expired,e=>{const n=ir.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(ir.deleted,e=>{const n=ir.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class R7 extends I4{constructor(e,n){super(e,n),this.projectId=e,this.logger=n,this.name=ug,this.initialized=!1,this.init=async r=>{x1()||!_u()||(this.verifyUrl=r?.verifyUrl||hg,await this.createIframe())},this.register=async r=>{var i;this.initialized||await this.init(),this.iframe&&((i=this.iframe.contentWindow)==null||i.postMessage(r.attestationId,this.verifyUrl),this.logger.info(`postMessage sent: ${r.attestationId} ${this.verifyUrl}`))},this.resolve=async r=>{var i;if(this.isDevEnv)return"";this.logger.info(`resolving attestation: ${r.attestationId}`);const o=this.startAbortTimer(Ue.FIVE_SECONDS),c=await fetch(`${this.verifyUrl}/attestation/${r.attestationId}`,{signal:this.abortController.signal});return clearTimeout(o),((i=await c.json())==null?void 0:i.origin)||""},this.createIframe=async()=>{try{const r=this.startAbortTimer(Ue.FIVE_SECONDS);await Promise.race([new Promise((i,o)=>{const c=document.createElement("iframe");c.setAttribute("id",ug),c.setAttribute("src",`${this.verifyUrl}/${this.projectId}`),c.style.display="none",c.addEventListener("load",()=>{this.initialized=!0,clearTimeout(r),i()}),c.addEventListener("error",l=>{o(l)}),document.body.append(c),this.iframe=c}),new Promise(i=>{this.abortController.signal.addEventListener("abort",()=>{i("iframe load timeout")})})])}catch(r){this.logger.error(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.error(r)}},this.logger=pt.generateChildLogger(n,this.name),this.verifyUrl=hg,this.abortController=new AbortController,this.isDevEnv=bu()&&process.env.IS_VITEST}get context(){return pt.getLoggerContext(this.logger)}startAbortTimer(e){return setTimeout(()=>this.abortController.abort(),yr(e))}}var N7=Object.defineProperty,yg=Object.getOwnPropertySymbols,L7=Object.prototype.hasOwnProperty,M7=Object.prototype.propertyIsEnumerable,bg=(t,e,n)=>e in t?N7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_g=(t,e)=>{for(var n in e||(e={}))L7.call(e,n)&&bg(t,n,e[n]);if(yg)for(var n of yg(e))M7.call(e,n)&&bg(t,n,e[n]);return t};class sh extends w4{constructor(e){super(e),this.protocol=og,this.version=FE,this.name=rh,this.events=new xn.exports.EventEmitter,this.initialized=!1,this.on=(r,i)=>this.events.on(r,i),this.once=(r,i)=>this.events.once(r,i),this.off=(r,i)=>this.events.off(r,i),this.removeListener=(r,i)=>this.events.removeListener(r,i),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||lg;const n=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||BE.logger}));this.logger=pt.generateChildLogger(n,this.name),this.heartbeat=new So.HeartBeat,this.crypto=new f7(this,this.logger,e?.keychain),this.history=new P7(this,this.logger),this.expirer=new T7(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new _6(_g(_g({},kE),e?.storageOptions)),this.relayer=new S7({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new $7(this,this.logger),this.verify=new R7(this.projectId||"",this.logger)}static async init(e){const n=new sh(e);return await n.initialize(),n}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 j7=sh,Eg="wc",xg=2,Cg="client",oh=`${Eg}@${xg}:${Cg}:`,ah={name:Cg,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},U7="proposal",Ig="Proposal expired",F7="session",nc=Ue.SEVEN_DAYS,B7="engine",Fo={wc_sessionPropose:{req:{ttl:Ue.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Ue.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:Ue.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Ue.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Ue.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Ue.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Ue.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Ue.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Ue.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Ue.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Ue.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Ue.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Ue.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Ue.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Ue.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:Ue.THIRTY_SECONDS,prompt:!1,tag:1115}}},ch={min:Ue.FIVE_MINUTES,max:Ue.SEVEN_DAYS},k7="request",H7=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var z7=Object.defineProperty,W7=Object.defineProperties,q7=Object.getOwnPropertyDescriptors,Sg=Object.getOwnPropertySymbols,V7=Object.prototype.hasOwnProperty,K7=Object.prototype.propertyIsEnumerable,Og=(t,e,n)=>e in t?z7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,sr=(t,e)=>{for(var n in e||(e={}))V7.call(e,n)&&Og(t,n,e[n]);if(Sg)for(var n of Sg(e))K7.call(e,n)&&Og(t,n,e[n]);return t},lh=(t,e)=>W7(t,q7(e));class G7 extends O4{constructor(e){super(e),this.name=B7,this.events=new xn.exports,this.initialized=!1,this.ignoredPayloadTypes=[Ti],this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.client.core.pairing.register({methods:Object.keys(Fo)}),this.initialized=!0)},this.connect=async n=>{this.isInitialized();const r=lh(sr({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(r);const{pairingTopic:i,requiredNamespaces:o,optionalNamespaces:c,sessionProperties:l,relays:h}=r;let f=i,v,E=!1;if(f&&(E=this.client.core.pairing.pairings.get(f).active),!f||!E){const{topic:L,uri:A}=await this.client.core.pairing.create();f=L,v=A}const b=await this.client.core.crypto.generateKeyPair(),C=sr({requiredNamespaces:o,optionalNamespaces:c,relays:h??[{protocol:cg}],proposer:{publicKey:b,metadata:this.client.metadata}},l&&{sessionProperties:l}),{reject:P,resolve:M,done:k}=_s(Ue.FIVE_MINUTES,Ig);if(this.events.once(tn("session_connect"),async({error:L,session:A})=>{if(L)P(L);else if(A){A.self.publicKey=b;const R=lh(sr({},A),{requiredNamespaces:A.requiredNamespaces,optionalNamespaces:A.optionalNamespaces});await this.client.session.set(A.topic,R),await this.setExpiry(A.topic,A.expiry),f&&await this.client.core.pairing.updateMetadata({topic:f,metadata:A.peer.metadata}),M(R)}}),!f){const{message:L}=Ee("NO_MATCHING_KEY",`connect() pairing topic: ${f}`);throw new Error(L)}const q=await this.sendRequest(f,"wc_sessionPropose",C),T=yr(Ue.FIVE_MINUTES);return await this.setProposal(q,sr({id:q,expiry:T},C)),{uri:v,approval:k}},this.pair=async n=>(this.isInitialized(),await this.client.core.pairing.pair(n)),this.approve=async n=>{this.isInitialized(),await this.isValidApprove(n);const{id:r,relayProtocol:i,namespaces:o,sessionProperties:c}=n,l=this.client.proposal.get(r);let{pairingTopic:h,proposer:f,requiredNamespaces:v,optionalNamespaces:E}=l;h=h||"",xs(v)||(v=_b(o,"approve()"));const b=await this.client.core.crypto.generateKeyPair(),C=f.publicKey,P=await this.client.core.crypto.generateSharedKey(b,C);h&&r&&(await this.client.core.pairing.updateMetadata({topic:h,metadata:f.metadata}),await this.sendResult(r,h,{relay:{protocol:i??"irn"},responderPublicKey:b}),await this.client.proposal.delete(r,Yt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:h}));const M=sr({relay:{protocol:i??"irn"},namespaces:o,requiredNamespaces:v,optionalNamespaces:E,pairingTopic:h,controller:{publicKey:b,metadata:this.client.metadata},expiry:yr(nc)},c&&{sessionProperties:c});await this.client.core.relayer.subscribe(P),await this.sendRequest(P,"wc_sessionSettle",M);const k=lh(sr({},M),{topic:P,pairingTopic:h,acknowledged:!1,self:M.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:b});return await this.client.session.set(P,k),await this.setExpiry(P,yr(nc)),{topic:P,acknowledged:()=>new Promise(q=>q(this.client.session.get(P)))}},this.reject=async n=>{this.isInitialized(),await this.isValidReject(n);const{id:r,reason:i}=n,{pairingTopic:o}=this.client.proposal.get(r);o&&(await this.sendError(r,o,i),await this.client.proposal.delete(r,Yt("USER_DISCONNECTED")))},this.update=async n=>{this.isInitialized(),await this.isValidUpdate(n);const{topic:r,namespaces:i}=n,o=await this.sendRequest(r,"wc_sessionUpdate",{namespaces:i}),{done:c,resolve:l,reject:h}=_s();return this.events.once(tn("session_update",o),({error:f})=>{f?h(f):l()}),await this.client.session.update(r,{namespaces:i}),{acknowledged:c}},this.extend=async n=>{this.isInitialized(),await this.isValidExtend(n);const{topic:r}=n,i=await this.sendRequest(r,"wc_sessionExtend",{}),{done:o,resolve:c,reject:l}=_s();return this.events.once(tn("session_extend",i),({error:h})=>{h?l(h):c()}),await this.setExpiry(r,yr(nc)),{acknowledged:o}},this.request=async n=>{this.isInitialized(),await this.isValidRequest(n);const{chainId:r,request:i,topic:o,expiry:c}=n,l=await this.sendRequest(o,"wc_sessionRequest",{request:i,chainId:r},c),{done:h,resolve:f,reject:v}=_s(c);return this.events.once(tn("session_request",l),({error:E,result:b})=>{E?v(E):f(b)}),this.client.events.emit("session_request_sent",{topic:o,request:i,chainId:r,id:l}),await h()},this.respond=async n=>{this.isInitialized(),await this.isValidRespond(n);const{topic:r,response:i}=n,{id:o}=i;Wr(i)?await this.sendResult(o,r,i.result):Or(i)&&await this.sendError(o,r,i.error),this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0})},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);const{topic:r}=n;if(this.client.session.keys.includes(r)){const i=await this.sendRequest(r,"wc_sessionPing",{}),{done:o,resolve:c,reject:l}=_s();this.events.once(tn("session_ping",i),({error:h})=>{h?l(h):c()}),await o()}else this.client.core.pairing.pairings.keys.includes(r)&&await this.client.core.pairing.ping({topic:r})},this.emit=async n=>{this.isInitialized(),await this.isValidEmit(n);const{topic:r,event:i,chainId:o}=n;await this.sendRequest(r,"wc_sessionEvent",{event:i,chainId:o})},this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:r}=n;this.client.session.keys.includes(r)?(await this.sendRequest(r,"wc_sessionDelete",Yt("USER_DISCONNECTED")),await this.deleteSession(r)):await this.client.core.pairing.disconnect({topic:r})},this.find=n=>(this.isInitialized(),this.client.session.getAll().filter(r=>Cb(r,n))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.deleteSession=async(n,r)=>{const{self:i}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await Promise.all([this.client.session.delete(n,Yt("USER_DISCONNECTED")),this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.deleteSymKey(n),r?Promise.resolve():this.client.core.expirer.del(n)])},this.deleteProposal=async(n,r)=>{await Promise.all([this.client.proposal.delete(n,Yt("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)])},this.deletePendingSessionRequest=async(n,r,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)])},this.setExpiry=async(n,r)=>{this.client.session.keys.includes(n)&&await this.client.session.update(n,{expiry:r}),this.client.core.expirer.set(n,r)},this.setProposal=async(n,r)=>{await this.client.proposal.set(n,r),this.client.core.expirer.set(n,r.expiry)},this.setPendingSessionRequest=async n=>{const r=Fo.wc_sessionRequest.req.ttl,{id:i,topic:o,params:c}=n;await this.client.pendingRequest.set(i,{id:i,topic:o,params:c}),r&&this.client.core.expirer.set(i,yr(r))},this.sendRequest=async(n,r,i,o)=>{const c=Yu(r,i);if(_u()&&H7.includes(r)){const f=Ri(JSON.stringify(c));await this.client.core.verify.register({attestationId:f})}const l=await this.client.core.crypto.encode(n,c),h=Fo[r].req;return o&&(h.ttl=o),this.client.core.history.set(n,c),this.client.core.relayer.publish(n,l,h),c.id},this.sendResult=async(n,r,i)=>{const o=Ju(n,i),c=await this.client.core.crypto.encode(r,o),l=await this.client.core.history.get(r,n),h=Fo[l.request.method].res;this.client.core.relayer.publish(r,c,h),await this.client.core.history.resolve(o)},this.sendError=async(n,r,i)=>{const o=Qa(n,i),c=await this.client.core.crypto.encode(r,o),l=await this.client.core.history.get(r,n),h=Fo[l.request.method].res;this.client.core.relayer.publish(r,c,h),await this.client.core.history.resolve(o)},this.cleanup=async()=>{const n=[],r=[];this.client.session.getAll().forEach(i=>{ai(i.expiry)&&n.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{ai(i.expiry)&&r.push(i.id)}),await Promise.all([...n.map(i=>this.deleteSession(i)),...r.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=n=>{const{topic:r,payload:i}=n,o=i.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeRequest(r,i);case"wc_sessionSettle":return this.onSessionSettleRequest(r,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(r,i);case"wc_sessionExtend":return this.onSessionExtendRequest(r,i);case"wc_sessionPing":return this.onSessionPingRequest(r,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(r,i);case"wc_sessionRequest":return this.onSessionRequest(r,i);case"wc_sessionEvent":return this.onSessionEventRequest(r,i);default:return this.client.logger.info(`Unsupported request method ${o}`)}},this.onRelayEventResponse=async n=>{const{topic:r,payload:i}=n,o=(await this.client.core.history.get(r,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,i);case"wc_sessionSettle":return this.onSessionSettleResponse(r,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,i);case"wc_sessionExtend":return this.onSessionExtendResponse(r,i);case"wc_sessionPing":return this.onSessionPingResponse(r,i);case"wc_sessionRequest":return this.onSessionRequestResponse(r,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}},this.onSessionProposeRequest=async(n,r)=>{const{params:i,id:o}=r;try{this.isValidConnect(sr({},r.params));const c=yr(Ue.FIVE_MINUTES),l=sr({id:o,pairingTopic:n,expiry:c},i);await this.setProposal(o,l);const h=Ri(JSON.stringify(r)),f=await this.getVerifyContext(h,l.proposer.metadata);this.client.events.emit("session_proposal",{id:o,params:l,context:f})}catch(c){await this.sendError(o,n,c),this.client.logger.error(c)}},this.onSessionProposeResponse=async(n,r)=>{const{id:i}=r;if(Wr(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const c=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:c});const l=c.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:l});const h=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const f=await this.client.core.crypto.generateSharedKey(l,h);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:f});const v=await this.client.core.relayer.subscribe(f);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:v}),await this.client.core.pairing.activate({topic:n})}else Or(r)&&(await this.client.proposal.delete(i,Yt("USER_DISCONNECTED")),this.events.emit(tn("session_connect"),{error:r.error}))},this.onSessionSettleRequest=async(n,r)=>{const{id:i,params:o}=r;try{this.isValidSessionSettleRequest(o);const{relay:c,controller:l,expiry:h,namespaces:f,requiredNamespaces:v,optionalNamespaces:E,sessionProperties:b,pairingTopic:C}=r.params,P=sr({topic:n,relay:c,expiry:h,namespaces:f,acknowledged:!0,pairingTopic:C,requiredNamespaces:v,optionalNamespaces:E,controller:l.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:l.publicKey,metadata:l.metadata}},b&&{sessionProperties:b});await this.sendResult(r.id,n,!0),this.events.emit(tn("session_connect"),{session:P})}catch(c){await this.sendError(i,n,c),this.client.logger.error(c)}},this.onSessionSettleResponse=async(n,r)=>{const{id:i}=r;Wr(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(tn("session_approve",i),{})):Or(r)&&(await this.client.session.delete(n,Yt("USER_DISCONNECTED")),this.events.emit(tn("session_approve",i),{error:r.error}))},this.onSessionUpdateRequest=async(n,r)=>{const{params:i,id:o}=r;try{this.isValidUpdate(sr({topic:n},i)),await this.client.session.update(n,{namespaces:i.namespaces}),await this.sendResult(o,n,!0),this.client.events.emit("session_update",{id:o,topic:n,params:i})}catch(c){await this.sendError(o,n,c),this.client.logger.error(c)}},this.onSessionUpdateResponse=(n,r)=>{const{id:i}=r;Wr(r)?this.events.emit(tn("session_update",i),{}):Or(r)&&this.events.emit(tn("session_update",i),{error:r.error})},this.onSessionExtendRequest=async(n,r)=>{const{id:i}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,yr(nc)),await this.sendResult(i,n,!0),this.client.events.emit("session_extend",{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.client.logger.error(o)}},this.onSessionExtendResponse=(n,r)=>{const{id:i}=r;Wr(r)?this.events.emit(tn("session_extend",i),{}):Or(r)&&this.events.emit(tn("session_extend",i),{error:r.error})},this.onSessionPingRequest=async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult(i,n,!0),this.client.events.emit("session_ping",{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.client.logger.error(o)}},this.onSessionPingResponse=(n,r)=>{const{id:i}=r;setTimeout(()=>{Wr(r)?this.events.emit(tn("session_ping",i),{}):Or(r)&&this.events.emit(tn("session_ping",i),{error:r.error})},500)},this.onSessionDeleteRequest=async(n,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:n,reason:r.params}),await Promise.all([new Promise(o=>{this.client.core.relayer.once(wn.publish,async()=>{o(await this.deleteSession(n))})}),this.sendResult(i,n,!0)]),this.client.events.emit("session_delete",{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.client.logger.error(o)}},this.onSessionRequest=async(n,r)=>{const{id:i,params:o}=r;try{this.isValidRequest(sr({topic:n},o)),await this.setPendingSessionRequest({id:i,topic:n,params:o});const c=Ri(JSON.stringify(r)),l=this.client.session.get(n),h=await this.getVerifyContext(c,l.peer.metadata);this.client.events.emit("session_request",{id:i,topic:n,params:o,context:h})}catch(c){await this.sendError(i,n,c),this.client.logger.error(c)}},this.onSessionRequestResponse=(n,r)=>{const{id:i}=r;Wr(r)?this.events.emit(tn("session_request",i),{result:r.result}):Or(r)&&this.events.emit(tn("session_request",i),{error:r.error})},this.onSessionEventRequest=async(n,r)=>{const{id:i,params:o}=r;try{this.isValidEmit(sr({topic:n},o)),this.client.events.emit("session_event",{id:i,topic:n,params:o})}catch(c){await this.sendError(i,n,c),this.client.logger.error(c)}},this.isValidConnect=async n=>{if(!kn(n)){const{message:h}=Ee("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(h)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:c,relays:l}=n;if($n(r)||await this.isValidPairingTopic(r),!Mb(l,!0)){const{message:h}=Ee("MISSING_OR_INVALID",`connect() relays: ${l}`);throw new Error(h)}!$n(i)&&xs(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!$n(o)&&xs(o)!==0&&this.validateNamespaces(o,"optionalNamespaces"),$n(c)||this.validateSessionProps(c,"sessionProperties")},this.validateNamespaces=(n,r)=>{const i=Lb(n,"connect()",r);if(i)throw new Error(i.message)},this.isValidApprove=async n=>{if(!kn(n))throw new Error(Ee("MISSING_OR_INVALID",`approve() params: ${n}`).message);const{id:r,namespaces:i,relayProtocol:o,sessionProperties:c}=n;await this.isValidProposalId(r);const l=this.client.proposal.get(r),h=Ka(i,"approve()");if(h)throw new Error(h.message);const f=M1(l.requiredNamespaces,i,"approve()");if(f)throw new Error(f.message);if(!mn(o,!0)){const{message:v}=Ee("MISSING_OR_INVALID",`approve() relayProtocol: ${o}`);throw new Error(v)}$n(c)||this.validateSessionProps(c,"sessionProperties")},this.isValidReject=async n=>{if(!kn(n)){const{message:o}=Ee("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(o)}const{id:r,reason:i}=n;if(await this.isValidProposalId(r),!Ub(i)){const{message:o}=Ee("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidSessionSettleRequest=n=>{if(!kn(n)){const{message:f}=Ee("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(f)}const{relay:r,controller:i,namespaces:o,expiry:c}=n;if(!N1(r)){const{message:f}=Ee("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(f)}const l=Ab(i,"onSessionSettleRequest()");if(l)throw new Error(l.message);const h=Ka(o,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(ai(c)){const{message:f}=Ee("EXPIRED","onSessionSettleRequest()");throw new Error(f)}},this.isValidUpdate=async n=>{if(!kn(n)){const{message:h}=Ee("MISSING_OR_INVALID",`update() params: ${n}`);throw new Error(h)}const{topic:r,namespaces:i}=n;await this.isValidSessionTopic(r);const o=this.client.session.get(r),c=Ka(i,"update()");if(c)throw new Error(c.message);const l=M1(o.requiredNamespaces,i,"update()");if(l)throw new Error(l.message)},this.isValidExtend=async n=>{if(!kn(n)){const{message:i}=Ee("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionTopic(r)},this.isValidRequest=async n=>{if(!kn(n)){const{message:h}=Ee("MISSING_OR_INVALID",`request() params: ${n}`);throw new Error(h)}const{topic:r,request:i,chainId:o,expiry:c}=n;await this.isValidSessionTopic(r);const{namespaces:l}=this.client.session.get(r);if(!L1(l,o)){const{message:h}=Ee("MISSING_OR_INVALID",`request() chainId: ${o}`);throw new Error(h)}if(!Fb(i)){const{message:h}=Ee("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(h)}if(!Hb(l,o,i.method)){const{message:h}=Ee("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(h)}if(c&&!Vb(c,ch)){const{message:h}=Ee("MISSING_OR_INVALID",`request() expiry: ${c}. Expiry must be a number (in seconds) between ${ch.min} and ${ch.max}`);throw new Error(h)}},this.isValidRespond=async n=>{if(!kn(n)){const{message:o}=Ee("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(o)}const{topic:r,response:i}=n;if(await this.isValidSessionTopic(r),!Bb(i)){const{message:o}=Ee("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidPing=async n=>{if(!kn(n)){const{message:i}=Ee("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)},this.isValidEmit=async n=>{if(!kn(n)){const{message:l}=Ee("MISSING_OR_INVALID",`emit() params: ${n}`);throw new Error(l)}const{topic:r,event:i,chainId:o}=n;await this.isValidSessionTopic(r);const{namespaces:c}=this.client.session.get(r);if(!L1(c,o)){const{message:l}=Ee("MISSING_OR_INVALID",`emit() chainId: ${o}`);throw new Error(l)}if(!kb(i)){const{message:l}=Ee("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}if(!zb(c,o,i.name)){const{message:l}=Ee("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}},this.isValidDisconnect=async n=>{if(!kn(n)){const{message:i}=Ee("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)},this.getVerifyContext=async(n,r)=>{const i={verified:{verifyUrl:r.verifyUrl||"",validation:"UNKNOWN",origin:r.url||""}};try{const o=await this.client.core.verify.resolve({attestationId:n,verifyUrl:r.verifyUrl});o&&(i.verified.origin=o,i.verified.validation=o===r.url?"VALID":"INVALID")}catch(o){this.client.logger.error(o)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(n,r)=>{Object.values(n).forEach(i=>{if(!mn(i,!1)){const{message:o}=Ee("MISSING_OR_INVALID",`${r} must be in Record<string, string> format. Received: ${JSON.stringify(i)}`);throw new Error(o)}})}}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.client.core.relayer.on(wn.message,async e=>{const{topic:n,message:r}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(r)))return;const i=await this.client.core.crypto.decode(n,r);Xu(i)?(this.client.core.history.set(n,i),this.onRelayEventRequest({topic:n,payload:i})):Bp(i)&&(await this.client.core.history.resolve(i),this.onRelayEventResponse({topic:n,payload:i}))})}registerExpirerEvents(){this.client.core.expirer.on(ir.expired,async e=>{const{topic:n,id:r}=D1(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,Ee("EXPIRED"),!0);n?this.client.session.keys.includes(n)&&(await this.deleteSession(n,!0),this.client.events.emit("session_expire",{topic:n})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}isValidPairingTopic(e){if(!mn(e,!1)){const{message:n}=Ee("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(n)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:n}=Ee("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(n)}if(ai(this.client.core.pairing.pairings.get(e).expiry)){const{message:n}=Ee("EXPIRED",`pairing topic: ${e}`);throw new Error(n)}}async isValidSessionTopic(e){if(!mn(e,!1)){const{message:n}=Ee("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(n)}if(!this.client.session.keys.includes(e)){const{message:n}=Ee("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(n)}if(ai(this.client.session.get(e).expiry)){await this.deleteSession(e);const{message:n}=Ee("EXPIRED",`session topic: ${e}`);throw new Error(n)}}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(mn(e,!1)){const{message:n}=Ee("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(n)}else{const{message:n}=Ee("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(n)}}async isValidProposalId(e){if(!jb(e)){const{message:n}=Ee("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(n)}if(!this.client.proposal.keys.includes(e)){const{message:n}=Ee("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(n)}if(ai(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:n}=Ee("EXPIRED",`proposal id: ${e}`);throw new Error(n)}}}class Z7 extends tc{constructor(e,n){super(e,n,U7,oh),this.core=e,this.logger=n}}class Y7 extends tc{constructor(e,n){super(e,n,F7,oh),this.core=e,this.logger=n}}class J7 extends tc{constructor(e,n){super(e,n,k7,oh,r=>r.id),this.core=e,this.logger=n}}class uh extends S4{constructor(e){super(e),this.protocol=Eg,this.version=xg,this.name=ah.name,this.events=new xn.exports.EventEmitter,this.on=(r,i)=>this.events.on(r,i),this.once=(r,i)=>this.events.once(r,i),this.off=(r,i)=>this.events.off(r,i),this.removeListener=(r,i)=>this.events.removeListener(r,i),this.removeAllListeners=r=>this.events.removeAllListeners(r),this.connect=async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}},this.pair=async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}},this.approve=async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}},this.reject=async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}},this.update=async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}},this.extend=async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}},this.request=async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}},this.respond=async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}},this.ping=async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}},this.emit=async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}},this.find=r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}},this.name=e?.name||ah.name,this.metadata=e?.metadata||nb();const n=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||ah.logger}));this.core=e?.core||new j7(e),this.logger=pt.generateChildLogger(n,this.name),this.session=new Y7(this.core,this.logger),this.proposal=new Z7(this.core,this.logger),this.pendingRequest=new J7(this.core,this.logger),this.engine=new G7(this)}static async init(e){const n=new uh(e);return await n.initialize(),n}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 hh={exports:{}};(function(t,e){var n=typeof self<"u"?self:Lt,r=function(){function o(){this.fetch=!1,this.DOMException=n.DOMException}return o.prototype=n,new o}();(function(o){(function(c){var l={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function h(O){return O&&DataView.prototype.isPrototypeOf(O)}if(l.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],v=ArrayBuffer.isView||function(O){return O&&f.indexOf(Object.prototype.toString.call(O))>-1};function E(O){if(typeof O!="string"&&(O=String(O)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(O))throw new TypeError("Invalid character in header field name");return O.toLowerCase()}function b(O){return typeof O!="string"&&(O=String(O)),O}function C(O){var U={next:function(){var ae=O.shift();return{done:ae===void 0,value:ae}}};return l.iterable&&(U[Symbol.iterator]=function(){return U}),U}function P(O){this.map={},O instanceof P?O.forEach(function(U,ae){this.append(ae,U)},this):Array.isArray(O)?O.forEach(function(U){this.append(U[0],U[1])},this):O&&Object.getOwnPropertyNames(O).forEach(function(U){this.append(U,O[U])},this)}P.prototype.append=function(O,U){O=E(O),U=b(U);var ae=this.map[O];this.map[O]=ae?ae+", "+U:U},P.prototype.delete=function(O){delete this.map[E(O)]},P.prototype.get=function(O){return O=E(O),this.has(O)?this.map[O]:null},P.prototype.has=function(O){return this.map.hasOwnProperty(E(O))},P.prototype.set=function(O,U){this.map[E(O)]=b(U)},P.prototype.forEach=function(O,U){for(var ae in this.map)this.map.hasOwnProperty(ae)&&O.call(U,this.map[ae],ae,this)},P.prototype.keys=function(){var O=[];return this.forEach(function(U,ae){O.push(ae)}),C(O)},P.prototype.values=function(){var O=[];return this.forEach(function(U){O.push(U)}),C(O)},P.prototype.entries=function(){var O=[];return this.forEach(function(U,ae){O.push([ae,U])}),C(O)},l.iterable&&(P.prototype[Symbol.iterator]=P.prototype.entries);function M(O){if(O.bodyUsed)return Promise.reject(new TypeError("Already read"));O.bodyUsed=!0}function k(O){return new Promise(function(U,ae){O.onload=function(){U(O.result)},O.onerror=function(){ae(O.error)}})}function q(O){var U=new FileReader,ae=k(U);return U.readAsArrayBuffer(O),ae}function T(O){var U=new FileReader,ae=k(U);return U.readAsText(O),ae}function L(O){for(var U=new Uint8Array(O),ae=new Array(U.length),le=0;le<U.length;le++)ae[le]=String.fromCharCode(U[le]);return ae.join("")}function A(O){if(O.slice)return O.slice(0);var U=new Uint8Array(O.byteLength);return U.set(new Uint8Array(O)),U.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(O){this._bodyInit=O,O?typeof O=="string"?this._bodyText=O:l.blob&&Blob.prototype.isPrototypeOf(O)?this._bodyBlob=O:l.formData&&FormData.prototype.isPrototypeOf(O)?this._bodyFormData=O:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(O)?this._bodyText=O.toString():l.arrayBuffer&&l.blob&&h(O)?(this._bodyArrayBuffer=A(O.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(O)||v(O))?this._bodyArrayBuffer=A(O):this._bodyText=O=Object.prototype.toString.call(O):this._bodyText="",this.headers.get("content-type")||(typeof O=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):l.searchParams&&URLSearchParams.prototype.isPrototypeOf(O)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var O=M(this);if(O)return O;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?M(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(q)}),this.text=function(){var O=M(this);if(O)return O;if(this._bodyBlob)return T(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(L(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},l.formData&&(this.formData=function(){return this.text().then(J)}),this.json=function(){return this.text().then(JSON.parse)},this}var I=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function d(O){var U=O.toUpperCase();return I.indexOf(U)>-1?U:O}function x(O,U){U=U||{};var ae=U.body;if(O instanceof x){if(O.bodyUsed)throw new TypeError("Already read");this.url=O.url,this.credentials=O.credentials,U.headers||(this.headers=new P(O.headers)),this.method=O.method,this.mode=O.mode,this.signal=O.signal,!ae&&O._bodyInit!=null&&(ae=O._bodyInit,O.bodyUsed=!0)}else this.url=String(O);if(this.credentials=U.credentials||this.credentials||"same-origin",(U.headers||!this.headers)&&(this.headers=new P(U.headers)),this.method=d(U.method||this.method||"GET"),this.mode=U.mode||this.mode||null,this.signal=U.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&ae)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(ae)}x.prototype.clone=function(){return new x(this,{body:this._bodyInit})};function J(O){var U=new FormData;return O.trim().split("&").forEach(function(ae){if(ae){var le=ae.split("="),ne=le.shift().replace(/\+/g," "),re=le.join("=").replace(/\+/g," ");U.append(decodeURIComponent(ne),decodeURIComponent(re))}}),U}function z(O){var U=new P,ae=O.replace(/\r?\n[\t ]+/g," ");return ae.split(/\r?\n/).forEach(function(le){var ne=le.split(":"),re=ne.shift().trim();if(re){var oe=ne.join(":").trim();U.append(re,oe)}}),U}R.call(x.prototype);function ee(O,U){U||(U={}),this.type="default",this.status=U.status===void 0?200:U.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in U?U.statusText:"OK",this.headers=new P(U.headers),this.url=U.url||"",this._initBody(O)}R.call(ee.prototype),ee.prototype.clone=function(){return new ee(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new P(this.headers),url:this.url})},ee.error=function(){var O=new ee(null,{status:0,statusText:""});return O.type="error",O};var de=[301,302,303,307,308];ee.redirect=function(O,U){if(de.indexOf(U)===-1)throw new RangeError("Invalid status code");return new ee(null,{status:U,headers:{location:O}})},c.DOMException=o.DOMException;try{new c.DOMException}catch{c.DOMException=function(U,ae){this.message=U,this.name=ae;var le=Error(U);this.stack=le.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function me(O,U){return new Promise(function(ae,le){var ne=new x(O,U);if(ne.signal&&ne.signal.aborted)return le(new c.DOMException("Aborted","AbortError"));var re=new XMLHttpRequest;function oe(){re.abort()}re.onload=function(){var ie={status:re.status,statusText:re.statusText,headers:z(re.getAllResponseHeaders()||"")};ie.url="responseURL"in re?re.responseURL:ie.headers.get("X-Request-URL");var Se="response"in re?re.response:re.responseText;ae(new ee(Se,ie))},re.onerror=function(){le(new TypeError("Network request failed"))},re.ontimeout=function(){le(new TypeError("Network request failed"))},re.onabort=function(){le(new c.DOMException("Aborted","AbortError"))},re.open(ne.method,ne.url,!0),ne.credentials==="include"?re.withCredentials=!0:ne.credentials==="omit"&&(re.withCredentials=!1),"responseType"in re&&l.blob&&(re.responseType="blob"),ne.headers.forEach(function(ie,Se){re.setRequestHeader(Se,ie)}),ne.signal&&(ne.signal.addEventListener("abort",oe),re.onreadystatechange=function(){re.readyState===4&&ne.signal.removeEventListener("abort",oe)}),re.send(typeof ne._bodyInit>"u"?null:ne._bodyInit)})}return me.polyfill=!0,o.fetch||(o.fetch=me,o.Headers=P,o.Request=x,o.Response=ee),c.Headers=P,c.Request=x,c.Response=ee,c.fetch=me,Object.defineProperty(c,"__esModule",{value:!0}),c})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=r;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})(hh,hh.exports);var Dg=rd(hh.exports);const Ag={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},$g=10;class Fi{constructor(e){if(this.url=e,this.events=new xn.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!jp(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}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,n){this.isAvailable||await this.register();try{const r=Po(e),o=await(await Dg(this.url,Object.assign(Object.assign({},Ag),{body:r}))).json();this.onPayload({data:o})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!jp(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,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"));r()})})}this.url=e,this.registering=!0;try{const n=Po({id:1,jsonrpc:"2.0",method:"test",params:[]});await Dg(e,Object.assign(Object.assign({},Ag),{body:n})),this.onOpen()}catch(n){const r=this.parseError(n);throw this.events.emit("register_error",r),this.onClose(),r}}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 n=typeof e.data=="string"?Bu(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),i=r.message||r.toString(),o=Qa(e,i);this.events.emit("payload",o)}parseError(e,n=this.url){return Pp(e,n,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>$g&&this.events.setMaxListeners($g)}}const Pg="error",X7="wss://relay.walletconnect.com",Q7="wc",ex="universal_provider",Tg=`${Q7}@${2}:${ex}:`,tx="https://rpc.walletconnect.com/v1",ui={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Bo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},fh={exports:{}};/**
86
86
  * @license
87
87
  * Lodash <https://lodash.com/>
88
88
  * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>