@walletconnect/ethereum-provider 2.11.1 → 2.11.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/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +5 -5
package/dist/index.umd.js
CHANGED
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
57
57
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
58
58
|
PERFORMANCE OF THIS SOFTWARE.
|
|
59
|
-
***************************************************************************** */var Ou=function(r,e){return Ou=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var i in n)n.hasOwnProperty(i)&&(t[i]=n[i])},Ou(r,e)};function _6(r,e){Ou(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var $u=function(){return $u=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++){t=arguments[n];for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a])}return e},$u.apply(this,arguments)};function E6(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t}function x6(r,e,t,n){var i=arguments.length,a=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,n);else for(var u=r.length-1;u>=0;u--)(c=r[u])&&(a=(i<3?c(a):i>3?c(e,t,a):c(e,t))||a);return i>3&&a&&Object.defineProperty(e,t,a),a}function I6(r,e){return function(t,n){e(t,n,r)}}function D6(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function S6(r,e,t,n){function i(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function u(m){try{h(n.next(m))}catch(w){c(w)}}function f(m){try{h(n.throw(m))}catch(w){c(w)}}function h(m){m.done?a(m.value):i(m.value).then(u,f)}h((n=n.apply(r,e||[])).next())})}function C6(r,e){var t={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},n,i,a,c;return c={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(c[Symbol.iterator]=function(){return this}),c;function u(h){return function(m){return f([h,m])}}function f(h){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,i&&(a=h[0]&2?i.return:h[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,h[1])).done)return a;switch(i=0,a&&(h=[h[0]&2,a.value]),h[0]){case 0:case 1:a=h;break;case 4:return t.label++,{value:h[1],done:!1};case 5:t.label++,i=h[1],h=[0];continue;case 7:h=t.ops.pop(),t.trys.pop();continue;default:if(a=t.trys,!(a=a.length>0&&a[a.length-1])&&(h[0]===6||h[0]===2)){t=0;continue}if(h[0]===3&&(!a||h[1]>a[0]&&h[1]<a[3])){t.label=h[1];break}if(h[0]===6&&t.label<a[1]){t.label=a[1],a=h;break}if(a&&t.label<a[2]){t.label=a[2],t.ops.push(h);break}a[2]&&t.ops.pop(),t.trys.pop();continue}h=e.call(r,t)}catch(m){h=[6,m],i=0}finally{n=a=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}}function O6(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}function $6(r,e){for(var t in r)t!=="default"&&!e.hasOwnProperty(t)&&(e[t]=r[t])}function Au(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function qp(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,a=[],c;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)a.push(i.value)}catch(u){c={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(c)throw c.error}}return a}function A6(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(qp(arguments[e]));return r}function P6(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),i=0,e=0;e<t;e++)for(var a=arguments[e],c=0,u=a.length;c<u;c++,i++)n[i]=a[c];return n}function Po(r){return this instanceof Po?(this.v=r,this):new Po(r)}function T6(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,e||[]),i,a=[];return i={},c("next"),c("throw"),c("return"),i[Symbol.asyncIterator]=function(){return this},i;function c(y){n[y]&&(i[y]=function(x){return new Promise(function(S,P){a.push([y,x,S,P])>1||u(y,x)})})}function u(y,x){try{f(n[y](x))}catch(S){w(a[0][3],S)}}function f(y){y.value instanceof Po?Promise.resolve(y.value.v).then(h,m):w(a[0][2],y)}function h(y){u("next",y)}function m(y){u("throw",y)}function w(y,x){y(x),a.shift(),a.length&&u(a[0][0],a[0][1])}}function R6(r){var e,t;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,a){e[i]=r[i]?function(c){return(t=!t)?{value:Po(r[i](c)),done:i==="return"}:a?a(c):c}:a}}function N6(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof Au=="function"?Au(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(a){t[a]=r[a]&&function(c){return new Promise(function(u,f){c=r[a](c),i(u,f,c.done,c.value)})}}function i(a,c,u,f){Promise.resolve(f).then(function(h){a({value:h,done:u})},c)}}function L6(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function M6(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)Object.hasOwnProperty.call(r,t)&&(e[t]=r[t]);return e.default=r,e}function U6(r){return r&&r.__esModule?r:{default:r}}function j6(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function F6(r,e,t){if(!e.has(r))throw new TypeError("attempted to set private field on non-instance");return e.set(r,t),t}var B6=Object.freeze({__proto__:null,__extends:_6,get __assign(){return $u},__rest:E6,__decorate:x6,__param:I6,__metadata:D6,__awaiter:S6,__generator:C6,__createBinding:O6,__exportStar:$6,__values:Au,__read:qp,__spread:A6,__spreadArrays:P6,__await:Po,__asyncGenerator:T6,__asyncDelegator:R6,__asyncValues:N6,__makeTemplateObject:L6,__importStar:M6,__importDefault:U6,__classPrivateFieldGet:j6,__classPrivateFieldSet:F6}),k6=Pi(B6),Nn={},zp;function q6(){if(zp)return Nn;zp=1,Object.defineProperty(Nn,"__esModule",{value:!0}),Nn.isBrowserCryptoAvailable=Nn.getSubtleCrypto=Nn.getBrowerCrypto=void 0;function r(){return yr?.crypto||yr?.msCrypto||{}}Nn.getBrowerCrypto=r;function e(){const n=r();return n.subtle||n.webkitSubtle}Nn.getSubtleCrypto=e;function t(){return!!r()&&!!e()}return Nn.isBrowserCryptoAvailable=t,Nn}var Ln={},Hp;function z6(){if(Hp)return Ln;Hp=1,Object.defineProperty(Ln,"__esModule",{value:!0}),Ln.isBrowser=Ln.isNode=Ln.isReactNative=void 0;function r(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ln.isReactNative=r;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Ln.isNode=e;function t(){return!r()&&!e()}return Ln.isBrowser=t,Ln}(function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=k6;e.__exportStar(q6(),r),e.__exportStar(z6(),r)})(kp);function Pu(r=3){const e=Date.now()*Math.pow(10,r),t=Math.floor(Math.random()*Math.pow(10,r));return e+t}function Wp(r=6){return BigInt(Pu(r))}function Ss(r,e,t){return{id:t||Pu(),jsonrpc:"2.0",method:r,params:e}}function za(r,e){return{id:r,jsonrpc:"2.0",result:e}}function Ha(r,e,t){return{id:r,jsonrpc:"2.0",error:H6(e,t)}}function H6(r,e){return typeof r>"u"?Fp(Up):(typeof r=="string"&&(r=Object.assign(Object.assign({},Fp(Cu)),{message:r})),typeof e<"u"&&(r.data=e),w6(r.code)&&(r=b6(r.code)),r)}class W6{}class K6 extends W6{constructor(){super()}}class V6 extends K6{constructor(e){super()}}const G6="^https?:",Y6="^wss?:";function J6(r){const e=r.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Kp(r,e){const t=J6(r);return typeof t>"u"?!1:new RegExp(e).test(t)}function Vp(r){return Kp(r,G6)}function Gp(r){return Kp(r,Y6)}function Z6(r){return new RegExp("wss?://localhost(:d{2,5})?").test(r)}function Yp(r){return typeof r=="object"&&"id"in r&&"jsonrpc"in r&&r.jsonrpc==="2.0"}function Tu(r){return Yp(r)&&"method"in r}function Wa(r){return Yp(r)&&(Mn(r)||dn(r))}function Mn(r){return"result"in r}function dn(r){return"error"in r}class Un extends V6{constructor(e){super(e),this.events=new lr.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,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async request(e,t){return this.requestStrict(Ss(e.method,e.params||[],e.id||Wp().toString()),t)}async requestStrict(e,t){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(a){i(a)}this.events.on(`${e.id}`,a=>{dn(a)?i(a.error):n(a.result)});try{await this.connection.send(e,t)}catch(a){i(a)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Wa(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 Q6=()=>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"),X6=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Jp=r=>r.split("?")[0],Zp=10,eE=Q6();class tE{constructor(e){if(this.url=e,this.events=new lr.exports.EventEmitter,this.registering=!1,!Gp(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,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,t)=>{if(typeof this.socket>"u"){t(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ji(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!Gp(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((n,i)=>{this.events.once("register_error",a=>{this.resetMaxListeners(),i(a)}),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((t,n)=>{const i=new URLSearchParams(e).get("origin"),a=kp.isReactNative()?{headers:{origin:i}}:{rejectUnauthorized:!Z6(e)},c=new eE(e,[],a);X6()?c.onerror=u=>{const f=u;n(this.emitError(f.error))}:c.on("error",u=>{n(this.emitError(u))}),c.onopen=()=>{this.onOpen(c),t(c)}})}onOpen(e){e.onmessage=t=>this.onPayload(t),e.onclose=t=>this.onClose(t),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 t=typeof e.data=="string"?Do(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const n=this.parseError(t),i=n.message||n.toString(),a=Ha(e,i);this.events.emit("payload",a)}parseError(e,t=this.url){return Bp(e,Jp(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Zp&&this.events.setMaxListeners(Zp)}emitError(e){const t=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Jp(this.url)}`));return this.events.emit("register_error",t),t}}var Ru={exports:{}};(function(r,e){var t=200,n="__lodash_hash_undefined__",i=1,a=2,c=9007199254740991,u="[object Arguments]",f="[object Array]",h="[object AsyncFunction]",m="[object Boolean]",w="[object Date]",y="[object Error]",x="[object Function]",S="[object GeneratorFunction]",P="[object Map]",U="[object Number]",j="[object Null]",A="[object Object]",T="[object Promise]",C="[object Proxy]",$="[object RegExp]",E="[object Set]",d="[object String]",b="[object Symbol]",H="[object Undefined]",F="[object WeakMap]",V="[object ArrayBuffer]",se="[object DataView]",ce="[object Float32Array]",I="[object Float64Array]",N="[object Int8Array]",X="[object Int16Array]",ee="[object Int32Array]",Y="[object Uint8Array]",J="[object Uint8ClampedArray]",Q="[object Uint16Array]",ie="[object Uint32Array]",Ee=/[\\^$.*+?()[\]{}|]/g,ae=/^\[object .+?Constructor\]$/,xe=/^(?:0|[1-9]\d*)$/,de={};de[ce]=de[I]=de[N]=de[X]=de[ee]=de[Y]=de[J]=de[Q]=de[ie]=!0,de[u]=de[f]=de[V]=de[m]=de[se]=de[w]=de[y]=de[x]=de[P]=de[U]=de[A]=de[$]=de[E]=de[d]=de[F]=!1;var be=typeof yr=="object"&&yr&&yr.Object===Object&&yr,K=typeof self=="object"&&self&&self.Object===Object&&self,W=be||K||Function("return this")(),B=e&&!e.nodeType&&e,g=B&&!0&&r&&!r.nodeType&&r,L=g&&g.exports===B,le=L&&be.process,pe=function(){try{return le&&le.binding&&le.binding("util")}catch{}}(),Ce=pe&&pe.isTypedArray;function Ke(O,k){for(var ne=-1,ge=O==null?0:O.length,vt=0,Ne=[];++ne<ge;){var Et=O[ne];k(Et,ne,O)&&(Ne[vt++]=Et)}return Ne}function Je(O,k){for(var ne=-1,ge=k.length,vt=O.length;++ne<ge;)O[vt+ne]=k[ne];return O}function ke(O,k){for(var ne=-1,ge=O==null?0:O.length;++ne<ge;)if(k(O[ne],ne,O))return!0;return!1}function St(O,k){for(var ne=-1,ge=Array(O);++ne<O;)ge[ne]=k(ne);return ge}function Ct(O){return function(k){return O(k)}}function ze(O,k){return O.has(k)}function Oe(O,k){return O?.[k]}function Ue(O){var k=-1,ne=Array(O.size);return O.forEach(function(ge,vt){ne[++k]=[vt,ge]}),ne}function je(O,k){return function(ne){return O(k(ne))}}function He(O){var k=-1,ne=Array(O.size);return O.forEach(function(ge){ne[++k]=ge}),ne}var Ae=Array.prototype,Fe=Function.prototype,Se=Object.prototype,Te=W["__core-js_shared__"],Ve=Fe.toString,$e=Se.hasOwnProperty,Ze=function(){var O=/[^.]+$/.exec(Te&&Te.keys&&Te.keys.IE_PROTO||"");return O?"Symbol(src)_1."+O:""}(),et=Se.toString,at=RegExp("^"+Ve.call($e).replace(Ee,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ct=L?W.Buffer:void 0,nt=W.Symbol,Sr=W.Uint8Array,Ur=Se.propertyIsEnumerable,On=Ae.splice,Cr=nt?nt.toStringTag:void 0,Wn=Object.getOwnPropertySymbols,bi=ct?ct.isBuffer:void 0,rs=je(Object.keys,Object),Lt=Gr(W,"DataView"),Ot=Gr(W,"Map"),Mt=Gr(W,"Promise"),Ut=Gr(W,"Set"),Tt=Gr(W,"WeakMap"),$t=Gr(Object,"create"),Gt=Vn(Lt),Yt=Vn(Ot),jt=Vn(Mt),Jt=Vn(Ut),Ft=Vn(Tt),Ht=nt?nt.prototype:void 0,Bt=Ht?Ht.valueOf:void 0;function _t(O){var k=-1,ne=O==null?0:O.length;for(this.clear();++k<ne;){var ge=O[k];this.set(ge[0],ge[1])}}function Zt(){this.__data__=$t?$t(null):{},this.size=0}function Qt(O){var k=this.has(O)&&delete this.__data__[O];return this.size-=k?1:0,k}function lf(O){var k=this.__data__;if($t){var ne=k[O];return ne===n?void 0:ne}return $e.call(k,O)?k[O]:void 0}function uf(O){var k=this.__data__;return $t?k[O]!==void 0:$e.call(k,O)}function hf(O,k){var ne=this.__data__;return this.size+=this.has(O)?0:1,ne[O]=$t&&k===void 0?n:k,this}_t.prototype.clear=Zt,_t.prototype.delete=Qt,_t.prototype.get=lf,_t.prototype.has=uf,_t.prototype.set=hf;function rn(O){var k=-1,ne=O==null?0:O.length;for(this.clear();++k<ne;){var ge=O[k];this.set(ge[0],ge[1])}}function ff(){this.__data__=[],this.size=0}function df(O){var k=this.__data__,ne=ns(k,O);if(ne<0)return!1;var ge=k.length-1;return ne==ge?k.pop():On.call(k,ne,1),--this.size,!0}function pf(O){var k=this.__data__,ne=ns(k,O);return ne<0?void 0:k[ne][1]}function gf(O){return ns(this.__data__,O)>-1}function mf(O,k){var ne=this.__data__,ge=ns(ne,O);return ge<0?(++this.size,ne.push([O,k])):ne[ge][1]=k,this}rn.prototype.clear=ff,rn.prototype.delete=df,rn.prototype.get=pf,rn.prototype.has=gf,rn.prototype.set=mf;function Kn(O){var k=-1,ne=O==null?0:O.length;for(this.clear();++k<ne;){var ge=O[k];this.set(ge[0],ge[1])}}function Ks(){this.size=0,this.__data__={hash:new _t,map:new(Ot||rn),string:new _t}}function vf(O){var k=_i(this,O).delete(O);return this.size-=k?1:0,k}function Vs(O){return _i(this,O).get(O)}function yf(O){return _i(this,O).has(O)}function wf(O,k){var ne=_i(this,O),ge=ne.size;return ne.set(O,k),this.size+=ne.size==ge?0:1,this}Kn.prototype.clear=Ks,Kn.prototype.delete=vf,Kn.prototype.get=Vs,Kn.prototype.has=yf,Kn.prototype.set=wf;function Gs(O){var k=-1,ne=O==null?0:O.length;for(this.__data__=new Kn;++k<ne;)this.add(O[k])}function Cc(O){return this.__data__.set(O,n),this}function Oc(O){return this.__data__.has(O)}Gs.prototype.add=Gs.prototype.push=Cc,Gs.prototype.has=Oc;function gn(O){var k=this.__data__=new rn(O);this.size=k.size}function bf(){this.__data__=new rn,this.size=0}function _f(O){var k=this.__data__,ne=k.delete(O);return this.size=k.size,ne}function Ef(O){return this.__data__.get(O)}function xf(O){return this.__data__.has(O)}function $c(O,k){var ne=this.__data__;if(ne instanceof rn){var ge=ne.__data__;if(!Ot||ge.length<t-1)return ge.push([O,k]),this.size=++ne.size,this;ne=this.__data__=new Kn(ge)}return ne.set(O,k),this.size=ne.size,this}gn.prototype.clear=bf,gn.prototype.delete=_f,gn.prototype.get=Ef,gn.prototype.has=xf,gn.prototype.set=$c;function Ac(O,k){var ne=Zs(O),ge=!ne&&qc(O),vt=!ne&&!ge&&sa(O),Ne=!ne&&!ge&&!vt&&Wc(O),Et=ne||ge||vt||Ne,Xt=Et?St(O.length,String):[],it=Xt.length;for(var yt in O)(k||$e.call(O,yt))&&!(Et&&(yt=="length"||vt&&(yt=="offset"||yt=="parent")||Ne&&(yt=="buffer"||yt=="byteLength"||yt=="byteOffset")||Uc(yt,it)))&&Xt.push(yt);return Xt}function ns(O,k){for(var ne=O.length;ne--;)if(kc(O[ne][0],k))return ne;return-1}function na(O,k,ne){var ge=k(O);return Zs(O)?ge:Je(ge,ne(O))}function is(O){return O==null?O===void 0?H:j:Cr&&Cr in Object(O)?Lc(O):Sf(O)}function ia(O){return os(O)&&is(O)==u}function ss(O,k,ne,ge,vt){return O===k?!0:O==null||k==null||!os(O)&&!os(k)?O!==O&&k!==k:Pc(O,k,ne,ge,ss,vt)}function Pc(O,k,ne,ge,vt,Ne){var Et=Zs(O),Xt=Zs(k),it=Et?f:$n(O),yt=Xt?f:$n(k);it=it==u?A:it,yt=yt==u?A:yt;var Wt=it==A,jr=yt==A,er=it==yt;if(er&&sa(O)){if(!sa(k))return!1;Et=!0,Wt=!1}if(er&&!Wt)return Ne||(Ne=new gn),Et||Wc(O)?Ys(O,k,ne,ge,vt,Ne):Df(O,k,it,ne,ge,vt,Ne);if(!(ne&i)){var xt=Wt&&$e.call(O,"__wrapped__"),Or=jr&&$e.call(k,"__wrapped__");if(xt||Or){var mn=xt?O.value():O,nn=Or?k.value():k;return Ne||(Ne=new gn),vt(mn,nn,ne,ge,Ne)}}return er?(Ne||(Ne=new gn),Nc(O,k,ne,ge,vt,Ne)):!1}function If(O){if(!Hc(O)||Fc(O))return!1;var k=Qs(O)?at:ae;return k.test(Vn(O))}function Tc(O){return os(O)&&zc(O.length)&&!!de[is(O)]}function Rc(O){if(!Bc(O))return rs(O);var k=[];for(var ne in Object(O))$e.call(O,ne)&&ne!="constructor"&&k.push(ne);return k}function Ys(O,k,ne,ge,vt,Ne){var Et=ne&i,Xt=O.length,it=k.length;if(Xt!=it&&!(Et&&it>Xt))return!1;var yt=Ne.get(O);if(yt&&Ne.get(k))return yt==k;var Wt=-1,jr=!0,er=ne&a?new Gs:void 0;for(Ne.set(O,k),Ne.set(k,O);++Wt<Xt;){var xt=O[Wt],Or=k[Wt];if(ge)var mn=Et?ge(Or,xt,Wt,k,O,Ne):ge(xt,Or,Wt,O,k,Ne);if(mn!==void 0){if(mn)continue;jr=!1;break}if(er){if(!ke(k,function(nn,An){if(!ze(er,An)&&(xt===nn||vt(xt,nn,ne,ge,Ne)))return er.push(An)})){jr=!1;break}}else if(!(xt===Or||vt(xt,Or,ne,ge,Ne))){jr=!1;break}}return Ne.delete(O),Ne.delete(k),jr}function Df(O,k,ne,ge,vt,Ne,Et){switch(ne){case se:if(O.byteLength!=k.byteLength||O.byteOffset!=k.byteOffset)return!1;O=O.buffer,k=k.buffer;case V:return!(O.byteLength!=k.byteLength||!Ne(new Sr(O),new Sr(k)));case m:case w:case U:return kc(+O,+k);case y:return O.name==k.name&&O.message==k.message;case $:case d:return O==k+"";case P:var Xt=Ue;case E:var it=ge&i;if(Xt||(Xt=He),O.size!=k.size&&!it)return!1;var yt=Et.get(O);if(yt)return yt==k;ge|=a,Et.set(O,k);var Wt=Ys(Xt(O),Xt(k),ge,vt,Ne,Et);return Et.delete(O),Wt;case b:if(Bt)return Bt.call(O)==Bt.call(k)}return!1}function Nc(O,k,ne,ge,vt,Ne){var Et=ne&i,Xt=Js(O),it=Xt.length,yt=Js(k),Wt=yt.length;if(it!=Wt&&!Et)return!1;for(var jr=it;jr--;){var er=Xt[jr];if(!(Et?er in k:$e.call(k,er)))return!1}var xt=Ne.get(O);if(xt&&Ne.get(k))return xt==k;var Or=!0;Ne.set(O,k),Ne.set(k,O);for(var mn=Et;++jr<it;){er=Xt[jr];var nn=O[er],An=k[er];if(ge)var oa=Et?ge(An,nn,er,k,O,Ne):ge(nn,An,er,O,k,Ne);if(!(oa===void 0?nn===An||vt(nn,An,ne,ge,Ne):oa)){Or=!1;break}mn||(mn=er=="constructor")}if(Or&&!mn){var as=O.constructor,ar=k.constructor;as!=ar&&"constructor"in O&&"constructor"in k&&!(typeof as=="function"&&as instanceof as&&typeof ar=="function"&&ar instanceof ar)&&(Or=!1)}return Ne.delete(O),Ne.delete(k),Or}function Js(O){return na(O,$f,Mc)}function _i(O,k){var ne=O.__data__;return jc(k)?ne[typeof k=="string"?"string":"hash"]:ne.map}function Gr(O,k){var ne=Oe(O,k);return If(ne)?ne:void 0}function Lc(O){var k=$e.call(O,Cr),ne=O[Cr];try{O[Cr]=void 0;var ge=!0}catch{}var vt=et.call(O);return ge&&(k?O[Cr]=ne:delete O[Cr]),vt}var Mc=Wn?function(O){return O==null?[]:(O=Object(O),Ke(Wn(O),function(k){return Ur.call(O,k)}))}:mt,$n=is;(Lt&&$n(new Lt(new ArrayBuffer(1)))!=se||Ot&&$n(new Ot)!=P||Mt&&$n(Mt.resolve())!=T||Ut&&$n(new Ut)!=E||Tt&&$n(new Tt)!=F)&&($n=function(O){var k=is(O),ne=k==A?O.constructor:void 0,ge=ne?Vn(ne):"";if(ge)switch(ge){case Gt:return se;case Yt:return P;case jt:return T;case Jt:return E;case Ft:return F}return k});function Uc(O,k){return k=k??c,!!k&&(typeof O=="number"||xe.test(O))&&O>-1&&O%1==0&&O<k}function jc(O){var k=typeof O;return k=="string"||k=="number"||k=="symbol"||k=="boolean"?O!=="__proto__":O===null}function Fc(O){return!!Ze&&Ze in O}function Bc(O){var k=O&&O.constructor,ne=typeof k=="function"&&k.prototype||Se;return O===ne}function Sf(O){return et.call(O)}function Vn(O){if(O!=null){try{return Ve.call(O)}catch{}try{return O+""}catch{}}return""}function kc(O,k){return O===k||O!==O&&k!==k}var qc=ia(function(){return arguments}())?ia:function(O){return os(O)&&$e.call(O,"callee")&&!Ur.call(O,"callee")},Zs=Array.isArray;function Cf(O){return O!=null&&zc(O.length)&&!Qs(O)}var sa=bi||gt;function Of(O,k){return ss(O,k)}function Qs(O){if(!Hc(O))return!1;var k=is(O);return k==x||k==S||k==h||k==C}function zc(O){return typeof O=="number"&&O>-1&&O%1==0&&O<=c}function Hc(O){var k=typeof O;return O!=null&&(k=="object"||k=="function")}function os(O){return O!=null&&typeof O=="object"}var Wc=Ce?Ct(Ce):Tc;function $f(O){return Cf(O)?Ac(O):Rc(O)}function mt(){return[]}function gt(){return!1}r.exports=Of})(Ru,Ru.exports);var rE=Ru.exports;function nE(r,e){return e=e||{},new Promise(function(t,n){var i=new XMLHttpRequest,a=[],c=[],u={},f=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:f,headers:{keys:function(){return a},entries:function(){return c},get:function(m){return u[m.toLowerCase()]},has:function(m){return m.toLowerCase()in u}}}};for(var h in i.open(e.method||"get",r,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(m,w,y){a.push(w=w.toLowerCase()),c.push([w,y]),u[w]=u[w]?u[w]+","+y:y}),t(f())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(h,e.headers[h]);i.send(e.body||null)})}var iE=Object.freeze({__proto__:null,default:nE}),Qp=Pi(iE),sE=self.fetch||(self.fetch=Qp.default||Qp),oE=Object.defineProperty,Xp=Object.getOwnPropertySymbols,aE=Object.prototype.hasOwnProperty,cE=Object.prototype.propertyIsEnumerable,e1=(r,e,t)=>e in r?oE(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,xr=(r,e)=>{for(var t in e||(e={}))aE.call(e,t)&&e1(r,t,e[t]);if(Xp)for(var t of Xp(e))cE.call(e,t)&&e1(r,t,e[t]);return r};function lE(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<r.length;i++){var a=r.charAt(i),c=a.charCodeAt(0);if(t[c]!==255)throw new TypeError(a+" is ambiguous");t[c]=i}var u=r.length,f=r.charAt(0),h=Math.log(u)/Math.log(256),m=Math.log(256)/Math.log(u);function w(S){if(S instanceof Uint8Array||(ArrayBuffer.isView(S)?S=new Uint8Array(S.buffer,S.byteOffset,S.byteLength):Array.isArray(S)&&(S=Uint8Array.from(S))),!(S instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(S.length===0)return"";for(var P=0,U=0,j=0,A=S.length;j!==A&&S[j]===0;)j++,P++;for(var T=(A-j)*m+1>>>0,C=new Uint8Array(T);j!==A;){for(var $=S[j],E=0,d=T-1;($!==0||E<U)&&d!==-1;d--,E++)$+=256*C[d]>>>0,C[d]=$%u>>>0,$=$/u>>>0;if($!==0)throw new Error("Non-zero carry");U=E,j++}for(var b=T-U;b!==T&&C[b]===0;)b++;for(var H=f.repeat(P);b<T;++b)H+=r.charAt(C[b]);return H}function y(S){if(typeof S!="string")throw new TypeError("Expected String");if(S.length===0)return new Uint8Array;var P=0;if(S[P]!==" "){for(var U=0,j=0;S[P]===f;)U++,P++;for(var A=(S.length-P)*h+1>>>0,T=new Uint8Array(A);S[P];){var C=t[S.charCodeAt(P)];if(C===255)return;for(var $=0,E=A-1;(C!==0||$<j)&&E!==-1;E--,$++)C+=u*T[E]>>>0,T[E]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");j=$,P++}if(S[P]!==" "){for(var d=A-j;d!==A&&T[d]===0;)d++;for(var b=new Uint8Array(U+(A-d)),H=U;d!==A;)b[H++]=T[d++];return b}}}function x(S){var P=y(S);if(P)return P;throw new Error(`Non-${e} character`)}return{encode:w,decodeUnsafe:y,decode:x}}var uE=lE,hE=uE;const t1=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},fE=r=>new TextEncoder().encode(r),dE=r=>new TextDecoder().decode(r);class pE{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class gE{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.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 r1(this,e)}}class mE{constructor(e){this.decoders=e}or(e){return r1(this,e)}decode(e){const t=e[0],n=this.decoders[t];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 r1=(r,e)=>new mE(xr(xr({},r.decoders||{[r.prefix]:r}),e.decoders||{[e.prefix]:e}));class vE{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new pE(e,t,n),this.decoder=new gE(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ka=({name:r,prefix:e,encode:t,decode:n})=>new vE(r,e,t,n),To=({prefix:r,name:e,alphabet:t})=>{const{encode:n,decode:i}=hE(t,e);return Ka({prefix:r,name:e,encode:n,decode:a=>t1(i(a))})},yE=(r,e,t,n)=>{const i={};for(let m=0;m<e.length;++m)i[e[m]]=m;let a=r.length;for(;r[a-1]==="=";)--a;const c=new Uint8Array(a*t/8|0);let u=0,f=0,h=0;for(let m=0;m<a;++m){const w=i[r[m]];if(w===void 0)throw new SyntaxError(`Non-${n} character`);f=f<<t|w,u+=t,u>=8&&(u-=8,c[h++]=255&f>>u)}if(u>=t||255&f<<8-u)throw new SyntaxError("Unexpected end of data");return c},wE=(r,e,t)=>{const n=e[e.length-1]==="=",i=(1<<t)-1;let a="",c=0,u=0;for(let f=0;f<r.length;++f)for(u=u<<8|r[f],c+=8;c>t;)c-=t,a+=e[i&u>>c];if(c&&(a+=e[i&u<<t-c]),n)for(;a.length*t&7;)a+="=";return a},hr=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>Ka({prefix:e,name:r,encode(i){return wE(i,n,t)},decode(i){return yE(i,n,t,r)}}),bE=Ka({prefix:"\0",name:"identity",encode:r=>dE(r),decode:r=>fE(r)});var _E=Object.freeze({__proto__:null,identity:bE});const EE=hr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var xE=Object.freeze({__proto__:null,base2:EE});const IE=hr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var DE=Object.freeze({__proto__:null,base8:IE});const SE=To({prefix:"9",name:"base10",alphabet:"0123456789"});var CE=Object.freeze({__proto__:null,base10:SE});const OE=hr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),$E=hr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var AE=Object.freeze({__proto__:null,base16:OE,base16upper:$E});const PE=hr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),TE=hr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),RE=hr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),NE=hr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),LE=hr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ME=hr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),UE=hr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),jE=hr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),FE=hr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var BE=Object.freeze({__proto__:null,base32:PE,base32upper:TE,base32pad:RE,base32padupper:NE,base32hex:LE,base32hexupper:ME,base32hexpad:UE,base32hexpadupper:jE,base32z:FE});const kE=To({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),qE=To({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var zE=Object.freeze({__proto__:null,base36:kE,base36upper:qE});const HE=To({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),WE=To({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var KE=Object.freeze({__proto__:null,base58btc:HE,base58flickr:WE});const VE=hr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),GE=hr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),YE=hr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),JE=hr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ZE=Object.freeze({__proto__:null,base64:VE,base64pad:GE,base64url:YE,base64urlpad:JE});const n1=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}"),QE=n1.reduce((r,e,t)=>(r[t]=e,r),[]),XE=n1.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function e4(r){return r.reduce((e,t)=>(e+=QE[t],e),"")}function t4(r){const e=[];for(const t of r){const n=XE[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}const r4=Ka({prefix:"\u{1F680}",name:"base256emoji",encode:e4,decode:t4});var n4=Object.freeze({__proto__:null,base256emoji:r4}),i4=s1,i1=128,s4=127,o4=~s4,a4=Math.pow(2,31);function s1(r,e,t){e=e||[],t=t||0;for(var n=t;r>=a4;)e[t++]=r&255|i1,r/=128;for(;r&o4;)e[t++]=r&255|i1,r>>>=7;return e[t]=r|0,s1.bytes=t-n+1,e}var c4=Nu,l4=128,o1=127;function Nu(r,n){var t=0,n=n||0,i=0,a=n,c,u=r.length;do{if(a>=u)throw Nu.bytes=0,new RangeError("Could not decode varint");c=r[a++],t+=i<28?(c&o1)<<i:(c&o1)*Math.pow(2,i),i+=7}while(c>=l4);return Nu.bytes=a-n,t}var u4=Math.pow(2,7),h4=Math.pow(2,14),f4=Math.pow(2,21),d4=Math.pow(2,28),p4=Math.pow(2,35),g4=Math.pow(2,42),m4=Math.pow(2,49),v4=Math.pow(2,56),y4=Math.pow(2,63),w4=function(r){return r<u4?1:r<h4?2:r<f4?3:r<d4?4:r<p4?5:r<g4?6:r<m4?7:r<v4?8:r<y4?9:10},b4={encode:i4,decode:c4,encodingLength:w4},a1=b4;const c1=(r,e,t=0)=>(a1.encode(r,e,t),e),l1=r=>a1.encodingLength(r),Lu=(r,e)=>{const t=e.byteLength,n=l1(r),i=n+l1(t),a=new Uint8Array(i+t);return c1(r,a,0),c1(t,a,n),a.set(e,i),new _4(r,t,e,a)};class _4{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}}const u1=({name:r,code:e,encode:t})=>new E4(r,e,t);class E4{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Lu(this.code,t):t.then(n=>Lu(this.code,n))}else throw Error("Unknown type, must be binary type")}}const h1=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),x4=u1({name:"sha2-256",code:18,encode:h1("SHA-256")}),I4=u1({name:"sha2-512",code:19,encode:h1("SHA-512")});var D4=Object.freeze({__proto__:null,sha256:x4,sha512:I4});const f1=0,S4="identity",d1=t1;var C4=Object.freeze({__proto__:null,identity:{code:f1,name:S4,encode:d1,digest:r=>Lu(f1,d1(r))}});new TextEncoder,new TextDecoder;const p1=xr(xr(xr(xr(xr(xr(xr(xr(xr(xr({},_E),xE),DE),CE),AE),BE),zE),KE),ZE),n4);xr(xr({},D4),C4);function g1(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function O4(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?g1(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function m1(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}const v1=m1("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Mu=m1("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);const e=O4(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),$4=xr({utf8:v1,"utf-8":v1,hex:p1.base16,latin1:Mu,ascii:Mu,binary:Mu},p1);function A4(r,e="utf8"){const t=$4[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?g1(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}const y1="wc",P4=2,Uu="core",si=`${y1}@2:${Uu}:`,T4={name:Uu,logger:"error"},R4={database:":memory:"},N4="crypto",w1="client_ed25519_seed",L4=ye.ONE_DAY,M4="keychain",U4="0.3",j4="messages",F4="0.3",B4=ye.SIX_HOURS,k4="publisher",b1="irn",q4="error",_1="wss://relay.walletconnect.com",E1="wss://relay.walletconnect.org",z4="relayer",pr={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"},H4="_subscription",jn={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},W4=ye.ONE_SECOND,K4="2.11.1",V4=1e4,G4="0.3",Y4="WALLETCONNECT_CLIENT_ID",pn={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},J4="subscription",Z4="0.3",Q4=ye.FIVE_SECONDS*1e3,X4="pairing",e8="0.3",Ro={wc_pairingDelete:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:ye.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:ye.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:0},res:{ttl:ye.ONE_DAY,prompt:!1,tag:0}}},No={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},xn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},t8="history",r8="0.3",n8="expirer",en={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},i8="0.3",ju="verify-api",Cs="https://verify.walletconnect.com",Fu="https://verify.walletconnect.org",s8=[Cs,Fu],o8="echo",a8="https://echo.walletconnect.com";class c8{constructor(e,t){this.core=e,this.logger=t,this.keychain=new Map,this.name=M4,this.version=U4,this.initialized=!1,this.storagePrefix=si,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:a}=ue("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(a)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=Xe.generateChildLogger(t,this.name)}get context(){return Xe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Z0(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Q0(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}}class l8{constructor(e,t,n){this.core=e,this.logger=t,this.name=N4,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(),a=Mp(i);return Lp(a.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const i=X2();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const a=await this.getClientSeed(),c=Mp(a),u=su();return await d6(u,i,L4,c)},this.generateSharedKey=(i,a,c)=>{this.isInitialized();const u=this.getPrivateKey(i),f=e_(u,a);return this.setSymKey(f,c)},this.setSymKey=async(i,a)=>{this.isInitialized();const c=a||t_(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,a,c)=>{this.isInitialized();const u=K0(c),f=ji(a);if(V0(u)){const y=u.senderPublicKey,x=u.receiverPublicKey;i=await this.generateSharedKey(y,x)}const h=this.getSymKey(i),{type:m,senderPublicKey:w}=u;return n_({type:m,symKey:h,message:f,senderPublicKey:w})},this.decode=async(i,a,c)=>{this.isInitialized();const u=o_(a,c);if(V0(u)){const f=u.receiverPublicKey,h=u.senderPublicKey;i=await this.generateSharedKey(f,h)}try{const f=this.getSymKey(i),h=i_({symKey:f,encoded:a});return Do(h)}catch(f){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(f)}},this.getPayloadType=i=>{const a=Ra(i);return wo(a.type)},this.getPayloadSenderPublicKey=i=>{const a=Ra(i);return a.senderPublicKey?wr(a.senderPublicKey,br):void 0},this.core=e,this.logger=Xe.generateChildLogger(t,this.name),this.keychain=n||new c8(this.core,this.logger)}get context(){return Xe.getLoggerContext(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(w1)}catch{e=su(),await this.keychain.set(w1,e)}return A4(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}}class u8 extends H5{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.name=j4,this.version=F4,this.initialized=!1,this.storagePrefix=si,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 a=bs(i);let c=this.messages.get(n);return typeof c>"u"&&(c={}),typeof c[a]<"u"||(c[a]=i,this.messages.set(n,c),await this.persist()),a},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();const a=this.get(n),c=bs(i);return typeof a[c]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=Xe.generateChildLogger(e,this.name),this.core=t}get context(){return Xe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Z0(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Q0(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}}class h8 extends W5{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new lr.exports.EventEmitter,this.name=k4,this.queue=new Map,this.publishTimeout=ye.toMiliseconds(ye.TEN_SECONDS*2),this.needsTransportRestart=!1,this.publish=async(n,i,a)=>{var c;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:a}});try{const u=a?.ttl||B4,f=cu(a),h=a?.prompt||!1,m=a?.tag||0,w=a?.id||Wp().toString(),y={topic:n,message:i,opts:{ttl:u,relay:f,prompt:h,tag:m,id:w}},x=setTimeout(()=>this.queue.set(w,y),this.publishTimeout);try{await await _o(this.rpcPublish(n,i,u,f,h,m,w),this.publishTimeout,`Failed to publish payload, please try again. id:${w} tag:${m}`),this.removeRequestFromQueue(w),this.relayer.events.emit(pr.publish,y)}catch(S){if(this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0,(c=a?.internal)!=null&&c.throwOnFailedPublish)throw this.removeRequestFromQueue(w),S;return}finally{clearTimeout(x)}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:a}})}catch(u){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(u),u}},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=Xe.generateChildLogger(t,this.name),this.registerEventListeners()}get context(){return Xe.getLoggerContext(this.logger)}rpcPublish(e,t,n,i,a,c,u){var f,h,m,w;const y={method:Na(i.protocol).publish,params:{topic:e,message:t,ttl:n,prompt:a,tag:c},id:u};return _r((f=y.params)==null?void 0:f.prompt)&&((h=y.params)==null||delete h.prompt),_r((m=y.params)==null?void 0:m.tag)&&((w=y.params)==null||delete w.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:y}),this.relayer.request(y)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:t,message:n,opts:i}=e;await this.publish(t,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(Ds.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(pr.connection_stalled);return}this.checkQueue()}),this.relayer.on(pr.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class f8{constructor(){this.map=new Map,this.set=(e,t)=>{const n=this.get(e);this.exists(e,t)||this.map.set(e,[...n,t])},this.get=e=>this.map.get(e)||[],this.exists=(e,t)=>this.get(e).includes(t),this.delete=(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,t))return;const i=n.filter(a=>a!==t);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 d8=Object.defineProperty,p8=Object.defineProperties,g8=Object.getOwnPropertyDescriptors,x1=Object.getOwnPropertySymbols,m8=Object.prototype.hasOwnProperty,v8=Object.prototype.propertyIsEnumerable,I1=(r,e,t)=>e in r?d8(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Lo=(r,e)=>{for(var t in e||(e={}))m8.call(e,t)&&I1(r,t,e[t]);if(x1)for(var t of x1(e))v8.call(e,t)&&I1(r,t,e[t]);return r},Bu=(r,e)=>p8(r,g8(e));class y8 extends G5{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new f8,this.events=new lr.exports.EventEmitter,this.name=J4,this.version=Z4,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=si,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),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 a=cu(i),c={topic:n,relay:a};this.pending.set(n,c);const u=await this.rpcSubscribe(n,a);return this.onSubscribe(u,c),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}}),u}catch(a){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(a),a}},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=>{if(this.topics.includes(n))return!0;const i=`${this.pendingSubscriptionWatchLabel}_${n}`;return await new Promise((a,c)=>{const u=new ye.Watch;u.start(i);const f=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(f),u.stop(i),a(!0)),u.elapsed(i)>=Q4&&(clearInterval(f),u.stop(i),c(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=Xe.generateChildLogger(t,this.name),this.clientId=""}get context(){return Xe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+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,t){let n=!1;try{n=this.getSubscription(e).topic===t}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,t)))}async unsubscribeById(e,t,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:n}});try{const i=cu(n);await this.rpcUnsubscribe(e,t,i);const a=It("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,a),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,t){const n={method:Na(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await _o(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(pr.connection_stalled)}return bs(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,n={method:Na(t.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 _o(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(pr.connection_stalled)}}rpcUnsubscribe(e,t,n){const i={method:Na(n.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,t){this.setSubscription(e,Bu(Lo({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,Lo({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,n){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,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,t){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t))}addSubscription(e,t){this.subscriptions.set(e,Lo({},t)),this.topicMap.set(t.topic,e),this.events.emit(pn.created,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:n}=ue("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(pn.deleted,Bu(Lo({},n),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(pn.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let t=0;t<e;t++){const n=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}}this.events.emit(pn.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=ue("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}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 t=await this.rpcBatchSubscribe(e);En(t)&&this.onBatchSubscribe(t.map((n,i)=>Bu(Lo({},e[i]),{id:n})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach(t=>{e.push(t)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(Ds.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(pr.connect,async()=>{await this.onConnect()}),this.relayer.on(pr.disconnect,()=>{this.onDisconnect()}),this.events.on(pn.created,async e=>{const t=pn.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}),this.events.on(pn.deleted,async e=>{const t=pn.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{const t=setInterval(()=>{this.restartInProgress||(clearInterval(t),e())},this.pollingInterval)})}}var w8=Object.defineProperty,D1=Object.getOwnPropertySymbols,b8=Object.prototype.hasOwnProperty,_8=Object.prototype.propertyIsEnumerable,S1=(r,e,t)=>e in r?w8(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,E8=(r,e)=>{for(var t in e||(e={}))b8.call(e,t)&&S1(r,t,e[t]);if(D1)for(var t of D1(e))_8.call(e,t)&&S1(r,t,e[t]);return r};class x8 extends K5{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new lr.exports.EventEmitter,this.name=z4,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.request=async t=>{this.logger.debug("Publishing Request Payload");const n=t.id,i=this.provider.request(t);this.requestsInFlight.set(n,{promise:i,request:t});try{return await this.toEstablishConnection(),await i}catch(a){throw this.logger.debug("Failed to Publish Request"),this.logger.error(a),a}finally{this.requestsInFlight.delete(n)}},this.onPayloadHandler=t=>{this.onProviderPayload(t)},this.onConnectHandler=()=>{this.events.emit(pr.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=t=>{this.logger.error(t),this.events.emit(pr.error,t),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(jn.payload,this.onPayloadHandler),this.provider.on(jn.connect,this.onConnectHandler),this.provider.on(jn.disconnect,this.onDisconnectHandler),this.provider.on(jn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Xe.generateChildLogger(e.logger,this.name):Xe.pino(Xe.getDefaultLoggerOptions({level:e.logger||q4})),this.messages=new u8(this.logger,e.core),this.subscriber=new y8(this,this.logger),this.publisher=new h8(this,this.logger),this.relayUrl=e?.relayUrl||_1,this.projectId=e.projectId,this.bundleId=f_(),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),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 ${E1}...`),await this.restartTransport(E1)}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)},V4)}get context(){return Xe.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,t,n){this.isInitialized(),await this.publisher.publish(e,t,n),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now()})}async subscribe(e,t){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"";if(i)return i;let a;const c=u=>{u.topic===e&&(this.subscriber.off(pn.created,c),a())};return await Promise.all([new Promise(u=>{a=u,this.subscriber.on(pn.created,c)}),new Promise(async u=>{i=await this.subscriber.subscribe(e,t),u()})]),i}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportClose(){this.requestsInFlight.size>0&&(this.logger.debug("Waiting for all in-flight requests to finish before closing transport..."),this.requestsInFlight.forEach(async e=>{await e.promise})),this.transportExplicitlyClosed=!0,this.hasExperiencedNetworkDisruption&&this.connected?await _o(this.provider.disconnect(),1e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.connected&&await this.provider.disconnect()}async transportOpen(e){if(this.transportExplicitlyClosed=!1,await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress){e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportClose(),await this.createProvider()),this.connectionAttemptInProgress=!0;try{await Promise.all([new Promise(t=>{if(!this.initialized)return t();this.subscriber.once(pn.resubscribed,()=>{t()})}),new Promise(async(t,n)=>{try{await _o(this.provider.connect(),1e4,`Socket stalled when trying to connect to ${this.relayUrl}`)}catch(i){n(i);return}t()})])}catch(t){this.logger.error(t);const n=t;if(!this.isConnectionStalled(n.message))throw t;this.provider.events.emit(jn.disconnect)}finally{this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1}}}async restartTransport(e){await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await up())throw new Error("No internet connection detected. Please restart your network and try again.")}isConnectionStalled(e){return this.staleConnectionErrors.some(t=>e.includes(t))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Un(new tE(y_({sdkVersion:K4,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:t,message:n}=e;await this.messages.set(t,n)}async shouldIgnoreMessageEvent(e){const{topic:t,message:n}=e;if(!n||n.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.debug(`Ignoring message for non-subscribed topic ${t}`),!0;const i=this.messages.has(t,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}),Tu(e)){if(!e.method.endsWith(H4))return;const t=e.params,{topic:n,message:i,publishedAt:a}=t.data,c={topic:n,message:i,publishedAt:a};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(E8({type:"event",event:t.id},c)),this.events.emit(t.id,c),await this.acknowledgePayload(e),await this.onMessageEvent(c)}else Wa(e)&&this.events.emit(pr.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(pr.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=za(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(jn.payload,this.onPayloadHandler),this.provider.off(jn.connect,this.onConnectHandler),this.provider.off(jn.disconnect,this.onDisconnectHandler),this.provider.off(jn.error,this.onProviderErrorHandler)}async registerEventListeners(){this.events.on(pr.connection_stalled,()=>{this.restartTransport().catch(t=>this.logger.error(t))});let e=await up();f3(async t=>{this.initialized&&e!==t&&(e=t,t?await this.restartTransport().catch(n=>this.logger.error(n)):(this.hasExperiencedNetworkDisruption=!0,await this.transportClose().catch(n=>this.logger.error(n))))})}onProviderDisconnect(){this.events.emit(pr.disconnect),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||(this.logger.info("attemptToReconnect called. Connecting..."),setTimeout(async()=>{await this.restartTransport().catch(e=>this.logger.error(e))},ye.toMiliseconds(W4)))}isInitialized(){if(!this.initialized){const{message:e}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectionAttemptInProgress)return await new Promise(e=>{const t=setInterval(()=>{this.connected&&(clearInterval(t),e())},this.connectionStatusPollingInterval)});await this.restartTransport()}}}var I8=Object.defineProperty,C1=Object.getOwnPropertySymbols,D8=Object.prototype.hasOwnProperty,S8=Object.prototype.propertyIsEnumerable,O1=(r,e,t)=>e in r?I8(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,$1=(r,e)=>{for(var t in e||(e={}))D8.call(e,t)&&O1(r,t,e[t]);if(C1)for(var t of C1(e))S8.call(e,t)&&O1(r,t,e[t]);return r};class Va extends V5{constructor(e,t,n,i=si,a=void 0){super(e,t,n,i),this.core=e,this.logger=t,this.name=n,this.map=new Map,this.version=G4,this.cached=[],this.initialized=!1,this.storagePrefix=si,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(c=>{this.getKey&&c!==null&&!_r(c)?this.map.set(this.getKey(c),c):z_(c)?this.map.set(c.id,c):H_(c)&&this.map.set(c.topic,c)}),this.cached=[],this.initialized=!0)},this.set=async(c,u)=>{this.isInitialized(),this.map.has(c)?await this.update(c,u):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:c,value:u}),this.map.set(c,u),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(u=>Object.keys(c).every(f=>rE(u[f],c[f]))):this.values),this.update=async(c,u)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:c,update:u});const f=$1($1({},this.getData(c)),u);this.map.set(c,f),await this.persist()},this.delete=async(c,u)=>{this.isInitialized(),this.map.has(c)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:c,reason:u}),this.map.delete(c),await this.persist())},this.logger=Xe.generateChildLogger(t,this.name),this.storagePrefix=i,this.getKey=a}get context(){return Xe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+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 t=this.map.get(e);if(!t){const{message:n}=ue("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return t}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:t}=ue("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}}class C8{constructor(e,t){this.core=e,this.logger=t,this.name=X4,this.version=e8,this.events=new lr.exports,this.initialized=!1,this.storagePrefix=si,this.ignoredPayloadTypes=[Li],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=su(),i=await this.core.crypto.setSymKey(n),a=Wr(ye.FIVE_MINUTES),c={protocol:b1},u={topic:i,expiry:a,relay:c,active:!1},f=N_({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:n,relay:c,expiryTimestamp:a});return await this.pairings.set(i,u),await this.core.relayer.subscribe(i),this.core.expirer.set(i,a),{topic:i,uri:f}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);const{topic:i,symKey:a,relay:c,expiryTimestamp:u}=np(n.uri);let f;if(this.pairings.keys.includes(i)&&(f=this.pairings.get(i),f.active))throw new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);const h=u||Wr(ye.FIVE_MINUTES),m={topic:i,relay:c,expiry:h,active:!1};return await this.pairings.set(i,m),this.core.expirer.set(i,h),n.activatePairing&&await this.activate({topic:i}),this.events.emit(No.create,m),this.core.crypto.keychain.has(i)||(await this.core.crypto.setSymKey(a,i),await this.core.relayer.subscribe(i,{relay:c})),m},this.activate=async({topic:n})=>{this.isInitialized();const i=Wr(ye.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 a=await this.sendRequest(i,"wc_pairingPing",{}),{done:c,resolve:u,reject:f}=xs();this.events.once(qt("pairing_ping",a),({error:h})=>{h?f(h):u()}),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",It("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,a)=>{const c=Ss(i,a),u=await this.core.crypto.encode(n,c),f=Ro[i].req;return this.core.history.set(n,c),this.core.relayer.publish(n,u,f),c.id},this.sendResult=async(n,i,a)=>{const c=za(n,a),u=await this.core.crypto.encode(i,c),f=await this.core.history.get(i,n),h=Ro[f.request.method].res;await this.core.relayer.publish(i,u,h),await this.core.history.resolve(c)},this.sendError=async(n,i,a)=>{const c=Ha(n,a),u=await this.core.crypto.encode(i,c),f=await this.core.history.get(i,n),h=Ro[f.request.method]?Ro[f.request.method].res:Ro.unregistered_method.res;await this.core.relayer.publish(i,u,h),await this.core.history.resolve(c)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,It("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=>ii(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{const{topic:i,payload:a}=n;switch(a.method){case"wc_pairingPing":return this.onPairingPingRequest(i,a);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,a);default:return this.onUnknownRpcMethodRequest(i,a)}},this.onRelayEventResponse=async n=>{const{topic:i,payload:a}=n,c=(await this.core.history.get(i,a.id)).request.method;switch(c){case"wc_pairingPing":return this.onPairingPingResponse(i,a);default:return this.onUnknownRpcMethodResponse(c)}},this.onPairingPingRequest=async(n,i)=>{const{id:a}=i;try{this.isValidPing({topic:n}),await this.sendResult(a,n,!0),this.events.emit(No.ping,{id:a,topic:n})}catch(c){await this.sendError(a,n,c),this.logger.error(c)}},this.onPairingPingResponse=(n,i)=>{const{id:a}=i;setTimeout(()=>{Mn(i)?this.events.emit(qt("pairing_ping",a),{}):dn(i)&&this.events.emit(qt("pairing_ping",a),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{const{id:a}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(No.delete,{id:a,topic:n})}catch(c){await this.sendError(a,n,c),this.logger.error(c)}},this.onUnknownRpcMethodRequest=async(n,i)=>{const{id:a,method:c}=i;try{if(this.registeredMethods.includes(c))return;const u=It("WC_METHOD_UNSUPPORTED",c);await this.sendError(a,n,u),this.logger.error(u)}catch(u){await this.sendError(a,n,u),this.logger.error(u)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(It("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{var i;if(!Rr(n)){const{message:c}=ue("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(c)}if(!q_(n.uri)){const{message:c}=ue("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(c)}const a=np(n.uri);if(!((i=a?.relay)!=null&&i.protocol)){const{message:c}=ue("MISSING_OR_INVALID","pair() uri#relay-protocol");throw new Error(c)}if(!(a!=null&&a.symKey)){const{message:c}=ue("MISSING_OR_INVALID","pair() uri#symKey");throw new Error(c)}if(a!=null&&a.expiryTimestamp&&ye.toMiliseconds(a?.expiryTimestamp)<Date.now()){const{message:c}=ue("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(c)}},this.isValidPing=async n=>{if(!Rr(n)){const{message:a}=ue("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(a)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!Rr(n)){const{message:a}=ue("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(a)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!ir(n,!1)){const{message:i}=ue("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=ue("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(ii(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=ue("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=Xe.generateChildLogger(t,this.name),this.pairings=new Va(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Xe.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(pr.message,async e=>{const{topic:t,message:n}=e;if(!this.pairings.keys.includes(t)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;const i=await this.core.crypto.decode(t,n);try{Tu(i)?(this.core.history.set(t,i),this.onRelayEventRequest({topic:t,payload:i})):Wa(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:t,payload:i}),this.core.history.delete(t,i.id))}catch(a){this.logger.error(a)}})}registerExpirerEvents(){this.core.expirer.on(en.expired,async e=>{const{topic:t}=ep(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(No.expire,{topic:t}))})}}class O8 extends z5{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new lr.exports.EventEmitter,this.name=t8,this.version=r8,this.cached=[],this.initialized=!1,this.storagePrefix=si,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,a)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:a}),this.records.has(i.id))return;const c={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:a,expiry:Wr(ye.THIRTY_DAYS)};this.records.set(c.id,c),this.events.emit(xn.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=dn(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.events.emit(xn.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(a=>{if(a.topic===n){if(typeof i<"u"&&a.id!==i)return;this.records.delete(a.id),this.events.emit(xn.deleted,a)}})},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=Xe.generateChildLogger(t,this.name)}get context(){return Xe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+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(t=>{if(typeof t.response<"u")return;const n={topic:t.topic,request:Ss(t.request.method,t.request.params,t.id),chainId:t.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 t=this.records.get(e);if(!t){const{message:n}=ue("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(xn.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=ue("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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(xn.created,e=>{const t=xn.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()}),this.events.on(xn.updated,e=>{const t=xn.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()}),this.events.on(xn.deleted,e=>{const t=xn.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()}),this.core.heartbeat.on(Ds.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.records.forEach(e=>{ye.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}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}}class $8 extends Y5{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new lr.exports.EventEmitter,this.name=n8,this.version=i8,this.cached=[],this.initialized=!1,this.storagePrefix=si,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 a=this.formatTarget(n),c={target:a,expiry:i};this.expirations.set(a,c),this.checkExpiry(a,c),this.events.emit(en.created,{target:a,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),a=this.getExpiration(i);this.expirations.delete(i),this.events.emit(en.deleted,{target:i,expiration:a})}},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=Xe.generateChildLogger(t,this.name)}get context(){return Xe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+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 w_(e);if(typeof e=="number")return b_(e);const{message:t}=ue("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(t)}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(en.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=ue("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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 t=this.expirations.get(e);if(!t){const{message:n}=ue("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return t}checkExpiry(e,t){const{expiry:n}=t;ye.toMiliseconds(n)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(en.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(Ds.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(en.created,e=>{const t=en.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(en.expired,e=>{const t=en.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(en.deleted,e=>{const t=en.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}}class A8 extends J5{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.name=ju,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async n=>{if(this.verifyDisabled||_s()||!Es())return;const i=this.getVerifyUrl(n?.verifyUrl);this.verifyUrl!==i&&this.removeIframe(),this.verifyUrl=i;try{await this.createIframe()}catch(a){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(a)}if(!this.initialized){this.removeIframe(),this.verifyUrl=Fu;try{await this.createIframe()}catch(a){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(a),this.verifyDisabled=!0}}},this.register=async n=>{this.initialized?this.sendPost(n.attestationId):(this.addToQueue(n.attestationId),await this.init())},this.resolve=async n=>{if(this.isDevEnv)return"";const i=this.getVerifyUrl(n?.verifyUrl);let a;try{a=await this.fetchAttestation(n.attestationId,i)}catch(c){this.logger.info(`failed to resolve attestation: ${n.attestationId} from url: ${i}`),this.logger.info(c),a=await this.fetchAttestation(n.attestationId,Fu)}return a},this.fetchAttestation=async(n,i)=>{this.logger.info(`resolving attestation: ${n} from url: ${i}`);const a=this.startAbortTimer(ye.ONE_SECOND*2),c=await fetch(`${i}/attestation/${n}`,{signal:this.abortController.signal});return clearTimeout(a),c.status===200?await c.json():void 0},this.addToQueue=n=>{this.queue.push(n)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(n=>this.sendPost(n)),this.queue=[])},this.sendPost=n=>{var i;try{if(!this.iframe)return;(i=this.iframe.contentWindow)==null||i.postMessage(n,"*"),this.logger.info(`postMessage sent: ${n} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let n;const i=a=>{a.data==="verify_ready"&&(this.initialized=!0,this.processQueue(),window.removeEventListener("message",i),n())};await Promise.race([new Promise(a=>{if(document.getElementById(ju))return a();window.addEventListener("message",i);const c=document.createElement("iframe");c.id=ju,c.src=`${this.verifyUrl}/${this.projectId}`,c.style.display="none",document.body.append(c),this.iframe=c,n=a}),new Promise((a,c)=>setTimeout(()=>{window.removeEventListener("message",i),c("verify iframe load timeout")},ye.toMiliseconds(ye.FIVE_SECONDS)))])},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.getVerifyUrl=n=>{let i=n||Cs;return s8.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${Cs}`),i=Cs),i},this.logger=Xe.generateChildLogger(t,this.name),this.verifyUrl=Cs,this.abortController=new AbortController,this.isDevEnv=ou()&&process.env.IS_VITEST}get context(){return Xe.getLoggerContext(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),ye.toMiliseconds(e))}}class P8 extends Z5{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.context=o8,this.registerDeviceToken=async n=>{const{clientId:i,token:a,notificationType:c,enableEncrypted:u=!1}=n,f=`${a8}/${this.projectId}/clients`;await sE(f,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:c,token:a,always_raw:u})})},this.logger=Xe.generateChildLogger(t,this.context)}}var T8=Object.defineProperty,A1=Object.getOwnPropertySymbols,R8=Object.prototype.hasOwnProperty,N8=Object.prototype.propertyIsEnumerable,P1=(r,e,t)=>e in r?T8(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,T1=(r,e)=>{for(var t in e||(e={}))R8.call(e,t)&&P1(r,t,e[t]);if(A1)for(var t of A1(e))N8.call(e,t)&&P1(r,t,e[t]);return r};class ku extends q5{constructor(e){super(e),this.protocol=y1,this.version=P4,this.name=Uu,this.events=new lr.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||_1,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Xe.pino(Xe.getDefaultLoggerOptions({level:e?.logger||T4.logger}));this.logger=Xe.generateChildLogger(t,this.name),this.heartbeat=new Ds.HeartBeat,this.crypto=new l8(this,this.logger,e?.keychain),this.history=new O8(this,this.logger),this.expirer=new $8(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new K3(T1(T1({},R4),e?.storageOptions)),this.relayer=new x8({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new C8(this,this.logger),this.verify=new A8(this.projectId||"",this.logger),this.echoClient=new P8(this.projectId||"",this.logger)}static async init(e){const t=new ku(e);await t.initialize();const n=await t.crypto.getClientId();return await t.storage.setItem(Y4,n),t}get context(){return Xe.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 L8=ku,R1="wc",N1=2,L1="client",qu=`${R1}@${N1}:${L1}:`,zu={name:L1,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},M1="WALLETCONNECT_DEEPLINK_CHOICE",M8="proposal",U1="Proposal expired",U8="session",Ga=ye.SEVEN_DAYS,j8="engine",Fn={wc_sessionPropose:{req:{ttl:ye.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1104},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1106},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:ye.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:ye.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1112},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:ye.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:ye.THIRTY_SECONDS,prompt:!1,tag:1115}}},Hu={min:ye.FIVE_MINUTES,max:ye.SEVEN_DAYS},Bn={idle:"IDLE",active:"ACTIVE"},F8="request",B8=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var k8=Object.defineProperty,q8=Object.defineProperties,z8=Object.getOwnPropertyDescriptors,j1=Object.getOwnPropertySymbols,H8=Object.prototype.hasOwnProperty,W8=Object.prototype.propertyIsEnumerable,F1=(r,e,t)=>e in r?k8(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ir=(r,e)=>{for(var t in e||(e={}))H8.call(e,t)&&F1(r,t,e[t]);if(j1)for(var t of j1(e))W8.call(e,t)&&F1(r,t,e[t]);return r},Os=(r,e)=>q8(r,z8(e));class K8 extends X5{constructor(e){super(e),this.name=j8,this.events=new lr.exports,this.initialized=!1,this.ignoredPayloadTypes=[Li],this.requestQueue={state:Bn.idle,queue:[]},this.sessionRequestQueue={state:Bn.idle,queue:[]},this.requestQueueDelay=ye.ONE_SECOND,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(Fn)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},ye.toMiliseconds(this.requestQueueDelay)))},this.connect=async t=>{await this.isInitialized();const n=Os(Ir({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:a,optionalNamespaces:c,sessionProperties:u,relays:f}=n;let h=i,m,w=!1;if(h&&(w=this.client.core.pairing.pairings.get(h).active),!h||!w){const{topic:C,uri:$}=await this.client.core.pairing.create();h=C,m=$}const y=await this.client.core.crypto.generateKeyPair(),x=Fn.wc_sessionPropose.req.ttl||ye.FIVE_MINUTES,S=Wr(x),P=Ir({requiredNamespaces:a,optionalNamespaces:c,relays:f??[{protocol:b1}],proposer:{publicKey:y,metadata:this.client.metadata},expiryTimestamp:S},u&&{sessionProperties:u}),{reject:U,resolve:j,done:A}=xs(x,U1);if(this.events.once(qt("session_connect"),async({error:C,session:$})=>{if(C)U(C);else if($){$.self.publicKey=y;const E=Os(Ir({},$),{requiredNamespaces:P.requiredNamespaces,optionalNamespaces:P.optionalNamespaces});await this.client.session.set($.topic,E),await this.setExpiry($.topic,$.expiry),h&&await this.client.core.pairing.updateMetadata({topic:h,metadata:$.peer.metadata}),j(E)}}),!h){const{message:C}=ue("NO_MATCHING_KEY",`connect() pairing topic: ${h}`);throw new Error(C)}const T=await this.sendRequest({topic:h,method:"wc_sessionPropose",params:P,throwOnFailedPublish:!0});return await this.setProposal(T,Ir({id:T},P)),{uri:m,approval:A}},this.pair=async t=>(await this.isInitialized(),await this.client.core.pairing.pair(t)),this.approve=async t=>{await this.isInitialized(),await this.isValidApprove(t);const{id:n,relayProtocol:i,namespaces:a,sessionProperties:c}=t,u=this.client.proposal.get(n);let{pairingTopic:f,proposer:h,requiredNamespaces:m,optionalNamespaces:w}=u;f=f||"";const y=await this.client.core.crypto.generateKeyPair(),x=h.publicKey,S=await this.client.core.crypto.generateSharedKey(y,x);f&&n&&(await this.client.core.pairing.updateMetadata({topic:f,metadata:h.metadata}),await this.sendResult({id:n,topic:f,result:{relay:{protocol:i??"irn"},responderPublicKey:y}}),await this.client.proposal.delete(n,It("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:f}));const P=Ir({relay:{protocol:i??"irn"},namespaces:a,pairingTopic:f,controller:{publicKey:y,metadata:this.client.metadata},expiry:Wr(Ga)},c&&{sessionProperties:c});await this.client.core.relayer.subscribe(S);const U=Os(Ir({},P),{topic:S,requiredNamespaces:m,optionalNamespaces:w,pairingTopic:f,acknowledged:!1,self:P.controller,peer:{publicKey:h.publicKey,metadata:h.metadata},controller:y});await this.client.session.set(S,U);try{await this.sendRequest({topic:S,method:"wc_sessionSettle",params:P,throwOnFailedPublish:!0})}catch(j){throw this.client.logger.error(j),this.client.session.delete(S,It("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(S),j}return await this.setExpiry(S,Wr(Ga)),{topic:S,acknowledged:()=>new Promise(j=>setTimeout(()=>j(this.client.session.get(S)),500))}},this.reject=async t=>{await this.isInitialized(),await this.isValidReject(t);const{id:n,reason:i}=t,{pairingTopic:a}=this.client.proposal.get(n);a&&(await this.sendError(n,a,i),await this.client.proposal.delete(n,It("USER_DISCONNECTED")))},this.update=async t=>{await this.isInitialized(),await this.isValidUpdate(t);const{topic:n,namespaces:i}=t,a=await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i}}),{done:c,resolve:u,reject:f}=xs();return this.events.once(qt("session_update",a),({error:h})=>{h?f(h):u()}),await this.client.session.update(n,{namespaces:i}),{acknowledged:c}},this.extend=async t=>{await this.isInitialized(),await this.isValidExtend(t);const{topic:n}=t,i=await this.sendRequest({topic:n,method:"wc_sessionExtend",params:{}}),{done:a,resolve:c,reject:u}=xs();return this.events.once(qt("session_extend",i),({error:f})=>{f?u(f):c()}),await this.setExpiry(n,Wr(Ga)),{acknowledged:a}},this.request=async t=>{await this.isInitialized(),await this.isValidRequest(t);const{chainId:n,request:i,topic:a,expiry:c=Fn.wc_sessionRequest.req.ttl}=t,u=Pu(),{done:f,resolve:h,reject:m}=xs(c,"Request expired. Please try again.");return this.events.once(qt("session_request",u),({error:w,result:y})=>{w?m(w):h(y)}),await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:u,topic:a,method:"wc_sessionRequest",params:{request:Os(Ir({},i),{expiryTimestamp:Wr(c)}),chainId:n},expiry:c,throwOnFailedPublish:!0}).catch(y=>m(y)),this.client.events.emit("session_request_sent",{topic:a,request:i,chainId:n,id:u}),w()}),new Promise(async w=>{const y=await E_(this.client.core.storage,M1);__({id:u,topic:a,wcDeepLink:y}),w()}),f()]).then(w=>w[2])},this.respond=async t=>{await this.isInitialized(),await this.isValidRespond(t);const{topic:n,response:i}=t,{id:a}=i;Mn(i)?await this.sendResult({id:a,topic:n,result:i.result,throwOnFailedPublish:!0}):dn(i)&&await this.sendError(a,n,i.error),this.cleanupAfterResponse(t)},this.ping=async t=>{await this.isInitialized(),await this.isValidPing(t);const{topic:n}=t;if(this.client.session.keys.includes(n)){const i=await this.sendRequest({topic:n,method:"wc_sessionPing",params:{}}),{done:a,resolve:c,reject:u}=xs();this.events.once(qt("session_ping",i),({error:f})=>{f?u(f):c()}),await a()}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async t=>{await this.isInitialized(),await this.isValidEmit(t);const{topic:n,event:i,chainId:a}=t;await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:a}})},this.disconnect=async t=>{await this.isInitialized(),await this.isValidDisconnect(t);const{topic:n}=t;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:It("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{const{message:i}=ue("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}},this.find=t=>(this.isInitialized(),this.client.session.getAll().filter(n=>B_(n,t))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.cleanupDuplicatePairings=async t=>{if(t.pairingTopic)try{const n=this.client.core.pairing.pairings.get(t.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(a=>{var c,u;return((c=a.peerMetadata)==null?void 0:c.url)&&((u=a.peerMetadata)==null?void 0:u.url)===t.peer.metadata.url&&a.topic&&a.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(a=>this.client.core.pairing.disconnect({topic:a.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async t=>{const{topic:n,expirerHasDeleted:i=!1,emitEvent:a=!0,id:c=0}=t,{self:u}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,It("USER_DISCONNECTED")),this.client.core.crypto.keychain.has(u.publicKey)&&await this.client.core.crypto.deleteKeyPair(u.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),i||this.client.core.expirer.del(n),this.client.core.storage.removeItem(M1).catch(f=>this.client.logger.warn(f)),this.getPendingSessionRequests().forEach(f=>{f.topic===n&&this.deletePendingSessionRequest(f.id,It("USER_DISCONNECTED"))}),a&&this.client.events.emit("session_delete",{id:c,topic:n})},this.deleteProposal=async(t,n)=>{await Promise.all([this.client.proposal.delete(t,It("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(t)])},this.deletePendingSessionRequest=async(t,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,n),i?Promise.resolve():this.client.core.expirer.del(t)]),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(a=>a.id!==t),i&&(this.sessionRequestQueue.state=Bn.idle,this.client.events.emit("session_request_expire",{id:t}))},this.setExpiry=async(t,n)=>{this.client.session.keys.includes(t)&&await this.client.session.update(t,{expiry:n}),this.client.core.expirer.set(t,n)},this.setProposal=async(t,n)=>{await this.client.proposal.set(t,n),this.client.core.expirer.set(t,Wr(Fn.wc_sessionPropose.req.ttl))},this.setPendingSessionRequest=async t=>{const{id:n,topic:i,params:a,verifyContext:c}=t,u=a.request.expiryTimestamp||Wr(Fn.wc_sessionRequest.req.ttl);await this.client.pendingRequest.set(n,{id:n,topic:i,params:a,verifyContext:c}),u&&this.client.core.expirer.set(n,u)},this.sendRequest=async t=>{const{topic:n,method:i,params:a,expiry:c,relayRpcId:u,clientRpcId:f,throwOnFailedPublish:h}=t,m=Ss(i,a,f);if(Es()&&B8.includes(i)){const x=bs(JSON.stringify(m));this.client.core.verify.register({attestationId:x})}const w=await this.client.core.crypto.encode(n,m),y=Fn[i].req;return c&&(y.ttl=c),u&&(y.id=u),this.client.core.history.set(n,m),h?(y.internal=Os(Ir({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,w,y)):this.client.core.relayer.publish(n,w,y).catch(x=>this.client.logger.error(x)),m.id},this.sendResult=async t=>{const{id:n,topic:i,result:a,throwOnFailedPublish:c}=t,u=za(n,a),f=await this.client.core.crypto.encode(i,u),h=await this.client.core.history.get(i,n),m=Fn[h.request.method].res;c?(m.internal=Os(Ir({},m.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,f,m)):this.client.core.relayer.publish(i,f,m).catch(w=>this.client.logger.error(w)),await this.client.core.history.resolve(u)},this.sendError=async(t,n,i)=>{const a=Ha(t,i),c=await this.client.core.crypto.encode(n,a),u=await this.client.core.history.get(n,t),f=Fn[u.request.method].res;this.client.core.relayer.publish(n,c,f),await this.client.core.history.resolve(a)},this.cleanup=async()=>{const t=[],n=[];this.client.session.getAll().forEach(i=>{let a=!1;ii(i.expiry)&&(a=!0),this.client.core.crypto.keychain.has(i.topic)||(a=!0),a&&t.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{ii(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...t.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===Bn.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Bn.active;const t=this.requestQueue.queue.shift();if(t)try{this.processRequest(t),await new Promise(n=>setTimeout(n,300))}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Bn.idle},this.processRequest=t=>{const{topic:n,payload:i}=t,a=i.method;switch(a){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 ${a}`)}},this.onRelayEventResponse=async t=>{const{topic:n,payload:i}=t,a=(await this.client.core.history.get(n,i.id)).request.method;switch(a){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 ${a}`)}},this.onRelayEventUnknownPayload=t=>{const{topic:n}=t,{message:i}=ue("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(t,n)=>{const{params:i,id:a}=n;try{this.isValidConnect(Ir({},n.params));const c=i.expiryTimestamp||Wr(Fn.wc_sessionPropose.req.ttl),u=Ir({id:a,pairingTopic:t,expiryTimestamp:c},i);await this.setProposal(a,u);const f=bs(JSON.stringify(n)),h=await this.getVerifyContext(f,u.proposer.metadata);this.client.events.emit("session_proposal",{id:a,params:u,verifyContext:h})}catch(c){await this.sendError(a,t,c),this.client.logger.error(c)}},this.onSessionProposeResponse=async(t,n)=>{const{id:i}=n;if(Mn(n)){const{result:a}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:a});const c=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:c});const u=c.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:u});const f=a.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:f});const h=await this.client.core.crypto.generateSharedKey(u,f);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:h});const m=await this.client.core.relayer.subscribe(h);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:m}),await this.client.core.pairing.activate({topic:t})}else dn(n)&&(await this.client.proposal.delete(i,It("USER_DISCONNECTED")),this.events.emit(qt("session_connect"),{error:n.error}))},this.onSessionSettleRequest=async(t,n)=>{const{id:i,params:a}=n;try{this.isValidSessionSettleRequest(a);const{relay:c,controller:u,expiry:f,namespaces:h,sessionProperties:m,pairingTopic:w}=n.params,y=Ir({topic:t,relay:c,expiry:f,namespaces:h,acknowledged:!0,pairingTopic:w,requiredNamespaces:{},optionalNamespaces:{},controller:u.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:u.publicKey,metadata:u.metadata}},m&&{sessionProperties:m});await this.sendResult({id:n.id,topic:t,result:!0}),this.events.emit(qt("session_connect"),{session:y}),this.cleanupDuplicatePairings(y)}catch(c){await this.sendError(i,t,c),this.client.logger.error(c)}},this.onSessionSettleResponse=async(t,n)=>{const{id:i}=n;Mn(n)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(qt("session_approve",i),{})):dn(n)&&(await this.client.session.delete(t,It("USER_DISCONNECTED")),this.events.emit(qt("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(t,n)=>{const{params:i,id:a}=n;try{const c=`${t}_session_update`,u=Ma.get(c);if(u&&this.isRequestOutOfSync(u,a)){this.client.logger.info(`Discarding out of sync request - ${a}`);return}this.isValidUpdate(Ir({topic:t},i)),await this.client.session.update(t,{namespaces:i.namespaces}),await this.sendResult({id:a,topic:t,result:!0}),this.client.events.emit("session_update",{id:a,topic:t,params:i}),Ma.set(c,a)}catch(c){await this.sendError(a,t,c),this.client.logger.error(c)}},this.isRequestOutOfSync=(t,n)=>parseInt(n.toString().slice(0,-3))<=parseInt(t.toString().slice(0,-3)),this.onSessionUpdateResponse=(t,n)=>{const{id:i}=n;Mn(n)?this.events.emit(qt("session_update",i),{}):dn(n)&&this.events.emit(qt("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(t,n)=>{const{id:i}=n;try{this.isValidExtend({topic:t}),await this.setExpiry(t,Wr(Ga)),await this.sendResult({id:i,topic:t,result:!0}),this.client.events.emit("session_extend",{id:i,topic:t})}catch(a){await this.sendError(i,t,a),this.client.logger.error(a)}},this.onSessionExtendResponse=(t,n)=>{const{id:i}=n;Mn(n)?this.events.emit(qt("session_extend",i),{}):dn(n)&&this.events.emit(qt("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(t,n)=>{const{id:i}=n;try{this.isValidPing({topic:t}),await this.sendResult({id:i,topic:t,result:!0}),this.client.events.emit("session_ping",{id:i,topic:t})}catch(a){await this.sendError(i,t,a),this.client.logger.error(a)}},this.onSessionPingResponse=(t,n)=>{const{id:i}=n;setTimeout(()=>{Mn(n)?this.events.emit(qt("session_ping",i),{}):dn(n)&&this.events.emit(qt("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(t,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:t,reason:n.params}),await Promise.all([new Promise(a=>{this.client.core.relayer.once(pr.publish,async()=>{a(await this.deleteSession({topic:t,id:i}))})}),this.sendResult({id:i,topic:t,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:It("USER_DISCONNECTED")})])}catch(a){this.client.logger.error(a)}},this.onSessionRequest=async(t,n)=>{const{id:i,params:a}=n;try{this.isValidRequest(Ir({topic:t},a));const c=bs(JSON.stringify(Ss("wc_sessionRequest",a,i))),u=this.client.session.get(t),f=await this.getVerifyContext(c,u.peer.metadata),h={id:i,topic:t,params:a,verifyContext:f};await this.setPendingSessionRequest(h),this.addSessionRequestToSessionRequestQueue(h),this.processSessionRequestQueue()}catch(c){await this.sendError(i,t,c),this.client.logger.error(c)}},this.onSessionRequestResponse=(t,n)=>{const{id:i}=n;Mn(n)?this.events.emit(qt("session_request",i),{result:n.result}):dn(n)&&this.events.emit(qt("session_request",i),{error:n.error})},this.onSessionEventRequest=async(t,n)=>{const{id:i,params:a}=n;try{const c=`${t}_session_event_${a.event.name}`,u=Ma.get(c);if(u&&this.isRequestOutOfSync(u,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(Ir({topic:t},a)),this.client.events.emit("session_event",{id:i,topic:t,params:a}),Ma.set(c,i)}catch(c){await this.sendError(i,t,c),this.client.logger.error(c)}},this.addSessionRequestToSessionRequestQueue=t=>{this.sessionRequestQueue.queue.push(t)},this.cleanupAfterResponse=t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Bn.idle,this.processSessionRequestQueue()},ye.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:t,error:n})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(a=>a.topic===t&&a.request.method==="wc_sessionRequest").forEach(a=>{this.events.emit(qt("session_request",a.request.id),{error:n})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===Bn.active){this.client.logger.info("session request queue is already active.");return}const t=this.sessionRequestQueue.queue[0];if(!t){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Bn.active,this.client.events.emit("session_request",t)}catch(n){this.client.logger.error(n)}},this.onPairingCreated=t=>{if(t.active)return;const n=this.client.proposal.getAll().find(i=>i.pairingTopic===t.topic);n&&this.onSessionProposeRequest(t.topic,Ss("wc_sessionPropose",{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties},n.id))},this.isValidConnect=async t=>{if(!Rr(t)){const{message:f}=ue("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(f)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:a,sessionProperties:c,relays:u}=t;if(_r(n)||await this.isValidPairingTopic(n),!Q_(u,!0)){const{message:f}=ue("MISSING_OR_INVALID",`connect() relays: ${u}`);throw new Error(f)}!_r(i)&&xo(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!_r(a)&&xo(a)!==0&&this.validateNamespaces(a,"optionalNamespaces"),_r(c)||this.validateSessionProps(c,"sessionProperties")},this.validateNamespaces=(t,n)=>{const i=Z_(t,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async t=>{if(!Rr(t))throw new Error(ue("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:n,namespaces:i,relayProtocol:a,sessionProperties:c}=t;await this.isValidProposalId(n);const u=this.client.proposal.get(n),f=hu(i,"approve()");if(f)throw new Error(f.message);const h=cp(u.requiredNamespaces,i,"approve()");if(h)throw new Error(h.message);if(!ir(a,!0)){const{message:m}=ue("MISSING_OR_INVALID",`approve() relayProtocol: ${a}`);throw new Error(m)}_r(c)||this.validateSessionProps(c,"sessionProperties")},this.isValidReject=async t=>{if(!Rr(t)){const{message:a}=ue("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(a)}const{id:n,reason:i}=t;if(await this.isValidProposalId(n),!e3(i)){const{message:a}=ue("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(a)}},this.isValidSessionSettleRequest=t=>{if(!Rr(t)){const{message:h}=ue("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(h)}const{relay:n,controller:i,namespaces:a,expiry:c}=t;if(!op(n)){const{message:h}=ue("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const u=W_(i,"onSessionSettleRequest()");if(u)throw new Error(u.message);const f=hu(a,"onSessionSettleRequest()");if(f)throw new Error(f.message);if(ii(c)){const{message:h}=ue("EXPIRED","onSessionSettleRequest()");throw new Error(h)}},this.isValidUpdate=async t=>{if(!Rr(t)){const{message:f}=ue("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(f)}const{topic:n,namespaces:i}=t;await this.isValidSessionTopic(n);const a=this.client.session.get(n),c=hu(i,"update()");if(c)throw new Error(c.message);const u=cp(a.requiredNamespaces,i,"update()");if(u)throw new Error(u.message)},this.isValidExtend=async t=>{if(!Rr(t)){const{message:i}=ue("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(i)}const{topic:n}=t;await this.isValidSessionTopic(n)},this.isValidRequest=async t=>{if(!Rr(t)){const{message:f}=ue("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(f)}const{topic:n,request:i,chainId:a,expiry:c}=t;await this.isValidSessionTopic(n);const{namespaces:u}=this.client.session.get(n);if(!ap(u,a)){const{message:f}=ue("MISSING_OR_INVALID",`request() chainId: ${a}`);throw new Error(f)}if(!t3(i)){const{message:f}=ue("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(f)}if(!i3(u,a,i.method)){const{message:f}=ue("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(f)}if(c&&!c3(c,Hu)){const{message:f}=ue("MISSING_OR_INVALID",`request() expiry: ${c}. Expiry must be a number (in seconds) between ${Hu.min} and ${Hu.max}`);throw new Error(f)}},this.isValidRespond=async t=>{var n;if(!Rr(t)){const{message:c}=ue("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(c)}const{topic:i,response:a}=t;try{await this.isValidSessionTopic(i)}catch(c){throw(n=t?.response)!=null&&n.id&&this.cleanupAfterResponse(t),c}if(!r3(a)){const{message:c}=ue("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(a)}`);throw new Error(c)}},this.isValidPing=async t=>{if(!Rr(t)){const{message:i}=ue("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(i)}const{topic:n}=t;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async t=>{if(!Rr(t)){const{message:u}=ue("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(u)}const{topic:n,event:i,chainId:a}=t;await this.isValidSessionTopic(n);const{namespaces:c}=this.client.session.get(n);if(!ap(c,a)){const{message:u}=ue("MISSING_OR_INVALID",`emit() chainId: ${a}`);throw new Error(u)}if(!n3(i)){const{message:u}=ue("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(u)}if(!s3(c,a,i.name)){const{message:u}=ue("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(u)}},this.isValidDisconnect=async t=>{if(!Rr(t)){const{message:i}=ue("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(i)}const{topic:n}=t;await this.isValidSessionOrPairingTopic(n)},this.getVerifyContext=async(t,n)=>{const i={verified:{verifyUrl:n.verifyUrl||Cs,validation:"UNKNOWN",origin:n.url||""}};try{const a=await this.client.core.verify.resolve({attestationId:t,verifyUrl:n.verifyUrl});a&&(i.verified.origin=a.origin,i.verified.isScam=a.isScam,i.verified.validation=a.origin===new URL(n.url).origin?"VALID":"INVALID")}catch(a){this.client.logger.info(a)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(t,n)=>{Object.values(t).forEach(i=>{if(!ir(i,!1)){const{message:a}=ue("MISSING_OR_INVALID",`${n} must be in Record<string, string> format. Received: ${JSON.stringify(i)}`);throw new Error(a)}})}}async isInitialized(){if(!this.initialized){const{message:e}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(pr.message,async e=>{const{topic:t,message:n}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(n)))return;const i=await this.client.core.crypto.decode(t,n);try{Tu(i)?(this.client.core.history.set(t,i),this.onRelayEventRequest({topic:t,payload:i})):Wa(i)?(await this.client.core.history.resolve(i),await this.onRelayEventResponse({topic:t,payload:i}),this.client.core.history.delete(t,i.id)):this.onRelayEventUnknownPayload({topic:t,payload:i})}catch(a){this.client.logger.error(a)}})}registerExpirerEvents(){this.client.core.expirer.on(en.expired,async e=>{const{topic:t,id:n}=ep(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,ue("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(No.create,e=>this.onPairingCreated(e))}isValidPairingTopic(e){if(!ir(e,!1)){const{message:t}=ue("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=ue("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(ii(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=ue("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!ir(e,!1)){const{message:t}=ue("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(!this.client.session.keys.includes(e)){const{message:t}=ue("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(ii(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=ue("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=ue("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}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(ir(e,!1)){const{message:t}=ue("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=ue("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!X_(e)){const{message:t}=ue("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=ue("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(ii(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=ue("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class V8 extends Va{constructor(e,t){super(e,t,M8,qu),this.core=e,this.logger=t}}class G8 extends Va{constructor(e,t){super(e,t,U8,qu),this.core=e,this.logger=t}}class Y8 extends Va{constructor(e,t){super(e,t,F8,qu,n=>n.id),this.core=e,this.logger=t}}class Wu extends Q5{constructor(e){super(e),this.protocol=R1,this.version=N1,this.name=zu.name,this.events=new lr.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||zu.name,this.metadata=e?.metadata||p_();const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Xe.pino(Xe.getDefaultLoggerOptions({level:e?.logger||zu.logger}));this.core=e?.core||new L8(e),this.logger=Xe.generateChildLogger(t,this.name),this.session=new G8(this.core,this.logger),this.proposal=new V8(this.core,this.logger),this.pendingRequest=new Y8(this.core,this.logger),this.engine=new K8(this)}static async init(e){const t=new Wu(e);return await t.initialize(),t}get context(){return Xe.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 Ku={exports:{}};(function(r,e){var t=typeof self<"u"?self:yr,n=function(){function a(){this.fetch=!1,this.DOMException=t.DOMException}return a.prototype=t,new a}();(function(a){(function(c){var u={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function f(I){return I&&DataView.prototype.isPrototypeOf(I)}if(u.arrayBuffer)var h=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],m=ArrayBuffer.isView||function(I){return I&&h.indexOf(Object.prototype.toString.call(I))>-1};function w(I){if(typeof I!="string"&&(I=String(I)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(I))throw new TypeError("Invalid character in header field name");return I.toLowerCase()}function y(I){return typeof I!="string"&&(I=String(I)),I}function x(I){var N={next:function(){var X=I.shift();return{done:X===void 0,value:X}}};return u.iterable&&(N[Symbol.iterator]=function(){return N}),N}function S(I){this.map={},I instanceof S?I.forEach(function(N,X){this.append(X,N)},this):Array.isArray(I)?I.forEach(function(N){this.append(N[0],N[1])},this):I&&Object.getOwnPropertyNames(I).forEach(function(N){this.append(N,I[N])},this)}S.prototype.append=function(I,N){I=w(I),N=y(N);var X=this.map[I];this.map[I]=X?X+", "+N:N},S.prototype.delete=function(I){delete this.map[w(I)]},S.prototype.get=function(I){return I=w(I),this.has(I)?this.map[I]:null},S.prototype.has=function(I){return this.map.hasOwnProperty(w(I))},S.prototype.set=function(I,N){this.map[w(I)]=y(N)},S.prototype.forEach=function(I,N){for(var X in this.map)this.map.hasOwnProperty(X)&&I.call(N,this.map[X],X,this)},S.prototype.keys=function(){var I=[];return this.forEach(function(N,X){I.push(X)}),x(I)},S.prototype.values=function(){var I=[];return this.forEach(function(N){I.push(N)}),x(I)},S.prototype.entries=function(){var I=[];return this.forEach(function(N,X){I.push([X,N])}),x(I)},u.iterable&&(S.prototype[Symbol.iterator]=S.prototype.entries);function P(I){if(I.bodyUsed)return Promise.reject(new TypeError("Already read"));I.bodyUsed=!0}function U(I){return new Promise(function(N,X){I.onload=function(){N(I.result)},I.onerror=function(){X(I.error)}})}function j(I){var N=new FileReader,X=U(N);return N.readAsArrayBuffer(I),X}function A(I){var N=new FileReader,X=U(N);return N.readAsText(I),X}function T(I){for(var N=new Uint8Array(I),X=new Array(N.length),ee=0;ee<N.length;ee++)X[ee]=String.fromCharCode(N[ee]);return X.join("")}function C(I){if(I.slice)return I.slice(0);var N=new Uint8Array(I.byteLength);return N.set(new Uint8Array(I)),N.buffer}function $(){return this.bodyUsed=!1,this._initBody=function(I){this._bodyInit=I,I?typeof I=="string"?this._bodyText=I:u.blob&&Blob.prototype.isPrototypeOf(I)?this._bodyBlob=I:u.formData&&FormData.prototype.isPrototypeOf(I)?this._bodyFormData=I:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(I)?this._bodyText=I.toString():u.arrayBuffer&&u.blob&&f(I)?(this._bodyArrayBuffer=C(I.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(I)||m(I))?this._bodyArrayBuffer=C(I):this._bodyText=I=Object.prototype.toString.call(I):this._bodyText="",this.headers.get("content-type")||(typeof I=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(I)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var I=P(this);if(I)return I;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?P(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(j)}),this.text=function(){var I=P(this);if(I)return I;if(this._bodyBlob)return A(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(T(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(H)}),this.json=function(){return this.text().then(JSON.parse)},this}var E=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function d(I){var N=I.toUpperCase();return E.indexOf(N)>-1?N:I}function b(I,N){N=N||{};var X=N.body;if(I instanceof b){if(I.bodyUsed)throw new TypeError("Already read");this.url=I.url,this.credentials=I.credentials,N.headers||(this.headers=new S(I.headers)),this.method=I.method,this.mode=I.mode,this.signal=I.signal,!X&&I._bodyInit!=null&&(X=I._bodyInit,I.bodyUsed=!0)}else this.url=String(I);if(this.credentials=N.credentials||this.credentials||"same-origin",(N.headers||!this.headers)&&(this.headers=new S(N.headers)),this.method=d(N.method||this.method||"GET"),this.mode=N.mode||this.mode||null,this.signal=N.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&X)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(X)}b.prototype.clone=function(){return new b(this,{body:this._bodyInit})};function H(I){var N=new FormData;return I.trim().split("&").forEach(function(X){if(X){var ee=X.split("="),Y=ee.shift().replace(/\+/g," "),J=ee.join("=").replace(/\+/g," ");N.append(decodeURIComponent(Y),decodeURIComponent(J))}}),N}function F(I){var N=new S,X=I.replace(/\r?\n[\t ]+/g," ");return X.split(/\r?\n/).forEach(function(ee){var Y=ee.split(":"),J=Y.shift().trim();if(J){var Q=Y.join(":").trim();N.append(J,Q)}}),N}$.call(b.prototype);function V(I,N){N||(N={}),this.type="default",this.status=N.status===void 0?200:N.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in N?N.statusText:"OK",this.headers=new S(N.headers),this.url=N.url||"",this._initBody(I)}$.call(V.prototype),V.prototype.clone=function(){return new V(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new S(this.headers),url:this.url})},V.error=function(){var I=new V(null,{status:0,statusText:""});return I.type="error",I};var se=[301,302,303,307,308];V.redirect=function(I,N){if(se.indexOf(N)===-1)throw new RangeError("Invalid status code");return new V(null,{status:N,headers:{location:I}})},c.DOMException=a.DOMException;try{new c.DOMException}catch{c.DOMException=function(N,X){this.message=N,this.name=X;var ee=Error(N);this.stack=ee.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function ce(I,N){return new Promise(function(X,ee){var Y=new b(I,N);if(Y.signal&&Y.signal.aborted)return ee(new c.DOMException("Aborted","AbortError"));var J=new XMLHttpRequest;function Q(){J.abort()}J.onload=function(){var ie={status:J.status,statusText:J.statusText,headers:F(J.getAllResponseHeaders()||"")};ie.url="responseURL"in J?J.responseURL:ie.headers.get("X-Request-URL");var Ee="response"in J?J.response:J.responseText;X(new V(Ee,ie))},J.onerror=function(){ee(new TypeError("Network request failed"))},J.ontimeout=function(){ee(new TypeError("Network request failed"))},J.onabort=function(){ee(new c.DOMException("Aborted","AbortError"))},J.open(Y.method,Y.url,!0),Y.credentials==="include"?J.withCredentials=!0:Y.credentials==="omit"&&(J.withCredentials=!1),"responseType"in J&&u.blob&&(J.responseType="blob"),Y.headers.forEach(function(ie,Ee){J.setRequestHeader(Ee,ie)}),Y.signal&&(Y.signal.addEventListener("abort",Q),J.onreadystatechange=function(){J.readyState===4&&Y.signal.removeEventListener("abort",Q)}),J.send(typeof Y._bodyInit>"u"?null:Y._bodyInit)})}return ce.polyfill=!0,a.fetch||(a.fetch=ce,a.Headers=S,a.Request=b,a.Response=V),c.Headers=S,c.Request=b,c.Response=V,c.fetch=ce,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,r.exports=e})(Ku,Ku.exports);var B1=Oy(Ku.exports);const k1={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},q1=10;class oi{constructor(e,t=!1){if(this.url=e,this.disableProviderPing=t,this.events=new lr.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!Vp(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=t}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}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,t){this.isAvailable||await this.register();try{const n=ji(e),a=await(await B1(this.url,Object.assign(Object.assign({},k1),{body:n}))).json();this.onPayload({data:a})}catch(n){this.onError(e.id,n)}}async register(e=this.url){if(!Vp(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((n,i)=>{this.events.once("register_error",a=>{this.resetMaxListeners(),i(a)}),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 t=ji({id:1,jsonrpc:"2.0",method:"test",params:[]});await B1(e,Object.assign(Object.assign({},k1),{body:t}))}this.onOpen()}catch(t){const n=this.parseError(t);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 t=typeof e.data=="string"?Do(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const n=this.parseError(t),i=n.message||n.toString(),a=Ha(e,i);this.events.emit("payload",a)}parseError(e,t=this.url){return Bp(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>q1&&this.events.setMaxListeners(q1)}}const z1="error",J8="wss://relay.walletconnect.com",Z8="wc",Q8="universal_provider",H1=`${Z8}@2:${Q8}:`,X8="https://rpc.walletconnect.com/v1/",kn={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Mo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Vu={exports:{}};/**
|
|
59
|
+
***************************************************************************** */var Ou=function(r,e){return Ou=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var i in n)n.hasOwnProperty(i)&&(t[i]=n[i])},Ou(r,e)};function _6(r,e){Ou(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var $u=function(){return $u=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++){t=arguments[n];for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a])}return e},$u.apply(this,arguments)};function E6(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t}function x6(r,e,t,n){var i=arguments.length,a=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,n);else for(var u=r.length-1;u>=0;u--)(c=r[u])&&(a=(i<3?c(a):i>3?c(e,t,a):c(e,t))||a);return i>3&&a&&Object.defineProperty(e,t,a),a}function I6(r,e){return function(t,n){e(t,n,r)}}function D6(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function S6(r,e,t,n){function i(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function u(m){try{h(n.next(m))}catch(w){c(w)}}function f(m){try{h(n.throw(m))}catch(w){c(w)}}function h(m){m.done?a(m.value):i(m.value).then(u,f)}h((n=n.apply(r,e||[])).next())})}function C6(r,e){var t={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},n,i,a,c;return c={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(c[Symbol.iterator]=function(){return this}),c;function u(h){return function(m){return f([h,m])}}function f(h){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,i&&(a=h[0]&2?i.return:h[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,h[1])).done)return a;switch(i=0,a&&(h=[h[0]&2,a.value]),h[0]){case 0:case 1:a=h;break;case 4:return t.label++,{value:h[1],done:!1};case 5:t.label++,i=h[1],h=[0];continue;case 7:h=t.ops.pop(),t.trys.pop();continue;default:if(a=t.trys,!(a=a.length>0&&a[a.length-1])&&(h[0]===6||h[0]===2)){t=0;continue}if(h[0]===3&&(!a||h[1]>a[0]&&h[1]<a[3])){t.label=h[1];break}if(h[0]===6&&t.label<a[1]){t.label=a[1],a=h;break}if(a&&t.label<a[2]){t.label=a[2],t.ops.push(h);break}a[2]&&t.ops.pop(),t.trys.pop();continue}h=e.call(r,t)}catch(m){h=[6,m],i=0}finally{n=a=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}}function O6(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}function $6(r,e){for(var t in r)t!=="default"&&!e.hasOwnProperty(t)&&(e[t]=r[t])}function Au(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function qp(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,a=[],c;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)a.push(i.value)}catch(u){c={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(c)throw c.error}}return a}function A6(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(qp(arguments[e]));return r}function P6(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),i=0,e=0;e<t;e++)for(var a=arguments[e],c=0,u=a.length;c<u;c++,i++)n[i]=a[c];return n}function Po(r){return this instanceof Po?(this.v=r,this):new Po(r)}function T6(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,e||[]),i,a=[];return i={},c("next"),c("throw"),c("return"),i[Symbol.asyncIterator]=function(){return this},i;function c(y){n[y]&&(i[y]=function(x){return new Promise(function(S,P){a.push([y,x,S,P])>1||u(y,x)})})}function u(y,x){try{f(n[y](x))}catch(S){w(a[0][3],S)}}function f(y){y.value instanceof Po?Promise.resolve(y.value.v).then(h,m):w(a[0][2],y)}function h(y){u("next",y)}function m(y){u("throw",y)}function w(y,x){y(x),a.shift(),a.length&&u(a[0][0],a[0][1])}}function R6(r){var e,t;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,a){e[i]=r[i]?function(c){return(t=!t)?{value:Po(r[i](c)),done:i==="return"}:a?a(c):c}:a}}function N6(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof Au=="function"?Au(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(a){t[a]=r[a]&&function(c){return new Promise(function(u,f){c=r[a](c),i(u,f,c.done,c.value)})}}function i(a,c,u,f){Promise.resolve(f).then(function(h){a({value:h,done:u})},c)}}function L6(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function M6(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)Object.hasOwnProperty.call(r,t)&&(e[t]=r[t]);return e.default=r,e}function U6(r){return r&&r.__esModule?r:{default:r}}function j6(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function F6(r,e,t){if(!e.has(r))throw new TypeError("attempted to set private field on non-instance");return e.set(r,t),t}var B6=Object.freeze({__proto__:null,__extends:_6,get __assign(){return $u},__rest:E6,__decorate:x6,__param:I6,__metadata:D6,__awaiter:S6,__generator:C6,__createBinding:O6,__exportStar:$6,__values:Au,__read:qp,__spread:A6,__spreadArrays:P6,__await:Po,__asyncGenerator:T6,__asyncDelegator:R6,__asyncValues:N6,__makeTemplateObject:L6,__importStar:M6,__importDefault:U6,__classPrivateFieldGet:j6,__classPrivateFieldSet:F6}),k6=Pi(B6),Nn={},zp;function q6(){if(zp)return Nn;zp=1,Object.defineProperty(Nn,"__esModule",{value:!0}),Nn.isBrowserCryptoAvailable=Nn.getSubtleCrypto=Nn.getBrowerCrypto=void 0;function r(){return yr?.crypto||yr?.msCrypto||{}}Nn.getBrowerCrypto=r;function e(){const n=r();return n.subtle||n.webkitSubtle}Nn.getSubtleCrypto=e;function t(){return!!r()&&!!e()}return Nn.isBrowserCryptoAvailable=t,Nn}var Ln={},Hp;function z6(){if(Hp)return Ln;Hp=1,Object.defineProperty(Ln,"__esModule",{value:!0}),Ln.isBrowser=Ln.isNode=Ln.isReactNative=void 0;function r(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ln.isReactNative=r;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Ln.isNode=e;function t(){return!r()&&!e()}return Ln.isBrowser=t,Ln}(function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=k6;e.__exportStar(q6(),r),e.__exportStar(z6(),r)})(kp);function Pu(r=3){const e=Date.now()*Math.pow(10,r),t=Math.floor(Math.random()*Math.pow(10,r));return e+t}function Wp(r=6){return BigInt(Pu(r))}function Ss(r,e,t){return{id:t||Pu(),jsonrpc:"2.0",method:r,params:e}}function za(r,e){return{id:r,jsonrpc:"2.0",result:e}}function Ha(r,e,t){return{id:r,jsonrpc:"2.0",error:H6(e,t)}}function H6(r,e){return typeof r>"u"?Fp(Up):(typeof r=="string"&&(r=Object.assign(Object.assign({},Fp(Cu)),{message:r})),typeof e<"u"&&(r.data=e),w6(r.code)&&(r=b6(r.code)),r)}class W6{}class K6 extends W6{constructor(){super()}}class V6 extends K6{constructor(e){super()}}const G6="^https?:",Y6="^wss?:";function J6(r){const e=r.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Kp(r,e){const t=J6(r);return typeof t>"u"?!1:new RegExp(e).test(t)}function Vp(r){return Kp(r,G6)}function Gp(r){return Kp(r,Y6)}function Z6(r){return new RegExp("wss?://localhost(:d{2,5})?").test(r)}function Yp(r){return typeof r=="object"&&"id"in r&&"jsonrpc"in r&&r.jsonrpc==="2.0"}function Tu(r){return Yp(r)&&"method"in r}function Wa(r){return Yp(r)&&(Mn(r)||dn(r))}function Mn(r){return"result"in r}function dn(r){return"error"in r}class Un extends V6{constructor(e){super(e),this.events=new lr.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,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async request(e,t){return this.requestStrict(Ss(e.method,e.params||[],e.id||Wp().toString()),t)}async requestStrict(e,t){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(a){i(a)}this.events.on(`${e.id}`,a=>{dn(a)?i(a.error):n(a.result)});try{await this.connection.send(e,t)}catch(a){i(a)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Wa(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 Q6=()=>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"),X6=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Jp=r=>r.split("?")[0],Zp=10,eE=Q6();class tE{constructor(e){if(this.url=e,this.events=new lr.exports.EventEmitter,this.registering=!1,!Gp(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,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,t)=>{if(typeof this.socket>"u"){t(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ji(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!Gp(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((n,i)=>{this.events.once("register_error",a=>{this.resetMaxListeners(),i(a)}),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((t,n)=>{const i=new URLSearchParams(e).get("origin"),a=kp.isReactNative()?{headers:{origin:i}}:{rejectUnauthorized:!Z6(e)},c=new eE(e,[],a);X6()?c.onerror=u=>{const f=u;n(this.emitError(f.error))}:c.on("error",u=>{n(this.emitError(u))}),c.onopen=()=>{this.onOpen(c),t(c)}})}onOpen(e){e.onmessage=t=>this.onPayload(t),e.onclose=t=>this.onClose(t),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 t=typeof e.data=="string"?Do(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const n=this.parseError(t),i=n.message||n.toString(),a=Ha(e,i);this.events.emit("payload",a)}parseError(e,t=this.url){return Bp(e,Jp(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Zp&&this.events.setMaxListeners(Zp)}emitError(e){const t=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Jp(this.url)}`));return this.events.emit("register_error",t),t}}var Ru={exports:{}};(function(r,e){var t=200,n="__lodash_hash_undefined__",i=1,a=2,c=9007199254740991,u="[object Arguments]",f="[object Array]",h="[object AsyncFunction]",m="[object Boolean]",w="[object Date]",y="[object Error]",x="[object Function]",S="[object GeneratorFunction]",P="[object Map]",U="[object Number]",j="[object Null]",A="[object Object]",T="[object Promise]",C="[object Proxy]",$="[object RegExp]",E="[object Set]",d="[object String]",b="[object Symbol]",H="[object Undefined]",F="[object WeakMap]",V="[object ArrayBuffer]",se="[object DataView]",ce="[object Float32Array]",I="[object Float64Array]",N="[object Int8Array]",X="[object Int16Array]",ee="[object Int32Array]",Y="[object Uint8Array]",J="[object Uint8ClampedArray]",Q="[object Uint16Array]",ie="[object Uint32Array]",Ee=/[\\^$.*+?()[\]{}|]/g,ae=/^\[object .+?Constructor\]$/,xe=/^(?:0|[1-9]\d*)$/,de={};de[ce]=de[I]=de[N]=de[X]=de[ee]=de[Y]=de[J]=de[Q]=de[ie]=!0,de[u]=de[f]=de[V]=de[m]=de[se]=de[w]=de[y]=de[x]=de[P]=de[U]=de[A]=de[$]=de[E]=de[d]=de[F]=!1;var be=typeof yr=="object"&&yr&&yr.Object===Object&&yr,K=typeof self=="object"&&self&&self.Object===Object&&self,W=be||K||Function("return this")(),B=e&&!e.nodeType&&e,g=B&&!0&&r&&!r.nodeType&&r,L=g&&g.exports===B,le=L&&be.process,pe=function(){try{return le&&le.binding&&le.binding("util")}catch{}}(),Ce=pe&&pe.isTypedArray;function Ke(O,k){for(var ne=-1,ge=O==null?0:O.length,vt=0,Ne=[];++ne<ge;){var Et=O[ne];k(Et,ne,O)&&(Ne[vt++]=Et)}return Ne}function Je(O,k){for(var ne=-1,ge=k.length,vt=O.length;++ne<ge;)O[vt+ne]=k[ne];return O}function ke(O,k){for(var ne=-1,ge=O==null?0:O.length;++ne<ge;)if(k(O[ne],ne,O))return!0;return!1}function St(O,k){for(var ne=-1,ge=Array(O);++ne<O;)ge[ne]=k(ne);return ge}function Ct(O){return function(k){return O(k)}}function ze(O,k){return O.has(k)}function Oe(O,k){return O?.[k]}function Ue(O){var k=-1,ne=Array(O.size);return O.forEach(function(ge,vt){ne[++k]=[vt,ge]}),ne}function je(O,k){return function(ne){return O(k(ne))}}function He(O){var k=-1,ne=Array(O.size);return O.forEach(function(ge){ne[++k]=ge}),ne}var Ae=Array.prototype,Fe=Function.prototype,Se=Object.prototype,Te=W["__core-js_shared__"],Ve=Fe.toString,$e=Se.hasOwnProperty,Ze=function(){var O=/[^.]+$/.exec(Te&&Te.keys&&Te.keys.IE_PROTO||"");return O?"Symbol(src)_1."+O:""}(),et=Se.toString,at=RegExp("^"+Ve.call($e).replace(Ee,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ct=L?W.Buffer:void 0,nt=W.Symbol,Sr=W.Uint8Array,Ur=Se.propertyIsEnumerable,On=Ae.splice,Cr=nt?nt.toStringTag:void 0,Wn=Object.getOwnPropertySymbols,bi=ct?ct.isBuffer:void 0,rs=je(Object.keys,Object),Lt=Gr(W,"DataView"),Ot=Gr(W,"Map"),Mt=Gr(W,"Promise"),Ut=Gr(W,"Set"),Tt=Gr(W,"WeakMap"),$t=Gr(Object,"create"),Gt=Vn(Lt),Yt=Vn(Ot),jt=Vn(Mt),Jt=Vn(Ut),Ft=Vn(Tt),Ht=nt?nt.prototype:void 0,Bt=Ht?Ht.valueOf:void 0;function _t(O){var k=-1,ne=O==null?0:O.length;for(this.clear();++k<ne;){var ge=O[k];this.set(ge[0],ge[1])}}function Zt(){this.__data__=$t?$t(null):{},this.size=0}function Qt(O){var k=this.has(O)&&delete this.__data__[O];return this.size-=k?1:0,k}function lf(O){var k=this.__data__;if($t){var ne=k[O];return ne===n?void 0:ne}return $e.call(k,O)?k[O]:void 0}function uf(O){var k=this.__data__;return $t?k[O]!==void 0:$e.call(k,O)}function hf(O,k){var ne=this.__data__;return this.size+=this.has(O)?0:1,ne[O]=$t&&k===void 0?n:k,this}_t.prototype.clear=Zt,_t.prototype.delete=Qt,_t.prototype.get=lf,_t.prototype.has=uf,_t.prototype.set=hf;function rn(O){var k=-1,ne=O==null?0:O.length;for(this.clear();++k<ne;){var ge=O[k];this.set(ge[0],ge[1])}}function ff(){this.__data__=[],this.size=0}function df(O){var k=this.__data__,ne=ns(k,O);if(ne<0)return!1;var ge=k.length-1;return ne==ge?k.pop():On.call(k,ne,1),--this.size,!0}function pf(O){var k=this.__data__,ne=ns(k,O);return ne<0?void 0:k[ne][1]}function gf(O){return ns(this.__data__,O)>-1}function mf(O,k){var ne=this.__data__,ge=ns(ne,O);return ge<0?(++this.size,ne.push([O,k])):ne[ge][1]=k,this}rn.prototype.clear=ff,rn.prototype.delete=df,rn.prototype.get=pf,rn.prototype.has=gf,rn.prototype.set=mf;function Kn(O){var k=-1,ne=O==null?0:O.length;for(this.clear();++k<ne;){var ge=O[k];this.set(ge[0],ge[1])}}function Ks(){this.size=0,this.__data__={hash:new _t,map:new(Ot||rn),string:new _t}}function vf(O){var k=_i(this,O).delete(O);return this.size-=k?1:0,k}function Vs(O){return _i(this,O).get(O)}function yf(O){return _i(this,O).has(O)}function wf(O,k){var ne=_i(this,O),ge=ne.size;return ne.set(O,k),this.size+=ne.size==ge?0:1,this}Kn.prototype.clear=Ks,Kn.prototype.delete=vf,Kn.prototype.get=Vs,Kn.prototype.has=yf,Kn.prototype.set=wf;function Gs(O){var k=-1,ne=O==null?0:O.length;for(this.__data__=new Kn;++k<ne;)this.add(O[k])}function Cc(O){return this.__data__.set(O,n),this}function Oc(O){return this.__data__.has(O)}Gs.prototype.add=Gs.prototype.push=Cc,Gs.prototype.has=Oc;function gn(O){var k=this.__data__=new rn(O);this.size=k.size}function bf(){this.__data__=new rn,this.size=0}function _f(O){var k=this.__data__,ne=k.delete(O);return this.size=k.size,ne}function Ef(O){return this.__data__.get(O)}function xf(O){return this.__data__.has(O)}function $c(O,k){var ne=this.__data__;if(ne instanceof rn){var ge=ne.__data__;if(!Ot||ge.length<t-1)return ge.push([O,k]),this.size=++ne.size,this;ne=this.__data__=new Kn(ge)}return ne.set(O,k),this.size=ne.size,this}gn.prototype.clear=bf,gn.prototype.delete=_f,gn.prototype.get=Ef,gn.prototype.has=xf,gn.prototype.set=$c;function Ac(O,k){var ne=Zs(O),ge=!ne&&qc(O),vt=!ne&&!ge&&sa(O),Ne=!ne&&!ge&&!vt&&Wc(O),Et=ne||ge||vt||Ne,Xt=Et?St(O.length,String):[],it=Xt.length;for(var yt in O)(k||$e.call(O,yt))&&!(Et&&(yt=="length"||vt&&(yt=="offset"||yt=="parent")||Ne&&(yt=="buffer"||yt=="byteLength"||yt=="byteOffset")||Uc(yt,it)))&&Xt.push(yt);return Xt}function ns(O,k){for(var ne=O.length;ne--;)if(kc(O[ne][0],k))return ne;return-1}function na(O,k,ne){var ge=k(O);return Zs(O)?ge:Je(ge,ne(O))}function is(O){return O==null?O===void 0?H:j:Cr&&Cr in Object(O)?Lc(O):Sf(O)}function ia(O){return os(O)&&is(O)==u}function ss(O,k,ne,ge,vt){return O===k?!0:O==null||k==null||!os(O)&&!os(k)?O!==O&&k!==k:Pc(O,k,ne,ge,ss,vt)}function Pc(O,k,ne,ge,vt,Ne){var Et=Zs(O),Xt=Zs(k),it=Et?f:$n(O),yt=Xt?f:$n(k);it=it==u?A:it,yt=yt==u?A:yt;var Wt=it==A,jr=yt==A,er=it==yt;if(er&&sa(O)){if(!sa(k))return!1;Et=!0,Wt=!1}if(er&&!Wt)return Ne||(Ne=new gn),Et||Wc(O)?Ys(O,k,ne,ge,vt,Ne):Df(O,k,it,ne,ge,vt,Ne);if(!(ne&i)){var xt=Wt&&$e.call(O,"__wrapped__"),Or=jr&&$e.call(k,"__wrapped__");if(xt||Or){var mn=xt?O.value():O,nn=Or?k.value():k;return Ne||(Ne=new gn),vt(mn,nn,ne,ge,Ne)}}return er?(Ne||(Ne=new gn),Nc(O,k,ne,ge,vt,Ne)):!1}function If(O){if(!Hc(O)||Fc(O))return!1;var k=Qs(O)?at:ae;return k.test(Vn(O))}function Tc(O){return os(O)&&zc(O.length)&&!!de[is(O)]}function Rc(O){if(!Bc(O))return rs(O);var k=[];for(var ne in Object(O))$e.call(O,ne)&&ne!="constructor"&&k.push(ne);return k}function Ys(O,k,ne,ge,vt,Ne){var Et=ne&i,Xt=O.length,it=k.length;if(Xt!=it&&!(Et&&it>Xt))return!1;var yt=Ne.get(O);if(yt&&Ne.get(k))return yt==k;var Wt=-1,jr=!0,er=ne&a?new Gs:void 0;for(Ne.set(O,k),Ne.set(k,O);++Wt<Xt;){var xt=O[Wt],Or=k[Wt];if(ge)var mn=Et?ge(Or,xt,Wt,k,O,Ne):ge(xt,Or,Wt,O,k,Ne);if(mn!==void 0){if(mn)continue;jr=!1;break}if(er){if(!ke(k,function(nn,An){if(!ze(er,An)&&(xt===nn||vt(xt,nn,ne,ge,Ne)))return er.push(An)})){jr=!1;break}}else if(!(xt===Or||vt(xt,Or,ne,ge,Ne))){jr=!1;break}}return Ne.delete(O),Ne.delete(k),jr}function Df(O,k,ne,ge,vt,Ne,Et){switch(ne){case se:if(O.byteLength!=k.byteLength||O.byteOffset!=k.byteOffset)return!1;O=O.buffer,k=k.buffer;case V:return!(O.byteLength!=k.byteLength||!Ne(new Sr(O),new Sr(k)));case m:case w:case U:return kc(+O,+k);case y:return O.name==k.name&&O.message==k.message;case $:case d:return O==k+"";case P:var Xt=Ue;case E:var it=ge&i;if(Xt||(Xt=He),O.size!=k.size&&!it)return!1;var yt=Et.get(O);if(yt)return yt==k;ge|=a,Et.set(O,k);var Wt=Ys(Xt(O),Xt(k),ge,vt,Ne,Et);return Et.delete(O),Wt;case b:if(Bt)return Bt.call(O)==Bt.call(k)}return!1}function Nc(O,k,ne,ge,vt,Ne){var Et=ne&i,Xt=Js(O),it=Xt.length,yt=Js(k),Wt=yt.length;if(it!=Wt&&!Et)return!1;for(var jr=it;jr--;){var er=Xt[jr];if(!(Et?er in k:$e.call(k,er)))return!1}var xt=Ne.get(O);if(xt&&Ne.get(k))return xt==k;var Or=!0;Ne.set(O,k),Ne.set(k,O);for(var mn=Et;++jr<it;){er=Xt[jr];var nn=O[er],An=k[er];if(ge)var oa=Et?ge(An,nn,er,k,O,Ne):ge(nn,An,er,O,k,Ne);if(!(oa===void 0?nn===An||vt(nn,An,ne,ge,Ne):oa)){Or=!1;break}mn||(mn=er=="constructor")}if(Or&&!mn){var as=O.constructor,ar=k.constructor;as!=ar&&"constructor"in O&&"constructor"in k&&!(typeof as=="function"&&as instanceof as&&typeof ar=="function"&&ar instanceof ar)&&(Or=!1)}return Ne.delete(O),Ne.delete(k),Or}function Js(O){return na(O,$f,Mc)}function _i(O,k){var ne=O.__data__;return jc(k)?ne[typeof k=="string"?"string":"hash"]:ne.map}function Gr(O,k){var ne=Oe(O,k);return If(ne)?ne:void 0}function Lc(O){var k=$e.call(O,Cr),ne=O[Cr];try{O[Cr]=void 0;var ge=!0}catch{}var vt=et.call(O);return ge&&(k?O[Cr]=ne:delete O[Cr]),vt}var Mc=Wn?function(O){return O==null?[]:(O=Object(O),Ke(Wn(O),function(k){return Ur.call(O,k)}))}:mt,$n=is;(Lt&&$n(new Lt(new ArrayBuffer(1)))!=se||Ot&&$n(new Ot)!=P||Mt&&$n(Mt.resolve())!=T||Ut&&$n(new Ut)!=E||Tt&&$n(new Tt)!=F)&&($n=function(O){var k=is(O),ne=k==A?O.constructor:void 0,ge=ne?Vn(ne):"";if(ge)switch(ge){case Gt:return se;case Yt:return P;case jt:return T;case Jt:return E;case Ft:return F}return k});function Uc(O,k){return k=k??c,!!k&&(typeof O=="number"||xe.test(O))&&O>-1&&O%1==0&&O<k}function jc(O){var k=typeof O;return k=="string"||k=="number"||k=="symbol"||k=="boolean"?O!=="__proto__":O===null}function Fc(O){return!!Ze&&Ze in O}function Bc(O){var k=O&&O.constructor,ne=typeof k=="function"&&k.prototype||Se;return O===ne}function Sf(O){return et.call(O)}function Vn(O){if(O!=null){try{return Ve.call(O)}catch{}try{return O+""}catch{}}return""}function kc(O,k){return O===k||O!==O&&k!==k}var qc=ia(function(){return arguments}())?ia:function(O){return os(O)&&$e.call(O,"callee")&&!Ur.call(O,"callee")},Zs=Array.isArray;function Cf(O){return O!=null&&zc(O.length)&&!Qs(O)}var sa=bi||gt;function Of(O,k){return ss(O,k)}function Qs(O){if(!Hc(O))return!1;var k=is(O);return k==x||k==S||k==h||k==C}function zc(O){return typeof O=="number"&&O>-1&&O%1==0&&O<=c}function Hc(O){var k=typeof O;return O!=null&&(k=="object"||k=="function")}function os(O){return O!=null&&typeof O=="object"}var Wc=Ce?Ct(Ce):Tc;function $f(O){return Cf(O)?Ac(O):Rc(O)}function mt(){return[]}function gt(){return!1}r.exports=Of})(Ru,Ru.exports);var rE=Ru.exports;function nE(r,e){return e=e||{},new Promise(function(t,n){var i=new XMLHttpRequest,a=[],c=[],u={},f=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:f,headers:{keys:function(){return a},entries:function(){return c},get:function(m){return u[m.toLowerCase()]},has:function(m){return m.toLowerCase()in u}}}};for(var h in i.open(e.method||"get",r,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(m,w,y){a.push(w=w.toLowerCase()),c.push([w,y]),u[w]=u[w]?u[w]+","+y:y}),t(f())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(h,e.headers[h]);i.send(e.body||null)})}var iE=Object.freeze({__proto__:null,default:nE}),Qp=Pi(iE),sE=self.fetch||(self.fetch=Qp.default||Qp),oE=Object.defineProperty,Xp=Object.getOwnPropertySymbols,aE=Object.prototype.hasOwnProperty,cE=Object.prototype.propertyIsEnumerable,e1=(r,e,t)=>e in r?oE(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,xr=(r,e)=>{for(var t in e||(e={}))aE.call(e,t)&&e1(r,t,e[t]);if(Xp)for(var t of Xp(e))cE.call(e,t)&&e1(r,t,e[t]);return r};function lE(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<r.length;i++){var a=r.charAt(i),c=a.charCodeAt(0);if(t[c]!==255)throw new TypeError(a+" is ambiguous");t[c]=i}var u=r.length,f=r.charAt(0),h=Math.log(u)/Math.log(256),m=Math.log(256)/Math.log(u);function w(S){if(S instanceof Uint8Array||(ArrayBuffer.isView(S)?S=new Uint8Array(S.buffer,S.byteOffset,S.byteLength):Array.isArray(S)&&(S=Uint8Array.from(S))),!(S instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(S.length===0)return"";for(var P=0,U=0,j=0,A=S.length;j!==A&&S[j]===0;)j++,P++;for(var T=(A-j)*m+1>>>0,C=new Uint8Array(T);j!==A;){for(var $=S[j],E=0,d=T-1;($!==0||E<U)&&d!==-1;d--,E++)$+=256*C[d]>>>0,C[d]=$%u>>>0,$=$/u>>>0;if($!==0)throw new Error("Non-zero carry");U=E,j++}for(var b=T-U;b!==T&&C[b]===0;)b++;for(var H=f.repeat(P);b<T;++b)H+=r.charAt(C[b]);return H}function y(S){if(typeof S!="string")throw new TypeError("Expected String");if(S.length===0)return new Uint8Array;var P=0;if(S[P]!==" "){for(var U=0,j=0;S[P]===f;)U++,P++;for(var A=(S.length-P)*h+1>>>0,T=new Uint8Array(A);S[P];){var C=t[S.charCodeAt(P)];if(C===255)return;for(var $=0,E=A-1;(C!==0||$<j)&&E!==-1;E--,$++)C+=u*T[E]>>>0,T[E]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");j=$,P++}if(S[P]!==" "){for(var d=A-j;d!==A&&T[d]===0;)d++;for(var b=new Uint8Array(U+(A-d)),H=U;d!==A;)b[H++]=T[d++];return b}}}function x(S){var P=y(S);if(P)return P;throw new Error(`Non-${e} character`)}return{encode:w,decodeUnsafe:y,decode:x}}var uE=lE,hE=uE;const t1=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},fE=r=>new TextEncoder().encode(r),dE=r=>new TextDecoder().decode(r);class pE{constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class gE{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.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 r1(this,e)}}class mE{constructor(e){this.decoders=e}or(e){return r1(this,e)}decode(e){const t=e[0],n=this.decoders[t];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 r1=(r,e)=>new mE(xr(xr({},r.decoders||{[r.prefix]:r}),e.decoders||{[e.prefix]:e}));class vE{constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new pE(e,t,n),this.decoder=new gE(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ka=({name:r,prefix:e,encode:t,decode:n})=>new vE(r,e,t,n),To=({prefix:r,name:e,alphabet:t})=>{const{encode:n,decode:i}=hE(t,e);return Ka({prefix:r,name:e,encode:n,decode:a=>t1(i(a))})},yE=(r,e,t,n)=>{const i={};for(let m=0;m<e.length;++m)i[e[m]]=m;let a=r.length;for(;r[a-1]==="=";)--a;const c=new Uint8Array(a*t/8|0);let u=0,f=0,h=0;for(let m=0;m<a;++m){const w=i[r[m]];if(w===void 0)throw new SyntaxError(`Non-${n} character`);f=f<<t|w,u+=t,u>=8&&(u-=8,c[h++]=255&f>>u)}if(u>=t||255&f<<8-u)throw new SyntaxError("Unexpected end of data");return c},wE=(r,e,t)=>{const n=e[e.length-1]==="=",i=(1<<t)-1;let a="",c=0,u=0;for(let f=0;f<r.length;++f)for(u=u<<8|r[f],c+=8;c>t;)c-=t,a+=e[i&u>>c];if(c&&(a+=e[i&u<<t-c]),n)for(;a.length*t&7;)a+="=";return a},hr=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>Ka({prefix:e,name:r,encode(i){return wE(i,n,t)},decode(i){return yE(i,n,t,r)}}),bE=Ka({prefix:"\0",name:"identity",encode:r=>dE(r),decode:r=>fE(r)});var _E=Object.freeze({__proto__:null,identity:bE});const EE=hr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var xE=Object.freeze({__proto__:null,base2:EE});const IE=hr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var DE=Object.freeze({__proto__:null,base8:IE});const SE=To({prefix:"9",name:"base10",alphabet:"0123456789"});var CE=Object.freeze({__proto__:null,base10:SE});const OE=hr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),$E=hr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var AE=Object.freeze({__proto__:null,base16:OE,base16upper:$E});const PE=hr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),TE=hr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),RE=hr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),NE=hr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),LE=hr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ME=hr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),UE=hr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),jE=hr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),FE=hr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var BE=Object.freeze({__proto__:null,base32:PE,base32upper:TE,base32pad:RE,base32padupper:NE,base32hex:LE,base32hexupper:ME,base32hexpad:UE,base32hexpadupper:jE,base32z:FE});const kE=To({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),qE=To({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var zE=Object.freeze({__proto__:null,base36:kE,base36upper:qE});const HE=To({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),WE=To({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var KE=Object.freeze({__proto__:null,base58btc:HE,base58flickr:WE});const VE=hr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),GE=hr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),YE=hr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),JE=hr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ZE=Object.freeze({__proto__:null,base64:VE,base64pad:GE,base64url:YE,base64urlpad:JE});const n1=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}"),QE=n1.reduce((r,e,t)=>(r[t]=e,r),[]),XE=n1.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function e4(r){return r.reduce((e,t)=>(e+=QE[t],e),"")}function t4(r){const e=[];for(const t of r){const n=XE[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}const r4=Ka({prefix:"\u{1F680}",name:"base256emoji",encode:e4,decode:t4});var n4=Object.freeze({__proto__:null,base256emoji:r4}),i4=s1,i1=128,s4=127,o4=~s4,a4=Math.pow(2,31);function s1(r,e,t){e=e||[],t=t||0;for(var n=t;r>=a4;)e[t++]=r&255|i1,r/=128;for(;r&o4;)e[t++]=r&255|i1,r>>>=7;return e[t]=r|0,s1.bytes=t-n+1,e}var c4=Nu,l4=128,o1=127;function Nu(r,n){var t=0,n=n||0,i=0,a=n,c,u=r.length;do{if(a>=u)throw Nu.bytes=0,new RangeError("Could not decode varint");c=r[a++],t+=i<28?(c&o1)<<i:(c&o1)*Math.pow(2,i),i+=7}while(c>=l4);return Nu.bytes=a-n,t}var u4=Math.pow(2,7),h4=Math.pow(2,14),f4=Math.pow(2,21),d4=Math.pow(2,28),p4=Math.pow(2,35),g4=Math.pow(2,42),m4=Math.pow(2,49),v4=Math.pow(2,56),y4=Math.pow(2,63),w4=function(r){return r<u4?1:r<h4?2:r<f4?3:r<d4?4:r<p4?5:r<g4?6:r<m4?7:r<v4?8:r<y4?9:10},b4={encode:i4,decode:c4,encodingLength:w4},a1=b4;const c1=(r,e,t=0)=>(a1.encode(r,e,t),e),l1=r=>a1.encodingLength(r),Lu=(r,e)=>{const t=e.byteLength,n=l1(r),i=n+l1(t),a=new Uint8Array(i+t);return c1(r,a,0),c1(t,a,n),a.set(e,i),new _4(r,t,e,a)};class _4{constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}}const u1=({name:r,code:e,encode:t})=>new E4(r,e,t);class E4{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Lu(this.code,t):t.then(n=>Lu(this.code,n))}else throw Error("Unknown type, must be binary type")}}const h1=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),x4=u1({name:"sha2-256",code:18,encode:h1("SHA-256")}),I4=u1({name:"sha2-512",code:19,encode:h1("SHA-512")});var D4=Object.freeze({__proto__:null,sha256:x4,sha512:I4});const f1=0,S4="identity",d1=t1;var C4=Object.freeze({__proto__:null,identity:{code:f1,name:S4,encode:d1,digest:r=>Lu(f1,d1(r))}});new TextEncoder,new TextDecoder;const p1=xr(xr(xr(xr(xr(xr(xr(xr(xr(xr({},_E),xE),DE),CE),AE),BE),zE),KE),ZE),n4);xr(xr({},D4),C4);function g1(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function O4(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?g1(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function m1(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}const v1=m1("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Mu=m1("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);const e=O4(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),$4=xr({utf8:v1,"utf-8":v1,hex:p1.base16,latin1:Mu,ascii:Mu,binary:Mu},p1);function A4(r,e="utf8"){const t=$4[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?g1(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}const y1="wc",P4=2,Uu="core",si=`${y1}@2:${Uu}:`,T4={name:Uu,logger:"error"},R4={database:":memory:"},N4="crypto",w1="client_ed25519_seed",L4=ye.ONE_DAY,M4="keychain",U4="0.3",j4="messages",F4="0.3",B4=ye.SIX_HOURS,k4="publisher",b1="irn",q4="error",_1="wss://relay.walletconnect.com",E1="wss://relay.walletconnect.org",z4="relayer",pr={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"},H4="_subscription",jn={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},W4=ye.ONE_SECOND,K4="2.11.2",V4=1e4,G4="0.3",Y4="WALLETCONNECT_CLIENT_ID",pn={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},J4="subscription",Z4="0.3",Q4=ye.FIVE_SECONDS*1e3,X4="pairing",e8="0.3",Ro={wc_pairingDelete:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:ye.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:ye.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:0},res:{ttl:ye.ONE_DAY,prompt:!1,tag:0}}},No={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},xn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},t8="history",r8="0.3",n8="expirer",en={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},i8="0.3",ju="verify-api",Cs="https://verify.walletconnect.com",Fu="https://verify.walletconnect.org",s8=[Cs,Fu],o8="echo",a8="https://echo.walletconnect.com";class c8{constructor(e,t){this.core=e,this.logger=t,this.keychain=new Map,this.name=M4,this.version=U4,this.initialized=!1,this.storagePrefix=si,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:a}=ue("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(a)}return i},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=e,this.logger=Xe.generateChildLogger(t,this.name)}get context(){return Xe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Z0(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Q0(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}}class l8{constructor(e,t,n){this.core=e,this.logger=t,this.name=N4,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(),a=Mp(i);return Lp(a.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const i=X2();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const a=await this.getClientSeed(),c=Mp(a),u=su();return await d6(u,i,L4,c)},this.generateSharedKey=(i,a,c)=>{this.isInitialized();const u=this.getPrivateKey(i),f=e_(u,a);return this.setSymKey(f,c)},this.setSymKey=async(i,a)=>{this.isInitialized();const c=a||t_(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,a,c)=>{this.isInitialized();const u=K0(c),f=ji(a);if(V0(u)){const y=u.senderPublicKey,x=u.receiverPublicKey;i=await this.generateSharedKey(y,x)}const h=this.getSymKey(i),{type:m,senderPublicKey:w}=u;return n_({type:m,symKey:h,message:f,senderPublicKey:w})},this.decode=async(i,a,c)=>{this.isInitialized();const u=o_(a,c);if(V0(u)){const f=u.receiverPublicKey,h=u.senderPublicKey;i=await this.generateSharedKey(f,h)}try{const f=this.getSymKey(i),h=i_({symKey:f,encoded:a});return Do(h)}catch(f){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(f)}},this.getPayloadType=i=>{const a=Ra(i);return wo(a.type)},this.getPayloadSenderPublicKey=i=>{const a=Ra(i);return a.senderPublicKey?wr(a.senderPublicKey,br):void 0},this.core=e,this.logger=Xe.generateChildLogger(t,this.name),this.keychain=n||new c8(this.core,this.logger)}get context(){return Xe.getLoggerContext(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(w1)}catch{e=su(),await this.keychain.set(w1,e)}return A4(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}}class u8 extends H5{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.name=j4,this.version=F4,this.initialized=!1,this.storagePrefix=si,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 a=bs(i);let c=this.messages.get(n);return typeof c>"u"&&(c={}),typeof c[a]<"u"||(c[a]=i,this.messages.set(n,c),await this.persist()),a},this.get=n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i},this.has=(n,i)=>{this.isInitialized();const a=this.get(n),c=bs(i);return typeof a[c]<"u"},this.del=async n=>{this.isInitialized(),this.messages.delete(n),await this.persist()},this.logger=Xe.generateChildLogger(e,this.name),this.core=t}get context(){return Xe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Z0(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Q0(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}}class h8 extends W5{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new lr.exports.EventEmitter,this.name=k4,this.queue=new Map,this.publishTimeout=ye.toMiliseconds(ye.TEN_SECONDS*2),this.needsTransportRestart=!1,this.publish=async(n,i,a)=>{var c;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:a}});try{const u=a?.ttl||B4,f=cu(a),h=a?.prompt||!1,m=a?.tag||0,w=a?.id||Wp().toString(),y={topic:n,message:i,opts:{ttl:u,relay:f,prompt:h,tag:m,id:w}},x=setTimeout(()=>this.queue.set(w,y),this.publishTimeout);try{await await _o(this.rpcPublish(n,i,u,f,h,m,w),this.publishTimeout,`Failed to publish payload, please try again. id:${w} tag:${m}`),this.removeRequestFromQueue(w),this.relayer.events.emit(pr.publish,y)}catch(S){if(this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0,(c=a?.internal)!=null&&c.throwOnFailedPublish)throw this.removeRequestFromQueue(w),S;return}finally{clearTimeout(x)}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:a}})}catch(u){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(u),u}},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=Xe.generateChildLogger(t,this.name),this.registerEventListeners()}get context(){return Xe.getLoggerContext(this.logger)}rpcPublish(e,t,n,i,a,c,u){var f,h,m,w;const y={method:Na(i.protocol).publish,params:{topic:e,message:t,ttl:n,prompt:a,tag:c},id:u};return _r((f=y.params)==null?void 0:f.prompt)&&((h=y.params)==null||delete h.prompt),_r((m=y.params)==null?void 0:m.tag)&&((w=y.params)==null||delete w.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:y}),this.relayer.request(y)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:t,message:n,opts:i}=e;await this.publish(t,n,i)})}registerEventListeners(){this.relayer.core.heartbeat.on(Ds.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(pr.connection_stalled);return}this.checkQueue()}),this.relayer.on(pr.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class f8{constructor(){this.map=new Map,this.set=(e,t)=>{const n=this.get(e);this.exists(e,t)||this.map.set(e,[...n,t])},this.get=e=>this.map.get(e)||[],this.exists=(e,t)=>this.get(e).includes(t),this.delete=(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,t))return;const i=n.filter(a=>a!==t);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 d8=Object.defineProperty,p8=Object.defineProperties,g8=Object.getOwnPropertyDescriptors,x1=Object.getOwnPropertySymbols,m8=Object.prototype.hasOwnProperty,v8=Object.prototype.propertyIsEnumerable,I1=(r,e,t)=>e in r?d8(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Lo=(r,e)=>{for(var t in e||(e={}))m8.call(e,t)&&I1(r,t,e[t]);if(x1)for(var t of x1(e))v8.call(e,t)&&I1(r,t,e[t]);return r},Bu=(r,e)=>p8(r,g8(e));class y8 extends G5{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new f8,this.events=new lr.exports.EventEmitter,this.name=J4,this.version=Z4,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=si,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),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 a=cu(i),c={topic:n,relay:a};this.pending.set(n,c);const u=await this.rpcSubscribe(n,a);return this.onSubscribe(u,c),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}}),u}catch(a){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(a),a}},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=>{if(this.topics.includes(n))return!0;const i=`${this.pendingSubscriptionWatchLabel}_${n}`;return await new Promise((a,c)=>{const u=new ye.Watch;u.start(i);const f=setInterval(()=>{!this.pending.has(n)&&this.topics.includes(n)&&(clearInterval(f),u.stop(i),a(!0)),u.elapsed(i)>=Q4&&(clearInterval(f),u.stop(i),c(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=Xe.generateChildLogger(t,this.name),this.clientId=""}get context(){return Xe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+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,t){let n=!1;try{n=this.getSubscription(e).topic===t}catch{}return n}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,t)))}async unsubscribeById(e,t,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:n}});try{const i=cu(n);await this.rpcUnsubscribe(e,t,i);const a=It("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,a),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,t){const n={method:Na(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await _o(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(pr.connection_stalled)}return bs(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,n={method:Na(t.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 _o(this.relayer.request(n),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(pr.connection_stalled)}}rpcUnsubscribe(e,t,n){const i={method:Na(n.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,t){this.setSubscription(e,Bu(Lo({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,Lo({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,n){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,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,t){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t))}addSubscription(e,t){this.subscriptions.set(e,Lo({},t)),this.topicMap.set(t.topic,e),this.events.emit(pn.created,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:n}=ue("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(pn.deleted,Bu(Lo({},n),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(pn.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let t=0;t<e;t++){const n=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}}this.events.emit(pn.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=ue("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}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 t=await this.rpcBatchSubscribe(e);En(t)&&this.onBatchSubscribe(t.map((n,i)=>Bu(Lo({},e[i]),{id:n})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach(t=>{e.push(t)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(Ds.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(pr.connect,async()=>{await this.onConnect()}),this.relayer.on(pr.disconnect,()=>{this.onDisconnect()}),this.events.on(pn.created,async e=>{const t=pn.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}),this.events.on(pn.deleted,async e=>{const t=pn.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{const t=setInterval(()=>{this.restartInProgress||(clearInterval(t),e())},this.pollingInterval)})}}var w8=Object.defineProperty,D1=Object.getOwnPropertySymbols,b8=Object.prototype.hasOwnProperty,_8=Object.prototype.propertyIsEnumerable,S1=(r,e,t)=>e in r?w8(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,E8=(r,e)=>{for(var t in e||(e={}))b8.call(e,t)&&S1(r,t,e[t]);if(D1)for(var t of D1(e))_8.call(e,t)&&S1(r,t,e[t]);return r};class x8 extends K5{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new lr.exports.EventEmitter,this.name=z4,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.request=async t=>{this.logger.debug("Publishing Request Payload");const n=t.id;try{await this.toEstablishConnection();const i=this.provider.request(t);return this.requestsInFlight.set(n,{promise:i,request:t}),await i}catch(i){throw this.logger.debug("Failed to Publish Request"),this.logger.error(i),i}finally{this.requestsInFlight.delete(n)}},this.onPayloadHandler=t=>{this.onProviderPayload(t)},this.onConnectHandler=()=>{this.events.emit(pr.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=t=>{this.logger.error(t),this.events.emit(pr.error,t),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(jn.payload,this.onPayloadHandler),this.provider.on(jn.connect,this.onConnectHandler),this.provider.on(jn.disconnect,this.onDisconnectHandler),this.provider.on(jn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Xe.generateChildLogger(e.logger,this.name):Xe.pino(Xe.getDefaultLoggerOptions({level:e.logger||q4})),this.messages=new u8(this.logger,e.core),this.subscriber=new y8(this,this.logger),this.publisher=new h8(this,this.logger),this.relayUrl=e?.relayUrl||_1,this.projectId=e.projectId,this.bundleId=f_(),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),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 ${E1}...`),await this.restartTransport(E1)}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)},V4)}get context(){return Xe.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,t,n){this.isInitialized(),await this.publisher.publish(e,t,n),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now()})}async subscribe(e,t){var n;this.isInitialized();let i=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"";if(i)return i;let a;const c=u=>{u.topic===e&&(this.subscriber.off(pn.created,c),a())};return await Promise.all([new Promise(u=>{a=u,this.subscriber.on(pn.created,c)}),new Promise(async u=>{i=await this.subscriber.subscribe(e,t),u()})]),i}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportClose(){this.requestsInFlight.size>0&&(this.logger.debug("Waiting for all in-flight requests to finish before closing transport..."),this.requestsInFlight.forEach(async e=>{await e.promise})),this.transportExplicitlyClosed=!0,this.hasExperiencedNetworkDisruption&&this.connected?await _o(this.provider.disconnect(),1e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.connected&&await this.provider.disconnect()}async transportOpen(e){if(this.transportExplicitlyClosed=!1,await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress){e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportClose(),await this.createProvider()),this.connectionAttemptInProgress=!0;try{await Promise.all([new Promise(t=>{if(!this.initialized)return t();this.subscriber.once(pn.resubscribed,()=>{t()})}),new Promise(async(t,n)=>{try{await _o(this.provider.connect(),1e4,`Socket stalled when trying to connect to ${this.relayUrl}`)}catch(i){n(i);return}t()})])}catch(t){this.logger.error(t);const n=t;if(!this.isConnectionStalled(n.message))throw t;this.provider.events.emit(jn.disconnect)}finally{this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1}}}async restartTransport(e){await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await up())throw new Error("No internet connection detected. Please restart your network and try again.")}isConnectionStalled(e){return this.staleConnectionErrors.some(t=>e.includes(t))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Un(new tE(y_({sdkVersion:K4,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:t,message:n}=e;await this.messages.set(t,n)}async shouldIgnoreMessageEvent(e){const{topic:t,message:n}=e;if(!n||n.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.debug(`Ignoring message for non-subscribed topic ${t}`),!0;const i=this.messages.has(t,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}),Tu(e)){if(!e.method.endsWith(H4))return;const t=e.params,{topic:n,message:i,publishedAt:a}=t.data,c={topic:n,message:i,publishedAt:a};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(E8({type:"event",event:t.id},c)),this.events.emit(t.id,c),await this.acknowledgePayload(e),await this.onMessageEvent(c)}else Wa(e)&&this.events.emit(pr.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(pr.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=za(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(jn.payload,this.onPayloadHandler),this.provider.off(jn.connect,this.onConnectHandler),this.provider.off(jn.disconnect,this.onDisconnectHandler),this.provider.off(jn.error,this.onProviderErrorHandler)}async registerEventListeners(){this.events.on(pr.connection_stalled,()=>{this.restartTransport().catch(t=>this.logger.error(t))});let e=await up();f3(async t=>{this.initialized&&e!==t&&(e=t,t?await this.restartTransport().catch(n=>this.logger.error(n)):(this.hasExperiencedNetworkDisruption=!0,await this.transportClose().catch(n=>this.logger.error(n))))})}onProviderDisconnect(){this.events.emit(pr.disconnect),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||(this.logger.info("attemptToReconnect called. Connecting..."),setTimeout(async()=>{await this.restartTransport().catch(e=>this.logger.error(e))},ye.toMiliseconds(W4)))}isInitialized(){if(!this.initialized){const{message:e}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectionAttemptInProgress)return await new Promise(e=>{const t=setInterval(()=>{this.connected&&(clearInterval(t),e())},this.connectionStatusPollingInterval)});await this.restartTransport()}}}var I8=Object.defineProperty,C1=Object.getOwnPropertySymbols,D8=Object.prototype.hasOwnProperty,S8=Object.prototype.propertyIsEnumerable,O1=(r,e,t)=>e in r?I8(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,$1=(r,e)=>{for(var t in e||(e={}))D8.call(e,t)&&O1(r,t,e[t]);if(C1)for(var t of C1(e))S8.call(e,t)&&O1(r,t,e[t]);return r};class Va extends V5{constructor(e,t,n,i=si,a=void 0){super(e,t,n,i),this.core=e,this.logger=t,this.name=n,this.map=new Map,this.version=G4,this.cached=[],this.initialized=!1,this.storagePrefix=si,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(c=>{this.getKey&&c!==null&&!_r(c)?this.map.set(this.getKey(c),c):z_(c)?this.map.set(c.id,c):H_(c)&&this.map.set(c.topic,c)}),this.cached=[],this.initialized=!0)},this.set=async(c,u)=>{this.isInitialized(),this.map.has(c)?await this.update(c,u):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:c,value:u}),this.map.set(c,u),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(u=>Object.keys(c).every(f=>rE(u[f],c[f]))):this.values),this.update=async(c,u)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:c,update:u});const f=$1($1({},this.getData(c)),u);this.map.set(c,f),await this.persist()},this.delete=async(c,u)=>{this.isInitialized(),this.map.has(c)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:c,reason:u}),this.map.delete(c),await this.persist())},this.logger=Xe.generateChildLogger(t,this.name),this.storagePrefix=i,this.getKey=a}get context(){return Xe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+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 t=this.map.get(e);if(!t){const{message:n}=ue("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return t}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:t}=ue("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}}class C8{constructor(e,t){this.core=e,this.logger=t,this.name=X4,this.version=e8,this.events=new lr.exports,this.initialized=!1,this.storagePrefix=si,this.ignoredPayloadTypes=[Li],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=su(),i=await this.core.crypto.setSymKey(n),a=Wr(ye.FIVE_MINUTES),c={protocol:b1},u={topic:i,expiry:a,relay:c,active:!1},f=N_({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:n,relay:c,expiryTimestamp:a});return await this.pairings.set(i,u),await this.core.relayer.subscribe(i),this.core.expirer.set(i,a),{topic:i,uri:f}},this.pair=async n=>{this.isInitialized(),this.isValidPair(n);const{topic:i,symKey:a,relay:c,expiryTimestamp:u}=np(n.uri);let f;if(this.pairings.keys.includes(i)&&(f=this.pairings.get(i),f.active))throw new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);const h=u||Wr(ye.FIVE_MINUTES),m={topic:i,relay:c,expiry:h,active:!1};return await this.pairings.set(i,m),this.core.expirer.set(i,h),n.activatePairing&&await this.activate({topic:i}),this.events.emit(No.create,m),this.core.crypto.keychain.has(i)||(await this.core.crypto.setSymKey(a,i),await this.core.relayer.subscribe(i,{relay:c})),m},this.activate=async({topic:n})=>{this.isInitialized();const i=Wr(ye.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 a=await this.sendRequest(i,"wc_pairingPing",{}),{done:c,resolve:u,reject:f}=xs();this.events.once(qt("pairing_ping",a),({error:h})=>{h?f(h):u()}),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",It("USER_DISCONNECTED")),await this.deletePairing(i))},this.sendRequest=async(n,i,a)=>{const c=Ss(i,a),u=await this.core.crypto.encode(n,c),f=Ro[i].req;return this.core.history.set(n,c),this.core.relayer.publish(n,u,f),c.id},this.sendResult=async(n,i,a)=>{const c=za(n,a),u=await this.core.crypto.encode(i,c),f=await this.core.history.get(i,n),h=Ro[f.request.method].res;await this.core.relayer.publish(i,u,h),await this.core.history.resolve(c)},this.sendError=async(n,i,a)=>{const c=Ha(n,a),u=await this.core.crypto.encode(i,c),f=await this.core.history.get(i,n),h=Ro[f.request.method]?Ro[f.request.method].res:Ro.unregistered_method.res;await this.core.relayer.publish(i,u,h),await this.core.history.resolve(c)},this.deletePairing=async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,It("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=>ii(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=n=>{const{topic:i,payload:a}=n;switch(a.method){case"wc_pairingPing":return this.onPairingPingRequest(i,a);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,a);default:return this.onUnknownRpcMethodRequest(i,a)}},this.onRelayEventResponse=async n=>{const{topic:i,payload:a}=n,c=(await this.core.history.get(i,a.id)).request.method;switch(c){case"wc_pairingPing":return this.onPairingPingResponse(i,a);default:return this.onUnknownRpcMethodResponse(c)}},this.onPairingPingRequest=async(n,i)=>{const{id:a}=i;try{this.isValidPing({topic:n}),await this.sendResult(a,n,!0),this.events.emit(No.ping,{id:a,topic:n})}catch(c){await this.sendError(a,n,c),this.logger.error(c)}},this.onPairingPingResponse=(n,i)=>{const{id:a}=i;setTimeout(()=>{Mn(i)?this.events.emit(qt("pairing_ping",a),{}):dn(i)&&this.events.emit(qt("pairing_ping",a),{error:i.error})},500)},this.onPairingDeleteRequest=async(n,i)=>{const{id:a}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(No.delete,{id:a,topic:n})}catch(c){await this.sendError(a,n,c),this.logger.error(c)}},this.onUnknownRpcMethodRequest=async(n,i)=>{const{id:a,method:c}=i;try{if(this.registeredMethods.includes(c))return;const u=It("WC_METHOD_UNSUPPORTED",c);await this.sendError(a,n,u),this.logger.error(u)}catch(u){await this.sendError(a,n,u),this.logger.error(u)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(It("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=n=>{var i;if(!Rr(n)){const{message:c}=ue("MISSING_OR_INVALID",`pair() params: ${n}`);throw new Error(c)}if(!q_(n.uri)){const{message:c}=ue("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw new Error(c)}const a=np(n.uri);if(!((i=a?.relay)!=null&&i.protocol)){const{message:c}=ue("MISSING_OR_INVALID","pair() uri#relay-protocol");throw new Error(c)}if(!(a!=null&&a.symKey)){const{message:c}=ue("MISSING_OR_INVALID","pair() uri#symKey");throw new Error(c)}if(a!=null&&a.expiryTimestamp&&ye.toMiliseconds(a?.expiryTimestamp)<Date.now()){const{message:c}=ue("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(c)}},this.isValidPing=async n=>{if(!Rr(n)){const{message:a}=ue("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(a)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidDisconnect=async n=>{if(!Rr(n)){const{message:a}=ue("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(a)}const{topic:i}=n;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async n=>{if(!ir(n,!1)){const{message:i}=ue("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=ue("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(ii(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=ue("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}},this.core=e,this.logger=Xe.generateChildLogger(t,this.name),this.pairings=new Va(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Xe.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(pr.message,async e=>{const{topic:t,message:n}=e;if(!this.pairings.keys.includes(t)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))return;const i=await this.core.crypto.decode(t,n);try{Tu(i)?(this.core.history.set(t,i),this.onRelayEventRequest({topic:t,payload:i})):Wa(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:t,payload:i}),this.core.history.delete(t,i.id))}catch(a){this.logger.error(a)}})}registerExpirerEvents(){this.core.expirer.on(en.expired,async e=>{const{topic:t}=ep(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(No.expire,{topic:t}))})}}class O8 extends z5{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new lr.exports.EventEmitter,this.name=t8,this.version=r8,this.cached=[],this.initialized=!1,this.storagePrefix=si,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,a)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:a}),this.records.has(i.id))return;const c={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:a,expiry:Wr(ye.THIRTY_DAYS)};this.records.set(c.id,c),this.events.emit(xn.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=dn(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.events.emit(xn.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(a=>{if(a.topic===n){if(typeof i<"u"&&a.id!==i)return;this.records.delete(a.id),this.events.emit(xn.deleted,a)}})},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=Xe.generateChildLogger(t,this.name)}get context(){return Xe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+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(t=>{if(typeof t.response<"u")return;const n={topic:t.topic,request:Ss(t.request.method,t.request.params,t.id),chainId:t.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 t=this.records.get(e);if(!t){const{message:n}=ue("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(xn.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=ue("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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(xn.created,e=>{const t=xn.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()}),this.events.on(xn.updated,e=>{const t=xn.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()}),this.events.on(xn.deleted,e=>{const t=xn.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()}),this.core.heartbeat.on(Ds.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.records.forEach(e=>{ye.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}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}}class $8 extends Y5{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new lr.exports.EventEmitter,this.name=n8,this.version=i8,this.cached=[],this.initialized=!1,this.storagePrefix=si,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 a=this.formatTarget(n),c={target:a,expiry:i};this.expirations.set(a,c),this.checkExpiry(a,c),this.events.emit(en.created,{target:a,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),a=this.getExpiration(i);this.expirations.delete(i),this.events.emit(en.deleted,{target:i,expiration:a})}},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=Xe.generateChildLogger(t,this.name)}get context(){return Xe.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+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 w_(e);if(typeof e=="number")return b_(e);const{message:t}=ue("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(t)}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(en.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=ue("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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 t=this.expirations.get(e);if(!t){const{message:n}=ue("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return t}checkExpiry(e,t){const{expiry:n}=t;ye.toMiliseconds(n)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(en.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(Ds.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(en.created,e=>{const t=en.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(en.expired,e=>{const t=en.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(en.deleted,e=>{const t=en.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}}}class A8 extends J5{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.name=ju,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async n=>{if(this.verifyDisabled||_s()||!Es())return;const i=this.getVerifyUrl(n?.verifyUrl);this.verifyUrl!==i&&this.removeIframe(),this.verifyUrl=i;try{await this.createIframe()}catch(a){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(a)}if(!this.initialized){this.removeIframe(),this.verifyUrl=Fu;try{await this.createIframe()}catch(a){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(a),this.verifyDisabled=!0}}},this.register=async n=>{this.initialized?this.sendPost(n.attestationId):(this.addToQueue(n.attestationId),await this.init())},this.resolve=async n=>{if(this.isDevEnv)return"";const i=this.getVerifyUrl(n?.verifyUrl);let a;try{a=await this.fetchAttestation(n.attestationId,i)}catch(c){this.logger.info(`failed to resolve attestation: ${n.attestationId} from url: ${i}`),this.logger.info(c),a=await this.fetchAttestation(n.attestationId,Fu)}return a},this.fetchAttestation=async(n,i)=>{this.logger.info(`resolving attestation: ${n} from url: ${i}`);const a=this.startAbortTimer(ye.ONE_SECOND*2),c=await fetch(`${i}/attestation/${n}`,{signal:this.abortController.signal});return clearTimeout(a),c.status===200?await c.json():void 0},this.addToQueue=n=>{this.queue.push(n)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(n=>this.sendPost(n)),this.queue=[])},this.sendPost=n=>{var i;try{if(!this.iframe)return;(i=this.iframe.contentWindow)==null||i.postMessage(n,"*"),this.logger.info(`postMessage sent: ${n} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let n;const i=a=>{a.data==="verify_ready"&&(this.initialized=!0,this.processQueue(),window.removeEventListener("message",i),n())};await Promise.race([new Promise(a=>{if(document.getElementById(ju))return a();window.addEventListener("message",i);const c=document.createElement("iframe");c.id=ju,c.src=`${this.verifyUrl}/${this.projectId}`,c.style.display="none",document.body.append(c),this.iframe=c,n=a}),new Promise((a,c)=>setTimeout(()=>{window.removeEventListener("message",i),c("verify iframe load timeout")},ye.toMiliseconds(ye.FIVE_SECONDS)))])},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.getVerifyUrl=n=>{let i=n||Cs;return s8.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${Cs}`),i=Cs),i},this.logger=Xe.generateChildLogger(t,this.name),this.verifyUrl=Cs,this.abortController=new AbortController,this.isDevEnv=ou()&&process.env.IS_VITEST}get context(){return Xe.getLoggerContext(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),ye.toMiliseconds(e))}}class P8 extends Z5{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.context=o8,this.registerDeviceToken=async n=>{const{clientId:i,token:a,notificationType:c,enableEncrypted:u=!1}=n,f=`${a8}/${this.projectId}/clients`;await sE(f,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:c,token:a,always_raw:u})})},this.logger=Xe.generateChildLogger(t,this.context)}}var T8=Object.defineProperty,A1=Object.getOwnPropertySymbols,R8=Object.prototype.hasOwnProperty,N8=Object.prototype.propertyIsEnumerable,P1=(r,e,t)=>e in r?T8(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,T1=(r,e)=>{for(var t in e||(e={}))R8.call(e,t)&&P1(r,t,e[t]);if(A1)for(var t of A1(e))N8.call(e,t)&&P1(r,t,e[t]);return r};class ku extends q5{constructor(e){super(e),this.protocol=y1,this.version=P4,this.name=Uu,this.events=new lr.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||_1,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Xe.pino(Xe.getDefaultLoggerOptions({level:e?.logger||T4.logger}));this.logger=Xe.generateChildLogger(t,this.name),this.heartbeat=new Ds.HeartBeat,this.crypto=new l8(this,this.logger,e?.keychain),this.history=new O8(this,this.logger),this.expirer=new $8(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new K3(T1(T1({},R4),e?.storageOptions)),this.relayer=new x8({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new C8(this,this.logger),this.verify=new A8(this.projectId||"",this.logger),this.echoClient=new P8(this.projectId||"",this.logger)}static async init(e){const t=new ku(e);await t.initialize();const n=await t.crypto.getClientId();return await t.storage.setItem(Y4,n),t}get context(){return Xe.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 L8=ku,R1="wc",N1=2,L1="client",qu=`${R1}@${N1}:${L1}:`,zu={name:L1,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},M1="WALLETCONNECT_DEEPLINK_CHOICE",M8="proposal",U1="Proposal expired",U8="session",Ga=ye.SEVEN_DAYS,j8="engine",Fn={wc_sessionPropose:{req:{ttl:ye.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1101}},wc_sessionSettle:{req:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1104},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1106},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:ye.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:ye.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:ye.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:ye.ONE_DAY,prompt:!1,tag:1112},res:{ttl:ye.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:ye.THIRTY_SECONDS,prompt:!1,tag:1114},res:{ttl:ye.THIRTY_SECONDS,prompt:!1,tag:1115}}},Hu={min:ye.FIVE_MINUTES,max:ye.SEVEN_DAYS},Bn={idle:"IDLE",active:"ACTIVE"},F8="request",B8=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var k8=Object.defineProperty,q8=Object.defineProperties,z8=Object.getOwnPropertyDescriptors,j1=Object.getOwnPropertySymbols,H8=Object.prototype.hasOwnProperty,W8=Object.prototype.propertyIsEnumerable,F1=(r,e,t)=>e in r?k8(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ir=(r,e)=>{for(var t in e||(e={}))H8.call(e,t)&&F1(r,t,e[t]);if(j1)for(var t of j1(e))W8.call(e,t)&&F1(r,t,e[t]);return r},Os=(r,e)=>q8(r,z8(e));class K8 extends X5{constructor(e){super(e),this.name=j8,this.events=new lr.exports,this.initialized=!1,this.ignoredPayloadTypes=[Li],this.requestQueue={state:Bn.idle,queue:[]},this.sessionRequestQueue={state:Bn.idle,queue:[]},this.requestQueueDelay=ye.ONE_SECOND,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.client.core.pairing.register({methods:Object.keys(Fn)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},ye.toMiliseconds(this.requestQueueDelay)))},this.connect=async t=>{await this.isInitialized();const n=Os(Ir({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:a,optionalNamespaces:c,sessionProperties:u,relays:f}=n;let h=i,m,w=!1;if(h&&(w=this.client.core.pairing.pairings.get(h).active),!h||!w){const{topic:C,uri:$}=await this.client.core.pairing.create();h=C,m=$}const y=await this.client.core.crypto.generateKeyPair(),x=Fn.wc_sessionPropose.req.ttl||ye.FIVE_MINUTES,S=Wr(x),P=Ir({requiredNamespaces:a,optionalNamespaces:c,relays:f??[{protocol:b1}],proposer:{publicKey:y,metadata:this.client.metadata},expiryTimestamp:S},u&&{sessionProperties:u}),{reject:U,resolve:j,done:A}=xs(x,U1);if(this.events.once(qt("session_connect"),async({error:C,session:$})=>{if(C)U(C);else if($){$.self.publicKey=y;const E=Os(Ir({},$),{requiredNamespaces:P.requiredNamespaces,optionalNamespaces:P.optionalNamespaces});await this.client.session.set($.topic,E),await this.setExpiry($.topic,$.expiry),h&&await this.client.core.pairing.updateMetadata({topic:h,metadata:$.peer.metadata}),j(E)}}),!h){const{message:C}=ue("NO_MATCHING_KEY",`connect() pairing topic: ${h}`);throw new Error(C)}const T=await this.sendRequest({topic:h,method:"wc_sessionPropose",params:P,throwOnFailedPublish:!0});return await this.setProposal(T,Ir({id:T},P)),{uri:m,approval:A}},this.pair=async t=>(await this.isInitialized(),await this.client.core.pairing.pair(t)),this.approve=async t=>{await this.isInitialized(),await this.isValidApprove(t);const{id:n,relayProtocol:i,namespaces:a,sessionProperties:c}=t,u=this.client.proposal.get(n);let{pairingTopic:f,proposer:h,requiredNamespaces:m,optionalNamespaces:w}=u;f=f||"";const y=await this.client.core.crypto.generateKeyPair(),x=h.publicKey,S=await this.client.core.crypto.generateSharedKey(y,x);f&&n&&(await this.client.core.pairing.updateMetadata({topic:f,metadata:h.metadata}),await this.sendResult({id:n,topic:f,result:{relay:{protocol:i??"irn"},responderPublicKey:y}}),await this.client.proposal.delete(n,It("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:f}));const P=Ir({relay:{protocol:i??"irn"},namespaces:a,pairingTopic:f,controller:{publicKey:y,metadata:this.client.metadata},expiry:Wr(Ga)},c&&{sessionProperties:c});await this.client.core.relayer.subscribe(S);const U=Os(Ir({},P),{topic:S,requiredNamespaces:m,optionalNamespaces:w,pairingTopic:f,acknowledged:!1,self:P.controller,peer:{publicKey:h.publicKey,metadata:h.metadata},controller:y});await this.client.session.set(S,U);try{await this.sendRequest({topic:S,method:"wc_sessionSettle",params:P,throwOnFailedPublish:!0})}catch(j){throw this.client.logger.error(j),this.client.session.delete(S,It("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(S),j}return await this.setExpiry(S,Wr(Ga)),{topic:S,acknowledged:()=>new Promise(j=>setTimeout(()=>j(this.client.session.get(S)),500))}},this.reject=async t=>{await this.isInitialized(),await this.isValidReject(t);const{id:n,reason:i}=t,{pairingTopic:a}=this.client.proposal.get(n);a&&(await this.sendError(n,a,i),await this.client.proposal.delete(n,It("USER_DISCONNECTED")))},this.update=async t=>{await this.isInitialized(),await this.isValidUpdate(t);const{topic:n,namespaces:i}=t,a=await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i}}),{done:c,resolve:u,reject:f}=xs();return this.events.once(qt("session_update",a),({error:h})=>{h?f(h):u()}),await this.client.session.update(n,{namespaces:i}),{acknowledged:c}},this.extend=async t=>{await this.isInitialized(),await this.isValidExtend(t);const{topic:n}=t,i=await this.sendRequest({topic:n,method:"wc_sessionExtend",params:{}}),{done:a,resolve:c,reject:u}=xs();return this.events.once(qt("session_extend",i),({error:f})=>{f?u(f):c()}),await this.setExpiry(n,Wr(Ga)),{acknowledged:a}},this.request=async t=>{await this.isInitialized(),await this.isValidRequest(t);const{chainId:n,request:i,topic:a,expiry:c=Fn.wc_sessionRequest.req.ttl}=t,u=Pu(),{done:f,resolve:h,reject:m}=xs(c,"Request expired. Please try again.");return this.events.once(qt("session_request",u),({error:w,result:y})=>{w?m(w):h(y)}),await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:u,topic:a,method:"wc_sessionRequest",params:{request:Os(Ir({},i),{expiryTimestamp:Wr(c)}),chainId:n},expiry:c,throwOnFailedPublish:!0}).catch(y=>m(y)),this.client.events.emit("session_request_sent",{topic:a,request:i,chainId:n,id:u}),w()}),new Promise(async w=>{const y=await E_(this.client.core.storage,M1);__({id:u,topic:a,wcDeepLink:y}),w()}),f()]).then(w=>w[2])},this.respond=async t=>{await this.isInitialized(),await this.isValidRespond(t);const{topic:n,response:i}=t,{id:a}=i;Mn(i)?await this.sendResult({id:a,topic:n,result:i.result,throwOnFailedPublish:!0}):dn(i)&&await this.sendError(a,n,i.error),this.cleanupAfterResponse(t)},this.ping=async t=>{await this.isInitialized(),await this.isValidPing(t);const{topic:n}=t;if(this.client.session.keys.includes(n)){const i=await this.sendRequest({topic:n,method:"wc_sessionPing",params:{}}),{done:a,resolve:c,reject:u}=xs();this.events.once(qt("session_ping",i),({error:f})=>{f?u(f):c()}),await a()}else this.client.core.pairing.pairings.keys.includes(n)&&await this.client.core.pairing.ping({topic:n})},this.emit=async t=>{await this.isInitialized(),await this.isValidEmit(t);const{topic:n,event:i,chainId:a}=t;await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:a}})},this.disconnect=async t=>{await this.isInitialized(),await this.isValidDisconnect(t);const{topic:n}=t;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:It("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{const{message:i}=ue("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}},this.find=t=>(this.isInitialized(),this.client.session.getAll().filter(n=>B_(n,t))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.cleanupDuplicatePairings=async t=>{if(t.pairingTopic)try{const n=this.client.core.pairing.pairings.get(t.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(a=>{var c,u;return((c=a.peerMetadata)==null?void 0:c.url)&&((u=a.peerMetadata)==null?void 0:u.url)===t.peer.metadata.url&&a.topic&&a.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(a=>this.client.core.pairing.disconnect({topic:a.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async t=>{const{topic:n,expirerHasDeleted:i=!1,emitEvent:a=!0,id:c=0}=t,{self:u}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,It("USER_DISCONNECTED")),this.client.core.crypto.keychain.has(u.publicKey)&&await this.client.core.crypto.deleteKeyPair(u.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),i||this.client.core.expirer.del(n),this.client.core.storage.removeItem(M1).catch(f=>this.client.logger.warn(f)),this.getPendingSessionRequests().forEach(f=>{f.topic===n&&this.deletePendingSessionRequest(f.id,It("USER_DISCONNECTED"))}),a&&this.client.events.emit("session_delete",{id:c,topic:n})},this.deleteProposal=async(t,n)=>{await Promise.all([this.client.proposal.delete(t,It("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(t)])},this.deletePendingSessionRequest=async(t,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,n),i?Promise.resolve():this.client.core.expirer.del(t)]),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(a=>a.id!==t),i&&(this.sessionRequestQueue.state=Bn.idle,this.client.events.emit("session_request_expire",{id:t}))},this.setExpiry=async(t,n)=>{this.client.session.keys.includes(t)&&await this.client.session.update(t,{expiry:n}),this.client.core.expirer.set(t,n)},this.setProposal=async(t,n)=>{await this.client.proposal.set(t,n),this.client.core.expirer.set(t,Wr(Fn.wc_sessionPropose.req.ttl))},this.setPendingSessionRequest=async t=>{const{id:n,topic:i,params:a,verifyContext:c}=t,u=a.request.expiryTimestamp||Wr(Fn.wc_sessionRequest.req.ttl);await this.client.pendingRequest.set(n,{id:n,topic:i,params:a,verifyContext:c}),u&&this.client.core.expirer.set(n,u)},this.sendRequest=async t=>{const{topic:n,method:i,params:a,expiry:c,relayRpcId:u,clientRpcId:f,throwOnFailedPublish:h}=t,m=Ss(i,a,f);if(Es()&&B8.includes(i)){const x=bs(JSON.stringify(m));this.client.core.verify.register({attestationId:x})}const w=await this.client.core.crypto.encode(n,m),y=Fn[i].req;return c&&(y.ttl=c),u&&(y.id=u),this.client.core.history.set(n,m),h?(y.internal=Os(Ir({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,w,y)):this.client.core.relayer.publish(n,w,y).catch(x=>this.client.logger.error(x)),m.id},this.sendResult=async t=>{const{id:n,topic:i,result:a,throwOnFailedPublish:c}=t,u=za(n,a),f=await this.client.core.crypto.encode(i,u),h=await this.client.core.history.get(i,n),m=Fn[h.request.method].res;c?(m.internal=Os(Ir({},m.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,f,m)):this.client.core.relayer.publish(i,f,m).catch(w=>this.client.logger.error(w)),await this.client.core.history.resolve(u)},this.sendError=async(t,n,i)=>{const a=Ha(t,i),c=await this.client.core.crypto.encode(n,a),u=await this.client.core.history.get(n,t),f=Fn[u.request.method].res;this.client.core.relayer.publish(n,c,f),await this.client.core.history.resolve(a)},this.cleanup=async()=>{const t=[],n=[];this.client.session.getAll().forEach(i=>{let a=!1;ii(i.expiry)&&(a=!0),this.client.core.crypto.keychain.has(i.topic)||(a=!0),a&&t.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{ii(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...t.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])},this.onRelayEventRequest=async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===Bn.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Bn.active;const t=this.requestQueue.queue.shift();if(t)try{this.processRequest(t),await new Promise(n=>setTimeout(n,300))}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Bn.idle},this.processRequest=t=>{const{topic:n,payload:i}=t,a=i.method;switch(a){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 ${a}`)}},this.onRelayEventResponse=async t=>{const{topic:n,payload:i}=t,a=(await this.client.core.history.get(n,i.id)).request.method;switch(a){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 ${a}`)}},this.onRelayEventUnknownPayload=t=>{const{topic:n}=t,{message:i}=ue("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(t,n)=>{const{params:i,id:a}=n;try{this.isValidConnect(Ir({},n.params));const c=i.expiryTimestamp||Wr(Fn.wc_sessionPropose.req.ttl),u=Ir({id:a,pairingTopic:t,expiryTimestamp:c},i);await this.setProposal(a,u);const f=bs(JSON.stringify(n)),h=await this.getVerifyContext(f,u.proposer.metadata);this.client.events.emit("session_proposal",{id:a,params:u,verifyContext:h})}catch(c){await this.sendError(a,t,c),this.client.logger.error(c)}},this.onSessionProposeResponse=async(t,n)=>{const{id:i}=n;if(Mn(n)){const{result:a}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:a});const c=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:c});const u=c.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:u});const f=a.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:f});const h=await this.client.core.crypto.generateSharedKey(u,f);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:h});const m=await this.client.core.relayer.subscribe(h);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:m}),await this.client.core.pairing.activate({topic:t})}else dn(n)&&(await this.client.proposal.delete(i,It("USER_DISCONNECTED")),this.events.emit(qt("session_connect"),{error:n.error}))},this.onSessionSettleRequest=async(t,n)=>{const{id:i,params:a}=n;try{this.isValidSessionSettleRequest(a);const{relay:c,controller:u,expiry:f,namespaces:h,sessionProperties:m,pairingTopic:w}=n.params,y=Ir({topic:t,relay:c,expiry:f,namespaces:h,acknowledged:!0,pairingTopic:w,requiredNamespaces:{},optionalNamespaces:{},controller:u.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:u.publicKey,metadata:u.metadata}},m&&{sessionProperties:m});await this.sendResult({id:n.id,topic:t,result:!0}),this.events.emit(qt("session_connect"),{session:y}),this.cleanupDuplicatePairings(y)}catch(c){await this.sendError(i,t,c),this.client.logger.error(c)}},this.onSessionSettleResponse=async(t,n)=>{const{id:i}=n;Mn(n)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(qt("session_approve",i),{})):dn(n)&&(await this.client.session.delete(t,It("USER_DISCONNECTED")),this.events.emit(qt("session_approve",i),{error:n.error}))},this.onSessionUpdateRequest=async(t,n)=>{const{params:i,id:a}=n;try{const c=`${t}_session_update`,u=Ma.get(c);if(u&&this.isRequestOutOfSync(u,a)){this.client.logger.info(`Discarding out of sync request - ${a}`);return}this.isValidUpdate(Ir({topic:t},i)),await this.client.session.update(t,{namespaces:i.namespaces}),await this.sendResult({id:a,topic:t,result:!0}),this.client.events.emit("session_update",{id:a,topic:t,params:i}),Ma.set(c,a)}catch(c){await this.sendError(a,t,c),this.client.logger.error(c)}},this.isRequestOutOfSync=(t,n)=>parseInt(n.toString().slice(0,-3))<=parseInt(t.toString().slice(0,-3)),this.onSessionUpdateResponse=(t,n)=>{const{id:i}=n;Mn(n)?this.events.emit(qt("session_update",i),{}):dn(n)&&this.events.emit(qt("session_update",i),{error:n.error})},this.onSessionExtendRequest=async(t,n)=>{const{id:i}=n;try{this.isValidExtend({topic:t}),await this.setExpiry(t,Wr(Ga)),await this.sendResult({id:i,topic:t,result:!0}),this.client.events.emit("session_extend",{id:i,topic:t})}catch(a){await this.sendError(i,t,a),this.client.logger.error(a)}},this.onSessionExtendResponse=(t,n)=>{const{id:i}=n;Mn(n)?this.events.emit(qt("session_extend",i),{}):dn(n)&&this.events.emit(qt("session_extend",i),{error:n.error})},this.onSessionPingRequest=async(t,n)=>{const{id:i}=n;try{this.isValidPing({topic:t}),await this.sendResult({id:i,topic:t,result:!0}),this.client.events.emit("session_ping",{id:i,topic:t})}catch(a){await this.sendError(i,t,a),this.client.logger.error(a)}},this.onSessionPingResponse=(t,n)=>{const{id:i}=n;setTimeout(()=>{Mn(n)?this.events.emit(qt("session_ping",i),{}):dn(n)&&this.events.emit(qt("session_ping",i),{error:n.error})},500)},this.onSessionDeleteRequest=async(t,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:t,reason:n.params}),await Promise.all([new Promise(a=>{this.client.core.relayer.once(pr.publish,async()=>{a(await this.deleteSession({topic:t,id:i}))})}),this.sendResult({id:i,topic:t,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:It("USER_DISCONNECTED")})])}catch(a){this.client.logger.error(a)}},this.onSessionRequest=async(t,n)=>{const{id:i,params:a}=n;try{this.isValidRequest(Ir({topic:t},a));const c=bs(JSON.stringify(Ss("wc_sessionRequest",a,i))),u=this.client.session.get(t),f=await this.getVerifyContext(c,u.peer.metadata),h={id:i,topic:t,params:a,verifyContext:f};await this.setPendingSessionRequest(h),this.addSessionRequestToSessionRequestQueue(h),this.processSessionRequestQueue()}catch(c){await this.sendError(i,t,c),this.client.logger.error(c)}},this.onSessionRequestResponse=(t,n)=>{const{id:i}=n;Mn(n)?this.events.emit(qt("session_request",i),{result:n.result}):dn(n)&&this.events.emit(qt("session_request",i),{error:n.error})},this.onSessionEventRequest=async(t,n)=>{const{id:i,params:a}=n;try{const c=`${t}_session_event_${a.event.name}`,u=Ma.get(c);if(u&&this.isRequestOutOfSync(u,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(Ir({topic:t},a)),this.client.events.emit("session_event",{id:i,topic:t,params:a}),Ma.set(c,i)}catch(c){await this.sendError(i,t,c),this.client.logger.error(c)}},this.addSessionRequestToSessionRequestQueue=t=>{this.sessionRequestQueue.queue.push(t)},this.cleanupAfterResponse=t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Bn.idle,this.processSessionRequestQueue()},ye.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:t,error:n})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(a=>a.topic===t&&a.request.method==="wc_sessionRequest").forEach(a=>{this.events.emit(qt("session_request",a.request.id),{error:n})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===Bn.active){this.client.logger.info("session request queue is already active.");return}const t=this.sessionRequestQueue.queue[0];if(!t){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Bn.active,this.client.events.emit("session_request",t)}catch(n){this.client.logger.error(n)}},this.onPairingCreated=t=>{if(t.active)return;const n=this.client.proposal.getAll().find(i=>i.pairingTopic===t.topic);n&&this.onSessionProposeRequest(t.topic,Ss("wc_sessionPropose",{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties},n.id))},this.isValidConnect=async t=>{if(!Rr(t)){const{message:f}=ue("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(f)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:a,sessionProperties:c,relays:u}=t;if(_r(n)||await this.isValidPairingTopic(n),!Q_(u,!0)){const{message:f}=ue("MISSING_OR_INVALID",`connect() relays: ${u}`);throw new Error(f)}!_r(i)&&xo(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!_r(a)&&xo(a)!==0&&this.validateNamespaces(a,"optionalNamespaces"),_r(c)||this.validateSessionProps(c,"sessionProperties")},this.validateNamespaces=(t,n)=>{const i=Z_(t,"connect()",n);if(i)throw new Error(i.message)},this.isValidApprove=async t=>{if(!Rr(t))throw new Error(ue("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:n,namespaces:i,relayProtocol:a,sessionProperties:c}=t;await this.isValidProposalId(n);const u=this.client.proposal.get(n),f=hu(i,"approve()");if(f)throw new Error(f.message);const h=cp(u.requiredNamespaces,i,"approve()");if(h)throw new Error(h.message);if(!ir(a,!0)){const{message:m}=ue("MISSING_OR_INVALID",`approve() relayProtocol: ${a}`);throw new Error(m)}_r(c)||this.validateSessionProps(c,"sessionProperties")},this.isValidReject=async t=>{if(!Rr(t)){const{message:a}=ue("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(a)}const{id:n,reason:i}=t;if(await this.isValidProposalId(n),!e3(i)){const{message:a}=ue("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(a)}},this.isValidSessionSettleRequest=t=>{if(!Rr(t)){const{message:h}=ue("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(h)}const{relay:n,controller:i,namespaces:a,expiry:c}=t;if(!op(n)){const{message:h}=ue("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const u=W_(i,"onSessionSettleRequest()");if(u)throw new Error(u.message);const f=hu(a,"onSessionSettleRequest()");if(f)throw new Error(f.message);if(ii(c)){const{message:h}=ue("EXPIRED","onSessionSettleRequest()");throw new Error(h)}},this.isValidUpdate=async t=>{if(!Rr(t)){const{message:f}=ue("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(f)}const{topic:n,namespaces:i}=t;await this.isValidSessionTopic(n);const a=this.client.session.get(n),c=hu(i,"update()");if(c)throw new Error(c.message);const u=cp(a.requiredNamespaces,i,"update()");if(u)throw new Error(u.message)},this.isValidExtend=async t=>{if(!Rr(t)){const{message:i}=ue("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(i)}const{topic:n}=t;await this.isValidSessionTopic(n)},this.isValidRequest=async t=>{if(!Rr(t)){const{message:f}=ue("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(f)}const{topic:n,request:i,chainId:a,expiry:c}=t;await this.isValidSessionTopic(n);const{namespaces:u}=this.client.session.get(n);if(!ap(u,a)){const{message:f}=ue("MISSING_OR_INVALID",`request() chainId: ${a}`);throw new Error(f)}if(!t3(i)){const{message:f}=ue("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(f)}if(!i3(u,a,i.method)){const{message:f}=ue("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(f)}if(c&&!c3(c,Hu)){const{message:f}=ue("MISSING_OR_INVALID",`request() expiry: ${c}. Expiry must be a number (in seconds) between ${Hu.min} and ${Hu.max}`);throw new Error(f)}},this.isValidRespond=async t=>{var n;if(!Rr(t)){const{message:c}=ue("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(c)}const{topic:i,response:a}=t;try{await this.isValidSessionTopic(i)}catch(c){throw(n=t?.response)!=null&&n.id&&this.cleanupAfterResponse(t),c}if(!r3(a)){const{message:c}=ue("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(a)}`);throw new Error(c)}},this.isValidPing=async t=>{if(!Rr(t)){const{message:i}=ue("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(i)}const{topic:n}=t;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async t=>{if(!Rr(t)){const{message:u}=ue("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(u)}const{topic:n,event:i,chainId:a}=t;await this.isValidSessionTopic(n);const{namespaces:c}=this.client.session.get(n);if(!ap(c,a)){const{message:u}=ue("MISSING_OR_INVALID",`emit() chainId: ${a}`);throw new Error(u)}if(!n3(i)){const{message:u}=ue("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(u)}if(!s3(c,a,i.name)){const{message:u}=ue("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(u)}},this.isValidDisconnect=async t=>{if(!Rr(t)){const{message:i}=ue("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(i)}const{topic:n}=t;await this.isValidSessionOrPairingTopic(n)},this.getVerifyContext=async(t,n)=>{const i={verified:{verifyUrl:n.verifyUrl||Cs,validation:"UNKNOWN",origin:n.url||""}};try{const a=await this.client.core.verify.resolve({attestationId:t,verifyUrl:n.verifyUrl});a&&(i.verified.origin=a.origin,i.verified.isScam=a.isScam,i.verified.validation=a.origin===new URL(n.url).origin?"VALID":"INVALID")}catch(a){this.client.logger.info(a)}return this.client.logger.info(`Verify context: ${JSON.stringify(i)}`),i},this.validateSessionProps=(t,n)=>{Object.values(t).forEach(i=>{if(!ir(i,!1)){const{message:a}=ue("MISSING_OR_INVALID",`${n} must be in Record<string, string> format. Received: ${JSON.stringify(i)}`);throw new Error(a)}})}}async isInitialized(){if(!this.initialized){const{message:e}=ue("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(pr.message,async e=>{const{topic:t,message:n}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(n)))return;const i=await this.client.core.crypto.decode(t,n);try{Tu(i)?(this.client.core.history.set(t,i),this.onRelayEventRequest({topic:t,payload:i})):Wa(i)?(await this.client.core.history.resolve(i),await this.onRelayEventResponse({topic:t,payload:i}),this.client.core.history.delete(t,i.id)):this.onRelayEventUnknownPayload({topic:t,payload:i})}catch(a){this.client.logger.error(a)}})}registerExpirerEvents(){this.client.core.expirer.on(en.expired,async e=>{const{topic:t,id:n}=ep(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,ue("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(No.create,e=>this.onPairingCreated(e))}isValidPairingTopic(e){if(!ir(e,!1)){const{message:t}=ue("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=ue("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(ii(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=ue("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!ir(e,!1)){const{message:t}=ue("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(!this.client.session.keys.includes(e)){const{message:t}=ue("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(ii(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=ue("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=ue("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}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(ir(e,!1)){const{message:t}=ue("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=ue("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!X_(e)){const{message:t}=ue("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=ue("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(ii(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=ue("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class V8 extends Va{constructor(e,t){super(e,t,M8,qu),this.core=e,this.logger=t}}class G8 extends Va{constructor(e,t){super(e,t,U8,qu),this.core=e,this.logger=t}}class Y8 extends Va{constructor(e,t){super(e,t,F8,qu,n=>n.id),this.core=e,this.logger=t}}class Wu extends Q5{constructor(e){super(e),this.protocol=R1,this.version=N1,this.name=zu.name,this.events=new lr.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||zu.name,this.metadata=e?.metadata||p_();const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Xe.pino(Xe.getDefaultLoggerOptions({level:e?.logger||zu.logger}));this.core=e?.core||new L8(e),this.logger=Xe.generateChildLogger(t,this.name),this.session=new G8(this.core,this.logger),this.proposal=new V8(this.core,this.logger),this.pendingRequest=new Y8(this.core,this.logger),this.engine=new K8(this)}static async init(e){const t=new Wu(e);return await t.initialize(),t}get context(){return Xe.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 Ku={exports:{}};(function(r,e){var t=typeof self<"u"?self:yr,n=function(){function a(){this.fetch=!1,this.DOMException=t.DOMException}return a.prototype=t,new a}();(function(a){(function(c){var u={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function f(I){return I&&DataView.prototype.isPrototypeOf(I)}if(u.arrayBuffer)var h=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],m=ArrayBuffer.isView||function(I){return I&&h.indexOf(Object.prototype.toString.call(I))>-1};function w(I){if(typeof I!="string"&&(I=String(I)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(I))throw new TypeError("Invalid character in header field name");return I.toLowerCase()}function y(I){return typeof I!="string"&&(I=String(I)),I}function x(I){var N={next:function(){var X=I.shift();return{done:X===void 0,value:X}}};return u.iterable&&(N[Symbol.iterator]=function(){return N}),N}function S(I){this.map={},I instanceof S?I.forEach(function(N,X){this.append(X,N)},this):Array.isArray(I)?I.forEach(function(N){this.append(N[0],N[1])},this):I&&Object.getOwnPropertyNames(I).forEach(function(N){this.append(N,I[N])},this)}S.prototype.append=function(I,N){I=w(I),N=y(N);var X=this.map[I];this.map[I]=X?X+", "+N:N},S.prototype.delete=function(I){delete this.map[w(I)]},S.prototype.get=function(I){return I=w(I),this.has(I)?this.map[I]:null},S.prototype.has=function(I){return this.map.hasOwnProperty(w(I))},S.prototype.set=function(I,N){this.map[w(I)]=y(N)},S.prototype.forEach=function(I,N){for(var X in this.map)this.map.hasOwnProperty(X)&&I.call(N,this.map[X],X,this)},S.prototype.keys=function(){var I=[];return this.forEach(function(N,X){I.push(X)}),x(I)},S.prototype.values=function(){var I=[];return this.forEach(function(N){I.push(N)}),x(I)},S.prototype.entries=function(){var I=[];return this.forEach(function(N,X){I.push([X,N])}),x(I)},u.iterable&&(S.prototype[Symbol.iterator]=S.prototype.entries);function P(I){if(I.bodyUsed)return Promise.reject(new TypeError("Already read"));I.bodyUsed=!0}function U(I){return new Promise(function(N,X){I.onload=function(){N(I.result)},I.onerror=function(){X(I.error)}})}function j(I){var N=new FileReader,X=U(N);return N.readAsArrayBuffer(I),X}function A(I){var N=new FileReader,X=U(N);return N.readAsText(I),X}function T(I){for(var N=new Uint8Array(I),X=new Array(N.length),ee=0;ee<N.length;ee++)X[ee]=String.fromCharCode(N[ee]);return X.join("")}function C(I){if(I.slice)return I.slice(0);var N=new Uint8Array(I.byteLength);return N.set(new Uint8Array(I)),N.buffer}function $(){return this.bodyUsed=!1,this._initBody=function(I){this._bodyInit=I,I?typeof I=="string"?this._bodyText=I:u.blob&&Blob.prototype.isPrototypeOf(I)?this._bodyBlob=I:u.formData&&FormData.prototype.isPrototypeOf(I)?this._bodyFormData=I:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(I)?this._bodyText=I.toString():u.arrayBuffer&&u.blob&&f(I)?(this._bodyArrayBuffer=C(I.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(I)||m(I))?this._bodyArrayBuffer=C(I):this._bodyText=I=Object.prototype.toString.call(I):this._bodyText="",this.headers.get("content-type")||(typeof I=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(I)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var I=P(this);if(I)return I;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?P(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(j)}),this.text=function(){var I=P(this);if(I)return I;if(this._bodyBlob)return A(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(T(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(H)}),this.json=function(){return this.text().then(JSON.parse)},this}var E=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function d(I){var N=I.toUpperCase();return E.indexOf(N)>-1?N:I}function b(I,N){N=N||{};var X=N.body;if(I instanceof b){if(I.bodyUsed)throw new TypeError("Already read");this.url=I.url,this.credentials=I.credentials,N.headers||(this.headers=new S(I.headers)),this.method=I.method,this.mode=I.mode,this.signal=I.signal,!X&&I._bodyInit!=null&&(X=I._bodyInit,I.bodyUsed=!0)}else this.url=String(I);if(this.credentials=N.credentials||this.credentials||"same-origin",(N.headers||!this.headers)&&(this.headers=new S(N.headers)),this.method=d(N.method||this.method||"GET"),this.mode=N.mode||this.mode||null,this.signal=N.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&X)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(X)}b.prototype.clone=function(){return new b(this,{body:this._bodyInit})};function H(I){var N=new FormData;return I.trim().split("&").forEach(function(X){if(X){var ee=X.split("="),Y=ee.shift().replace(/\+/g," "),J=ee.join("=").replace(/\+/g," ");N.append(decodeURIComponent(Y),decodeURIComponent(J))}}),N}function F(I){var N=new S,X=I.replace(/\r?\n[\t ]+/g," ");return X.split(/\r?\n/).forEach(function(ee){var Y=ee.split(":"),J=Y.shift().trim();if(J){var Q=Y.join(":").trim();N.append(J,Q)}}),N}$.call(b.prototype);function V(I,N){N||(N={}),this.type="default",this.status=N.status===void 0?200:N.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in N?N.statusText:"OK",this.headers=new S(N.headers),this.url=N.url||"",this._initBody(I)}$.call(V.prototype),V.prototype.clone=function(){return new V(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new S(this.headers),url:this.url})},V.error=function(){var I=new V(null,{status:0,statusText:""});return I.type="error",I};var se=[301,302,303,307,308];V.redirect=function(I,N){if(se.indexOf(N)===-1)throw new RangeError("Invalid status code");return new V(null,{status:N,headers:{location:I}})},c.DOMException=a.DOMException;try{new c.DOMException}catch{c.DOMException=function(N,X){this.message=N,this.name=X;var ee=Error(N);this.stack=ee.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function ce(I,N){return new Promise(function(X,ee){var Y=new b(I,N);if(Y.signal&&Y.signal.aborted)return ee(new c.DOMException("Aborted","AbortError"));var J=new XMLHttpRequest;function Q(){J.abort()}J.onload=function(){var ie={status:J.status,statusText:J.statusText,headers:F(J.getAllResponseHeaders()||"")};ie.url="responseURL"in J?J.responseURL:ie.headers.get("X-Request-URL");var Ee="response"in J?J.response:J.responseText;X(new V(Ee,ie))},J.onerror=function(){ee(new TypeError("Network request failed"))},J.ontimeout=function(){ee(new TypeError("Network request failed"))},J.onabort=function(){ee(new c.DOMException("Aborted","AbortError"))},J.open(Y.method,Y.url,!0),Y.credentials==="include"?J.withCredentials=!0:Y.credentials==="omit"&&(J.withCredentials=!1),"responseType"in J&&u.blob&&(J.responseType="blob"),Y.headers.forEach(function(ie,Ee){J.setRequestHeader(Ee,ie)}),Y.signal&&(Y.signal.addEventListener("abort",Q),J.onreadystatechange=function(){J.readyState===4&&Y.signal.removeEventListener("abort",Q)}),J.send(typeof Y._bodyInit>"u"?null:Y._bodyInit)})}return ce.polyfill=!0,a.fetch||(a.fetch=ce,a.Headers=S,a.Request=b,a.Response=V),c.Headers=S,c.Request=b,c.Response=V,c.fetch=ce,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,r.exports=e})(Ku,Ku.exports);var B1=Oy(Ku.exports);const k1={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},q1=10;class oi{constructor(e,t=!1){if(this.url=e,this.disableProviderPing=t,this.events=new lr.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!Vp(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=t}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}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,t){this.isAvailable||await this.register();try{const n=ji(e),a=await(await B1(this.url,Object.assign(Object.assign({},k1),{body:n}))).json();this.onPayload({data:a})}catch(n){this.onError(e.id,n)}}async register(e=this.url){if(!Vp(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+1),new Promise((n,i)=>{this.events.once("register_error",a=>{this.resetMaxListeners(),i(a)}),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 t=ji({id:1,jsonrpc:"2.0",method:"test",params:[]});await B1(e,Object.assign(Object.assign({},k1),{body:t}))}this.onOpen()}catch(t){const n=this.parseError(t);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 t=typeof e.data=="string"?Do(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const n=this.parseError(t),i=n.message||n.toString(),a=Ha(e,i);this.events.emit("payload",a)}parseError(e,t=this.url){return Bp(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>q1&&this.events.setMaxListeners(q1)}}const z1="error",J8="wss://relay.walletconnect.com",Z8="wc",Q8="universal_provider",H1=`${Z8}@2:${Q8}:`,X8="https://rpc.walletconnect.com/v1/",kn={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Mo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Vu={exports:{}};/**
|
|
60
60
|
* @license
|
|
61
61
|
* Lodash <https://lodash.com/>
|
|
62
62
|
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
|