@walletconnect/ethereum-provider 2.9.2-rc.0 → 2.9.2
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 +1 -1
- package/dist/index.umd.js.map +1 -1
- package/package.json +5 -5
package/dist/index.umd.js
CHANGED
|
@@ -69,7 +69,7 @@
|
|
|
69
69
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
70
70
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
71
71
|
PERFORMANCE OF THIS SOFTWARE.
|
|
72
|
-
***************************************************************************** */var eh=function(t,e){return eh=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])},eh(t,e)};function e_(t,e){eh(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var th=function(){return th=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},th.apply(this,arguments)};function t_(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 r_(t,e,r,n){var i=arguments.length,o=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,r,n);else for(var l=t.length-1;l>=0;l--)(c=t[l])&&(o=(i<3?c(o):i>3?c(e,r,o):c(e,r))||o);return i>3&&o&&Object.defineProperty(e,r,o),o}function n_(t,e){return function(r,n){e(r,n,t)}}function i_(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function s_(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function l(v){try{f(n.next(v))}catch(x){c(x)}}function h(v){try{f(n.throw(v))}catch(x){c(x)}}function f(v){v.done?o(v.value):i(v.value).then(l,h)}f((n=n.apply(t,e||[])).next())})}function o_(t,e){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,c;return c={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(c[Symbol.iterator]=function(){return this}),c;function l(f){return function(v){return h([f,v])}}function h(f){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(o=f[0]&2?i.return:f[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,f[1])).done)return o;switch(i=0,o&&(f=[f[0]&2,o.value]),f[0]){case 0:case 1:o=f;break;case 4:return r.label++,{value:f[1],done:!1};case 5:r.label++,i=f[1],f=[0];continue;case 7:f=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(f[0]===6||f[0]===2)){r=0;continue}if(f[0]===3&&(!o||f[1]>o[0]&&f[1]<o[3])){r.label=f[1];break}if(f[0]===6&&r.label<o[1]){r.label=o[1],o=f;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(f);break}o[2]&&r.ops.pop(),r.trys.pop();continue}f=e.call(t,r)}catch(v){f=[6,v],i=0}finally{n=o=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}}function a_(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function c_(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function rh(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 xp(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],c;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(l){c={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(c)throw c.error}}return o}function l_(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(xp(arguments[e]));return t}function u_(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var o=arguments[e],c=0,l=o.length;c<l;c++,i++)n[i]=o[c];return n}function jo(t){return this instanceof jo?(this.v=t,this):new jo(t)}function h_(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,o=[];return i={},c("next"),c("throw"),c("return"),i[Symbol.asyncIterator]=function(){return this},i;function c(_){n[_]&&(i[_]=function(S){return new Promise(function(P,j){o.push([_,S,P,j])>1||l(_,S)})})}function l(_,S){try{h(n[_](S))}catch(P){x(o[0][3],P)}}function h(_){_.value instanceof jo?Promise.resolve(_.value.v).then(f,v):x(o[0][2],_)}function f(_){l("next",_)}function v(_){l("throw",_)}function x(_,S){_(S),o.shift(),o.length&&l(o[0][0],o[0][1])}}function f_(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,o){e[i]=t[i]?function(c){return(r=!r)?{value:jo(t[i](c)),done:i==="return"}:o?o(c):c}:o}}function d_(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 rh=="function"?rh(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(o){r[o]=t[o]&&function(c){return new Promise(function(l,h){c=t[o](c),i(l,h,c.done,c.value)})}}function i(o,c,l,h){Promise.resolve(h).then(function(f){o({value:f,done:l})},c)}}function p_(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function g_(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 m_(t){return t&&t.__esModule?t:{default:t}}function w_(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function v_(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 y_=Object.freeze({__proto__:null,__extends:e_,get __assign(){return th},__rest:t_,__decorate:r_,__param:n_,__metadata:i_,__awaiter:s_,__generator:o_,__createBinding:a_,__exportStar:c_,__values:rh,__read:xp,__spread:l_,__spreadArrays:u_,__await:jo,__asyncGenerator:h_,__asyncDelegator:f_,__asyncValues:d_,__makeTemplateObject:p_,__importStar:g_,__importDefault:m_,__classPrivateFieldGet:w_,__classPrivateFieldSet:v_}),b_=Ui(y_),Wn={},Cp;function __(){if(Cp)return Wn;Cp=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.isBrowserCryptoAvailable=Wn.getSubtleCrypto=Wn.getBrowerCrypto=void 0;function t(){return pr?.crypto||pr?.msCrypto||{}}Wn.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}Wn.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Wn.isBrowserCryptoAvailable=r,Wn}var qn={},Ip;function E_(){if(Ip)return qn;Ip=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.isBrowser=qn.isNode=qn.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}qn.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}qn.isNode=e;function r(){return!t()&&!e()}return qn.isBrowser=r,qn}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=b_;e.__exportStar(__(),t),e.__exportStar(E_(),t)})(Ep);function Sp(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function nh(t=6){return BigInt(Sp(t))}function nc(t,e,r){return{id:r||Sp(),jsonrpc:"2.0",method:t,params:e}}function ih(t,e){return{id:t,jsonrpc:"2.0",result:e}}function ic(t,e,r){return{id:t,jsonrpc:"2.0",error:x_(e,r)}}function x_(t,e){return typeof t>"u"?bp(vp):(typeof t=="string"&&(t=Object.assign(Object.assign({},bp(Qu)),{message:t})),typeof e<"u"&&(t.data=e),X4(t.code)&&(t=Q4(t.code)),t)}class C_{}class I_ extends C_{constructor(){super()}}class S_ extends I_{constructor(e){super()}}const O_="^https?:",A_="^wss?:";function D_(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Op(t,e){const r=D_(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Ap(t){return Op(t,O_)}function Dp(t){return Op(t,A_)}function $_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function $p(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function sh(t){return $p(t)&&"method"in t}function sc(t){return $p(t)&&(Vn(t)||xn(t))}function Vn(t){return"result"in t}function xn(t){return"error"in t}class fi extends S_{constructor(e){super(e),this.events=new br.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(nc(e.method,e.params||[],e.id||nh().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(o){i(o)}this.events.on(`${e.id}`,o=>{xn(o)?i(o.error):n(o.result)});try{await this.connection.send(e,r)}catch(o){i(o)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),sc(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const P_=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),T_=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Pp=t=>t.split("?")[0],Tp=10,N_=P_();class R_{constructor(e){if(this.url=e,this.events=new br.exports.EventEmitter,this.registering=!1,!Dp(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e,r){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Mo(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!Dp(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",o=>{this.resetMaxListeners(),i(o)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=Ep.isReactNative()?void 0:{rejectUnauthorized:!$_(e)},o=new N_(e,[],i);T_()?o.onerror=c=>{const l=c;n(this.emitError(l.error))}:o.on("error",c=>{n(this.emitError(c))}),o.onopen=()=>{this.onOpen(o),r(o)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?Ju(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=ic(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return _p(e,Pp(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Tp&&this.events.setMaxListeners(Tp)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Pp(this.url)}`));return this.events.emit("register_error",r),r}}var oh={exports:{}};(function(t,e){var r=200,n="__lodash_hash_undefined__",i=1,o=2,c=9007199254740991,l="[object Arguments]",h="[object Array]",f="[object AsyncFunction]",v="[object Boolean]",x="[object Date]",_="[object Error]",S="[object Function]",P="[object GeneratorFunction]",j="[object Map]",H="[object Number]",Z="[object Null]",R="[object Object]",L="[object Promise]",$="[object Proxy]",T="[object RegExp]",I="[object Set]",d="[object String]",E="[object Symbol]",J="[object Undefined]",z="[object WeakMap]",ee="[object ArrayBuffer]",de="[object DataView]",me="[object Float32Array]",O="[object Float64Array]",U="[object Int8Array]",ce="[object Int16Array]",le="[object Int32Array]",re="[object Uint8Array]",ne="[object Uint8ClampedArray]",ae="[object Uint16Array]",ie="[object Uint32Array]",Ae=/[\\^$.*+?()[\]{}|]/g,ge=/^\[object .+?Constructor\]$/,Be=/^(?:0|[1-9]\d*)$/,ye={};ye[me]=ye[O]=ye[U]=ye[ce]=ye[le]=ye[re]=ye[ne]=ye[ae]=ye[ie]=!0,ye[l]=ye[h]=ye[ee]=ye[v]=ye[de]=ye[x]=ye[_]=ye[S]=ye[j]=ye[H]=ye[R]=ye[T]=ye[I]=ye[d]=ye[z]=!1;var Me=typeof pr=="object"&&pr&&pr.Object===Object&&pr,X=typeof self=="object"&&self&&self.Object===Object&&self,Y=Me||X||Function("return this")(),W=e&&!e.nodeType&&e,w=W&&!0&&t&&!t.nodeType&&t,F=w&&w.exports===W,we=F&&Me.process,ve=function(){try{return we&&we.binding&&we.binding("util")}catch{}}(),Ue=ve&&ve.isTypedArray;function nt(N,q){for(var fe=-1,Ce=N==null?0:N.length,It=0,Xe=[];++fe<Ce;){var Tt=N[fe];q(Tt,fe,N)&&(Xe[It++]=Tt)}return Xe}function at(N,q){for(var fe=-1,Ce=q.length,It=N.length;++fe<Ce;)N[It+fe]=q[fe];return N}function Ge(N,q){for(var fe=-1,Ce=N==null?0:N.length;++fe<Ce;)if(q(N[fe],fe,N))return!0;return!1}function Dt(N,q){for(var fe=-1,Ce=Array(N);++fe<N;)Ce[fe]=q(fe);return Ce}function $t(N){return function(q){return N(q)}}function Je(N,q){return N.has(q)}function He(N,q){return N?.[q]}function ke(N){var q=-1,fe=Array(N.size);return N.forEach(function(Ce,It){fe[++q]=[It,Ce]}),fe}function Ke(N,q){return function(fe){return N(q(fe))}}function rt(N){var q=-1,fe=Array(N.size);return N.forEach(function(Ce){fe[++q]=Ce}),fe}var je=Array.prototype,Ze=Function.prototype,b=Object.prototype,p=Y["__core-js_shared__"],m=Ze.toString,D=b.hasOwnProperty,B=function(){var N=/[^.]+$/.exec(p&&p.keys&&p.keys.IE_PROTO||"");return N?"Symbol(src)_1."+N:""}(),K=b.toString,Q=RegExp("^"+m.call(D).replace(Ae,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ee=F?Y.Buffer:void 0,Ne=Y.Symbol,st=Y.Uint8Array,ht=b.propertyIsEnumerable,lt=je.splice,Ur=Ne?Ne.toStringTag:void 0,Jn=Object.getOwnPropertySymbols,Si=Ee?Ee.isBuffer:void 0,cs=Ke(Object.keys,Object),zt=Qr(Y,"DataView"),Lt=Qr(Y,"Map"),Wt=Qr(Y,"Promise"),qt=Qr(Y,"Set"),Ft=Qr(Y,"WeakMap"),Mt=Qr(Object,"create"),ir=Qn(zt),sr=Qn(Lt),Vt=Qn(Wt),or=Qn(qt),Kt=Qn(Ft),Xt=Ne?Ne.prototype:void 0,Gt=Xt?Xt.valueOf:void 0;function Pt(N){var q=-1,fe=N==null?0:N.length;for(this.clear();++q<fe;){var Ce=N[q];this.set(Ce[0],Ce[1])}}function ar(){this.__data__=Mt?Mt(null):{},this.size=0}function cr(N){var q=this.has(N)&&delete this.__data__[N];return this.size-=q?1:0,q}function Hf(N){var q=this.__data__;if(Mt){var fe=q[N];return fe===n?void 0:fe}return D.call(q,N)?q[N]:void 0}function zf(N){var q=this.__data__;return Mt?q[N]!==void 0:D.call(q,N)}function Wf(N,q){var fe=this.__data__;return this.size+=this.has(N)?0:1,fe[N]=Mt&&q===void 0?n:q,this}Pt.prototype.clear=ar,Pt.prototype.delete=cr,Pt.prototype.get=Hf,Pt.prototype.has=zf,Pt.prototype.set=Wf;function fn(N){var q=-1,fe=N==null?0:N.length;for(this.clear();++q<fe;){var Ce=N[q];this.set(Ce[0],Ce[1])}}function qf(){this.__data__=[],this.size=0}function Vf(N){var q=this.__data__,fe=ls(q,N);if(fe<0)return!1;var Ce=q.length-1;return fe==Ce?q.pop():lt.call(q,fe,1),--this.size,!0}function Kf(N){var q=this.__data__,fe=ls(q,N);return fe<0?void 0:q[fe][1]}function Gf(N){return ls(this.__data__,N)>-1}function Zf(N,q){var fe=this.__data__,Ce=ls(fe,N);return Ce<0?(++this.size,fe.push([N,q])):fe[Ce][1]=q,this}fn.prototype.clear=qf,fn.prototype.delete=Vf,fn.prototype.get=Kf,fn.prototype.has=Gf,fn.prototype.set=Zf;function Xn(N){var q=-1,fe=N==null?0:N.length;for(this.clear();++q<fe;){var Ce=N[q];this.set(Ce[0],Ce[1])}}function Qs(){this.size=0,this.__data__={hash:new Pt,map:new(Lt||fn),string:new Pt}}function Yf(N){var q=Oi(this,N).delete(N);return this.size-=q?1:0,q}function eo(N){return Oi(this,N).get(N)}function Jf(N){return Oi(this,N).has(N)}function Xf(N,q){var fe=Oi(this,N),Ce=fe.size;return fe.set(N,q),this.size+=fe.size==Ce?0:1,this}Xn.prototype.clear=Qs,Xn.prototype.delete=Yf,Xn.prototype.get=eo,Xn.prototype.has=Jf,Xn.prototype.set=Xf;function to(N){var q=-1,fe=N==null?0:N.length;for(this.__data__=new Xn;++q<fe;)this.add(N[q])}function Xc(N){return this.__data__.set(N,n),this}function Qc(N){return this.__data__.has(N)}to.prototype.add=to.prototype.push=Xc,to.prototype.has=Qc;function Cn(N){var q=this.__data__=new fn(N);this.size=q.size}function Qf(){this.__data__=new fn,this.size=0}function e0(N){var q=this.__data__,fe=q.delete(N);return this.size=q.size,fe}function t0(N){return this.__data__.get(N)}function r0(N){return this.__data__.has(N)}function el(N,q){var fe=this.__data__;if(fe instanceof fn){var Ce=fe.__data__;if(!Lt||Ce.length<r-1)return Ce.push([N,q]),this.size=++fe.size,this;fe=this.__data__=new Xn(Ce)}return fe.set(N,q),this.size=fe.size,this}Cn.prototype.clear=Qf,Cn.prototype.delete=e0,Cn.prototype.get=t0,Cn.prototype.has=r0,Cn.prototype.set=el;function tl(N,q){var fe=io(N),Ce=!fe&&dl(N),It=!fe&&!Ce&&ba(N),Xe=!fe&&!Ce&&!It&&ml(N),Tt=fe||Ce||It||Xe,lr=Tt?Dt(N.length,String):[],mt=lr.length;for(var St in N)(q||D.call(N,St))&&!(Tt&&(St=="length"||It&&(St=="offset"||St=="parent")||Xe&&(St=="buffer"||St=="byteLength"||St=="byteOffset")||cl(St,mt)))&&lr.push(St);return lr}function ls(N,q){for(var fe=N.length;fe--;)if(fl(N[fe][0],q))return fe;return-1}function va(N,q,fe){var Ce=q(N);return io(N)?Ce:at(Ce,fe(N))}function us(N){return N==null?N===void 0?J:Z:Ur&&Ur in Object(N)?ol(N):s0(N)}function ya(N){return fs(N)&&us(N)==l}function hs(N,q,fe,Ce,It){return N===q?!0:N==null||q==null||!fs(N)&&!fs(q)?N!==N&&q!==q:rl(N,q,fe,Ce,hs,It)}function rl(N,q,fe,Ce,It,Xe){var Tt=io(N),lr=io(q),mt=Tt?h:Fn(N),St=lr?h:Fn(q);mt=mt==l?R:mt,St=St==l?R:St;var Qt=mt==R,qr=St==R,ur=mt==St;if(ur&&ba(N)){if(!ba(q))return!1;Tt=!0,Qt=!1}if(ur&&!Qt)return Xe||(Xe=new Cn),Tt||ml(N)?ro(N,q,fe,Ce,It,Xe):i0(N,q,mt,fe,Ce,It,Xe);if(!(fe&i)){var Nt=Qt&&D.call(N,"__wrapped__"),jr=qr&&D.call(q,"__wrapped__");if(Nt||jr){var In=Nt?N.value():N,dn=jr?q.value():q;return Xe||(Xe=new Cn),It(In,dn,fe,Ce,Xe)}}return ur?(Xe||(Xe=new Cn),sl(N,q,fe,Ce,It,Xe)):!1}function n0(N){if(!gl(N)||ul(N))return!1;var q=so(N)?Q:ge;return q.test(Qn(N))}function nl(N){return fs(N)&&pl(N.length)&&!!ye[us(N)]}function il(N){if(!hl(N))return cs(N);var q=[];for(var fe in Object(N))D.call(N,fe)&&fe!="constructor"&&q.push(fe);return q}function ro(N,q,fe,Ce,It,Xe){var Tt=fe&i,lr=N.length,mt=q.length;if(lr!=mt&&!(Tt&&mt>lr))return!1;var St=Xe.get(N);if(St&&Xe.get(q))return St==q;var Qt=-1,qr=!0,ur=fe&o?new to:void 0;for(Xe.set(N,q),Xe.set(q,N);++Qt<lr;){var Nt=N[Qt],jr=q[Qt];if(Ce)var In=Tt?Ce(jr,Nt,Qt,q,N,Xe):Ce(Nt,jr,Qt,N,q,Xe);if(In!==void 0){if(In)continue;qr=!1;break}if(ur){if(!Ge(q,function(dn,Bn){if(!Je(ur,Bn)&&(Nt===dn||It(Nt,dn,fe,Ce,Xe)))return ur.push(Bn)})){qr=!1;break}}else if(!(Nt===jr||It(Nt,jr,fe,Ce,Xe))){qr=!1;break}}return Xe.delete(N),Xe.delete(q),qr}function i0(N,q,fe,Ce,It,Xe,Tt){switch(fe){case de:if(N.byteLength!=q.byteLength||N.byteOffset!=q.byteOffset)return!1;N=N.buffer,q=q.buffer;case ee:return!(N.byteLength!=q.byteLength||!Xe(new st(N),new st(q)));case v:case x:case H:return fl(+N,+q);case _:return N.name==q.name&&N.message==q.message;case T:case d:return N==q+"";case j:var lr=ke;case I:var mt=Ce&i;if(lr||(lr=rt),N.size!=q.size&&!mt)return!1;var St=Tt.get(N);if(St)return St==q;Ce|=o,Tt.set(N,q);var Qt=ro(lr(N),lr(q),Ce,It,Xe,Tt);return Tt.delete(N),Qt;case E:if(Gt)return Gt.call(N)==Gt.call(q)}return!1}function sl(N,q,fe,Ce,It,Xe){var Tt=fe&i,lr=no(N),mt=lr.length,St=no(q),Qt=St.length;if(mt!=Qt&&!Tt)return!1;for(var qr=mt;qr--;){var ur=lr[qr];if(!(Tt?ur in q:D.call(q,ur)))return!1}var Nt=Xe.get(N);if(Nt&&Xe.get(q))return Nt==q;var jr=!0;Xe.set(N,q),Xe.set(q,N);for(var In=Tt;++qr<mt;){ur=lr[qr];var dn=N[ur],Bn=q[ur];if(Ce)var _a=Tt?Ce(Bn,dn,ur,q,N,Xe):Ce(dn,Bn,ur,N,q,Xe);if(!(_a===void 0?dn===Bn||It(dn,Bn,fe,Ce,Xe):_a)){jr=!1;break}In||(In=ur=="constructor")}if(jr&&!In){var ds=N.constructor,vr=q.constructor;ds!=vr&&"constructor"in N&&"constructor"in q&&!(typeof ds=="function"&&ds instanceof ds&&typeof vr=="function"&&vr instanceof vr)&&(jr=!1)}return Xe.delete(N),Xe.delete(q),jr}function no(N){return va(N,c0,al)}function Oi(N,q){var fe=N.__data__;return ll(q)?fe[typeof q=="string"?"string":"hash"]:fe.map}function Qr(N,q){var fe=He(N,q);return n0(fe)?fe:void 0}function ol(N){var q=D.call(N,Ur),fe=N[Ur];try{N[Ur]=void 0;var Ce=!0}catch{}var It=K.call(N);return Ce&&(q?N[Ur]=fe:delete N[Ur]),It}var al=Jn?function(N){return N==null?[]:(N=Object(N),nt(Jn(N),function(q){return ht.call(N,q)}))}:Ct,Fn=us;(zt&&Fn(new zt(new ArrayBuffer(1)))!=de||Lt&&Fn(new Lt)!=j||Wt&&Fn(Wt.resolve())!=L||qt&&Fn(new qt)!=I||Ft&&Fn(new Ft)!=z)&&(Fn=function(N){var q=us(N),fe=q==R?N.constructor:void 0,Ce=fe?Qn(fe):"";if(Ce)switch(Ce){case ir:return de;case sr:return j;case Vt:return L;case or:return I;case Kt:return z}return q});function cl(N,q){return q=q??c,!!q&&(typeof N=="number"||Be.test(N))&&N>-1&&N%1==0&&N<q}function ll(N){var q=typeof N;return q=="string"||q=="number"||q=="symbol"||q=="boolean"?N!=="__proto__":N===null}function ul(N){return!!B&&B in N}function hl(N){var q=N&&N.constructor,fe=typeof q=="function"&&q.prototype||b;return N===fe}function s0(N){return K.call(N)}function Qn(N){if(N!=null){try{return m.call(N)}catch{}try{return N+""}catch{}}return""}function fl(N,q){return N===q||N!==N&&q!==q}var dl=ya(function(){return arguments}())?ya:function(N){return fs(N)&&D.call(N,"callee")&&!ht.call(N,"callee")},io=Array.isArray;function o0(N){return N!=null&&pl(N.length)&&!so(N)}var ba=Si||xt;function a0(N,q){return hs(N,q)}function so(N){if(!gl(N))return!1;var q=us(N);return q==S||q==P||q==f||q==$}function pl(N){return typeof N=="number"&&N>-1&&N%1==0&&N<=c}function gl(N){var q=typeof N;return N!=null&&(q=="object"||q=="function")}function fs(N){return N!=null&&typeof N=="object"}var ml=Ue?$t(Ue):nl;function c0(N){return o0(N)?tl(N):il(N)}function Ct(){return[]}function xt(){return!1}t.exports=a0})(oh,oh.exports);var L_=oh.exports,M_=Object.defineProperty,Np=Object.getOwnPropertySymbols,U_=Object.prototype.hasOwnProperty,j_=Object.prototype.propertyIsEnumerable,Rp=(t,e,r)=>e in t?M_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nr=(t,e)=>{for(var r in e||(e={}))U_.call(e,r)&&Rp(t,r,e[r]);if(Np)for(var r of Np(e))j_.call(e,r)&&Rp(t,r,e[r]);return t};function F_(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),c=o.charCodeAt(0);if(r[c]!==255)throw new TypeError(o+" is ambiguous");r[c]=i}var l=t.length,h=t.charAt(0),f=Math.log(l)/Math.log(256),v=Math.log(256)/Math.log(l);function x(P){if(P instanceof Uint8Array||(ArrayBuffer.isView(P)?P=new Uint8Array(P.buffer,P.byteOffset,P.byteLength):Array.isArray(P)&&(P=Uint8Array.from(P))),!(P instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(P.length===0)return"";for(var j=0,H=0,Z=0,R=P.length;Z!==R&&P[Z]===0;)Z++,j++;for(var L=(R-Z)*v+1>>>0,$=new Uint8Array(L);Z!==R;){for(var T=P[Z],I=0,d=L-1;(T!==0||I<H)&&d!==-1;d--,I++)T+=256*$[d]>>>0,$[d]=T%l>>>0,T=T/l>>>0;if(T!==0)throw new Error("Non-zero carry");H=I,Z++}for(var E=L-H;E!==L&&$[E]===0;)E++;for(var J=h.repeat(j);E<L;++E)J+=t.charAt($[E]);return J}function _(P){if(typeof P!="string")throw new TypeError("Expected String");if(P.length===0)return new Uint8Array;var j=0;if(P[j]!==" "){for(var H=0,Z=0;P[j]===h;)H++,j++;for(var R=(P.length-j)*f+1>>>0,L=new Uint8Array(R);P[j];){var $=r[P.charCodeAt(j)];if($===255)return;for(var T=0,I=R-1;($!==0||T<Z)&&I!==-1;I--,T++)$+=l*L[I]>>>0,L[I]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");Z=T,j++}if(P[j]!==" "){for(var d=R-Z;d!==R&&L[d]===0;)d++;for(var E=new Uint8Array(H+(R-d)),J=H;d!==R;)E[J++]=L[d++];return E}}}function S(P){var j=_(P);if(j)return j;throw new Error(`Non-${e} character`)}return{encode:x,decodeUnsafe:_,decode:S}}var B_=F_,k_=B_;const Lp=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")},H_=t=>new TextEncoder().encode(t),z_=t=>new TextDecoder().decode(t);class W_{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 q_{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 Mp(this,e)}}class V_{constructor(e){this.decoders=e}or(e){return Mp(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 Mp=(t,e)=>new V_(Nr(Nr({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class K_{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new W_(e,r,n),this.decoder=new q_(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const oc=({name:t,prefix:e,encode:r,decode:n})=>new K_(t,e,r,n),Fo=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=k_(r,e);return oc({prefix:t,name:e,encode:n,decode:o=>Lp(i(o))})},G_=(t,e,r,n)=>{const i={};for(let v=0;v<e.length;++v)i[e[v]]=v;let o=t.length;for(;t[o-1]==="=";)--o;const c=new Uint8Array(o*r/8|0);let l=0,h=0,f=0;for(let v=0;v<o;++v){const x=i[t[v]];if(x===void 0)throw new SyntaxError(`Non-${n} character`);h=h<<r|x,l+=r,l>=8&&(l-=8,c[f++]=255&h>>l)}if(l>=r||255&h<<8-l)throw new SyntaxError("Unexpected end of data");return c},Z_=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let o="",c=0,l=0;for(let h=0;h<t.length;++h)for(l=l<<8|t[h],c+=8;c>r;)c-=r,o+=e[i&l>>c];if(c&&(o+=e[i&l<<r-c]),n)for(;o.length*r&7;)o+="=";return o},Er=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>oc({prefix:e,name:t,encode(i){return Z_(i,n,r)},decode(i){return G_(i,n,r,t)}}),Y_=oc({prefix:"\0",name:"identity",encode:t=>z_(t),decode:t=>H_(t)});var J_=Object.freeze({__proto__:null,identity:Y_});const X_=Er({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Q_=Object.freeze({__proto__:null,base2:X_});const e8=Er({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var t8=Object.freeze({__proto__:null,base8:e8});const r8=Fo({prefix:"9",name:"base10",alphabet:"0123456789"});var n8=Object.freeze({__proto__:null,base10:r8});const i8=Er({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),s8=Er({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var o8=Object.freeze({__proto__:null,base16:i8,base16upper:s8});const a8=Er({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),c8=Er({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),l8=Er({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),u8=Er({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),h8=Er({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),f8=Er({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),d8=Er({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),p8=Er({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),g8=Er({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var m8=Object.freeze({__proto__:null,base32:a8,base32upper:c8,base32pad:l8,base32padupper:u8,base32hex:h8,base32hexupper:f8,base32hexpad:d8,base32hexpadupper:p8,base32z:g8});const w8=Fo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),v8=Fo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var y8=Object.freeze({__proto__:null,base36:w8,base36upper:v8});const b8=Fo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),_8=Fo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var E8=Object.freeze({__proto__:null,base58btc:b8,base58flickr:_8});const x8=Er({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),C8=Er({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),I8=Er({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),S8=Er({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var O8=Object.freeze({__proto__:null,base64:x8,base64pad:C8,base64url:I8,base64urlpad:S8});const Up=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}"),A8=Up.reduce((t,e,r)=>(t[r]=e,t),[]),D8=Up.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function $8(t){return t.reduce((e,r)=>(e+=A8[r],e),"")}function P8(t){const e=[];for(const r of t){const n=D8[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const T8=oc({prefix:"\u{1F680}",name:"base256emoji",encode:$8,decode:P8});var N8=Object.freeze({__proto__:null,base256emoji:T8}),R8=Fp,jp=128,L8=127,M8=~L8,U8=Math.pow(2,31);function Fp(t,e,r){e=e||[],r=r||0;for(var n=r;t>=U8;)e[r++]=t&255|jp,t/=128;for(;t&M8;)e[r++]=t&255|jp,t>>>=7;return e[r]=t|0,Fp.bytes=r-n+1,e}var j8=ah,F8=128,Bp=127;function ah(t,n){var r=0,n=n||0,i=0,o=n,c,l=t.length;do{if(o>=l)throw ah.bytes=0,new RangeError("Could not decode varint");c=t[o++],r+=i<28?(c&Bp)<<i:(c&Bp)*Math.pow(2,i),i+=7}while(c>=F8);return ah.bytes=o-n,r}var B8=Math.pow(2,7),k8=Math.pow(2,14),H8=Math.pow(2,21),z8=Math.pow(2,28),W8=Math.pow(2,35),q8=Math.pow(2,42),V8=Math.pow(2,49),K8=Math.pow(2,56),G8=Math.pow(2,63),Z8=function(t){return t<B8?1:t<k8?2:t<H8?3:t<z8?4:t<W8?5:t<q8?6:t<V8?7:t<K8?8:t<G8?9:10},Y8={encode:R8,decode:j8,encodingLength:Z8},kp=Y8;const Hp=(t,e,r=0)=>(kp.encode(t,e,r),e),zp=t=>kp.encodingLength(t),ch=(t,e)=>{const r=e.byteLength,n=zp(t),i=n+zp(r),o=new Uint8Array(i+r);return Hp(t,o,0),Hp(r,o,n),o.set(e,i),new J8(t,r,e,o)};class J8{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Wp=({name:t,code:e,encode:r})=>new X8(t,e,r);class X8{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?ch(this.code,r):r.then(n=>ch(this.code,n))}else throw Error("Unknown type, must be binary type")}}const qp=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Q8=Wp({name:"sha2-256",code:18,encode:qp("SHA-256")}),eE=Wp({name:"sha2-512",code:19,encode:qp("SHA-512")});var tE=Object.freeze({__proto__:null,sha256:Q8,sha512:eE});const Vp=0,rE="identity",Kp=Lp;var nE=Object.freeze({__proto__:null,identity:{code:Vp,name:rE,encode:Kp,digest:t=>ch(Vp,Kp(t))}});new TextEncoder,new TextDecoder;const Gp=Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr({},J_),Q_),t8),n8),o8),m8),y8),E8),O8),N8);Nr(Nr({},tE),nE);function Zp(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function iE(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Zp(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Yp(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Jp=Yp("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),lh=Yp("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=iE(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),sE=Nr({utf8:Jp,"utf-8":Jp,hex:Gp.base16,latin1:lh,ascii:lh,binary:lh},Gp);function oE(t,e="utf8"){const r=sE[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Zp(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}const Xp="wc",aE=2,uh="core",di=`${Xp}@2:${uh}:`,cE={name:uh,logger:"error"},lE={database:":memory:"},uE="crypto",Qp="client_ed25519_seed",hE=De.ONE_DAY,fE="keychain",dE="0.3",pE="messages",gE="0.3",mE=De.SIX_HOURS,wE="publisher",eg="irn",vE="error",tg="wss://relay.walletconnect.com",rg="wss://relay.walletconnect.org",yE="relayer",kt={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},bE="_subscription",Bo={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},_E=De.ONE_SECOND/2,EE="2.9.2-rc.0",xE=1e4,CE="0.3",IE="WALLETCONNECT_CLIENT_ID",Tn={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},SE="subscription",OE="0.3",AE=De.FIVE_SECONDS*1e3,DE="pairing",$E="0.3",ko={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}}},Nn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},PE="history",TE="0.3",NE="expirer",on={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},RE="0.3",hh="verify-api",ng="https://verify.walletconnect.com";class LE{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=fE,this.version=dE,this.initialized=!1,this.storagePrefix=di,this.init=async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:o}=_e("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(o)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=pt.generateChildLogger(r,this.name)}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,T1(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?N1(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class ME{constructor(e,r,n){this.core=e,this.logger=r,this.name=uE,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();const i=await this.getClientSeed(),o=wp(i);return mp(o.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const i=z5();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const o=await this.getClientSeed(),c=wp(o),l=Du();return await V4(l,i,hE,c)},this.generateSharedKey=(i,o,c)=>{this.isInitialized();const l=this.getPrivateKey(i),h=W5(l,o);return this.setSymKey(h,c)},this.setSymKey=async(i,o)=>{this.isInitialized();const c=o||q5(i);return await this.keychain.set(c,i),c},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,o,c)=>{this.isInitialized();const l=S1(c),h=Mo(o);if(O1(l)){const _=l.senderPublicKey,S=l.receiverPublicKey;i=await this.generateSharedKey(_,S)}const f=this.getSymKey(i),{type:v,senderPublicKey:x}=l;return K5({type:v,symKey:f,message:h,senderPublicKey:x})},this.decode=async(i,o,c)=>{this.isInitialized();const l=Y5(o,c);if(O1(l)){const h=l.receiverPublicKey,f=l.senderPublicKey;i=await this.generateSharedKey(h,f)}try{const h=this.getSymKey(i),f=G5({symKey:h,encoded:o});return Ju(f)}catch(h){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(h)}},this.getPayloadType=i=>{const o=Ga(i);return So(o.type)},this.getPayloadSenderPublicKey=i=>{const o=Ga(i);return o.senderPublicKey?Dr(o.senderPublicKey,$r):void 0},this.core=e,this.logger=pt.generateChildLogger(r,this.name),this.keychain=n||new LE(this.core,this.logger)}get context(){return pt.getLoggerContext(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Qp)}catch{e=Du(),await this.keychain.set(Qp,e)}return oE(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class UE extends E4{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=pE,this.version=gE,this.initialized=!1,this.storagePrefix=di,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();const o=Ss(i);let c=this.messages.get(n);return typeof c>"u"&&(c={}),typeof c[o]<"u"||(c[o]=i,this.messages.set(n,c),await this.persist()),o},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();const o=this.get(n),c=Ss(i);return typeof o[c]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=pt.generateChildLogger(e,this.name),this.core=r}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,T1(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?N1(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class jE extends x4{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new br.exports.EventEmitter,this.name=wE,this.queue=new Map,this.publishTimeout=De.toMiliseconds(De.TEN_SECONDS),this.queueTimeout=De.toMiliseconds(De.FIVE_SECONDS),this.needsTransportRestart=!1,this.publish=async(n,i,o)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:o}});try{const c=o?.ttl||mE,l=Ru(o),h=o?.prompt||!1,f=o?.tag||0,v=o?.id||nh().toString(),x={topic:n,message:i,opts:{ttl:c,relay:l,prompt:h,tag:f,id:v}},_=setTimeout(()=>this.queue.set(v,x),this.queueTimeout);try{await await Za(this.rpcPublish(n,i,c,l,h,f,v),this.publishTimeout),clearTimeout(_),this.relayer.events.emit(kt.publish,x)}catch{this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0;return}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:o}})}catch(c){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(c),c}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=pt.generateChildLogger(r,this.name),this.registerEventListeners()}get context(){return pt.getLoggerContext(this.logger)}rpcPublish(e,r,n,i,o,c,l){var h,f,v,x;const _={method:Ya(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:o,tag:c},id:l};return Pr((h=_.params)==null?void 0:h.prompt)&&((f=_.params)==null||delete f.prompt),Pr((v=_.params)==null?void 0:v.tag)&&((x=_.params)==null||delete x.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:_}),this.relayer.request(_)}onPublish(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(Ps.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(kt.connection_stalled);return}this.checkQueue()}),this.relayer.on(kt.message_ack,e=>{this.onPublish(e.id.toString())})}}class FE{constructor(){this.map=new Map,this.set=(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(o=>o!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var BE=Object.defineProperty,kE=Object.defineProperties,HE=Object.getOwnPropertyDescriptors,ig=Object.getOwnPropertySymbols,zE=Object.prototype.hasOwnProperty,WE=Object.prototype.propertyIsEnumerable,sg=(t,e,r)=>e in t?BE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ho=(t,e)=>{for(var r in e||(e={}))zE.call(e,r)&&sg(t,r,e[r]);if(ig)for(var r of ig(e))WE.call(e,r)&&sg(t,r,e[r]);return t},fh=(t,e)=>kE(t,HE(e));class qE extends S4{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new FE,this.events=new br.exports.EventEmitter,this.name=SE,this.version=OE,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=di,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restart(),this.registerEventListeners(),this.onEnable(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const o=Ru(i),c={topic:n,relay:o};this.pending.set(n,c);const l=await this.rpcSubscribe(n,o);return this.onSubscribe(l,c),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}}),l}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>this.topics.includes(n)?!0:await new Promise((i,o)=>{const c=new De.Watch;c.start(this.pendingSubscriptionWatchLabel);const l=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(l),c.stop(this.pendingSubscriptionWatchLabel),i(!0)),c.elapsed(this.pendingSubscriptionWatchLabel)>=AE&&(clearInterval(l),c.stop(this.pendingSubscriptionWatchLabel),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=pt.generateChildLogger(r,this.name),this.clientId=""}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=Ru(n);await this.rpcUnsubscribe(e,r,i);const o=Yt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,o),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){const n={method:Ya(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await Za(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(kt.connection_stalled)}return Ss(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Ya(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 Za(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(kt.connection_stalled)}}rpcUnsubscribe(e,r,n){const i={method:Ya(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,fh(Ho({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Ho({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r))}addSubscription(e,r){this.subscriptions.set(e,Ho({},r)),this.topicMap.set(r.topic,e),this.events.emit(Tn.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(Tn.deleted,fh(Ho({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Tn.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<e;r++){const n=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}}this.events.emit(Tn.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;const r=await this.rpcBatchSubscribe(e);Pn(r)&&this.onBatchSubscribe(r.map((n,i)=>fh(Ho({},e[i]),{id:n})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(Ps.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(kt.connect,async()=>{await this.onConnect()}),this.relayer.on(kt.disconnect,()=>{this.onDisconnect()}),this.events.on(Tn.created,async e=>{const r=Tn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(Tn.deleted,async e=>{const r=Tn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}}var VE=Object.defineProperty,og=Object.getOwnPropertySymbols,KE=Object.prototype.hasOwnProperty,GE=Object.prototype.propertyIsEnumerable,ag=(t,e,r)=>e in t?VE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ZE=(t,e)=>{for(var r in e||(e={}))KE.call(e,r)&&ag(t,r,e[r]);if(og)for(var r of og(e))GE.call(e,r)&&ag(t,r,e[r]);return t};class YE extends C4{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new br.exports.EventEmitter,this.name=yE,this.transportExplicitlyClosed=!1,this.initialized=!1,this.reconnecting=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],this.request=async r=>{this.logger.debug("Publishing Request Payload");try{return await this.toEstablishConnection(),await this.provider.request(r)}catch(n){throw this.logger.debug("Failed to Publish Request"),this.logger.error(n),n}},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?pt.generateChildLogger(e.logger,this.name):pt.pino(pt.getDefaultLoggerOptions({level:e.logger||vE})),this.messages=new UE(this.logger,e.core),this.subscriber=new qE(this,this.logger),this.publisher=new jE(this,this.logger),this.relayUrl=e?.relayUrl||tg,this.projectId=e.projectId,this.provider={}}async init(){this.logger.trace("Initialized"),await this.createProvider(),await Promise.all([this.messages.init(),this.subscriber.init()]);try{await this.transportOpen()}catch{this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${rg}...`),await this.restartTransport(rg)}this.registerEventListeners(),this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},xE)}get context(){return pt.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"";return i||(await Promise.all([new Promise(o=>{this.subscriber.once(Tn.created,c=>{c.topic===e&&o()})}),new Promise(async o=>{i=await this.subscriber.subscribe(e,r),o()})]),i)}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportClose(){this.transportExplicitlyClosed=!0,this.connected&&(await this.provider.disconnect(),this.events.emit(kt.transport_closed))}async transportOpen(e){if(this.transportExplicitlyClosed=!1,!this.reconnecting){this.relayUrl=e||this.relayUrl,this.reconnecting=!0;try{await Promise.all([new Promise(r=>{this.initialized||r(),this.subscriber.once(Tn.resubscribed,()=>{r()})}),await Promise.race([new Promise(async(r,n)=>{await Za(this.provider.connect(),1e4,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(i=>n(i)).then(()=>r()).finally(()=>this.removeListener(kt.transport_closed,this.rejectTransportOpen))}),new Promise(r=>this.once(kt.transport_closed,this.rejectTransportOpen))])])}catch(r){this.logger.error(r);const n=r;if(!this.isConnectionStalled(n.message))throw r;this.events.emit(kt.transport_closed)}finally{this.reconnecting=!1}}}async restartTransport(e){this.transportExplicitlyClosed||this.reconnecting||(this.relayUrl=e||this.relayUrl,this.connected&&await Promise.all([new Promise(r=>{this.provider.once(Bo.disconnect,()=>{r()})}),this.transportClose()]),await this.createProvider(),await this.transportOpen())}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}rejectTransportOpen(){throw new Error("Attempt to connect to relay via `transportOpen` has stalled. Retrying...")}async createProvider(){const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new fi(new R_(ab({sdkVersion:EE,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;const i=this.messages.has(r,n);return i&&this.logger.debug(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),sh(e)){if(!e.method.endsWith(bE))return;const r=e.params,{topic:n,message:i,publishedAt:o}=r.data,c={topic:n,message:i,publishedAt:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(ZE({type:"event",event:r.id},c)),this.events.emit(r.id,c),await this.acknowledgePayload(e),await this.onMessageEvent(c)}else sc(e)&&this.events.emit(kt.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(kt.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=ih(e.id,!0);await this.provider.connection.send(r)}registerProviderListeners(){this.provider.on(Bo.payload,e=>this.onProviderPayload(e)),this.provider.on(Bo.connect,()=>{this.events.emit(kt.connect)}),this.provider.on(Bo.disconnect,()=>{this.onProviderDisconnect()}),this.provider.on(Bo.error,e=>{this.logger.error(e),this.events.emit(kt.error,e)})}registerEventListeners(){this.events.on(kt.connection_stalled,async()=>{await this.restartTransport()})}onProviderDisconnect(){this.events.emit(kt.disconnect),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||setTimeout(async()=>{await this.restartTransport()},De.toMiliseconds(_E))}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(!this.connected){if(this.connecting)return await new Promise(e=>{const r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)});await this.restartTransport()}}}var JE=Object.defineProperty,cg=Object.getOwnPropertySymbols,XE=Object.prototype.hasOwnProperty,QE=Object.prototype.propertyIsEnumerable,lg=(t,e,r)=>e in t?JE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ug=(t,e)=>{for(var r in e||(e={}))XE.call(e,r)&&lg(t,r,e[r]);if(cg)for(var r of cg(e))QE.call(e,r)&&lg(t,r,e[r]);return t};class ac extends I4{constructor(e,r,n,i=di,o=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=CE,this.cached=[],this.initialized=!1,this.storagePrefix=di,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(c=>{this.getKey&&c!==null&&!Pr(c)?this.map.set(this.getKey(c),c):$b(c)?this.map.set(c.id,c):Pb(c)&&this.map.set(c.topic,c)}),this.cached=[],this.initialized=!0)},this.set=async(c,l)=>{this.isInitialized(),this.map.has(c)?await this.update(c,l):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:c,value:l}),this.map.set(c,l),await this.persist())},this.get=c=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:c}),this.getData(c)),this.getAll=c=>(this.isInitialized(),c?this.values.filter(l=>Object.keys(c).every(h=>L_(l[h],c[h]))):this.values),this.update=async(c,l)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:c,update:l});const h=ug(ug({},this.getData(c)),l);this.map.set(c,h),await this.persist()},this.delete=async(c,l)=>{this.isInitialized(),this.map.has(c)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:c,reason:l}),this.map.delete(c),await this.persist())},this.logger=pt.generateChildLogger(r,this.name),this.storagePrefix=i,this.getKey=o}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){const{message:n}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class e7{constructor(e,r){this.core=e,this.logger=r,this.name=DE,this.version=$E,this.events=new br.exports,this.initialized=!1,this.storagePrefix=di,this.ignoredPayloadTypes=[ki],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=Du(),i=await this.core.crypto.setSymKey(n),o=En(De.FIVE_MINUTES),c={protocol:eg},l={topic:i,expiry:o,relay:c,active:!1},h=bb({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:n,relay:c});return await this.pairings.set(i,l),await this.core.relayer.subscribe(i),this.core.expirer.set(i,o),{topic:i,uri:h}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);const{topic:i,symKey:o,relay:c}=wb(n.uri);if(this.pairings.keys.includes(i))throw new Error(`Pairing already exists: ${i}`);if(this.core.crypto.hasKeys(i))throw new Error(`Keychain already exists: ${i}`);const l=En(De.FIVE_MINUTES),h={topic:i,relay:c,expiry:l,active:!1};return await this.pairings.set(i,h),await this.core.crypto.setSymKey(o,i),await this.core.relayer.subscribe(i,{relay:c}),this.core.expirer.set(i,l),n.activatePairing&&await this.activate({topic:i}),h},this.activate=async({topic:n})=>{this.isInitialized();const i=En(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 o=await this.sendRequest(i,"wc_pairingPing",{}),{done:c,resolve:l,reject:h}=Os();this.events.once(rr("pairing_ping",o),({error:f})=>{f?h(f):l()}),await c()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",Yt("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,o)=>{const c=nc(i,o),l=await this.core.crypto.encode(n,c),h=ko[i].req;return this.core.history.set(n,c),this.core.relayer.publish(n,l,h),c.id},this.sendResult=async(n,i,o)=>{const c=ih(n,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,n),f=ko[h.request.method].res;await this.core.relayer.publish(i,l,f),await this.core.history.resolve(c)},this.sendError=async(n,i,o)=>{const c=ic(n,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,n),f=ko[h.request.method]?ko[h.request.method].res:ko.unregistered_method.res;await this.core.relayer.publish(i,l,f),await this.core.history.resolve(c)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Yt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{const n=this.pairings.getAll().filter(i=>hi(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{const{topic:i,payload:o}=n;switch(o.method){case"wc_pairingPing":return this.onPairingPingRequest(i,o);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,o);default:return this.onUnknownRpcMethodRequest(i,o)}},this.onRelayEventResponse=async n=>{const{topic:i,payload:o}=n,c=(await this.core.history.get(i,o.id)).request.method;switch(c){case"wc_pairingPing":return this.onPairingPingResponse(i,o);default:return this.onUnknownRpcMethodResponse(c)}},this.onPairingPingRequest=async(n,i)=>{const{id:o}=i;try{this.isValidPing({topic:n}),await this.sendResult(o,n,!0),this.events.emit("pairing_ping",{id:o,topic:n})}catch(c){await this.sendError(o,n,c),this.logger.error(c)}},this.onPairingPingResponse=(n,i)=>{const{id:o}=i;setTimeout(()=>{Vn(i)?this.events.emit(rr("pairing_ping",o),{}):xn(i)&&this.events.emit(rr("pairing_ping",o),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{const{id:o}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit("pairing_delete",{id:o,topic:n})}catch(c){await this.sendError(o,n,c),this.logger.error(c)}},this.onUnknownRpcMethodRequest=async(n,i)=>{const{id:o,method:c}=i;try{if(this.registeredMethods.includes(c))return;const l=Yt("WC_METHOD_UNSUPPORTED",c);await this.sendError(o,n,l),this.logger.error(l)}catch(l){await this.sendError(o,n,l),this.logger.error(l)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(Yt("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{if(!zr(n)){const{message:i}=_e("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(i)}if(!Db(n.uri)){const{message:i}=_e("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(i)}},this.isValidPing=async n=>{if(!zr(n)){const{message:o}=_e("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(o)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!zr(n)){const{message:o}=_e("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(o)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!gr(n,!1)){const{message:i}=_e("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=_e("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(hi(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=_e("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=pt.generateChildLogger(r,this.name),this.pairings=new ac(this.core,this.logger,this.name,this.storagePrefix)}get context(){return pt.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(kt.message,async e=>{const{topic:r,message:n}=e;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;const i=await this.core.crypto.decode(r,n);try{sh(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):sc(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.core.history.delete(r,i.id))}catch(o){this.logger.error(o)}})}registerExpirerEvents(){this.core.expirer.on(on.expired,async e=>{const{topic:r}=L1(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit("pairing_expire",{topic:r}))})}}class t7 extends _4{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new br.exports.EventEmitter,this.name=PE,this.version=TE,this.cached=[],this.initialized=!1,this.storagePrefix=di,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,o)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:o}),this.records.has(i.id))return;const c={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:o,expiry:En(De.THIRTY_DAYS)};this.records.set(c.id,c),this.events.emit(Nn.created,c)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=xn(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.events.emit(Nn.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(o=>{if(o.topic===n){if(typeof i<"u"&&o.id!==i)return;this.records.delete(o.id),this.events.emit(Nn.deleted,o)}})},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=pt.generateChildLogger(r,this.name)}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:nc(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:n}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Nn.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Nn.created,e=>{const r=Nn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(Nn.updated,e=>{const r=Nn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(Nn.deleted,e=>{const r=Nn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.core.heartbeat.on(Ps.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.records.forEach(e=>{De.toMiliseconds(e.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${e.id}`),this.delete(e.topic,e.id))})}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class r7 extends O4{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new br.exports.EventEmitter,this.name=NE,this.version=RE,this.cached=[],this.initialized=!1,this.storagePrefix=di,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();const o=this.formatTarget(n),c={target:o,expiry:i};this.expirations.set(o,c),this.checkExpiry(o,c),this.events.emit(on.created,{target:o,expiration:c})},this.get=n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),o=this.getExpiration(i);this.expirations.delete(i),this.events.emit(on.deleted,{target:i,expiration:o})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=pt.generateChildLogger(r,this.name)}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return cb(e);if(typeof e=="number")return lb(e);const{message:r}=_e("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(on.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:n}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;De.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(on.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Ps.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(on.created,e=>{const r=on.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(on.expired,e=>{const r=on.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(on.deleted,e=>{const r=on.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class n7 extends A4{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=hh,this.initialized=!1,this.init=async n=>{P1()||!Pu()||(this.verifyUrl=n?.verifyUrl||ng,await this.createIframe())},this.register=async n=>{var i;if(this.initialized||await this.init(),!!this.iframe)try{(i=this.iframe.contentWindow)==null||i.postMessage(n.attestationId,this.verifyUrl),this.logger.info(`postMessage sent: ${n.attestationId} ${this.verifyUrl}`)}catch{}},this.resolve=async n=>{var i;if(this.isDevEnv)return"";this.logger.info(`resolving attestation: ${n.attestationId}`);const o=this.startAbortTimer(De.FIVE_SECONDS),c=await fetch(`${this.verifyUrl}/attestation/${n.attestationId}`,{signal:this.abortController.signal});return clearTimeout(o),c.status===200?(i=await c.json())==null?void 0:i.origin:""},this.createIframe=async()=>{try{await Promise.race([new Promise((n,i)=>{if(document.getElementById(hh))return n();const o=document.createElement("iframe");o.setAttribute("id",hh),o.setAttribute("src",`${this.verifyUrl}/${this.projectId}`),o.style.display="none",o.addEventListener("load",()=>{this.initialized=!0,n()}),o.addEventListener("error",c=>{i(c)}),document.body.append(o),this.iframe=o}),new Promise(n=>{setTimeout(()=>n("iframe load timeout"),De.toMiliseconds(De.ONE_SECOND/2))})])}catch(n){this.logger.error(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.error(n)}},this.logger=pt.generateChildLogger(r,this.name),this.verifyUrl=ng,this.abortController=new AbortController,this.isDevEnv=$u()&&process.env.IS_VITEST}get context(){return pt.getLoggerContext(this.logger)}startAbortTimer(e){return setTimeout(()=>this.abortController.abort(),De.toMiliseconds(e))}}var i7=Object.defineProperty,hg=Object.getOwnPropertySymbols,s7=Object.prototype.hasOwnProperty,o7=Object.prototype.propertyIsEnumerable,fg=(t,e,r)=>e in t?i7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,dg=(t,e)=>{for(var r in e||(e={}))s7.call(e,r)&&fg(t,r,e[r]);if(hg)for(var r of hg(e))o7.call(e,r)&&fg(t,r,e[r]);return t};class dh extends b4{constructor(e){super(e),this.protocol=Xp,this.version=aE,this.name=uh,this.events=new br.exports.EventEmitter,this.initialized=!1,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||tg;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||cE.logger}));this.logger=pt.generateChildLogger(r,this.name),this.heartbeat=new Ps.HeartBeat,this.crypto=new ME(this,this.logger,e?.keychain),this.history=new t7(this,this.logger),this.expirer=new r7(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new C6(dg(dg({},lE),e?.storageOptions)),this.relayer=new YE({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new e7(this,this.logger),this.verify=new n7(this.projectId||"",this.logger)}static async init(e){const r=new dh(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(IE,n),r}get context(){return pt.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const a7=dh,pg="wc",gg=2,mg="client",ph=`${pg}@${gg}:${mg}:`,gh={name:mg,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},wg="WALLETCONNECT_DEEPLINK_CHOICE",c7="proposal",vg="Proposal expired",l7="session",cc=De.SEVEN_DAYS,u7="engine",zo={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}}},mh={min:De.FIVE_MINUTES,max:De.SEVEN_DAYS},Wo={idle:"idle",active:"active"},h7="request",f7=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var d7=Object.defineProperty,p7=Object.defineProperties,g7=Object.getOwnPropertyDescriptors,yg=Object.getOwnPropertySymbols,m7=Object.prototype.hasOwnProperty,w7=Object.prototype.propertyIsEnumerable,bg=(t,e,r)=>e in t?d7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,an=(t,e)=>{for(var r in e||(e={}))m7.call(e,r)&&bg(t,r,e[r]);if(yg)for(var r of yg(e))w7.call(e,r)&&bg(t,r,e[r]);return t},wh=(t,e)=>p7(t,g7(e));class v7 extends $4{constructor(e){super(e),this.name=u7,this.events=new br.exports,this.initialized=!1,this.ignoredPayloadTypes=[ki],this.requestQueue={state:Wo.idle,requests:[]},this.requestQueueDelay=De.ONE_SECOND,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.client.core.pairing.register({methods:Object.keys(zo)}),this.initialized=!0,setTimeout(()=>{this.requestQueue.requests=this.getPendingSessionRequests(),this.processRequestQueue()},De.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{this.isInitialized();const n=wh(an({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:o,optionalNamespaces:c,sessionProperties:l,relays:h}=n;let f=i,v,x=!1;if(f&&(x=this.client.core.pairing.pairings.get(f).active),!f||!x){const{topic:L,uri:$}=await this.client.core.pairing.create();f=L,v=$}const _=await this.client.core.crypto.generateKeyPair(),S=an({requiredNamespaces:o,optionalNamespaces:c,relays:h??[{protocol:eg}],proposer:{publicKey:_,metadata:this.client.metadata}},l&&{sessionProperties:l}),{reject:P,resolve:j,done:H}=Os(De.FIVE_MINUTES,vg);if(this.events.once(rr("session_connect"),async({error:L,session:$})=>{if(L)P(L);else if($){$.self.publicKey=_;const T=wh(an({},$),{requiredNamespaces:$.requiredNamespaces,optionalNamespaces:$.optionalNamespaces});await this.client.session.set($.topic,T),await this.setExpiry($.topic,$.expiry),f&&await this.client.core.pairing.updateMetadata({topic:f,metadata:$.peer.metadata}),j(T)}}),!f){const{message:L}=_e("NO_MATCHING_KEY",`connect() pairing topic: ${f}`);throw new Error(L)}const Z=await this.sendRequest(f,"wc_sessionPropose",S),R=En(De.FIVE_MINUTES);return await this.setProposal(Z,an({id:Z,expiry:R},S)),{uri:v,approval:H}},this.pair=async r=>(this.isInitialized(),await this.client.core.pairing.pair(r)),this.approve=async r=>{this.isInitialized(),await this.isValidApprove(r);const{id:n,relayProtocol:i,namespaces:o,sessionProperties:c}=r,l=this.client.proposal.get(n);let{pairingTopic:h,proposer:f,requiredNamespaces:v,optionalNamespaces:x}=l;h=h||"",Ds(v)||(v=Cb(o,"approve()"));const _=await this.client.core.crypto.generateKeyPair(),S=f.publicKey,P=await this.client.core.crypto.generateSharedKey(_,S);h&&n&&(await this.client.core.pairing.updateMetadata({topic:h,metadata:f.metadata}),await this.sendResult(n,h,{relay:{protocol:i??"irn"},responderPublicKey:_}),await this.client.proposal.delete(n,Yt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:h}));const j=an({relay:{protocol:i??"irn"},namespaces:o,requiredNamespaces:v,optionalNamespaces:x,pairingTopic:h,controller:{publicKey:_,metadata:this.client.metadata},expiry:En(cc)},c&&{sessionProperties:c});await this.client.core.relayer.subscribe(P),await this.sendRequest(P,"wc_sessionSettle",j);const H=wh(an({},j),{topic:P,pairingTopic:h,acknowledged:!1,self:j.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:_});return await this.client.session.set(P,H),await this.setExpiry(P,En(cc)),{topic:P,acknowledged:()=>new Promise(Z=>setTimeout(()=>Z(this.client.session.get(P)),500))}},this.reject=async r=>{this.isInitialized(),await this.isValidReject(r);const{id:n,reason:i}=r,{pairingTopic:o}=this.client.proposal.get(n);o&&(await this.sendError(n,o,i),await this.client.proposal.delete(n,Yt("USER_DISCONNECTED")))},this.update=async r=>{this.isInitialized(),await this.isValidUpdate(r);const{topic:n,namespaces:i}=r,o=await this.sendRequest(n,"wc_sessionUpdate",{namespaces:i}),{done:c,resolve:l,reject:h}=Os();return this.events.once(rr("session_update",o),({error:f})=>{f?h(f):l()}),await this.client.session.update(n,{namespaces:i}),{acknowledged:c}},this.extend=async r=>{this.isInitialized(),await this.isValidExtend(r);const{topic:n}=r,i=await this.sendRequest(n,"wc_sessionExtend",{}),{done:o,resolve:c,reject:l}=Os();return this.events.once(rr("session_extend",i),({error:h})=>{h?l(h):c()}),await this.setExpiry(n,En(cc)),{acknowledged:o}},this.request=async r=>{this.isInitialized(),await this.isValidRequest(r);const{chainId:n,request:i,topic:o,expiry:c}=r,l=await this.sendRequest(o,"wc_sessionRequest",{request:i,chainId:n},c),{done:h,resolve:f,reject:v}=Os(c);this.events.once(rr("session_request",l),({error:_,result:S})=>{_?v(_):f(S)}),this.client.events.emit("session_request_sent",{topic:o,request:i,chainId:n,id:l});const x=await this.client.core.storage.getItem(wg);return ub({id:l,topic:o,wcDeepLink:x}),await h()},this.respond=async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:o}=i;Vn(i)?await this.sendResult(o,n,i.result):xn(i)&&await this.sendError(o,n,i.error),this.cleanupAfterResponse(r)},this.ping=async r=>{this.isInitialized(),await this.isValidPing(r);const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=await this.sendRequest(n,"wc_sessionPing",{}),{done:o,resolve:c,reject:l}=Os();this.events.once(rr("session_ping",i),({error:h})=>{h?l(h):c()}),await o()}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{this.isInitialized(),await this.isValidEmit(r);const{topic:n,event:i,chainId:o}=r;await this.sendRequest(n,"wc_sessionEvent",{event:i,chainId:o})},this.disconnect=async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=nh().toString();let o;const c=l=>{l?.id.toString()===i&&(this.client.core.relayer.events.removeListener(kt.message_ack,c),o())};await Promise.all([new Promise(l=>{o=l,this.client.core.relayer.on(kt.message_ack,c)}),this.sendRequest(n,"wc_sessionDelete",Yt("USER_DISCONNECTED"),void 0,i)]),await this.deleteSession(n)}else await this.client.core.pairing.disconnect({topic:n})},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>Ob(n,r))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{const n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(o=>{var c,l;return((c=o.peerMetadata)==null?void 0:c.url)&&((l=o.peerMetadata)==null?void 0:l.url)===r.peer.metadata.url&&o.topic&&o.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(o=>this.client.core.pairing.disconnect({topic:o.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async(r,n)=>{const{self:i}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),this.client.session.delete(r,Yt("USER_DISCONNECTED")),this.client.core.crypto.keychain.has(i.publicKey)&&await this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(wg).catch(o=>this.client.logger.warn(o))},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,Yt("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.requestQueue.requests=this.requestQueue.requests.filter(o=>o.id!==r),i&&(this.requestQueue.state=Wo.idle)},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:n}),this.client.core.expirer.set(r,n)},this.setProposal=async(r,n)=>{await this.client.proposal.set(r,n),this.client.core.expirer.set(r,n.expiry)},this.setPendingSessionRequest=async r=>{const n=zo.wc_sessionRequest.req.ttl,{id:i,topic:o,params:c}=r;await this.client.pendingRequest.set(i,{id:i,topic:o,params:c}),n&&this.client.core.expirer.set(i,En(n))},this.sendRequest=async(r,n,i,o,c)=>{const l=nc(n,i);if(Pu()&&f7.includes(n)){const v=Ss(JSON.stringify(l));await this.client.core.verify.register({attestationId:v})}const h=await this.client.core.crypto.encode(r,l),f=zo[n].req;return o&&(f.ttl=o),c&&(f.id=c),this.client.core.history.set(r,l),this.client.core.relayer.publish(r,h,f),l.id},this.sendResult=async(r,n,i)=>{const o=ih(r,i),c=await this.client.core.crypto.encode(n,o),l=await this.client.core.history.get(n,r),h=zo[l.request.method].res;this.client.core.relayer.publish(n,c,h),await this.client.core.history.resolve(o)},this.sendError=async(r,n,i)=>{const o=ic(r,i),c=await this.client.core.crypto.encode(n,o),l=await this.client.core.history.get(n,r),h=zo[l.request.method].res;this.client.core.relayer.publish(n,c,h),await this.client.core.history.resolve(o)},this.cleanup=async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{hi(i.expiry)&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{hi(i.expiry)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession(i)),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=r=>{const{topic:n,payload:i}=r,o=i.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${o}`)}},this.onRelayEventResponse=async r=>{const{topic:n,payload:i}=r,o=(await this.client.core.history.get(n,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}},this.onRelayEventUnknownPayload=r=>{const{topic:n}=r,{message:i}=_e("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.onSessionProposeRequest=async(r,n)=>{const{params:i,id:o}=n;try{this.isValidConnect(an({},n.params));const c=En(De.FIVE_MINUTES),l=an({id:o,pairingTopic:r,expiry:c},i);await this.setProposal(o,l);const h=Ss(JSON.stringify(n)),f=await this.getVerifyContext(h,l.proposer.metadata);this.client.events.emit("session_proposal",{id:o,params:l,verifyContext:f})}catch(c){await this.sendError(o,r,c),this.client.logger.error(c)}},this.onSessionProposeResponse=async(r,n)=>{const{id:i}=n;if(Vn(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const c=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:c});const l=c.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:l});const h=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const f=await this.client.core.crypto.generateSharedKey(l,h);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:f});const v=await this.client.core.relayer.subscribe(f);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:v}),await this.client.core.pairing.activate({topic:r})}else xn(n)&&(await this.client.proposal.delete(i,Yt("USER_DISCONNECTED")),this.events.emit(rr("session_connect"),{error:n.error}))},this.onSessionSettleRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidSessionSettleRequest(o);const{relay:c,controller:l,expiry:h,namespaces:f,requiredNamespaces:v,optionalNamespaces:x,sessionProperties:_,pairingTopic:S}=n.params,P=an({topic:r,relay:c,expiry:h,namespaces:f,acknowledged:!0,pairingTopic:S,requiredNamespaces:v,optionalNamespaces:x,controller:l.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:l.publicKey,metadata:l.metadata}},_&&{sessionProperties:_});await this.sendResult(n.id,r,!0),this.events.emit(rr("session_connect"),{session:P}),this.cleanupDuplicatePairings(P)}catch(c){await this.sendError(i,r,c),this.client.logger.error(c)}},this.onSessionSettleResponse=async(r,n)=>{const{id:i}=n;Vn(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(rr("session_approve",i),{})):xn(n)&&(await this.client.session.delete(r,Yt("USER_DISCONNECTED")),this.events.emit(rr("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{const{params:i,id:o}=n;try{this.isValidUpdate(an({topic:r},i)),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult(o,r,!0),this.client.events.emit("session_update",{id:o,topic:r,params:i})}catch(c){await this.sendError(o,r,c),this.client.logger.error(c)}},this.onSessionUpdateResponse=(r,n)=>{const{id:i}=n;Vn(n)?this.events.emit(rr("session_update",i),{}):xn(n)&&this.events.emit(rr("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,En(cc)),await this.sendResult(i,r,!0),this.client.events.emit("session_extend",{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionExtendResponse=(r,n)=>{const{id:i}=n;Vn(n)?this.events.emit(rr("session_extend",i),{}):xn(n)&&this.events.emit(rr("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult(i,r,!0),this.client.events.emit("session_ping",{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionPingResponse=(r,n)=>{const{id:i}=n;setTimeout(()=>{Vn(n)?this.events.emit(rr("session_ping",i),{}):xn(n)&&this.events.emit(rr("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(o=>{this.client.core.relayer.once(kt.publish,async()=>{o(await this.deleteSession(r))})}),this.sendResult(i,r,!0)]),this.client.events.emit("session_delete",{id:i,topic:r})}catch(o){this.client.logger.error(o)}},this.onSessionRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidRequest(an({topic:r},o)),await this.setPendingSessionRequest({id:i,topic:r,params:o}),this.addRequestToQueue({id:i,topic:r,params:o}),await this.processRequestQueue()}catch(c){await this.sendError(i,r,c),this.client.logger.error(c)}},this.onSessionRequestResponse=(r,n)=>{const{id:i}=n;Vn(n)?this.events.emit(rr("session_request",i),{result:n.result}):xn(n)&&this.events.emit(rr("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidEmit(an({topic:r},o)),this.client.events.emit("session_event",{id:i,topic:r,params:o})}catch(c){await this.sendError(i,r,c),this.client.logger.error(c)}},this.addRequestToQueue=r=>{this.requestQueue.requests.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.requestQueue.state=Wo.idle,this.processRequestQueue()},De.toMiliseconds(this.requestQueueDelay))},this.processRequestQueue=async()=>{if(this.requestQueue.state===Wo.active){this.client.logger.info("session request queue is already active.");return}const r=this.requestQueue.requests[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{const{id:n,topic:i,params:o}=r,c=Ss(JSON.stringify({id:n,params:o})),l=this.client.session.get(i),h=await this.getVerifyContext(c,l.peer.metadata);this.requestQueue.state=Wo.active,this.client.events.emit("session_request",{id:n,topic:i,params:o,verifyContext:h})}catch(n){this.client.logger.error(n)}},this.isValidConnect=async r=>{if(!zr(r)){const{message:h}=_e("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(h)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:c,relays:l}=r;if(Pr(n)||await this.isValidPairingTopic(n),!Fb(l,!0)){const{message:h}=_e("MISSING_OR_INVALID",`connect() relays: ${l}`);throw new Error(h)}!Pr(i)&&Ds(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Pr(o)&&Ds(o)!==0&&this.validateNamespaces(o,"optionalNamespaces"),Pr(c)||this.validateSessionProps(c,"sessionProperties")},this.validateNamespaces=(r,n)=>{const i=jb(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!zr(r))throw new Error(_e("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:o,sessionProperties:c}=r;await this.isValidProposalId(n);const l=this.client.proposal.get(n),h=Qa(i,"approve()");if(h)throw new Error(h.message);const f=H1(l.requiredNamespaces,i,"approve()");if(f)throw new Error(f.message);if(!gr(o,!0)){const{message:v}=_e("MISSING_OR_INVALID",`approve() relayProtocol: ${o}`);throw new Error(v)}Pr(c)||this.validateSessionProps(c,"sessionProperties")},this.isValidReject=async r=>{if(!zr(r)){const{message:o}=_e("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(o)}const{id:n,reason:i}=r;if(await this.isValidProposalId(n),!kb(i)){const{message:o}=_e("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidSessionSettleRequest=r=>{if(!zr(r)){const{message:f}=_e("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(f)}const{relay:n,controller:i,namespaces:o,expiry:c}=r;if(!B1(n)){const{message:f}=_e("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(f)}const l=Tb(i,"onSessionSettleRequest()");if(l)throw new Error(l.message);const h=Qa(o,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(hi(c)){const{message:f}=_e("EXPIRED","onSessionSettleRequest()");throw new Error(f)}},this.isValidUpdate=async r=>{if(!zr(r)){const{message:h}=_e("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(h)}const{topic:n,namespaces:i}=r;await this.isValidSessionTopic(n);const o=this.client.session.get(n),c=Qa(i,"update()");if(c)throw new Error(c.message);const l=H1(o.requiredNamespaces,i,"update()");if(l)throw new Error(l.message)},this.isValidExtend=async r=>{if(!zr(r)){const{message:i}=_e("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!zr(r)){const{message:h}=_e("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(h)}const{topic:n,request:i,chainId:o,expiry:c}=r;await this.isValidSessionTopic(n);const{namespaces:l}=this.client.session.get(n);if(!k1(l,o)){const{message:h}=_e("MISSING_OR_INVALID",`request() chainId: ${o}`);throw new Error(h)}if(!Hb(i)){const{message:h}=_e("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(h)}if(!qb(l,o,i.method)){const{message:h}=_e("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(h)}if(c&&!Zb(c,mh)){const{message:h}=_e("MISSING_OR_INVALID",`request() expiry: ${c}. Expiry must be a number (in seconds) between ${mh.min} and ${mh.max}`);throw new Error(h)}},this.isValidRespond=async r=>{if(!zr(r)){const{message:o}=_e("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:n,response:i}=r;if(await this.isValidSessionTopic(n),!zb(i)){const{message:o}=_e("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidPing=async r=>{if(!zr(r)){const{message:i}=_e("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!zr(r)){const{message:l}=_e("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(l)}const{topic:n,event:i,chainId:o}=r;await this.isValidSessionTopic(n);const{namespaces:c}=this.client.session.get(n);if(!k1(c,o)){const{message:l}=_e("MISSING_OR_INVALID",`emit() chainId: ${o}`);throw new Error(l)}if(!Wb(i)){const{message:l}=_e("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}if(!Vb(c,o,i.name)){const{message:l}=_e("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}},this.isValidDisconnect=async r=>{if(!zr(r)){const{message:i}=_e("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.getVerifyContext=async(r,n)=>{const i={verified:{verifyUrl:n.verifyUrl||"",validation:"UNKNOWN",origin:n.url||""}};try{const o=await this.client.core.verify.resolve({attestationId:r,verifyUrl:n.verifyUrl});o&&(i.verified.origin=o,i.verified.validation=o===n.url?"VALID":"INVALID")}catch(o){this.client.logger.error(o)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!gr(i,!1)){const{message:o}=_e("MISSING_OR_INVALID",`${n} must be in Record<string, string> format. Received: ${JSON.stringify(i)}`);throw new Error(o)}})}}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.client.core.relayer.on(kt.message,async e=>{const{topic:r,message:n}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(n)))return;const i=await this.client.core.crypto.decode(r,n);try{sh(i)?(this.client.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):sc(i)?(await this.client.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.client.core.history.delete(r,i.id)):this.onRelayEventUnknownPayload({topic:r,payload:i})}catch(o){this.client.logger.error(o)}})}registerExpirerEvents(){this.client.core.expirer.on(on.expired,async e=>{const{topic:r,id:n}=L1(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,_e("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession(r,!0),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}isValidPairingTopic(e){if(!gr(e,!1)){const{message:r}=_e("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=_e("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(hi(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=_e("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!gr(e,!1)){const{message:r}=_e("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(!this.client.session.keys.includes(e)){const{message:r}=_e("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(hi(this.client.session.get(e).expiry)){await this.deleteSession(e);const{message:r}=_e("EXPIRED",`session topic: ${e}`);throw new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(gr(e,!1)){const{message:r}=_e("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=_e("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!Bb(e)){const{message:r}=_e("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=_e("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(hi(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:r}=_e("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class y7 extends ac{constructor(e,r){super(e,r,c7,ph),this.core=e,this.logger=r}}class b7 extends ac{constructor(e,r){super(e,r,l7,ph),this.core=e,this.logger=r}}class _7 extends ac{constructor(e,r){super(e,r,h7,ph,n=>n.id),this.core=e,this.logger=r}}class vh extends D4{constructor(e){super(e),this.protocol=pg,this.version=gg,this.name=gh.name,this.events=new br.exports.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.name=e?.name||gh.name,this.metadata=e?.metadata||nb();const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||gh.logger}));this.core=e?.core||new a7(e),this.logger=pt.generateChildLogger(r,this.name),this.session=new b7(this.core,this.logger),this.proposal=new y7(this.core,this.logger),this.pendingRequest=new _7(this.core,this.logger),this.engine=new v7(this)}static async init(e){const r=new vh(e);return await r.initialize(),r}get context(){return pt.getLoggerContext(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),this.core.verify.init({verifyUrl:this.metadata.verifyUrl}),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var yh={exports:{}};(function(t,e){var r=typeof self<"u"?self:pr,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(c){var l={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function h(O){return O&&DataView.prototype.isPrototypeOf(O)}if(l.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],v=ArrayBuffer.isView||function(O){return O&&f.indexOf(Object.prototype.toString.call(O))>-1};function x(O){if(typeof O!="string"&&(O=String(O)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(O))throw new TypeError("Invalid character in header field name");return O.toLowerCase()}function _(O){return typeof O!="string"&&(O=String(O)),O}function S(O){var U={next:function(){var ce=O.shift();return{done:ce===void 0,value:ce}}};return l.iterable&&(U[Symbol.iterator]=function(){return U}),U}function P(O){this.map={},O instanceof P?O.forEach(function(U,ce){this.append(ce,U)},this):Array.isArray(O)?O.forEach(function(U){this.append(U[0],U[1])},this):O&&Object.getOwnPropertyNames(O).forEach(function(U){this.append(U,O[U])},this)}P.prototype.append=function(O,U){O=x(O),U=_(U);var ce=this.map[O];this.map[O]=ce?ce+", "+U:U},P.prototype.delete=function(O){delete this.map[x(O)]},P.prototype.get=function(O){return O=x(O),this.has(O)?this.map[O]:null},P.prototype.has=function(O){return this.map.hasOwnProperty(x(O))},P.prototype.set=function(O,U){this.map[x(O)]=_(U)},P.prototype.forEach=function(O,U){for(var ce in this.map)this.map.hasOwnProperty(ce)&&O.call(U,this.map[ce],ce,this)},P.prototype.keys=function(){var O=[];return this.forEach(function(U,ce){O.push(ce)}),S(O)},P.prototype.values=function(){var O=[];return this.forEach(function(U){O.push(U)}),S(O)},P.prototype.entries=function(){var O=[];return this.forEach(function(U,ce){O.push([ce,U])}),S(O)},l.iterable&&(P.prototype[Symbol.iterator]=P.prototype.entries);function j(O){if(O.bodyUsed)return Promise.reject(new TypeError("Already read"));O.bodyUsed=!0}function H(O){return new Promise(function(U,ce){O.onload=function(){U(O.result)},O.onerror=function(){ce(O.error)}})}function Z(O){var U=new FileReader,ce=H(U);return U.readAsArrayBuffer(O),ce}function R(O){var U=new FileReader,ce=H(U);return U.readAsText(O),ce}function L(O){for(var U=new Uint8Array(O),ce=new Array(U.length),le=0;le<U.length;le++)ce[le]=String.fromCharCode(U[le]);return ce.join("")}function $(O){if(O.slice)return O.slice(0);var U=new Uint8Array(O.byteLength);return U.set(new Uint8Array(O)),U.buffer}function T(){return this.bodyUsed=!1,this._initBody=function(O){this._bodyInit=O,O?typeof O=="string"?this._bodyText=O:l.blob&&Blob.prototype.isPrototypeOf(O)?this._bodyBlob=O:l.formData&&FormData.prototype.isPrototypeOf(O)?this._bodyFormData=O:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(O)?this._bodyText=O.toString():l.arrayBuffer&&l.blob&&h(O)?(this._bodyArrayBuffer=$(O.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(O)||v(O))?this._bodyArrayBuffer=$(O):this._bodyText=O=Object.prototype.toString.call(O):this._bodyText="",this.headers.get("content-type")||(typeof O=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):l.searchParams&&URLSearchParams.prototype.isPrototypeOf(O)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var O=j(this);if(O)return O;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?j(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(Z)}),this.text=function(){var O=j(this);if(O)return O;if(this._bodyBlob)return R(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(L(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},l.formData&&(this.formData=function(){return this.text().then(J)}),this.json=function(){return this.text().then(JSON.parse)},this}var I=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function d(O){var U=O.toUpperCase();return I.indexOf(U)>-1?U:O}function E(O,U){U=U||{};var ce=U.body;if(O instanceof E){if(O.bodyUsed)throw new TypeError("Already read");this.url=O.url,this.credentials=O.credentials,U.headers||(this.headers=new P(O.headers)),this.method=O.method,this.mode=O.mode,this.signal=O.signal,!ce&&O._bodyInit!=null&&(ce=O._bodyInit,O.bodyUsed=!0)}else this.url=String(O);if(this.credentials=U.credentials||this.credentials||"same-origin",(U.headers||!this.headers)&&(this.headers=new P(U.headers)),this.method=d(U.method||this.method||"GET"),this.mode=U.mode||this.mode||null,this.signal=U.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&ce)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(ce)}E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function J(O){var U=new FormData;return O.trim().split("&").forEach(function(ce){if(ce){var le=ce.split("="),re=le.shift().replace(/\+/g," "),ne=le.join("=").replace(/\+/g," ");U.append(decodeURIComponent(re),decodeURIComponent(ne))}}),U}function z(O){var U=new P,ce=O.replace(/\r?\n[\t ]+/g," ");return ce.split(/\r?\n/).forEach(function(le){var re=le.split(":"),ne=re.shift().trim();if(ne){var ae=re.join(":").trim();U.append(ne,ae)}}),U}T.call(E.prototype);function ee(O,U){U||(U={}),this.type="default",this.status=U.status===void 0?200:U.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in U?U.statusText:"OK",this.headers=new P(U.headers),this.url=U.url||"",this._initBody(O)}T.call(ee.prototype),ee.prototype.clone=function(){return new ee(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new P(this.headers),url:this.url})},ee.error=function(){var O=new ee(null,{status:0,statusText:""});return O.type="error",O};var de=[301,302,303,307,308];ee.redirect=function(O,U){if(de.indexOf(U)===-1)throw new RangeError("Invalid status code");return new ee(null,{status:U,headers:{location:O}})},c.DOMException=o.DOMException;try{new c.DOMException}catch{c.DOMException=function(U,ce){this.message=U,this.name=ce;var le=Error(U);this.stack=le.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function me(O,U){return new Promise(function(ce,le){var re=new E(O,U);if(re.signal&&re.signal.aborted)return le(new c.DOMException("Aborted","AbortError"));var ne=new XMLHttpRequest;function ae(){ne.abort()}ne.onload=function(){var ie={status:ne.status,statusText:ne.statusText,headers:z(ne.getAllResponseHeaders()||"")};ie.url="responseURL"in ne?ne.responseURL:ie.headers.get("X-Request-URL");var Ae="response"in ne?ne.response:ne.responseText;ce(new ee(Ae,ie))},ne.onerror=function(){le(new TypeError("Network request failed"))},ne.ontimeout=function(){le(new TypeError("Network request failed"))},ne.onabort=function(){le(new c.DOMException("Aborted","AbortError"))},ne.open(re.method,re.url,!0),re.credentials==="include"?ne.withCredentials=!0:re.credentials==="omit"&&(ne.withCredentials=!1),"responseType"in ne&&l.blob&&(ne.responseType="blob"),re.headers.forEach(function(ie,Ae){ne.setRequestHeader(Ae,ie)}),re.signal&&(re.signal.addEventListener("abort",ae),ne.onreadystatechange=function(){ne.readyState===4&&re.signal.removeEventListener("abort",ae)}),ne.send(typeof re._bodyInit>"u"?null:re._bodyInit)})}return me.polyfill=!0,o.fetch||(o.fetch=me,o.Headers=P,o.Request=E,o.Response=ee),c.Headers=P,c.Request=E,c.Response=ee,c.fetch=me,Object.defineProperty(c,"__esModule",{value:!0}),c})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(yh,yh.exports);var _g=bw(yh.exports);const Eg={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},xg=10;class Vi{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new br.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!Ap(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e,r){this.isAvailable||await this.register();try{const n=Mo(e),o=await(await _g(this.url,Object.assign(Object.assign({},Eg),{body:n}))).json();this.onPayload({data:o})}catch(n){this.onError(e.id,n)}}async register(e=this.url){if(!Ap(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",o=>{this.resetMaxListeners(),i(o)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));n()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=Mo({id:1,jsonrpc:"2.0",method:"test",params:[]});await _g(e,Object.assign(Object.assign({},Eg),{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"?Ju(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=ic(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return _p(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>xg&&this.events.setMaxListeners(xg)}}const Cg="error",E7="wss://relay.walletconnect.com",x7="wc",C7="universal_provider",Ig=`${x7}@2:${C7}:`,I7="https://rpc.walletconnect.com/v1",pi={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var qo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},bh={exports:{}};/**
|
|
72
|
+
***************************************************************************** */var eh=function(t,e){return eh=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])},eh(t,e)};function e_(t,e){eh(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var th=function(){return th=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},th.apply(this,arguments)};function t_(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 r_(t,e,r,n){var i=arguments.length,o=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,r,n);else for(var l=t.length-1;l>=0;l--)(c=t[l])&&(o=(i<3?c(o):i>3?c(e,r,o):c(e,r))||o);return i>3&&o&&Object.defineProperty(e,r,o),o}function n_(t,e){return function(r,n){e(r,n,t)}}function i_(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function s_(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function l(v){try{f(n.next(v))}catch(x){c(x)}}function h(v){try{f(n.throw(v))}catch(x){c(x)}}function f(v){v.done?o(v.value):i(v.value).then(l,h)}f((n=n.apply(t,e||[])).next())})}function o_(t,e){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,c;return c={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(c[Symbol.iterator]=function(){return this}),c;function l(f){return function(v){return h([f,v])}}function h(f){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(o=f[0]&2?i.return:f[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,f[1])).done)return o;switch(i=0,o&&(f=[f[0]&2,o.value]),f[0]){case 0:case 1:o=f;break;case 4:return r.label++,{value:f[1],done:!1};case 5:r.label++,i=f[1],f=[0];continue;case 7:f=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(f[0]===6||f[0]===2)){r=0;continue}if(f[0]===3&&(!o||f[1]>o[0]&&f[1]<o[3])){r.label=f[1];break}if(f[0]===6&&r.label<o[1]){r.label=o[1],o=f;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(f);break}o[2]&&r.ops.pop(),r.trys.pop();continue}f=e.call(t,r)}catch(v){f=[6,v],i=0}finally{n=o=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}}function a_(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function c_(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function rh(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 xp(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],c;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(l){c={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(c)throw c.error}}return o}function l_(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(xp(arguments[e]));return t}function u_(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var o=arguments[e],c=0,l=o.length;c<l;c++,i++)n[i]=o[c];return n}function jo(t){return this instanceof jo?(this.v=t,this):new jo(t)}function h_(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,o=[];return i={},c("next"),c("throw"),c("return"),i[Symbol.asyncIterator]=function(){return this},i;function c(_){n[_]&&(i[_]=function(S){return new Promise(function(P,j){o.push([_,S,P,j])>1||l(_,S)})})}function l(_,S){try{h(n[_](S))}catch(P){x(o[0][3],P)}}function h(_){_.value instanceof jo?Promise.resolve(_.value.v).then(f,v):x(o[0][2],_)}function f(_){l("next",_)}function v(_){l("throw",_)}function x(_,S){_(S),o.shift(),o.length&&l(o[0][0],o[0][1])}}function f_(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,o){e[i]=t[i]?function(c){return(r=!r)?{value:jo(t[i](c)),done:i==="return"}:o?o(c):c}:o}}function d_(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 rh=="function"?rh(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(o){r[o]=t[o]&&function(c){return new Promise(function(l,h){c=t[o](c),i(l,h,c.done,c.value)})}}function i(o,c,l,h){Promise.resolve(h).then(function(f){o({value:f,done:l})},c)}}function p_(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function g_(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 m_(t){return t&&t.__esModule?t:{default:t}}function w_(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function v_(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 y_=Object.freeze({__proto__:null,__extends:e_,get __assign(){return th},__rest:t_,__decorate:r_,__param:n_,__metadata:i_,__awaiter:s_,__generator:o_,__createBinding:a_,__exportStar:c_,__values:rh,__read:xp,__spread:l_,__spreadArrays:u_,__await:jo,__asyncGenerator:h_,__asyncDelegator:f_,__asyncValues:d_,__makeTemplateObject:p_,__importStar:g_,__importDefault:m_,__classPrivateFieldGet:w_,__classPrivateFieldSet:v_}),b_=Ui(y_),Wn={},Cp;function __(){if(Cp)return Wn;Cp=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.isBrowserCryptoAvailable=Wn.getSubtleCrypto=Wn.getBrowerCrypto=void 0;function t(){return pr?.crypto||pr?.msCrypto||{}}Wn.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}Wn.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Wn.isBrowserCryptoAvailable=r,Wn}var qn={},Ip;function E_(){if(Ip)return qn;Ip=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.isBrowser=qn.isNode=qn.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}qn.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}qn.isNode=e;function r(){return!t()&&!e()}return qn.isBrowser=r,qn}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=b_;e.__exportStar(__(),t),e.__exportStar(E_(),t)})(Ep);function Sp(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function nh(t=6){return BigInt(Sp(t))}function nc(t,e,r){return{id:r||Sp(),jsonrpc:"2.0",method:t,params:e}}function ih(t,e){return{id:t,jsonrpc:"2.0",result:e}}function ic(t,e,r){return{id:t,jsonrpc:"2.0",error:x_(e,r)}}function x_(t,e){return typeof t>"u"?bp(vp):(typeof t=="string"&&(t=Object.assign(Object.assign({},bp(Qu)),{message:t})),typeof e<"u"&&(t.data=e),X4(t.code)&&(t=Q4(t.code)),t)}class C_{}class I_ extends C_{constructor(){super()}}class S_ extends I_{constructor(e){super()}}const O_="^https?:",A_="^wss?:";function D_(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Op(t,e){const r=D_(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Ap(t){return Op(t,O_)}function Dp(t){return Op(t,A_)}function $_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function $p(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function sh(t){return $p(t)&&"method"in t}function sc(t){return $p(t)&&(Vn(t)||xn(t))}function Vn(t){return"result"in t}function xn(t){return"error"in t}class fi extends S_{constructor(e){super(e),this.events=new br.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(nc(e.method,e.params||[],e.id||nh().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(o){i(o)}this.events.on(`${e.id}`,o=>{xn(o)?i(o.error):n(o.result)});try{await this.connection.send(e,r)}catch(o){i(o)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),sc(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const P_=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),T_=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Pp=t=>t.split("?")[0],Tp=10,N_=P_();class R_{constructor(e){if(this.url=e,this.events=new br.exports.EventEmitter,this.registering=!1,!Dp(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e,r){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Mo(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!Dp(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",o=>{this.resetMaxListeners(),i(o)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=Ep.isReactNative()?void 0:{rejectUnauthorized:!$_(e)},o=new N_(e,[],i);T_()?o.onerror=c=>{const l=c;n(this.emitError(l.error))}:o.on("error",c=>{n(this.emitError(c))}),o.onopen=()=>{this.onOpen(o),r(o)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?Ju(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=ic(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return _p(e,Pp(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Tp&&this.events.setMaxListeners(Tp)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Pp(this.url)}`));return this.events.emit("register_error",r),r}}var oh={exports:{}};(function(t,e){var r=200,n="__lodash_hash_undefined__",i=1,o=2,c=9007199254740991,l="[object Arguments]",h="[object Array]",f="[object AsyncFunction]",v="[object Boolean]",x="[object Date]",_="[object Error]",S="[object Function]",P="[object GeneratorFunction]",j="[object Map]",H="[object Number]",Z="[object Null]",R="[object Object]",L="[object Promise]",$="[object Proxy]",T="[object RegExp]",I="[object Set]",d="[object String]",E="[object Symbol]",J="[object Undefined]",z="[object WeakMap]",ee="[object ArrayBuffer]",de="[object DataView]",me="[object Float32Array]",O="[object Float64Array]",U="[object Int8Array]",ce="[object Int16Array]",le="[object Int32Array]",re="[object Uint8Array]",ne="[object Uint8ClampedArray]",ae="[object Uint16Array]",ie="[object Uint32Array]",Ae=/[\\^$.*+?()[\]{}|]/g,ge=/^\[object .+?Constructor\]$/,Be=/^(?:0|[1-9]\d*)$/,ye={};ye[me]=ye[O]=ye[U]=ye[ce]=ye[le]=ye[re]=ye[ne]=ye[ae]=ye[ie]=!0,ye[l]=ye[h]=ye[ee]=ye[v]=ye[de]=ye[x]=ye[_]=ye[S]=ye[j]=ye[H]=ye[R]=ye[T]=ye[I]=ye[d]=ye[z]=!1;var Me=typeof pr=="object"&&pr&&pr.Object===Object&&pr,X=typeof self=="object"&&self&&self.Object===Object&&self,Y=Me||X||Function("return this")(),W=e&&!e.nodeType&&e,w=W&&!0&&t&&!t.nodeType&&t,F=w&&w.exports===W,we=F&&Me.process,ve=function(){try{return we&&we.binding&&we.binding("util")}catch{}}(),Ue=ve&&ve.isTypedArray;function nt(N,q){for(var fe=-1,Ce=N==null?0:N.length,It=0,Xe=[];++fe<Ce;){var Tt=N[fe];q(Tt,fe,N)&&(Xe[It++]=Tt)}return Xe}function at(N,q){for(var fe=-1,Ce=q.length,It=N.length;++fe<Ce;)N[It+fe]=q[fe];return N}function Ge(N,q){for(var fe=-1,Ce=N==null?0:N.length;++fe<Ce;)if(q(N[fe],fe,N))return!0;return!1}function Dt(N,q){for(var fe=-1,Ce=Array(N);++fe<N;)Ce[fe]=q(fe);return Ce}function $t(N){return function(q){return N(q)}}function Je(N,q){return N.has(q)}function He(N,q){return N?.[q]}function ke(N){var q=-1,fe=Array(N.size);return N.forEach(function(Ce,It){fe[++q]=[It,Ce]}),fe}function Ke(N,q){return function(fe){return N(q(fe))}}function rt(N){var q=-1,fe=Array(N.size);return N.forEach(function(Ce){fe[++q]=Ce}),fe}var je=Array.prototype,Ze=Function.prototype,b=Object.prototype,p=Y["__core-js_shared__"],m=Ze.toString,D=b.hasOwnProperty,B=function(){var N=/[^.]+$/.exec(p&&p.keys&&p.keys.IE_PROTO||"");return N?"Symbol(src)_1."+N:""}(),K=b.toString,Q=RegExp("^"+m.call(D).replace(Ae,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ee=F?Y.Buffer:void 0,Ne=Y.Symbol,st=Y.Uint8Array,ht=b.propertyIsEnumerable,lt=je.splice,Ur=Ne?Ne.toStringTag:void 0,Jn=Object.getOwnPropertySymbols,Si=Ee?Ee.isBuffer:void 0,cs=Ke(Object.keys,Object),zt=Qr(Y,"DataView"),Lt=Qr(Y,"Map"),Wt=Qr(Y,"Promise"),qt=Qr(Y,"Set"),Ft=Qr(Y,"WeakMap"),Mt=Qr(Object,"create"),ir=Qn(zt),sr=Qn(Lt),Vt=Qn(Wt),or=Qn(qt),Kt=Qn(Ft),Xt=Ne?Ne.prototype:void 0,Gt=Xt?Xt.valueOf:void 0;function Pt(N){var q=-1,fe=N==null?0:N.length;for(this.clear();++q<fe;){var Ce=N[q];this.set(Ce[0],Ce[1])}}function ar(){this.__data__=Mt?Mt(null):{},this.size=0}function cr(N){var q=this.has(N)&&delete this.__data__[N];return this.size-=q?1:0,q}function Hf(N){var q=this.__data__;if(Mt){var fe=q[N];return fe===n?void 0:fe}return D.call(q,N)?q[N]:void 0}function zf(N){var q=this.__data__;return Mt?q[N]!==void 0:D.call(q,N)}function Wf(N,q){var fe=this.__data__;return this.size+=this.has(N)?0:1,fe[N]=Mt&&q===void 0?n:q,this}Pt.prototype.clear=ar,Pt.prototype.delete=cr,Pt.prototype.get=Hf,Pt.prototype.has=zf,Pt.prototype.set=Wf;function fn(N){var q=-1,fe=N==null?0:N.length;for(this.clear();++q<fe;){var Ce=N[q];this.set(Ce[0],Ce[1])}}function qf(){this.__data__=[],this.size=0}function Vf(N){var q=this.__data__,fe=ls(q,N);if(fe<0)return!1;var Ce=q.length-1;return fe==Ce?q.pop():lt.call(q,fe,1),--this.size,!0}function Kf(N){var q=this.__data__,fe=ls(q,N);return fe<0?void 0:q[fe][1]}function Gf(N){return ls(this.__data__,N)>-1}function Zf(N,q){var fe=this.__data__,Ce=ls(fe,N);return Ce<0?(++this.size,fe.push([N,q])):fe[Ce][1]=q,this}fn.prototype.clear=qf,fn.prototype.delete=Vf,fn.prototype.get=Kf,fn.prototype.has=Gf,fn.prototype.set=Zf;function Xn(N){var q=-1,fe=N==null?0:N.length;for(this.clear();++q<fe;){var Ce=N[q];this.set(Ce[0],Ce[1])}}function Qs(){this.size=0,this.__data__={hash:new Pt,map:new(Lt||fn),string:new Pt}}function Yf(N){var q=Oi(this,N).delete(N);return this.size-=q?1:0,q}function eo(N){return Oi(this,N).get(N)}function Jf(N){return Oi(this,N).has(N)}function Xf(N,q){var fe=Oi(this,N),Ce=fe.size;return fe.set(N,q),this.size+=fe.size==Ce?0:1,this}Xn.prototype.clear=Qs,Xn.prototype.delete=Yf,Xn.prototype.get=eo,Xn.prototype.has=Jf,Xn.prototype.set=Xf;function to(N){var q=-1,fe=N==null?0:N.length;for(this.__data__=new Xn;++q<fe;)this.add(N[q])}function Xc(N){return this.__data__.set(N,n),this}function Qc(N){return this.__data__.has(N)}to.prototype.add=to.prototype.push=Xc,to.prototype.has=Qc;function Cn(N){var q=this.__data__=new fn(N);this.size=q.size}function Qf(){this.__data__=new fn,this.size=0}function e0(N){var q=this.__data__,fe=q.delete(N);return this.size=q.size,fe}function t0(N){return this.__data__.get(N)}function r0(N){return this.__data__.has(N)}function el(N,q){var fe=this.__data__;if(fe instanceof fn){var Ce=fe.__data__;if(!Lt||Ce.length<r-1)return Ce.push([N,q]),this.size=++fe.size,this;fe=this.__data__=new Xn(Ce)}return fe.set(N,q),this.size=fe.size,this}Cn.prototype.clear=Qf,Cn.prototype.delete=e0,Cn.prototype.get=t0,Cn.prototype.has=r0,Cn.prototype.set=el;function tl(N,q){var fe=io(N),Ce=!fe&&dl(N),It=!fe&&!Ce&&ba(N),Xe=!fe&&!Ce&&!It&&ml(N),Tt=fe||Ce||It||Xe,lr=Tt?Dt(N.length,String):[],mt=lr.length;for(var St in N)(q||D.call(N,St))&&!(Tt&&(St=="length"||It&&(St=="offset"||St=="parent")||Xe&&(St=="buffer"||St=="byteLength"||St=="byteOffset")||cl(St,mt)))&&lr.push(St);return lr}function ls(N,q){for(var fe=N.length;fe--;)if(fl(N[fe][0],q))return fe;return-1}function va(N,q,fe){var Ce=q(N);return io(N)?Ce:at(Ce,fe(N))}function us(N){return N==null?N===void 0?J:Z:Ur&&Ur in Object(N)?ol(N):s0(N)}function ya(N){return fs(N)&&us(N)==l}function hs(N,q,fe,Ce,It){return N===q?!0:N==null||q==null||!fs(N)&&!fs(q)?N!==N&&q!==q:rl(N,q,fe,Ce,hs,It)}function rl(N,q,fe,Ce,It,Xe){var Tt=io(N),lr=io(q),mt=Tt?h:Fn(N),St=lr?h:Fn(q);mt=mt==l?R:mt,St=St==l?R:St;var Qt=mt==R,qr=St==R,ur=mt==St;if(ur&&ba(N)){if(!ba(q))return!1;Tt=!0,Qt=!1}if(ur&&!Qt)return Xe||(Xe=new Cn),Tt||ml(N)?ro(N,q,fe,Ce,It,Xe):i0(N,q,mt,fe,Ce,It,Xe);if(!(fe&i)){var Nt=Qt&&D.call(N,"__wrapped__"),jr=qr&&D.call(q,"__wrapped__");if(Nt||jr){var In=Nt?N.value():N,dn=jr?q.value():q;return Xe||(Xe=new Cn),It(In,dn,fe,Ce,Xe)}}return ur?(Xe||(Xe=new Cn),sl(N,q,fe,Ce,It,Xe)):!1}function n0(N){if(!gl(N)||ul(N))return!1;var q=so(N)?Q:ge;return q.test(Qn(N))}function nl(N){return fs(N)&&pl(N.length)&&!!ye[us(N)]}function il(N){if(!hl(N))return cs(N);var q=[];for(var fe in Object(N))D.call(N,fe)&&fe!="constructor"&&q.push(fe);return q}function ro(N,q,fe,Ce,It,Xe){var Tt=fe&i,lr=N.length,mt=q.length;if(lr!=mt&&!(Tt&&mt>lr))return!1;var St=Xe.get(N);if(St&&Xe.get(q))return St==q;var Qt=-1,qr=!0,ur=fe&o?new to:void 0;for(Xe.set(N,q),Xe.set(q,N);++Qt<lr;){var Nt=N[Qt],jr=q[Qt];if(Ce)var In=Tt?Ce(jr,Nt,Qt,q,N,Xe):Ce(Nt,jr,Qt,N,q,Xe);if(In!==void 0){if(In)continue;qr=!1;break}if(ur){if(!Ge(q,function(dn,Bn){if(!Je(ur,Bn)&&(Nt===dn||It(Nt,dn,fe,Ce,Xe)))return ur.push(Bn)})){qr=!1;break}}else if(!(Nt===jr||It(Nt,jr,fe,Ce,Xe))){qr=!1;break}}return Xe.delete(N),Xe.delete(q),qr}function i0(N,q,fe,Ce,It,Xe,Tt){switch(fe){case de:if(N.byteLength!=q.byteLength||N.byteOffset!=q.byteOffset)return!1;N=N.buffer,q=q.buffer;case ee:return!(N.byteLength!=q.byteLength||!Xe(new st(N),new st(q)));case v:case x:case H:return fl(+N,+q);case _:return N.name==q.name&&N.message==q.message;case T:case d:return N==q+"";case j:var lr=ke;case I:var mt=Ce&i;if(lr||(lr=rt),N.size!=q.size&&!mt)return!1;var St=Tt.get(N);if(St)return St==q;Ce|=o,Tt.set(N,q);var Qt=ro(lr(N),lr(q),Ce,It,Xe,Tt);return Tt.delete(N),Qt;case E:if(Gt)return Gt.call(N)==Gt.call(q)}return!1}function sl(N,q,fe,Ce,It,Xe){var Tt=fe&i,lr=no(N),mt=lr.length,St=no(q),Qt=St.length;if(mt!=Qt&&!Tt)return!1;for(var qr=mt;qr--;){var ur=lr[qr];if(!(Tt?ur in q:D.call(q,ur)))return!1}var Nt=Xe.get(N);if(Nt&&Xe.get(q))return Nt==q;var jr=!0;Xe.set(N,q),Xe.set(q,N);for(var In=Tt;++qr<mt;){ur=lr[qr];var dn=N[ur],Bn=q[ur];if(Ce)var _a=Tt?Ce(Bn,dn,ur,q,N,Xe):Ce(dn,Bn,ur,N,q,Xe);if(!(_a===void 0?dn===Bn||It(dn,Bn,fe,Ce,Xe):_a)){jr=!1;break}In||(In=ur=="constructor")}if(jr&&!In){var ds=N.constructor,vr=q.constructor;ds!=vr&&"constructor"in N&&"constructor"in q&&!(typeof ds=="function"&&ds instanceof ds&&typeof vr=="function"&&vr instanceof vr)&&(jr=!1)}return Xe.delete(N),Xe.delete(q),jr}function no(N){return va(N,c0,al)}function Oi(N,q){var fe=N.__data__;return ll(q)?fe[typeof q=="string"?"string":"hash"]:fe.map}function Qr(N,q){var fe=He(N,q);return n0(fe)?fe:void 0}function ol(N){var q=D.call(N,Ur),fe=N[Ur];try{N[Ur]=void 0;var Ce=!0}catch{}var It=K.call(N);return Ce&&(q?N[Ur]=fe:delete N[Ur]),It}var al=Jn?function(N){return N==null?[]:(N=Object(N),nt(Jn(N),function(q){return ht.call(N,q)}))}:Ct,Fn=us;(zt&&Fn(new zt(new ArrayBuffer(1)))!=de||Lt&&Fn(new Lt)!=j||Wt&&Fn(Wt.resolve())!=L||qt&&Fn(new qt)!=I||Ft&&Fn(new Ft)!=z)&&(Fn=function(N){var q=us(N),fe=q==R?N.constructor:void 0,Ce=fe?Qn(fe):"";if(Ce)switch(Ce){case ir:return de;case sr:return j;case Vt:return L;case or:return I;case Kt:return z}return q});function cl(N,q){return q=q??c,!!q&&(typeof N=="number"||Be.test(N))&&N>-1&&N%1==0&&N<q}function ll(N){var q=typeof N;return q=="string"||q=="number"||q=="symbol"||q=="boolean"?N!=="__proto__":N===null}function ul(N){return!!B&&B in N}function hl(N){var q=N&&N.constructor,fe=typeof q=="function"&&q.prototype||b;return N===fe}function s0(N){return K.call(N)}function Qn(N){if(N!=null){try{return m.call(N)}catch{}try{return N+""}catch{}}return""}function fl(N,q){return N===q||N!==N&&q!==q}var dl=ya(function(){return arguments}())?ya:function(N){return fs(N)&&D.call(N,"callee")&&!ht.call(N,"callee")},io=Array.isArray;function o0(N){return N!=null&&pl(N.length)&&!so(N)}var ba=Si||xt;function a0(N,q){return hs(N,q)}function so(N){if(!gl(N))return!1;var q=us(N);return q==S||q==P||q==f||q==$}function pl(N){return typeof N=="number"&&N>-1&&N%1==0&&N<=c}function gl(N){var q=typeof N;return N!=null&&(q=="object"||q=="function")}function fs(N){return N!=null&&typeof N=="object"}var ml=Ue?$t(Ue):nl;function c0(N){return o0(N)?tl(N):il(N)}function Ct(){return[]}function xt(){return!1}t.exports=a0})(oh,oh.exports);var L_=oh.exports,M_=Object.defineProperty,Np=Object.getOwnPropertySymbols,U_=Object.prototype.hasOwnProperty,j_=Object.prototype.propertyIsEnumerable,Rp=(t,e,r)=>e in t?M_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nr=(t,e)=>{for(var r in e||(e={}))U_.call(e,r)&&Rp(t,r,e[r]);if(Np)for(var r of Np(e))j_.call(e,r)&&Rp(t,r,e[r]);return t};function F_(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),c=o.charCodeAt(0);if(r[c]!==255)throw new TypeError(o+" is ambiguous");r[c]=i}var l=t.length,h=t.charAt(0),f=Math.log(l)/Math.log(256),v=Math.log(256)/Math.log(l);function x(P){if(P instanceof Uint8Array||(ArrayBuffer.isView(P)?P=new Uint8Array(P.buffer,P.byteOffset,P.byteLength):Array.isArray(P)&&(P=Uint8Array.from(P))),!(P instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(P.length===0)return"";for(var j=0,H=0,Z=0,R=P.length;Z!==R&&P[Z]===0;)Z++,j++;for(var L=(R-Z)*v+1>>>0,$=new Uint8Array(L);Z!==R;){for(var T=P[Z],I=0,d=L-1;(T!==0||I<H)&&d!==-1;d--,I++)T+=256*$[d]>>>0,$[d]=T%l>>>0,T=T/l>>>0;if(T!==0)throw new Error("Non-zero carry");H=I,Z++}for(var E=L-H;E!==L&&$[E]===0;)E++;for(var J=h.repeat(j);E<L;++E)J+=t.charAt($[E]);return J}function _(P){if(typeof P!="string")throw new TypeError("Expected String");if(P.length===0)return new Uint8Array;var j=0;if(P[j]!==" "){for(var H=0,Z=0;P[j]===h;)H++,j++;for(var R=(P.length-j)*f+1>>>0,L=new Uint8Array(R);P[j];){var $=r[P.charCodeAt(j)];if($===255)return;for(var T=0,I=R-1;($!==0||T<Z)&&I!==-1;I--,T++)$+=l*L[I]>>>0,L[I]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");Z=T,j++}if(P[j]!==" "){for(var d=R-Z;d!==R&&L[d]===0;)d++;for(var E=new Uint8Array(H+(R-d)),J=H;d!==R;)E[J++]=L[d++];return E}}}function S(P){var j=_(P);if(j)return j;throw new Error(`Non-${e} character`)}return{encode:x,decodeUnsafe:_,decode:S}}var B_=F_,k_=B_;const Lp=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")},H_=t=>new TextEncoder().encode(t),z_=t=>new TextDecoder().decode(t);class W_{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 q_{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 Mp(this,e)}}class V_{constructor(e){this.decoders=e}or(e){return Mp(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 Mp=(t,e)=>new V_(Nr(Nr({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class K_{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new W_(e,r,n),this.decoder=new q_(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const oc=({name:t,prefix:e,encode:r,decode:n})=>new K_(t,e,r,n),Fo=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=k_(r,e);return oc({prefix:t,name:e,encode:n,decode:o=>Lp(i(o))})},G_=(t,e,r,n)=>{const i={};for(let v=0;v<e.length;++v)i[e[v]]=v;let o=t.length;for(;t[o-1]==="=";)--o;const c=new Uint8Array(o*r/8|0);let l=0,h=0,f=0;for(let v=0;v<o;++v){const x=i[t[v]];if(x===void 0)throw new SyntaxError(`Non-${n} character`);h=h<<r|x,l+=r,l>=8&&(l-=8,c[f++]=255&h>>l)}if(l>=r||255&h<<8-l)throw new SyntaxError("Unexpected end of data");return c},Z_=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let o="",c=0,l=0;for(let h=0;h<t.length;++h)for(l=l<<8|t[h],c+=8;c>r;)c-=r,o+=e[i&l>>c];if(c&&(o+=e[i&l<<r-c]),n)for(;o.length*r&7;)o+="=";return o},Er=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>oc({prefix:e,name:t,encode(i){return Z_(i,n,r)},decode(i){return G_(i,n,r,t)}}),Y_=oc({prefix:"\0",name:"identity",encode:t=>z_(t),decode:t=>H_(t)});var J_=Object.freeze({__proto__:null,identity:Y_});const X_=Er({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Q_=Object.freeze({__proto__:null,base2:X_});const e8=Er({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var t8=Object.freeze({__proto__:null,base8:e8});const r8=Fo({prefix:"9",name:"base10",alphabet:"0123456789"});var n8=Object.freeze({__proto__:null,base10:r8});const i8=Er({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),s8=Er({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var o8=Object.freeze({__proto__:null,base16:i8,base16upper:s8});const a8=Er({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),c8=Er({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),l8=Er({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),u8=Er({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),h8=Er({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),f8=Er({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),d8=Er({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),p8=Er({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),g8=Er({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var m8=Object.freeze({__proto__:null,base32:a8,base32upper:c8,base32pad:l8,base32padupper:u8,base32hex:h8,base32hexupper:f8,base32hexpad:d8,base32hexpadupper:p8,base32z:g8});const w8=Fo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),v8=Fo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var y8=Object.freeze({__proto__:null,base36:w8,base36upper:v8});const b8=Fo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),_8=Fo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var E8=Object.freeze({__proto__:null,base58btc:b8,base58flickr:_8});const x8=Er({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),C8=Er({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),I8=Er({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),S8=Er({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var O8=Object.freeze({__proto__:null,base64:x8,base64pad:C8,base64url:I8,base64urlpad:S8});const Up=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}"),A8=Up.reduce((t,e,r)=>(t[r]=e,t),[]),D8=Up.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function $8(t){return t.reduce((e,r)=>(e+=A8[r],e),"")}function P8(t){const e=[];for(const r of t){const n=D8[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const T8=oc({prefix:"\u{1F680}",name:"base256emoji",encode:$8,decode:P8});var N8=Object.freeze({__proto__:null,base256emoji:T8}),R8=Fp,jp=128,L8=127,M8=~L8,U8=Math.pow(2,31);function Fp(t,e,r){e=e||[],r=r||0;for(var n=r;t>=U8;)e[r++]=t&255|jp,t/=128;for(;t&M8;)e[r++]=t&255|jp,t>>>=7;return e[r]=t|0,Fp.bytes=r-n+1,e}var j8=ah,F8=128,Bp=127;function ah(t,n){var r=0,n=n||0,i=0,o=n,c,l=t.length;do{if(o>=l)throw ah.bytes=0,new RangeError("Could not decode varint");c=t[o++],r+=i<28?(c&Bp)<<i:(c&Bp)*Math.pow(2,i),i+=7}while(c>=F8);return ah.bytes=o-n,r}var B8=Math.pow(2,7),k8=Math.pow(2,14),H8=Math.pow(2,21),z8=Math.pow(2,28),W8=Math.pow(2,35),q8=Math.pow(2,42),V8=Math.pow(2,49),K8=Math.pow(2,56),G8=Math.pow(2,63),Z8=function(t){return t<B8?1:t<k8?2:t<H8?3:t<z8?4:t<W8?5:t<q8?6:t<V8?7:t<K8?8:t<G8?9:10},Y8={encode:R8,decode:j8,encodingLength:Z8},kp=Y8;const Hp=(t,e,r=0)=>(kp.encode(t,e,r),e),zp=t=>kp.encodingLength(t),ch=(t,e)=>{const r=e.byteLength,n=zp(t),i=n+zp(r),o=new Uint8Array(i+r);return Hp(t,o,0),Hp(r,o,n),o.set(e,i),new J8(t,r,e,o)};class J8{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Wp=({name:t,code:e,encode:r})=>new X8(t,e,r);class X8{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?ch(this.code,r):r.then(n=>ch(this.code,n))}else throw Error("Unknown type, must be binary type")}}const qp=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Q8=Wp({name:"sha2-256",code:18,encode:qp("SHA-256")}),eE=Wp({name:"sha2-512",code:19,encode:qp("SHA-512")});var tE=Object.freeze({__proto__:null,sha256:Q8,sha512:eE});const Vp=0,rE="identity",Kp=Lp;var nE=Object.freeze({__proto__:null,identity:{code:Vp,name:rE,encode:Kp,digest:t=>ch(Vp,Kp(t))}});new TextEncoder,new TextDecoder;const Gp=Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr(Nr({},J_),Q_),t8),n8),o8),m8),y8),E8),O8),N8);Nr(Nr({},tE),nE);function Zp(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function iE(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Zp(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Yp(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Jp=Yp("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),lh=Yp("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=iE(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),sE=Nr({utf8:Jp,"utf-8":Jp,hex:Gp.base16,latin1:lh,ascii:lh,binary:lh},Gp);function oE(t,e="utf8"){const r=sE[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Zp(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}const Xp="wc",aE=2,uh="core",di=`${Xp}@2:${uh}:`,cE={name:uh,logger:"error"},lE={database:":memory:"},uE="crypto",Qp="client_ed25519_seed",hE=De.ONE_DAY,fE="keychain",dE="0.3",pE="messages",gE="0.3",mE=De.SIX_HOURS,wE="publisher",eg="irn",vE="error",tg="wss://relay.walletconnect.com",rg="wss://relay.walletconnect.org",yE="relayer",kt={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},bE="_subscription",Bo={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},_E=De.ONE_SECOND/2,EE="2.9.2",xE=1e4,CE="0.3",IE="WALLETCONNECT_CLIENT_ID",Tn={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},SE="subscription",OE="0.3",AE=De.FIVE_SECONDS*1e3,DE="pairing",$E="0.3",ko={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}}},Nn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},PE="history",TE="0.3",NE="expirer",on={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},RE="0.3",hh="verify-api",ng="https://verify.walletconnect.com";class LE{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=fE,this.version=dE,this.initialized=!1,this.storagePrefix=di,this.init=async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()},this.get=n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:o}=_e("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(o)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=pt.generateChildLogger(r,this.name)}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,T1(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?N1(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class ME{constructor(e,r,n){this.core=e,this.logger=r,this.name=uE,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();const i=await this.getClientSeed(),o=wp(i);return mp(o.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const i=z5();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const o=await this.getClientSeed(),c=wp(o),l=Du();return await V4(l,i,hE,c)},this.generateSharedKey=(i,o,c)=>{this.isInitialized();const l=this.getPrivateKey(i),h=W5(l,o);return this.setSymKey(h,c)},this.setSymKey=async(i,o)=>{this.isInitialized();const c=o||q5(i);return await this.keychain.set(c,i),c},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,o,c)=>{this.isInitialized();const l=S1(c),h=Mo(o);if(O1(l)){const _=l.senderPublicKey,S=l.receiverPublicKey;i=await this.generateSharedKey(_,S)}const f=this.getSymKey(i),{type:v,senderPublicKey:x}=l;return K5({type:v,symKey:f,message:h,senderPublicKey:x})},this.decode=async(i,o,c)=>{this.isInitialized();const l=Y5(o,c);if(O1(l)){const h=l.receiverPublicKey,f=l.senderPublicKey;i=await this.generateSharedKey(h,f)}try{const h=this.getSymKey(i),f=G5({symKey:h,encoded:o});return Ju(f)}catch(h){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(h)}},this.getPayloadType=i=>{const o=Ga(i);return So(o.type)},this.getPayloadSenderPublicKey=i=>{const o=Ga(i);return o.senderPublicKey?Dr(o.senderPublicKey,$r):void 0},this.core=e,this.logger=pt.generateChildLogger(r,this.name),this.keychain=n||new LE(this.core,this.logger)}get context(){return pt.getLoggerContext(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Qp)}catch{e=Du(),await this.keychain.set(Qp,e)}return oE(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class UE extends E4{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=pE,this.version=gE,this.initialized=!1,this.storagePrefix=di,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,i)=>{this.isInitialized();const o=Ss(i);let c=this.messages.get(n);return typeof c>"u"&&(c={}),typeof c[o]<"u"||(c[o]=i,this.messages.set(n,c),await this.persist()),o},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();const o=this.get(n),c=Ss(i);return typeof o[c]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=pt.generateChildLogger(e,this.name),this.core=r}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,T1(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?N1(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class jE extends x4{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new br.exports.EventEmitter,this.name=wE,this.queue=new Map,this.publishTimeout=De.toMiliseconds(De.TEN_SECONDS),this.queueTimeout=De.toMiliseconds(De.FIVE_SECONDS),this.needsTransportRestart=!1,this.publish=async(n,i,o)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:o}});try{const c=o?.ttl||mE,l=Ru(o),h=o?.prompt||!1,f=o?.tag||0,v=o?.id||nh().toString(),x={topic:n,message:i,opts:{ttl:c,relay:l,prompt:h,tag:f,id:v}},_=setTimeout(()=>this.queue.set(v,x),this.queueTimeout);try{await await Za(this.rpcPublish(n,i,c,l,h,f,v),this.publishTimeout),clearTimeout(_),this.relayer.events.emit(kt.publish,x)}catch{this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0;return}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:o}})}catch(c){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(c),c}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.relayer=e,this.logger=pt.generateChildLogger(r,this.name),this.registerEventListeners()}get context(){return pt.getLoggerContext(this.logger)}rpcPublish(e,r,n,i,o,c,l){var h,f,v,x;const _={method:Ya(i.protocol).publish,params:{topic:e,message:r,ttl:n,prompt:o,tag:c},id:l};return Pr((h=_.params)==null?void 0:h.prompt)&&((f=_.params)==null||delete f.prompt),Pr((v=_.params)==null?void 0:v.tag)&&((x=_.params)==null||delete x.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:_}),this.relayer.request(_)}onPublish(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:r,message:n,opts:i}=e;await this.publish(r,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(Ps.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(kt.connection_stalled);return}this.checkQueue()}),this.relayer.on(kt.message_ack,e=>{this.onPublish(e.id.toString())})}}class FE{constructor(){this.map=new Map,this.set=(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(o=>o!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var BE=Object.defineProperty,kE=Object.defineProperties,HE=Object.getOwnPropertyDescriptors,ig=Object.getOwnPropertySymbols,zE=Object.prototype.hasOwnProperty,WE=Object.prototype.propertyIsEnumerable,sg=(t,e,r)=>e in t?BE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ho=(t,e)=>{for(var r in e||(e={}))zE.call(e,r)&&sg(t,r,e[r]);if(ig)for(var r of ig(e))WE.call(e,r)&&sg(t,r,e[r]);return t},fh=(t,e)=>kE(t,HE(e));class qE extends S4{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new FE,this.events=new br.exports.EventEmitter,this.name=SE,this.version=OE,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=di,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restart(),this.registerEventListeners(),this.onEnable(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const o=Ru(i),c={topic:n,relay:o};this.pending.set(n,c);const l=await this.rpcSubscribe(n,o);return this.onSubscribe(l,c),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}}),l}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}},this.unsubscribe=async(n,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)},this.isSubscribed=async n=>this.topics.includes(n)?!0:await new Promise((i,o)=>{const c=new De.Watch;c.start(this.pendingSubscriptionWatchLabel);const l=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(l),c.stop(this.pendingSubscriptionWatchLabel),i(!0)),c.elapsed(this.pendingSubscriptionWatchLabel)>=AE&&(clearInterval(l),c.stop(this.pendingSubscriptionWatchLabel),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=pt.generateChildLogger(r,this.name),this.clientId=""}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=Ru(n);await this.rpcUnsubscribe(e,r,i);const o=Yt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,o),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r){const n={method:Ya(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await Za(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(kt.connection_stalled)}return Ss(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Ya(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 Za(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(kt.connection_stalled)}}rpcUnsubscribe(e,r,n){const i={method:Ya(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,fh(Ho({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Ho({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r))}addSubscription(e,r){this.subscriptions.set(e,Ho({},r)),this.topicMap.set(r.topic,e),this.events.emit(Tn.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(Tn.deleted,fh(Ho({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Tn.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<e;r++){const n=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}}this.events.emit(Tn.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;const r=await this.rpcBatchSubscribe(e);Pn(r)&&this.onBatchSubscribe(r.map((n,i)=>fh(Ho({},e[i]),{id:n})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(Ps.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(kt.connect,async()=>{await this.onConnect()}),this.relayer.on(kt.disconnect,()=>{this.onDisconnect()}),this.events.on(Tn.created,async e=>{const r=Tn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(Tn.deleted,async e=>{const r=Tn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}}var VE=Object.defineProperty,og=Object.getOwnPropertySymbols,KE=Object.prototype.hasOwnProperty,GE=Object.prototype.propertyIsEnumerable,ag=(t,e,r)=>e in t?VE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ZE=(t,e)=>{for(var r in e||(e={}))KE.call(e,r)&&ag(t,r,e[r]);if(og)for(var r of og(e))GE.call(e,r)&&ag(t,r,e[r]);return t};class YE extends C4{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new br.exports.EventEmitter,this.name=yE,this.transportExplicitlyClosed=!1,this.initialized=!1,this.reconnecting=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],this.request=async r=>{this.logger.debug("Publishing Request Payload");try{return await this.toEstablishConnection(),await this.provider.request(r)}catch(n){throw this.logger.debug("Failed to Publish Request"),this.logger.error(n),n}},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?pt.generateChildLogger(e.logger,this.name):pt.pino(pt.getDefaultLoggerOptions({level:e.logger||vE})),this.messages=new UE(this.logger,e.core),this.subscriber=new qE(this,this.logger),this.publisher=new jE(this,this.logger),this.relayUrl=e?.relayUrl||tg,this.projectId=e.projectId,this.provider={}}async init(){this.logger.trace("Initialized"),await this.createProvider(),await Promise.all([this.messages.init(),this.subscriber.init()]);try{await this.transportOpen()}catch{this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${rg}...`),await this.restartTransport(rg)}this.registerEventListeners(),this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},xE)}get context(){return pt.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now()})}async subscribe(e,r){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"";return i||(await Promise.all([new Promise(o=>{this.subscriber.once(Tn.created,c=>{c.topic===e&&o()})}),new Promise(async o=>{i=await this.subscriber.subscribe(e,r),o()})]),i)}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportClose(){this.transportExplicitlyClosed=!0,this.connected&&(await this.provider.disconnect(),this.events.emit(kt.transport_closed))}async transportOpen(e){if(this.transportExplicitlyClosed=!1,!this.reconnecting){this.relayUrl=e||this.relayUrl,this.reconnecting=!0;try{await Promise.all([new Promise(r=>{this.initialized||r(),this.subscriber.once(Tn.resubscribed,()=>{r()})}),await Promise.race([new Promise(async(r,n)=>{await Za(this.provider.connect(),1e4,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(i=>n(i)).then(()=>r()).finally(()=>this.removeListener(kt.transport_closed,this.rejectTransportOpen))}),new Promise(r=>this.once(kt.transport_closed,this.rejectTransportOpen))])])}catch(r){this.logger.error(r);const n=r;if(!this.isConnectionStalled(n.message))throw r;this.events.emit(kt.transport_closed)}finally{this.reconnecting=!1}}}async restartTransport(e){this.transportExplicitlyClosed||this.reconnecting||(this.relayUrl=e||this.relayUrl,this.connected&&await Promise.all([new Promise(r=>{this.provider.once(Bo.disconnect,()=>{r()})}),this.transportClose()]),await this.createProvider(),await this.transportOpen())}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}rejectTransportOpen(){throw new Error("Attempt to connect to relay via `transportOpen` has stalled. Retrying...")}async createProvider(){const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new fi(new R_(ab({sdkVersion:EE,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:r,message:n}=e;await this.messages.set(r,n)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;const i=this.messages.has(r,n);return i&&this.logger.debug(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),sh(e)){if(!e.method.endsWith(bE))return;const r=e.params,{topic:n,message:i,publishedAt:o}=r.data,c={topic:n,message:i,publishedAt:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(ZE({type:"event",event:r.id},c)),this.events.emit(r.id,c),await this.acknowledgePayload(e),await this.onMessageEvent(c)}else sc(e)&&this.events.emit(kt.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(kt.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=ih(e.id,!0);await this.provider.connection.send(r)}registerProviderListeners(){this.provider.on(Bo.payload,e=>this.onProviderPayload(e)),this.provider.on(Bo.connect,()=>{this.events.emit(kt.connect)}),this.provider.on(Bo.disconnect,()=>{this.onProviderDisconnect()}),this.provider.on(Bo.error,e=>{this.logger.error(e),this.events.emit(kt.error,e)})}registerEventListeners(){this.events.on(kt.connection_stalled,async()=>{await this.restartTransport()})}onProviderDisconnect(){this.events.emit(kt.disconnect),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||setTimeout(async()=>{await this.restartTransport()},De.toMiliseconds(_E))}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(!this.connected){if(this.connecting)return await new Promise(e=>{const r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)});await this.restartTransport()}}}var JE=Object.defineProperty,cg=Object.getOwnPropertySymbols,XE=Object.prototype.hasOwnProperty,QE=Object.prototype.propertyIsEnumerable,lg=(t,e,r)=>e in t?JE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ug=(t,e)=>{for(var r in e||(e={}))XE.call(e,r)&&lg(t,r,e[r]);if(cg)for(var r of cg(e))QE.call(e,r)&&lg(t,r,e[r]);return t};class ac extends I4{constructor(e,r,n,i=di,o=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,this.map=new Map,this.version=CE,this.cached=[],this.initialized=!1,this.storagePrefix=di,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(c=>{this.getKey&&c!==null&&!Pr(c)?this.map.set(this.getKey(c),c):$b(c)?this.map.set(c.id,c):Pb(c)&&this.map.set(c.topic,c)}),this.cached=[],this.initialized=!0)},this.set=async(c,l)=>{this.isInitialized(),this.map.has(c)?await this.update(c,l):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:c,value:l}),this.map.set(c,l),await this.persist())},this.get=c=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:c}),this.getData(c)),this.getAll=c=>(this.isInitialized(),c?this.values.filter(l=>Object.keys(c).every(h=>L_(l[h],c[h]))):this.values),this.update=async(c,l)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:c,update:l});const h=ug(ug({},this.getData(c)),l);this.map.set(c,h),await this.persist()},this.delete=async(c,l)=>{this.isInitialized(),this.map.has(c)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:c,reason:l}),this.map.delete(c),await this.persist())},this.logger=pt.generateChildLogger(r,this.name),this.storagePrefix=i,this.getKey=o}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){const{message:n}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class e7{constructor(e,r){this.core=e,this.logger=r,this.name=DE,this.version=$E,this.events=new br.exports,this.initialized=!1,this.storagePrefix=di,this.ignoredPayloadTypes=[ki],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=Du(),i=await this.core.crypto.setSymKey(n),o=En(De.FIVE_MINUTES),c={protocol:eg},l={topic:i,expiry:o,relay:c,active:!1},h=bb({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:n,relay:c});return await this.pairings.set(i,l),await this.core.relayer.subscribe(i),this.core.expirer.set(i,o),{topic:i,uri:h}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);const{topic:i,symKey:o,relay:c}=wb(n.uri);if(this.pairings.keys.includes(i))throw new Error(`Pairing already exists: ${i}`);if(this.core.crypto.hasKeys(i))throw new Error(`Keychain already exists: ${i}`);const l=En(De.FIVE_MINUTES),h={topic:i,relay:c,expiry:l,active:!1};return await this.pairings.set(i,h),await this.core.crypto.setSymKey(o,i),await this.core.relayer.subscribe(i,{relay:c}),this.core.expirer.set(i,l),n.activatePairing&&await this.activate({topic:i}),h},this.activate=async({topic:n})=>{this.isInitialized();const i=En(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 o=await this.sendRequest(i,"wc_pairingPing",{}),{done:c,resolve:l,reject:h}=Os();this.events.once(rr("pairing_ping",o),({error:f})=>{f?h(f):l()}),await c()}},this.updateExpiry=async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})},this.updateMetadata=async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",Yt("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,o)=>{const c=nc(i,o),l=await this.core.crypto.encode(n,c),h=ko[i].req;return this.core.history.set(n,c),this.core.relayer.publish(n,l,h),c.id},this.sendResult=async(n,i,o)=>{const c=ih(n,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,n),f=ko[h.request.method].res;await this.core.relayer.publish(i,l,f),await this.core.history.resolve(c)},this.sendError=async(n,i,o)=>{const c=ic(n,o),l=await this.core.crypto.encode(i,c),h=await this.core.history.get(i,n),f=ko[h.request.method]?ko[h.request.method].res:ko.unregistered_method.res;await this.core.relayer.publish(i,l,f),await this.core.history.resolve(c)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Yt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{const n=this.pairings.getAll().filter(i=>hi(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{const{topic:i,payload:o}=n;switch(o.method){case"wc_pairingPing":return this.onPairingPingRequest(i,o);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,o);default:return this.onUnknownRpcMethodRequest(i,o)}},this.onRelayEventResponse=async n=>{const{topic:i,payload:o}=n,c=(await this.core.history.get(i,o.id)).request.method;switch(c){case"wc_pairingPing":return this.onPairingPingResponse(i,o);default:return this.onUnknownRpcMethodResponse(c)}},this.onPairingPingRequest=async(n,i)=>{const{id:o}=i;try{this.isValidPing({topic:n}),await this.sendResult(o,n,!0),this.events.emit("pairing_ping",{id:o,topic:n})}catch(c){await this.sendError(o,n,c),this.logger.error(c)}},this.onPairingPingResponse=(n,i)=>{const{id:o}=i;setTimeout(()=>{Vn(i)?this.events.emit(rr("pairing_ping",o),{}):xn(i)&&this.events.emit(rr("pairing_ping",o),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{const{id:o}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit("pairing_delete",{id:o,topic:n})}catch(c){await this.sendError(o,n,c),this.logger.error(c)}},this.onUnknownRpcMethodRequest=async(n,i)=>{const{id:o,method:c}=i;try{if(this.registeredMethods.includes(c))return;const l=Yt("WC_METHOD_UNSUPPORTED",c);await this.sendError(o,n,l),this.logger.error(l)}catch(l){await this.sendError(o,n,l),this.logger.error(l)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(Yt("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{if(!zr(n)){const{message:i}=_e("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(i)}if(!Db(n.uri)){const{message:i}=_e("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(i)}},this.isValidPing=async n=>{if(!zr(n)){const{message:o}=_e("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(o)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!zr(n)){const{message:o}=_e("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(o)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!gr(n,!1)){const{message:i}=_e("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=_e("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(hi(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=_e("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=pt.generateChildLogger(r,this.name),this.pairings=new ac(this.core,this.logger,this.name,this.storagePrefix)}get context(){return pt.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(kt.message,async e=>{const{topic:r,message:n}=e;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;const i=await this.core.crypto.decode(r,n);try{sh(i)?(this.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):sc(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.core.history.delete(r,i.id))}catch(o){this.logger.error(o)}})}registerExpirerEvents(){this.core.expirer.on(on.expired,async e=>{const{topic:r}=L1(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit("pairing_expire",{topic:r}))})}}class t7 extends _4{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new br.exports.EventEmitter,this.name=PE,this.version=TE,this.cached=[],this.initialized=!1,this.storagePrefix=di,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,i,o)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:o}),this.records.has(i.id))return;const c={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:o,expiry:En(De.THIRTY_DAYS)};this.records.set(c.id,c),this.events.emit(Nn.created,c)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=xn(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.events.emit(Nn.updated,i))},this.get=async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i)),this.delete=(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(o=>{if(o.topic===n){if(typeof i<"u"&&o.id!==i)return;this.records.delete(o.id),this.events.emit(Nn.deleted,o)}})},this.exists=async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1),this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=pt.generateChildLogger(r,this.name)}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:nc(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:n}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Nn.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Nn.created,e=>{const r=Nn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(Nn.updated,e=>{const r=Nn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.events.on(Nn.deleted,e=>{const r=Nn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e}),this.persist()}),this.core.heartbeat.on(Ps.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.records.forEach(e=>{De.toMiliseconds(e.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${e.id}`),this.delete(e.topic,e.id))})}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class r7 extends O4{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new br.exports.EventEmitter,this.name=NE,this.version=RE,this.cached=[],this.initialized=!1,this.storagePrefix=di,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(n,i)=>{this.isInitialized();const o=this.formatTarget(n),c={target:o,expiry:i};this.expirations.set(o,c),this.checkExpiry(o,c),this.events.emit(on.created,{target:o,expiration:c})},this.get=n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)},this.del=n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),o=this.getExpiration(i);this.expirations.delete(i),this.events.emit(on.deleted,{target:i,expiration:o})}},this.on=(n,i)=>{this.events.on(n,i)},this.once=(n,i)=>{this.events.once(n,i)},this.off=(n,i)=>{this.events.off(n,i)},this.removeListener=(n,i)=>{this.events.removeListener(n,i)},this.logger=pt.generateChildLogger(r,this.name)}get context(){return pt.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return cb(e);if(typeof e=="number")return lb(e);const{message:r}=_e("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(on.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=_e("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:n}=_e("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;De.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(on.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Ps.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(on.created,e=>{const r=on.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(on.expired,e=>{const r=on.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(on.deleted,e=>{const r=on.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}}class n7 extends A4{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.name=hh,this.initialized=!1,this.init=async n=>{P1()||!Pu()||(this.verifyUrl=n?.verifyUrl||ng,await this.createIframe())},this.register=async n=>{var i;if(this.initialized||await this.init(),!!this.iframe)try{(i=this.iframe.contentWindow)==null||i.postMessage(n.attestationId,this.verifyUrl),this.logger.info(`postMessage sent: ${n.attestationId} ${this.verifyUrl}`)}catch{}},this.resolve=async n=>{var i;if(this.isDevEnv)return"";this.logger.info(`resolving attestation: ${n.attestationId}`);const o=this.startAbortTimer(De.FIVE_SECONDS),c=await fetch(`${this.verifyUrl}/attestation/${n.attestationId}`,{signal:this.abortController.signal});return clearTimeout(o),c.status===200?(i=await c.json())==null?void 0:i.origin:""},this.createIframe=async()=>{try{await Promise.race([new Promise((n,i)=>{if(document.getElementById(hh))return n();const o=document.createElement("iframe");o.setAttribute("id",hh),o.setAttribute("src",`${this.verifyUrl}/${this.projectId}`),o.style.display="none",o.addEventListener("load",()=>{this.initialized=!0,n()}),o.addEventListener("error",c=>{i(c)}),document.body.append(o),this.iframe=o}),new Promise(n=>{setTimeout(()=>n("iframe load timeout"),De.toMiliseconds(De.ONE_SECOND/2))})])}catch(n){this.logger.error(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.error(n)}},this.logger=pt.generateChildLogger(r,this.name),this.verifyUrl=ng,this.abortController=new AbortController,this.isDevEnv=$u()&&process.env.IS_VITEST}get context(){return pt.getLoggerContext(this.logger)}startAbortTimer(e){return setTimeout(()=>this.abortController.abort(),De.toMiliseconds(e))}}var i7=Object.defineProperty,hg=Object.getOwnPropertySymbols,s7=Object.prototype.hasOwnProperty,o7=Object.prototype.propertyIsEnumerable,fg=(t,e,r)=>e in t?i7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,dg=(t,e)=>{for(var r in e||(e={}))s7.call(e,r)&&fg(t,r,e[r]);if(hg)for(var r of hg(e))o7.call(e,r)&&fg(t,r,e[r]);return t};class dh extends b4{constructor(e){super(e),this.protocol=Xp,this.version=aE,this.name=uh,this.events=new br.exports.EventEmitter,this.initialized=!1,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||tg;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||cE.logger}));this.logger=pt.generateChildLogger(r,this.name),this.heartbeat=new Ps.HeartBeat,this.crypto=new ME(this,this.logger,e?.keychain),this.history=new t7(this,this.logger),this.expirer=new r7(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new C6(dg(dg({},lE),e?.storageOptions)),this.relayer=new YE({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new e7(this,this.logger),this.verify=new n7(this.projectId||"",this.logger)}static async init(e){const r=new dh(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(IE,n),r}get context(){return pt.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const a7=dh,pg="wc",gg=2,mg="client",ph=`${pg}@${gg}:${mg}:`,gh={name:mg,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},wg="WALLETCONNECT_DEEPLINK_CHOICE",c7="proposal",vg="Proposal expired",l7="session",cc=De.SEVEN_DAYS,u7="engine",zo={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}}},mh={min:De.FIVE_MINUTES,max:De.SEVEN_DAYS},Wo={idle:"idle",active:"active"},h7="request",f7=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var d7=Object.defineProperty,p7=Object.defineProperties,g7=Object.getOwnPropertyDescriptors,yg=Object.getOwnPropertySymbols,m7=Object.prototype.hasOwnProperty,w7=Object.prototype.propertyIsEnumerable,bg=(t,e,r)=>e in t?d7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,an=(t,e)=>{for(var r in e||(e={}))m7.call(e,r)&&bg(t,r,e[r]);if(yg)for(var r of yg(e))w7.call(e,r)&&bg(t,r,e[r]);return t},wh=(t,e)=>p7(t,g7(e));class v7 extends $4{constructor(e){super(e),this.name=u7,this.events=new br.exports,this.initialized=!1,this.ignoredPayloadTypes=[ki],this.requestQueue={state:Wo.idle,requests:[]},this.requestQueueDelay=De.ONE_SECOND,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.client.core.pairing.register({methods:Object.keys(zo)}),this.initialized=!0,setTimeout(()=>{this.requestQueue.requests=this.getPendingSessionRequests(),this.processRequestQueue()},De.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{this.isInitialized();const n=wh(an({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:o,optionalNamespaces:c,sessionProperties:l,relays:h}=n;let f=i,v,x=!1;if(f&&(x=this.client.core.pairing.pairings.get(f).active),!f||!x){const{topic:L,uri:$}=await this.client.core.pairing.create();f=L,v=$}const _=await this.client.core.crypto.generateKeyPair(),S=an({requiredNamespaces:o,optionalNamespaces:c,relays:h??[{protocol:eg}],proposer:{publicKey:_,metadata:this.client.metadata}},l&&{sessionProperties:l}),{reject:P,resolve:j,done:H}=Os(De.FIVE_MINUTES,vg);if(this.events.once(rr("session_connect"),async({error:L,session:$})=>{if(L)P(L);else if($){$.self.publicKey=_;const T=wh(an({},$),{requiredNamespaces:$.requiredNamespaces,optionalNamespaces:$.optionalNamespaces});await this.client.session.set($.topic,T),await this.setExpiry($.topic,$.expiry),f&&await this.client.core.pairing.updateMetadata({topic:f,metadata:$.peer.metadata}),j(T)}}),!f){const{message:L}=_e("NO_MATCHING_KEY",`connect() pairing topic: ${f}`);throw new Error(L)}const Z=await this.sendRequest(f,"wc_sessionPropose",S),R=En(De.FIVE_MINUTES);return await this.setProposal(Z,an({id:Z,expiry:R},S)),{uri:v,approval:H}},this.pair=async r=>(this.isInitialized(),await this.client.core.pairing.pair(r)),this.approve=async r=>{this.isInitialized(),await this.isValidApprove(r);const{id:n,relayProtocol:i,namespaces:o,sessionProperties:c}=r,l=this.client.proposal.get(n);let{pairingTopic:h,proposer:f,requiredNamespaces:v,optionalNamespaces:x}=l;h=h||"",Ds(v)||(v=Cb(o,"approve()"));const _=await this.client.core.crypto.generateKeyPair(),S=f.publicKey,P=await this.client.core.crypto.generateSharedKey(_,S);h&&n&&(await this.client.core.pairing.updateMetadata({topic:h,metadata:f.metadata}),await this.sendResult(n,h,{relay:{protocol:i??"irn"},responderPublicKey:_}),await this.client.proposal.delete(n,Yt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:h}));const j=an({relay:{protocol:i??"irn"},namespaces:o,requiredNamespaces:v,optionalNamespaces:x,pairingTopic:h,controller:{publicKey:_,metadata:this.client.metadata},expiry:En(cc)},c&&{sessionProperties:c});await this.client.core.relayer.subscribe(P),await this.sendRequest(P,"wc_sessionSettle",j);const H=wh(an({},j),{topic:P,pairingTopic:h,acknowledged:!1,self:j.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:_});return await this.client.session.set(P,H),await this.setExpiry(P,En(cc)),{topic:P,acknowledged:()=>new Promise(Z=>setTimeout(()=>Z(this.client.session.get(P)),500))}},this.reject=async r=>{this.isInitialized(),await this.isValidReject(r);const{id:n,reason:i}=r,{pairingTopic:o}=this.client.proposal.get(n);o&&(await this.sendError(n,o,i),await this.client.proposal.delete(n,Yt("USER_DISCONNECTED")))},this.update=async r=>{this.isInitialized(),await this.isValidUpdate(r);const{topic:n,namespaces:i}=r,o=await this.sendRequest(n,"wc_sessionUpdate",{namespaces:i}),{done:c,resolve:l,reject:h}=Os();return this.events.once(rr("session_update",o),({error:f})=>{f?h(f):l()}),await this.client.session.update(n,{namespaces:i}),{acknowledged:c}},this.extend=async r=>{this.isInitialized(),await this.isValidExtend(r);const{topic:n}=r,i=await this.sendRequest(n,"wc_sessionExtend",{}),{done:o,resolve:c,reject:l}=Os();return this.events.once(rr("session_extend",i),({error:h})=>{h?l(h):c()}),await this.setExpiry(n,En(cc)),{acknowledged:o}},this.request=async r=>{this.isInitialized(),await this.isValidRequest(r);const{chainId:n,request:i,topic:o,expiry:c}=r,l=await this.sendRequest(o,"wc_sessionRequest",{request:i,chainId:n},c),{done:h,resolve:f,reject:v}=Os(c);this.events.once(rr("session_request",l),({error:_,result:S})=>{_?v(_):f(S)}),this.client.events.emit("session_request_sent",{topic:o,request:i,chainId:n,id:l});const x=await this.client.core.storage.getItem(wg);return ub({id:l,topic:o,wcDeepLink:x}),await h()},this.respond=async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:o}=i;Vn(i)?await this.sendResult(o,n,i.result):xn(i)&&await this.sendError(o,n,i.error),this.cleanupAfterResponse(r)},this.ping=async r=>{this.isInitialized(),await this.isValidPing(r);const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=await this.sendRequest(n,"wc_sessionPing",{}),{done:o,resolve:c,reject:l}=Os();this.events.once(rr("session_ping",i),({error:h})=>{h?l(h):c()}),await o()}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async r=>{this.isInitialized(),await this.isValidEmit(r);const{topic:n,event:i,chainId:o}=r;await this.sendRequest(n,"wc_sessionEvent",{event:i,chainId:o})},this.disconnect=async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=nh().toString();let o;const c=l=>{l?.id.toString()===i&&(this.client.core.relayer.events.removeListener(kt.message_ack,c),o())};await Promise.all([new Promise(l=>{o=l,this.client.core.relayer.on(kt.message_ack,c)}),this.sendRequest(n,"wc_sessionDelete",Yt("USER_DISCONNECTED"),void 0,i)]),await this.deleteSession(n)}else await this.client.core.pairing.disconnect({topic:n})},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>Ob(n,r))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{const n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(o=>{var c,l;return((c=o.peerMetadata)==null?void 0:c.url)&&((l=o.peerMetadata)==null?void 0:l.url)===r.peer.metadata.url&&o.topic&&o.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(o=>this.client.core.pairing.disconnect({topic:o.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async(r,n)=>{const{self:i}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),this.client.session.delete(r,Yt("USER_DISCONNECTED")),this.client.core.crypto.keychain.has(i.publicKey)&&await this.client.core.crypto.deleteKeyPair(i.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(wg).catch(o=>this.client.logger.warn(o))},this.deleteProposal=async(r,n)=>{await Promise.all([this.client.proposal.delete(r,Yt("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)])},this.deletePendingSessionRequest=async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.requestQueue.requests=this.requestQueue.requests.filter(o=>o.id!==r),i&&(this.requestQueue.state=Wo.idle)},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&await this.client.session.update(r,{expiry:n}),this.client.core.expirer.set(r,n)},this.setProposal=async(r,n)=>{await this.client.proposal.set(r,n),this.client.core.expirer.set(r,n.expiry)},this.setPendingSessionRequest=async r=>{const n=zo.wc_sessionRequest.req.ttl,{id:i,topic:o,params:c}=r;await this.client.pendingRequest.set(i,{id:i,topic:o,params:c}),n&&this.client.core.expirer.set(i,En(n))},this.sendRequest=async(r,n,i,o,c)=>{const l=nc(n,i);if(Pu()&&f7.includes(n)){const v=Ss(JSON.stringify(l));await this.client.core.verify.register({attestationId:v})}const h=await this.client.core.crypto.encode(r,l),f=zo[n].req;return o&&(f.ttl=o),c&&(f.id=c),this.client.core.history.set(r,l),this.client.core.relayer.publish(r,h,f),l.id},this.sendResult=async(r,n,i)=>{const o=ih(r,i),c=await this.client.core.crypto.encode(n,o),l=await this.client.core.history.get(n,r),h=zo[l.request.method].res;this.client.core.relayer.publish(n,c,h),await this.client.core.history.resolve(o)},this.sendError=async(r,n,i)=>{const o=ic(r,i),c=await this.client.core.crypto.encode(n,o),l=await this.client.core.history.get(n,r),h=zo[l.request.method].res;this.client.core.relayer.publish(n,c,h),await this.client.core.history.resolve(o)},this.cleanup=async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{hi(i.expiry)&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{hi(i.expiry)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession(i)),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=r=>{const{topic:n,payload:i}=r,o=i.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeRequest(n,i);case"wc_sessionSettle":return this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return this.onSessionExtendRequest(n,i);case"wc_sessionPing":return this.onSessionPingRequest(n,i);case"wc_sessionDelete":return this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return this.onSessionRequest(n,i);case"wc_sessionEvent":return this.onSessionEventRequest(n,i);default:return this.client.logger.info(`Unsupported request method ${o}`)}},this.onRelayEventResponse=async r=>{const{topic:n,payload:i}=r,o=(await this.client.core.history.get(n,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}},this.onRelayEventUnknownPayload=r=>{const{topic:n}=r,{message:i}=_e("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.onSessionProposeRequest=async(r,n)=>{const{params:i,id:o}=n;try{this.isValidConnect(an({},n.params));const c=En(De.FIVE_MINUTES),l=an({id:o,pairingTopic:r,expiry:c},i);await this.setProposal(o,l);const h=Ss(JSON.stringify(n)),f=await this.getVerifyContext(h,l.proposer.metadata);this.client.events.emit("session_proposal",{id:o,params:l,verifyContext:f})}catch(c){await this.sendError(o,r,c),this.client.logger.error(c)}},this.onSessionProposeResponse=async(r,n)=>{const{id:i}=n;if(Vn(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const c=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:c});const l=c.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:l});const h=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const f=await this.client.core.crypto.generateSharedKey(l,h);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:f});const v=await this.client.core.relayer.subscribe(f);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:v}),await this.client.core.pairing.activate({topic:r})}else xn(n)&&(await this.client.proposal.delete(i,Yt("USER_DISCONNECTED")),this.events.emit(rr("session_connect"),{error:n.error}))},this.onSessionSettleRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidSessionSettleRequest(o);const{relay:c,controller:l,expiry:h,namespaces:f,requiredNamespaces:v,optionalNamespaces:x,sessionProperties:_,pairingTopic:S}=n.params,P=an({topic:r,relay:c,expiry:h,namespaces:f,acknowledged:!0,pairingTopic:S,requiredNamespaces:v,optionalNamespaces:x,controller:l.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:l.publicKey,metadata:l.metadata}},_&&{sessionProperties:_});await this.sendResult(n.id,r,!0),this.events.emit(rr("session_connect"),{session:P}),this.cleanupDuplicatePairings(P)}catch(c){await this.sendError(i,r,c),this.client.logger.error(c)}},this.onSessionSettleResponse=async(r,n)=>{const{id:i}=n;Vn(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(rr("session_approve",i),{})):xn(n)&&(await this.client.session.delete(r,Yt("USER_DISCONNECTED")),this.events.emit(rr("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{const{params:i,id:o}=n;try{this.isValidUpdate(an({topic:r},i)),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult(o,r,!0),this.client.events.emit("session_update",{id:o,topic:r,params:i})}catch(c){await this.sendError(o,r,c),this.client.logger.error(c)}},this.onSessionUpdateResponse=(r,n)=>{const{id:i}=n;Vn(n)?this.events.emit(rr("session_update",i),{}):xn(n)&&this.events.emit(rr("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,En(cc)),await this.sendResult(i,r,!0),this.client.events.emit("session_extend",{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionExtendResponse=(r,n)=>{const{id:i}=n;Vn(n)?this.events.emit(rr("session_extend",i),{}):xn(n)&&this.events.emit(rr("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult(i,r,!0),this.client.events.emit("session_ping",{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.client.logger.error(o)}},this.onSessionPingResponse=(r,n)=>{const{id:i}=n;setTimeout(()=>{Vn(n)?this.events.emit(rr("session_ping",i),{}):xn(n)&&this.events.emit(rr("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(o=>{this.client.core.relayer.once(kt.publish,async()=>{o(await this.deleteSession(r))})}),this.sendResult(i,r,!0)]),this.client.events.emit("session_delete",{id:i,topic:r})}catch(o){this.client.logger.error(o)}},this.onSessionRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidRequest(an({topic:r},o)),await this.setPendingSessionRequest({id:i,topic:r,params:o}),this.addRequestToQueue({id:i,topic:r,params:o}),await this.processRequestQueue()}catch(c){await this.sendError(i,r,c),this.client.logger.error(c)}},this.onSessionRequestResponse=(r,n)=>{const{id:i}=n;Vn(n)?this.events.emit(rr("session_request",i),{result:n.result}):xn(n)&&this.events.emit(rr("session_request",i),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{const{id:i,params:o}=n;try{this.isValidEmit(an({topic:r},o)),this.client.events.emit("session_event",{id:i,topic:r,params:o})}catch(c){await this.sendError(i,r,c),this.client.logger.error(c)}},this.addRequestToQueue=r=>{this.requestQueue.requests.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.requestQueue.state=Wo.idle,this.processRequestQueue()},De.toMiliseconds(this.requestQueueDelay))},this.processRequestQueue=async()=>{if(this.requestQueue.state===Wo.active){this.client.logger.info("session request queue is already active.");return}const r=this.requestQueue.requests[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{const{id:n,topic:i,params:o}=r,c=Ss(JSON.stringify({id:n,params:o})),l=this.client.session.get(i),h=await this.getVerifyContext(c,l.peer.metadata);this.requestQueue.state=Wo.active,this.client.events.emit("session_request",{id:n,topic:i,params:o,verifyContext:h})}catch(n){this.client.logger.error(n)}},this.isValidConnect=async r=>{if(!zr(r)){const{message:h}=_e("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(h)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:c,relays:l}=r;if(Pr(n)||await this.isValidPairingTopic(n),!Fb(l,!0)){const{message:h}=_e("MISSING_OR_INVALID",`connect() relays: ${l}`);throw new Error(h)}!Pr(i)&&Ds(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Pr(o)&&Ds(o)!==0&&this.validateNamespaces(o,"optionalNamespaces"),Pr(c)||this.validateSessionProps(c,"sessionProperties")},this.validateNamespaces=(r,n)=>{const i=jb(r,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async r=>{if(!zr(r))throw new Error(_e("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:o,sessionProperties:c}=r;await this.isValidProposalId(n);const l=this.client.proposal.get(n),h=Qa(i,"approve()");if(h)throw new Error(h.message);const f=H1(l.requiredNamespaces,i,"approve()");if(f)throw new Error(f.message);if(!gr(o,!0)){const{message:v}=_e("MISSING_OR_INVALID",`approve() relayProtocol: ${o}`);throw new Error(v)}Pr(c)||this.validateSessionProps(c,"sessionProperties")},this.isValidReject=async r=>{if(!zr(r)){const{message:o}=_e("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(o)}const{id:n,reason:i}=r;if(await this.isValidProposalId(n),!kb(i)){const{message:o}=_e("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidSessionSettleRequest=r=>{if(!zr(r)){const{message:f}=_e("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(f)}const{relay:n,controller:i,namespaces:o,expiry:c}=r;if(!B1(n)){const{message:f}=_e("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(f)}const l=Tb(i,"onSessionSettleRequest()");if(l)throw new Error(l.message);const h=Qa(o,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(hi(c)){const{message:f}=_e("EXPIRED","onSessionSettleRequest()");throw new Error(f)}},this.isValidUpdate=async r=>{if(!zr(r)){const{message:h}=_e("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(h)}const{topic:n,namespaces:i}=r;await this.isValidSessionTopic(n);const o=this.client.session.get(n),c=Qa(i,"update()");if(c)throw new Error(c.message);const l=H1(o.requiredNamespaces,i,"update()");if(l)throw new Error(l.message)},this.isValidExtend=async r=>{if(!zr(r)){const{message:i}=_e("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!zr(r)){const{message:h}=_e("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(h)}const{topic:n,request:i,chainId:o,expiry:c}=r;await this.isValidSessionTopic(n);const{namespaces:l}=this.client.session.get(n);if(!k1(l,o)){const{message:h}=_e("MISSING_OR_INVALID",`request() chainId: ${o}`);throw new Error(h)}if(!Hb(i)){const{message:h}=_e("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(h)}if(!qb(l,o,i.method)){const{message:h}=_e("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(h)}if(c&&!Zb(c,mh)){const{message:h}=_e("MISSING_OR_INVALID",`request() expiry: ${c}. Expiry must be a number (in seconds) between ${mh.min} and ${mh.max}`);throw new Error(h)}},this.isValidRespond=async r=>{if(!zr(r)){const{message:o}=_e("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:n,response:i}=r;if(await this.isValidSessionTopic(n),!zb(i)){const{message:o}=_e("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(o)}},this.isValidPing=async r=>{if(!zr(r)){const{message:i}=_e("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!zr(r)){const{message:l}=_e("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(l)}const{topic:n,event:i,chainId:o}=r;await this.isValidSessionTopic(n);const{namespaces:c}=this.client.session.get(n);if(!k1(c,o)){const{message:l}=_e("MISSING_OR_INVALID",`emit() chainId: ${o}`);throw new Error(l)}if(!Wb(i)){const{message:l}=_e("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}if(!Vb(c,o,i.name)){const{message:l}=_e("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(l)}},this.isValidDisconnect=async r=>{if(!zr(r)){const{message:i}=_e("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.getVerifyContext=async(r,n)=>{const i={verified:{verifyUrl:n.verifyUrl||"",validation:"UNKNOWN",origin:n.url||""}};try{const o=await this.client.core.verify.resolve({attestationId:r,verifyUrl:n.verifyUrl});o&&(i.verified.origin=o,i.verified.validation=o===n.url?"VALID":"INVALID")}catch(o){this.client.logger.error(o)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(r,n)=>{Object.values(r).forEach(i=>{if(!gr(i,!1)){const{message:o}=_e("MISSING_OR_INVALID",`${n} must be in Record<string, string> format. Received: ${JSON.stringify(i)}`);throw new Error(o)}})}}isInitialized(){if(!this.initialized){const{message:e}=_e("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.client.core.relayer.on(kt.message,async e=>{const{topic:r,message:n}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(n)))return;const i=await this.client.core.crypto.decode(r,n);try{sh(i)?(this.client.core.history.set(r,i),this.onRelayEventRequest({topic:r,payload:i})):sc(i)?(await this.client.core.history.resolve(i),await this.onRelayEventResponse({topic:r,payload:i}),this.client.core.history.delete(r,i.id)):this.onRelayEventUnknownPayload({topic:r,payload:i})}catch(o){this.client.logger.error(o)}})}registerExpirerEvents(){this.client.core.expirer.on(on.expired,async e=>{const{topic:r,id:n}=L1(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,_e("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession(r,!0),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}isValidPairingTopic(e){if(!gr(e,!1)){const{message:r}=_e("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=_e("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(hi(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=_e("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!gr(e,!1)){const{message:r}=_e("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(!this.client.session.keys.includes(e)){const{message:r}=_e("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(hi(this.client.session.get(e).expiry)){await this.deleteSession(e);const{message:r}=_e("EXPIRED",`session topic: ${e}`);throw new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(gr(e,!1)){const{message:r}=_e("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=_e("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!Bb(e)){const{message:r}=_e("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=_e("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(hi(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:r}=_e("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class y7 extends ac{constructor(e,r){super(e,r,c7,ph),this.core=e,this.logger=r}}class b7 extends ac{constructor(e,r){super(e,r,l7,ph),this.core=e,this.logger=r}}class _7 extends ac{constructor(e,r){super(e,r,h7,ph,n=>n.id),this.core=e,this.logger=r}}class vh extends D4{constructor(e){super(e),this.protocol=pg,this.version=gg,this.name=gh.name,this.events=new br.exports.EventEmitter,this.on=(n,i)=>this.events.on(n,i),this.once=(n,i)=>this.events.once(n,i),this.off=(n,i)=>this.events.off(n,i),this.removeListener=(n,i)=>this.events.removeListener(n,i),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}},this.update=async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}},this.request=async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}},this.find=n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.name=e?.name||gh.name,this.metadata=e?.metadata||nb();const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pt.pino(pt.getDefaultLoggerOptions({level:e?.logger||gh.logger}));this.core=e?.core||new a7(e),this.logger=pt.generateChildLogger(r,this.name),this.session=new b7(this.core,this.logger),this.proposal=new y7(this.core,this.logger),this.pendingRequest=new _7(this.core,this.logger),this.engine=new v7(this)}static async init(e){const r=new vh(e);return await r.initialize(),r}get context(){return pt.getLoggerContext(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),this.core.verify.init({verifyUrl:this.metadata.verifyUrl}),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var yh={exports:{}};(function(t,e){var r=typeof self<"u"?self:pr,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(c){var l={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function h(O){return O&&DataView.prototype.isPrototypeOf(O)}if(l.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],v=ArrayBuffer.isView||function(O){return O&&f.indexOf(Object.prototype.toString.call(O))>-1};function x(O){if(typeof O!="string"&&(O=String(O)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(O))throw new TypeError("Invalid character in header field name");return O.toLowerCase()}function _(O){return typeof O!="string"&&(O=String(O)),O}function S(O){var U={next:function(){var ce=O.shift();return{done:ce===void 0,value:ce}}};return l.iterable&&(U[Symbol.iterator]=function(){return U}),U}function P(O){this.map={},O instanceof P?O.forEach(function(U,ce){this.append(ce,U)},this):Array.isArray(O)?O.forEach(function(U){this.append(U[0],U[1])},this):O&&Object.getOwnPropertyNames(O).forEach(function(U){this.append(U,O[U])},this)}P.prototype.append=function(O,U){O=x(O),U=_(U);var ce=this.map[O];this.map[O]=ce?ce+", "+U:U},P.prototype.delete=function(O){delete this.map[x(O)]},P.prototype.get=function(O){return O=x(O),this.has(O)?this.map[O]:null},P.prototype.has=function(O){return this.map.hasOwnProperty(x(O))},P.prototype.set=function(O,U){this.map[x(O)]=_(U)},P.prototype.forEach=function(O,U){for(var ce in this.map)this.map.hasOwnProperty(ce)&&O.call(U,this.map[ce],ce,this)},P.prototype.keys=function(){var O=[];return this.forEach(function(U,ce){O.push(ce)}),S(O)},P.prototype.values=function(){var O=[];return this.forEach(function(U){O.push(U)}),S(O)},P.prototype.entries=function(){var O=[];return this.forEach(function(U,ce){O.push([ce,U])}),S(O)},l.iterable&&(P.prototype[Symbol.iterator]=P.prototype.entries);function j(O){if(O.bodyUsed)return Promise.reject(new TypeError("Already read"));O.bodyUsed=!0}function H(O){return new Promise(function(U,ce){O.onload=function(){U(O.result)},O.onerror=function(){ce(O.error)}})}function Z(O){var U=new FileReader,ce=H(U);return U.readAsArrayBuffer(O),ce}function R(O){var U=new FileReader,ce=H(U);return U.readAsText(O),ce}function L(O){for(var U=new Uint8Array(O),ce=new Array(U.length),le=0;le<U.length;le++)ce[le]=String.fromCharCode(U[le]);return ce.join("")}function $(O){if(O.slice)return O.slice(0);var U=new Uint8Array(O.byteLength);return U.set(new Uint8Array(O)),U.buffer}function T(){return this.bodyUsed=!1,this._initBody=function(O){this._bodyInit=O,O?typeof O=="string"?this._bodyText=O:l.blob&&Blob.prototype.isPrototypeOf(O)?this._bodyBlob=O:l.formData&&FormData.prototype.isPrototypeOf(O)?this._bodyFormData=O:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(O)?this._bodyText=O.toString():l.arrayBuffer&&l.blob&&h(O)?(this._bodyArrayBuffer=$(O.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(O)||v(O))?this._bodyArrayBuffer=$(O):this._bodyText=O=Object.prototype.toString.call(O):this._bodyText="",this.headers.get("content-type")||(typeof O=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):l.searchParams&&URLSearchParams.prototype.isPrototypeOf(O)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var O=j(this);if(O)return O;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?j(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(Z)}),this.text=function(){var O=j(this);if(O)return O;if(this._bodyBlob)return R(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(L(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},l.formData&&(this.formData=function(){return this.text().then(J)}),this.json=function(){return this.text().then(JSON.parse)},this}var I=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function d(O){var U=O.toUpperCase();return I.indexOf(U)>-1?U:O}function E(O,U){U=U||{};var ce=U.body;if(O instanceof E){if(O.bodyUsed)throw new TypeError("Already read");this.url=O.url,this.credentials=O.credentials,U.headers||(this.headers=new P(O.headers)),this.method=O.method,this.mode=O.mode,this.signal=O.signal,!ce&&O._bodyInit!=null&&(ce=O._bodyInit,O.bodyUsed=!0)}else this.url=String(O);if(this.credentials=U.credentials||this.credentials||"same-origin",(U.headers||!this.headers)&&(this.headers=new P(U.headers)),this.method=d(U.method||this.method||"GET"),this.mode=U.mode||this.mode||null,this.signal=U.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&ce)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(ce)}E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function J(O){var U=new FormData;return O.trim().split("&").forEach(function(ce){if(ce){var le=ce.split("="),re=le.shift().replace(/\+/g," "),ne=le.join("=").replace(/\+/g," ");U.append(decodeURIComponent(re),decodeURIComponent(ne))}}),U}function z(O){var U=new P,ce=O.replace(/\r?\n[\t ]+/g," ");return ce.split(/\r?\n/).forEach(function(le){var re=le.split(":"),ne=re.shift().trim();if(ne){var ae=re.join(":").trim();U.append(ne,ae)}}),U}T.call(E.prototype);function ee(O,U){U||(U={}),this.type="default",this.status=U.status===void 0?200:U.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in U?U.statusText:"OK",this.headers=new P(U.headers),this.url=U.url||"",this._initBody(O)}T.call(ee.prototype),ee.prototype.clone=function(){return new ee(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new P(this.headers),url:this.url})},ee.error=function(){var O=new ee(null,{status:0,statusText:""});return O.type="error",O};var de=[301,302,303,307,308];ee.redirect=function(O,U){if(de.indexOf(U)===-1)throw new RangeError("Invalid status code");return new ee(null,{status:U,headers:{location:O}})},c.DOMException=o.DOMException;try{new c.DOMException}catch{c.DOMException=function(U,ce){this.message=U,this.name=ce;var le=Error(U);this.stack=le.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function me(O,U){return new Promise(function(ce,le){var re=new E(O,U);if(re.signal&&re.signal.aborted)return le(new c.DOMException("Aborted","AbortError"));var ne=new XMLHttpRequest;function ae(){ne.abort()}ne.onload=function(){var ie={status:ne.status,statusText:ne.statusText,headers:z(ne.getAllResponseHeaders()||"")};ie.url="responseURL"in ne?ne.responseURL:ie.headers.get("X-Request-URL");var Ae="response"in ne?ne.response:ne.responseText;ce(new ee(Ae,ie))},ne.onerror=function(){le(new TypeError("Network request failed"))},ne.ontimeout=function(){le(new TypeError("Network request failed"))},ne.onabort=function(){le(new c.DOMException("Aborted","AbortError"))},ne.open(re.method,re.url,!0),re.credentials==="include"?ne.withCredentials=!0:re.credentials==="omit"&&(ne.withCredentials=!1),"responseType"in ne&&l.blob&&(ne.responseType="blob"),re.headers.forEach(function(ie,Ae){ne.setRequestHeader(Ae,ie)}),re.signal&&(re.signal.addEventListener("abort",ae),ne.onreadystatechange=function(){ne.readyState===4&&re.signal.removeEventListener("abort",ae)}),ne.send(typeof re._bodyInit>"u"?null:re._bodyInit)})}return me.polyfill=!0,o.fetch||(o.fetch=me,o.Headers=P,o.Request=E,o.Response=ee),c.Headers=P,c.Request=E,c.Response=ee,c.fetch=me,Object.defineProperty(c,"__esModule",{value:!0}),c})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(yh,yh.exports);var _g=bw(yh.exports);const Eg={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},xg=10;class Vi{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new br.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!Ap(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e,r){this.isAvailable||await this.register();try{const n=Mo(e),o=await(await _g(this.url,Object.assign(Object.assign({},Eg),{body:n}))).json();this.onPayload({data:o})}catch(n){this.onError(e.id,n)}}async register(e=this.url){if(!Ap(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",o=>{this.resetMaxListeners(),i(o)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));n()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=Mo({id:1,jsonrpc:"2.0",method:"test",params:[]});await _g(e,Object.assign(Object.assign({},Eg),{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"?Ju(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),o=ic(e,i);this.events.emit("payload",o)}parseError(e,r=this.url){return _p(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>xg&&this.events.setMaxListeners(xg)}}const Cg="error",E7="wss://relay.walletconnect.com",x7="wc",C7="universal_provider",Ig=`${x7}@2:${C7}:`,I7="https://rpc.walletconnect.com/v1",pi={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var qo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},bh={exports:{}};/**
|
|
73
73
|
* @license
|
|
74
74
|
* Lodash <https://lodash.com/>
|
|
75
75
|
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
|