@walletconnect/ethereum-provider 2.4.7-a3bfbe12 → 2.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -67,7 +67,7 @@
67
67
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
68
68
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
69
69
  PERFORMANCE OF THIS SOFTWARE.
70
- ***************************************************************************** */var na=function(t,e){return na=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},na(t,e)};function $m(t,e){na(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var ia=function(){return ia=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},ia.apply(this,arguments)};function Pm(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Tm(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function Nm(t,e){return function(r,n){e(r,n,t)}}function Rm(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Lm(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(p){try{l(n.next(p))}catch(m){o(m)}}function c(p){try{l(n.throw(p))}catch(m){o(m)}}function l(p){p.done?s(p.value):i(p.value).then(a,c)}l((n=n.apply(t,e||[])).next())})}function Mm(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(p){return c([l,p])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,i=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(p){l=[6,p],i=0}finally{n=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Um(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function Fm(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function sa(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Yu(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function Bm(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Yu(arguments[e]));return t}function jm(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function ii(t){return this instanceof ii?(this.v=t,this):new ii(t)}function km(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(b){n[b]&&(i[b]=function(w){return new Promise(function(E,A){s.push([b,w,E,A])>1||a(b,w)})})}function a(b,w){try{c(n[b](w))}catch(E){m(s[0][3],E)}}function c(b){b.value instanceof ii?Promise.resolve(b.value.v).then(l,p):m(s[0][2],b)}function l(b){a("next",b)}function p(b){a("throw",b)}function m(b,w){b(w),s.shift(),s.length&&a(s[0][0],s[0][1])}}function Hm(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:ii(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function zm(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof sa=="function"?sa(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function Wm(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function qm(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function Vm(t){return t&&t.__esModule?t:{default:t}}function Km(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function Gm(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var Zm=Object.freeze({__proto__:null,__extends:$m,get __assign(){return ia},__rest:Pm,__decorate:Tm,__param:Nm,__metadata:Rm,__awaiter:Lm,__generator:Mm,__createBinding:Um,__exportStar:Fm,__values:sa,__read:Yu,__spread:Bm,__spreadArrays:jm,__await:ii,__asyncGenerator:km,__asyncDelegator:Hm,__asyncValues:zm,__makeTemplateObject:Wm,__importStar:qm,__importDefault:Vm,__classPrivateFieldGet:Km,__classPrivateFieldSet:Gm}),Ym=Or(Zm),lr={},Ju;function Jm(){if(Ju)return lr;Ju=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.isBrowserCryptoAvailable=lr.getSubtleCrypto=lr.getBrowerCrypto=void 0;function t(){return ut?.crypto||ut?.msCrypto||{}}lr.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}lr.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return lr.isBrowserCryptoAvailable=r,lr}var ur={},Xu;function Xm(){if(Xu)return ur;Xu=1,Object.defineProperty(ur,"__esModule",{value:!0}),ur.isBrowser=ur.isNode=ur.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}ur.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}ur.isNode=e;function r(){return!t()&&!e()}return ur.isBrowser=r,ur}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ym;e.__exportStar(Jm(),t),e.__exportStar(Xm(),t)})(Zu);function Qm(){const t=Date.now()*Math.pow(10,3),e=Math.floor(Math.random()*Math.pow(10,3));return t+e}function ls(t,e,r){return{id:r||Qm(),jsonrpc:"2.0",method:t,params:e}}function oa(t,e){return{id:t,jsonrpc:"2.0",result:e}}function us(t,e,r){return{id:t,jsonrpc:"2.0",error:e5(e,r)}}function e5(t,e){return typeof t>"u"?Ku(qu):(typeof t=="string"&&(t=Object.assign(Object.assign({},Ku(ra)),{message:t})),typeof e<"u"&&(t.data=e),Om(t.code)&&(t=Am(t.code)),t)}class t5{}class r5 extends t5{constructor(){super()}}class n5 extends r5{constructor(e){super()}}const i5="^https?:",s5="^wss?:";function o5(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Qu(t,e){const r=o5(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function eh(t){return Qu(t,i5)}function th(t){return Qu(t,s5)}function a5(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function rh(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function aa(t){return rh(t)&&"method"in t}function ca(t){return rh(t)&&(hr(t)||Jt(t))}function hr(t){return"result"in t}function Jt(t){return"error"in t}class si extends n5{constructor(e){super(e),this.events=new Et.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(ls(e.method,e.params||[]),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{Jt(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ca(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",()=>this.events.emit("disconnect")),this.connection.on("error",e=>this.events.emit("error",e)),this.hasRegisteredEventListeners=!0)}}const nh=10,c5=()=>typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:require("ws"),l5=()=>typeof window<"u",u5=c5();class h5{constructor(e){if(this.url=e,this.events=new Et.exports.EventEmitter,this.registering=!1,!th(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=()=>{this.onClose(),e()},this.socket.close()})}async send(e,r){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ri(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!th(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=Zu.isReactNative()?void 0:{rejectUnauthorized:!a5(e)},s=new u5(e,[],i);l5()?s.onerror=o=>{const a=o;n(this.emitError(a.error))}:s.on("error",o=>{n(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=()=>this.onClose(),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(){this.socket=void 0,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ea(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=us(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return Gu(e,r,"WS")}resetMaxListeners(){this.events.getMaxListeners()>nh&&this.events.setMaxListeners(nh)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for URL: ${this.url}`));return this.events.emit("register_error",r),r}}var la={exports:{}};(function(t,e){var r=200,n="__lodash_hash_undefined__",i=1,s=2,o=9007199254740991,a="[object Arguments]",c="[object Array]",l="[object AsyncFunction]",p="[object Boolean]",m="[object Date]",b="[object Error]",w="[object Function]",E="[object GeneratorFunction]",A="[object Map]",N="[object Number]",M="[object Null]",x="[object Object]",D="[object Promise]",y="[object Proxy]",I="[object RegExp]",O="[object Set]",h="[object String]",_="[object Symbol]",H="[object Undefined]",j="[object WeakMap]",q="[object ArrayBuffer]",X="[object DataView]",re="[object Float32Array]",C="[object Float64Array]",$="[object Int8Array]",G="[object Int16Array]",K="[object Int32Array]",W="[object Uint8Array]",z="[object Uint8ClampedArray]",J="[object Uint16Array]",Z="[object Uint32Array]",le=/[\\^$.*+?()[\]{}|]/g,ee=/^\[object .+?Constructor\]$/,pe=/^(?:0|[1-9]\d*)$/,ae={};ae[re]=ae[C]=ae[$]=ae[G]=ae[K]=ae[W]=ae[z]=ae[J]=ae[Z]=!0,ae[a]=ae[c]=ae[q]=ae[p]=ae[X]=ae[m]=ae[b]=ae[w]=ae[A]=ae[N]=ae[x]=ae[I]=ae[O]=ae[h]=ae[j]=!1;var Ce=typeof ut=="object"&&ut&&ut.Object===Object&&ut,B=typeof self=="object"&&self&&self.Object===Object&&self,F=Ce||B||Function("return this")(),R=e&&!e.nodeType&&e,f=R&&!0&&t&&!t.nodeType&&t,P=f&&f.exports===R,te=P&&Ce.process,ie=function(){try{return te&&te.binding&&te.binding("util")}catch{}}(),Ee=ie&&ie.isTypedArray;function Le(S,L){for(var Y=-1,ce=S==null?0:S.length,We=0,Ie=[];++Y<ce;){var Qe=S[Y];L(Qe,Y,S)&&(Ie[We++]=Qe)}return Ie}function $e(S,L){for(var Y=-1,ce=L.length,We=S.length;++Y<ce;)S[We+Y]=L[Y];return S}function Me(S,L){for(var Y=-1,ce=S==null?0:S.length;++Y<ce;)if(L(S[Y],Y,S))return!0;return!1}function Ze(S,L){for(var Y=-1,ce=Array(S);++Y<S;)ce[Y]=L(Y);return ce}function Ke(S){return function(L){return S(L)}}function Pe(S,L){return S.has(L)}function De(S,L){return S?.[L]}function me(S){var L=-1,Y=Array(S.size);return S.forEach(function(ce,We){Y[++L]=[We,ce]}),Y}function Se(S,L){return function(Y){return S(L(Y))}}function Oe(S){var L=-1,Y=Array(S.size);return S.forEach(function(ce){Y[++L]=ce}),Y}var ge=Array.prototype,xe=Function.prototype,g=Object.prototype,u=F["__core-js_shared__"],d=xe.toString,v=g.hasOwnProperty,T=function(){var S=/[^.]+$/.exec(u&&u.keys&&u.keys.IE_PROTO||"");return S?"Symbol(src)_1."+S:""}(),U=g.toString,k=RegExp("^"+d.call(v).replace(le,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),oe=P?F.Buffer:void 0,he=F.Symbol,Ne=F.Uint8Array,Fe=g.propertyIsEnumerable,Re=ge.splice,Ht=he?he.toStringTag:void 0,tn=Object.getOwnPropertySymbols,ki=oe?oe.isBuffer:void 0,eo=Se(Object.keys,Object),rt=Tn(F,"DataView"),Je=Tn(F,"Map"),nt=Tn(F,"Promise"),it=Tn(F,"Set"),st=Tn(F,"WeakMap"),Xe=Tn(Object,"create"),pt=nn(rt),gt=nn(Je),mt=nn(nt),wt=nn(it),bt=nn(st),lt=he?he.prototype:void 0,ot=lt?lt.valueOf:void 0;function Ge(S){var L=-1,Y=S==null?0:S.length;for(this.clear();++L<Y;){var ce=S[L];this.set(ce[0],ce[1])}}function yt(){this.__data__=Xe?Xe(null):{},this.size=0}function vt(S){var L=this.has(S)&&delete this.__data__[S];return this.size-=L?1:0,L}function V_(S){var L=this.__data__;if(Xe){var Y=L[S];return Y===n?void 0:Y}return v.call(L,S)?L[S]:void 0}function K_(S){var L=this.__data__;return Xe?L[S]!==void 0:v.call(L,S)}function G_(S,L){var Y=this.__data__;return this.size+=this.has(S)?0:1,Y[S]=Xe&&L===void 0?n:L,this}Ge.prototype.clear=yt,Ge.prototype.delete=vt,Ge.prototype.get=V_,Ge.prototype.has=K_,Ge.prototype.set=G_;function fr(S){var L=-1,Y=S==null?0:S.length;for(this.clear();++L<Y;){var ce=S[L];this.set(ce[0],ce[1])}}function Z_(){this.__data__=[],this.size=0}function Y_(S){var L=this.__data__,Y=ro(L,S);if(Y<0)return!1;var ce=L.length-1;return Y==ce?L.pop():Re.call(L,Y,1),--this.size,!0}function J_(S){var L=this.__data__,Y=ro(L,S);return Y<0?void 0:L[Y][1]}function X_(S){return ro(this.__data__,S)>-1}function Q_(S,L){var Y=this.__data__,ce=ro(Y,S);return ce<0?(++this.size,Y.push([S,L])):Y[ce][1]=L,this}fr.prototype.clear=Z_,fr.prototype.delete=Y_,fr.prototype.get=J_,fr.prototype.has=X_,fr.prototype.set=Q_;function rn(S){var L=-1,Y=S==null?0:S.length;for(this.clear();++L<Y;){var ce=S[L];this.set(ce[0],ce[1])}}function e7(){this.size=0,this.__data__={hash:new Ge,map:new(Je||fr),string:new Ge}}function t7(S){var L=no(this,S).delete(S);return this.size-=L?1:0,L}function r7(S){return no(this,S).get(S)}function n7(S){return no(this,S).has(S)}function i7(S,L){var Y=no(this,S),ce=Y.size;return Y.set(S,L),this.size+=Y.size==ce?0:1,this}rn.prototype.clear=e7,rn.prototype.delete=t7,rn.prototype.get=r7,rn.prototype.has=n7,rn.prototype.set=i7;function to(S){var L=-1,Y=S==null?0:S.length;for(this.__data__=new rn;++L<Y;)this.add(S[L])}function s7(S){return this.__data__.set(S,n),this}function o7(S){return this.__data__.has(S)}to.prototype.add=to.prototype.push=s7,to.prototype.has=o7;function Sr(S){var L=this.__data__=new fr(S);this.size=L.size}function a7(){this.__data__=new fr,this.size=0}function c7(S){var L=this.__data__,Y=L.delete(S);return this.size=L.size,Y}function l7(S){return this.__data__.get(S)}function u7(S){return this.__data__.has(S)}function h7(S,L){var Y=this.__data__;if(Y instanceof fr){var ce=Y.__data__;if(!Je||ce.length<r-1)return ce.push([S,L]),this.size=++Y.size,this;Y=this.__data__=new rn(ce)}return Y.set(S,L),this.size=Y.size,this}Sr.prototype.clear=a7,Sr.prototype.delete=c7,Sr.prototype.get=l7,Sr.prototype.has=u7,Sr.prototype.set=h7;function d7(S,L){var Y=io(S),ce=!Y&&D7(S),We=!Y&&!ce&&Mc(S),Ie=!Y&&!ce&&!We&&Bd(S),Qe=Y||ce||We||Ie,_t=Qe?Ze(S.length,String):[],St=_t.length;for(var Ye in S)(L||v.call(S,Ye))&&!(Qe&&(Ye=="length"||We&&(Ye=="offset"||Ye=="parent")||Ie&&(Ye=="buffer"||Ye=="byteLength"||Ye=="byteOffset")||E7(Ye,St)))&&_t.push(Ye);return _t}function ro(S,L){for(var Y=S.length;Y--;)if(Ld(S[Y][0],L))return Y;return-1}function f7(S,L,Y){var ce=L(S);return io(S)?ce:$e(ce,Y(S))}function Hi(S){return S==null?S===void 0?H:M:Ht&&Ht in Object(S)?v7(S):I7(S)}function Pd(S){return zi(S)&&Hi(S)==a}function Td(S,L,Y,ce,We){return S===L?!0:S==null||L==null||!zi(S)&&!zi(L)?S!==S&&L!==L:p7(S,L,Y,ce,Td,We)}function p7(S,L,Y,ce,We,Ie){var Qe=io(S),_t=io(L),St=Qe?c:Ir(S),Ye=_t?c:Ir(L);St=St==a?x:St,Ye=Ye==a?x:Ye;var zt=St==x,Xt=Ye==x,Dt=St==Ye;if(Dt&&Mc(S)){if(!Mc(L))return!1;Qe=!0,zt=!1}if(Dt&&!zt)return Ie||(Ie=new Sr),Qe||Bd(S)?Nd(S,L,Y,ce,We,Ie):b7(S,L,St,Y,ce,We,Ie);if(!(Y&i)){var Gt=zt&&v.call(S,"__wrapped__"),Zt=Xt&&v.call(L,"__wrapped__");if(Gt||Zt){var Dr=Gt?S.value():S,pr=Zt?L.value():L;return Ie||(Ie=new Sr),We(Dr,pr,Y,ce,Ie)}}return Dt?(Ie||(Ie=new Sr),y7(S,L,Y,ce,We,Ie)):!1}function g7(S){if(!Fd(S)||C7(S))return!1;var L=Md(S)?k:ee;return L.test(nn(S))}function m7(S){return zi(S)&&Ud(S.length)&&!!ae[Hi(S)]}function w7(S){if(!S7(S))return eo(S);var L=[];for(var Y in Object(S))v.call(S,Y)&&Y!="constructor"&&L.push(Y);return L}function Nd(S,L,Y,ce,We,Ie){var Qe=Y&i,_t=S.length,St=L.length;if(_t!=St&&!(Qe&&St>_t))return!1;var Ye=Ie.get(S);if(Ye&&Ie.get(L))return Ye==L;var zt=-1,Xt=!0,Dt=Y&s?new to:void 0;for(Ie.set(S,L),Ie.set(L,S);++zt<_t;){var Gt=S[zt],Zt=L[zt];if(ce)var Dr=Qe?ce(Zt,Gt,zt,L,S,Ie):ce(Gt,Zt,zt,S,L,Ie);if(Dr!==void 0){if(Dr)continue;Xt=!1;break}if(Dt){if(!Me(L,function(pr,sn){if(!Pe(Dt,sn)&&(Gt===pr||We(Gt,pr,Y,ce,Ie)))return Dt.push(sn)})){Xt=!1;break}}else if(!(Gt===Zt||We(Gt,Zt,Y,ce,Ie))){Xt=!1;break}}return Ie.delete(S),Ie.delete(L),Xt}function b7(S,L,Y,ce,We,Ie,Qe){switch(Y){case X:if(S.byteLength!=L.byteLength||S.byteOffset!=L.byteOffset)return!1;S=S.buffer,L=L.buffer;case q:return!(S.byteLength!=L.byteLength||!Ie(new Ne(S),new Ne(L)));case p:case m:case N:return Ld(+S,+L);case b:return S.name==L.name&&S.message==L.message;case I:case h:return S==L+"";case A:var _t=me;case O:var St=ce&i;if(_t||(_t=Oe),S.size!=L.size&&!St)return!1;var Ye=Qe.get(S);if(Ye)return Ye==L;ce|=s,Qe.set(S,L);var zt=Nd(_t(S),_t(L),ce,We,Ie,Qe);return Qe.delete(S),zt;case _:if(ot)return ot.call(S)==ot.call(L)}return!1}function y7(S,L,Y,ce,We,Ie){var Qe=Y&i,_t=Rd(S),St=_t.length,Ye=Rd(L),zt=Ye.length;if(St!=zt&&!Qe)return!1;for(var Xt=St;Xt--;){var Dt=_t[Xt];if(!(Qe?Dt in L:v.call(L,Dt)))return!1}var Gt=Ie.get(S);if(Gt&&Ie.get(L))return Gt==L;var Zt=!0;Ie.set(S,L),Ie.set(L,S);for(var Dr=Qe;++Xt<St;){Dt=_t[Xt];var pr=S[Dt],sn=L[Dt];if(ce)var jd=Qe?ce(sn,pr,Dt,L,S,Ie):ce(pr,sn,Dt,S,L,Ie);if(!(jd===void 0?pr===sn||We(pr,sn,Y,ce,Ie):jd)){Zt=!1;break}Dr||(Dr=Dt=="constructor")}if(Zt&&!Dr){var so=S.constructor,oo=L.constructor;so!=oo&&"constructor"in S&&"constructor"in L&&!(typeof so=="function"&&so instanceof so&&typeof oo=="function"&&oo instanceof oo)&&(Zt=!1)}return Ie.delete(S),Ie.delete(L),Zt}function Rd(S){return f7(S,$7,_7)}function no(S,L){var Y=S.__data__;return x7(L)?Y[typeof L=="string"?"string":"hash"]:Y.map}function Tn(S,L){var Y=De(S,L);return g7(Y)?Y:void 0}function v7(S){var L=v.call(S,Ht),Y=S[Ht];try{S[Ht]=void 0;var ce=!0}catch{}var We=U.call(S);return ce&&(L?S[Ht]=Y:delete S[Ht]),We}var _7=tn?function(S){return S==null?[]:(S=Object(S),Le(tn(S),function(L){return Fe.call(S,L)}))}:P7,Ir=Hi;(rt&&Ir(new rt(new ArrayBuffer(1)))!=X||Je&&Ir(new Je)!=A||nt&&Ir(nt.resolve())!=D||it&&Ir(new it)!=O||st&&Ir(new st)!=j)&&(Ir=function(S){var L=Hi(S),Y=L==x?S.constructor:void 0,ce=Y?nn(Y):"";if(ce)switch(ce){case pt:return X;case gt:return A;case mt:return D;case wt:return O;case bt:return j}return L});function E7(S,L){return L=L??o,!!L&&(typeof S=="number"||pe.test(S))&&S>-1&&S%1==0&&S<L}function x7(S){var L=typeof S;return L=="string"||L=="number"||L=="symbol"||L=="boolean"?S!=="__proto__":S===null}function C7(S){return!!T&&T in S}function S7(S){var L=S&&S.constructor,Y=typeof L=="function"&&L.prototype||g;return S===Y}function I7(S){return U.call(S)}function nn(S){if(S!=null){try{return d.call(S)}catch{}try{return S+""}catch{}}return""}function Ld(S,L){return S===L||S!==S&&L!==L}var D7=Pd(function(){return arguments}())?Pd:function(S){return zi(S)&&v.call(S,"callee")&&!Fe.call(S,"callee")},io=Array.isArray;function O7(S){return S!=null&&Ud(S.length)&&!Md(S)}var Mc=ki||T7;function A7(S,L){return Td(S,L)}function Md(S){if(!Fd(S))return!1;var L=Hi(S);return L==w||L==E||L==l||L==y}function Ud(S){return typeof S=="number"&&S>-1&&S%1==0&&S<=o}function Fd(S){var L=typeof S;return S!=null&&(L=="object"||L=="function")}function zi(S){return S!=null&&typeof S=="object"}var Bd=Ee?Ke(Ee):m7;function $7(S){return O7(S)?d7(S):w7(S)}function P7(){return[]}function T7(){return!1}t.exports=A7})(la,la.exports);var d5=la.exports,f5=Object.defineProperty,ih=Object.getOwnPropertySymbols,p5=Object.prototype.hasOwnProperty,g5=Object.prototype.propertyIsEnumerable,sh=(t,e,r)=>e in t?f5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$t=(t,e)=>{for(var r in e||(e={}))p5.call(e,r)&&sh(t,r,e[r]);if(ih)for(var r of ih(e))g5.call(e,r)&&sh(t,r,e[r]);return t};function m5(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),p=Math.log(256)/Math.log(a);function m(E){if(E instanceof Uint8Array||(ArrayBuffer.isView(E)?E=new Uint8Array(E.buffer,E.byteOffset,E.byteLength):Array.isArray(E)&&(E=Uint8Array.from(E))),!(E instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(E.length===0)return"";for(var A=0,N=0,M=0,x=E.length;M!==x&&E[M]===0;)M++,A++;for(var D=(x-M)*p+1>>>0,y=new Uint8Array(D);M!==x;){for(var I=E[M],O=0,h=D-1;(I!==0||O<N)&&h!==-1;h--,O++)I+=256*y[h]>>>0,y[h]=I%a>>>0,I=I/a>>>0;if(I!==0)throw new Error("Non-zero carry");N=O,M++}for(var _=D-N;_!==D&&y[_]===0;)_++;for(var H=c.repeat(A);_<D;++_)H+=t.charAt(y[_]);return H}function b(E){if(typeof E!="string")throw new TypeError("Expected String");if(E.length===0)return new Uint8Array;var A=0;if(E[A]!==" "){for(var N=0,M=0;E[A]===c;)N++,A++;for(var x=(E.length-A)*l+1>>>0,D=new Uint8Array(x);E[A];){var y=r[E.charCodeAt(A)];if(y===255)return;for(var I=0,O=x-1;(y!==0||I<M)&&O!==-1;O--,I++)y+=a*D[O]>>>0,D[O]=y%256>>>0,y=y/256>>>0;if(y!==0)throw new Error("Non-zero carry");M=I,A++}if(E[A]!==" "){for(var h=x-M;h!==x&&D[h]===0;)h++;for(var _=new Uint8Array(N+(x-h)),H=N;h!==x;)_[H++]=D[h++];return _}}}function w(E){var A=b(E);if(A)return A;throw new Error(`Non-${e} character`)}return{encode:m,decodeUnsafe:b,decode:w}}var w5=m5,b5=w5;const oh=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")},y5=t=>new TextEncoder().encode(t),v5=t=>new TextDecoder().decode(t);class _5{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class E5{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ah(this,e)}}class x5{constructor(e){this.decoders=e}or(e){return ah(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const ah=(t,e)=>new x5($t($t({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class C5{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new _5(e,r,n),this.decoder=new E5(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const hs=({name:t,prefix:e,encode:r,decode:n})=>new C5(t,e,r,n),oi=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=b5(r,e);return hs({prefix:t,name:e,encode:n,decode:s=>oh(i(s))})},S5=(t,e,r,n)=>{const i={};for(let p=0;p<e.length;++p)i[e[p]]=p;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,l=0;for(let p=0;p<s;++p){const m=i[t[p]];if(m===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|m,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},I5=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},Ct=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>hs({prefix:e,name:t,encode(i){return I5(i,n,r)},decode(i){return S5(i,n,r,t)}}),D5=hs({prefix:"\0",name:"identity",encode:t=>v5(t),decode:t=>y5(t)});var O5=Object.freeze({__proto__:null,identity:D5});const A5=Ct({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var $5=Object.freeze({__proto__:null,base2:A5});const P5=Ct({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var T5=Object.freeze({__proto__:null,base8:P5});const N5=oi({prefix:"9",name:"base10",alphabet:"0123456789"});var R5=Object.freeze({__proto__:null,base10:N5});const L5=Ct({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),M5=Ct({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var U5=Object.freeze({__proto__:null,base16:L5,base16upper:M5});const F5=Ct({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),B5=Ct({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),j5=Ct({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),k5=Ct({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),H5=Ct({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),z5=Ct({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),W5=Ct({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),q5=Ct({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),V5=Ct({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var K5=Object.freeze({__proto__:null,base32:F5,base32upper:B5,base32pad:j5,base32padupper:k5,base32hex:H5,base32hexupper:z5,base32hexpad:W5,base32hexpadupper:q5,base32z:V5});const G5=oi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Z5=oi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Y5=Object.freeze({__proto__:null,base36:G5,base36upper:Z5});const J5=oi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),X5=oi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Q5=Object.freeze({__proto__:null,base58btc:J5,base58flickr:X5});const ew=Ct({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),tw=Ct({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),rw=Ct({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),nw=Ct({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var iw=Object.freeze({__proto__:null,base64:ew,base64pad:tw,base64url:rw,base64urlpad:nw});const ch=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}"),sw=ch.reduce((t,e,r)=>(t[r]=e,t),[]),ow=ch.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function aw(t){return t.reduce((e,r)=>(e+=sw[r],e),"")}function cw(t){const e=[];for(const r of t){const n=ow[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const lw=hs({prefix:"\u{1F680}",name:"base256emoji",encode:aw,decode:cw});var uw=Object.freeze({__proto__:null,base256emoji:lw}),hw=uh,lh=128,dw=127,fw=~dw,pw=Math.pow(2,31);function uh(t,e,r){e=e||[],r=r||0;for(var n=r;t>=pw;)e[r++]=t&255|lh,t/=128;for(;t&fw;)e[r++]=t&255|lh,t>>>=7;return e[r]=t|0,uh.bytes=r-n+1,e}var gw=ua,mw=128,hh=127;function ua(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw ua.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&hh)<<i:(o&hh)*Math.pow(2,i),i+=7}while(o>=mw);return ua.bytes=s-n,r}var ww=Math.pow(2,7),bw=Math.pow(2,14),yw=Math.pow(2,21),vw=Math.pow(2,28),_w=Math.pow(2,35),Ew=Math.pow(2,42),xw=Math.pow(2,49),Cw=Math.pow(2,56),Sw=Math.pow(2,63),Iw=function(t){return t<ww?1:t<bw?2:t<yw?3:t<vw?4:t<_w?5:t<Ew?6:t<xw?7:t<Cw?8:t<Sw?9:10},Dw={encode:hw,decode:gw,encodingLength:Iw},dh=Dw;const fh=(t,e,r=0)=>(dh.encode(t,e,r),e),ph=t=>dh.encodingLength(t),ha=(t,e)=>{const r=e.byteLength,n=ph(t),i=n+ph(r),s=new Uint8Array(i+r);return fh(t,s,0),fh(r,s,n),s.set(e,i),new Ow(t,r,e,s)};class Ow{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const gh=({name:t,code:e,encode:r})=>new Aw(t,e,r);class Aw{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?ha(this.code,r):r.then(n=>ha(this.code,n))}else throw Error("Unknown type, must be binary type")}}const mh=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),$w=gh({name:"sha2-256",code:18,encode:mh("SHA-256")}),Pw=gh({name:"sha2-512",code:19,encode:mh("SHA-512")});var Tw=Object.freeze({__proto__:null,sha256:$w,sha512:Pw});const wh=0,Nw="identity",bh=oh;var Rw=Object.freeze({__proto__:null,identity:{code:wh,name:Nw,encode:bh,digest:t=>ha(wh,bh(t))}});new TextEncoder,new TextDecoder;const yh=$t($t($t($t($t($t($t($t($t($t({},O5),$5),T5),R5),U5),K5),Y5),Q5),iw),uw);$t($t({},Tw),Rw);function Lw(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function vh(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const _h=vh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),da=vh("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=Lw(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Mw=$t({utf8:_h,"utf-8":_h,hex:yh.base16,latin1:da,ascii:da,binary:da},yh);function Uw(t,e="utf8"){const r=Mw[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}const Eh="wc",Fw=2,fa="core",br=`${Eh}@${2}:${fa}:`,Bw={name:fa,logger:"error"},jw={database:":memory:"},kw="crypto",xh="client_ed25519_seed",Hw=de.ONE_DAY,zw="keychain",Ww="0.3",qw="messages",Vw="0.3",Kw=de.SIX_HOURS,Gw="publisher",Ch="irn",Zw="error",Sh="wss://relay.walletconnect.com",Yw="relayer",dt={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"},Jw="_subscription",ds={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Ih=de.ONE_SECOND,Xw="2.4.7-a3bfbe12",Qw="0.3",rr={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},eb="subscription",tb="0.3",rb=de.FIVE_SECONDS*1e3,nb="pairing",ib="0.3",ai={wc_pairingDelete:{req:{ttl:de.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:de.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:de.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:de.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:de.ONE_DAY,prompt:!1,tag:0},res:{ttl:de.ONE_DAY,prompt:!1,tag:0}}},nr={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},sb="history",ob="0.3",ab="expirer",Wt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},cb="0.3";class lb{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=zw,this.version=Ww,this.initialized=!1,this.storagePrefix=br,this.init=async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=se("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=je.generateChildLogger(r,this.name)}get context(){return je.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,iu(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?su(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}}class ub{constructor(e,r,n){this.core=e,this.logger=r,this.name=kw,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(),s=Wu(i);return zu(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const i=hg();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const s=await this.getClientSeed(),o=Wu(s),a=Ro();return await Em(a,i,Hw,o)},this.generateSharedKey=(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=dg(a,s);return this.setSymKey(c,o)},this.setSymKey=async(i,s)=>{this.isInitialized();const o=s||Jl(i);return await this.keychain.set(o,i),o},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,s,o)=>{this.isInitialized();const a=Xl(o),c=ri(s);if(Ql(a)){const b=a.senderPublicKey,w=a.receiverPublicKey;i=await this.generateSharedKey(b,w)}const l=this.getSymKey(i),{type:p,senderPublicKey:m}=a;return pg({type:p,symKey:l,message:c,senderPublicKey:m})},this.decode=async(i,s,o)=>{this.isInitialized();const a=wg(s,o);if(Ql(a)){const p=a.receiverPublicKey,m=a.senderPublicKey;i=await this.generateSharedKey(p,m)}const c=this.getSymKey(i),l=gg({symKey:c,encoded:s});return ea(l)},this.core=e,this.logger=je.generateChildLogger(r,this.name),this.keychain=n||new lb(this.core,this.logger)}get context(){return je.getLoggerContext(this.logger)}getPayloadType(e){const r=Lo(e);return Bn(r.type)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(xh)}catch{e=Ro(),await this.keychain.set(xh,e)}return Uw(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}}class hb extends tm{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=qw,this.version=Vw,this.initialized=!1,this.storagePrefix=br,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();const s=ts(i);let o=this.messages.get(n);return typeof o>"u"&&(o={}),typeof o[s]<"u"||(o[s]=i,this.messages.set(n,o),await this.persist()),s},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();const s=this.get(n),o=ts(i);return typeof s[o]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=je.generateChildLogger(e,this.name),this.core=r}get context(){return je.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,iu(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?su(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}}class db extends rm{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new Et.exports.EventEmitter,this.name=Gw,this.queue=new Map,this.publishTimeout=1e4,this.publish=async(n,i,s)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});try{const o=s?.ttl||Kw,a=Uo(s),c=s?.prompt||!1,l=s?.tag||0,p={topic:n,message:i,opts:{ttl:o,relay:a,prompt:c,tag:l}},m=ts(i);this.queue.set(m,p);try{await await Mo(this.rpcPublish(n,i,o,a,c,l),this.publishTimeout),this.relayer.events.emit(dt.publish,p)}catch{this.logger.debug("Publishing Payload stalled"),this.relayer.events.emit(dt.connection_stalled);return}this.onPublish(m,p),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}})}catch(o){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(o),o}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=je.generateChildLogger(r,this.name),this.registerEventListeners()}get context(){return je.getLoggerContext(this.logger)}rpcPublish(e,r,n,i,s,o){var a,c,l,p;const m={method:rs(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:s,tag:o}};return Ot((a=m.params)==null?void 0:a.prompt)&&((c=m.params)==null||delete c.prompt),Ot((l=m.params)==null?void 0:l.tag)&&((p=m.params)==null||delete p.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:m}),this.relayer.provider.request(m)}onPublish(e,r){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(Jn.HEARTBEAT_EVENTS.pulse,()=>{this.checkQueue()})}}class fb{constructor(){this.map=new Map,this.set=(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var pb=Object.defineProperty,gb=Object.defineProperties,mb=Object.getOwnPropertyDescriptors,Dh=Object.getOwnPropertySymbols,wb=Object.prototype.hasOwnProperty,bb=Object.prototype.propertyIsEnumerable,Oh=(t,e,r)=>e in t?pb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ci=(t,e)=>{for(var r in e||(e={}))wb.call(e,r)&&Oh(t,r,e[r]);if(Dh)for(var r of Dh(e))bb.call(e,r)&&Oh(t,r,e[r]);return t},pa=(t,e)=>gb(t,mb(e));class yb extends sm{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new fb,this.events=new Et.exports.EventEmitter,this.name=eb,this.version=tb,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=br,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restart(),this.registerEventListeners(),this.onEnable(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const s=Uo(i),o={topic:n,relay:s};this.pending.set(n,o);const a=await this.rpcSubscribe(n,s);return this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}}),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>this.topics.includes(n)?!0:await new Promise((i,s)=>{const o=new de.Watch;o.start(this.pendingSubscriptionWatchLabel);const a=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(a),o.stop(this.pendingSubscriptionWatchLabel),i(!0)),o.elapsed(this.pendingSubscriptionWatchLabel)>=rb&&(clearInterval(a),o.stop(this.pendingSubscriptionWatchLabel),s(!1))},this.pollingInterval)}),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=je.generateChildLogger(r,this.name),this.clientId=""}get context(){return je.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear(),this.initialized=!1}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=Uo(n);await this.rpcUnsubscribe(e,r,i);const s=tt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){const n={method:rs(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await Mo(this.relayer.provider.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(dt.connection_stalled)}return ts(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:rs(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await Mo(this.relayer.provider.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(dt.connection_stalled)}}rpcUnsubscribe(e,r,n){const i={method:rs(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.provider.request(i)}onSubscribe(e,r){this.setSubscription(e,pa(ci({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,ci({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r))}addSubscription(e,r){this.subscriptions.set(e,ci({},r)),this.topicMap.set(r.topic,e),this.events.emit(rr.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=se("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(rr.deleted,pa(ci({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(rr.sync)}async reset(){if(!this.cached.length)return;const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<e;r++){const n=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}this.events.emit(rr.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;const r=await this.rpcBatchSubscribe(e);this.onBatchSubscribe(r.map((n,i)=>pa(ci({},e[i]),{id:n})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(Jn.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(dt.connect,async()=>{await this.onConnect()}),this.relayer.on(dt.disconnect,()=>{this.onDisconnect()}),this.events.on(rr.created,async e=>{const r=rr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(rr.deleted,async e=>{const r=rr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}}var vb=Object.defineProperty,Ah=Object.getOwnPropertySymbols,_b=Object.prototype.hasOwnProperty,Eb=Object.prototype.propertyIsEnumerable,$h=(t,e,r)=>e in t?vb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xb=(t,e)=>{for(var r in e||(e={}))_b.call(e,r)&&$h(t,r,e[r]);if(Ah)for(var r of Ah(e))Eb.call(e,r)&&$h(t,r,e[r]);return t};class Cb extends nm{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new Et.exports.EventEmitter,this.name=Yw,this.transportExplicitlyClosed=!1,this.initialized=!1,this.reconnecting=!1,this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?je.generateChildLogger(e.logger,this.name):zn(je.getDefaultLoggerOptions({level:e.logger||Zw})),this.messages=new hb(this.logger,e.core),this.subscriber=new yb(this,this.logger),this.publisher=new db(this,this.logger),this.relayUrl=e?.relayUrl||Sh,this.projectId=e.projectId,this.provider={}}async init(){this.logger.trace("Initialized"),this.provider=await this.createProvider(),await Promise.all([this.messages.init(),this.transportOpen(),this.subscriber.init()]),this.registerEventListeners(),this.initialized=!0}get context(){return je.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){this.isInitialized();let n="";return await Promise.all([new Promise(i=>{this.subscriber.once(rr.created,s=>{s.topic===e&&i()})}),new Promise(async i=>{n=await this.subscriber.subscribe(e,r),i()})]),n}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportClose(){this.transportExplicitlyClosed=!0,this.connected&&(await this.provider.disconnect(),this.events.emit(dt.transport_closed))}async transportOpen(e){if(!this.reconnecting){this.relayUrl=e||this.relayUrl,this.transportExplicitlyClosed=!1,this.reconnecting=!0;try{await Promise.all([new Promise(r=>{this.initialized||r(),this.subscriber.once(rr.resubscribed,()=>{r()})}),await Promise.race([new Promise(async r=>{await this.provider.connect(),this.removeListener(dt.transport_closed,this.rejectTransportOpen),r()}),new Promise(r=>this.once(dt.transport_closed,this.rejectTransportOpen))])])}catch(r){const n=r;if(!/socket hang up/i.test(n.message))throw r;this.logger.error(r),this.events.emit(dt.transport_closed)}finally{this.reconnecting=!1}}}async restartTransport(e){this.transportExplicitlyClosed||(await this.transportClose(),await new Promise(r=>setTimeout(r,Ih)),await this.transportOpen(e))}rejectTransportOpen(){throw new Error("closeTransport called before connection was established")}async createProvider(){const e=await this.core.crypto.signJWT(this.relayUrl);return new si(new h5(Pg({sdkVersion:Xw,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e})))}async recordMessageEvent(e){const{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;return await this.subscriber.isSubscribed(r)?this.messages.has(r,n):!0}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),aa(e)){if(!e.method.endsWith(Jw))return;const r=e.params,{topic:n,message:i,publishedAt:s}=r.data,o={topic:n,message:i,publishedAt:s};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(xb({type:"event",event:r.id},o)),this.events.emit(r.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(dt.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=oa(e.id,!0);await this.provider.connection.send(r)}registerEventListeners(){this.provider.on(ds.payload,e=>this.onProviderPayload(e)),this.provider.on(ds.connect,()=>{this.events.emit(dt.connect)}),this.provider.on(ds.disconnect,()=>{this.events.emit(dt.disconnect),this.attemptToReconnect()}),this.provider.on(ds.error,e=>this.events.emit(dt.error,e)),this.events.on(dt.connection_stalled,async()=>{await this.restartTransport()})}attemptToReconnect(){this.transportExplicitlyClosed||setTimeout(async()=>{await this.transportOpen()},de.toMiliseconds(Ih))}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Sb=Object.defineProperty,Ph=Object.getOwnPropertySymbols,Ib=Object.prototype.hasOwnProperty,Db=Object.prototype.propertyIsEnumerable,Th=(t,e,r)=>e in t?Sb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nh=(t,e)=>{for(var r in e||(e={}))Ib.call(e,r)&&Th(t,r,e[r]);if(Ph)for(var r of Ph(e))Db.call(e,r)&&Th(t,r,e[r]);return t};class fs extends im{constructor(e,r,n,i=br,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=Qw,this.cached=[],this.initialized=!1,this.storagePrefix=br,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{Xg(o)?this.map.set(o.id,o):Qg(o)?this.map.set(o.topic,o):this.getKey&&o!==null&&!Ot(o)&&this.map.set(this.getKey(o),o)}),this.cached=[],this.initialized=!0)},this.set=async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())},this.get=o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o)),this.getAll=o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>d5(a[c],o[c]))):this.values),this.update=async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Nh(Nh({},this.getData(o)),a);this.map.set(o,c),await this.persist()},this.delete=async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),await this.persist())},this.logger=je.generateChildLogger(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return je.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){const{message:n}=se("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Ob{constructor(e,r){this.core=e,this.logger=r,this.name=nb,this.version=ib,this.events=new Et.exports,this.initialized=!1,this.storagePrefix=br,this.ignoredPayloadTypes=[Tr],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async()=>{this.isInitialized();const n=Ro(),i=await this.core.crypto.setSymKey(n),s=er(de.FIVE_MINUTES),o={protocol:Ch},a={topic:i,expiry:s,relay:o,active:!1},c=Hg({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:n,relay:o});return await this.pairings.set(i,a),await this.core.relayer.subscribe(i),this.core.expirer.set(i,s),{topic:i,uri:c}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);const{topic:i,symKey:s,relay:o}=jg(n.uri),a=er(de.FIVE_MINUTES),c={topic:i,relay:o,expiry:a,active:!1};return await this.pairings.set(i,c),await this.core.crypto.setSymKey(s,i),await this.core.relayer.subscribe(i,{relay:o}),this.core.expirer.set(i,a),n.activatePairing&&await this.activate({topic:i}),c},this.activate=async({topic:n})=>{this.isInitialized();const i=er(de.THIRTY_DAYS);await this.pairings.update(n,{active:!0,expiry:i}),this.core.expirer.set(n,i)},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);const{topic:i}=n;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Rr();this.events.once(et("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",tt("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,s)=>{const o=ls(i,s),a=await this.core.crypto.encode(n,o),c=ai[i].req;return this.core.history.set(n,o),await this.core.relayer.publish(n,a,c),o.id},this.sendResult=async(n,i,s)=>{const o=oa(n,s),a=await this.core.crypto.encode(i,o),c=await this.core.history.get(i,n),l=ai[c.request.method].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)},this.sendError=async(n,i,s)=>{const o=us(n,s),a=await this.core.crypto.encode(i,o),c=await this.core.history.get(i,n),l=ai[c.request.method]?ai[c.request.method].res:ai.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,tt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{const n=this.pairings.getAll().filter(i=>mr(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{const{topic:i,payload:s}=n,o=s.method;if(this.pairings.keys.includes(i))switch(o){case"wc_pairingPing":return this.onPairingPingRequest(i,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,s);default:return this.onUnknownRpcMethodRequest(i,s)}},this.onRelayEventResponse=async n=>{const{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;if(this.pairings.keys.includes(i))switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}},this.onPairingPingRequest=async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit("pairing_ping",{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onPairingPingResponse=(n,i)=>{const{id:s}=i;setTimeout(()=>{hr(i)?this.events.emit(et("pairing_ping",s),{}):Jt(i)&&this.events.emit(et("pairing_ping",s),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit("pairing_delete",{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onUnknownRpcMethodRequest=async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=tt("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(tt("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{if(!Rt(n)){const{message:i}=se("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(i)}if(!Jg(n.uri)){const{message:i}=se("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(i)}},this.isValidPing=async n=>{if(!Rt(n)){const{message:s}=se("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!Rt(n)){const{message:s}=se("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!ht(n,!1)){const{message:i}=se("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=se("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(mr(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=se("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=je.generateChildLogger(r,this.name),this.pairings=new fs(this.core,this.logger,this.name,this.storagePrefix)}get context(){return je.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(dt.message,async e=>{const{topic:r,message:n}=e;if(this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;const i=await this.core.crypto.decode(r,n);aa(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):ca(i)&&(await this.core.history.resolve(i),this.onRelayEventResponse({topic:r,payload:i}))})}registerExpirerEvents(){this.core.expirer.on(Wt.expired,async e=>{const{topic:r}=au(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit("pairing_expire",{topic:r}))})}}class Ab extends em{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new Et.exports.EventEmitter,this.name=sb,this.version=ob,this.cached=[],this.initialized=!1,this.storagePrefix=br,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s};this.records.set(o.id,o),this.events.emit(nr.created,o)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=Jt(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.events.emit(nr.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(nr.deleted,s)}})},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=je.generateChildLogger(r,this.name)}get context(){return je.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:ls(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:n}=se("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(nr.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(nr.created,e=>{const r=nr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(nr.updated,e=>{const r=nr.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(nr.deleted,e=>{const r=nr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}}class $b extends om{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new Et.exports.EventEmitter,this.name=ab,this.version=cb,this.cached=[],this.initialized=!1,this.storagePrefix=br,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();const s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Wt.created,{target:s,expiration:o})},this.get=n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Wt.deleted,{target:i,expiration:s})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=je.generateChildLogger(r,this.name)}get context(){return je.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 Tg(e);if(typeof e=="number")return Ng(e);const{message:r}=se("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Wt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:n}=se("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;de.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Wt.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Jn.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(Wt.created,e=>{const r=Wt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Wt.expired,e=>{const r=Wt.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Wt.deleted,e=>{const r=Wt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Pb=Object.defineProperty,Rh=Object.getOwnPropertySymbols,Tb=Object.prototype.hasOwnProperty,Nb=Object.prototype.propertyIsEnumerable,Lh=(t,e,r)=>e in t?Pb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mh=(t,e)=>{for(var r in e||(e={}))Tb.call(e,r)&&Lh(t,r,e[r]);if(Rh)for(var r of Rh(e))Nb.call(e,r)&&Lh(t,r,e[r]);return t};class ga extends Q3{constructor(e){super(e),this.protocol=Eh,this.version=Fw,this.name=fa,this.events=new Et.exports.EventEmitter,this.initialized=!1,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Sh;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:zn(je.getDefaultLoggerOptions({level:e?.logger||Bw.logger}));this.logger=je.generateChildLogger(r,this.name),this.heartbeat=new Jn.HeartBeat,this.crypto=new ub(this,this.logger,e?.keychain),this.history=new Ab(this,this.logger),this.expirer=new $b(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new s3(Mh(Mh({},jw),e?.storageOptions)),this.relayer=new Cb({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Ob(this,this.logger)}static async init(e){const r=new ga(e);return await r.initialize(),r}get context(){return je.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 Rb=ga,Uh="wc",Fh=2,Bh="client",ma=`${Uh}@${Fh}:${Bh}:`,wa={name:Bh,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},Lb="proposal",jh="Proposal expired",Mb="session",ps=de.SEVEN_DAYS,Ub="engine",li={wc_sessionPropose:{req:{ttl:de.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:de.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:de.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:de.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:de.ONE_DAY,prompt:!1,tag:1104},res:{ttl:de.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:de.ONE_DAY,prompt:!1,tag:1106},res:{ttl:de.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:de.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:de.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:de.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:de.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:de.ONE_DAY,prompt:!1,tag:1112},res:{ttl:de.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:de.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:de.THIRTY_SECONDS,prompt:!1,tag:1115}}},ba={min:de.FIVE_MINUTES,max:de.SEVEN_DAYS},Fb="request";var Bb=Object.defineProperty,jb=Object.defineProperties,kb=Object.getOwnPropertyDescriptors,kh=Object.getOwnPropertySymbols,Hb=Object.prototype.hasOwnProperty,zb=Object.prototype.propertyIsEnumerable,Hh=(t,e,r)=>e in t?Bb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qt=(t,e)=>{for(var r in e||(e={}))Hb.call(e,r)&&Hh(t,r,e[r]);if(kh)for(var r of kh(e))zb.call(e,r)&&Hh(t,r,e[r]);return t},ya=(t,e)=>jb(t,kb(e));class Wb extends cm{constructor(e){super(e),this.name=Ub,this.events=new Et.exports,this.initialized=!1,this.ignoredPayloadTypes=[Tr],this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.client.core.pairing.register({methods:Object.keys(li)}),this.initialized=!0)},this.connect=async r=>{this.isInitialized();const n=ya(qt({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,relays:c}=n;let l=i,p,m=!1;if(l&&(m=this.client.core.pairing.pairings.get(l).active),!l||!m){const{topic:D,uri:y}=await this.client.core.pairing.create();l=D,p=y}const b=await this.client.core.crypto.generateKeyPair(),w=qt({requiredNamespaces:s,optionalNamespaces:o,relays:c??[{protocol:Ch}],proposer:{publicKey:b,metadata:this.client.metadata}},a&&{sessionProperties:a}),{reject:E,resolve:A,done:N}=Rr(de.FIVE_MINUTES,jh);if(this.events.once(et("session_connect"),async({error:D,session:y})=>{if(D)E(D);else if(y){y.self.publicKey=b;const I=ya(qt({},y),{requiredNamespaces:y.requiredNamespaces,optionalNamespaces:y.optionalNamespaces});await this.client.session.set(y.topic,I),await this.setExpiry(y.topic,y.expiry),l&&await this.client.core.pairing.updateMetadata({topic:l,metadata:y.peer.metadata}),A(I)}}),!l){const{message:D}=se("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(D)}const M=await this.sendRequest(l,"wc_sessionPropose",w),x=er(de.FIVE_MINUTES);return await this.setProposal(M,qt({id:M,expiry:x},w)),{uri:p,approval:N}},this.pair=async r=>(this.isInitialized(),await this.client.core.pairing.pair(r)),this.approve=async r=>{this.isInitialized(),await this.isValidApprove(r);const{id:n,relayProtocol:i,namespaces:s,sessionProperties:o}=r,a=this.client.proposal.get(n);let{pairingTopic:c,proposer:l,requiredNamespaces:p,optionalNamespaces:m}=a;Hn(p)||(p=Vg(s,"approve()"));const b=await this.client.core.crypto.generateKeyPair(),w=l.publicKey,E=await this.client.core.crypto.generateSharedKey(b,w);c&&n&&(await this.client.core.pairing.updateMetadata({topic:c,metadata:l.metadata}),await this.sendResult(n,c,{relay:{protocol:i??"irn"},responderPublicKey:b}),await this.client.proposal.delete(n,tt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:c}));const A=qt({relay:{protocol:i??"irn"},namespaces:s,requiredNamespaces:p,optionalNamespaces:m,controller:{publicKey:b,metadata:this.client.metadata},expiry:er(ps)},o&&{sessionProperties:o});await this.client.core.relayer.subscribe(E);const N=await this.sendRequest(E,"wc_sessionSettle",A),{done:M,resolve:x,reject:D}=Rr();this.events.once(et("session_approve",N),({error:I})=>{I?D(I):x(this.client.session.get(E))});const y=ya(qt({},A),{topic:E,acknowledged:!1,self:A.controller,peer:{publicKey:l.publicKey,metadata:l.metadata},controller:b});return await this.client.session.set(E,y),await this.setExpiry(E,er(ps)),{topic:E,acknowledged:M}},this.reject=async r=>{this.isInitialized(),await this.isValidReject(r);const{id:n,reason:i}=r,{pairingTopic:s}=this.client.proposal.get(n);s&&(await this.sendError(n,s,i),await this.client.proposal.delete(n,tt("USER_DISCONNECTED")))},this.update=async r=>{this.isInitialized(),await this.isValidUpdate(r);const{topic:n,namespaces:i}=r,s=await this.sendRequest(n,"wc_sessionUpdate",{namespaces:i}),{done:o,resolve:a,reject:c}=Rr();return this.events.once(et("session_update",s),({error:l})=>{l?c(l):a()}),await this.client.session.update(n,{namespaces:i}),{acknowledged:o}},this.extend=async r=>{this.isInitialized(),await this.isValidExtend(r);const{topic:n}=r,i=await this.sendRequest(n,"wc_sessionExtend",{}),{done:s,resolve:o,reject:a}=Rr();return this.events.once(et("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,er(ps)),{acknowledged:s}},this.request=async r=>{this.isInitialized(),await this.isValidRequest(r);const{chainId:n,request:i,topic:s,expiry:o}=r,a=await this.sendRequest(s,"wc_sessionRequest",{request:i,chainId:n},o),{done:c,resolve:l,reject:p}=Rr(o);return this.events.once(et("session_request",a),({error:m,result:b})=>{m?p(m):l(b)}),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n}),await c()},this.respond=async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:s}=i;hr(i)?await this.sendResult(s,n,i.result):Jt(i)&&await this.sendError(s,n,i.error),this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0})},this.ping=async r=>{this.isInitialized(),await this.isValidPing(r);const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=await this.sendRequest(n,"wc_sessionPing",{}),{done:s,resolve:o,reject:a}=Rr();this.events.once(et("session_ping",i),({error:c})=>{c?a(c):o()}),await s()}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{this.isInitialized(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r;await this.sendRequest(n,"wc_sessionEvent",{event:i,chainId:s})},this.disconnect=async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:n}=r;this.client.session.keys.includes(n)?(await this.sendRequest(n,"wc_sessionDelete",tt("USER_DISCONNECTED")),await this.deleteSession(n)):await this.client.core.pairing.disconnect({topic:n})},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>Zg(n,r))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.deleteSession=async(r,n)=>{const{self:i}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await Promise.all([this.client.session.delete(r,tt("USER_DISCONNECTED")),this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.deleteSymKey(r),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,tt("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)])},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:n}),this.client.core.expirer.set(r,n)},this.setProposal=async(r,n)=>{await this.client.proposal.set(r,n),this.client.core.expirer.set(r,n.expiry)},this.setPendingSessionRequest=async r=>{const n=li.wc_sessionRequest.req.ttl,{id:i,topic:s,params:o}=r;await this.client.pendingRequest.set(i,{id:i,topic:s,params:o}),n&&this.client.core.expirer.set(i,er(n))},this.sendRequest=async(r,n,i,s)=>{const o=ls(n,i),a=await this.client.core.crypto.encode(r,o),c=li[n].req;return s&&(c.ttl=s),this.client.core.history.set(r,o),this.client.core.relayer.publish(r,a,c),o.id},this.sendResult=async(r,n,i)=>{const s=oa(r,i),o=await this.client.core.crypto.encode(n,s),a=await this.client.core.history.get(n,r),c=li[a.request.method].res;this.client.core.relayer.publish(n,o,c),await this.client.core.history.resolve(s)},this.sendError=async(r,n,i)=>{const s=us(r,i),o=await this.client.core.crypto.encode(n,s),a=await this.client.core.history.get(n,r),c=li[a.request.method].res;this.client.core.relayer.publish(n,o,c),await this.client.core.history.resolve(s)},this.cleanup=async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{mr(i.expiry)&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{mr(i.expiry)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession(i)),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=r=>{const{topic:n,payload:i}=r,s=i.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${s}`)}},this.onRelayEventResponse=async r=>{const{topic:n,payload:i}=r,s=(await this.client.core.history.get(n,i.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${s}`)}},this.onSessionProposeRequest=async(r,n)=>{const{params:i,id:s}=n;try{this.isValidConnect(qt({},n.params));const o=er(de.FIVE_MINUTES),a=qt({id:s,pairingTopic:r,expiry:o},i);await this.setProposal(s,a),this.client.events.emit("session_proposal",{id:s,params:a})}catch(o){await this.sendError(s,r,o),this.client.logger.error(o)}},this.onSessionProposeResponse=async(r,n)=>{const{id:i}=n;if(hr(n)){const{result:s}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});const o=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:o});const a=o.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:a});const c=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:c});const l=await this.client.core.crypto.generateSharedKey(a,c);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:l});const p=await this.client.core.relayer.subscribe(l);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:p}),await this.client.core.pairing.activate({topic:r})}else Jt(n)&&(await this.client.proposal.delete(i,tt("USER_DISCONNECTED")),this.events.emit(et("session_connect"),{error:n.error}))},this.onSessionSettleRequest=async(r,n)=>{const{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,requiredNamespaces:p,optionalNamespaces:m,sessionProperties:b}=n.params,w=qt({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,requiredNamespaces:p,optionalNamespaces:m,controller:a.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},b&&{sessionProperties:b});await this.sendResult(n.id,r,!0),this.events.emit(et("session_connect"),{session:w})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionSettleResponse=async(r,n)=>{const{id:i}=n;hr(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(et("session_approve",i),{})):Jt(n)&&(await this.client.session.delete(r,tt("USER_DISCONNECTED")),this.events.emit(et("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{const{params:i,id:s}=n;try{this.isValidUpdate(qt({topic:r},i)),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult(s,r,!0),this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError(s,r,o),this.client.logger.error(o)}},this.onSessionUpdateResponse=(r,n)=>{const{id:i}=n;hr(n)?this.events.emit(et("session_update",i),{}):Jt(n)&&this.events.emit(et("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,er(ps)),await this.sendResult(i,r,!0),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError(i,r,s),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,n)=>{const{id:i}=n;hr(n)?this.events.emit(et("session_extend",i),{}):Jt(n)&&this.events.emit(et("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult(i,r,!0),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError(i,r,s),this.client.logger.error(s)}},this.onSessionPingResponse=(r,n)=>{const{id:i}=n;setTimeout(()=>{hr(n)?this.events.emit(et("session_ping",i),{}):Jt(n)&&this.events.emit(et("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),this.client.core.relayer.once(dt.publish,async()=>{await this.deleteSession(r)}),await this.sendResult(i,r,!0),this.client.events.emit("session_delete",{id:i,topic:r})}catch(s){await this.sendError(i,r,s),this.client.logger.error(s)}},this.onSessionRequest=async(r,n)=>{const{id:i,params:s}=n;try{this.isValidRequest(qt({topic:r},s)),await this.setPendingSessionRequest({id:i,topic:r,params:s}),this.client.events.emit("session_request",{id:i,topic:r,params:s})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionRequestResponse=(r,n)=>{const{id:i}=n;hr(n)?this.events.emit(et("session_request",i),{result:n.result}):Jt(n)&&this.events.emit(et("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{const{id:i,params:s}=n;try{this.isValidEmit(qt({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.isValidConnect=async r=>{if(!Rt(r)){const{message:c}=se("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(c)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,relays:a}=r;if(Ot(n)||await this.isValidPairingTopic(n),!a2(a,!0)){const{message:c}=se("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(c)}!Ot(i)&&Hn(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Ot(s)&&Hn(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),Ot(o)||this.validateSessionProps(o,"sessionProperties")},this.validateNamespaces=(r,n)=>{const i=o2(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!Rt(r))throw new Error(se("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:s,sessionProperties:o}=r;await this.isValidProposalId(n);const a=this.client.proposal.get(n),c=ns(i,"approve()");if(c)throw new Error(c.message);const l=pu(a.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!ht(s,!0)){const{message:p}=se("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(p)}Ot(o)||this.validateSessionProps(o,"sessionProperties")},this.isValidReject=async r=>{if(!Rt(r)){const{message:s}=se("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(await this.isValidProposalId(n),!l2(i)){const{message:s}=se("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!Rt(r)){const{message:l}=se("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!du(n)){const{message:l}=se("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=e2(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=ns(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(mr(o)){const{message:l}=se("EXPIRED","onSessionSettleRequest()");throw new Error(l)}},this.isValidUpdate=async r=>{if(!Rt(r)){const{message:c}=se("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:n,namespaces:i}=r;await this.isValidSessionTopic(n);const s=this.client.session.get(n),o=ns(i,"update()");if(o)throw new Error(o.message);const a=pu(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)},this.isValidExtend=async r=>{if(!Rt(r)){const{message:i}=se("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!Rt(r)){const{message:c}=se("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:n,request:i,chainId:s,expiry:o}=r;await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!fu(a,s)){const{message:c}=se("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!u2(i)){const{message:c}=se("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!f2(a,s,i.method)){const{message:c}=se("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!w2(o,ba)){const{message:c}=se("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${ba.min} and ${ba.max}`);throw new Error(c)}},this.isValidRespond=async r=>{if(!Rt(r)){const{message:s}=se("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(s)}const{topic:n,response:i}=r;if(await this.isValidSessionTopic(n),!h2(i)){const{message:s}=se("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(s)}},this.isValidPing=async r=>{if(!Rt(r)){const{message:i}=se("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!Rt(r)){const{message:a}=se("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!fu(o,s)){const{message:a}=se("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!d2(i)){const{message:a}=se("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!p2(o,s,i.name)){const{message:a}=se("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}},this.isValidDisconnect=async r=>{if(!Rt(r)){const{message:i}=se("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!ht(i,!1)){const{message:s}=se("MISSING_OR_INVALID",`${n} must be in Record<string, string> format. Received: ${JSON.stringify(i)}`);throw new Error(s)}})}}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.client.core.relayer.on(dt.message,async e=>{const{topic:r,message:n}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(n)))return;const i=await this.client.core.crypto.decode(r,n);aa(i)?(this.client.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):ca(i)&&(await this.client.core.history.resolve(i),this.onRelayEventResponse({topic:r,payload:i}))})}registerExpirerEvents(){this.client.core.expirer.on(Wt.expired,async e=>{const{topic:r,id:n}=au(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,se("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession(r,!0),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}isValidPairingTopic(e){if(!ht(e,!1)){const{message:r}=se("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=se("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(mr(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=se("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!ht(e,!1)){const{message:r}=se("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(!this.client.session.keys.includes(e)){const{message:r}=se("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(mr(this.client.session.get(e).expiry)){await this.deleteSession(e);const{message:r}=se("EXPIRED",`session topic: ${e}`);throw new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ht(e,!1)){const{message:r}=se("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=se("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!c2(e)){const{message:r}=se("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=se("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(mr(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:r}=se("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class qb extends fs{constructor(e,r){super(e,r,Lb,ma),this.core=e,this.logger=r}}class Vb extends fs{constructor(e,r){super(e,r,Mb,ma),this.core=e,this.logger=r}}class Kb extends fs{constructor(e,r){super(e,r,Fb,ma),this.core=e,this.logger=r}}class va extends am{constructor(e){super(e),this.protocol=Uh,this.version=Fh,this.name=wa.name,this.events=new Et.exports.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.name=e?.name||wa.name,this.metadata=e?.metadata||Dg();const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:zn(je.getDefaultLoggerOptions({level:e?.logger||wa.logger}));this.core=e?.core||new Rb(e),this.logger=je.generateChildLogger(r,this.name),this.session=new Vb(this.core,this.logger),this.proposal=new qb(this.core,this.logger),this.pendingRequest=new Kb(this.core,this.logger),this.engine=new Wb(this)}static async init(e){const r=new va(e);return await r.initialize(),r}get context(){return je.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.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var _a={exports:{}};(function(t,e){var r=typeof self<"u"?self:ut,n=function(){function s(){this.fetch=!1,this.DOMException=r.DOMException}return s.prototype=r,new s}();(function(s){(function(o){var a={searchParams:"URLSearchParams"in s,iterable:"Symbol"in s&&"iterator"in Symbol,blob:"FileReader"in s&&"Blob"in s&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in s,arrayBuffer:"ArrayBuffer"in s};function c(C){return C&&DataView.prototype.isPrototypeOf(C)}if(a.arrayBuffer)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],p=ArrayBuffer.isView||function(C){return C&&l.indexOf(Object.prototype.toString.call(C))>-1};function m(C){if(typeof C!="string"&&(C=String(C)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(C))throw new TypeError("Invalid character in header field name");return C.toLowerCase()}function b(C){return typeof C!="string"&&(C=String(C)),C}function w(C){var $={next:function(){var G=C.shift();return{done:G===void 0,value:G}}};return a.iterable&&($[Symbol.iterator]=function(){return $}),$}function E(C){this.map={},C instanceof E?C.forEach(function($,G){this.append(G,$)},this):Array.isArray(C)?C.forEach(function($){this.append($[0],$[1])},this):C&&Object.getOwnPropertyNames(C).forEach(function($){this.append($,C[$])},this)}E.prototype.append=function(C,$){C=m(C),$=b($);var G=this.map[C];this.map[C]=G?G+", "+$:$},E.prototype.delete=function(C){delete this.map[m(C)]},E.prototype.get=function(C){return C=m(C),this.has(C)?this.map[C]:null},E.prototype.has=function(C){return this.map.hasOwnProperty(m(C))},E.prototype.set=function(C,$){this.map[m(C)]=b($)},E.prototype.forEach=function(C,$){for(var G in this.map)this.map.hasOwnProperty(G)&&C.call($,this.map[G],G,this)},E.prototype.keys=function(){var C=[];return this.forEach(function($,G){C.push(G)}),w(C)},E.prototype.values=function(){var C=[];return this.forEach(function($){C.push($)}),w(C)},E.prototype.entries=function(){var C=[];return this.forEach(function($,G){C.push([G,$])}),w(C)},a.iterable&&(E.prototype[Symbol.iterator]=E.prototype.entries);function A(C){if(C.bodyUsed)return Promise.reject(new TypeError("Already read"));C.bodyUsed=!0}function N(C){return new Promise(function($,G){C.onload=function(){$(C.result)},C.onerror=function(){G(C.error)}})}function M(C){var $=new FileReader,G=N($);return $.readAsArrayBuffer(C),G}function x(C){var $=new FileReader,G=N($);return $.readAsText(C),G}function D(C){for(var $=new Uint8Array(C),G=new Array($.length),K=0;K<$.length;K++)G[K]=String.fromCharCode($[K]);return G.join("")}function y(C){if(C.slice)return C.slice(0);var $=new Uint8Array(C.byteLength);return $.set(new Uint8Array(C)),$.buffer}function I(){return this.bodyUsed=!1,this._initBody=function(C){this._bodyInit=C,C?typeof C=="string"?this._bodyText=C:a.blob&&Blob.prototype.isPrototypeOf(C)?this._bodyBlob=C:a.formData&&FormData.prototype.isPrototypeOf(C)?this._bodyFormData=C:a.searchParams&&URLSearchParams.prototype.isPrototypeOf(C)?this._bodyText=C.toString():a.arrayBuffer&&a.blob&&c(C)?(this._bodyArrayBuffer=y(C.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(C)||p(C))?this._bodyArrayBuffer=y(C):this._bodyText=C=Object.prototype.toString.call(C):this._bodyText="",this.headers.get("content-type")||(typeof C=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):a.searchParams&&URLSearchParams.prototype.isPrototypeOf(C)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a.blob&&(this.blob=function(){var C=A(this);if(C)return C;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?A(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(M)}),this.text=function(){var C=A(this);if(C)return C;if(this._bodyBlob)return x(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(D(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},a.formData&&(this.formData=function(){return this.text().then(H)}),this.json=function(){return this.text().then(JSON.parse)},this}var O=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function h(C){var $=C.toUpperCase();return O.indexOf($)>-1?$:C}function _(C,$){$=$||{};var G=$.body;if(C instanceof _){if(C.bodyUsed)throw new TypeError("Already read");this.url=C.url,this.credentials=C.credentials,$.headers||(this.headers=new E(C.headers)),this.method=C.method,this.mode=C.mode,this.signal=C.signal,!G&&C._bodyInit!=null&&(G=C._bodyInit,C.bodyUsed=!0)}else this.url=String(C);if(this.credentials=$.credentials||this.credentials||"same-origin",($.headers||!this.headers)&&(this.headers=new E($.headers)),this.method=h($.method||this.method||"GET"),this.mode=$.mode||this.mode||null,this.signal=$.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&G)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(G)}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})};function H(C){var $=new FormData;return C.trim().split("&").forEach(function(G){if(G){var K=G.split("="),W=K.shift().replace(/\+/g," "),z=K.join("=").replace(/\+/g," ");$.append(decodeURIComponent(W),decodeURIComponent(z))}}),$}function j(C){var $=new E,G=C.replace(/\r?\n[\t ]+/g," ");return G.split(/\r?\n/).forEach(function(K){var W=K.split(":"),z=W.shift().trim();if(z){var J=W.join(":").trim();$.append(z,J)}}),$}I.call(_.prototype);function q(C,$){$||($={}),this.type="default",this.status=$.status===void 0?200:$.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in $?$.statusText:"OK",this.headers=new E($.headers),this.url=$.url||"",this._initBody(C)}I.call(q.prototype),q.prototype.clone=function(){return new q(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new E(this.headers),url:this.url})},q.error=function(){var C=new q(null,{status:0,statusText:""});return C.type="error",C};var X=[301,302,303,307,308];q.redirect=function(C,$){if(X.indexOf($)===-1)throw new RangeError("Invalid status code");return new q(null,{status:$,headers:{location:C}})},o.DOMException=s.DOMException;try{new o.DOMException}catch{o.DOMException=function($,G){this.message=$,this.name=G;var K=Error($);this.stack=K.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function re(C,$){return new Promise(function(G,K){var W=new _(C,$);if(W.signal&&W.signal.aborted)return K(new o.DOMException("Aborted","AbortError"));var z=new XMLHttpRequest;function J(){z.abort()}z.onload=function(){var Z={status:z.status,statusText:z.statusText,headers:j(z.getAllResponseHeaders()||"")};Z.url="responseURL"in z?z.responseURL:Z.headers.get("X-Request-URL");var le="response"in z?z.response:z.responseText;G(new q(le,Z))},z.onerror=function(){K(new TypeError("Network request failed"))},z.ontimeout=function(){K(new TypeError("Network request failed"))},z.onabort=function(){K(new o.DOMException("Aborted","AbortError"))},z.open(W.method,W.url,!0),W.credentials==="include"?z.withCredentials=!0:W.credentials==="omit"&&(z.withCredentials=!1),"responseType"in z&&a.blob&&(z.responseType="blob"),W.headers.forEach(function(Z,le){z.setRequestHeader(le,Z)}),W.signal&&(W.signal.addEventListener("abort",J),z.onreadystatechange=function(){z.readyState===4&&W.signal.removeEventListener("abort",J)}),z.send(typeof W._bodyInit>"u"?null:W._bodyInit)})}return re.polyfill=!0,s.fetch||(s.fetch=re,s.Headers=E,s.Request=_,s.Response=q),o.Headers=E,o.Request=_,o.Response=q,o.fetch=re,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(_a,_a.exports);var zh=kd(_a.exports);const Wh={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},qh=10;class gs{constructor(e){if(this.url=e,this.events=new Et.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!eh(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,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e,r){this.isAvailable||await this.register();try{const n=ri(e),s=await(await zh(this.url,Object.assign(Object.assign({},Wh),{body:n}))).json();this.onPayload({data:s})}catch(n){this.onError(e.id,n)}}async register(e=this.url){if(!eh(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));n()})})}this.url=e,this.registering=!0;try{const r=ri({id:1,jsonrpc:"2.0",method:"test",params:[]});await zh(e,Object.assign(Object.assign({},Wh),{body:r})),this.onOpen()}catch(r){const n=this.parseError(r);throw this.events.emit("register_error",n),this.onClose(),n}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ea(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=us(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return Gu(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>qh&&this.events.setMaxListeners(qh)}}const Vh="error",Gb="wss://relay.walletconnect.com",Zb="wc",Yb="universal_provider",Kh=`${Zb}@${2}:${Yb}:`,Jb="https://rpc.walletconnect.com/v1",ui={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function fn(t,e,r){let n;const i=Ea(t);return e.rpcMap&&(n=e.rpcMap[i]),n||(n=`${Jb}?chainId=eip155:${i}&projectId=${r}`),n}function Ea(t){return t.includes("eip155")?Number(t.split(":")[1]):Number(t)}function Xb(t,e){if(!e.includes(t))throw new Error(`Chain '${t}' not approved. Please use one of the following: ${e.toString()}`)}function Qb(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}const ms=(t,e)=>{const r=n=>{n.request!==e.request||n.topic!==e.topic||(t.events.removeListener("session_request_sent",r),ey())};t.on("session_request_sent",r)};function ey(){if(typeof window<"u")try{const t=window.localStorage.getItem("WALLETCONNECT_DEEPLINK_CHOICE");if(t){const e=JSON.parse(t);window.open(e.href,"_self","noreferrer noopener")}}catch(t){console.error(t)}}class ty{constructor(e){this.name="eip155",this.namespace=e.namespace,this.client=e.client,this.events=e.events,this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){var r;switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return this.handleSwitchChain(e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0"),null;case"eth_chainId":return parseInt(this.getDefaultChain())}return this.namespace.methods.includes(e.request.method)?(ms(this.client,e),await this.client.request(e)):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){const n=Ea(e);if(!this.httpProviders[n]){const i=r||fn(`${this.name}:${n}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${n}`);this.setHttpProvider(n,i)}this.chainId=n,this.events.emit(ui.DEFAULT_CHAIN_CHANGED,`${this.name}:${n}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,r){const n=r||fn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new si(new gs(n))}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=Ea(r);e[n]=this.createHttpProvider(n)}),e}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}handleSwitchChain(e){const r=parseInt(e,16),n=`${this.name}:${r}`;Xb(n,this.namespace.chains),this.setDefaultChain(`${r}`)}}class ry{constructor(e){this.name="solana",this.namespace=e.namespace,this.events=e.events,this.client=e.client,this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?(ms(this.client,e),this.client.request(e)):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const n=r||fn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(ui.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{e[r]=this.createHttpProvider(r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||fn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new si(new gs(n))}}class ny{constructor(e){this.name="cosmos",this.namespace=e.namespace,this.events=e.events,this.client=e.client,this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?(ms(this.client,e),this.client.request(e)):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||fn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(ui.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{e[r]=this.createHttpProvider(r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||fn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new si(new gs(n))}}class iy{constructor(e){this.name="cip34",this.namespace=e.namespace,this.events=e.events,this.client=e.client,this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?(ms(this.client,e),this.client.request(e)):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||this.getCardanoRPCUrl(e);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(ui.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=this.getCardanoRPCUrl(r);e[r]=this.createHttpProvider(r,n)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||this.getCardanoRPCUrl(e);return typeof n>"u"?void 0:new si(new gs(n))}}var sy=Object.defineProperty,oy=Object.defineProperties,ay=Object.getOwnPropertyDescriptors,Gh=Object.getOwnPropertySymbols,cy=Object.prototype.hasOwnProperty,ly=Object.prototype.propertyIsEnumerable,Zh=(t,e,r)=>e in t?sy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ws=(t,e)=>{for(var r in e||(e={}))cy.call(e,r)&&Zh(t,r,e[r]);if(Gh)for(var r of Gh(e))ly.call(e,r)&&Zh(t,r,e[r]);return t},xa=(t,e)=>oy(t,ay(e));class Ca{constructor(e){this.events=new Et.exports,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:zn(je.getDefaultLoggerOptions({level:e?.logger||Vh}))}static async init(e){const r=new Ca(e);return await r.initialize(),r}async request(e,r){const[n,i]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:ws({},e),chainId:`${n}:${i}`,topic:this.session.topic})}sendAsync(e,r,n){this.request(e,n).then(i=>r(null,i)).catch(i=>r(i,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:tt("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){this.shouldAbortPairingAttempt=!1;let r=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(r>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:n,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});n&&(this.uri=n,this.events.emit("display_uri",n)),await i().then(s=>{this.session=s}).catch(s=>{if(s.message!==jh)throw s;r++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(e,r){try{const[n,i]=this.validateChain(e);this.getProvider(n).setDefaultChain(i,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(wr(r)){for(const n of r)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await va.init({logger:this.providerOpts.logger||Vh,relayUrl:this.providerOpts.relayUrl||Gb,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,name:this.providerOpts.name}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");Object.keys(this.namespaces).forEach(e=>{var r,n,i;const s=((r=this.session)==null?void 0:r.namespaces[e].accounts)||[],o=Qb(s),a=xa(ws({},Object.assign(this.namespaces[e],(i=(n=this.optionalNamespaces)==null?void 0:n[e])!=null?i:{})),{accounts:s,chains:o});switch(e){case"eip155":this.rpcProviders[e]=new ty({client:this.client,namespace:a,events:this.events});break;case"solana":this.rpcProviders[e]=new ry({client:this.client,namespace:a,events:this.events});break;case"cosmos":this.rpcProviders[e]=new ny({client:this.client,namespace:a,events:this.events});break;case"polkadot":break;case"cip34":this.rpcProviders[e]=new iy({client:this.client,namespace:a,events:this.events});break}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?this.events.emit("accountsChanged",n.data):n.name==="chainChanged"?this.onChainChanged(r.chainId):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var n;const{namespaces:i}=r,s=(n=this.client)==null?void 0:n.session.get(e);this.session=xa(ws({},s),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",xa(ws({},tt("USER_DISCONNECTED")),{data:e.topic}))}),this.on(ui.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){if(!this.rpcProviders[e])throw new Error(`Provider not found: ${e}`);return this.rpcProviders[e]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r,optionalNamespaces:n,sessionProperties:i}=e;if(!r||!Object.keys(r).length)throw new Error("Namespaces must be not empty");this.namespaces=r,this.optionalNamespaces=n,this.sessionProperties=i,this.persist("namespaces",r),this.persist("optionalNamespaces",n)}validateChain(e){const[r,n]=e?.split(":")||["",""];if(r&&!Object.keys(this.namespaces).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];const i=Object.keys(this.namespaces)[0],s=this.rpcProviders[i].getDefaultChain();return[i,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,r=!1){const[n,i]=this.validateChain(e);r||this.getProvider(n).setDefaultChain(i),this.namespaces[n].defaultChain=i,this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",i)}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0})}persist(e,r){this.client.core.storage.setItem(`${Kh}/${e}`,r)}async getFromStore(e){return await this.client.core.storage.getItem(`${Kh}/${e}`)}}const uy=Ca,hy="wc",dy="ethereum_provider",fy=`${hy}@${2}:${dy}:`,py="https://rpc.walletconnect.com/v1/",bs=["eth_sendTransaction","personal_sign"],gy=["eth_accounts","eth_requestAccounts","eth_call","eth_getBalance","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],ys=["chainChanged","accountsChanged"],my=["message","disconnect","connect"];var wy=Object.defineProperty,by=Object.defineProperties,yy=Object.getOwnPropertyDescriptors,Yh=Object.getOwnPropertySymbols,vy=Object.prototype.hasOwnProperty,_y=Object.prototype.propertyIsEnumerable,Jh=(t,e,r)=>e in t?wy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Xh=(t,e)=>{for(var r in e||(e={}))vy.call(e,r)&&Jh(t,r,e[r]);if(Yh)for(var r of Yh(e))_y.call(e,r)&&Jh(t,r,e[r]);return t},Qh=(t,e)=>by(t,yy(e));function Sa(t){return Number(t[0].split(":")[1])}function Ia(t){return`0x${t.toString(16)}`}function Ey(t){const{chains:e,optionalChains:r,methods:n,optionalMethods:i,events:s,optionalEvents:o,rpcMap:a}=t;if(!wr(e))throw new Error("Invalid chains");const c=e,l=n||bs,p=s||ys,m={[Sa(c)]:a[Sa(c)]},b={chains:c,methods:l,events:p,rpcMap:m},w=s?.filter(M=>!ys.includes(M)),E=n?.filter(M=>!bs.includes(M));if(!r&&!o&&!i&&!(w!=null&&w.length)&&!(E!=null&&E.length))return{required:b};const A=w?.length&&E?.length||!r,N={chains:[...new Set(A?c.concat(r||[]):r)],methods:[...new Set(l.concat(i||[]))],events:[...new Set(p.concat(o||[]))],rpcMap:a};return{required:b,optional:N}}class vs{constructor(){this.events=new Et.exports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=fy,this.on=(e,r)=>(this.events.on(e,r),this),this.once=(e,r)=>(this.events.once(e,r),this),this.removeListener=(e,r)=>(this.events.removeListener(e,r),this),this.off=(e,r)=>(this.events.off(e,r),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const r=new vs;return await r.initialize(e),r}async request(e){return await this.signer.request(e,this.formatChainId(this.chainId))}sendAsync(e,r){this.signer.sendAsync(e,r,this.formatChainId(this.chainId))}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:n}=Ey(this.rpc);try{const i=await new Promise(async(o,a)=>{var c;this.rpc.showQrModal&&((c=this.modal)==null||c.subscribeModal(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(Qh(Xh({namespaces:{[this.namespace]:r}},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e?.pairingTopic})).then(l=>{o(l)}).catch(l=>{a(new Error(l.message))})});if(!i)return;this.setChainIds(this.rpc.chains);const s=lg(i.namespaces,[this.namespace]);this.setAccounts(s),this.events.emit("connect",{chainId:Ia(this.chainId)})}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",Ia(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",Qh(Xh({},tt("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var r,n;this.rpc.showQrModal&&((r=this.modal)==null||r.closeModal(),(n=this.modal)==null||n.openModal({uri:e})),this.events.emit("display_uri",e)})}setHttpProvider(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",Ia(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.setHttpProvider(r)}}parseAccountId(e){const[r,n,i]=e.split(":");return{chainId:`${r}:${n}`,address:i}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,n;return{chains:((r=e.chains)==null?void 0:r.map(i=>this.formatChainId(i)))||[`${this.namespace}:1`],optionalChains:e.optionalChains?e.optionalChains.map(i=>this.formatChainId(i)):void 0,methods:e?.methods||bs,events:e?.events||ys,optionalMethods:e?.optionalMethods||[],optionalEvents:e?.optionalEvents||[],rpcMap:e?.rpcMap||this.buildRpcMap(e.chains.concat(e.optionalChains||[]),e.projectId),showQrModal:(n=e?.showQrModal)!=null?n:!0,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const n={};return e.forEach(i=>{n[i]=this.getRpcUrl(i,r)}),n}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=Sa(this.rpc.chains),this.signer=await uy.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){const{Web3Modal:r}=await Promise.resolve().then(function(){return qy});this.modal=new r({walletConnectVersion:2,projectId:this.rpc.projectId,standaloneChains:this.rpc.chains})}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:n,rpcMap:i}=e;r&&wr(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)})),n&&wr(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(s=>this.formatChainId(s)),n.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)}))}getRpcUrl(e,r){var n;return((n=this.rpc.rpcMap)==null?void 0:n[e])||`${py}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`);this.setChainIds(e?[this.formatChainId(e)]:this.session.namespaces[this.namespace].accounts),this.setAccounts(this.session.namespaces[this.namespace].accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const xy=vs,Cy=Symbol(),e0=Object.getPrototypeOf,Da=new WeakMap,Sy=t=>t&&(Da.has(t)?Da.get(t):e0(t)===Object.prototype||e0(t)===Array.prototype),Iy=t=>Sy(t)&&t[Cy]||null,t0=(t,e=!0)=>{Da.set(t,e)},Oa=t=>typeof t=="object"&&t!==null,Fr=new WeakMap,_s=new WeakSet,Dy=(t=Object.is,e=(l,p)=>new Proxy(l,p),r=l=>Oa(l)&&!_s.has(l)&&(Array.isArray(l)||!(Symbol.iterator in l))&&!(l instanceof WeakMap)&&!(l instanceof WeakSet)&&!(l instanceof Error)&&!(l instanceof Number)&&!(l instanceof Date)&&!(l instanceof String)&&!(l instanceof RegExp)&&!(l instanceof ArrayBuffer),n=l=>{switch(l.status){case"fulfilled":return l.value;case"rejected":throw l.reason;default:throw l}},i=new WeakMap,s=(l,p,m=n)=>{const b=i.get(l);if(b?.[0]===p)return b[1];const w=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return t0(w,!0),i.set(l,[p,w]),Reflect.ownKeys(l).forEach(E=>{const A=Reflect.get(l,E);_s.has(A)?(t0(A,!1),w[E]=A):A instanceof Promise?Object.defineProperty(w,E,{get(){return m(A)}}):Fr.has(A)?w[E]=Ay(A,m):w[E]=A}),Object.freeze(w)},o=new WeakMap,a=[1,1],c=l=>{if(!Oa(l))throw new Error("object required");const p=o.get(l);if(p)return p;let m=a[0];const b=new Set,w=(H,j=++a[0])=>{m!==j&&(m=j,b.forEach(q=>q(H,j)))};let E=a[1];const A=(H=++a[1])=>(E!==H&&!b.size&&(E=H,M.forEach(([j])=>{const q=j[1](H);q>m&&(m=q)})),m),N=H=>(j,q)=>{const X=[...j];X[1]=[H,...X[1]],w(X,q)},M=new Map,x=(H,j)=>{if(void 0!=="production"&&M.has(H))throw new Error("prop listener already exists");if(b.size){const q=j[3](N(H));M.set(H,[j,q])}else M.set(H,[j])},D=H=>{var j;const q=M.get(H);q&&(M.delete(H),(j=q[1])==null||j.call(q))},y=H=>(b.add(H),b.size===1&&M.forEach(([q,X],re)=>{if(void 0!=="production"&&X)throw new Error("remove already exists");const C=q[3](N(re));M.set(re,[q,C])}),()=>{b.delete(H),b.size===0&&M.forEach(([q,X],re)=>{X&&(X(),M.set(re,[q]))})}),I=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),h=e(I,{deleteProperty(H,j){const q=Reflect.get(H,j);D(j);const X=Reflect.deleteProperty(H,j);return X&&w(["delete",[j],q]),X},set(H,j,q,X){var re;const C=Reflect.has(H,j),$=Reflect.get(H,j,X);if(C&&t($,q))return!0;D(j),Oa(q)&&(q=Iy(q)||q);let G=q;if(!((re=Object.getOwnPropertyDescriptor(H,j))!=null&&re.set))if(q instanceof Promise)q.then(K=>{q.status="fulfilled",q.value=K,w(["resolve",[j],K])}).catch(K=>{q.status="rejected",q.reason=K,w(["reject",[j],K])});else{!Fr.has(q)&&r(q)&&(G=yr(q));const K=!_s.has(G)&&Fr.get(G);K&&x(j,K)}return Reflect.set(H,j,G,X),w(["set",[j],q,$]),!0}});o.set(l,h);const _=[I,A,s,y];return Fr.set(h,_),Reflect.ownKeys(l).forEach(H=>{const j=Object.getOwnPropertyDescriptor(l,H);j.get||j.set?Object.defineProperty(I,H,j):h[H]=l[H]}),h})=>[c,Fr,_s,t,e,r,n,i,s,o,a],[Oy]=Dy();function yr(t={}){return Oy(t)}function hi(t,e,r){const n=Fr.get(t);void 0!=="production"&&!n&&console.warn("Please use proxy object");let i;const s=[],o=n[3];let a=!1;const l=o(p=>{if(s.push(p),r){e(s.splice(0));return}i||(i=Promise.resolve().then(()=>{i=void 0,a&&e(s.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Ay(t,e){const r=Fr.get(t);void 0!=="production"&&!r&&console.warn("Please use proxy object");const[n,i,s]=r;return s(n,i(),e)}var r0={},Es={};Es.byteLength=Ty,Es.toByteArray=Ry,Es.fromByteArray=Uy;for(var ir=[],Vt=[],$y=typeof Uint8Array<"u"?Uint8Array:Array,Aa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",pn=0,Py=Aa.length;pn<Py;++pn)ir[pn]=Aa[pn],Vt[Aa.charCodeAt(pn)]=pn;Vt["-".charCodeAt(0)]=62,Vt["_".charCodeAt(0)]=63;function n0(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function Ty(t){var e=n0(t),r=e[0],n=e[1];return(r+n)*3/4-n}function Ny(t,e,r){return(e+r)*3/4-r}function Ry(t){var e,r=n0(t),n=r[0],i=r[1],s=new $y(Ny(t,n,i)),o=0,a=i>0?n-4:n,c;for(c=0;c<a;c+=4)e=Vt[t.charCodeAt(c)]<<18|Vt[t.charCodeAt(c+1)]<<12|Vt[t.charCodeAt(c+2)]<<6|Vt[t.charCodeAt(c+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Vt[t.charCodeAt(c)]<<2|Vt[t.charCodeAt(c+1)]>>4,s[o++]=e&255),i===1&&(e=Vt[t.charCodeAt(c)]<<10|Vt[t.charCodeAt(c+1)]<<4|Vt[t.charCodeAt(c+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function Ly(t){return ir[t>>18&63]+ir[t>>12&63]+ir[t>>6&63]+ir[t&63]}function My(t,e,r){for(var n,i=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(Ly(n));return i.join("")}function Uy(t){for(var e,r=t.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(My(t,o,o+s>a?a:o+s));return n===1?(e=t[r-1],i.push(ir[e>>2]+ir[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(ir[e>>10]+ir[e>>4&63]+ir[e<<2&63]+"=")),i.join("")}var $a={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */$a.read=function(t,e,r,n,i){var s,o,a=i*8-n-1,c=(1<<a)-1,l=c>>1,p=-7,m=r?i-1:0,b=r?-1:1,w=t[e+m];for(m+=b,s=w&(1<<-p)-1,w>>=-p,p+=a;p>0;s=s*256+t[e+m],m+=b,p-=8);for(o=s&(1<<-p)-1,s>>=-p,p+=n;p>0;o=o*256+t[e+m],m+=b,p-=8);if(s===0)s=1-l;else{if(s===c)return o?NaN:(w?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-l}return(w?-1:1)*o*Math.pow(2,s-n)},$a.write=function(t,e,r,n,i,s){var o,a,c,l=s*8-i-1,p=(1<<l)-1,m=p>>1,b=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,w=n?0:s-1,E=n?1:-1,A=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=p):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+m>=1?e+=b/c:e+=b*Math.pow(2,1-m),e*c>=2&&(o++,c/=2),o+m>=p?(a=0,o=p):o+m>=1?(a=(e*c-1)*Math.pow(2,i),o=o+m):(a=e*Math.pow(2,m-1)*Math.pow(2,i),o=0));i>=8;t[r+w]=a&255,w+=E,a/=256,i-=8);for(o=o<<i|a,l+=i;l>0;t[r+w]=o&255,w+=E,o/=256,l-=8);t[r+w-E]|=A*128};/*!
70
+ ***************************************************************************** */var na=function(t,e){return na=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},na(t,e)};function $m(t,e){na(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var ia=function(){return ia=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},ia.apply(this,arguments)};function Pm(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Tm(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function Nm(t,e){return function(r,n){e(r,n,t)}}function Rm(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Lm(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(p){try{l(n.next(p))}catch(m){o(m)}}function c(p){try{l(n.throw(p))}catch(m){o(m)}}function l(p){p.done?s(p.value):i(p.value).then(a,c)}l((n=n.apply(t,e||[])).next())})}function Mm(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(p){return c([l,p])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,i=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(p){l=[6,p],i=0}finally{n=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Um(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function Fm(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function sa(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Yu(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function Bm(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Yu(arguments[e]));return t}function jm(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function ii(t){return this instanceof ii?(this.v=t,this):new ii(t)}function km(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(b){n[b]&&(i[b]=function(w){return new Promise(function(E,A){s.push([b,w,E,A])>1||a(b,w)})})}function a(b,w){try{c(n[b](w))}catch(E){m(s[0][3],E)}}function c(b){b.value instanceof ii?Promise.resolve(b.value.v).then(l,p):m(s[0][2],b)}function l(b){a("next",b)}function p(b){a("throw",b)}function m(b,w){b(w),s.shift(),s.length&&a(s[0][0],s[0][1])}}function Hm(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:ii(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function zm(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof sa=="function"?sa(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function Wm(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function qm(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function Vm(t){return t&&t.__esModule?t:{default:t}}function Km(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function Gm(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var Zm=Object.freeze({__proto__:null,__extends:$m,get __assign(){return ia},__rest:Pm,__decorate:Tm,__param:Nm,__metadata:Rm,__awaiter:Lm,__generator:Mm,__createBinding:Um,__exportStar:Fm,__values:sa,__read:Yu,__spread:Bm,__spreadArrays:jm,__await:ii,__asyncGenerator:km,__asyncDelegator:Hm,__asyncValues:zm,__makeTemplateObject:Wm,__importStar:qm,__importDefault:Vm,__classPrivateFieldGet:Km,__classPrivateFieldSet:Gm}),Ym=Or(Zm),lr={},Ju;function Jm(){if(Ju)return lr;Ju=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.isBrowserCryptoAvailable=lr.getSubtleCrypto=lr.getBrowerCrypto=void 0;function t(){return ut?.crypto||ut?.msCrypto||{}}lr.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}lr.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return lr.isBrowserCryptoAvailable=r,lr}var ur={},Xu;function Xm(){if(Xu)return ur;Xu=1,Object.defineProperty(ur,"__esModule",{value:!0}),ur.isBrowser=ur.isNode=ur.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}ur.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}ur.isNode=e;function r(){return!t()&&!e()}return ur.isBrowser=r,ur}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ym;e.__exportStar(Jm(),t),e.__exportStar(Xm(),t)})(Zu);function Qm(){const t=Date.now()*Math.pow(10,3),e=Math.floor(Math.random()*Math.pow(10,3));return t+e}function ls(t,e,r){return{id:r||Qm(),jsonrpc:"2.0",method:t,params:e}}function oa(t,e){return{id:t,jsonrpc:"2.0",result:e}}function us(t,e,r){return{id:t,jsonrpc:"2.0",error:e5(e,r)}}function e5(t,e){return typeof t>"u"?Ku(qu):(typeof t=="string"&&(t=Object.assign(Object.assign({},Ku(ra)),{message:t})),typeof e<"u"&&(t.data=e),Om(t.code)&&(t=Am(t.code)),t)}class t5{}class r5 extends t5{constructor(){super()}}class n5 extends r5{constructor(e){super()}}const i5="^https?:",s5="^wss?:";function o5(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Qu(t,e){const r=o5(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function eh(t){return Qu(t,i5)}function th(t){return Qu(t,s5)}function a5(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function rh(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function aa(t){return rh(t)&&"method"in t}function ca(t){return rh(t)&&(hr(t)||Jt(t))}function hr(t){return"result"in t}function Jt(t){return"error"in t}class si extends n5{constructor(e){super(e),this.events=new Et.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(ls(e.method,e.params||[]),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{Jt(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ca(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",()=>this.events.emit("disconnect")),this.connection.on("error",e=>this.events.emit("error",e)),this.hasRegisteredEventListeners=!0)}}const nh=10,c5=()=>typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:require("ws"),l5=()=>typeof window<"u",u5=c5();class h5{constructor(e){if(this.url=e,this.events=new Et.exports.EventEmitter,this.registering=!1,!th(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=()=>{this.onClose(),e()},this.socket.close()})}async send(e,r){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ri(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!th(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=Zu.isReactNative()?void 0:{rejectUnauthorized:!a5(e)},s=new u5(e,[],i);l5()?s.onerror=o=>{const a=o;n(this.emitError(a.error))}:s.on("error",o=>{n(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=()=>this.onClose(),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(){this.socket=void 0,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ea(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=us(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return Gu(e,r,"WS")}resetMaxListeners(){this.events.getMaxListeners()>nh&&this.events.setMaxListeners(nh)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for URL: ${this.url}`));return this.events.emit("register_error",r),r}}var la={exports:{}};(function(t,e){var r=200,n="__lodash_hash_undefined__",i=1,s=2,o=9007199254740991,a="[object Arguments]",c="[object Array]",l="[object AsyncFunction]",p="[object Boolean]",m="[object Date]",b="[object Error]",w="[object Function]",E="[object GeneratorFunction]",A="[object Map]",N="[object Number]",M="[object Null]",x="[object Object]",D="[object Promise]",y="[object Proxy]",I="[object RegExp]",O="[object Set]",h="[object String]",_="[object Symbol]",H="[object Undefined]",j="[object WeakMap]",q="[object ArrayBuffer]",X="[object DataView]",re="[object Float32Array]",C="[object Float64Array]",$="[object Int8Array]",G="[object Int16Array]",K="[object Int32Array]",W="[object Uint8Array]",z="[object Uint8ClampedArray]",J="[object Uint16Array]",Z="[object Uint32Array]",le=/[\\^$.*+?()[\]{}|]/g,ee=/^\[object .+?Constructor\]$/,pe=/^(?:0|[1-9]\d*)$/,ae={};ae[re]=ae[C]=ae[$]=ae[G]=ae[K]=ae[W]=ae[z]=ae[J]=ae[Z]=!0,ae[a]=ae[c]=ae[q]=ae[p]=ae[X]=ae[m]=ae[b]=ae[w]=ae[A]=ae[N]=ae[x]=ae[I]=ae[O]=ae[h]=ae[j]=!1;var Ce=typeof ut=="object"&&ut&&ut.Object===Object&&ut,B=typeof self=="object"&&self&&self.Object===Object&&self,F=Ce||B||Function("return this")(),R=e&&!e.nodeType&&e,f=R&&!0&&t&&!t.nodeType&&t,P=f&&f.exports===R,te=P&&Ce.process,ie=function(){try{return te&&te.binding&&te.binding("util")}catch{}}(),Ee=ie&&ie.isTypedArray;function Le(S,L){for(var Y=-1,ce=S==null?0:S.length,We=0,Ie=[];++Y<ce;){var Qe=S[Y];L(Qe,Y,S)&&(Ie[We++]=Qe)}return Ie}function $e(S,L){for(var Y=-1,ce=L.length,We=S.length;++Y<ce;)S[We+Y]=L[Y];return S}function Me(S,L){for(var Y=-1,ce=S==null?0:S.length;++Y<ce;)if(L(S[Y],Y,S))return!0;return!1}function Ze(S,L){for(var Y=-1,ce=Array(S);++Y<S;)ce[Y]=L(Y);return ce}function Ke(S){return function(L){return S(L)}}function Pe(S,L){return S.has(L)}function De(S,L){return S?.[L]}function me(S){var L=-1,Y=Array(S.size);return S.forEach(function(ce,We){Y[++L]=[We,ce]}),Y}function Se(S,L){return function(Y){return S(L(Y))}}function Oe(S){var L=-1,Y=Array(S.size);return S.forEach(function(ce){Y[++L]=ce}),Y}var ge=Array.prototype,xe=Function.prototype,g=Object.prototype,u=F["__core-js_shared__"],d=xe.toString,v=g.hasOwnProperty,T=function(){var S=/[^.]+$/.exec(u&&u.keys&&u.keys.IE_PROTO||"");return S?"Symbol(src)_1."+S:""}(),U=g.toString,k=RegExp("^"+d.call(v).replace(le,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),oe=P?F.Buffer:void 0,he=F.Symbol,Ne=F.Uint8Array,Fe=g.propertyIsEnumerable,Re=ge.splice,Ht=he?he.toStringTag:void 0,tn=Object.getOwnPropertySymbols,ki=oe?oe.isBuffer:void 0,eo=Se(Object.keys,Object),rt=Tn(F,"DataView"),Je=Tn(F,"Map"),nt=Tn(F,"Promise"),it=Tn(F,"Set"),st=Tn(F,"WeakMap"),Xe=Tn(Object,"create"),pt=nn(rt),gt=nn(Je),mt=nn(nt),wt=nn(it),bt=nn(st),lt=he?he.prototype:void 0,ot=lt?lt.valueOf:void 0;function Ge(S){var L=-1,Y=S==null?0:S.length;for(this.clear();++L<Y;){var ce=S[L];this.set(ce[0],ce[1])}}function yt(){this.__data__=Xe?Xe(null):{},this.size=0}function vt(S){var L=this.has(S)&&delete this.__data__[S];return this.size-=L?1:0,L}function V_(S){var L=this.__data__;if(Xe){var Y=L[S];return Y===n?void 0:Y}return v.call(L,S)?L[S]:void 0}function K_(S){var L=this.__data__;return Xe?L[S]!==void 0:v.call(L,S)}function G_(S,L){var Y=this.__data__;return this.size+=this.has(S)?0:1,Y[S]=Xe&&L===void 0?n:L,this}Ge.prototype.clear=yt,Ge.prototype.delete=vt,Ge.prototype.get=V_,Ge.prototype.has=K_,Ge.prototype.set=G_;function fr(S){var L=-1,Y=S==null?0:S.length;for(this.clear();++L<Y;){var ce=S[L];this.set(ce[0],ce[1])}}function Z_(){this.__data__=[],this.size=0}function Y_(S){var L=this.__data__,Y=ro(L,S);if(Y<0)return!1;var ce=L.length-1;return Y==ce?L.pop():Re.call(L,Y,1),--this.size,!0}function J_(S){var L=this.__data__,Y=ro(L,S);return Y<0?void 0:L[Y][1]}function X_(S){return ro(this.__data__,S)>-1}function Q_(S,L){var Y=this.__data__,ce=ro(Y,S);return ce<0?(++this.size,Y.push([S,L])):Y[ce][1]=L,this}fr.prototype.clear=Z_,fr.prototype.delete=Y_,fr.prototype.get=J_,fr.prototype.has=X_,fr.prototype.set=Q_;function rn(S){var L=-1,Y=S==null?0:S.length;for(this.clear();++L<Y;){var ce=S[L];this.set(ce[0],ce[1])}}function e7(){this.size=0,this.__data__={hash:new Ge,map:new(Je||fr),string:new Ge}}function t7(S){var L=no(this,S).delete(S);return this.size-=L?1:0,L}function r7(S){return no(this,S).get(S)}function n7(S){return no(this,S).has(S)}function i7(S,L){var Y=no(this,S),ce=Y.size;return Y.set(S,L),this.size+=Y.size==ce?0:1,this}rn.prototype.clear=e7,rn.prototype.delete=t7,rn.prototype.get=r7,rn.prototype.has=n7,rn.prototype.set=i7;function to(S){var L=-1,Y=S==null?0:S.length;for(this.__data__=new rn;++L<Y;)this.add(S[L])}function s7(S){return this.__data__.set(S,n),this}function o7(S){return this.__data__.has(S)}to.prototype.add=to.prototype.push=s7,to.prototype.has=o7;function Sr(S){var L=this.__data__=new fr(S);this.size=L.size}function a7(){this.__data__=new fr,this.size=0}function c7(S){var L=this.__data__,Y=L.delete(S);return this.size=L.size,Y}function l7(S){return this.__data__.get(S)}function u7(S){return this.__data__.has(S)}function h7(S,L){var Y=this.__data__;if(Y instanceof fr){var ce=Y.__data__;if(!Je||ce.length<r-1)return ce.push([S,L]),this.size=++Y.size,this;Y=this.__data__=new rn(ce)}return Y.set(S,L),this.size=Y.size,this}Sr.prototype.clear=a7,Sr.prototype.delete=c7,Sr.prototype.get=l7,Sr.prototype.has=u7,Sr.prototype.set=h7;function d7(S,L){var Y=io(S),ce=!Y&&D7(S),We=!Y&&!ce&&Mc(S),Ie=!Y&&!ce&&!We&&Bd(S),Qe=Y||ce||We||Ie,_t=Qe?Ze(S.length,String):[],St=_t.length;for(var Ye in S)(L||v.call(S,Ye))&&!(Qe&&(Ye=="length"||We&&(Ye=="offset"||Ye=="parent")||Ie&&(Ye=="buffer"||Ye=="byteLength"||Ye=="byteOffset")||E7(Ye,St)))&&_t.push(Ye);return _t}function ro(S,L){for(var Y=S.length;Y--;)if(Ld(S[Y][0],L))return Y;return-1}function f7(S,L,Y){var ce=L(S);return io(S)?ce:$e(ce,Y(S))}function Hi(S){return S==null?S===void 0?H:M:Ht&&Ht in Object(S)?v7(S):I7(S)}function Pd(S){return zi(S)&&Hi(S)==a}function Td(S,L,Y,ce,We){return S===L?!0:S==null||L==null||!zi(S)&&!zi(L)?S!==S&&L!==L:p7(S,L,Y,ce,Td,We)}function p7(S,L,Y,ce,We,Ie){var Qe=io(S),_t=io(L),St=Qe?c:Ir(S),Ye=_t?c:Ir(L);St=St==a?x:St,Ye=Ye==a?x:Ye;var zt=St==x,Xt=Ye==x,Dt=St==Ye;if(Dt&&Mc(S)){if(!Mc(L))return!1;Qe=!0,zt=!1}if(Dt&&!zt)return Ie||(Ie=new Sr),Qe||Bd(S)?Nd(S,L,Y,ce,We,Ie):b7(S,L,St,Y,ce,We,Ie);if(!(Y&i)){var Gt=zt&&v.call(S,"__wrapped__"),Zt=Xt&&v.call(L,"__wrapped__");if(Gt||Zt){var Dr=Gt?S.value():S,pr=Zt?L.value():L;return Ie||(Ie=new Sr),We(Dr,pr,Y,ce,Ie)}}return Dt?(Ie||(Ie=new Sr),y7(S,L,Y,ce,We,Ie)):!1}function g7(S){if(!Fd(S)||C7(S))return!1;var L=Md(S)?k:ee;return L.test(nn(S))}function m7(S){return zi(S)&&Ud(S.length)&&!!ae[Hi(S)]}function w7(S){if(!S7(S))return eo(S);var L=[];for(var Y in Object(S))v.call(S,Y)&&Y!="constructor"&&L.push(Y);return L}function Nd(S,L,Y,ce,We,Ie){var Qe=Y&i,_t=S.length,St=L.length;if(_t!=St&&!(Qe&&St>_t))return!1;var Ye=Ie.get(S);if(Ye&&Ie.get(L))return Ye==L;var zt=-1,Xt=!0,Dt=Y&s?new to:void 0;for(Ie.set(S,L),Ie.set(L,S);++zt<_t;){var Gt=S[zt],Zt=L[zt];if(ce)var Dr=Qe?ce(Zt,Gt,zt,L,S,Ie):ce(Gt,Zt,zt,S,L,Ie);if(Dr!==void 0){if(Dr)continue;Xt=!1;break}if(Dt){if(!Me(L,function(pr,sn){if(!Pe(Dt,sn)&&(Gt===pr||We(Gt,pr,Y,ce,Ie)))return Dt.push(sn)})){Xt=!1;break}}else if(!(Gt===Zt||We(Gt,Zt,Y,ce,Ie))){Xt=!1;break}}return Ie.delete(S),Ie.delete(L),Xt}function b7(S,L,Y,ce,We,Ie,Qe){switch(Y){case X:if(S.byteLength!=L.byteLength||S.byteOffset!=L.byteOffset)return!1;S=S.buffer,L=L.buffer;case q:return!(S.byteLength!=L.byteLength||!Ie(new Ne(S),new Ne(L)));case p:case m:case N:return Ld(+S,+L);case b:return S.name==L.name&&S.message==L.message;case I:case h:return S==L+"";case A:var _t=me;case O:var St=ce&i;if(_t||(_t=Oe),S.size!=L.size&&!St)return!1;var Ye=Qe.get(S);if(Ye)return Ye==L;ce|=s,Qe.set(S,L);var zt=Nd(_t(S),_t(L),ce,We,Ie,Qe);return Qe.delete(S),zt;case _:if(ot)return ot.call(S)==ot.call(L)}return!1}function y7(S,L,Y,ce,We,Ie){var Qe=Y&i,_t=Rd(S),St=_t.length,Ye=Rd(L),zt=Ye.length;if(St!=zt&&!Qe)return!1;for(var Xt=St;Xt--;){var Dt=_t[Xt];if(!(Qe?Dt in L:v.call(L,Dt)))return!1}var Gt=Ie.get(S);if(Gt&&Ie.get(L))return Gt==L;var Zt=!0;Ie.set(S,L),Ie.set(L,S);for(var Dr=Qe;++Xt<St;){Dt=_t[Xt];var pr=S[Dt],sn=L[Dt];if(ce)var jd=Qe?ce(sn,pr,Dt,L,S,Ie):ce(pr,sn,Dt,S,L,Ie);if(!(jd===void 0?pr===sn||We(pr,sn,Y,ce,Ie):jd)){Zt=!1;break}Dr||(Dr=Dt=="constructor")}if(Zt&&!Dr){var so=S.constructor,oo=L.constructor;so!=oo&&"constructor"in S&&"constructor"in L&&!(typeof so=="function"&&so instanceof so&&typeof oo=="function"&&oo instanceof oo)&&(Zt=!1)}return Ie.delete(S),Ie.delete(L),Zt}function Rd(S){return f7(S,$7,_7)}function no(S,L){var Y=S.__data__;return x7(L)?Y[typeof L=="string"?"string":"hash"]:Y.map}function Tn(S,L){var Y=De(S,L);return g7(Y)?Y:void 0}function v7(S){var L=v.call(S,Ht),Y=S[Ht];try{S[Ht]=void 0;var ce=!0}catch{}var We=U.call(S);return ce&&(L?S[Ht]=Y:delete S[Ht]),We}var _7=tn?function(S){return S==null?[]:(S=Object(S),Le(tn(S),function(L){return Fe.call(S,L)}))}:P7,Ir=Hi;(rt&&Ir(new rt(new ArrayBuffer(1)))!=X||Je&&Ir(new Je)!=A||nt&&Ir(nt.resolve())!=D||it&&Ir(new it)!=O||st&&Ir(new st)!=j)&&(Ir=function(S){var L=Hi(S),Y=L==x?S.constructor:void 0,ce=Y?nn(Y):"";if(ce)switch(ce){case pt:return X;case gt:return A;case mt:return D;case wt:return O;case bt:return j}return L});function E7(S,L){return L=L??o,!!L&&(typeof S=="number"||pe.test(S))&&S>-1&&S%1==0&&S<L}function x7(S){var L=typeof S;return L=="string"||L=="number"||L=="symbol"||L=="boolean"?S!=="__proto__":S===null}function C7(S){return!!T&&T in S}function S7(S){var L=S&&S.constructor,Y=typeof L=="function"&&L.prototype||g;return S===Y}function I7(S){return U.call(S)}function nn(S){if(S!=null){try{return d.call(S)}catch{}try{return S+""}catch{}}return""}function Ld(S,L){return S===L||S!==S&&L!==L}var D7=Pd(function(){return arguments}())?Pd:function(S){return zi(S)&&v.call(S,"callee")&&!Fe.call(S,"callee")},io=Array.isArray;function O7(S){return S!=null&&Ud(S.length)&&!Md(S)}var Mc=ki||T7;function A7(S,L){return Td(S,L)}function Md(S){if(!Fd(S))return!1;var L=Hi(S);return L==w||L==E||L==l||L==y}function Ud(S){return typeof S=="number"&&S>-1&&S%1==0&&S<=o}function Fd(S){var L=typeof S;return S!=null&&(L=="object"||L=="function")}function zi(S){return S!=null&&typeof S=="object"}var Bd=Ee?Ke(Ee):m7;function $7(S){return O7(S)?d7(S):w7(S)}function P7(){return[]}function T7(){return!1}t.exports=A7})(la,la.exports);var d5=la.exports,f5=Object.defineProperty,ih=Object.getOwnPropertySymbols,p5=Object.prototype.hasOwnProperty,g5=Object.prototype.propertyIsEnumerable,sh=(t,e,r)=>e in t?f5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$t=(t,e)=>{for(var r in e||(e={}))p5.call(e,r)&&sh(t,r,e[r]);if(ih)for(var r of ih(e))g5.call(e,r)&&sh(t,r,e[r]);return t};function m5(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),p=Math.log(256)/Math.log(a);function m(E){if(E instanceof Uint8Array||(ArrayBuffer.isView(E)?E=new Uint8Array(E.buffer,E.byteOffset,E.byteLength):Array.isArray(E)&&(E=Uint8Array.from(E))),!(E instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(E.length===0)return"";for(var A=0,N=0,M=0,x=E.length;M!==x&&E[M]===0;)M++,A++;for(var D=(x-M)*p+1>>>0,y=new Uint8Array(D);M!==x;){for(var I=E[M],O=0,h=D-1;(I!==0||O<N)&&h!==-1;h--,O++)I+=256*y[h]>>>0,y[h]=I%a>>>0,I=I/a>>>0;if(I!==0)throw new Error("Non-zero carry");N=O,M++}for(var _=D-N;_!==D&&y[_]===0;)_++;for(var H=c.repeat(A);_<D;++_)H+=t.charAt(y[_]);return H}function b(E){if(typeof E!="string")throw new TypeError("Expected String");if(E.length===0)return new Uint8Array;var A=0;if(E[A]!==" "){for(var N=0,M=0;E[A]===c;)N++,A++;for(var x=(E.length-A)*l+1>>>0,D=new Uint8Array(x);E[A];){var y=r[E.charCodeAt(A)];if(y===255)return;for(var I=0,O=x-1;(y!==0||I<M)&&O!==-1;O--,I++)y+=a*D[O]>>>0,D[O]=y%256>>>0,y=y/256>>>0;if(y!==0)throw new Error("Non-zero carry");M=I,A++}if(E[A]!==" "){for(var h=x-M;h!==x&&D[h]===0;)h++;for(var _=new Uint8Array(N+(x-h)),H=N;h!==x;)_[H++]=D[h++];return _}}}function w(E){var A=b(E);if(A)return A;throw new Error(`Non-${e} character`)}return{encode:m,decodeUnsafe:b,decode:w}}var w5=m5,b5=w5;const oh=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")},y5=t=>new TextEncoder().encode(t),v5=t=>new TextDecoder().decode(t);class _5{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class E5{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ah(this,e)}}class x5{constructor(e){this.decoders=e}or(e){return ah(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const ah=(t,e)=>new x5($t($t({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class C5{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new _5(e,r,n),this.decoder=new E5(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const hs=({name:t,prefix:e,encode:r,decode:n})=>new C5(t,e,r,n),oi=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=b5(r,e);return hs({prefix:t,name:e,encode:n,decode:s=>oh(i(s))})},S5=(t,e,r,n)=>{const i={};for(let p=0;p<e.length;++p)i[e[p]]=p;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,l=0;for(let p=0;p<s;++p){const m=i[t[p]];if(m===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|m,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},I5=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},Ct=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>hs({prefix:e,name:t,encode(i){return I5(i,n,r)},decode(i){return S5(i,n,r,t)}}),D5=hs({prefix:"\0",name:"identity",encode:t=>v5(t),decode:t=>y5(t)});var O5=Object.freeze({__proto__:null,identity:D5});const A5=Ct({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var $5=Object.freeze({__proto__:null,base2:A5});const P5=Ct({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var T5=Object.freeze({__proto__:null,base8:P5});const N5=oi({prefix:"9",name:"base10",alphabet:"0123456789"});var R5=Object.freeze({__proto__:null,base10:N5});const L5=Ct({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),M5=Ct({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var U5=Object.freeze({__proto__:null,base16:L5,base16upper:M5});const F5=Ct({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),B5=Ct({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),j5=Ct({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),k5=Ct({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),H5=Ct({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),z5=Ct({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),W5=Ct({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),q5=Ct({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),V5=Ct({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var K5=Object.freeze({__proto__:null,base32:F5,base32upper:B5,base32pad:j5,base32padupper:k5,base32hex:H5,base32hexupper:z5,base32hexpad:W5,base32hexpadupper:q5,base32z:V5});const G5=oi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Z5=oi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Y5=Object.freeze({__proto__:null,base36:G5,base36upper:Z5});const J5=oi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),X5=oi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Q5=Object.freeze({__proto__:null,base58btc:J5,base58flickr:X5});const ew=Ct({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),tw=Ct({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),rw=Ct({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),nw=Ct({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var iw=Object.freeze({__proto__:null,base64:ew,base64pad:tw,base64url:rw,base64urlpad:nw});const ch=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}"),sw=ch.reduce((t,e,r)=>(t[r]=e,t),[]),ow=ch.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function aw(t){return t.reduce((e,r)=>(e+=sw[r],e),"")}function cw(t){const e=[];for(const r of t){const n=ow[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const lw=hs({prefix:"\u{1F680}",name:"base256emoji",encode:aw,decode:cw});var uw=Object.freeze({__proto__:null,base256emoji:lw}),hw=uh,lh=128,dw=127,fw=~dw,pw=Math.pow(2,31);function uh(t,e,r){e=e||[],r=r||0;for(var n=r;t>=pw;)e[r++]=t&255|lh,t/=128;for(;t&fw;)e[r++]=t&255|lh,t>>>=7;return e[r]=t|0,uh.bytes=r-n+1,e}var gw=ua,mw=128,hh=127;function ua(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw ua.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&hh)<<i:(o&hh)*Math.pow(2,i),i+=7}while(o>=mw);return ua.bytes=s-n,r}var ww=Math.pow(2,7),bw=Math.pow(2,14),yw=Math.pow(2,21),vw=Math.pow(2,28),_w=Math.pow(2,35),Ew=Math.pow(2,42),xw=Math.pow(2,49),Cw=Math.pow(2,56),Sw=Math.pow(2,63),Iw=function(t){return t<ww?1:t<bw?2:t<yw?3:t<vw?4:t<_w?5:t<Ew?6:t<xw?7:t<Cw?8:t<Sw?9:10},Dw={encode:hw,decode:gw,encodingLength:Iw},dh=Dw;const fh=(t,e,r=0)=>(dh.encode(t,e,r),e),ph=t=>dh.encodingLength(t),ha=(t,e)=>{const r=e.byteLength,n=ph(t),i=n+ph(r),s=new Uint8Array(i+r);return fh(t,s,0),fh(r,s,n),s.set(e,i),new Ow(t,r,e,s)};class Ow{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const gh=({name:t,code:e,encode:r})=>new Aw(t,e,r);class Aw{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?ha(this.code,r):r.then(n=>ha(this.code,n))}else throw Error("Unknown type, must be binary type")}}const mh=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),$w=gh({name:"sha2-256",code:18,encode:mh("SHA-256")}),Pw=gh({name:"sha2-512",code:19,encode:mh("SHA-512")});var Tw=Object.freeze({__proto__:null,sha256:$w,sha512:Pw});const wh=0,Nw="identity",bh=oh;var Rw=Object.freeze({__proto__:null,identity:{code:wh,name:Nw,encode:bh,digest:t=>ha(wh,bh(t))}});new TextEncoder,new TextDecoder;const yh=$t($t($t($t($t($t($t($t($t($t({},O5),$5),T5),R5),U5),K5),Y5),Q5),iw),uw);$t($t({},Tw),Rw);function Lw(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function vh(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const _h=vh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),da=vh("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=Lw(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Mw=$t({utf8:_h,"utf-8":_h,hex:yh.base16,latin1:da,ascii:da,binary:da},yh);function Uw(t,e="utf8"){const r=Mw[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}const Eh="wc",Fw=2,fa="core",br=`${Eh}@${2}:${fa}:`,Bw={name:fa,logger:"error"},jw={database:":memory:"},kw="crypto",xh="client_ed25519_seed",Hw=de.ONE_DAY,zw="keychain",Ww="0.3",qw="messages",Vw="0.3",Kw=de.SIX_HOURS,Gw="publisher",Ch="irn",Zw="error",Sh="wss://relay.walletconnect.com",Yw="relayer",dt={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"},Jw="_subscription",ds={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Ih=de.ONE_SECOND,Xw="2.4.7",Qw="0.3",rr={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},eb="subscription",tb="0.3",rb=de.FIVE_SECONDS*1e3,nb="pairing",ib="0.3",ai={wc_pairingDelete:{req:{ttl:de.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:de.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:de.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:de.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:de.ONE_DAY,prompt:!1,tag:0},res:{ttl:de.ONE_DAY,prompt:!1,tag:0}}},nr={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},sb="history",ob="0.3",ab="expirer",Wt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},cb="0.3";class lb{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=zw,this.version=Ww,this.initialized=!1,this.storagePrefix=br,this.init=async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=se("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=je.generateChildLogger(r,this.name)}get context(){return je.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,iu(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?su(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}}class ub{constructor(e,r,n){this.core=e,this.logger=r,this.name=kw,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(),s=Wu(i);return zu(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const i=hg();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const s=await this.getClientSeed(),o=Wu(s),a=Ro();return await Em(a,i,Hw,o)},this.generateSharedKey=(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=dg(a,s);return this.setSymKey(c,o)},this.setSymKey=async(i,s)=>{this.isInitialized();const o=s||Jl(i);return await this.keychain.set(o,i),o},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,s,o)=>{this.isInitialized();const a=Xl(o),c=ri(s);if(Ql(a)){const b=a.senderPublicKey,w=a.receiverPublicKey;i=await this.generateSharedKey(b,w)}const l=this.getSymKey(i),{type:p,senderPublicKey:m}=a;return pg({type:p,symKey:l,message:c,senderPublicKey:m})},this.decode=async(i,s,o)=>{this.isInitialized();const a=wg(s,o);if(Ql(a)){const p=a.receiverPublicKey,m=a.senderPublicKey;i=await this.generateSharedKey(p,m)}const c=this.getSymKey(i),l=gg({symKey:c,encoded:s});return ea(l)},this.core=e,this.logger=je.generateChildLogger(r,this.name),this.keychain=n||new lb(this.core,this.logger)}get context(){return je.getLoggerContext(this.logger)}getPayloadType(e){const r=Lo(e);return Bn(r.type)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(xh)}catch{e=Ro(),await this.keychain.set(xh,e)}return Uw(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}}class hb extends tm{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=qw,this.version=Vw,this.initialized=!1,this.storagePrefix=br,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();const s=ts(i);let o=this.messages.get(n);return typeof o>"u"&&(o={}),typeof o[s]<"u"||(o[s]=i,this.messages.set(n,o),await this.persist()),s},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();const s=this.get(n),o=ts(i);return typeof s[o]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=je.generateChildLogger(e,this.name),this.core=r}get context(){return je.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,iu(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?su(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}}class db extends rm{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new Et.exports.EventEmitter,this.name=Gw,this.queue=new Map,this.publishTimeout=1e4,this.publish=async(n,i,s)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});try{const o=s?.ttl||Kw,a=Uo(s),c=s?.prompt||!1,l=s?.tag||0,p={topic:n,message:i,opts:{ttl:o,relay:a,prompt:c,tag:l}},m=ts(i);this.queue.set(m,p);try{await await Mo(this.rpcPublish(n,i,o,a,c,l),this.publishTimeout),this.relayer.events.emit(dt.publish,p)}catch{this.logger.debug("Publishing Payload stalled"),this.relayer.events.emit(dt.connection_stalled);return}this.onPublish(m,p),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}})}catch(o){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(o),o}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=je.generateChildLogger(r,this.name),this.registerEventListeners()}get context(){return je.getLoggerContext(this.logger)}rpcPublish(e,r,n,i,s,o){var a,c,l,p;const m={method:rs(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:s,tag:o}};return Ot((a=m.params)==null?void 0:a.prompt)&&((c=m.params)==null||delete c.prompt),Ot((l=m.params)==null?void 0:l.tag)&&((p=m.params)==null||delete p.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:m}),this.relayer.provider.request(m)}onPublish(e,r){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(Jn.HEARTBEAT_EVENTS.pulse,()=>{this.checkQueue()})}}class fb{constructor(){this.map=new Map,this.set=(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var pb=Object.defineProperty,gb=Object.defineProperties,mb=Object.getOwnPropertyDescriptors,Dh=Object.getOwnPropertySymbols,wb=Object.prototype.hasOwnProperty,bb=Object.prototype.propertyIsEnumerable,Oh=(t,e,r)=>e in t?pb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ci=(t,e)=>{for(var r in e||(e={}))wb.call(e,r)&&Oh(t,r,e[r]);if(Dh)for(var r of Dh(e))bb.call(e,r)&&Oh(t,r,e[r]);return t},pa=(t,e)=>gb(t,mb(e));class yb extends sm{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new fb,this.events=new Et.exports.EventEmitter,this.name=eb,this.version=tb,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=br,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restart(),this.registerEventListeners(),this.onEnable(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const s=Uo(i),o={topic:n,relay:s};this.pending.set(n,o);const a=await this.rpcSubscribe(n,s);return this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}}),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>this.topics.includes(n)?!0:await new Promise((i,s)=>{const o=new de.Watch;o.start(this.pendingSubscriptionWatchLabel);const a=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(a),o.stop(this.pendingSubscriptionWatchLabel),i(!0)),o.elapsed(this.pendingSubscriptionWatchLabel)>=rb&&(clearInterval(a),o.stop(this.pendingSubscriptionWatchLabel),s(!1))},this.pollingInterval)}),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=je.generateChildLogger(r,this.name),this.clientId=""}get context(){return je.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear(),this.initialized=!1}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=Uo(n);await this.rpcUnsubscribe(e,r,i);const s=tt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){const n={method:rs(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await Mo(this.relayer.provider.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(dt.connection_stalled)}return ts(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:rs(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await await Mo(this.relayer.provider.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(dt.connection_stalled)}}rpcUnsubscribe(e,r,n){const i={method:rs(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.provider.request(i)}onSubscribe(e,r){this.setSubscription(e,pa(ci({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,ci({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r))}addSubscription(e,r){this.subscriptions.set(e,ci({},r)),this.topicMap.set(r.topic,e),this.events.emit(rr.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=se("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(rr.deleted,pa(ci({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(rr.sync)}async reset(){if(!this.cached.length)return;const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<e;r++){const n=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}this.events.emit(rr.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;const r=await this.rpcBatchSubscribe(e);this.onBatchSubscribe(r.map((n,i)=>pa(ci({},e[i]),{id:n})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(Jn.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(dt.connect,async()=>{await this.onConnect()}),this.relayer.on(dt.disconnect,()=>{this.onDisconnect()}),this.events.on(rr.created,async e=>{const r=rr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(rr.deleted,async e=>{const r=rr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}}var vb=Object.defineProperty,Ah=Object.getOwnPropertySymbols,_b=Object.prototype.hasOwnProperty,Eb=Object.prototype.propertyIsEnumerable,$h=(t,e,r)=>e in t?vb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xb=(t,e)=>{for(var r in e||(e={}))_b.call(e,r)&&$h(t,r,e[r]);if(Ah)for(var r of Ah(e))Eb.call(e,r)&&$h(t,r,e[r]);return t};class Cb extends nm{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new Et.exports.EventEmitter,this.name=Yw,this.transportExplicitlyClosed=!1,this.initialized=!1,this.reconnecting=!1,this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?je.generateChildLogger(e.logger,this.name):zn(je.getDefaultLoggerOptions({level:e.logger||Zw})),this.messages=new hb(this.logger,e.core),this.subscriber=new yb(this,this.logger),this.publisher=new db(this,this.logger),this.relayUrl=e?.relayUrl||Sh,this.projectId=e.projectId,this.provider={}}async init(){this.logger.trace("Initialized"),this.provider=await this.createProvider(),await Promise.all([this.messages.init(),this.transportOpen(),this.subscriber.init()]),this.registerEventListeners(),this.initialized=!0}get context(){return je.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){this.isInitialized();let n="";return await Promise.all([new Promise(i=>{this.subscriber.once(rr.created,s=>{s.topic===e&&i()})}),new Promise(async i=>{n=await this.subscriber.subscribe(e,r),i()})]),n}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportClose(){this.transportExplicitlyClosed=!0,this.connected&&(await this.provider.disconnect(),this.events.emit(dt.transport_closed))}async transportOpen(e){if(!this.reconnecting){this.relayUrl=e||this.relayUrl,this.transportExplicitlyClosed=!1,this.reconnecting=!0;try{await Promise.all([new Promise(r=>{this.initialized||r(),this.subscriber.once(rr.resubscribed,()=>{r()})}),await Promise.race([new Promise(async r=>{await this.provider.connect(),this.removeListener(dt.transport_closed,this.rejectTransportOpen),r()}),new Promise(r=>this.once(dt.transport_closed,this.rejectTransportOpen))])])}catch(r){const n=r;if(!/socket hang up/i.test(n.message))throw r;this.logger.error(r),this.events.emit(dt.transport_closed)}finally{this.reconnecting=!1}}}async restartTransport(e){this.transportExplicitlyClosed||(await this.transportClose(),await new Promise(r=>setTimeout(r,Ih)),await this.transportOpen(e))}rejectTransportOpen(){throw new Error("closeTransport called before connection was established")}async createProvider(){const e=await this.core.crypto.signJWT(this.relayUrl);return new si(new h5(Pg({sdkVersion:Xw,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e})))}async recordMessageEvent(e){const{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;return await this.subscriber.isSubscribed(r)?this.messages.has(r,n):!0}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),aa(e)){if(!e.method.endsWith(Jw))return;const r=e.params,{topic:n,message:i,publishedAt:s}=r.data,o={topic:n,message:i,publishedAt:s};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(xb({type:"event",event:r.id},o)),this.events.emit(r.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(dt.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=oa(e.id,!0);await this.provider.connection.send(r)}registerEventListeners(){this.provider.on(ds.payload,e=>this.onProviderPayload(e)),this.provider.on(ds.connect,()=>{this.events.emit(dt.connect)}),this.provider.on(ds.disconnect,()=>{this.events.emit(dt.disconnect),this.attemptToReconnect()}),this.provider.on(ds.error,e=>this.events.emit(dt.error,e)),this.events.on(dt.connection_stalled,async()=>{await this.restartTransport()})}attemptToReconnect(){this.transportExplicitlyClosed||setTimeout(async()=>{await this.transportOpen()},de.toMiliseconds(Ih))}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Sb=Object.defineProperty,Ph=Object.getOwnPropertySymbols,Ib=Object.prototype.hasOwnProperty,Db=Object.prototype.propertyIsEnumerable,Th=(t,e,r)=>e in t?Sb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nh=(t,e)=>{for(var r in e||(e={}))Ib.call(e,r)&&Th(t,r,e[r]);if(Ph)for(var r of Ph(e))Db.call(e,r)&&Th(t,r,e[r]);return t};class fs extends im{constructor(e,r,n,i=br,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=Qw,this.cached=[],this.initialized=!1,this.storagePrefix=br,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{Xg(o)?this.map.set(o.id,o):Qg(o)?this.map.set(o.topic,o):this.getKey&&o!==null&&!Ot(o)&&this.map.set(this.getKey(o),o)}),this.cached=[],this.initialized=!0)},this.set=async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())},this.get=o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o)),this.getAll=o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>d5(a[c],o[c]))):this.values),this.update=async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Nh(Nh({},this.getData(o)),a);this.map.set(o,c),await this.persist()},this.delete=async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),await this.persist())},this.logger=je.generateChildLogger(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return je.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){const{message:n}=se("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Ob{constructor(e,r){this.core=e,this.logger=r,this.name=nb,this.version=ib,this.events=new Et.exports,this.initialized=!1,this.storagePrefix=br,this.ignoredPayloadTypes=[Tr],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async()=>{this.isInitialized();const n=Ro(),i=await this.core.crypto.setSymKey(n),s=er(de.FIVE_MINUTES),o={protocol:Ch},a={topic:i,expiry:s,relay:o,active:!1},c=Hg({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:n,relay:o});return await this.pairings.set(i,a),await this.core.relayer.subscribe(i),this.core.expirer.set(i,s),{topic:i,uri:c}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);const{topic:i,symKey:s,relay:o}=jg(n.uri),a=er(de.FIVE_MINUTES),c={topic:i,relay:o,expiry:a,active:!1};return await this.pairings.set(i,c),await this.core.crypto.setSymKey(s,i),await this.core.relayer.subscribe(i,{relay:o}),this.core.expirer.set(i,a),n.activatePairing&&await this.activate({topic:i}),c},this.activate=async({topic:n})=>{this.isInitialized();const i=er(de.THIRTY_DAYS);await this.pairings.update(n,{active:!0,expiry:i}),this.core.expirer.set(n,i)},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n);const{topic:i}=n;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Rr();this.events.once(et("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",tt("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,s)=>{const o=ls(i,s),a=await this.core.crypto.encode(n,o),c=ai[i].req;return this.core.history.set(n,o),await this.core.relayer.publish(n,a,c),o.id},this.sendResult=async(n,i,s)=>{const o=oa(n,s),a=await this.core.crypto.encode(i,o),c=await this.core.history.get(i,n),l=ai[c.request.method].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)},this.sendError=async(n,i,s)=>{const o=us(n,s),a=await this.core.crypto.encode(i,o),c=await this.core.history.get(i,n),l=ai[c.request.method]?ai[c.request.method].res:ai.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,tt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{const n=this.pairings.getAll().filter(i=>mr(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{const{topic:i,payload:s}=n,o=s.method;if(this.pairings.keys.includes(i))switch(o){case"wc_pairingPing":return this.onPairingPingRequest(i,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,s);default:return this.onUnknownRpcMethodRequest(i,s)}},this.onRelayEventResponse=async n=>{const{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;if(this.pairings.keys.includes(i))switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}},this.onPairingPingRequest=async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit("pairing_ping",{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onPairingPingResponse=(n,i)=>{const{id:s}=i;setTimeout(()=>{hr(i)?this.events.emit(et("pairing_ping",s),{}):Jt(i)&&this.events.emit(et("pairing_ping",s),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit("pairing_delete",{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}},this.onUnknownRpcMethodRequest=async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=tt("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(tt("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{if(!Rt(n)){const{message:i}=se("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(i)}if(!Jg(n.uri)){const{message:i}=se("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(i)}},this.isValidPing=async n=>{if(!Rt(n)){const{message:s}=se("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!Rt(n)){const{message:s}=se("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!ht(n,!1)){const{message:i}=se("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=se("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(mr(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=se("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=je.generateChildLogger(r,this.name),this.pairings=new fs(this.core,this.logger,this.name,this.storagePrefix)}get context(){return je.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(dt.message,async e=>{const{topic:r,message:n}=e;if(this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;const i=await this.core.crypto.decode(r,n);aa(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):ca(i)&&(await this.core.history.resolve(i),this.onRelayEventResponse({topic:r,payload:i}))})}registerExpirerEvents(){this.core.expirer.on(Wt.expired,async e=>{const{topic:r}=au(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit("pairing_expire",{topic:r}))})}}class Ab extends em{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new Et.exports.EventEmitter,this.name=sb,this.version=ob,this.cached=[],this.initialized=!1,this.storagePrefix=br,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s};this.records.set(o.id,o),this.events.emit(nr.created,o)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=Jt(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.events.emit(nr.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(nr.deleted,s)}})},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=je.generateChildLogger(r,this.name)}get context(){return je.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:ls(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:n}=se("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(nr.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(nr.created,e=>{const r=nr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(nr.updated,e=>{const r=nr.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(nr.deleted,e=>{const r=nr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}}class $b extends om{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new Et.exports.EventEmitter,this.name=ab,this.version=cb,this.cached=[],this.initialized=!1,this.storagePrefix=br,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();const s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Wt.created,{target:s,expiration:o})},this.get=n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Wt.deleted,{target:i,expiration:s})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=je.generateChildLogger(r,this.name)}get context(){return je.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 Tg(e);if(typeof e=="number")return Ng(e);const{message:r}=se("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Wt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:n}=se("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;de.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Wt.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Jn.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(Wt.created,e=>{const r=Wt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Wt.expired,e=>{const r=Wt.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Wt.deleted,e=>{const r=Wt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Pb=Object.defineProperty,Rh=Object.getOwnPropertySymbols,Tb=Object.prototype.hasOwnProperty,Nb=Object.prototype.propertyIsEnumerable,Lh=(t,e,r)=>e in t?Pb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mh=(t,e)=>{for(var r in e||(e={}))Tb.call(e,r)&&Lh(t,r,e[r]);if(Rh)for(var r of Rh(e))Nb.call(e,r)&&Lh(t,r,e[r]);return t};class ga extends Q3{constructor(e){super(e),this.protocol=Eh,this.version=Fw,this.name=fa,this.events=new Et.exports.EventEmitter,this.initialized=!1,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Sh;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:zn(je.getDefaultLoggerOptions({level:e?.logger||Bw.logger}));this.logger=je.generateChildLogger(r,this.name),this.heartbeat=new Jn.HeartBeat,this.crypto=new ub(this,this.logger,e?.keychain),this.history=new Ab(this,this.logger),this.expirer=new $b(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new s3(Mh(Mh({},jw),e?.storageOptions)),this.relayer=new Cb({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Ob(this,this.logger)}static async init(e){const r=new ga(e);return await r.initialize(),r}get context(){return je.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 Rb=ga,Uh="wc",Fh=2,Bh="client",ma=`${Uh}@${Fh}:${Bh}:`,wa={name:Bh,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},Lb="proposal",jh="Proposal expired",Mb="session",ps=de.SEVEN_DAYS,Ub="engine",li={wc_sessionPropose:{req:{ttl:de.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:de.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:de.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:de.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:de.ONE_DAY,prompt:!1,tag:1104},res:{ttl:de.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:de.ONE_DAY,prompt:!1,tag:1106},res:{ttl:de.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:de.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:de.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:de.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:de.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:de.ONE_DAY,prompt:!1,tag:1112},res:{ttl:de.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:de.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:de.THIRTY_SECONDS,prompt:!1,tag:1115}}},ba={min:de.FIVE_MINUTES,max:de.SEVEN_DAYS},Fb="request";var Bb=Object.defineProperty,jb=Object.defineProperties,kb=Object.getOwnPropertyDescriptors,kh=Object.getOwnPropertySymbols,Hb=Object.prototype.hasOwnProperty,zb=Object.prototype.propertyIsEnumerable,Hh=(t,e,r)=>e in t?Bb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qt=(t,e)=>{for(var r in e||(e={}))Hb.call(e,r)&&Hh(t,r,e[r]);if(kh)for(var r of kh(e))zb.call(e,r)&&Hh(t,r,e[r]);return t},ya=(t,e)=>jb(t,kb(e));class Wb extends cm{constructor(e){super(e),this.name=Ub,this.events=new Et.exports,this.initialized=!1,this.ignoredPayloadTypes=[Tr],this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.client.core.pairing.register({methods:Object.keys(li)}),this.initialized=!0)},this.connect=async r=>{this.isInitialized();const n=ya(qt({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,relays:c}=n;let l=i,p,m=!1;if(l&&(m=this.client.core.pairing.pairings.get(l).active),!l||!m){const{topic:D,uri:y}=await this.client.core.pairing.create();l=D,p=y}const b=await this.client.core.crypto.generateKeyPair(),w=qt({requiredNamespaces:s,optionalNamespaces:o,relays:c??[{protocol:Ch}],proposer:{publicKey:b,metadata:this.client.metadata}},a&&{sessionProperties:a}),{reject:E,resolve:A,done:N}=Rr(de.FIVE_MINUTES,jh);if(this.events.once(et("session_connect"),async({error:D,session:y})=>{if(D)E(D);else if(y){y.self.publicKey=b;const I=ya(qt({},y),{requiredNamespaces:y.requiredNamespaces,optionalNamespaces:y.optionalNamespaces});await this.client.session.set(y.topic,I),await this.setExpiry(y.topic,y.expiry),l&&await this.client.core.pairing.updateMetadata({topic:l,metadata:y.peer.metadata}),A(I)}}),!l){const{message:D}=se("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(D)}const M=await this.sendRequest(l,"wc_sessionPropose",w),x=er(de.FIVE_MINUTES);return await this.setProposal(M,qt({id:M,expiry:x},w)),{uri:p,approval:N}},this.pair=async r=>(this.isInitialized(),await this.client.core.pairing.pair(r)),this.approve=async r=>{this.isInitialized(),await this.isValidApprove(r);const{id:n,relayProtocol:i,namespaces:s,sessionProperties:o}=r,a=this.client.proposal.get(n);let{pairingTopic:c,proposer:l,requiredNamespaces:p,optionalNamespaces:m}=a;Hn(p)||(p=Vg(s,"approve()"));const b=await this.client.core.crypto.generateKeyPair(),w=l.publicKey,E=await this.client.core.crypto.generateSharedKey(b,w);c&&n&&(await this.client.core.pairing.updateMetadata({topic:c,metadata:l.metadata}),await this.sendResult(n,c,{relay:{protocol:i??"irn"},responderPublicKey:b}),await this.client.proposal.delete(n,tt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:c}));const A=qt({relay:{protocol:i??"irn"},namespaces:s,requiredNamespaces:p,optionalNamespaces:m,controller:{publicKey:b,metadata:this.client.metadata},expiry:er(ps)},o&&{sessionProperties:o});await this.client.core.relayer.subscribe(E);const N=await this.sendRequest(E,"wc_sessionSettle",A),{done:M,resolve:x,reject:D}=Rr();this.events.once(et("session_approve",N),({error:I})=>{I?D(I):x(this.client.session.get(E))});const y=ya(qt({},A),{topic:E,acknowledged:!1,self:A.controller,peer:{publicKey:l.publicKey,metadata:l.metadata},controller:b});return await this.client.session.set(E,y),await this.setExpiry(E,er(ps)),{topic:E,acknowledged:M}},this.reject=async r=>{this.isInitialized(),await this.isValidReject(r);const{id:n,reason:i}=r,{pairingTopic:s}=this.client.proposal.get(n);s&&(await this.sendError(n,s,i),await this.client.proposal.delete(n,tt("USER_DISCONNECTED")))},this.update=async r=>{this.isInitialized(),await this.isValidUpdate(r);const{topic:n,namespaces:i}=r,s=await this.sendRequest(n,"wc_sessionUpdate",{namespaces:i}),{done:o,resolve:a,reject:c}=Rr();return this.events.once(et("session_update",s),({error:l})=>{l?c(l):a()}),await this.client.session.update(n,{namespaces:i}),{acknowledged:o}},this.extend=async r=>{this.isInitialized(),await this.isValidExtend(r);const{topic:n}=r,i=await this.sendRequest(n,"wc_sessionExtend",{}),{done:s,resolve:o,reject:a}=Rr();return this.events.once(et("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,er(ps)),{acknowledged:s}},this.request=async r=>{this.isInitialized(),await this.isValidRequest(r);const{chainId:n,request:i,topic:s,expiry:o}=r,a=await this.sendRequest(s,"wc_sessionRequest",{request:i,chainId:n},o),{done:c,resolve:l,reject:p}=Rr(o);return this.events.once(et("session_request",a),({error:m,result:b})=>{m?p(m):l(b)}),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n}),await c()},this.respond=async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:s}=i;hr(i)?await this.sendResult(s,n,i.result):Jt(i)&&await this.sendError(s,n,i.error),this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0})},this.ping=async r=>{this.isInitialized(),await this.isValidPing(r);const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=await this.sendRequest(n,"wc_sessionPing",{}),{done:s,resolve:o,reject:a}=Rr();this.events.once(et("session_ping",i),({error:c})=>{c?a(c):o()}),await s()}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{this.isInitialized(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r;await this.sendRequest(n,"wc_sessionEvent",{event:i,chainId:s})},this.disconnect=async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:n}=r;this.client.session.keys.includes(n)?(await this.sendRequest(n,"wc_sessionDelete",tt("USER_DISCONNECTED")),await this.deleteSession(n)):await this.client.core.pairing.disconnect({topic:n})},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>Zg(n,r))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.deleteSession=async(r,n)=>{const{self:i}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await Promise.all([this.client.session.delete(r,tt("USER_DISCONNECTED")),this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.deleteSymKey(r),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,tt("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)])},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:n}),this.client.core.expirer.set(r,n)},this.setProposal=async(r,n)=>{await this.client.proposal.set(r,n),this.client.core.expirer.set(r,n.expiry)},this.setPendingSessionRequest=async r=>{const n=li.wc_sessionRequest.req.ttl,{id:i,topic:s,params:o}=r;await this.client.pendingRequest.set(i,{id:i,topic:s,params:o}),n&&this.client.core.expirer.set(i,er(n))},this.sendRequest=async(r,n,i,s)=>{const o=ls(n,i),a=await this.client.core.crypto.encode(r,o),c=li[n].req;return s&&(c.ttl=s),this.client.core.history.set(r,o),this.client.core.relayer.publish(r,a,c),o.id},this.sendResult=async(r,n,i)=>{const s=oa(r,i),o=await this.client.core.crypto.encode(n,s),a=await this.client.core.history.get(n,r),c=li[a.request.method].res;this.client.core.relayer.publish(n,o,c),await this.client.core.history.resolve(s)},this.sendError=async(r,n,i)=>{const s=us(r,i),o=await this.client.core.crypto.encode(n,s),a=await this.client.core.history.get(n,r),c=li[a.request.method].res;this.client.core.relayer.publish(n,o,c),await this.client.core.history.resolve(s)},this.cleanup=async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{mr(i.expiry)&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{mr(i.expiry)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession(i)),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=r=>{const{topic:n,payload:i}=r,s=i.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${s}`)}},this.onRelayEventResponse=async r=>{const{topic:n,payload:i}=r,s=(await this.client.core.history.get(n,i.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${s}`)}},this.onSessionProposeRequest=async(r,n)=>{const{params:i,id:s}=n;try{this.isValidConnect(qt({},n.params));const o=er(de.FIVE_MINUTES),a=qt({id:s,pairingTopic:r,expiry:o},i);await this.setProposal(s,a),this.client.events.emit("session_proposal",{id:s,params:a})}catch(o){await this.sendError(s,r,o),this.client.logger.error(o)}},this.onSessionProposeResponse=async(r,n)=>{const{id:i}=n;if(hr(n)){const{result:s}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});const o=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:o});const a=o.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:a});const c=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:c});const l=await this.client.core.crypto.generateSharedKey(a,c);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:l});const p=await this.client.core.relayer.subscribe(l);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:p}),await this.client.core.pairing.activate({topic:r})}else Jt(n)&&(await this.client.proposal.delete(i,tt("USER_DISCONNECTED")),this.events.emit(et("session_connect"),{error:n.error}))},this.onSessionSettleRequest=async(r,n)=>{const{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,requiredNamespaces:p,optionalNamespaces:m,sessionProperties:b}=n.params,w=qt({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,requiredNamespaces:p,optionalNamespaces:m,controller:a.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},b&&{sessionProperties:b});await this.sendResult(n.id,r,!0),this.events.emit(et("session_connect"),{session:w})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionSettleResponse=async(r,n)=>{const{id:i}=n;hr(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(et("session_approve",i),{})):Jt(n)&&(await this.client.session.delete(r,tt("USER_DISCONNECTED")),this.events.emit(et("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{const{params:i,id:s}=n;try{this.isValidUpdate(qt({topic:r},i)),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult(s,r,!0),this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError(s,r,o),this.client.logger.error(o)}},this.onSessionUpdateResponse=(r,n)=>{const{id:i}=n;hr(n)?this.events.emit(et("session_update",i),{}):Jt(n)&&this.events.emit(et("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,er(ps)),await this.sendResult(i,r,!0),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError(i,r,s),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,n)=>{const{id:i}=n;hr(n)?this.events.emit(et("session_extend",i),{}):Jt(n)&&this.events.emit(et("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult(i,r,!0),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError(i,r,s),this.client.logger.error(s)}},this.onSessionPingResponse=(r,n)=>{const{id:i}=n;setTimeout(()=>{hr(n)?this.events.emit(et("session_ping",i),{}):Jt(n)&&this.events.emit(et("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),this.client.core.relayer.once(dt.publish,async()=>{await this.deleteSession(r)}),await this.sendResult(i,r,!0),this.client.events.emit("session_delete",{id:i,topic:r})}catch(s){await this.sendError(i,r,s),this.client.logger.error(s)}},this.onSessionRequest=async(r,n)=>{const{id:i,params:s}=n;try{this.isValidRequest(qt({topic:r},s)),await this.setPendingSessionRequest({id:i,topic:r,params:s}),this.client.events.emit("session_request",{id:i,topic:r,params:s})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionRequestResponse=(r,n)=>{const{id:i}=n;hr(n)?this.events.emit(et("session_request",i),{result:n.result}):Jt(n)&&this.events.emit(et("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{const{id:i,params:s}=n;try{this.isValidEmit(qt({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.isValidConnect=async r=>{if(!Rt(r)){const{message:c}=se("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(c)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,relays:a}=r;if(Ot(n)||await this.isValidPairingTopic(n),!a2(a,!0)){const{message:c}=se("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(c)}!Ot(i)&&Hn(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Ot(s)&&Hn(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),Ot(o)||this.validateSessionProps(o,"sessionProperties")},this.validateNamespaces=(r,n)=>{const i=o2(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!Rt(r))throw new Error(se("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:s,sessionProperties:o}=r;await this.isValidProposalId(n);const a=this.client.proposal.get(n),c=ns(i,"approve()");if(c)throw new Error(c.message);const l=pu(a.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!ht(s,!0)){const{message:p}=se("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(p)}Ot(o)||this.validateSessionProps(o,"sessionProperties")},this.isValidReject=async r=>{if(!Rt(r)){const{message:s}=se("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(await this.isValidProposalId(n),!l2(i)){const{message:s}=se("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!Rt(r)){const{message:l}=se("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!du(n)){const{message:l}=se("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=e2(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=ns(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(mr(o)){const{message:l}=se("EXPIRED","onSessionSettleRequest()");throw new Error(l)}},this.isValidUpdate=async r=>{if(!Rt(r)){const{message:c}=se("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:n,namespaces:i}=r;await this.isValidSessionTopic(n);const s=this.client.session.get(n),o=ns(i,"update()");if(o)throw new Error(o.message);const a=pu(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)},this.isValidExtend=async r=>{if(!Rt(r)){const{message:i}=se("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!Rt(r)){const{message:c}=se("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:n,request:i,chainId:s,expiry:o}=r;await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!fu(a,s)){const{message:c}=se("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!u2(i)){const{message:c}=se("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!f2(a,s,i.method)){const{message:c}=se("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!w2(o,ba)){const{message:c}=se("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${ba.min} and ${ba.max}`);throw new Error(c)}},this.isValidRespond=async r=>{if(!Rt(r)){const{message:s}=se("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(s)}const{topic:n,response:i}=r;if(await this.isValidSessionTopic(n),!h2(i)){const{message:s}=se("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(s)}},this.isValidPing=async r=>{if(!Rt(r)){const{message:i}=se("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!Rt(r)){const{message:a}=se("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!fu(o,s)){const{message:a}=se("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!d2(i)){const{message:a}=se("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!p2(o,s,i.name)){const{message:a}=se("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}},this.isValidDisconnect=async r=>{if(!Rt(r)){const{message:i}=se("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!ht(i,!1)){const{message:s}=se("MISSING_OR_INVALID",`${n} must be in Record<string, string> format. Received: ${JSON.stringify(i)}`);throw new Error(s)}})}}isInitialized(){if(!this.initialized){const{message:e}=se("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.client.core.relayer.on(dt.message,async e=>{const{topic:r,message:n}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(n)))return;const i=await this.client.core.crypto.decode(r,n);aa(i)?(this.client.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):ca(i)&&(await this.client.core.history.resolve(i),this.onRelayEventResponse({topic:r,payload:i}))})}registerExpirerEvents(){this.client.core.expirer.on(Wt.expired,async e=>{const{topic:r,id:n}=au(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,se("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession(r,!0),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}isValidPairingTopic(e){if(!ht(e,!1)){const{message:r}=se("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=se("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(mr(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=se("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!ht(e,!1)){const{message:r}=se("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(!this.client.session.keys.includes(e)){const{message:r}=se("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(mr(this.client.session.get(e).expiry)){await this.deleteSession(e);const{message:r}=se("EXPIRED",`session topic: ${e}`);throw new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ht(e,!1)){const{message:r}=se("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=se("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!c2(e)){const{message:r}=se("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=se("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(mr(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:r}=se("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class qb extends fs{constructor(e,r){super(e,r,Lb,ma),this.core=e,this.logger=r}}class Vb extends fs{constructor(e,r){super(e,r,Mb,ma),this.core=e,this.logger=r}}class Kb extends fs{constructor(e,r){super(e,r,Fb,ma),this.core=e,this.logger=r}}class va extends am{constructor(e){super(e),this.protocol=Uh,this.version=Fh,this.name=wa.name,this.events=new Et.exports.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.name=e?.name||wa.name,this.metadata=e?.metadata||Dg();const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:zn(je.getDefaultLoggerOptions({level:e?.logger||wa.logger}));this.core=e?.core||new Rb(e),this.logger=je.generateChildLogger(r,this.name),this.session=new Vb(this.core,this.logger),this.proposal=new qb(this.core,this.logger),this.pendingRequest=new Kb(this.core,this.logger),this.engine=new Wb(this)}static async init(e){const r=new va(e);return await r.initialize(),r}get context(){return je.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.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var _a={exports:{}};(function(t,e){var r=typeof self<"u"?self:ut,n=function(){function s(){this.fetch=!1,this.DOMException=r.DOMException}return s.prototype=r,new s}();(function(s){(function(o){var a={searchParams:"URLSearchParams"in s,iterable:"Symbol"in s&&"iterator"in Symbol,blob:"FileReader"in s&&"Blob"in s&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in s,arrayBuffer:"ArrayBuffer"in s};function c(C){return C&&DataView.prototype.isPrototypeOf(C)}if(a.arrayBuffer)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],p=ArrayBuffer.isView||function(C){return C&&l.indexOf(Object.prototype.toString.call(C))>-1};function m(C){if(typeof C!="string"&&(C=String(C)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(C))throw new TypeError("Invalid character in header field name");return C.toLowerCase()}function b(C){return typeof C!="string"&&(C=String(C)),C}function w(C){var $={next:function(){var G=C.shift();return{done:G===void 0,value:G}}};return a.iterable&&($[Symbol.iterator]=function(){return $}),$}function E(C){this.map={},C instanceof E?C.forEach(function($,G){this.append(G,$)},this):Array.isArray(C)?C.forEach(function($){this.append($[0],$[1])},this):C&&Object.getOwnPropertyNames(C).forEach(function($){this.append($,C[$])},this)}E.prototype.append=function(C,$){C=m(C),$=b($);var G=this.map[C];this.map[C]=G?G+", "+$:$},E.prototype.delete=function(C){delete this.map[m(C)]},E.prototype.get=function(C){return C=m(C),this.has(C)?this.map[C]:null},E.prototype.has=function(C){return this.map.hasOwnProperty(m(C))},E.prototype.set=function(C,$){this.map[m(C)]=b($)},E.prototype.forEach=function(C,$){for(var G in this.map)this.map.hasOwnProperty(G)&&C.call($,this.map[G],G,this)},E.prototype.keys=function(){var C=[];return this.forEach(function($,G){C.push(G)}),w(C)},E.prototype.values=function(){var C=[];return this.forEach(function($){C.push($)}),w(C)},E.prototype.entries=function(){var C=[];return this.forEach(function($,G){C.push([G,$])}),w(C)},a.iterable&&(E.prototype[Symbol.iterator]=E.prototype.entries);function A(C){if(C.bodyUsed)return Promise.reject(new TypeError("Already read"));C.bodyUsed=!0}function N(C){return new Promise(function($,G){C.onload=function(){$(C.result)},C.onerror=function(){G(C.error)}})}function M(C){var $=new FileReader,G=N($);return $.readAsArrayBuffer(C),G}function x(C){var $=new FileReader,G=N($);return $.readAsText(C),G}function D(C){for(var $=new Uint8Array(C),G=new Array($.length),K=0;K<$.length;K++)G[K]=String.fromCharCode($[K]);return G.join("")}function y(C){if(C.slice)return C.slice(0);var $=new Uint8Array(C.byteLength);return $.set(new Uint8Array(C)),$.buffer}function I(){return this.bodyUsed=!1,this._initBody=function(C){this._bodyInit=C,C?typeof C=="string"?this._bodyText=C:a.blob&&Blob.prototype.isPrototypeOf(C)?this._bodyBlob=C:a.formData&&FormData.prototype.isPrototypeOf(C)?this._bodyFormData=C:a.searchParams&&URLSearchParams.prototype.isPrototypeOf(C)?this._bodyText=C.toString():a.arrayBuffer&&a.blob&&c(C)?(this._bodyArrayBuffer=y(C.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(C)||p(C))?this._bodyArrayBuffer=y(C):this._bodyText=C=Object.prototype.toString.call(C):this._bodyText="",this.headers.get("content-type")||(typeof C=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):a.searchParams&&URLSearchParams.prototype.isPrototypeOf(C)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a.blob&&(this.blob=function(){var C=A(this);if(C)return C;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?A(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(M)}),this.text=function(){var C=A(this);if(C)return C;if(this._bodyBlob)return x(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(D(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},a.formData&&(this.formData=function(){return this.text().then(H)}),this.json=function(){return this.text().then(JSON.parse)},this}var O=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function h(C){var $=C.toUpperCase();return O.indexOf($)>-1?$:C}function _(C,$){$=$||{};var G=$.body;if(C instanceof _){if(C.bodyUsed)throw new TypeError("Already read");this.url=C.url,this.credentials=C.credentials,$.headers||(this.headers=new E(C.headers)),this.method=C.method,this.mode=C.mode,this.signal=C.signal,!G&&C._bodyInit!=null&&(G=C._bodyInit,C.bodyUsed=!0)}else this.url=String(C);if(this.credentials=$.credentials||this.credentials||"same-origin",($.headers||!this.headers)&&(this.headers=new E($.headers)),this.method=h($.method||this.method||"GET"),this.mode=$.mode||this.mode||null,this.signal=$.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&G)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(G)}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})};function H(C){var $=new FormData;return C.trim().split("&").forEach(function(G){if(G){var K=G.split("="),W=K.shift().replace(/\+/g," "),z=K.join("=").replace(/\+/g," ");$.append(decodeURIComponent(W),decodeURIComponent(z))}}),$}function j(C){var $=new E,G=C.replace(/\r?\n[\t ]+/g," ");return G.split(/\r?\n/).forEach(function(K){var W=K.split(":"),z=W.shift().trim();if(z){var J=W.join(":").trim();$.append(z,J)}}),$}I.call(_.prototype);function q(C,$){$||($={}),this.type="default",this.status=$.status===void 0?200:$.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in $?$.statusText:"OK",this.headers=new E($.headers),this.url=$.url||"",this._initBody(C)}I.call(q.prototype),q.prototype.clone=function(){return new q(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new E(this.headers),url:this.url})},q.error=function(){var C=new q(null,{status:0,statusText:""});return C.type="error",C};var X=[301,302,303,307,308];q.redirect=function(C,$){if(X.indexOf($)===-1)throw new RangeError("Invalid status code");return new q(null,{status:$,headers:{location:C}})},o.DOMException=s.DOMException;try{new o.DOMException}catch{o.DOMException=function($,G){this.message=$,this.name=G;var K=Error($);this.stack=K.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function re(C,$){return new Promise(function(G,K){var W=new _(C,$);if(W.signal&&W.signal.aborted)return K(new o.DOMException("Aborted","AbortError"));var z=new XMLHttpRequest;function J(){z.abort()}z.onload=function(){var Z={status:z.status,statusText:z.statusText,headers:j(z.getAllResponseHeaders()||"")};Z.url="responseURL"in z?z.responseURL:Z.headers.get("X-Request-URL");var le="response"in z?z.response:z.responseText;G(new q(le,Z))},z.onerror=function(){K(new TypeError("Network request failed"))},z.ontimeout=function(){K(new TypeError("Network request failed"))},z.onabort=function(){K(new o.DOMException("Aborted","AbortError"))},z.open(W.method,W.url,!0),W.credentials==="include"?z.withCredentials=!0:W.credentials==="omit"&&(z.withCredentials=!1),"responseType"in z&&a.blob&&(z.responseType="blob"),W.headers.forEach(function(Z,le){z.setRequestHeader(le,Z)}),W.signal&&(W.signal.addEventListener("abort",J),z.onreadystatechange=function(){z.readyState===4&&W.signal.removeEventListener("abort",J)}),z.send(typeof W._bodyInit>"u"?null:W._bodyInit)})}return re.polyfill=!0,s.fetch||(s.fetch=re,s.Headers=E,s.Request=_,s.Response=q),o.Headers=E,o.Request=_,o.Response=q,o.fetch=re,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(_a,_a.exports);var zh=kd(_a.exports);const Wh={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},qh=10;class gs{constructor(e){if(this.url=e,this.events=new Et.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!eh(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,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e,r){this.isAvailable||await this.register();try{const n=ri(e),s=await(await zh(this.url,Object.assign(Object.assign({},Wh),{body:n}))).json();this.onPayload({data:s})}catch(n){this.onError(e.id,n)}}async register(e=this.url){if(!eh(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));n()})})}this.url=e,this.registering=!0;try{const r=ri({id:1,jsonrpc:"2.0",method:"test",params:[]});await zh(e,Object.assign(Object.assign({},Wh),{body:r})),this.onOpen()}catch(r){const n=this.parseError(r);throw this.events.emit("register_error",n),this.onClose(),n}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ea(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=us(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return Gu(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>qh&&this.events.setMaxListeners(qh)}}const Vh="error",Gb="wss://relay.walletconnect.com",Zb="wc",Yb="universal_provider",Kh=`${Zb}@${2}:${Yb}:`,Jb="https://rpc.walletconnect.com/v1",ui={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function fn(t,e,r){let n;const i=Ea(t);return e.rpcMap&&(n=e.rpcMap[i]),n||(n=`${Jb}?chainId=eip155:${i}&projectId=${r}`),n}function Ea(t){return t.includes("eip155")?Number(t.split(":")[1]):Number(t)}function Xb(t,e){if(!e.includes(t))throw new Error(`Chain '${t}' not approved. Please use one of the following: ${e.toString()}`)}function Qb(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}const ms=(t,e)=>{const r=n=>{n.request!==e.request||n.topic!==e.topic||(t.events.removeListener("session_request_sent",r),ey())};t.on("session_request_sent",r)};function ey(){if(typeof window<"u")try{const t=window.localStorage.getItem("WALLETCONNECT_DEEPLINK_CHOICE");if(t){const e=JSON.parse(t);window.open(e.href,"_self","noreferrer noopener")}}catch(t){console.error(t)}}class ty{constructor(e){this.name="eip155",this.namespace=e.namespace,this.client=e.client,this.events=e.events,this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){var r;switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return this.handleSwitchChain(e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0"),null;case"eth_chainId":return parseInt(this.getDefaultChain())}return this.namespace.methods.includes(e.request.method)?(ms(this.client,e),await this.client.request(e)):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){const n=Ea(e);if(!this.httpProviders[n]){const i=r||fn(`${this.name}:${n}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${n}`);this.setHttpProvider(n,i)}this.chainId=n,this.events.emit(ui.DEFAULT_CHAIN_CHANGED,`${this.name}:${n}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,r){const n=r||fn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new si(new gs(n))}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=Ea(r);e[n]=this.createHttpProvider(n)}),e}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}handleSwitchChain(e){const r=parseInt(e,16),n=`${this.name}:${r}`;Xb(n,this.namespace.chains),this.setDefaultChain(`${r}`)}}class ry{constructor(e){this.name="solana",this.namespace=e.namespace,this.events=e.events,this.client=e.client,this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?(ms(this.client,e),this.client.request(e)):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const n=r||fn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.chainId=e,this.events.emit(ui.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{e[r]=this.createHttpProvider(r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||fn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new si(new gs(n))}}class ny{constructor(e){this.name="cosmos",this.namespace=e.namespace,this.events=e.events,this.client=e.client,this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?(ms(this.client,e),this.client.request(e)):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||fn(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(ui.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{e[r]=this.createHttpProvider(r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||fn(e,this.namespace,this.client.core.projectId);return typeof n>"u"?void 0:new si(new gs(n))}}class iy{constructor(e){this.name="cip34",this.namespace=e.namespace,this.events=e.events,this.client=e.client,this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?(ms(this.client,e),this.client.request(e)):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const n=r||this.getCardanoRPCUrl(e);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,n)}this.events.emit(ui.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const n=this.getCardanoRPCUrl(r);e[r]=this.createHttpProvider(r,n)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const n=this.createHttpProvider(e,r);n&&(this.httpProviders[e]=n)}createHttpProvider(e,r){const n=r||this.getCardanoRPCUrl(e);return typeof n>"u"?void 0:new si(new gs(n))}}var sy=Object.defineProperty,oy=Object.defineProperties,ay=Object.getOwnPropertyDescriptors,Gh=Object.getOwnPropertySymbols,cy=Object.prototype.hasOwnProperty,ly=Object.prototype.propertyIsEnumerable,Zh=(t,e,r)=>e in t?sy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ws=(t,e)=>{for(var r in e||(e={}))cy.call(e,r)&&Zh(t,r,e[r]);if(Gh)for(var r of Gh(e))ly.call(e,r)&&Zh(t,r,e[r]);return t},xa=(t,e)=>oy(t,ay(e));class Ca{constructor(e){this.events=new Et.exports,this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:zn(je.getDefaultLoggerOptions({level:e?.logger||Vh}))}static async init(e){const r=new Ca(e);return await r.initialize(),r}async request(e,r){const[n,i]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:ws({},e),chainId:`${n}:${i}`,topic:this.session.topic})}sendAsync(e,r,n){this.request(e,n).then(i=>r(null,i)).catch(i=>r(i,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:tt("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){this.shouldAbortPairingAttempt=!1;let r=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(r>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:n,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});n&&(this.uri=n,this.events.emit("display_uri",n)),await i().then(s=>{this.session=s}).catch(s=>{if(s.message!==jh)throw s;r++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(e,r){try{const[n,i]=this.validateChain(e);this.getProvider(n).setDefaultChain(i,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(wr(r)){for(const n of r)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await va.init({logger:this.providerOpts.logger||Vh,relayUrl:this.providerOpts.relayUrl||Gb,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,name:this.providerOpts.name}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");Object.keys(this.namespaces).forEach(e=>{var r,n,i;const s=((r=this.session)==null?void 0:r.namespaces[e].accounts)||[],o=Qb(s),a=xa(ws({},Object.assign(this.namespaces[e],(i=(n=this.optionalNamespaces)==null?void 0:n[e])!=null?i:{})),{accounts:s,chains:o});switch(e){case"eip155":this.rpcProviders[e]=new ty({client:this.client,namespace:a,events:this.events});break;case"solana":this.rpcProviders[e]=new ry({client:this.client,namespace:a,events:this.events});break;case"cosmos":this.rpcProviders[e]=new ny({client:this.client,namespace:a,events:this.events});break;case"polkadot":break;case"cip34":this.rpcProviders[e]=new iy({client:this.client,namespace:a,events:this.events});break}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?this.events.emit("accountsChanged",n.data):n.name==="chainChanged"?this.onChainChanged(r.chainId):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var n;const{namespaces:i}=r,s=(n=this.client)==null?void 0:n.session.get(e);this.session=xa(ws({},s),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",xa(ws({},tt("USER_DISCONNECTED")),{data:e.topic}))}),this.on(ui.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){if(!this.rpcProviders[e])throw new Error(`Provider not found: ${e}`);return this.rpcProviders[e]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r,optionalNamespaces:n,sessionProperties:i}=e;if(!r||!Object.keys(r).length)throw new Error("Namespaces must be not empty");this.namespaces=r,this.optionalNamespaces=n,this.sessionProperties=i,this.persist("namespaces",r),this.persist("optionalNamespaces",n)}validateChain(e){const[r,n]=e?.split(":")||["",""];if(r&&!Object.keys(this.namespaces).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];const i=Object.keys(this.namespaces)[0],s=this.rpcProviders[i].getDefaultChain();return[i,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,r=!1){const[n,i]=this.validateChain(e);r||this.getProvider(n).setDefaultChain(i),this.namespaces[n].defaultChain=i,this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",i)}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0})}persist(e,r){this.client.core.storage.setItem(`${Kh}/${e}`,r)}async getFromStore(e){return await this.client.core.storage.getItem(`${Kh}/${e}`)}}const uy=Ca,hy="wc",dy="ethereum_provider",fy=`${hy}@${2}:${dy}:`,py="https://rpc.walletconnect.com/v1/",bs=["eth_sendTransaction","personal_sign"],gy=["eth_accounts","eth_requestAccounts","eth_call","eth_getBalance","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode"],ys=["chainChanged","accountsChanged"],my=["message","disconnect","connect"];var wy=Object.defineProperty,by=Object.defineProperties,yy=Object.getOwnPropertyDescriptors,Yh=Object.getOwnPropertySymbols,vy=Object.prototype.hasOwnProperty,_y=Object.prototype.propertyIsEnumerable,Jh=(t,e,r)=>e in t?wy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Xh=(t,e)=>{for(var r in e||(e={}))vy.call(e,r)&&Jh(t,r,e[r]);if(Yh)for(var r of Yh(e))_y.call(e,r)&&Jh(t,r,e[r]);return t},Qh=(t,e)=>by(t,yy(e));function Sa(t){return Number(t[0].split(":")[1])}function Ia(t){return`0x${t.toString(16)}`}function Ey(t){const{chains:e,optionalChains:r,methods:n,optionalMethods:i,events:s,optionalEvents:o,rpcMap:a}=t;if(!wr(e))throw new Error("Invalid chains");const c=e,l=n||bs,p=s||ys,m={[Sa(c)]:a[Sa(c)]},b={chains:c,methods:l,events:p,rpcMap:m},w=s?.filter(M=>!ys.includes(M)),E=n?.filter(M=>!bs.includes(M));if(!r&&!o&&!i&&!(w!=null&&w.length)&&!(E!=null&&E.length))return{required:b};const A=w?.length&&E?.length||!r,N={chains:[...new Set(A?c.concat(r||[]):r)],methods:[...new Set(l.concat(i||[]))],events:[...new Set(p.concat(o||[]))],rpcMap:a};return{required:b,optional:N}}class vs{constructor(){this.events=new Et.exports.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=fy,this.on=(e,r)=>(this.events.on(e,r),this),this.once=(e,r)=>(this.events.once(e,r),this),this.removeListener=(e,r)=>(this.events.removeListener(e,r),this),this.off=(e,r)=>(this.events.off(e,r),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const r=new vs;return await r.initialize(e),r}async request(e){return await this.signer.request(e,this.formatChainId(this.chainId))}sendAsync(e,r){this.signer.sendAsync(e,r,this.formatChainId(this.chainId))}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:n}=Ey(this.rpc);try{const i=await new Promise(async(o,a)=>{var c;this.rpc.showQrModal&&((c=this.modal)==null||c.subscribeModal(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(Qh(Xh({namespaces:{[this.namespace]:r}},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e?.pairingTopic})).then(l=>{o(l)}).catch(l=>{a(new Error(l.message))})});if(!i)return;this.setChainIds(this.rpc.chains);const s=lg(i.namespaces,[this.namespace]);this.setAccounts(s),this.events.emit("connect",{chainId:Ia(this.chainId)})}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.data),this.events.emit("session_event",e)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",Ia(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",Qh(Xh({},tt("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var r,n;this.rpc.showQrModal&&((r=this.modal)==null||r.closeModal(),(n=this.modal)==null||n.openModal({uri:e})),this.events.emit("display_uri",e)})}setHttpProvider(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",Ia(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.setHttpProvider(r)}}parseAccountId(e){const[r,n,i]=e.split(":");return{chainId:`${r}:${n}`,address:i}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,n;return{chains:((r=e.chains)==null?void 0:r.map(i=>this.formatChainId(i)))||[`${this.namespace}:1`],optionalChains:e.optionalChains?e.optionalChains.map(i=>this.formatChainId(i)):void 0,methods:e?.methods||bs,events:e?.events||ys,optionalMethods:e?.optionalMethods||[],optionalEvents:e?.optionalEvents||[],rpcMap:e?.rpcMap||this.buildRpcMap(e.chains.concat(e.optionalChains||[]),e.projectId),showQrModal:(n=e?.showQrModal)!=null?n:!0,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const n={};return e.forEach(i=>{n[i]=this.getRpcUrl(i,r)}),n}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=Sa(this.rpc.chains),this.signer=await uy.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){const{Web3Modal:r}=await Promise.resolve().then(function(){return qy});this.modal=new r({walletConnectVersion:2,projectId:this.rpc.projectId,standaloneChains:this.rpc.chains})}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:n,rpcMap:i}=e;r&&wr(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)})),n&&wr(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(s=>this.formatChainId(s)),n.forEach(s=>{this.rpc.rpcMap[s]=i?.[s]||this.getRpcUrl(s)}))}getRpcUrl(e,r){var n;return((n=this.rpc.rpcMap)==null?void 0:n[e])||`${py}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(!this.session)return;const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`);this.setChainIds(e?[this.formatChainId(e)]:this.session.namespaces[this.namespace].accounts),this.setAccounts(this.session.namespaces[this.namespace].accounts)}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const xy=vs,Cy=Symbol(),e0=Object.getPrototypeOf,Da=new WeakMap,Sy=t=>t&&(Da.has(t)?Da.get(t):e0(t)===Object.prototype||e0(t)===Array.prototype),Iy=t=>Sy(t)&&t[Cy]||null,t0=(t,e=!0)=>{Da.set(t,e)},Oa=t=>typeof t=="object"&&t!==null,Fr=new WeakMap,_s=new WeakSet,Dy=(t=Object.is,e=(l,p)=>new Proxy(l,p),r=l=>Oa(l)&&!_s.has(l)&&(Array.isArray(l)||!(Symbol.iterator in l))&&!(l instanceof WeakMap)&&!(l instanceof WeakSet)&&!(l instanceof Error)&&!(l instanceof Number)&&!(l instanceof Date)&&!(l instanceof String)&&!(l instanceof RegExp)&&!(l instanceof ArrayBuffer),n=l=>{switch(l.status){case"fulfilled":return l.value;case"rejected":throw l.reason;default:throw l}},i=new WeakMap,s=(l,p,m=n)=>{const b=i.get(l);if(b?.[0]===p)return b[1];const w=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return t0(w,!0),i.set(l,[p,w]),Reflect.ownKeys(l).forEach(E=>{const A=Reflect.get(l,E);_s.has(A)?(t0(A,!1),w[E]=A):A instanceof Promise?Object.defineProperty(w,E,{get(){return m(A)}}):Fr.has(A)?w[E]=Ay(A,m):w[E]=A}),Object.freeze(w)},o=new WeakMap,a=[1,1],c=l=>{if(!Oa(l))throw new Error("object required");const p=o.get(l);if(p)return p;let m=a[0];const b=new Set,w=(H,j=++a[0])=>{m!==j&&(m=j,b.forEach(q=>q(H,j)))};let E=a[1];const A=(H=++a[1])=>(E!==H&&!b.size&&(E=H,M.forEach(([j])=>{const q=j[1](H);q>m&&(m=q)})),m),N=H=>(j,q)=>{const X=[...j];X[1]=[H,...X[1]],w(X,q)},M=new Map,x=(H,j)=>{if(void 0!=="production"&&M.has(H))throw new Error("prop listener already exists");if(b.size){const q=j[3](N(H));M.set(H,[j,q])}else M.set(H,[j])},D=H=>{var j;const q=M.get(H);q&&(M.delete(H),(j=q[1])==null||j.call(q))},y=H=>(b.add(H),b.size===1&&M.forEach(([q,X],re)=>{if(void 0!=="production"&&X)throw new Error("remove already exists");const C=q[3](N(re));M.set(re,[q,C])}),()=>{b.delete(H),b.size===0&&M.forEach(([q,X],re)=>{X&&(X(),M.set(re,[q]))})}),I=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),h=e(I,{deleteProperty(H,j){const q=Reflect.get(H,j);D(j);const X=Reflect.deleteProperty(H,j);return X&&w(["delete",[j],q]),X},set(H,j,q,X){var re;const C=Reflect.has(H,j),$=Reflect.get(H,j,X);if(C&&t($,q))return!0;D(j),Oa(q)&&(q=Iy(q)||q);let G=q;if(!((re=Object.getOwnPropertyDescriptor(H,j))!=null&&re.set))if(q instanceof Promise)q.then(K=>{q.status="fulfilled",q.value=K,w(["resolve",[j],K])}).catch(K=>{q.status="rejected",q.reason=K,w(["reject",[j],K])});else{!Fr.has(q)&&r(q)&&(G=yr(q));const K=!_s.has(G)&&Fr.get(G);K&&x(j,K)}return Reflect.set(H,j,G,X),w(["set",[j],q,$]),!0}});o.set(l,h);const _=[I,A,s,y];return Fr.set(h,_),Reflect.ownKeys(l).forEach(H=>{const j=Object.getOwnPropertyDescriptor(l,H);j.get||j.set?Object.defineProperty(I,H,j):h[H]=l[H]}),h})=>[c,Fr,_s,t,e,r,n,i,s,o,a],[Oy]=Dy();function yr(t={}){return Oy(t)}function hi(t,e,r){const n=Fr.get(t);void 0!=="production"&&!n&&console.warn("Please use proxy object");let i;const s=[],o=n[3];let a=!1;const l=o(p=>{if(s.push(p),r){e(s.splice(0));return}i||(i=Promise.resolve().then(()=>{i=void 0,a&&e(s.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Ay(t,e){const r=Fr.get(t);void 0!=="production"&&!r&&console.warn("Please use proxy object");const[n,i,s]=r;return s(n,i(),e)}var r0={},Es={};Es.byteLength=Ty,Es.toByteArray=Ry,Es.fromByteArray=Uy;for(var ir=[],Vt=[],$y=typeof Uint8Array<"u"?Uint8Array:Array,Aa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",pn=0,Py=Aa.length;pn<Py;++pn)ir[pn]=Aa[pn],Vt[Aa.charCodeAt(pn)]=pn;Vt["-".charCodeAt(0)]=62,Vt["_".charCodeAt(0)]=63;function n0(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function Ty(t){var e=n0(t),r=e[0],n=e[1];return(r+n)*3/4-n}function Ny(t,e,r){return(e+r)*3/4-r}function Ry(t){var e,r=n0(t),n=r[0],i=r[1],s=new $y(Ny(t,n,i)),o=0,a=i>0?n-4:n,c;for(c=0;c<a;c+=4)e=Vt[t.charCodeAt(c)]<<18|Vt[t.charCodeAt(c+1)]<<12|Vt[t.charCodeAt(c+2)]<<6|Vt[t.charCodeAt(c+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Vt[t.charCodeAt(c)]<<2|Vt[t.charCodeAt(c+1)]>>4,s[o++]=e&255),i===1&&(e=Vt[t.charCodeAt(c)]<<10|Vt[t.charCodeAt(c+1)]<<4|Vt[t.charCodeAt(c+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function Ly(t){return ir[t>>18&63]+ir[t>>12&63]+ir[t>>6&63]+ir[t&63]}function My(t,e,r){for(var n,i=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(Ly(n));return i.join("")}function Uy(t){for(var e,r=t.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(My(t,o,o+s>a?a:o+s));return n===1?(e=t[r-1],i.push(ir[e>>2]+ir[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(ir[e>>10]+ir[e>>4&63]+ir[e<<2&63]+"=")),i.join("")}var $a={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */$a.read=function(t,e,r,n,i){var s,o,a=i*8-n-1,c=(1<<a)-1,l=c>>1,p=-7,m=r?i-1:0,b=r?-1:1,w=t[e+m];for(m+=b,s=w&(1<<-p)-1,w>>=-p,p+=a;p>0;s=s*256+t[e+m],m+=b,p-=8);for(o=s&(1<<-p)-1,s>>=-p,p+=n;p>0;o=o*256+t[e+m],m+=b,p-=8);if(s===0)s=1-l;else{if(s===c)return o?NaN:(w?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-l}return(w?-1:1)*o*Math.pow(2,s-n)},$a.write=function(t,e,r,n,i,s){var o,a,c,l=s*8-i-1,p=(1<<l)-1,m=p>>1,b=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,w=n?0:s-1,E=n?1:-1,A=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=p):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+m>=1?e+=b/c:e+=b*Math.pow(2,1-m),e*c>=2&&(o++,c/=2),o+m>=p?(a=0,o=p):o+m>=1?(a=(e*c-1)*Math.pow(2,i),o=o+m):(a=e*Math.pow(2,m-1)*Math.pow(2,i),o=0));i>=8;t[r+w]=a&255,w+=E,a/=256,i-=8);for(o=o<<i|a,l+=i;l>0;t[r+w]=o&255,w+=E,o/=256,l-=8);t[r+w-E]|=A*128};/*!
71
71
  * The buffer module from node.js, for the browser.
72
72
  *
73
73
  * @author Feross Aboukhadijeh <https://feross.org>