@walletconnect/ethereum-provider 2.10.4-rc.0 → 2.10.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/package.json +5 -5
package/dist/index.umd.js
CHANGED
|
@@ -69,7 +69,7 @@
|
|
|
69
69
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
70
70
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
71
71
|
PERFORMANCE OF THIS SOFTWARE.
|
|
72
|
-
***************************************************************************** */var bc=function(r,e){return bc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var o in i)i.hasOwnProperty(o)&&(t[o]=i[o])},bc(r,e)};function Pm(r,e){bc(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var mc=function(){return mc=Object.assign||function(e){for(var t,i=1,o=arguments.length;i<o;i++){t=arguments[i];for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a])}return e},mc.apply(this,arguments)};function Cm(r,e){var t={};for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&e.indexOf(i)<0&&(t[i]=r[i]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,i=Object.getOwnPropertySymbols(r);o<i.length;o++)e.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(r,i[o])&&(t[i[o]]=r[i[o]]);return t}function Am(r,e,t,i){var o=arguments.length,a=o<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,u;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,i);else for(var f=r.length-1;f>=0;f--)(u=r[f])&&(a=(o<3?u(a):o>3?u(e,t,a):u(e,t))||a);return o>3&&a&&Object.defineProperty(e,t,a),a}function Tm(r,e){return function(t,i){e(t,i,r)}}function Rm(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function Nm(r,e,t,i){function o(a){return a instanceof t?a:new t(function(u){u(a)})}return new(t||(t=Promise))(function(a,u){function f(w){try{p(i.next(w))}catch(I){u(I)}}function v(w){try{p(i.throw(w))}catch(I){u(I)}}function p(w){w.done?a(w.value):o(w.value).then(f,v)}p((i=i.apply(r,e||[])).next())})}function $m(r,e){var t={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,o,a,u;return u={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(u[Symbol.iterator]=function(){return this}),u;function f(p){return function(w){return v([p,w])}}function v(p){if(i)throw new TypeError("Generator is already executing.");for(;t;)try{if(i=1,o&&(a=p[0]&2?o.return:p[0]?o.throw||((a=o.return)&&a.call(o),0):o.next)&&!(a=a.call(o,p[1])).done)return a;switch(o=0,a&&(p=[p[0]&2,a.value]),p[0]){case 0:case 1:a=p;break;case 4:return t.label++,{value:p[1],done:!1};case 5:t.label++,o=p[1],p=[0];continue;case 7:p=t.ops.pop(),t.trys.pop();continue;default:if(a=t.trys,!(a=a.length>0&&a[a.length-1])&&(p[0]===6||p[0]===2)){t=0;continue}if(p[0]===3&&(!a||p[1]>a[0]&&p[1]<a[3])){t.label=p[1];break}if(p[0]===6&&t.label<a[1]){t.label=a[1],a=p;break}if(a&&t.label<a[2]){t.label=a[2],t.ops.push(p);break}a[2]&&t.ops.pop(),t.trys.pop();continue}p=e.call(r,t)}catch(w){p=[6,w],o=0}finally{i=a=0}if(p[0]&5)throw p[1];return{value:p[0]?p[1]:void 0,done:!0}}}function Fm(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]}function Lm(r,e){for(var t in r)t!=="default"&&!e.hasOwnProperty(t)&&(e[t]=r[t])}function wc(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],i=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&i>=r.length&&(r=void 0),{value:r&&r[i++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function If(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i=t.call(r),o,a=[],u;try{for(;(e===void 0||e-- >0)&&!(o=i.next()).done;)a.push(o.value)}catch(f){u={error:f}}finally{try{o&&!o.done&&(t=i.return)&&t.call(i)}finally{if(u)throw u.error}}return a}function Um(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(If(arguments[e]));return r}function jm(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var i=Array(r),o=0,e=0;e<t;e++)for(var a=arguments[e],u=0,f=a.length;u<f;u++,o++)i[o]=a[u];return i}function ds(r){return this instanceof ds?(this.v=r,this):new ds(r)}function Mm(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(r,e||[]),o,a=[];return o={},u("next"),u("throw"),u("return"),o[Symbol.asyncIterator]=function(){return this},o;function u(S){i[S]&&(o[S]=function(C){return new Promise(function(R,B){a.push([S,C,R,B])>1||f(S,C)})})}function f(S,C){try{v(i[S](C))}catch(R){I(a[0][3],R)}}function v(S){S.value instanceof ds?Promise.resolve(S.value.v).then(p,w):I(a[0][2],S)}function p(S){f("next",S)}function w(S){f("throw",S)}function I(S,C){S(C),a.shift(),a.length&&f(a[0][0],a[0][1])}}function qm(r){var e,t;return e={},i("next"),i("throw",function(o){throw o}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(o,a){e[o]=r[o]?function(u){return(t=!t)?{value:ds(r[o](u)),done:o==="return"}:a?a(u):u}:a}}function Hm(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 wc=="function"?wc(r):r[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(a){t[a]=r[a]&&function(u){return new Promise(function(f,v){u=r[a](u),o(f,v,u.done,u.value)})}}function o(a,u,f,v){Promise.resolve(v).then(function(p){a({value:p,done:f})},u)}}function Bm(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function zm(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 Km(r){return r&&r.__esModule?r:{default:r}}function Vm(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function km(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 Gm=Object.freeze({__proto__:null,__extends:Pm,get __assign(){return mc},__rest:Cm,__decorate:Am,__param:Tm,__metadata:Rm,__awaiter:Nm,__generator:$m,__createBinding:Fm,__exportStar:Lm,__values:wc,__read:If,__spread:Um,__spreadArrays:jm,__await:ds,__asyncGenerator:Mm,__asyncDelegator:qm,__asyncValues:Hm,__makeTemplateObject:Bm,__importStar:zm,__importDefault:Km,__classPrivateFieldGet:Vm,__classPrivateFieldSet:km}),Wm=Bn(Gm),an={},Pf;function Ym(){if(Pf)return an;Pf=1,Object.defineProperty(an,"__esModule",{value:!0}),an.isBrowserCryptoAvailable=an.getSubtleCrypto=an.getBrowerCrypto=void 0;function r(){return Vt?.crypto||Vt?.msCrypto||{}}an.getBrowerCrypto=r;function e(){const i=r();return i.subtle||i.webkitSubtle}an.getSubtleCrypto=e;function t(){return!!r()&&!!e()}return an.isBrowserCryptoAvailable=t,an}var cn={},Cf;function Jm(){if(Cf)return cn;Cf=1,Object.defineProperty(cn,"__esModule",{value:!0}),cn.isBrowser=cn.isNode=cn.isReactNative=void 0;function r(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}cn.isReactNative=r;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}cn.isNode=e;function t(){return!r()&&!e()}return cn.isBrowser=t,cn}(function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=Wm;e.__exportStar(Ym(),r),e.__exportStar(Jm(),r)})(Of);function Ec(r=3){const e=Date.now()*Math.pow(10,r),t=Math.floor(Math.random()*Math.pow(10,r));return e+t}function Af(r=6){return BigInt(Ec(r))}function Ei(r,e,t){return{id:t||Ec(),jsonrpc:"2.0",method:r,params:e}}function Dc(r,e){return{id:r,jsonrpc:"2.0",result:e}}function oo(r,e,t){return{id:r,jsonrpc:"2.0",error:Qm(e,t)}}function Qm(r,e){return typeof r>"u"?Sf(Ef):(typeof r=="string"&&(r=Object.assign(Object.assign({},Sf(_c)),{message:r})),typeof e<"u"&&(r.data=e),Om(r.code)&&(r=Im(r.code)),r)}class Xm{}class Zm extends Xm{constructor(){super()}}class ew extends Zm{constructor(e){super()}}const tw="^https?:",rw="^wss?:";function nw(r){const e=r.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Tf(r,e){const t=nw(r);return typeof t>"u"?!1:new RegExp(e).test(t)}function Rf(r){return Tf(r,tw)}function Nf(r){return Tf(r,rw)}function iw(r){return new RegExp("wss?://localhost(:d{2,5})?").test(r)}function $f(r){return typeof r=="object"&&"id"in r&&"jsonrpc"in r&&r.jsonrpc==="2.0"}function Sc(r){return $f(r)&&"method"in r}function ao(r){return $f(r)&&(un(r)||zr(r))}function un(r){return"result"in r}function zr(r){return"error"in r}class hn extends ew{constructor(e){super(e),this.events=new Yt.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(Ei(e.method,e.params||[],e.id||Af().toString()),t)}async requestStrict(e,t){return new Promise(async(i,o)=>{if(!this.connection.connected)try{await this.open()}catch(a){o(a)}this.events.on(`${e.id}`,a=>{zr(a)?o(a.error):i(a.result)});try{await this.connection.send(e,t)}catch(a){o(a)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ao(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 sw=()=>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"),ow=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Ff=r=>r.split("?")[0],Lf=10,aw=sw();class cw{constructor(e){if(this.url=e,this.events=new Yt.exports.EventEmitter,this.registering=!1,!Nf(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=i=>{this.onClose(i),e()},this.socket.close()})}async send(e,t){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ls(e))}catch(i){this.onError(e.id,i)}}register(e=this.url){if(!Nf(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((i,o)=>{this.events.once("register_error",a=>{this.resetMaxListeners(),o(a)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return o(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((t,i)=>{const o=Of.isReactNative()?void 0:{rejectUnauthorized:!iw(e)},a=new aw(e,[],o);ow()?a.onerror=u=>{const f=u;i(this.emitError(f.error))}:a.on("error",u=>{i(this.emitError(u))}),a.onopen=()=>{this.onOpen(a),t(a)}})}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"?vc(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),o=i.message||i.toString(),a=oo(e,o);this.events.emit("payload",a)}parseError(e,t=this.url){return xf(e,Ff(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Lf&&this.events.setMaxListeners(Lf)}emitError(e){const t=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Ff(this.url)}`));return this.events.emit("register_error",t),t}}var xc={exports:{}};(function(r,e){var t=200,i="__lodash_hash_undefined__",o=1,a=2,u=9007199254740991,f="[object Arguments]",v="[object Array]",p="[object AsyncFunction]",w="[object Boolean]",I="[object Date]",S="[object Error]",C="[object Function]",R="[object GeneratorFunction]",B="[object Map]",K="[object Number]",se="[object Null]",$="[object Object]",U="[object Promise]",x="[object Proxy]",T="[object RegExp]",E="[object Set]",h="[object String]",b="[object Symbol]",G="[object Undefined]",Y="[object WeakMap]",ie="[object ArrayBuffer]",ce="[object DataView]",de="[object Float32Array]",m="[object Float64Array]",P="[object Int8Array]",ee="[object Int16Array]",Q="[object Int32Array]",V="[object Uint8Array]",k="[object Uint8ClampedArray]",J="[object Uint16Array]",re="[object Uint32Array]",me=/[\\^$.*+?()[\]{}|]/g,oe=/^\[object .+?Constructor\]$/,we=/^(?:0|[1-9]\d*)$/,le={};le[de]=le[m]=le[P]=le[ee]=le[Q]=le[V]=le[k]=le[J]=le[re]=!0,le[f]=le[v]=le[ie]=le[w]=le[ce]=le[I]=le[S]=le[C]=le[B]=le[K]=le[$]=le[T]=le[E]=le[h]=le[Y]=!1;var _e=typeof Vt=="object"&&Vt&&Vt.Object===Object&&Vt,H=typeof self=="object"&&self&&self.Object===Object&&self,q=_e||H||Function("return this")(),F=e&&!e.nodeType&&e,d=F&&!0&&r&&!r.nodeType&&r,A=d&&d.exports===F,ae=A&&_e.process,fe=function(){try{return ae&&ae.binding&&ae.binding("util")}catch{}}(),xe=fe&&fe.isTypedArray;function Be(D,L){for(var te=-1,pe=D==null?0:D.length,ct=0,Te=[];++te<pe;){var dt=D[te];L(dt,te,D)&&(Te[ct++]=dt)}return Te}function Ve(D,L){for(var te=-1,pe=L.length,ct=D.length;++te<pe;)D[ct+te]=L[te];return D}function Ue(D,L){for(var te=-1,pe=D==null?0:D.length;++te<pe;)if(L(D[te],te,D))return!0;return!1}function vt(D,L){for(var te=-1,pe=Array(D);++te<D;)pe[te]=L(te);return pe}function yt(D){return function(L){return D(L)}}function Me(D,L){return D.has(L)}function Oe(D,L){return D?.[L]}function $e(D){var L=-1,te=Array(D.size);return D.forEach(function(pe,ct){te[++L]=[ct,pe]}),te}function Fe(D,L){return function(te){return D(L(te))}}function qe(D){var L=-1,te=Array(D.size);return D.forEach(function(pe){te[++L]=pe}),te}var Pe=Array.prototype,Le=Function.prototype,Se=Object.prototype,Ce=q["__core-js_shared__"],ze=Le.toString,Ie=Se.hasOwnProperty,ke=function(){var D=/[^.]+$/.exec(Ce&&Ce.keys&&Ce.keys.IE_PROTO||"");return D?"Symbol(src)_1."+D:""}(),We=Se.toString,et=RegExp("^"+ze.call(Ie).replace(me,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),tt=A?q.Buffer:void 0,Qe=q.Symbol,cr=q.Uint8Array,yr=Se.propertyIsEnumerable,en=Pe.splice,ur=Qe?Qe.toStringTag:void 0,pn=Object.getOwnPropertySymbols,Tn=tt?tt.isBuffer:void 0,Xn=Fe(Object.keys,Object),Dt=xr(q,"DataView"),_t=xr(q,"Map"),St=xr(q,"Promise"),xt=xr(q,"Set"),wt=xr(q,"WeakMap"),bt=xr(Object,"create"),Lt=vn(Dt),Ut=vn(_t),Ot=vn(St),jt=vn(xt),It=vn(wt),Tt=Qe?Qe.prototype:void 0,Pt=Tt?Tt.valueOf:void 0;function ft(D){var L=-1,te=D==null?0:D.length;for(this.clear();++L<te;){var pe=D[L];this.set(pe[0],pe[1])}}function Mt(){this.__data__=bt?bt(null):{},this.size=0}function qt(D){var L=this.has(D)&&delete this.__data__[D];return this.size-=L?1:0,L}function Vc(D){var L=this.__data__;if(bt){var te=L[D];return te===i?void 0:te}return Ie.call(L,D)?L[D]:void 0}function kc(D){var L=this.__data__;return bt?L[D]!==void 0:Ie.call(L,D)}function Gc(D,L){var te=this.__data__;return this.size+=this.has(D)?0:1,te[D]=bt&&L===void 0?i:L,this}ft.prototype.clear=Mt,ft.prototype.delete=qt,ft.prototype.get=Vc,ft.prototype.has=kc,ft.prototype.set=Gc;function Rr(D){var L=-1,te=D==null?0:D.length;for(this.clear();++L<te;){var pe=D[L];this.set(pe[0],pe[1])}}function Wc(){this.__data__=[],this.size=0}function Yc(D){var L=this.__data__,te=Zn(L,D);if(te<0)return!1;var pe=L.length-1;return te==pe?L.pop():en.call(L,te,1),--this.size,!0}function Jc(D){var L=this.__data__,te=Zn(L,D);return te<0?void 0:L[te][1]}function Qc(D){return Zn(this.__data__,D)>-1}function Xc(D,L){var te=this.__data__,pe=Zn(te,D);return pe<0?(++this.size,te.push([D,L])):te[pe][1]=L,this}Rr.prototype.clear=Wc,Rr.prototype.delete=Yc,Rr.prototype.get=Jc,Rr.prototype.has=Qc,Rr.prototype.set=Xc;function gn(D){var L=-1,te=D==null?0:D.length;for(this.clear();++L<te;){var pe=D[L];this.set(pe[0],pe[1])}}function Si(){this.size=0,this.__data__={hash:new ft,map:new(_t||Rr),string:new ft}}function Zc(D){var L=Rn(this,D).delete(D);return this.size-=L?1:0,L}function xi(D){return Rn(this,D).get(D)}function eu(D){return Rn(this,D).has(D)}function tu(D,L){var te=Rn(this,D),pe=te.size;return te.set(D,L),this.size+=te.size==pe?0:1,this}gn.prototype.clear=Si,gn.prototype.delete=Zc,gn.prototype.get=xi,gn.prototype.has=eu,gn.prototype.set=tu;function Oi(D){var L=-1,te=D==null?0:D.length;for(this.__data__=new gn;++L<te;)this.add(D[L])}function _o(D){return this.__data__.set(D,i),this}function bo(D){return this.__data__.has(D)}Oi.prototype.add=Oi.prototype.push=_o,Oi.prototype.has=bo;function Vr(D){var L=this.__data__=new Rr(D);this.size=L.size}function ru(){this.__data__=new Rr,this.size=0}function nu(D){var L=this.__data__,te=L.delete(D);return this.size=L.size,te}function iu(D){return this.__data__.get(D)}function su(D){return this.__data__.has(D)}function mo(D,L){var te=this.__data__;if(te instanceof Rr){var pe=te.__data__;if(!_t||pe.length<t-1)return pe.push([D,L]),this.size=++te.size,this;te=this.__data__=new gn(pe)}return te.set(D,L),this.size=te.size,this}Vr.prototype.clear=ru,Vr.prototype.delete=nu,Vr.prototype.get=iu,Vr.prototype.has=su,Vr.prototype.set=mo;function wo(D,L){var te=Ci(D),pe=!te&&No(D),ct=!te&&!pe&&Ss(D),Te=!te&&!pe&&!ct&&Lo(D),dt=te||pe||ct||Te,Ht=dt?vt(D.length,String):[],Xe=Ht.length;for(var ut in D)(L||Ie.call(D,ut))&&!(dt&&(ut=="length"||ct&&(ut=="offset"||ut=="parent")||Te&&(ut=="buffer"||ut=="byteLength"||ut=="byteOffset")||Po(ut,Xe)))&&Ht.push(ut);return Ht}function Zn(D,L){for(var te=D.length;te--;)if(Ro(D[te][0],L))return te;return-1}function Es(D,L,te){var pe=L(D);return Ci(D)?pe:Ve(pe,te(D))}function ei(D){return D==null?D===void 0?G:se:ur&&ur in Object(D)?Oo(D):cu(D)}function Ds(D){return ri(D)&&ei(D)==f}function ti(D,L,te,pe,ct){return D===L?!0:D==null||L==null||!ri(D)&&!ri(L)?D!==D&&L!==L:Eo(D,L,te,pe,ti,ct)}function Eo(D,L,te,pe,ct,Te){var dt=Ci(D),Ht=Ci(L),Xe=dt?v:tn(D),ut=Ht?v:tn(L);Xe=Xe==f?$:Xe,ut=ut==f?$:ut;var Rt=Xe==$,_r=ut==$,Bt=Xe==ut;if(Bt&&Ss(D)){if(!Ss(L))return!1;dt=!0,Rt=!1}if(Bt&&!Rt)return Te||(Te=new Vr),dt||Lo(D)?Ii(D,L,te,pe,ct,Te):au(D,L,Xe,te,pe,ct,Te);if(!(te&o)){var pt=Rt&&Ie.call(D,"__wrapped__"),hr=_r&&Ie.call(L,"__wrapped__");if(pt||hr){var kr=pt?D.value():D,Nr=hr?L.value():L;return Te||(Te=new Vr),ct(kr,Nr,te,pe,Te)}}return Bt?(Te||(Te=new Vr),xo(D,L,te,pe,ct,Te)):!1}function ou(D){if(!Fo(D)||Ao(D))return!1;var L=Ai(D)?et:oe;return L.test(vn(D))}function Do(D){return ri(D)&&$o(D.length)&&!!le[ei(D)]}function So(D){if(!To(D))return Xn(D);var L=[];for(var te in Object(D))Ie.call(D,te)&&te!="constructor"&&L.push(te);return L}function Ii(D,L,te,pe,ct,Te){var dt=te&o,Ht=D.length,Xe=L.length;if(Ht!=Xe&&!(dt&&Xe>Ht))return!1;var ut=Te.get(D);if(ut&&Te.get(L))return ut==L;var Rt=-1,_r=!0,Bt=te&a?new Oi:void 0;for(Te.set(D,L),Te.set(L,D);++Rt<Ht;){var pt=D[Rt],hr=L[Rt];if(pe)var kr=dt?pe(hr,pt,Rt,L,D,Te):pe(pt,hr,Rt,D,L,Te);if(kr!==void 0){if(kr)continue;_r=!1;break}if(Bt){if(!Ue(L,function(Nr,rn){if(!Me(Bt,rn)&&(pt===Nr||ct(pt,Nr,te,pe,Te)))return Bt.push(rn)})){_r=!1;break}}else if(!(pt===hr||ct(pt,hr,te,pe,Te))){_r=!1;break}}return Te.delete(D),Te.delete(L),_r}function au(D,L,te,pe,ct,Te,dt){switch(te){case ce:if(D.byteLength!=L.byteLength||D.byteOffset!=L.byteOffset)return!1;D=D.buffer,L=L.buffer;case ie:return!(D.byteLength!=L.byteLength||!Te(new cr(D),new cr(L)));case w:case I:case K:return Ro(+D,+L);case S:return D.name==L.name&&D.message==L.message;case T:case h:return D==L+"";case B:var Ht=$e;case E:var Xe=pe&o;if(Ht||(Ht=qe),D.size!=L.size&&!Xe)return!1;var ut=dt.get(D);if(ut)return ut==L;pe|=a,dt.set(D,L);var Rt=Ii(Ht(D),Ht(L),pe,ct,Te,dt);return dt.delete(D),Rt;case b:if(Pt)return Pt.call(D)==Pt.call(L)}return!1}function xo(D,L,te,pe,ct,Te){var dt=te&o,Ht=Pi(D),Xe=Ht.length,ut=Pi(L),Rt=ut.length;if(Xe!=Rt&&!dt)return!1;for(var _r=Xe;_r--;){var Bt=Ht[_r];if(!(dt?Bt in L:Ie.call(L,Bt)))return!1}var pt=Te.get(D);if(pt&&Te.get(L))return pt==L;var hr=!0;Te.set(D,L),Te.set(L,D);for(var kr=dt;++_r<Xe;){Bt=Ht[_r];var Nr=D[Bt],rn=L[Bt];if(pe)var xs=dt?pe(rn,Nr,Bt,L,D,Te):pe(Nr,rn,Bt,D,L,Te);if(!(xs===void 0?Nr===rn||ct(Nr,rn,te,pe,Te):xs)){hr=!1;break}kr||(kr=Bt=="constructor")}if(hr&&!kr){var ni=D.constructor,Gt=L.constructor;ni!=Gt&&"constructor"in D&&"constructor"in L&&!(typeof ni=="function"&&ni instanceof ni&&typeof Gt=="function"&&Gt instanceof Gt)&&(hr=!1)}return Te.delete(D),Te.delete(L),hr}function Pi(D){return Es(D,lu,Io)}function Rn(D,L){var te=D.__data__;return Co(L)?te[typeof L=="string"?"string":"hash"]:te.map}function xr(D,L){var te=Oe(D,L);return ou(te)?te:void 0}function Oo(D){var L=Ie.call(D,ur),te=D[ur];try{D[ur]=void 0;var pe=!0}catch{}var ct=We.call(D);return pe&&(L?D[ur]=te:delete D[ur]),ct}var Io=pn?function(D){return D==null?[]:(D=Object(D),Be(pn(D),function(L){return yr.call(D,L)}))}:at,tn=ei;(Dt&&tn(new Dt(new ArrayBuffer(1)))!=ce||_t&&tn(new _t)!=B||St&&tn(St.resolve())!=U||xt&&tn(new xt)!=E||wt&&tn(new wt)!=Y)&&(tn=function(D){var L=ei(D),te=L==$?D.constructor:void 0,pe=te?vn(te):"";if(pe)switch(pe){case Lt:return ce;case Ut:return B;case Ot:return U;case jt:return E;case It:return Y}return L});function Po(D,L){return L=L??u,!!L&&(typeof D=="number"||we.test(D))&&D>-1&&D%1==0&&D<L}function Co(D){var L=typeof D;return L=="string"||L=="number"||L=="symbol"||L=="boolean"?D!=="__proto__":D===null}function Ao(D){return!!ke&&ke in D}function To(D){var L=D&&D.constructor,te=typeof L=="function"&&L.prototype||Se;return D===te}function cu(D){return We.call(D)}function vn(D){if(D!=null){try{return ze.call(D)}catch{}try{return D+""}catch{}}return""}function Ro(D,L){return D===L||D!==D&&L!==L}var No=Ds(function(){return arguments}())?Ds:function(D){return ri(D)&&Ie.call(D,"callee")&&!yr.call(D,"callee")},Ci=Array.isArray;function uu(D){return D!=null&&$o(D.length)&&!Ai(D)}var Ss=Tn||ot;function hu(D,L){return ti(D,L)}function Ai(D){if(!Fo(D))return!1;var L=ei(D);return L==C||L==R||L==p||L==x}function $o(D){return typeof D=="number"&&D>-1&&D%1==0&&D<=u}function Fo(D){var L=typeof D;return D!=null&&(L=="object"||L=="function")}function ri(D){return D!=null&&typeof D=="object"}var Lo=xe?yt(xe):Do;function lu(D){return uu(D)?wo(D):So(D)}function at(){return[]}function ot(){return!1}r.exports=hu})(xc,xc.exports);var uw=xc.exports,hw=Object.defineProperty,Uf=Object.getOwnPropertySymbols,lw=Object.prototype.hasOwnProperty,fw=Object.prototype.propertyIsEnumerable,jf=(r,e,t)=>e in r?hw(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ar=(r,e)=>{for(var t in e||(e={}))lw.call(e,t)&&jf(r,t,e[t]);if(Uf)for(var t of Uf(e))fw.call(e,t)&&jf(r,t,e[t]);return r};function dw(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var o=0;o<r.length;o++){var a=r.charAt(o),u=a.charCodeAt(0);if(t[u]!==255)throw new TypeError(a+" is ambiguous");t[u]=o}var f=r.length,v=r.charAt(0),p=Math.log(f)/Math.log(256),w=Math.log(256)/Math.log(f);function I(R){if(R instanceof Uint8Array||(ArrayBuffer.isView(R)?R=new Uint8Array(R.buffer,R.byteOffset,R.byteLength):Array.isArray(R)&&(R=Uint8Array.from(R))),!(R instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(R.length===0)return"";for(var B=0,K=0,se=0,$=R.length;se!==$&&R[se]===0;)se++,B++;for(var U=($-se)*w+1>>>0,x=new Uint8Array(U);se!==$;){for(var T=R[se],E=0,h=U-1;(T!==0||E<K)&&h!==-1;h--,E++)T+=256*x[h]>>>0,x[h]=T%f>>>0,T=T/f>>>0;if(T!==0)throw new Error("Non-zero carry");K=E,se++}for(var b=U-K;b!==U&&x[b]===0;)b++;for(var G=v.repeat(B);b<U;++b)G+=r.charAt(x[b]);return G}function S(R){if(typeof R!="string")throw new TypeError("Expected String");if(R.length===0)return new Uint8Array;var B=0;if(R[B]!==" "){for(var K=0,se=0;R[B]===v;)K++,B++;for(var $=(R.length-B)*p+1>>>0,U=new Uint8Array($);R[B];){var x=t[R.charCodeAt(B)];if(x===255)return;for(var T=0,E=$-1;(x!==0||T<se)&&E!==-1;E--,T++)x+=f*U[E]>>>0,U[E]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");se=T,B++}if(R[B]!==" "){for(var h=$-se;h!==$&&U[h]===0;)h++;for(var b=new Uint8Array(K+($-h)),G=K;h!==$;)b[G++]=U[h++];return b}}}function C(R){var B=S(R);if(B)return B;throw new Error(`Non-${e} character`)}return{encode:I,decodeUnsafe:S,decode:C}}var pw=dw,gw=pw;const Mf=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")},vw=r=>new TextEncoder().encode(r),yw=r=>new TextDecoder().decode(r);class _w{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class bw{constructor(e,t,i){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=i}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 qf(this,e)}}class mw{constructor(e){this.decoders=e}or(e){return qf(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const qf=(r,e)=>new mw(ar(ar({},r.decoders||{[r.prefix]:r}),e.decoders||{[e.prefix]:e}));class ww{constructor(e,t,i,o){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=o,this.encoder=new _w(e,t,i),this.decoder=new bw(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const co=({name:r,prefix:e,encode:t,decode:i})=>new ww(r,e,t,i),ps=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:o}=gw(t,e);return co({prefix:r,name:e,encode:i,decode:a=>Mf(o(a))})},Ew=(r,e,t,i)=>{const o={};for(let w=0;w<e.length;++w)o[e[w]]=w;let a=r.length;for(;r[a-1]==="=";)--a;const u=new Uint8Array(a*t/8|0);let f=0,v=0,p=0;for(let w=0;w<a;++w){const I=o[r[w]];if(I===void 0)throw new SyntaxError(`Non-${i} character`);v=v<<t|I,f+=t,f>=8&&(f-=8,u[p++]=255&v>>f)}if(f>=t||255&v<<8-f)throw new SyntaxError("Unexpected end of data");return u},Dw=(r,e,t)=>{const i=e[e.length-1]==="=",o=(1<<t)-1;let a="",u=0,f=0;for(let v=0;v<r.length;++v)for(f=f<<8|r[v],u+=8;u>t;)u-=t,a+=e[o&f>>u];if(u&&(a+=e[o&f<<t-u]),i)for(;a.length*t&7;)a+="=";return a},Qt=({name:r,prefix:e,bitsPerChar:t,alphabet:i})=>co({prefix:e,name:r,encode(o){return Dw(o,i,t)},decode(o){return Ew(o,i,t,r)}}),Sw=co({prefix:"\0",name:"identity",encode:r=>yw(r),decode:r=>vw(r)});var xw=Object.freeze({__proto__:null,identity:Sw});const Ow=Qt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Iw=Object.freeze({__proto__:null,base2:Ow});const Pw=Qt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Cw=Object.freeze({__proto__:null,base8:Pw});const Aw=ps({prefix:"9",name:"base10",alphabet:"0123456789"});var Tw=Object.freeze({__proto__:null,base10:Aw});const Rw=Qt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Nw=Qt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var $w=Object.freeze({__proto__:null,base16:Rw,base16upper:Nw});const Fw=Qt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Lw=Qt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Uw=Qt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),jw=Qt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Mw=Qt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),qw=Qt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Hw=Qt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Bw=Qt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),zw=Qt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Kw=Object.freeze({__proto__:null,base32:Fw,base32upper:Lw,base32pad:Uw,base32padupper:jw,base32hex:Mw,base32hexupper:qw,base32hexpad:Hw,base32hexpadupper:Bw,base32z:zw});const Vw=ps({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),kw=ps({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Gw=Object.freeze({__proto__:null,base36:Vw,base36upper:kw});const Ww=ps({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Yw=ps({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Jw=Object.freeze({__proto__:null,base58btc:Ww,base58flickr:Yw});const Qw=Qt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Xw=Qt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zw=Qt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),eE=Qt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var tE=Object.freeze({__proto__:null,base64:Qw,base64pad:Xw,base64url:Zw,base64urlpad:eE});const Hf=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}"),rE=Hf.reduce((r,e,t)=>(r[t]=e,r),[]),nE=Hf.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function iE(r){return r.reduce((e,t)=>(e+=rE[t],e),"")}function sE(r){const e=[];for(const t of r){const i=nE[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const oE=co({prefix:"\u{1F680}",name:"base256emoji",encode:iE,decode:sE});var aE=Object.freeze({__proto__:null,base256emoji:oE}),cE=zf,Bf=128,uE=127,hE=~uE,lE=Math.pow(2,31);function zf(r,e,t){e=e||[],t=t||0;for(var i=t;r>=lE;)e[t++]=r&255|Bf,r/=128;for(;r&hE;)e[t++]=r&255|Bf,r>>>=7;return e[t]=r|0,zf.bytes=t-i+1,e}var fE=Oc,dE=128,Kf=127;function Oc(r,i){var t=0,i=i||0,o=0,a=i,u,f=r.length;do{if(a>=f)throw Oc.bytes=0,new RangeError("Could not decode varint");u=r[a++],t+=o<28?(u&Kf)<<o:(u&Kf)*Math.pow(2,o),o+=7}while(u>=dE);return Oc.bytes=a-i,t}var pE=Math.pow(2,7),gE=Math.pow(2,14),vE=Math.pow(2,21),yE=Math.pow(2,28),_E=Math.pow(2,35),bE=Math.pow(2,42),mE=Math.pow(2,49),wE=Math.pow(2,56),EE=Math.pow(2,63),DE=function(r){return r<pE?1:r<gE?2:r<vE?3:r<yE?4:r<_E?5:r<bE?6:r<mE?7:r<wE?8:r<EE?9:10},SE={encode:cE,decode:fE,encodingLength:DE},Vf=SE;const kf=(r,e,t=0)=>(Vf.encode(r,e,t),e),Gf=r=>Vf.encodingLength(r),Ic=(r,e)=>{const t=e.byteLength,i=Gf(r),o=i+Gf(t),a=new Uint8Array(o+t);return kf(r,a,0),kf(t,a,i),a.set(e,o),new xE(r,t,e,a)};class xE{constructor(e,t,i,o){this.code=e,this.size=t,this.digest=i,this.bytes=o}}const Wf=({name:r,code:e,encode:t})=>new OE(r,e,t);class OE{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Ic(this.code,t):t.then(i=>Ic(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Yf=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),IE=Wf({name:"sha2-256",code:18,encode:Yf("SHA-256")}),PE=Wf({name:"sha2-512",code:19,encode:Yf("SHA-512")});var CE=Object.freeze({__proto__:null,sha256:IE,sha512:PE});const Jf=0,AE="identity",Qf=Mf;var TE=Object.freeze({__proto__:null,identity:{code:Jf,name:AE,encode:Qf,digest:r=>Ic(Jf,Qf(r))}});new TextEncoder,new TextDecoder;const Xf=ar(ar(ar(ar(ar(ar(ar(ar(ar(ar({},xw),Iw),Cw),Tw),$w),Kw),Gw),Jw),tE),aE);ar(ar({},CE),TE);function Zf(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function RE(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Zf(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function ed(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const td=ed("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Pc=ed("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=RE(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),NE=ar({utf8:td,"utf-8":td,hex:Xf.base16,latin1:Pc,ascii:Pc,binary:Pc},Xf);function $E(r,e="utf8"){const t=NE[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Zf(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}const rd="wc",FE=2,Cc="core",Pn=`${rd}@2:${Cc}:`,LE={name:Cc,logger:"error"},UE={database:":memory:"},jE="crypto",nd="client_ed25519_seed",ME=ye.ONE_DAY,qE="keychain",HE="0.3",BE="messages",zE="0.3",KE=ye.SIX_HOURS,VE="publisher",id="irn",kE="error",sd="wss://relay.walletconnect.com",od="wss://relay.walletconnect.org",GE="relayer",er={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"},WE="_subscription",ln={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},YE=ye.ONE_SECOND,JE="2.10.4-rc.0",QE=1e4,XE="0.3",ZE="WALLETCONNECT_CLIENT_ID",Kr={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},e3="subscription",t3="0.3",r3=ye.FIVE_SECONDS*1e3,n3="pairing",i3="0.3",gs={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}}},vs={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Zr={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},s3="history",o3="0.3",a3="expirer",Tr={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},c3="0.3",Ac="verify-api",Di="https://verify.walletconnect.com",Tc="https://verify.walletconnect.org",u3=[Di,Tc];class h3{constructor(e,t){this.core=e,this.logger=t,this.keychain=new Map,this.name=qE,this.version=HE,this.initialized=!1,this.storagePrefix=Pn,this.init=async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}},this.has=i=>(this.isInitialized(),this.keychain.has(i)),this.set=async(i,o)=>{this.isInitialized(),this.keychain.set(i,o),await this.persist()},this.get=i=>{this.isInitialized();const o=this.keychain.get(i);if(typeof o>"u"){const{message:a}=he("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(a)}return o},this.del=async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()},this.core=e,this.logger=Je.generateChildLogger(t,this.name)}get context(){return Je.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,$l(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Fl(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=he("NOT_INITIALIZED",this.name);throw new Error(e)}}}class l3{constructor(e,t,i){this.core=e,this.logger=t,this.name=jE,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=o=>(this.isInitialized(),this.keychain.has(o)),this.getClientId=async()=>{this.isInitialized();const o=await this.getClientSeed(),a=wf(o);return mf(a.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const o=l_();return this.setPrivateKey(o.publicKey,o.privateKey)},this.signJWT=async o=>{this.isInitialized();const a=await this.getClientSeed(),u=wf(a),f=Ya();return await mm(f,o,ME,u)},this.generateSharedKey=(o,a,u)=>{this.isInitialized();const f=this.getPrivateKey(o),v=f_(f,a);return this.setSymKey(v,u)},this.setSymKey=async(o,a)=>{this.isInitialized();const u=a||d_(o);return await this.keychain.set(u,o),u},this.deleteKeyPair=async o=>{this.isInitialized(),await this.keychain.del(o)},this.deleteSymKey=async o=>{this.isInitialized(),await this.keychain.del(o)},this.encode=async(o,a,u)=>{this.isInitialized();const f=Cl(u),v=ls(a);if(Al(f)){const S=f.senderPublicKey,C=f.receiverPublicKey;o=await this.generateSharedKey(S,C)}const p=this.getSymKey(o),{type:w,senderPublicKey:I}=f;return g_({type:w,symKey:p,message:v,senderPublicKey:I})},this.decode=async(o,a,u)=>{this.isInitialized();const f=__(a,u);if(Al(f)){const v=f.receiverPublicKey,p=f.senderPublicKey;o=await this.generateSharedKey(v,p)}try{const v=this.getSymKey(o),p=v_({symKey:v,encoded:a});return vc(p)}catch(v){this.logger.error(`Failed to decode message from topic: '${o}', clientId: '${await this.getClientId()}'`),this.logger.error(v)}},this.getPayloadType=o=>{const a=Xs(o);return Ji(a.type)},this.getPayloadSenderPublicKey=o=>{const a=Xs(o);return a.senderPublicKey?nr(a.senderPublicKey,ir):void 0},this.core=e,this.logger=Je.generateChildLogger(t,this.name),this.keychain=i||new h3(this.core,this.logger)}get context(){return Je.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(nd)}catch{e=Ya(),await this.keychain.set(nd,e)}return $E(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=he("NOT_INITIALIZED",this.name);throw new Error(e)}}}class f3 extends Jb{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.name=BE,this.version=zE,this.initialized=!1,this.storagePrefix=Pn,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}},this.set=async(i,o)=>{this.isInitialized();const a=vi(o);let u=this.messages.get(i);return typeof u>"u"&&(u={}),typeof u[a]<"u"||(u[a]=o,this.messages.set(i,u),await this.persist()),a},this.get=i=>{this.isInitialized();let o=this.messages.get(i);return typeof o>"u"&&(o={}),o},this.has=(i,o)=>{this.isInitialized();const a=this.get(i),u=vi(o);return typeof a[u]<"u"},this.del=async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()},this.logger=Je.generateChildLogger(e,this.name),this.core=t}get context(){return Je.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,$l(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Fl(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=he("NOT_INITIALIZED",this.name);throw new Error(e)}}}class d3 extends Qb{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new Yt.exports.EventEmitter,this.name=VE,this.queue=new Map,this.publishTimeout=ye.toMiliseconds(ye.TEN_SECONDS),this.needsTransportRestart=!1,this.publish=async(i,o,a)=>{var u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:o,opts:a}});try{const f=a?.ttl||KE,v=Xa(a),p=a?.prompt||!1,w=a?.tag||0,I=a?.id||Af().toString(),S={topic:i,message:o,opts:{ttl:f,relay:v,prompt:p,tag:w,id:I}},C=setTimeout(()=>this.queue.set(I,S),this.publishTimeout);try{await await es(this.rpcPublish(i,o,f,v,p,w,I),this.publishTimeout,"Failed to publish payload, please try again."),this.removeRequestFromQueue(I),this.relayer.events.emit(er.publish,S)}catch(R){if(this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0,(u=a?.internal)!=null&&u.throwOnFailedPublish)throw this.removeRequestFromQueue(I),R;return}finally{clearTimeout(C)}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:o,opts:a}})}catch(f){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(f),f}},this.on=(i,o)=>{this.events.on(i,o)},this.once=(i,o)=>{this.events.once(i,o)},this.off=(i,o)=>{this.events.off(i,o)},this.removeListener=(i,o)=>{this.events.removeListener(i,o)},this.relayer=e,this.logger=Je.generateChildLogger(t,this.name),this.registerEventListeners()}get context(){return Je.getLoggerContext(this.logger)}rpcPublish(e,t,i,o,a,u,f){var v,p,w,I;const S={method:Zs(o.protocol).publish,params:{topic:e,message:t,ttl:i,prompt:a,tag:u},id:f};return sr((v=S.params)==null?void 0:v.prompt)&&((p=S.params)==null||delete p.prompt),sr((w=S.params)==null?void 0:w.tag)&&((I=S.params)==null||delete I.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:S}),this.relayer.request(S)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:t,message:i,opts:o}=e;await this.publish(t,i,o)})}registerEventListeners(){this.relayer.core.heartbeat.on(wi.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(er.connection_stalled);return}this.checkQueue()}),this.relayer.on(er.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class p3{constructor(){this.map=new Map,this.set=(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,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 i=this.get(e);if(!this.exists(e,t))return;const o=i.filter(a=>a!==t);if(!o.length){this.map.delete(e);return}this.map.set(e,o)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var g3=Object.defineProperty,v3=Object.defineProperties,y3=Object.getOwnPropertyDescriptors,ad=Object.getOwnPropertySymbols,_3=Object.prototype.hasOwnProperty,b3=Object.prototype.propertyIsEnumerable,cd=(r,e,t)=>e in r?g3(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ys=(r,e)=>{for(var t in e||(e={}))_3.call(e,t)&&cd(r,t,e[t]);if(ad)for(var t of ad(e))b3.call(e,t)&&cd(r,t,e[t]);return r},Rc=(r,e)=>v3(r,y3(e));class m3 extends em{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new p3,this.events=new Yt.exports.EventEmitter,this.name=e3,this.version=t3,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=Pn,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(i,o)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:o}});try{const a=Xa(o),u={topic:i,relay:a};this.pending.set(i,u);const f=await this.rpcSubscribe(i,a);return this.onSubscribe(f,u),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:o}}),f}catch(a){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(a),a}},this.unsubscribe=async(i,o)=>{await this.restartToComplete(),this.isInitialized(),typeof o?.id<"u"?await this.unsubscribeById(i,o.id,o):await this.unsubscribeByTopic(i,o)},this.isSubscribed=async i=>this.topics.includes(i)?!0:await new Promise((o,a)=>{const u=new ye.Watch;u.start(this.pendingSubscriptionWatchLabel);const f=setInterval(()=>{!this.pending.has(i)&&this.topics.includes(i)&&(clearInterval(f),u.stop(this.pendingSubscriptionWatchLabel),o(!0)),u.elapsed(this.pendingSubscriptionWatchLabel)>=r3&&(clearInterval(f),u.stop(this.pendingSubscriptionWatchLabel),a(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1),this.on=(i,o)=>{this.events.on(i,o)},this.once=(i,o)=>{this.events.once(i,o)},this.off=(i,o)=>{this.events.off(i,o)},this.removeListener=(i,o)=>{this.events.removeListener(i,o)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=Je.generateChildLogger(t,this.name),this.clientId=""}get context(){return Je.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 i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map(async o=>await this.unsubscribeById(e,o,t)))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const o=Xa(i);await this.rpcUnsubscribe(e,t,o);const a=At("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:i}})}catch(o){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(o),o}}async rpcSubscribe(e,t){const i={method:Zs(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await es(this.relayer.request(i),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(er.connection_stalled)}return vi(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:Zs(t.protocol).batchSubscribe,params:{topics:e.map(o=>o.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{return await await es(this.relayer.request(i),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(er.connection_stalled)}}rpcUnsubscribe(e,t,i){const o={method:Zs(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:o}),this.relayer.request(o)}onSubscribe(e,t){this.setSubscription(e,Rc(ys({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,ys({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),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,ys({},t)),this.topicMap.set(t.topic,e),this.events.emit(Kr.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:i}=he("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(Kr.deleted,Rc(ys({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Kr.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let t=0;t<e;t++){const i=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(Kr.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=he("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);Xr(t)&&this.onBatchSubscribe(t.map((i,o)=>Rc(ys({},e[o]),{id:i})))}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(wi.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(er.connect,async()=>{await this.onConnect()}),this.relayer.on(er.disconnect,()=>{this.onDisconnect()}),this.events.on(Kr.created,async e=>{const t=Kr.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}),this.events.on(Kr.deleted,async e=>{const t=Kr.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}=he("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 w3=Object.defineProperty,ud=Object.getOwnPropertySymbols,E3=Object.prototype.hasOwnProperty,D3=Object.prototype.propertyIsEnumerable,hd=(r,e,t)=>e in r?w3(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,S3=(r,e)=>{for(var t in e||(e={}))E3.call(e,t)&&hd(r,t,e[t]);if(ud)for(var t of ud(e))D3.call(e,t)&&hd(r,t,e[t]);return r};class x3 extends Xb{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new Yt.exports.EventEmitter,this.name=GE,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],this.hasExperiencedNetworkDisruption=!1,this.request=async t=>{this.logger.debug("Publishing Request Payload");try{return await this.toEstablishConnection(),await this.provider.request(t)}catch(i){throw this.logger.debug("Failed to Publish Request"),this.logger.error(i),i}},this.onPayloadHandler=t=>{this.onProviderPayload(t)},this.onConnectHandler=()=>{this.events.emit(er.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=t=>{this.logger.error(t),this.events.emit(er.error,t),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(ln.payload,this.onPayloadHandler),this.provider.on(ln.connect,this.onConnectHandler),this.provider.on(ln.disconnect,this.onDisconnectHandler),this.provider.on(ln.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Je.generateChildLogger(e.logger,this.name):Je.pino(Je.getDefaultLoggerOptions({level:e.logger||kE})),this.messages=new f3(this.logger,e.core),this.subscriber=new m3(this,this.logger),this.publisher=new d3(this,this.logger),this.relayUrl=e?.relayUrl||sd,this.projectId=e.projectId,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 ${od}...`),await this.restartTransport(od)}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)},QE)}get context(){return Je.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now()})}async subscribe(e,t){var i;this.isInitialized();let o=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"";if(o)return o;let a;const u=f=>{f.topic===e&&(this.subscriber.off(Kr.created,u),a())};return await Promise.all([new Promise(f=>{a=f,this.subscriber.on(Kr.created,u)}),new Promise(async f=>{o=await this.subscriber.subscribe(e,t),f()})]),o}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.transportExplicitlyClosed=!0,this.hasExperiencedNetworkDisruption&&this.connected?await es(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(Kr.resubscribed,()=>{t()})}),new Promise(async(t,i)=>{try{await es(this.provider.connect(),1e4,`Socket stalled when trying to connect to ${this.relayUrl}`)}catch(o){i(o);return}t()})])}catch(t){this.logger.error(t);const i=t;if(!this.isConnectionStalled(i.message))throw t;this.provider.events.emit(ln.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 kl())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 hn(new cw(C_({sdkVersion:JE,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:t,message:i}=e;await this.messages.set(t,i)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||i.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.debug(`Ignoring message for non-subscribed topic ${t}`),!0;const o=this.messages.has(t,i);return o&&this.logger.debug(`Ignoring duplicate message: ${i}`),o}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Sc(e)){if(!e.method.endsWith(WE))return;const t=e.params,{topic:i,message:o,publishedAt:a}=t.data,u={topic:i,message:o,publishedAt:a};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(S3({type:"event",event:t.id},u)),this.events.emit(t.id,u),await this.acknowledgePayload(e),await this.onMessageEvent(u)}else ao(e)&&this.events.emit(er.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(er.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=Dc(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(ln.payload,this.onPayloadHandler),this.provider.off(ln.connect,this.onConnectHandler),this.provider.off(ln.disconnect,this.onDisconnectHandler),this.provider.off(ln.error,this.onProviderErrorHandler)}async registerEventListeners(){this.events.on(er.connection_stalled,()=>{this.restartTransport().catch(t=>this.logger.error(t))});let e=await kl();w1(async t=>{this.initialized&&e!==t&&(e=t,t?await this.restartTransport().catch(i=>this.logger.error(i)):(this.hasExperiencedNetworkDisruption=!0,await this.transportClose().catch(i=>this.logger.error(i))))})}onProviderDisconnect(){this.events.emit(er.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(YE)))}isInitialized(){if(!this.initialized){const{message:e}=he("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 O3=Object.defineProperty,ld=Object.getOwnPropertySymbols,I3=Object.prototype.hasOwnProperty,P3=Object.prototype.propertyIsEnumerable,fd=(r,e,t)=>e in r?O3(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,dd=(r,e)=>{for(var t in e||(e={}))I3.call(e,t)&&fd(r,t,e[t]);if(ld)for(var t of ld(e))P3.call(e,t)&&fd(r,t,e[t]);return r};class uo extends Zb{constructor(e,t,i,o=Pn,a=void 0){super(e,t,i,o),this.core=e,this.logger=t,this.name=i,this.map=new Map,this.version=XE,this.cached=[],this.initialized=!1,this.storagePrefix=Pn,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(u=>{this.getKey&&u!==null&&!sr(u)?this.map.set(this.getKey(u),u):X_(u)?this.map.set(u.id,u):Z_(u)&&this.map.set(u.topic,u)}),this.cached=[],this.initialized=!0)},this.set=async(u,f)=>{this.isInitialized(),this.map.has(u)?await this.update(u,f):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:u,value:f}),this.map.set(u,f),await this.persist())},this.get=u=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:u}),this.getData(u)),this.getAll=u=>(this.isInitialized(),u?this.values.filter(f=>Object.keys(u).every(v=>uw(f[v],u[v]))):this.values),this.update=async(u,f)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:u,update:f});const v=dd(dd({},this.getData(u)),f);this.map.set(u,v),await this.persist()},this.delete=async(u,f)=>{this.isInitialized(),this.map.has(u)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:u,reason:f}),this.map.delete(u),await this.persist())},this.logger=Je.generateChildLogger(t,this.name),this.storagePrefix=o,this.getKey=a}get context(){return Je.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:i}=he("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}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}=he("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}=he("NOT_INITIALIZED",this.name);throw new Error(e)}}}class C3{constructor(e,t){this.core=e,this.logger=t,this.name=n3,this.version=i3,this.events=new Yt.exports,this.initialized=!1,this.storagePrefix=Pn,this.ignoredPayloadTypes=[kn],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:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]},this.create=async()=>{this.isInitialized();const i=Ya(),o=await this.core.crypto.setSymKey(i),a=Br(ye.FIVE_MINUTES),u={protocol:id},f={topic:o,expiry:a,relay:u,active:!1},v=B_({protocol:this.core.protocol,version:this.core.version,topic:o,symKey:i,relay:u});return await this.pairings.set(o,f),await this.core.relayer.subscribe(o),this.core.expirer.set(o,a),{topic:o,uri:v}},this.pair=async i=>{this.isInitialized(),this.isValidPair(i);const{topic:o,symKey:a,relay:u}=M_(i.uri);let f;if(this.pairings.keys.includes(o)&&(f=this.pairings.get(o),f.active))throw new Error(`Pairing already exists: ${o}. Please try again with a new connection URI.`);this.core.crypto.keychain.has(o)||(await this.core.crypto.setSymKey(a,o),await this.core.relayer.subscribe(o,{relay:u}));const v=Br(ye.FIVE_MINUTES),p={topic:o,relay:u,expiry:v,active:!1};return await this.pairings.set(o,p),this.core.expirer.set(o,v),i.activatePairing&&await this.activate({topic:o}),this.events.emit(vs.create,p),p},this.activate=async({topic:i})=>{this.isInitialized();const o=Br(ye.THIRTY_DAYS);await this.pairings.update(i,{active:!0,expiry:o}),this.core.expirer.set(i,o)},this.ping=async i=>{this.isInitialized(),await this.isValidPing(i);const{topic:o}=i;if(this.pairings.keys.includes(o)){const a=await this.sendRequest(o,"wc_pairingPing",{}),{done:u,resolve:f,reject:v}=yi();this.events.once(Ft("pairing_ping",a),({error:p})=>{p?v(p):f()}),await u()}},this.updateExpiry=async({topic:i,expiry:o})=>{this.isInitialized(),await this.pairings.update(i,{expiry:o})},this.updateMetadata=async({topic:i,metadata:o})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:o})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:o}=i;this.pairings.keys.includes(o)&&(await this.sendRequest(o,"wc_pairingDelete",At("USER_DISCONNECTED")),await this.deletePairing(o))},this.sendRequest=async(i,o,a)=>{const u=Ei(o,a),f=await this.core.crypto.encode(i,u),v=gs[o].req;return this.core.history.set(i,u),this.core.relayer.publish(i,f,v),u.id},this.sendResult=async(i,o,a)=>{const u=Dc(i,a),f=await this.core.crypto.encode(o,u),v=await this.core.history.get(o,i),p=gs[v.request.method].res;await this.core.relayer.publish(o,f,p),await this.core.history.resolve(u)},this.sendError=async(i,o,a)=>{const u=oo(i,a),f=await this.core.crypto.encode(o,u),v=await this.core.history.get(o,i),p=gs[v.request.method]?gs[v.request.method].res:gs.unregistered_method.res;await this.core.relayer.publish(o,f,p),await this.core.history.resolve(u)},this.deletePairing=async(i,o)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,At("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),o?Promise.resolve():this.core.expirer.del(i)])},this.cleanup=async()=>{const i=this.pairings.getAll().filter(o=>In(o.expiry));await Promise.all(i.map(o=>this.deletePairing(o.topic)))},this.onRelayEventRequest=i=>{const{topic:o,payload:a}=i;switch(a.method){case"wc_pairingPing":return this.onPairingPingRequest(o,a);case"wc_pairingDelete":return this.onPairingDeleteRequest(o,a);default:return this.onUnknownRpcMethodRequest(o,a)}},this.onRelayEventResponse=async i=>{const{topic:o,payload:a}=i,u=(await this.core.history.get(o,a.id)).request.method;switch(u){case"wc_pairingPing":return this.onPairingPingResponse(o,a);default:return this.onUnknownRpcMethodResponse(u)}},this.onPairingPingRequest=async(i,o)=>{const{id:a}=o;try{this.isValidPing({topic:i}),await this.sendResult(a,i,!0),this.events.emit(vs.ping,{id:a,topic:i})}catch(u){await this.sendError(a,i,u),this.logger.error(u)}},this.onPairingPingResponse=(i,o)=>{const{id:a}=o;setTimeout(()=>{un(o)?this.events.emit(Ft("pairing_ping",a),{}):zr(o)&&this.events.emit(Ft("pairing_ping",a),{error:o.error})},500)},this.onPairingDeleteRequest=async(i,o)=>{const{id:a}=o;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(vs.delete,{id:a,topic:i})}catch(u){await this.sendError(a,i,u),this.logger.error(u)}},this.onUnknownRpcMethodRequest=async(i,o)=>{const{id:a,method:u}=o;try{if(this.registeredMethods.includes(u))return;const f=At("WC_METHOD_UNSUPPORTED",u);await this.sendError(a,i,f),this.logger.error(f)}catch(f){await this.sendError(a,i,f),this.logger.error(f)}},this.onUnknownRpcMethodResponse=i=>{this.registeredMethods.includes(i)||this.logger.error(At("WC_METHOD_UNSUPPORTED",i))},this.isValidPair=i=>{if(!gr(i)){const{message:o}=he("MISSING_OR_INVALID",`pair() params: ${i}`);throw new Error(o)}if(!Q_(i.uri)){const{message:o}=he("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw new Error(o)}},this.isValidPing=async i=>{if(!gr(i)){const{message:a}=he("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(a)}const{topic:o}=i;await this.isValidPairingTopic(o)},this.isValidDisconnect=async i=>{if(!gr(i)){const{message:a}=he("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(a)}const{topic:o}=i;await this.isValidPairingTopic(o)},this.isValidPairingTopic=async i=>{if(!kt(i,!1)){const{message:o}=he("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(o)}if(!this.pairings.keys.includes(i)){const{message:o}=he("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(o)}if(In(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:o}=he("EXPIRED",`pairing topic: ${i}`);throw new Error(o)}},this.core=e,this.logger=Je.generateChildLogger(t,this.name),this.pairings=new uo(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Je.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=he("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(er.message,async e=>{const{topic:t,message:i}=e;if(!this.pairings.keys.includes(t)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const o=await this.core.crypto.decode(t,i);try{Sc(o)?(this.core.history.set(t,o),this.onRelayEventRequest({topic:t,payload:o})):ao(o)&&(await this.core.history.resolve(o),await this.onRelayEventResponse({topic:t,payload:o}),this.core.history.delete(t,o.id))}catch(a){this.logger.error(a)}})}registerExpirerEvents(){this.core.expirer.on(Tr.expired,async e=>{const{topic:t}=Ul(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(vs.expire,{topic:t}))})}}class A3 extends Yb{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new Yt.exports.EventEmitter,this.name=s3,this.version=o3,this.cached=[],this.initialized=!1,this.storagePrefix=Pn,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(i,o,a)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:o,chainId:a}),this.records.has(o.id))return;const u={id:o.id,topic:i,request:{method:o.method,params:o.params||null},chainId:a,expiry:Br(ye.THIRTY_DAYS)};this.records.set(u.id,u),this.events.emit(Zr.created,u)},this.resolve=async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const o=await this.getRecord(i.id);typeof o.response>"u"&&(o.response=zr(i)?{error:i.error}:{result:i.result},this.records.set(o.id,o),this.events.emit(Zr.updated,o))},this.get=async(i,o)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:o}),await this.getRecord(o)),this.delete=(i,o)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:o}),this.values.forEach(a=>{if(a.topic===i){if(typeof o<"u"&&a.id!==o)return;this.records.delete(a.id),this.events.emit(Zr.deleted,a)}})},this.exists=async(i,o)=>(this.isInitialized(),this.records.has(o)?(await this.getRecord(o)).topic===i:!1),this.on=(i,o)=>{this.events.on(i,o)},this.once=(i,o)=>{this.events.once(i,o)},this.off=(i,o)=>{this.events.off(i,o)},this.removeListener=(i,o)=>{this.events.removeListener(i,o)},this.logger=Je.generateChildLogger(t,this.name)}get context(){return Je.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 i={topic:t.topic,request:Ei(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)}),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:i}=he("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Zr.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=he("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(Zr.created,e=>{const t=Zr.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()}),this.events.on(Zr.updated,e=>{const t=Zr.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()}),this.events.on(Zr.deleted,e=>{const t=Zr.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()}),this.core.heartbeat.on(wi.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}=he("NOT_INITIALIZED",this.name);throw new Error(e)}}}class T3 extends tm{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new Yt.exports.EventEmitter,this.name=a3,this.version=c3,this.cached=[],this.initialized=!1,this.storagePrefix=Pn,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=i=>{try{const o=this.formatTarget(i);return typeof this.getExpiration(o)<"u"}catch{return!1}},this.set=(i,o)=>{this.isInitialized();const a=this.formatTarget(i),u={target:a,expiry:o};this.expirations.set(a,u),this.checkExpiry(a,u),this.events.emit(Tr.created,{target:a,expiration:u})},this.get=i=>{this.isInitialized();const o=this.formatTarget(i);return this.getExpiration(o)},this.del=i=>{if(this.isInitialized(),this.has(i)){const o=this.formatTarget(i),a=this.getExpiration(o);this.expirations.delete(o),this.events.emit(Tr.deleted,{target:o,expiration:a})}},this.on=(i,o)=>{this.events.on(i,o)},this.once=(i,o)=>{this.events.once(i,o)},this.off=(i,o)=>{this.events.off(i,o)},this.removeListener=(i,o)=>{this.events.removeListener(i,o)},this.logger=Je.generateChildLogger(t,this.name)}get context(){return Je.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 A_(e);if(typeof e=="number")return T_(e);const{message:t}=he("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(Tr.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=he("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:i}=he("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;ye.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Tr.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(wi.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(Tr.created,e=>{const t=Tr.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Tr.expired,e=>{const t=Tr.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Tr.deleted,e=>{const t=Tr.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=he("NOT_INITIALIZED",this.name);throw new Error(e)}}}class R3 extends rm{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.name=Ac,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async i=>{if(this.verifyDisabled||Qi()||!Xi())return;const o=this.getVerifyUrl(i?.verifyUrl);this.verifyUrl!==o&&this.removeIframe(),this.verifyUrl=o;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=Tc;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 i=>{this.initialized?this.sendPost(i.attestationId):(this.addToQueue(i.attestationId),await this.init())},this.resolve=async i=>{if(this.isDevEnv)return"";const o=this.getVerifyUrl(i?.verifyUrl);let a;try{a=await this.fetchAttestation(i.attestationId,o)}catch(u){this.logger.info(`failed to resolve attestation: ${i.attestationId} from url: ${o}`),this.logger.info(u),a=await this.fetchAttestation(i.attestationId,Tc)}return a},this.fetchAttestation=async(i,o)=>{this.logger.info(`resolving attestation: ${i} from url: ${o}`);const a=this.startAbortTimer(ye.ONE_SECOND*2),u=await fetch(`${o}/attestation/${i}`,{signal:this.abortController.signal});return clearTimeout(a),u.status===200?await u.json():void 0},this.addToQueue=i=>{this.queue.push(i)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(i=>this.sendPost(i)),this.queue=[])},this.sendPost=i=>{var o;try{if(!this.iframe)return;(o=this.iframe.contentWindow)==null||o.postMessage(i,"*"),this.logger.info(`postMessage sent: ${i} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let i;const o=a=>{a.data==="verify_ready"&&(this.initialized=!0,this.processQueue(),window.removeEventListener("message",o),i())};await Promise.race([new Promise(a=>{if(document.getElementById(Ac))return a();window.addEventListener("message",o);const u=document.createElement("iframe");u.id=Ac,u.src=`${this.verifyUrl}/${this.projectId}`,u.style.display="none",document.body.append(u),this.iframe=u,i=a}),new Promise((a,u)=>setTimeout(()=>{window.removeEventListener("message",o),u("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=i=>{let o=i||Di;return u3.includes(o)||(this.logger.info(`verify url: ${o}, not included in trusted list, assigning default: ${Di}`),o=Di),o},this.logger=Je.generateChildLogger(t,this.name),this.verifyUrl=Di,this.abortController=new AbortController,this.isDevEnv=Ja()&&process.env.IS_VITEST}get context(){return Je.getLoggerContext(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),ye.toMiliseconds(e))}}var N3=Object.defineProperty,pd=Object.getOwnPropertySymbols,$3=Object.prototype.hasOwnProperty,F3=Object.prototype.propertyIsEnumerable,gd=(r,e,t)=>e in r?N3(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,vd=(r,e)=>{for(var t in e||(e={}))$3.call(e,t)&&gd(r,t,e[t]);if(pd)for(var t of pd(e))F3.call(e,t)&&gd(r,t,e[t]);return r};class Nc extends Wb{constructor(e){super(e),this.protocol=rd,this.version=FE,this.name=Cc,this.events=new Yt.exports.EventEmitter,this.initialized=!1,this.on=(i,o)=>this.events.on(i,o),this.once=(i,o)=>this.events.once(i,o),this.off=(i,o)=>this.events.off(i,o),this.removeListener=(i,o)=>this.events.removeListener(i,o),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||sd,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Je.pino(Je.getDefaultLoggerOptions({level:e?.logger||LE.logger}));this.logger=Je.generateChildLogger(t,this.name),this.heartbeat=new wi.HeartBeat,this.crypto=new l3(this,this.logger,e?.keychain),this.history=new A3(this,this.logger),this.expirer=new T3(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new X1(vd(vd({},UE),e?.storageOptions)),this.relayer=new x3({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new C3(this,this.logger),this.verify=new R3(this.projectId||"",this.logger)}static async init(e){const t=new Nc(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(ZE,i),t}get context(){return Je.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const L3=Nc,yd="wc",_d=2,bd="client",$c=`${yd}@${_d}:${bd}:`,Fc={name:bd,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},md="WALLETCONNECT_DEEPLINK_CHOICE",U3="proposal",wd="Proposal expired",j3="session",ho=ye.SEVEN_DAYS,M3="engine",_s={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}}},Lc={min:ye.FIVE_MINUTES,max:ye.SEVEN_DAYS},fn={idle:"IDLE",active:"ACTIVE"},q3="request",H3=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var B3=Object.defineProperty,z3=Object.defineProperties,K3=Object.getOwnPropertyDescriptors,Ed=Object.getOwnPropertySymbols,V3=Object.prototype.hasOwnProperty,k3=Object.prototype.propertyIsEnumerable,Dd=(r,e,t)=>e in r?B3(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,vr=(r,e)=>{for(var t in e||(e={}))V3.call(e,t)&&Dd(r,t,e[t]);if(Ed)for(var t of Ed(e))k3.call(e,t)&&Dd(r,t,e[t]);return r},bs=(r,e)=>z3(r,K3(e));class G3 extends im{constructor(e){super(e),this.name=M3,this.events=new Yt.exports,this.initialized=!1,this.ignoredPayloadTypes=[kn],this.requestQueue={state:fn.idle,queue:[]},this.sessionRequestQueue={state:fn.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(_s)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},ye.toMiliseconds(this.requestQueueDelay)))},this.connect=async t=>{await this.isInitialized();const i=bs(vr({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:o,requiredNamespaces:a,optionalNamespaces:u,sessionProperties:f,relays:v}=i;let p=o,w,I=!1;if(p&&(I=this.client.core.pairing.pairings.get(p).active),!p||!I){const{topic:U,uri:x}=await this.client.core.pairing.create();p=U,w=x}const S=await this.client.core.crypto.generateKeyPair(),C=vr({requiredNamespaces:a,optionalNamespaces:u,relays:v??[{protocol:id}],proposer:{publicKey:S,metadata:this.client.metadata}},f&&{sessionProperties:f}),{reject:R,resolve:B,done:K}=yi(ye.FIVE_MINUTES,wd);if(this.events.once(Ft("session_connect"),async({error:U,session:x})=>{if(U)R(U);else if(x){x.self.publicKey=S;const T=bs(vr({},x),{requiredNamespaces:x.requiredNamespaces,optionalNamespaces:x.optionalNamespaces});await this.client.session.set(x.topic,T),await this.setExpiry(x.topic,x.expiry),p&&await this.client.core.pairing.updateMetadata({topic:p,metadata:x.peer.metadata}),B(T)}}),!p){const{message:U}=he("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(U)}const se=await this.sendRequest({topic:p,method:"wc_sessionPropose",params:C}),$=Br(ye.FIVE_MINUTES);return await this.setProposal(se,vr({id:se,expiry:$},C)),{uri:w,approval:K}},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:i,relayProtocol:o,namespaces:a,sessionProperties:u}=t,f=this.client.proposal.get(i);let{pairingTopic:v,proposer:p,requiredNamespaces:w,optionalNamespaces:I}=f;v=v||"",bi(w)||(w=k_(a,"approve()"));const S=await this.client.core.crypto.generateKeyPair(),C=p.publicKey,R=await this.client.core.crypto.generateSharedKey(S,C);v&&i&&(await this.client.core.pairing.updateMetadata({topic:v,metadata:p.metadata}),await this.sendResult({id:i,topic:v,result:{relay:{protocol:o??"irn"},responderPublicKey:S}}),await this.client.proposal.delete(i,At("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:v}));const B=vr({relay:{protocol:o??"irn"},namespaces:a,requiredNamespaces:w,optionalNamespaces:I,pairingTopic:v,controller:{publicKey:S,metadata:this.client.metadata},expiry:Br(ho)},u&&{sessionProperties:u});await this.client.core.relayer.subscribe(R),await this.sendRequest({topic:R,method:"wc_sessionSettle",params:B,throwOnFailedPublish:!0});const K=bs(vr({},B),{topic:R,pairingTopic:v,acknowledged:!1,self:B.controller,peer:{publicKey:p.publicKey,metadata:p.metadata},controller:S});return await this.client.session.set(R,K),await this.setExpiry(R,Br(ho)),{topic:R,acknowledged:()=>new Promise(se=>setTimeout(()=>se(this.client.session.get(R)),500))}},this.reject=async t=>{await this.isInitialized(),await this.isValidReject(t);const{id:i,reason:o}=t,{pairingTopic:a}=this.client.proposal.get(i);a&&(await this.sendError(i,a,o),await this.client.proposal.delete(i,At("USER_DISCONNECTED")))},this.update=async t=>{await this.isInitialized(),await this.isValidUpdate(t);const{topic:i,namespaces:o}=t,a=await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:o}}),{done:u,resolve:f,reject:v}=yi();return this.events.once(Ft("session_update",a),({error:p})=>{p?v(p):f()}),await this.client.session.update(i,{namespaces:o}),{acknowledged:u}},this.extend=async t=>{await this.isInitialized(),await this.isValidExtend(t);const{topic:i}=t,o=await this.sendRequest({topic:i,method:"wc_sessionExtend",params:{}}),{done:a,resolve:u,reject:f}=yi();return this.events.once(Ft("session_extend",o),({error:v})=>{v?f(v):u()}),await this.setExpiry(i,Br(ho)),{acknowledged:a}},this.request=async t=>{await this.isInitialized(),await this.isValidRequest(t);const{chainId:i,request:o,topic:a,expiry:u}=t,f=Ec(),{done:v,resolve:p,reject:w}=yi(u,"Request expired. Please try again.");return this.events.once(Ft("session_request",f),({error:I,result:S})=>{I?w(I):p(S)}),await Promise.all([new Promise(async I=>{await this.sendRequest({clientRpcId:f,topic:a,method:"wc_sessionRequest",params:{request:o,chainId:i},expiry:u,throwOnFailedPublish:!0}).catch(S=>w(S)),this.client.events.emit("session_request_sent",{topic:a,request:o,chainId:i,id:f}),I()}),new Promise(async I=>{const S=await this.client.core.storage.getItem(md);R_({id:f,topic:a,wcDeepLink:S}),I()}),v()]).then(I=>I[2])},this.respond=async t=>{await this.isInitialized(),await this.isValidRespond(t);const{topic:i,response:o}=t,{id:a}=o;un(o)?await this.sendResult({id:a,topic:i,result:o.result,throwOnFailedPublish:!0}):zr(o)&&await this.sendError(a,i,o.error),this.cleanupAfterResponse(t)},this.ping=async t=>{await this.isInitialized(),await this.isValidPing(t);const{topic:i}=t;if(this.client.session.keys.includes(i)){const o=await this.sendRequest({topic:i,method:"wc_sessionPing",params:{}}),{done:a,resolve:u,reject:f}=yi();this.events.once(Ft("session_ping",o),({error:v})=>{v?f(v):u()}),await a()}else this.client.core.pairing.pairings.keys.includes(i)&&await this.client.core.pairing.ping({topic:i})},this.emit=async t=>{await this.isInitialized(),await this.isValidEmit(t);const{topic:i,event:o,chainId:a}=t;await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:o,chainId:a}})},this.disconnect=async t=>{await this.isInitialized(),await this.isValidDisconnect(t);const{topic:i}=t;this.client.session.keys.includes(i)?(await this.sendRequest({topic:i,method:"wc_sessionDelete",params:At("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession(i)):await this.client.core.pairing.disconnect({topic:i})},this.find=t=>(this.isInitialized(),this.client.session.getAll().filter(i=>Y_(i,t))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async t=>{if(t.pairingTopic)try{const i=this.client.core.pairing.pairings.get(t.pairingTopic),o=this.client.core.pairing.pairings.getAll().filter(a=>{var u,f;return((u=a.peerMetadata)==null?void 0:u.url)&&((f=a.peerMetadata)==null?void 0:f.url)===t.peer.metadata.url&&a.topic&&a.topic!==i.topic});if(o.length===0)return;this.client.logger.info(`Cleaning up ${o.length} duplicate pairing(s)`),await Promise.all(o.map(a=>this.client.core.pairing.disconnect({topic:a.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}},this.deleteSession=async(t,i)=>{const{self:o}=this.client.session.get(t);await this.client.core.relayer.unsubscribe(t),this.client.session.delete(t,At("USER_DISCONNECTED")),this.client.core.crypto.keychain.has(o.publicKey)&&await this.client.core.crypto.deleteKeyPair(o.publicKey),this.client.core.crypto.keychain.has(t)&&await this.client.core.crypto.deleteSymKey(t),i||this.client.core.expirer.del(t),this.client.core.storage.removeItem(md).catch(a=>this.client.logger.warn(a))},this.deleteProposal=async(t,i)=>{await Promise.all([this.client.proposal.delete(t,At("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(t)])},this.deletePendingSessionRequest=async(t,i,o=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,i),o?Promise.resolve():this.client.core.expirer.del(t)]),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(a=>a.id!==t),o&&(this.sessionRequestQueue.state=fn.idle)},this.setExpiry=async(t,i)=>{this.client.session.keys.includes(t)&&await this.client.session.update(t,{expiry:i}),this.client.core.expirer.set(t,i)},this.setProposal=async(t,i)=>{await this.client.proposal.set(t,i),this.client.core.expirer.set(t,i.expiry)},this.setPendingSessionRequest=async t=>{const i=_s.wc_sessionRequest.req.ttl,{id:o,topic:a,params:u,verifyContext:f}=t;await this.client.pendingRequest.set(o,{id:o,topic:a,params:u,verifyContext:f}),i&&this.client.core.expirer.set(o,Br(i))},this.sendRequest=async t=>{const{topic:i,method:o,params:a,expiry:u,relayRpcId:f,clientRpcId:v,throwOnFailedPublish:p}=t,w=Ei(o,a,v);if(Xi()&&H3.includes(o)){const C=vi(JSON.stringify(w));this.client.core.verify.register({attestationId:C})}const I=await this.client.core.crypto.encode(i,w),S=_s[o].req;return u&&(S.ttl=u),f&&(S.id=f),this.client.core.history.set(i,w),p?(S.internal=bs(vr({},S.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,I,S)):this.client.core.relayer.publish(i,I,S).catch(C=>this.client.logger.error(C)),w.id},this.sendResult=async t=>{const{id:i,topic:o,result:a,throwOnFailedPublish:u}=t,f=Dc(i,a),v=await this.client.core.crypto.encode(o,f),p=await this.client.core.history.get(o,i),w=_s[p.request.method].res;u?(w.internal=bs(vr({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(o,v,w)):this.client.core.relayer.publish(o,v,w).catch(I=>this.client.logger.error(I)),await this.client.core.history.resolve(f)},this.sendError=async(t,i,o)=>{const a=oo(t,o),u=await this.client.core.crypto.encode(i,a),f=await this.client.core.history.get(i,t),v=_s[f.request.method].res;this.client.core.relayer.publish(i,u,v),await this.client.core.history.resolve(a)},this.cleanup=async()=>{const t=[],i=[];this.client.session.getAll().forEach(o=>{In(o.expiry)&&t.push(o.topic)}),this.client.proposal.getAll().forEach(o=>{In(o.expiry)&&i.push(o.id)}),await Promise.all([...t.map(o=>this.deleteSession(o)),...i.map(o=>this.deleteProposal(o))])},this.onRelayEventRequest=async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===fn.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=fn.active;const t=this.requestQueue.queue.shift();if(t)try{this.processRequest(t),await new Promise(i=>setTimeout(i,300))}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=fn.idle},this.processRequest=t=>{const{topic:i,payload:o}=t,a=o.method;switch(a){case"wc_sessionPropose":return this.onSessionProposeRequest(i,o);case"wc_sessionSettle":return this.onSessionSettleRequest(i,o);case"wc_sessionUpdate":return this.onSessionUpdateRequest(i,o);case"wc_sessionExtend":return this.onSessionExtendRequest(i,o);case"wc_sessionPing":return this.onSessionPingRequest(i,o);case"wc_sessionDelete":return this.onSessionDeleteRequest(i,o);case"wc_sessionRequest":return this.onSessionRequest(i,o);case"wc_sessionEvent":return this.onSessionEventRequest(i,o);default:return this.client.logger.info(`Unsupported request method ${a}`)}},this.onRelayEventResponse=async t=>{const{topic:i,payload:o}=t,a=(await this.client.core.history.get(i,o.id)).request.method;switch(a){case"wc_sessionPropose":return this.onSessionProposeResponse(i,o);case"wc_sessionSettle":return this.onSessionSettleResponse(i,o);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,o);case"wc_sessionExtend":return this.onSessionExtendResponse(i,o);case"wc_sessionPing":return this.onSessionPingResponse(i,o);case"wc_sessionRequest":return this.onSessionRequestResponse(i,o);default:return this.client.logger.info(`Unsupported response method ${a}`)}},this.onRelayEventUnknownPayload=t=>{const{topic:i}=t,{message:o}=he("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(o)},this.onSessionProposeRequest=async(t,i)=>{const{params:o,id:a}=i;try{this.isValidConnect(vr({},i.params));const u=Br(ye.FIVE_MINUTES),f=vr({id:a,pairingTopic:t,expiry:u},o);await this.setProposal(a,f);const v=vi(JSON.stringify(i)),p=await this.getVerifyContext(v,f.proposer.metadata);this.client.events.emit("session_proposal",{id:a,params:f,verifyContext:p})}catch(u){await this.sendError(a,t,u),this.client.logger.error(u)}},this.onSessionProposeResponse=async(t,i)=>{const{id:o}=i;if(un(i)){const{result:a}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:a});const u=this.client.proposal.get(o);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:u});const f=u.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:f});const v=a.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:v});const p=await this.client.core.crypto.generateSharedKey(f,v);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:p});const w=await this.client.core.relayer.subscribe(p);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:w}),await this.client.core.pairing.activate({topic:t})}else zr(i)&&(await this.client.proposal.delete(o,At("USER_DISCONNECTED")),this.events.emit(Ft("session_connect"),{error:i.error}))},this.onSessionSettleRequest=async(t,i)=>{const{id:o,params:a}=i;try{this.isValidSessionSettleRequest(a);const{relay:u,controller:f,expiry:v,namespaces:p,requiredNamespaces:w,optionalNamespaces:I,sessionProperties:S,pairingTopic:C}=i.params,R=vr({topic:t,relay:u,expiry:v,namespaces:p,acknowledged:!0,pairingTopic:C,requiredNamespaces:w,optionalNamespaces:I,controller:f.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:f.publicKey,metadata:f.metadata}},S&&{sessionProperties:S});await this.sendResult({id:i.id,topic:t,result:!0}),this.events.emit(Ft("session_connect"),{session:R}),this.cleanupDuplicatePairings(R)}catch(u){await this.sendError(o,t,u),this.client.logger.error(u)}},this.onSessionSettleResponse=async(t,i)=>{const{id:o}=i;un(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(Ft("session_approve",o),{})):zr(i)&&(await this.client.session.delete(t,At("USER_DISCONNECTED")),this.events.emit(Ft("session_approve",o),{error:i.error}))},this.onSessionUpdateRequest=async(t,i)=>{const{params:o,id:a}=i;try{const u=`${t}_session_update`,f=ro.get(u);if(f&&this.isRequestOutOfSync(f,a)){this.client.logger.info(`Discarding out of sync request - ${a}`);return}this.isValidUpdate(vr({topic:t},o)),await this.client.session.update(t,{namespaces:o.namespaces}),await this.sendResult({id:a,topic:t,result:!0}),this.client.events.emit("session_update",{id:a,topic:t,params:o}),ro.set(u,a)}catch(u){await this.sendError(a,t,u),this.client.logger.error(u)}},this.isRequestOutOfSync=(t,i)=>parseInt(i.toString().slice(0,-3))<=parseInt(t.toString().slice(0,-3)),this.onSessionUpdateResponse=(t,i)=>{const{id:o}=i;un(i)?this.events.emit(Ft("session_update",o),{}):zr(i)&&this.events.emit(Ft("session_update",o),{error:i.error})},this.onSessionExtendRequest=async(t,i)=>{const{id:o}=i;try{this.isValidExtend({topic:t}),await this.setExpiry(t,Br(ho)),await this.sendResult({id:o,topic:t,result:!0}),this.client.events.emit("session_extend",{id:o,topic:t})}catch(a){await this.sendError(o,t,a),this.client.logger.error(a)}},this.onSessionExtendResponse=(t,i)=>{const{id:o}=i;un(i)?this.events.emit(Ft("session_extend",o),{}):zr(i)&&this.events.emit(Ft("session_extend",o),{error:i.error})},this.onSessionPingRequest=async(t,i)=>{const{id:o}=i;try{this.isValidPing({topic:t}),await this.sendResult({id:o,topic:t,result:!0}),this.client.events.emit("session_ping",{id:o,topic:t})}catch(a){await this.sendError(o,t,a),this.client.logger.error(a)}},this.onSessionPingResponse=(t,i)=>{const{id:o}=i;setTimeout(()=>{un(i)?this.events.emit(Ft("session_ping",o),{}):zr(i)&&this.events.emit(Ft("session_ping",o),{error:i.error})},500)},this.onSessionDeleteRequest=async(t,i)=>{const{id:o}=i;try{this.isValidDisconnect({topic:t,reason:i.params}),await Promise.all([new Promise(a=>{this.client.core.relayer.once(er.publish,async()=>{a(await this.deleteSession(t))})}),this.sendResult({id:o,topic:t,result:!0})]),this.client.events.emit("session_delete",{id:o,topic:t})}catch(a){this.client.logger.error(a)}},this.onSessionRequest=async(t,i)=>{const{id:o,params:a}=i;try{this.isValidRequest(vr({topic:t},a));const u=vi(JSON.stringify(Ei("wc_sessionRequest",a,o))),f=this.client.session.get(t),v=await this.getVerifyContext(u,f.peer.metadata),p={id:o,topic:t,params:a,verifyContext:v};await this.setPendingSessionRequest(p),this.addSessionRequestToSessionRequestQueue(p),this.processSessionRequestQueue()}catch(u){await this.sendError(o,t,u),this.client.logger.error(u)}},this.onSessionRequestResponse=(t,i)=>{const{id:o}=i;un(i)?this.events.emit(Ft("session_request",o),{result:i.result}):zr(i)&&this.events.emit(Ft("session_request",o),{error:i.error})},this.onSessionEventRequest=async(t,i)=>{const{id:o,params:a}=i;try{const u=`${t}_session_event_${a.event.name}`,f=ro.get(u);if(f&&this.isRequestOutOfSync(f,o)){this.client.logger.info(`Discarding out of sync request - ${o}`);return}this.isValidEmit(vr({topic:t},a)),this.client.events.emit("session_event",{id:o,topic:t,params:a}),ro.set(u,o)}catch(u){await this.sendError(o,t,u),this.client.logger.error(u)}},this.addSessionRequestToSessionRequestQueue=t=>{this.sessionRequestQueue.queue.push(t)},this.cleanupAfterResponse=t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=fn.idle,this.processSessionRequestQueue()},ye.toMiliseconds(this.requestQueueDelay))},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===fn.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=fn.active,this.client.events.emit("session_request",t)}catch(i){this.client.logger.error(i)}},this.onPairingCreated=t=>{if(t.active)return;const i=this.client.proposal.getAll().find(o=>o.pairingTopic===t.topic);i&&this.onSessionProposeRequest(t.topic,Ei("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer},i.id))},this.isValidConnect=async t=>{if(!gr(t)){const{message:v}=he("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(v)}const{pairingTopic:i,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:u,relays:f}=t;if(sr(i)||await this.isValidPairingTopic(i),!a1(f,!0)){const{message:v}=he("MISSING_OR_INVALID",`connect() relays: ${f}`);throw new Error(v)}!sr(o)&&bi(o)!==0&&this.validateNamespaces(o,"requiredNamespaces"),!sr(a)&&bi(a)!==0&&this.validateNamespaces(a,"optionalNamespaces"),sr(u)||this.validateSessionProps(u,"sessionProperties")},this.validateNamespaces=(t,i)=>{const o=o1(t,"connect()",i);if(o)throw new Error(o.message)},this.isValidApprove=async t=>{if(!gr(t))throw new Error(he("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:i,namespaces:o,relayProtocol:a,sessionProperties:u}=t;await this.isValidProposalId(i);const f=this.client.proposal.get(i),v=to(o,"approve()");if(v)throw new Error(v.message);const p=Kl(f.requiredNamespaces,o,"approve()");if(p)throw new Error(p.message);if(!kt(a,!0)){const{message:w}=he("MISSING_OR_INVALID",`approve() relayProtocol: ${a}`);throw new Error(w)}sr(u)||this.validateSessionProps(u,"sessionProperties")},this.isValidReject=async t=>{if(!gr(t)){const{message:a}=he("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(a)}const{id:i,reason:o}=t;if(await this.isValidProposalId(i),!u1(o)){const{message:a}=he("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(o)}`);throw new Error(a)}},this.isValidSessionSettleRequest=t=>{if(!gr(t)){const{message:p}=he("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(p)}const{relay:i,controller:o,namespaces:a,expiry:u}=t;if(!Bl(i)){const{message:p}=he("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(p)}const f=e1(o,"onSessionSettleRequest()");if(f)throw new Error(f.message);const v=to(a,"onSessionSettleRequest()");if(v)throw new Error(v.message);if(In(u)){const{message:p}=he("EXPIRED","onSessionSettleRequest()");throw new Error(p)}},this.isValidUpdate=async t=>{if(!gr(t)){const{message:v}=he("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(v)}const{topic:i,namespaces:o}=t;await this.isValidSessionTopic(i);const a=this.client.session.get(i),u=to(o,"update()");if(u)throw new Error(u.message);const f=Kl(a.requiredNamespaces,o,"update()");if(f)throw new Error(f.message)},this.isValidExtend=async t=>{if(!gr(t)){const{message:o}=he("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(o)}const{topic:i}=t;await this.isValidSessionTopic(i)},this.isValidRequest=async t=>{if(!gr(t)){const{message:v}=he("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(v)}const{topic:i,request:o,chainId:a,expiry:u}=t;await this.isValidSessionTopic(i);const{namespaces:f}=this.client.session.get(i);if(!zl(f,a)){const{message:v}=he("MISSING_OR_INVALID",`request() chainId: ${a}`);throw new Error(v)}if(!h1(o)){const{message:v}=he("MISSING_OR_INVALID",`request() ${JSON.stringify(o)}`);throw new Error(v)}if(!d1(f,a,o.method)){const{message:v}=he("MISSING_OR_INVALID",`request() method: ${o.method}`);throw new Error(v)}if(u&&!y1(u,Lc)){const{message:v}=he("MISSING_OR_INVALID",`request() expiry: ${u}. Expiry must be a number (in seconds) between ${Lc.min} and ${Lc.max}`);throw new Error(v)}},this.isValidRespond=async t=>{if(!gr(t)){const{message:a}=he("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(a)}const{topic:i,response:o}=t;if(await this.isValidSessionTopic(i),!l1(o)){const{message:a}=he("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(o)}`);throw new Error(a)}},this.isValidPing=async t=>{if(!gr(t)){const{message:o}=he("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(o)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)},this.isValidEmit=async t=>{if(!gr(t)){const{message:f}=he("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(f)}const{topic:i,event:o,chainId:a}=t;await this.isValidSessionTopic(i);const{namespaces:u}=this.client.session.get(i);if(!zl(u,a)){const{message:f}=he("MISSING_OR_INVALID",`emit() chainId: ${a}`);throw new Error(f)}if(!f1(o)){const{message:f}=he("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(f)}if(!p1(u,a,o.name)){const{message:f}=he("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(f)}},this.isValidDisconnect=async t=>{if(!gr(t)){const{message:o}=he("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(o)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)},this.getVerifyContext=async(t,i)=>{const o={verified:{verifyUrl:i.verifyUrl||Di,validation:"UNKNOWN",origin:i.url||""}};try{const a=await this.client.core.verify.resolve({attestationId:t,verifyUrl:i.verifyUrl});a&&(o.verified.origin=a.origin,o.verified.isScam=a.isScam,o.verified.validation=a.origin===new URL(i.url).origin?"VALID":"INVALID")}catch(a){this.client.logger.info(a)}return this.client.logger.info(`Verify context: ${JSON.stringify(o)}`),o},this.validateSessionProps=(t,i)=>{Object.values(t).forEach(o=>{if(!kt(o,!1)){const{message:a}=he("MISSING_OR_INVALID",`${i} must be in Record<string, string> format. Received: ${JSON.stringify(o)}`);throw new Error(a)}})}}async isInitialized(){if(!this.initialized){const{message:e}=he("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(er.message,async e=>{const{topic:t,message:i}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(i)))return;const o=await this.client.core.crypto.decode(t,i);try{Sc(o)?(this.client.core.history.set(t,o),this.onRelayEventRequest({topic:t,payload:o})):ao(o)?(await this.client.core.history.resolve(o),await this.onRelayEventResponse({topic:t,payload:o}),this.client.core.history.delete(t,o.id)):this.onRelayEventUnknownPayload({topic:t,payload:o})}catch(a){this.client.logger.error(a)}})}registerExpirerEvents(){this.client.core.expirer.on(Tr.expired,async e=>{const{topic:t,id:i}=Ul(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,he("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession(t,!0),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(vs.create,e=>this.onPairingCreated(e))}isValidPairingTopic(e){if(!kt(e,!1)){const{message:t}=he("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}=he("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(In(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=he("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!kt(e,!1)){const{message:t}=he("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(!this.client.session.keys.includes(e)){const{message:t}=he("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(In(this.client.session.get(e).expiry)){await this.deleteSession(e);const{message:t}=he("EXPIRED",`session topic: ${e}`);throw 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(kt(e,!1)){const{message:t}=he("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=he("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!c1(e)){const{message:t}=he("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=he("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(In(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:t}=he("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class W3 extends uo{constructor(e,t){super(e,t,U3,$c),this.core=e,this.logger=t}}class Y3 extends uo{constructor(e,t){super(e,t,j3,$c),this.core=e,this.logger=t}}class J3 extends uo{constructor(e,t){super(e,t,q3,$c,i=>i.id),this.core=e,this.logger=t}}class Uc extends nm{constructor(e){super(e),this.protocol=yd,this.version=_d,this.name=Fc.name,this.events=new Yt.exports.EventEmitter,this.on=(i,o)=>this.events.on(i,o),this.once=(i,o)=>this.events.once(i,o),this.off=(i,o)=>this.events.off(i,o),this.removeListener=(i,o)=>this.events.removeListener(i,o),this.removeAllListeners=i=>this.events.removeAllListeners(i),this.connect=async i=>{try{return await this.engine.connect(i)}catch(o){throw this.logger.error(o.message),o}},this.pair=async i=>{try{return await this.engine.pair(i)}catch(o){throw this.logger.error(o.message),o}},this.approve=async i=>{try{return await this.engine.approve(i)}catch(o){throw this.logger.error(o.message),o}},this.reject=async i=>{try{return await this.engine.reject(i)}catch(o){throw this.logger.error(o.message),o}},this.update=async i=>{try{return await this.engine.update(i)}catch(o){throw this.logger.error(o.message),o}},this.extend=async i=>{try{return await this.engine.extend(i)}catch(o){throw this.logger.error(o.message),o}},this.request=async i=>{try{return await this.engine.request(i)}catch(o){throw this.logger.error(o.message),o}},this.respond=async i=>{try{return await this.engine.respond(i)}catch(o){throw this.logger.error(o.message),o}},this.ping=async i=>{try{return await this.engine.ping(i)}catch(o){throw this.logger.error(o.message),o}},this.emit=async i=>{try{return await this.engine.emit(i)}catch(o){throw this.logger.error(o.message),o}},this.disconnect=async i=>{try{return await this.engine.disconnect(i)}catch(o){throw this.logger.error(o.message),o}},this.find=i=>{try{return this.engine.find(i)}catch(o){throw this.logger.error(o.message),o}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}},this.name=e?.name||Fc.name,this.metadata=e?.metadata||x_();const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Je.pino(Je.getDefaultLoggerOptions({level:e?.logger||Fc.logger}));this.core=e?.core||new L3(e),this.logger=Je.generateChildLogger(t,this.name),this.session=new Y3(this.core,this.logger),this.proposal=new W3(this.core,this.logger),this.pendingRequest=new J3(this.core,this.logger),this.engine=new G3(this)}static async init(e){const t=new Uc(e);return await t.initialize(),t}get context(){return Je.getLoggerContext(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),this.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 jc={exports:{}};(function(r,e){var t=typeof self<"u"?self:Vt,i=function(){function a(){this.fetch=!1,this.DOMException=t.DOMException}return a.prototype=t,new a}();(function(a){(function(u){var f={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 v(m){return m&&DataView.prototype.isPrototypeOf(m)}if(f.arrayBuffer)var p=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],w=ArrayBuffer.isView||function(m){return m&&p.indexOf(Object.prototype.toString.call(m))>-1};function I(m){if(typeof m!="string"&&(m=String(m)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(m))throw new TypeError("Invalid character in header field name");return m.toLowerCase()}function S(m){return typeof m!="string"&&(m=String(m)),m}function C(m){var P={next:function(){var ee=m.shift();return{done:ee===void 0,value:ee}}};return f.iterable&&(P[Symbol.iterator]=function(){return P}),P}function R(m){this.map={},m instanceof R?m.forEach(function(P,ee){this.append(ee,P)},this):Array.isArray(m)?m.forEach(function(P){this.append(P[0],P[1])},this):m&&Object.getOwnPropertyNames(m).forEach(function(P){this.append(P,m[P])},this)}R.prototype.append=function(m,P){m=I(m),P=S(P);var ee=this.map[m];this.map[m]=ee?ee+", "+P:P},R.prototype.delete=function(m){delete this.map[I(m)]},R.prototype.get=function(m){return m=I(m),this.has(m)?this.map[m]:null},R.prototype.has=function(m){return this.map.hasOwnProperty(I(m))},R.prototype.set=function(m,P){this.map[I(m)]=S(P)},R.prototype.forEach=function(m,P){for(var ee in this.map)this.map.hasOwnProperty(ee)&&m.call(P,this.map[ee],ee,this)},R.prototype.keys=function(){var m=[];return this.forEach(function(P,ee){m.push(ee)}),C(m)},R.prototype.values=function(){var m=[];return this.forEach(function(P){m.push(P)}),C(m)},R.prototype.entries=function(){var m=[];return this.forEach(function(P,ee){m.push([ee,P])}),C(m)},f.iterable&&(R.prototype[Symbol.iterator]=R.prototype.entries);function B(m){if(m.bodyUsed)return Promise.reject(new TypeError("Already read"));m.bodyUsed=!0}function K(m){return new Promise(function(P,ee){m.onload=function(){P(m.result)},m.onerror=function(){ee(m.error)}})}function se(m){var P=new FileReader,ee=K(P);return P.readAsArrayBuffer(m),ee}function $(m){var P=new FileReader,ee=K(P);return P.readAsText(m),ee}function U(m){for(var P=new Uint8Array(m),ee=new Array(P.length),Q=0;Q<P.length;Q++)ee[Q]=String.fromCharCode(P[Q]);return ee.join("")}function x(m){if(m.slice)return m.slice(0);var P=new Uint8Array(m.byteLength);return P.set(new Uint8Array(m)),P.buffer}function T(){return this.bodyUsed=!1,this._initBody=function(m){this._bodyInit=m,m?typeof m=="string"?this._bodyText=m:f.blob&&Blob.prototype.isPrototypeOf(m)?this._bodyBlob=m:f.formData&&FormData.prototype.isPrototypeOf(m)?this._bodyFormData=m:f.searchParams&&URLSearchParams.prototype.isPrototypeOf(m)?this._bodyText=m.toString():f.arrayBuffer&&f.blob&&v(m)?(this._bodyArrayBuffer=x(m.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):f.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(m)||w(m))?this._bodyArrayBuffer=x(m):this._bodyText=m=Object.prototype.toString.call(m):this._bodyText="",this.headers.get("content-type")||(typeof m=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):f.searchParams&&URLSearchParams.prototype.isPrototypeOf(m)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},f.blob&&(this.blob=function(){var m=B(this);if(m)return m;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?B(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(se)}),this.text=function(){var m=B(this);if(m)return m;if(this._bodyBlob)return $(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(U(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},f.formData&&(this.formData=function(){return this.text().then(G)}),this.json=function(){return this.text().then(JSON.parse)},this}var E=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function h(m){var P=m.toUpperCase();return E.indexOf(P)>-1?P:m}function b(m,P){P=P||{};var ee=P.body;if(m instanceof b){if(m.bodyUsed)throw new TypeError("Already read");this.url=m.url,this.credentials=m.credentials,P.headers||(this.headers=new R(m.headers)),this.method=m.method,this.mode=m.mode,this.signal=m.signal,!ee&&m._bodyInit!=null&&(ee=m._bodyInit,m.bodyUsed=!0)}else this.url=String(m);if(this.credentials=P.credentials||this.credentials||"same-origin",(P.headers||!this.headers)&&(this.headers=new R(P.headers)),this.method=h(P.method||this.method||"GET"),this.mode=P.mode||this.mode||null,this.signal=P.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&ee)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(ee)}b.prototype.clone=function(){return new b(this,{body:this._bodyInit})};function G(m){var P=new FormData;return m.trim().split("&").forEach(function(ee){if(ee){var Q=ee.split("="),V=Q.shift().replace(/\+/g," "),k=Q.join("=").replace(/\+/g," ");P.append(decodeURIComponent(V),decodeURIComponent(k))}}),P}function Y(m){var P=new R,ee=m.replace(/\r?\n[\t ]+/g," ");return ee.split(/\r?\n/).forEach(function(Q){var V=Q.split(":"),k=V.shift().trim();if(k){var J=V.join(":").trim();P.append(k,J)}}),P}T.call(b.prototype);function ie(m,P){P||(P={}),this.type="default",this.status=P.status===void 0?200:P.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in P?P.statusText:"OK",this.headers=new R(P.headers),this.url=P.url||"",this._initBody(m)}T.call(ie.prototype),ie.prototype.clone=function(){return new ie(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new R(this.headers),url:this.url})},ie.error=function(){var m=new ie(null,{status:0,statusText:""});return m.type="error",m};var ce=[301,302,303,307,308];ie.redirect=function(m,P){if(ce.indexOf(P)===-1)throw new RangeError("Invalid status code");return new ie(null,{status:P,headers:{location:m}})},u.DOMException=a.DOMException;try{new u.DOMException}catch{u.DOMException=function(P,ee){this.message=P,this.name=ee;var Q=Error(P);this.stack=Q.stack},u.DOMException.prototype=Object.create(Error.prototype),u.DOMException.prototype.constructor=u.DOMException}function de(m,P){return new Promise(function(ee,Q){var V=new b(m,P);if(V.signal&&V.signal.aborted)return Q(new u.DOMException("Aborted","AbortError"));var k=new XMLHttpRequest;function J(){k.abort()}k.onload=function(){var re={status:k.status,statusText:k.statusText,headers:Y(k.getAllResponseHeaders()||"")};re.url="responseURL"in k?k.responseURL:re.headers.get("X-Request-URL");var me="response"in k?k.response:k.responseText;ee(new ie(me,re))},k.onerror=function(){Q(new TypeError("Network request failed"))},k.ontimeout=function(){Q(new TypeError("Network request failed"))},k.onabort=function(){Q(new u.DOMException("Aborted","AbortError"))},k.open(V.method,V.url,!0),V.credentials==="include"?k.withCredentials=!0:V.credentials==="omit"&&(k.withCredentials=!1),"responseType"in k&&f.blob&&(k.responseType="blob"),V.headers.forEach(function(re,me){k.setRequestHeader(me,re)}),V.signal&&(V.signal.addEventListener("abort",J),k.onreadystatechange=function(){k.readyState===4&&V.signal.removeEventListener("abort",J)}),k.send(typeof V._bodyInit>"u"?null:V._bodyInit)})}return de.polyfill=!0,a.fetch||(a.fetch=de,a.Headers=R,a.Request=b,a.Response=ie),u.Headers=R,u.Request=b,u.Response=ie,u.fetch=de,Object.defineProperty(u,"__esModule",{value:!0}),u})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var o=i;e=o.fetch,e.default=o.fetch,e.fetch=o.fetch,e.Headers=o.Headers,e.Request=o.Request,e.Response=o.Response,r.exports=e})(jc,jc.exports);var Sd=qg(jc.exports);const xd={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},Od=10;class Cn{constructor(e,t=!1){if(this.url=e,this.disableProviderPing=t,this.events=new Yt.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!Rf(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 i=ls(e),a=await(await Sd(this.url,Object.assign(Object.assign({},xd),{body:i}))).json();this.onPayload({data:a})}catch(i){this.onError(e.id,i)}}async register(e=this.url){if(!Rf(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((i,o)=>{this.events.once("register_error",a=>{this.resetMaxListeners(),o(a)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return o(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const t=ls({id:1,jsonrpc:"2.0",method:"test",params:[]});await Sd(e,Object.assign(Object.assign({},xd),{body:t}))}this.onOpen()}catch(t){const i=this.parseError(t);throw this.events.emit("register_error",i),this.onClose(),i}}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"?vc(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),o=i.message||i.toString(),a=oo(e,o);this.events.emit("payload",a)}parseError(e,t=this.url){return xf(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Od&&this.events.setMaxListeners(Od)}}const Id="error",Q3="wss://relay.walletconnect.com",X3="wc",Z3="universal_provider",Pd=`${X3}@2:${Z3}:`,e2="https://rpc.walletconnect.com/v1/",dn={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var ms=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Mc={exports:{}};/**
|
|
72
|
+
***************************************************************************** */var bc=function(r,e){return bc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var o in i)i.hasOwnProperty(o)&&(t[o]=i[o])},bc(r,e)};function Pm(r,e){bc(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var mc=function(){return mc=Object.assign||function(e){for(var t,i=1,o=arguments.length;i<o;i++){t=arguments[i];for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a])}return e},mc.apply(this,arguments)};function Cm(r,e){var t={};for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&e.indexOf(i)<0&&(t[i]=r[i]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,i=Object.getOwnPropertySymbols(r);o<i.length;o++)e.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(r,i[o])&&(t[i[o]]=r[i[o]]);return t}function Am(r,e,t,i){var o=arguments.length,a=o<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,u;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,e,t,i);else for(var f=r.length-1;f>=0;f--)(u=r[f])&&(a=(o<3?u(a):o>3?u(e,t,a):u(e,t))||a);return o>3&&a&&Object.defineProperty(e,t,a),a}function Tm(r,e){return function(t,i){e(t,i,r)}}function Rm(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function Nm(r,e,t,i){function o(a){return a instanceof t?a:new t(function(u){u(a)})}return new(t||(t=Promise))(function(a,u){function f(w){try{p(i.next(w))}catch(I){u(I)}}function v(w){try{p(i.throw(w))}catch(I){u(I)}}function p(w){w.done?a(w.value):o(w.value).then(f,v)}p((i=i.apply(r,e||[])).next())})}function $m(r,e){var t={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,o,a,u;return u={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(u[Symbol.iterator]=function(){return this}),u;function f(p){return function(w){return v([p,w])}}function v(p){if(i)throw new TypeError("Generator is already executing.");for(;t;)try{if(i=1,o&&(a=p[0]&2?o.return:p[0]?o.throw||((a=o.return)&&a.call(o),0):o.next)&&!(a=a.call(o,p[1])).done)return a;switch(o=0,a&&(p=[p[0]&2,a.value]),p[0]){case 0:case 1:a=p;break;case 4:return t.label++,{value:p[1],done:!1};case 5:t.label++,o=p[1],p=[0];continue;case 7:p=t.ops.pop(),t.trys.pop();continue;default:if(a=t.trys,!(a=a.length>0&&a[a.length-1])&&(p[0]===6||p[0]===2)){t=0;continue}if(p[0]===3&&(!a||p[1]>a[0]&&p[1]<a[3])){t.label=p[1];break}if(p[0]===6&&t.label<a[1]){t.label=a[1],a=p;break}if(a&&t.label<a[2]){t.label=a[2],t.ops.push(p);break}a[2]&&t.ops.pop(),t.trys.pop();continue}p=e.call(r,t)}catch(w){p=[6,w],o=0}finally{i=a=0}if(p[0]&5)throw p[1];return{value:p[0]?p[1]:void 0,done:!0}}}function Fm(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]}function Lm(r,e){for(var t in r)t!=="default"&&!e.hasOwnProperty(t)&&(e[t]=r[t])}function wc(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],i=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&i>=r.length&&(r=void 0),{value:r&&r[i++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function If(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i=t.call(r),o,a=[],u;try{for(;(e===void 0||e-- >0)&&!(o=i.next()).done;)a.push(o.value)}catch(f){u={error:f}}finally{try{o&&!o.done&&(t=i.return)&&t.call(i)}finally{if(u)throw u.error}}return a}function Um(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(If(arguments[e]));return r}function jm(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var i=Array(r),o=0,e=0;e<t;e++)for(var a=arguments[e],u=0,f=a.length;u<f;u++,o++)i[o]=a[u];return i}function ds(r){return this instanceof ds?(this.v=r,this):new ds(r)}function Mm(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(r,e||[]),o,a=[];return o={},u("next"),u("throw"),u("return"),o[Symbol.asyncIterator]=function(){return this},o;function u(S){i[S]&&(o[S]=function(C){return new Promise(function(R,B){a.push([S,C,R,B])>1||f(S,C)})})}function f(S,C){try{v(i[S](C))}catch(R){I(a[0][3],R)}}function v(S){S.value instanceof ds?Promise.resolve(S.value.v).then(p,w):I(a[0][2],S)}function p(S){f("next",S)}function w(S){f("throw",S)}function I(S,C){S(C),a.shift(),a.length&&f(a[0][0],a[0][1])}}function qm(r){var e,t;return e={},i("next"),i("throw",function(o){throw o}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(o,a){e[o]=r[o]?function(u){return(t=!t)?{value:ds(r[o](u)),done:o==="return"}:a?a(u):u}:a}}function Hm(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 wc=="function"?wc(r):r[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(a){t[a]=r[a]&&function(u){return new Promise(function(f,v){u=r[a](u),o(f,v,u.done,u.value)})}}function o(a,u,f,v){Promise.resolve(v).then(function(p){a({value:p,done:f})},u)}}function Bm(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function zm(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 Km(r){return r&&r.__esModule?r:{default:r}}function Vm(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function km(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 Gm=Object.freeze({__proto__:null,__extends:Pm,get __assign(){return mc},__rest:Cm,__decorate:Am,__param:Tm,__metadata:Rm,__awaiter:Nm,__generator:$m,__createBinding:Fm,__exportStar:Lm,__values:wc,__read:If,__spread:Um,__spreadArrays:jm,__await:ds,__asyncGenerator:Mm,__asyncDelegator:qm,__asyncValues:Hm,__makeTemplateObject:Bm,__importStar:zm,__importDefault:Km,__classPrivateFieldGet:Vm,__classPrivateFieldSet:km}),Wm=Bn(Gm),an={},Pf;function Ym(){if(Pf)return an;Pf=1,Object.defineProperty(an,"__esModule",{value:!0}),an.isBrowserCryptoAvailable=an.getSubtleCrypto=an.getBrowerCrypto=void 0;function r(){return Vt?.crypto||Vt?.msCrypto||{}}an.getBrowerCrypto=r;function e(){const i=r();return i.subtle||i.webkitSubtle}an.getSubtleCrypto=e;function t(){return!!r()&&!!e()}return an.isBrowserCryptoAvailable=t,an}var cn={},Cf;function Jm(){if(Cf)return cn;Cf=1,Object.defineProperty(cn,"__esModule",{value:!0}),cn.isBrowser=cn.isNode=cn.isReactNative=void 0;function r(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}cn.isReactNative=r;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}cn.isNode=e;function t(){return!r()&&!e()}return cn.isBrowser=t,cn}(function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=Wm;e.__exportStar(Ym(),r),e.__exportStar(Jm(),r)})(Of);function Ec(r=3){const e=Date.now()*Math.pow(10,r),t=Math.floor(Math.random()*Math.pow(10,r));return e+t}function Af(r=6){return BigInt(Ec(r))}function Ei(r,e,t){return{id:t||Ec(),jsonrpc:"2.0",method:r,params:e}}function Dc(r,e){return{id:r,jsonrpc:"2.0",result:e}}function oo(r,e,t){return{id:r,jsonrpc:"2.0",error:Qm(e,t)}}function Qm(r,e){return typeof r>"u"?Sf(Ef):(typeof r=="string"&&(r=Object.assign(Object.assign({},Sf(_c)),{message:r})),typeof e<"u"&&(r.data=e),Om(r.code)&&(r=Im(r.code)),r)}class Xm{}class Zm extends Xm{constructor(){super()}}class ew extends Zm{constructor(e){super()}}const tw="^https?:",rw="^wss?:";function nw(r){const e=r.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Tf(r,e){const t=nw(r);return typeof t>"u"?!1:new RegExp(e).test(t)}function Rf(r){return Tf(r,tw)}function Nf(r){return Tf(r,rw)}function iw(r){return new RegExp("wss?://localhost(:d{2,5})?").test(r)}function $f(r){return typeof r=="object"&&"id"in r&&"jsonrpc"in r&&r.jsonrpc==="2.0"}function Sc(r){return $f(r)&&"method"in r}function ao(r){return $f(r)&&(un(r)||zr(r))}function un(r){return"result"in r}function zr(r){return"error"in r}class hn extends ew{constructor(e){super(e),this.events=new Yt.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(Ei(e.method,e.params||[],e.id||Af().toString()),t)}async requestStrict(e,t){return new Promise(async(i,o)=>{if(!this.connection.connected)try{await this.open()}catch(a){o(a)}this.events.on(`${e.id}`,a=>{zr(a)?o(a.error):i(a.result)});try{await this.connection.send(e,t)}catch(a){o(a)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ao(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 sw=()=>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"),ow=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Ff=r=>r.split("?")[0],Lf=10,aw=sw();class cw{constructor(e){if(this.url=e,this.events=new Yt.exports.EventEmitter,this.registering=!1,!Nf(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=i=>{this.onClose(i),e()},this.socket.close()})}async send(e,t){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ls(e))}catch(i){this.onError(e.id,i)}}register(e=this.url){if(!Nf(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((i,o)=>{this.events.once("register_error",a=>{this.resetMaxListeners(),o(a)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return o(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((t,i)=>{const o=Of.isReactNative()?void 0:{rejectUnauthorized:!iw(e)},a=new aw(e,[],o);ow()?a.onerror=u=>{const f=u;i(this.emitError(f.error))}:a.on("error",u=>{i(this.emitError(u))}),a.onopen=()=>{this.onOpen(a),t(a)}})}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"?vc(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),o=i.message||i.toString(),a=oo(e,o);this.events.emit("payload",a)}parseError(e,t=this.url){return xf(e,Ff(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Lf&&this.events.setMaxListeners(Lf)}emitError(e){const t=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Ff(this.url)}`));return this.events.emit("register_error",t),t}}var xc={exports:{}};(function(r,e){var t=200,i="__lodash_hash_undefined__",o=1,a=2,u=9007199254740991,f="[object Arguments]",v="[object Array]",p="[object AsyncFunction]",w="[object Boolean]",I="[object Date]",S="[object Error]",C="[object Function]",R="[object GeneratorFunction]",B="[object Map]",K="[object Number]",se="[object Null]",$="[object Object]",U="[object Promise]",x="[object Proxy]",T="[object RegExp]",E="[object Set]",h="[object String]",b="[object Symbol]",G="[object Undefined]",Y="[object WeakMap]",ie="[object ArrayBuffer]",ce="[object DataView]",de="[object Float32Array]",m="[object Float64Array]",P="[object Int8Array]",ee="[object Int16Array]",Q="[object Int32Array]",V="[object Uint8Array]",k="[object Uint8ClampedArray]",J="[object Uint16Array]",re="[object Uint32Array]",me=/[\\^$.*+?()[\]{}|]/g,oe=/^\[object .+?Constructor\]$/,we=/^(?:0|[1-9]\d*)$/,le={};le[de]=le[m]=le[P]=le[ee]=le[Q]=le[V]=le[k]=le[J]=le[re]=!0,le[f]=le[v]=le[ie]=le[w]=le[ce]=le[I]=le[S]=le[C]=le[B]=le[K]=le[$]=le[T]=le[E]=le[h]=le[Y]=!1;var _e=typeof Vt=="object"&&Vt&&Vt.Object===Object&&Vt,H=typeof self=="object"&&self&&self.Object===Object&&self,q=_e||H||Function("return this")(),F=e&&!e.nodeType&&e,d=F&&!0&&r&&!r.nodeType&&r,A=d&&d.exports===F,ae=A&&_e.process,fe=function(){try{return ae&&ae.binding&&ae.binding("util")}catch{}}(),xe=fe&&fe.isTypedArray;function Be(D,L){for(var te=-1,pe=D==null?0:D.length,ct=0,Te=[];++te<pe;){var dt=D[te];L(dt,te,D)&&(Te[ct++]=dt)}return Te}function Ve(D,L){for(var te=-1,pe=L.length,ct=D.length;++te<pe;)D[ct+te]=L[te];return D}function Ue(D,L){for(var te=-1,pe=D==null?0:D.length;++te<pe;)if(L(D[te],te,D))return!0;return!1}function vt(D,L){for(var te=-1,pe=Array(D);++te<D;)pe[te]=L(te);return pe}function yt(D){return function(L){return D(L)}}function Me(D,L){return D.has(L)}function Oe(D,L){return D?.[L]}function $e(D){var L=-1,te=Array(D.size);return D.forEach(function(pe,ct){te[++L]=[ct,pe]}),te}function Fe(D,L){return function(te){return D(L(te))}}function qe(D){var L=-1,te=Array(D.size);return D.forEach(function(pe){te[++L]=pe}),te}var Pe=Array.prototype,Le=Function.prototype,Se=Object.prototype,Ce=q["__core-js_shared__"],ze=Le.toString,Ie=Se.hasOwnProperty,ke=function(){var D=/[^.]+$/.exec(Ce&&Ce.keys&&Ce.keys.IE_PROTO||"");return D?"Symbol(src)_1."+D:""}(),We=Se.toString,et=RegExp("^"+ze.call(Ie).replace(me,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),tt=A?q.Buffer:void 0,Qe=q.Symbol,cr=q.Uint8Array,yr=Se.propertyIsEnumerable,en=Pe.splice,ur=Qe?Qe.toStringTag:void 0,pn=Object.getOwnPropertySymbols,Tn=tt?tt.isBuffer:void 0,Xn=Fe(Object.keys,Object),Dt=xr(q,"DataView"),_t=xr(q,"Map"),St=xr(q,"Promise"),xt=xr(q,"Set"),wt=xr(q,"WeakMap"),bt=xr(Object,"create"),Lt=vn(Dt),Ut=vn(_t),Ot=vn(St),jt=vn(xt),It=vn(wt),Tt=Qe?Qe.prototype:void 0,Pt=Tt?Tt.valueOf:void 0;function ft(D){var L=-1,te=D==null?0:D.length;for(this.clear();++L<te;){var pe=D[L];this.set(pe[0],pe[1])}}function Mt(){this.__data__=bt?bt(null):{},this.size=0}function qt(D){var L=this.has(D)&&delete this.__data__[D];return this.size-=L?1:0,L}function Vc(D){var L=this.__data__;if(bt){var te=L[D];return te===i?void 0:te}return Ie.call(L,D)?L[D]:void 0}function kc(D){var L=this.__data__;return bt?L[D]!==void 0:Ie.call(L,D)}function Gc(D,L){var te=this.__data__;return this.size+=this.has(D)?0:1,te[D]=bt&&L===void 0?i:L,this}ft.prototype.clear=Mt,ft.prototype.delete=qt,ft.prototype.get=Vc,ft.prototype.has=kc,ft.prototype.set=Gc;function Rr(D){var L=-1,te=D==null?0:D.length;for(this.clear();++L<te;){var pe=D[L];this.set(pe[0],pe[1])}}function Wc(){this.__data__=[],this.size=0}function Yc(D){var L=this.__data__,te=Zn(L,D);if(te<0)return!1;var pe=L.length-1;return te==pe?L.pop():en.call(L,te,1),--this.size,!0}function Jc(D){var L=this.__data__,te=Zn(L,D);return te<0?void 0:L[te][1]}function Qc(D){return Zn(this.__data__,D)>-1}function Xc(D,L){var te=this.__data__,pe=Zn(te,D);return pe<0?(++this.size,te.push([D,L])):te[pe][1]=L,this}Rr.prototype.clear=Wc,Rr.prototype.delete=Yc,Rr.prototype.get=Jc,Rr.prototype.has=Qc,Rr.prototype.set=Xc;function gn(D){var L=-1,te=D==null?0:D.length;for(this.clear();++L<te;){var pe=D[L];this.set(pe[0],pe[1])}}function Si(){this.size=0,this.__data__={hash:new ft,map:new(_t||Rr),string:new ft}}function Zc(D){var L=Rn(this,D).delete(D);return this.size-=L?1:0,L}function xi(D){return Rn(this,D).get(D)}function eu(D){return Rn(this,D).has(D)}function tu(D,L){var te=Rn(this,D),pe=te.size;return te.set(D,L),this.size+=te.size==pe?0:1,this}gn.prototype.clear=Si,gn.prototype.delete=Zc,gn.prototype.get=xi,gn.prototype.has=eu,gn.prototype.set=tu;function Oi(D){var L=-1,te=D==null?0:D.length;for(this.__data__=new gn;++L<te;)this.add(D[L])}function _o(D){return this.__data__.set(D,i),this}function bo(D){return this.__data__.has(D)}Oi.prototype.add=Oi.prototype.push=_o,Oi.prototype.has=bo;function Vr(D){var L=this.__data__=new Rr(D);this.size=L.size}function ru(){this.__data__=new Rr,this.size=0}function nu(D){var L=this.__data__,te=L.delete(D);return this.size=L.size,te}function iu(D){return this.__data__.get(D)}function su(D){return this.__data__.has(D)}function mo(D,L){var te=this.__data__;if(te instanceof Rr){var pe=te.__data__;if(!_t||pe.length<t-1)return pe.push([D,L]),this.size=++te.size,this;te=this.__data__=new gn(pe)}return te.set(D,L),this.size=te.size,this}Vr.prototype.clear=ru,Vr.prototype.delete=nu,Vr.prototype.get=iu,Vr.prototype.has=su,Vr.prototype.set=mo;function wo(D,L){var te=Ci(D),pe=!te&&No(D),ct=!te&&!pe&&Ss(D),Te=!te&&!pe&&!ct&&Lo(D),dt=te||pe||ct||Te,Ht=dt?vt(D.length,String):[],Xe=Ht.length;for(var ut in D)(L||Ie.call(D,ut))&&!(dt&&(ut=="length"||ct&&(ut=="offset"||ut=="parent")||Te&&(ut=="buffer"||ut=="byteLength"||ut=="byteOffset")||Po(ut,Xe)))&&Ht.push(ut);return Ht}function Zn(D,L){for(var te=D.length;te--;)if(Ro(D[te][0],L))return te;return-1}function Es(D,L,te){var pe=L(D);return Ci(D)?pe:Ve(pe,te(D))}function ei(D){return D==null?D===void 0?G:se:ur&&ur in Object(D)?Oo(D):cu(D)}function Ds(D){return ri(D)&&ei(D)==f}function ti(D,L,te,pe,ct){return D===L?!0:D==null||L==null||!ri(D)&&!ri(L)?D!==D&&L!==L:Eo(D,L,te,pe,ti,ct)}function Eo(D,L,te,pe,ct,Te){var dt=Ci(D),Ht=Ci(L),Xe=dt?v:tn(D),ut=Ht?v:tn(L);Xe=Xe==f?$:Xe,ut=ut==f?$:ut;var Rt=Xe==$,_r=ut==$,Bt=Xe==ut;if(Bt&&Ss(D)){if(!Ss(L))return!1;dt=!0,Rt=!1}if(Bt&&!Rt)return Te||(Te=new Vr),dt||Lo(D)?Ii(D,L,te,pe,ct,Te):au(D,L,Xe,te,pe,ct,Te);if(!(te&o)){var pt=Rt&&Ie.call(D,"__wrapped__"),hr=_r&&Ie.call(L,"__wrapped__");if(pt||hr){var kr=pt?D.value():D,Nr=hr?L.value():L;return Te||(Te=new Vr),ct(kr,Nr,te,pe,Te)}}return Bt?(Te||(Te=new Vr),xo(D,L,te,pe,ct,Te)):!1}function ou(D){if(!Fo(D)||Ao(D))return!1;var L=Ai(D)?et:oe;return L.test(vn(D))}function Do(D){return ri(D)&&$o(D.length)&&!!le[ei(D)]}function So(D){if(!To(D))return Xn(D);var L=[];for(var te in Object(D))Ie.call(D,te)&&te!="constructor"&&L.push(te);return L}function Ii(D,L,te,pe,ct,Te){var dt=te&o,Ht=D.length,Xe=L.length;if(Ht!=Xe&&!(dt&&Xe>Ht))return!1;var ut=Te.get(D);if(ut&&Te.get(L))return ut==L;var Rt=-1,_r=!0,Bt=te&a?new Oi:void 0;for(Te.set(D,L),Te.set(L,D);++Rt<Ht;){var pt=D[Rt],hr=L[Rt];if(pe)var kr=dt?pe(hr,pt,Rt,L,D,Te):pe(pt,hr,Rt,D,L,Te);if(kr!==void 0){if(kr)continue;_r=!1;break}if(Bt){if(!Ue(L,function(Nr,rn){if(!Me(Bt,rn)&&(pt===Nr||ct(pt,Nr,te,pe,Te)))return Bt.push(rn)})){_r=!1;break}}else if(!(pt===hr||ct(pt,hr,te,pe,Te))){_r=!1;break}}return Te.delete(D),Te.delete(L),_r}function au(D,L,te,pe,ct,Te,dt){switch(te){case ce:if(D.byteLength!=L.byteLength||D.byteOffset!=L.byteOffset)return!1;D=D.buffer,L=L.buffer;case ie:return!(D.byteLength!=L.byteLength||!Te(new cr(D),new cr(L)));case w:case I:case K:return Ro(+D,+L);case S:return D.name==L.name&&D.message==L.message;case T:case h:return D==L+"";case B:var Ht=$e;case E:var Xe=pe&o;if(Ht||(Ht=qe),D.size!=L.size&&!Xe)return!1;var ut=dt.get(D);if(ut)return ut==L;pe|=a,dt.set(D,L);var Rt=Ii(Ht(D),Ht(L),pe,ct,Te,dt);return dt.delete(D),Rt;case b:if(Pt)return Pt.call(D)==Pt.call(L)}return!1}function xo(D,L,te,pe,ct,Te){var dt=te&o,Ht=Pi(D),Xe=Ht.length,ut=Pi(L),Rt=ut.length;if(Xe!=Rt&&!dt)return!1;for(var _r=Xe;_r--;){var Bt=Ht[_r];if(!(dt?Bt in L:Ie.call(L,Bt)))return!1}var pt=Te.get(D);if(pt&&Te.get(L))return pt==L;var hr=!0;Te.set(D,L),Te.set(L,D);for(var kr=dt;++_r<Xe;){Bt=Ht[_r];var Nr=D[Bt],rn=L[Bt];if(pe)var xs=dt?pe(rn,Nr,Bt,L,D,Te):pe(Nr,rn,Bt,D,L,Te);if(!(xs===void 0?Nr===rn||ct(Nr,rn,te,pe,Te):xs)){hr=!1;break}kr||(kr=Bt=="constructor")}if(hr&&!kr){var ni=D.constructor,Gt=L.constructor;ni!=Gt&&"constructor"in D&&"constructor"in L&&!(typeof ni=="function"&&ni instanceof ni&&typeof Gt=="function"&&Gt instanceof Gt)&&(hr=!1)}return Te.delete(D),Te.delete(L),hr}function Pi(D){return Es(D,lu,Io)}function Rn(D,L){var te=D.__data__;return Co(L)?te[typeof L=="string"?"string":"hash"]:te.map}function xr(D,L){var te=Oe(D,L);return ou(te)?te:void 0}function Oo(D){var L=Ie.call(D,ur),te=D[ur];try{D[ur]=void 0;var pe=!0}catch{}var ct=We.call(D);return pe&&(L?D[ur]=te:delete D[ur]),ct}var Io=pn?function(D){return D==null?[]:(D=Object(D),Be(pn(D),function(L){return yr.call(D,L)}))}:at,tn=ei;(Dt&&tn(new Dt(new ArrayBuffer(1)))!=ce||_t&&tn(new _t)!=B||St&&tn(St.resolve())!=U||xt&&tn(new xt)!=E||wt&&tn(new wt)!=Y)&&(tn=function(D){var L=ei(D),te=L==$?D.constructor:void 0,pe=te?vn(te):"";if(pe)switch(pe){case Lt:return ce;case Ut:return B;case Ot:return U;case jt:return E;case It:return Y}return L});function Po(D,L){return L=L??u,!!L&&(typeof D=="number"||we.test(D))&&D>-1&&D%1==0&&D<L}function Co(D){var L=typeof D;return L=="string"||L=="number"||L=="symbol"||L=="boolean"?D!=="__proto__":D===null}function Ao(D){return!!ke&&ke in D}function To(D){var L=D&&D.constructor,te=typeof L=="function"&&L.prototype||Se;return D===te}function cu(D){return We.call(D)}function vn(D){if(D!=null){try{return ze.call(D)}catch{}try{return D+""}catch{}}return""}function Ro(D,L){return D===L||D!==D&&L!==L}var No=Ds(function(){return arguments}())?Ds:function(D){return ri(D)&&Ie.call(D,"callee")&&!yr.call(D,"callee")},Ci=Array.isArray;function uu(D){return D!=null&&$o(D.length)&&!Ai(D)}var Ss=Tn||ot;function hu(D,L){return ti(D,L)}function Ai(D){if(!Fo(D))return!1;var L=ei(D);return L==C||L==R||L==p||L==x}function $o(D){return typeof D=="number"&&D>-1&&D%1==0&&D<=u}function Fo(D){var L=typeof D;return D!=null&&(L=="object"||L=="function")}function ri(D){return D!=null&&typeof D=="object"}var Lo=xe?yt(xe):Do;function lu(D){return uu(D)?wo(D):So(D)}function at(){return[]}function ot(){return!1}r.exports=hu})(xc,xc.exports);var uw=xc.exports,hw=Object.defineProperty,Uf=Object.getOwnPropertySymbols,lw=Object.prototype.hasOwnProperty,fw=Object.prototype.propertyIsEnumerable,jf=(r,e,t)=>e in r?hw(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ar=(r,e)=>{for(var t in e||(e={}))lw.call(e,t)&&jf(r,t,e[t]);if(Uf)for(var t of Uf(e))fw.call(e,t)&&jf(r,t,e[t]);return r};function dw(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var o=0;o<r.length;o++){var a=r.charAt(o),u=a.charCodeAt(0);if(t[u]!==255)throw new TypeError(a+" is ambiguous");t[u]=o}var f=r.length,v=r.charAt(0),p=Math.log(f)/Math.log(256),w=Math.log(256)/Math.log(f);function I(R){if(R instanceof Uint8Array||(ArrayBuffer.isView(R)?R=new Uint8Array(R.buffer,R.byteOffset,R.byteLength):Array.isArray(R)&&(R=Uint8Array.from(R))),!(R instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(R.length===0)return"";for(var B=0,K=0,se=0,$=R.length;se!==$&&R[se]===0;)se++,B++;for(var U=($-se)*w+1>>>0,x=new Uint8Array(U);se!==$;){for(var T=R[se],E=0,h=U-1;(T!==0||E<K)&&h!==-1;h--,E++)T+=256*x[h]>>>0,x[h]=T%f>>>0,T=T/f>>>0;if(T!==0)throw new Error("Non-zero carry");K=E,se++}for(var b=U-K;b!==U&&x[b]===0;)b++;for(var G=v.repeat(B);b<U;++b)G+=r.charAt(x[b]);return G}function S(R){if(typeof R!="string")throw new TypeError("Expected String");if(R.length===0)return new Uint8Array;var B=0;if(R[B]!==" "){for(var K=0,se=0;R[B]===v;)K++,B++;for(var $=(R.length-B)*p+1>>>0,U=new Uint8Array($);R[B];){var x=t[R.charCodeAt(B)];if(x===255)return;for(var T=0,E=$-1;(x!==0||T<se)&&E!==-1;E--,T++)x+=f*U[E]>>>0,U[E]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");se=T,B++}if(R[B]!==" "){for(var h=$-se;h!==$&&U[h]===0;)h++;for(var b=new Uint8Array(K+($-h)),G=K;h!==$;)b[G++]=U[h++];return b}}}function C(R){var B=S(R);if(B)return B;throw new Error(`Non-${e} character`)}return{encode:I,decodeUnsafe:S,decode:C}}var pw=dw,gw=pw;const Mf=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")},vw=r=>new TextEncoder().encode(r),yw=r=>new TextDecoder().decode(r);class _w{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class bw{constructor(e,t,i){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=i}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 qf(this,e)}}class mw{constructor(e){this.decoders=e}or(e){return qf(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const qf=(r,e)=>new mw(ar(ar({},r.decoders||{[r.prefix]:r}),e.decoders||{[e.prefix]:e}));class ww{constructor(e,t,i,o){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=o,this.encoder=new _w(e,t,i),this.decoder=new bw(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const co=({name:r,prefix:e,encode:t,decode:i})=>new ww(r,e,t,i),ps=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:o}=gw(t,e);return co({prefix:r,name:e,encode:i,decode:a=>Mf(o(a))})},Ew=(r,e,t,i)=>{const o={};for(let w=0;w<e.length;++w)o[e[w]]=w;let a=r.length;for(;r[a-1]==="=";)--a;const u=new Uint8Array(a*t/8|0);let f=0,v=0,p=0;for(let w=0;w<a;++w){const I=o[r[w]];if(I===void 0)throw new SyntaxError(`Non-${i} character`);v=v<<t|I,f+=t,f>=8&&(f-=8,u[p++]=255&v>>f)}if(f>=t||255&v<<8-f)throw new SyntaxError("Unexpected end of data");return u},Dw=(r,e,t)=>{const i=e[e.length-1]==="=",o=(1<<t)-1;let a="",u=0,f=0;for(let v=0;v<r.length;++v)for(f=f<<8|r[v],u+=8;u>t;)u-=t,a+=e[o&f>>u];if(u&&(a+=e[o&f<<t-u]),i)for(;a.length*t&7;)a+="=";return a},Qt=({name:r,prefix:e,bitsPerChar:t,alphabet:i})=>co({prefix:e,name:r,encode(o){return Dw(o,i,t)},decode(o){return Ew(o,i,t,r)}}),Sw=co({prefix:"\0",name:"identity",encode:r=>yw(r),decode:r=>vw(r)});var xw=Object.freeze({__proto__:null,identity:Sw});const Ow=Qt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Iw=Object.freeze({__proto__:null,base2:Ow});const Pw=Qt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Cw=Object.freeze({__proto__:null,base8:Pw});const Aw=ps({prefix:"9",name:"base10",alphabet:"0123456789"});var Tw=Object.freeze({__proto__:null,base10:Aw});const Rw=Qt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Nw=Qt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var $w=Object.freeze({__proto__:null,base16:Rw,base16upper:Nw});const Fw=Qt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Lw=Qt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Uw=Qt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),jw=Qt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Mw=Qt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),qw=Qt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Hw=Qt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Bw=Qt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),zw=Qt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Kw=Object.freeze({__proto__:null,base32:Fw,base32upper:Lw,base32pad:Uw,base32padupper:jw,base32hex:Mw,base32hexupper:qw,base32hexpad:Hw,base32hexpadupper:Bw,base32z:zw});const Vw=ps({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),kw=ps({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Gw=Object.freeze({__proto__:null,base36:Vw,base36upper:kw});const Ww=ps({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Yw=ps({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Jw=Object.freeze({__proto__:null,base58btc:Ww,base58flickr:Yw});const Qw=Qt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Xw=Qt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zw=Qt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),eE=Qt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var tE=Object.freeze({__proto__:null,base64:Qw,base64pad:Xw,base64url:Zw,base64urlpad:eE});const Hf=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}"),rE=Hf.reduce((r,e,t)=>(r[t]=e,r),[]),nE=Hf.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function iE(r){return r.reduce((e,t)=>(e+=rE[t],e),"")}function sE(r){const e=[];for(const t of r){const i=nE[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const oE=co({prefix:"\u{1F680}",name:"base256emoji",encode:iE,decode:sE});var aE=Object.freeze({__proto__:null,base256emoji:oE}),cE=zf,Bf=128,uE=127,hE=~uE,lE=Math.pow(2,31);function zf(r,e,t){e=e||[],t=t||0;for(var i=t;r>=lE;)e[t++]=r&255|Bf,r/=128;for(;r&hE;)e[t++]=r&255|Bf,r>>>=7;return e[t]=r|0,zf.bytes=t-i+1,e}var fE=Oc,dE=128,Kf=127;function Oc(r,i){var t=0,i=i||0,o=0,a=i,u,f=r.length;do{if(a>=f)throw Oc.bytes=0,new RangeError("Could not decode varint");u=r[a++],t+=o<28?(u&Kf)<<o:(u&Kf)*Math.pow(2,o),o+=7}while(u>=dE);return Oc.bytes=a-i,t}var pE=Math.pow(2,7),gE=Math.pow(2,14),vE=Math.pow(2,21),yE=Math.pow(2,28),_E=Math.pow(2,35),bE=Math.pow(2,42),mE=Math.pow(2,49),wE=Math.pow(2,56),EE=Math.pow(2,63),DE=function(r){return r<pE?1:r<gE?2:r<vE?3:r<yE?4:r<_E?5:r<bE?6:r<mE?7:r<wE?8:r<EE?9:10},SE={encode:cE,decode:fE,encodingLength:DE},Vf=SE;const kf=(r,e,t=0)=>(Vf.encode(r,e,t),e),Gf=r=>Vf.encodingLength(r),Ic=(r,e)=>{const t=e.byteLength,i=Gf(r),o=i+Gf(t),a=new Uint8Array(o+t);return kf(r,a,0),kf(t,a,i),a.set(e,o),new xE(r,t,e,a)};class xE{constructor(e,t,i,o){this.code=e,this.size=t,this.digest=i,this.bytes=o}}const Wf=({name:r,code:e,encode:t})=>new OE(r,e,t);class OE{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Ic(this.code,t):t.then(i=>Ic(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Yf=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),IE=Wf({name:"sha2-256",code:18,encode:Yf("SHA-256")}),PE=Wf({name:"sha2-512",code:19,encode:Yf("SHA-512")});var CE=Object.freeze({__proto__:null,sha256:IE,sha512:PE});const Jf=0,AE="identity",Qf=Mf;var TE=Object.freeze({__proto__:null,identity:{code:Jf,name:AE,encode:Qf,digest:r=>Ic(Jf,Qf(r))}});new TextEncoder,new TextDecoder;const Xf=ar(ar(ar(ar(ar(ar(ar(ar(ar(ar({},xw),Iw),Cw),Tw),$w),Kw),Gw),Jw),tE),aE);ar(ar({},CE),TE);function Zf(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function RE(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Zf(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function ed(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const td=ed("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Pc=ed("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=RE(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),NE=ar({utf8:td,"utf-8":td,hex:Xf.base16,latin1:Pc,ascii:Pc,binary:Pc},Xf);function $E(r,e="utf8"){const t=NE[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Zf(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}const rd="wc",FE=2,Cc="core",Pn=`${rd}@2:${Cc}:`,LE={name:Cc,logger:"error"},UE={database:":memory:"},jE="crypto",nd="client_ed25519_seed",ME=ye.ONE_DAY,qE="keychain",HE="0.3",BE="messages",zE="0.3",KE=ye.SIX_HOURS,VE="publisher",id="irn",kE="error",sd="wss://relay.walletconnect.com",od="wss://relay.walletconnect.org",GE="relayer",er={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"},WE="_subscription",ln={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},YE=ye.ONE_SECOND,JE="2.10.4",QE=1e4,XE="0.3",ZE="WALLETCONNECT_CLIENT_ID",Kr={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},e3="subscription",t3="0.3",r3=ye.FIVE_SECONDS*1e3,n3="pairing",i3="0.3",gs={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}}},vs={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Zr={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},s3="history",o3="0.3",a3="expirer",Tr={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},c3="0.3",Ac="verify-api",Di="https://verify.walletconnect.com",Tc="https://verify.walletconnect.org",u3=[Di,Tc];class h3{constructor(e,t){this.core=e,this.logger=t,this.keychain=new Map,this.name=qE,this.version=HE,this.initialized=!1,this.storagePrefix=Pn,this.init=async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}},this.has=i=>(this.isInitialized(),this.keychain.has(i)),this.set=async(i,o)=>{this.isInitialized(),this.keychain.set(i,o),await this.persist()},this.get=i=>{this.isInitialized();const o=this.keychain.get(i);if(typeof o>"u"){const{message:a}=he("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(a)}return o},this.del=async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()},this.core=e,this.logger=Je.generateChildLogger(t,this.name)}get context(){return Je.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,$l(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Fl(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=he("NOT_INITIALIZED",this.name);throw new Error(e)}}}class l3{constructor(e,t,i){this.core=e,this.logger=t,this.name=jE,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=o=>(this.isInitialized(),this.keychain.has(o)),this.getClientId=async()=>{this.isInitialized();const o=await this.getClientSeed(),a=wf(o);return mf(a.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const o=l_();return this.setPrivateKey(o.publicKey,o.privateKey)},this.signJWT=async o=>{this.isInitialized();const a=await this.getClientSeed(),u=wf(a),f=Ya();return await mm(f,o,ME,u)},this.generateSharedKey=(o,a,u)=>{this.isInitialized();const f=this.getPrivateKey(o),v=f_(f,a);return this.setSymKey(v,u)},this.setSymKey=async(o,a)=>{this.isInitialized();const u=a||d_(o);return await this.keychain.set(u,o),u},this.deleteKeyPair=async o=>{this.isInitialized(),await this.keychain.del(o)},this.deleteSymKey=async o=>{this.isInitialized(),await this.keychain.del(o)},this.encode=async(o,a,u)=>{this.isInitialized();const f=Cl(u),v=ls(a);if(Al(f)){const S=f.senderPublicKey,C=f.receiverPublicKey;o=await this.generateSharedKey(S,C)}const p=this.getSymKey(o),{type:w,senderPublicKey:I}=f;return g_({type:w,symKey:p,message:v,senderPublicKey:I})},this.decode=async(o,a,u)=>{this.isInitialized();const f=__(a,u);if(Al(f)){const v=f.receiverPublicKey,p=f.senderPublicKey;o=await this.generateSharedKey(v,p)}try{const v=this.getSymKey(o),p=v_({symKey:v,encoded:a});return vc(p)}catch(v){this.logger.error(`Failed to decode message from topic: '${o}', clientId: '${await this.getClientId()}'`),this.logger.error(v)}},this.getPayloadType=o=>{const a=Xs(o);return Ji(a.type)},this.getPayloadSenderPublicKey=o=>{const a=Xs(o);return a.senderPublicKey?nr(a.senderPublicKey,ir):void 0},this.core=e,this.logger=Je.generateChildLogger(t,this.name),this.keychain=i||new h3(this.core,this.logger)}get context(){return Je.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(nd)}catch{e=Ya(),await this.keychain.set(nd,e)}return $E(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=he("NOT_INITIALIZED",this.name);throw new Error(e)}}}class f3 extends Jb{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.name=BE,this.version=zE,this.initialized=!1,this.storagePrefix=Pn,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}},this.set=async(i,o)=>{this.isInitialized();const a=vi(o);let u=this.messages.get(i);return typeof u>"u"&&(u={}),typeof u[a]<"u"||(u[a]=o,this.messages.set(i,u),await this.persist()),a},this.get=i=>{this.isInitialized();let o=this.messages.get(i);return typeof o>"u"&&(o={}),o},this.has=(i,o)=>{this.isInitialized();const a=this.get(i),u=vi(o);return typeof a[u]<"u"},this.del=async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()},this.logger=Je.generateChildLogger(e,this.name),this.core=t}get context(){return Je.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,$l(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Fl(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=he("NOT_INITIALIZED",this.name);throw new Error(e)}}}class d3 extends Qb{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new Yt.exports.EventEmitter,this.name=VE,this.queue=new Map,this.publishTimeout=ye.toMiliseconds(ye.TEN_SECONDS),this.needsTransportRestart=!1,this.publish=async(i,o,a)=>{var u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:o,opts:a}});try{const f=a?.ttl||KE,v=Xa(a),p=a?.prompt||!1,w=a?.tag||0,I=a?.id||Af().toString(),S={topic:i,message:o,opts:{ttl:f,relay:v,prompt:p,tag:w,id:I}},C=setTimeout(()=>this.queue.set(I,S),this.publishTimeout);try{await await es(this.rpcPublish(i,o,f,v,p,w,I),this.publishTimeout,"Failed to publish payload, please try again."),this.removeRequestFromQueue(I),this.relayer.events.emit(er.publish,S)}catch(R){if(this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0,(u=a?.internal)!=null&&u.throwOnFailedPublish)throw this.removeRequestFromQueue(I),R;return}finally{clearTimeout(C)}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:o,opts:a}})}catch(f){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(f),f}},this.on=(i,o)=>{this.events.on(i,o)},this.once=(i,o)=>{this.events.once(i,o)},this.off=(i,o)=>{this.events.off(i,o)},this.removeListener=(i,o)=>{this.events.removeListener(i,o)},this.relayer=e,this.logger=Je.generateChildLogger(t,this.name),this.registerEventListeners()}get context(){return Je.getLoggerContext(this.logger)}rpcPublish(e,t,i,o,a,u,f){var v,p,w,I;const S={method:Zs(o.protocol).publish,params:{topic:e,message:t,ttl:i,prompt:a,tag:u},id:f};return sr((v=S.params)==null?void 0:v.prompt)&&((p=S.params)==null||delete p.prompt),sr((w=S.params)==null?void 0:w.tag)&&((I=S.params)==null||delete I.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:S}),this.relayer.request(S)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:t,message:i,opts:o}=e;await this.publish(t,i,o)})}registerEventListeners(){this.relayer.core.heartbeat.on(wi.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(er.connection_stalled);return}this.checkQueue()}),this.relayer.on(er.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class p3{constructor(){this.map=new Map,this.set=(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,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 i=this.get(e);if(!this.exists(e,t))return;const o=i.filter(a=>a!==t);if(!o.length){this.map.delete(e);return}this.map.set(e,o)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var g3=Object.defineProperty,v3=Object.defineProperties,y3=Object.getOwnPropertyDescriptors,ad=Object.getOwnPropertySymbols,_3=Object.prototype.hasOwnProperty,b3=Object.prototype.propertyIsEnumerable,cd=(r,e,t)=>e in r?g3(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ys=(r,e)=>{for(var t in e||(e={}))_3.call(e,t)&&cd(r,t,e[t]);if(ad)for(var t of ad(e))b3.call(e,t)&&cd(r,t,e[t]);return r},Rc=(r,e)=>v3(r,y3(e));class m3 extends em{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new p3,this.events=new Yt.exports.EventEmitter,this.name=e3,this.version=t3,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=Pn,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(i,o)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:o}});try{const a=Xa(o),u={topic:i,relay:a};this.pending.set(i,u);const f=await this.rpcSubscribe(i,a);return this.onSubscribe(f,u),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:o}}),f}catch(a){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(a),a}},this.unsubscribe=async(i,o)=>{await this.restartToComplete(),this.isInitialized(),typeof o?.id<"u"?await this.unsubscribeById(i,o.id,o):await this.unsubscribeByTopic(i,o)},this.isSubscribed=async i=>this.topics.includes(i)?!0:await new Promise((o,a)=>{const u=new ye.Watch;u.start(this.pendingSubscriptionWatchLabel);const f=setInterval(()=>{!this.pending.has(i)&&this.topics.includes(i)&&(clearInterval(f),u.stop(this.pendingSubscriptionWatchLabel),o(!0)),u.elapsed(this.pendingSubscriptionWatchLabel)>=r3&&(clearInterval(f),u.stop(this.pendingSubscriptionWatchLabel),a(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1),this.on=(i,o)=>{this.events.on(i,o)},this.once=(i,o)=>{this.events.once(i,o)},this.off=(i,o)=>{this.events.off(i,o)},this.removeListener=(i,o)=>{this.events.removeListener(i,o)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=Je.generateChildLogger(t,this.name),this.clientId=""}get context(){return Je.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 i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map(async o=>await this.unsubscribeById(e,o,t)))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const o=Xa(i);await this.rpcUnsubscribe(e,t,o);const a=At("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:i}})}catch(o){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(o),o}}async rpcSubscribe(e,t){const i={method:Zs(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await es(this.relayer.request(i),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(er.connection_stalled)}return vi(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:Zs(t.protocol).batchSubscribe,params:{topics:e.map(o=>o.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{return await await es(this.relayer.request(i),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(er.connection_stalled)}}rpcUnsubscribe(e,t,i){const o={method:Zs(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:o}),this.relayer.request(o)}onSubscribe(e,t){this.setSubscription(e,Rc(ys({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,ys({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),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,ys({},t)),this.topicMap.set(t.topic,e),this.events.emit(Kr.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:i}=he("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(Kr.deleted,Rc(ys({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Kr.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let t=0;t<e;t++){const i=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(Kr.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=he("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);Xr(t)&&this.onBatchSubscribe(t.map((i,o)=>Rc(ys({},e[o]),{id:i})))}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(wi.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(er.connect,async()=>{await this.onConnect()}),this.relayer.on(er.disconnect,()=>{this.onDisconnect()}),this.events.on(Kr.created,async e=>{const t=Kr.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}),this.events.on(Kr.deleted,async e=>{const t=Kr.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}=he("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 w3=Object.defineProperty,ud=Object.getOwnPropertySymbols,E3=Object.prototype.hasOwnProperty,D3=Object.prototype.propertyIsEnumerable,hd=(r,e,t)=>e in r?w3(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,S3=(r,e)=>{for(var t in e||(e={}))E3.call(e,t)&&hd(r,t,e[t]);if(ud)for(var t of ud(e))D3.call(e,t)&&hd(r,t,e[t]);return r};class x3 extends Xb{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new Yt.exports.EventEmitter,this.name=GE,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],this.hasExperiencedNetworkDisruption=!1,this.request=async t=>{this.logger.debug("Publishing Request Payload");try{return await this.toEstablishConnection(),await this.provider.request(t)}catch(i){throw this.logger.debug("Failed to Publish Request"),this.logger.error(i),i}},this.onPayloadHandler=t=>{this.onProviderPayload(t)},this.onConnectHandler=()=>{this.events.emit(er.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=t=>{this.logger.error(t),this.events.emit(er.error,t),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(ln.payload,this.onPayloadHandler),this.provider.on(ln.connect,this.onConnectHandler),this.provider.on(ln.disconnect,this.onDisconnectHandler),this.provider.on(ln.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Je.generateChildLogger(e.logger,this.name):Je.pino(Je.getDefaultLoggerOptions({level:e.logger||kE})),this.messages=new f3(this.logger,e.core),this.subscriber=new m3(this,this.logger),this.publisher=new d3(this,this.logger),this.relayUrl=e?.relayUrl||sd,this.projectId=e.projectId,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 ${od}...`),await this.restartTransport(od)}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)},QE)}get context(){return Je.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now()})}async subscribe(e,t){var i;this.isInitialized();let o=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"";if(o)return o;let a;const u=f=>{f.topic===e&&(this.subscriber.off(Kr.created,u),a())};return await Promise.all([new Promise(f=>{a=f,this.subscriber.on(Kr.created,u)}),new Promise(async f=>{o=await this.subscriber.subscribe(e,t),f()})]),o}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.transportExplicitlyClosed=!0,this.hasExperiencedNetworkDisruption&&this.connected?await es(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(Kr.resubscribed,()=>{t()})}),new Promise(async(t,i)=>{try{await es(this.provider.connect(),1e4,`Socket stalled when trying to connect to ${this.relayUrl}`)}catch(o){i(o);return}t()})])}catch(t){this.logger.error(t);const i=t;if(!this.isConnectionStalled(i.message))throw t;this.provider.events.emit(ln.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 kl())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 hn(new cw(C_({sdkVersion:JE,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:t,message:i}=e;await this.messages.set(t,i)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||i.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.debug(`Ignoring message for non-subscribed topic ${t}`),!0;const o=this.messages.has(t,i);return o&&this.logger.debug(`Ignoring duplicate message: ${i}`),o}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Sc(e)){if(!e.method.endsWith(WE))return;const t=e.params,{topic:i,message:o,publishedAt:a}=t.data,u={topic:i,message:o,publishedAt:a};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(S3({type:"event",event:t.id},u)),this.events.emit(t.id,u),await this.acknowledgePayload(e),await this.onMessageEvent(u)}else ao(e)&&this.events.emit(er.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(er.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=Dc(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(ln.payload,this.onPayloadHandler),this.provider.off(ln.connect,this.onConnectHandler),this.provider.off(ln.disconnect,this.onDisconnectHandler),this.provider.off(ln.error,this.onProviderErrorHandler)}async registerEventListeners(){this.events.on(er.connection_stalled,()=>{this.restartTransport().catch(t=>this.logger.error(t))});let e=await kl();w1(async t=>{this.initialized&&e!==t&&(e=t,t?await this.restartTransport().catch(i=>this.logger.error(i)):(this.hasExperiencedNetworkDisruption=!0,await this.transportClose().catch(i=>this.logger.error(i))))})}onProviderDisconnect(){this.events.emit(er.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(YE)))}isInitialized(){if(!this.initialized){const{message:e}=he("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 O3=Object.defineProperty,ld=Object.getOwnPropertySymbols,I3=Object.prototype.hasOwnProperty,P3=Object.prototype.propertyIsEnumerable,fd=(r,e,t)=>e in r?O3(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,dd=(r,e)=>{for(var t in e||(e={}))I3.call(e,t)&&fd(r,t,e[t]);if(ld)for(var t of ld(e))P3.call(e,t)&&fd(r,t,e[t]);return r};class uo extends Zb{constructor(e,t,i,o=Pn,a=void 0){super(e,t,i,o),this.core=e,this.logger=t,this.name=i,this.map=new Map,this.version=XE,this.cached=[],this.initialized=!1,this.storagePrefix=Pn,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(u=>{this.getKey&&u!==null&&!sr(u)?this.map.set(this.getKey(u),u):X_(u)?this.map.set(u.id,u):Z_(u)&&this.map.set(u.topic,u)}),this.cached=[],this.initialized=!0)},this.set=async(u,f)=>{this.isInitialized(),this.map.has(u)?await this.update(u,f):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:u,value:f}),this.map.set(u,f),await this.persist())},this.get=u=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:u}),this.getData(u)),this.getAll=u=>(this.isInitialized(),u?this.values.filter(f=>Object.keys(u).every(v=>uw(f[v],u[v]))):this.values),this.update=async(u,f)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:u,update:f});const v=dd(dd({},this.getData(u)),f);this.map.set(u,v),await this.persist()},this.delete=async(u,f)=>{this.isInitialized(),this.map.has(u)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:u,reason:f}),this.map.delete(u),await this.persist())},this.logger=Je.generateChildLogger(t,this.name),this.storagePrefix=o,this.getKey=a}get context(){return Je.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:i}=he("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}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}=he("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}=he("NOT_INITIALIZED",this.name);throw new Error(e)}}}class C3{constructor(e,t){this.core=e,this.logger=t,this.name=n3,this.version=i3,this.events=new Yt.exports,this.initialized=!1,this.storagePrefix=Pn,this.ignoredPayloadTypes=[kn],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:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]},this.create=async()=>{this.isInitialized();const i=Ya(),o=await this.core.crypto.setSymKey(i),a=Br(ye.FIVE_MINUTES),u={protocol:id},f={topic:o,expiry:a,relay:u,active:!1},v=B_({protocol:this.core.protocol,version:this.core.version,topic:o,symKey:i,relay:u});return await this.pairings.set(o,f),await this.core.relayer.subscribe(o),this.core.expirer.set(o,a),{topic:o,uri:v}},this.pair=async i=>{this.isInitialized(),this.isValidPair(i);const{topic:o,symKey:a,relay:u}=M_(i.uri);let f;if(this.pairings.keys.includes(o)&&(f=this.pairings.get(o),f.active))throw new Error(`Pairing already exists: ${o}. Please try again with a new connection URI.`);this.core.crypto.keychain.has(o)||(await this.core.crypto.setSymKey(a,o),await this.core.relayer.subscribe(o,{relay:u}));const v=Br(ye.FIVE_MINUTES),p={topic:o,relay:u,expiry:v,active:!1};return await this.pairings.set(o,p),this.core.expirer.set(o,v),i.activatePairing&&await this.activate({topic:o}),this.events.emit(vs.create,p),p},this.activate=async({topic:i})=>{this.isInitialized();const o=Br(ye.THIRTY_DAYS);await this.pairings.update(i,{active:!0,expiry:o}),this.core.expirer.set(i,o)},this.ping=async i=>{this.isInitialized(),await this.isValidPing(i);const{topic:o}=i;if(this.pairings.keys.includes(o)){const a=await this.sendRequest(o,"wc_pairingPing",{}),{done:u,resolve:f,reject:v}=yi();this.events.once(Ft("pairing_ping",a),({error:p})=>{p?v(p):f()}),await u()}},this.updateExpiry=async({topic:i,expiry:o})=>{this.isInitialized(),await this.pairings.update(i,{expiry:o})},this.updateMetadata=async({topic:i,metadata:o})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:o})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:o}=i;this.pairings.keys.includes(o)&&(await this.sendRequest(o,"wc_pairingDelete",At("USER_DISCONNECTED")),await this.deletePairing(o))},this.sendRequest=async(i,o,a)=>{const u=Ei(o,a),f=await this.core.crypto.encode(i,u),v=gs[o].req;return this.core.history.set(i,u),this.core.relayer.publish(i,f,v),u.id},this.sendResult=async(i,o,a)=>{const u=Dc(i,a),f=await this.core.crypto.encode(o,u),v=await this.core.history.get(o,i),p=gs[v.request.method].res;await this.core.relayer.publish(o,f,p),await this.core.history.resolve(u)},this.sendError=async(i,o,a)=>{const u=oo(i,a),f=await this.core.crypto.encode(o,u),v=await this.core.history.get(o,i),p=gs[v.request.method]?gs[v.request.method].res:gs.unregistered_method.res;await this.core.relayer.publish(o,f,p),await this.core.history.resolve(u)},this.deletePairing=async(i,o)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,At("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),o?Promise.resolve():this.core.expirer.del(i)])},this.cleanup=async()=>{const i=this.pairings.getAll().filter(o=>In(o.expiry));await Promise.all(i.map(o=>this.deletePairing(o.topic)))},this.onRelayEventRequest=i=>{const{topic:o,payload:a}=i;switch(a.method){case"wc_pairingPing":return this.onPairingPingRequest(o,a);case"wc_pairingDelete":return this.onPairingDeleteRequest(o,a);default:return this.onUnknownRpcMethodRequest(o,a)}},this.onRelayEventResponse=async i=>{const{topic:o,payload:a}=i,u=(await this.core.history.get(o,a.id)).request.method;switch(u){case"wc_pairingPing":return this.onPairingPingResponse(o,a);default:return this.onUnknownRpcMethodResponse(u)}},this.onPairingPingRequest=async(i,o)=>{const{id:a}=o;try{this.isValidPing({topic:i}),await this.sendResult(a,i,!0),this.events.emit(vs.ping,{id:a,topic:i})}catch(u){await this.sendError(a,i,u),this.logger.error(u)}},this.onPairingPingResponse=(i,o)=>{const{id:a}=o;setTimeout(()=>{un(o)?this.events.emit(Ft("pairing_ping",a),{}):zr(o)&&this.events.emit(Ft("pairing_ping",a),{error:o.error})},500)},this.onPairingDeleteRequest=async(i,o)=>{const{id:a}=o;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(vs.delete,{id:a,topic:i})}catch(u){await this.sendError(a,i,u),this.logger.error(u)}},this.onUnknownRpcMethodRequest=async(i,o)=>{const{id:a,method:u}=o;try{if(this.registeredMethods.includes(u))return;const f=At("WC_METHOD_UNSUPPORTED",u);await this.sendError(a,i,f),this.logger.error(f)}catch(f){await this.sendError(a,i,f),this.logger.error(f)}},this.onUnknownRpcMethodResponse=i=>{this.registeredMethods.includes(i)||this.logger.error(At("WC_METHOD_UNSUPPORTED",i))},this.isValidPair=i=>{if(!gr(i)){const{message:o}=he("MISSING_OR_INVALID",`pair() params: ${i}`);throw new Error(o)}if(!Q_(i.uri)){const{message:o}=he("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw new Error(o)}},this.isValidPing=async i=>{if(!gr(i)){const{message:a}=he("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(a)}const{topic:o}=i;await this.isValidPairingTopic(o)},this.isValidDisconnect=async i=>{if(!gr(i)){const{message:a}=he("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(a)}const{topic:o}=i;await this.isValidPairingTopic(o)},this.isValidPairingTopic=async i=>{if(!kt(i,!1)){const{message:o}=he("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(o)}if(!this.pairings.keys.includes(i)){const{message:o}=he("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(o)}if(In(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:o}=he("EXPIRED",`pairing topic: ${i}`);throw new Error(o)}},this.core=e,this.logger=Je.generateChildLogger(t,this.name),this.pairings=new uo(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Je.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=he("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(er.message,async e=>{const{topic:t,message:i}=e;if(!this.pairings.keys.includes(t)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const o=await this.core.crypto.decode(t,i);try{Sc(o)?(this.core.history.set(t,o),this.onRelayEventRequest({topic:t,payload:o})):ao(o)&&(await this.core.history.resolve(o),await this.onRelayEventResponse({topic:t,payload:o}),this.core.history.delete(t,o.id))}catch(a){this.logger.error(a)}})}registerExpirerEvents(){this.core.expirer.on(Tr.expired,async e=>{const{topic:t}=Ul(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(vs.expire,{topic:t}))})}}class A3 extends Yb{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new Yt.exports.EventEmitter,this.name=s3,this.version=o3,this.cached=[],this.initialized=!1,this.storagePrefix=Pn,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(i,o,a)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:o,chainId:a}),this.records.has(o.id))return;const u={id:o.id,topic:i,request:{method:o.method,params:o.params||null},chainId:a,expiry:Br(ye.THIRTY_DAYS)};this.records.set(u.id,u),this.events.emit(Zr.created,u)},this.resolve=async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const o=await this.getRecord(i.id);typeof o.response>"u"&&(o.response=zr(i)?{error:i.error}:{result:i.result},this.records.set(o.id,o),this.events.emit(Zr.updated,o))},this.get=async(i,o)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:o}),await this.getRecord(o)),this.delete=(i,o)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:o}),this.values.forEach(a=>{if(a.topic===i){if(typeof o<"u"&&a.id!==o)return;this.records.delete(a.id),this.events.emit(Zr.deleted,a)}})},this.exists=async(i,o)=>(this.isInitialized(),this.records.has(o)?(await this.getRecord(o)).topic===i:!1),this.on=(i,o)=>{this.events.on(i,o)},this.once=(i,o)=>{this.events.once(i,o)},this.off=(i,o)=>{this.events.off(i,o)},this.removeListener=(i,o)=>{this.events.removeListener(i,o)},this.logger=Je.generateChildLogger(t,this.name)}get context(){return Je.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 i={topic:t.topic,request:Ei(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)}),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:i}=he("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Zr.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=he("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(Zr.created,e=>{const t=Zr.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()}),this.events.on(Zr.updated,e=>{const t=Zr.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()}),this.events.on(Zr.deleted,e=>{const t=Zr.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()}),this.core.heartbeat.on(wi.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}=he("NOT_INITIALIZED",this.name);throw new Error(e)}}}class T3 extends tm{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new Yt.exports.EventEmitter,this.name=a3,this.version=c3,this.cached=[],this.initialized=!1,this.storagePrefix=Pn,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=i=>{try{const o=this.formatTarget(i);return typeof this.getExpiration(o)<"u"}catch{return!1}},this.set=(i,o)=>{this.isInitialized();const a=this.formatTarget(i),u={target:a,expiry:o};this.expirations.set(a,u),this.checkExpiry(a,u),this.events.emit(Tr.created,{target:a,expiration:u})},this.get=i=>{this.isInitialized();const o=this.formatTarget(i);return this.getExpiration(o)},this.del=i=>{if(this.isInitialized(),this.has(i)){const o=this.formatTarget(i),a=this.getExpiration(o);this.expirations.delete(o),this.events.emit(Tr.deleted,{target:o,expiration:a})}},this.on=(i,o)=>{this.events.on(i,o)},this.once=(i,o)=>{this.events.once(i,o)},this.off=(i,o)=>{this.events.off(i,o)},this.removeListener=(i,o)=>{this.events.removeListener(i,o)},this.logger=Je.generateChildLogger(t,this.name)}get context(){return Je.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 A_(e);if(typeof e=="number")return T_(e);const{message:t}=he("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(Tr.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=he("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:i}=he("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;ye.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Tr.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(wi.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(Tr.created,e=>{const t=Tr.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Tr.expired,e=>{const t=Tr.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Tr.deleted,e=>{const t=Tr.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=he("NOT_INITIALIZED",this.name);throw new Error(e)}}}class R3 extends rm{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.name=Ac,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async i=>{if(this.verifyDisabled||Qi()||!Xi())return;const o=this.getVerifyUrl(i?.verifyUrl);this.verifyUrl!==o&&this.removeIframe(),this.verifyUrl=o;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=Tc;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 i=>{this.initialized?this.sendPost(i.attestationId):(this.addToQueue(i.attestationId),await this.init())},this.resolve=async i=>{if(this.isDevEnv)return"";const o=this.getVerifyUrl(i?.verifyUrl);let a;try{a=await this.fetchAttestation(i.attestationId,o)}catch(u){this.logger.info(`failed to resolve attestation: ${i.attestationId} from url: ${o}`),this.logger.info(u),a=await this.fetchAttestation(i.attestationId,Tc)}return a},this.fetchAttestation=async(i,o)=>{this.logger.info(`resolving attestation: ${i} from url: ${o}`);const a=this.startAbortTimer(ye.ONE_SECOND*2),u=await fetch(`${o}/attestation/${i}`,{signal:this.abortController.signal});return clearTimeout(a),u.status===200?await u.json():void 0},this.addToQueue=i=>{this.queue.push(i)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(i=>this.sendPost(i)),this.queue=[])},this.sendPost=i=>{var o;try{if(!this.iframe)return;(o=this.iframe.contentWindow)==null||o.postMessage(i,"*"),this.logger.info(`postMessage sent: ${i} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let i;const o=a=>{a.data==="verify_ready"&&(this.initialized=!0,this.processQueue(),window.removeEventListener("message",o),i())};await Promise.race([new Promise(a=>{if(document.getElementById(Ac))return a();window.addEventListener("message",o);const u=document.createElement("iframe");u.id=Ac,u.src=`${this.verifyUrl}/${this.projectId}`,u.style.display="none",document.body.append(u),this.iframe=u,i=a}),new Promise((a,u)=>setTimeout(()=>{window.removeEventListener("message",o),u("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=i=>{let o=i||Di;return u3.includes(o)||(this.logger.info(`verify url: ${o}, not included in trusted list, assigning default: ${Di}`),o=Di),o},this.logger=Je.generateChildLogger(t,this.name),this.verifyUrl=Di,this.abortController=new AbortController,this.isDevEnv=Ja()&&process.env.IS_VITEST}get context(){return Je.getLoggerContext(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),ye.toMiliseconds(e))}}var N3=Object.defineProperty,pd=Object.getOwnPropertySymbols,$3=Object.prototype.hasOwnProperty,F3=Object.prototype.propertyIsEnumerable,gd=(r,e,t)=>e in r?N3(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,vd=(r,e)=>{for(var t in e||(e={}))$3.call(e,t)&&gd(r,t,e[t]);if(pd)for(var t of pd(e))F3.call(e,t)&&gd(r,t,e[t]);return r};class Nc extends Wb{constructor(e){super(e),this.protocol=rd,this.version=FE,this.name=Cc,this.events=new Yt.exports.EventEmitter,this.initialized=!1,this.on=(i,o)=>this.events.on(i,o),this.once=(i,o)=>this.events.once(i,o),this.off=(i,o)=>this.events.off(i,o),this.removeListener=(i,o)=>this.events.removeListener(i,o),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||sd,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Je.pino(Je.getDefaultLoggerOptions({level:e?.logger||LE.logger}));this.logger=Je.generateChildLogger(t,this.name),this.heartbeat=new wi.HeartBeat,this.crypto=new l3(this,this.logger,e?.keychain),this.history=new A3(this,this.logger),this.expirer=new T3(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new X1(vd(vd({},UE),e?.storageOptions)),this.relayer=new x3({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new C3(this,this.logger),this.verify=new R3(this.projectId||"",this.logger)}static async init(e){const t=new Nc(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(ZE,i),t}get context(){return Je.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const L3=Nc,yd="wc",_d=2,bd="client",$c=`${yd}@${_d}:${bd}:`,Fc={name:bd,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},md="WALLETCONNECT_DEEPLINK_CHOICE",U3="proposal",wd="Proposal expired",j3="session",ho=ye.SEVEN_DAYS,M3="engine",_s={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}}},Lc={min:ye.FIVE_MINUTES,max:ye.SEVEN_DAYS},fn={idle:"IDLE",active:"ACTIVE"},q3="request",H3=["wc_sessionPropose","wc_sessionRequest","wc_authRequest"];var B3=Object.defineProperty,z3=Object.defineProperties,K3=Object.getOwnPropertyDescriptors,Ed=Object.getOwnPropertySymbols,V3=Object.prototype.hasOwnProperty,k3=Object.prototype.propertyIsEnumerable,Dd=(r,e,t)=>e in r?B3(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,vr=(r,e)=>{for(var t in e||(e={}))V3.call(e,t)&&Dd(r,t,e[t]);if(Ed)for(var t of Ed(e))k3.call(e,t)&&Dd(r,t,e[t]);return r},bs=(r,e)=>z3(r,K3(e));class G3 extends im{constructor(e){super(e),this.name=M3,this.events=new Yt.exports,this.initialized=!1,this.ignoredPayloadTypes=[kn],this.requestQueue={state:fn.idle,queue:[]},this.sessionRequestQueue={state:fn.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(_s)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},ye.toMiliseconds(this.requestQueueDelay)))},this.connect=async t=>{await this.isInitialized();const i=bs(vr({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:o,requiredNamespaces:a,optionalNamespaces:u,sessionProperties:f,relays:v}=i;let p=o,w,I=!1;if(p&&(I=this.client.core.pairing.pairings.get(p).active),!p||!I){const{topic:U,uri:x}=await this.client.core.pairing.create();p=U,w=x}const S=await this.client.core.crypto.generateKeyPair(),C=vr({requiredNamespaces:a,optionalNamespaces:u,relays:v??[{protocol:id}],proposer:{publicKey:S,metadata:this.client.metadata}},f&&{sessionProperties:f}),{reject:R,resolve:B,done:K}=yi(ye.FIVE_MINUTES,wd);if(this.events.once(Ft("session_connect"),async({error:U,session:x})=>{if(U)R(U);else if(x){x.self.publicKey=S;const T=bs(vr({},x),{requiredNamespaces:x.requiredNamespaces,optionalNamespaces:x.optionalNamespaces});await this.client.session.set(x.topic,T),await this.setExpiry(x.topic,x.expiry),p&&await this.client.core.pairing.updateMetadata({topic:p,metadata:x.peer.metadata}),B(T)}}),!p){const{message:U}=he("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(U)}const se=await this.sendRequest({topic:p,method:"wc_sessionPropose",params:C}),$=Br(ye.FIVE_MINUTES);return await this.setProposal(se,vr({id:se,expiry:$},C)),{uri:w,approval:K}},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:i,relayProtocol:o,namespaces:a,sessionProperties:u}=t,f=this.client.proposal.get(i);let{pairingTopic:v,proposer:p,requiredNamespaces:w,optionalNamespaces:I}=f;v=v||"",bi(w)||(w=k_(a,"approve()"));const S=await this.client.core.crypto.generateKeyPair(),C=p.publicKey,R=await this.client.core.crypto.generateSharedKey(S,C);v&&i&&(await this.client.core.pairing.updateMetadata({topic:v,metadata:p.metadata}),await this.sendResult({id:i,topic:v,result:{relay:{protocol:o??"irn"},responderPublicKey:S}}),await this.client.proposal.delete(i,At("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:v}));const B=vr({relay:{protocol:o??"irn"},namespaces:a,requiredNamespaces:w,optionalNamespaces:I,pairingTopic:v,controller:{publicKey:S,metadata:this.client.metadata},expiry:Br(ho)},u&&{sessionProperties:u});await this.client.core.relayer.subscribe(R),await this.sendRequest({topic:R,method:"wc_sessionSettle",params:B,throwOnFailedPublish:!0});const K=bs(vr({},B),{topic:R,pairingTopic:v,acknowledged:!1,self:B.controller,peer:{publicKey:p.publicKey,metadata:p.metadata},controller:S});return await this.client.session.set(R,K),await this.setExpiry(R,Br(ho)),{topic:R,acknowledged:()=>new Promise(se=>setTimeout(()=>se(this.client.session.get(R)),500))}},this.reject=async t=>{await this.isInitialized(),await this.isValidReject(t);const{id:i,reason:o}=t,{pairingTopic:a}=this.client.proposal.get(i);a&&(await this.sendError(i,a,o),await this.client.proposal.delete(i,At("USER_DISCONNECTED")))},this.update=async t=>{await this.isInitialized(),await this.isValidUpdate(t);const{topic:i,namespaces:o}=t,a=await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:o}}),{done:u,resolve:f,reject:v}=yi();return this.events.once(Ft("session_update",a),({error:p})=>{p?v(p):f()}),await this.client.session.update(i,{namespaces:o}),{acknowledged:u}},this.extend=async t=>{await this.isInitialized(),await this.isValidExtend(t);const{topic:i}=t,o=await this.sendRequest({topic:i,method:"wc_sessionExtend",params:{}}),{done:a,resolve:u,reject:f}=yi();return this.events.once(Ft("session_extend",o),({error:v})=>{v?f(v):u()}),await this.setExpiry(i,Br(ho)),{acknowledged:a}},this.request=async t=>{await this.isInitialized(),await this.isValidRequest(t);const{chainId:i,request:o,topic:a,expiry:u}=t,f=Ec(),{done:v,resolve:p,reject:w}=yi(u,"Request expired. Please try again.");return this.events.once(Ft("session_request",f),({error:I,result:S})=>{I?w(I):p(S)}),await Promise.all([new Promise(async I=>{await this.sendRequest({clientRpcId:f,topic:a,method:"wc_sessionRequest",params:{request:o,chainId:i},expiry:u,throwOnFailedPublish:!0}).catch(S=>w(S)),this.client.events.emit("session_request_sent",{topic:a,request:o,chainId:i,id:f}),I()}),new Promise(async I=>{const S=await this.client.core.storage.getItem(md);R_({id:f,topic:a,wcDeepLink:S}),I()}),v()]).then(I=>I[2])},this.respond=async t=>{await this.isInitialized(),await this.isValidRespond(t);const{topic:i,response:o}=t,{id:a}=o;un(o)?await this.sendResult({id:a,topic:i,result:o.result,throwOnFailedPublish:!0}):zr(o)&&await this.sendError(a,i,o.error),this.cleanupAfterResponse(t)},this.ping=async t=>{await this.isInitialized(),await this.isValidPing(t);const{topic:i}=t;if(this.client.session.keys.includes(i)){const o=await this.sendRequest({topic:i,method:"wc_sessionPing",params:{}}),{done:a,resolve:u,reject:f}=yi();this.events.once(Ft("session_ping",o),({error:v})=>{v?f(v):u()}),await a()}else this.client.core.pairing.pairings.keys.includes(i)&&await this.client.core.pairing.ping({topic:i})},this.emit=async t=>{await this.isInitialized(),await this.isValidEmit(t);const{topic:i,event:o,chainId:a}=t;await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:o,chainId:a}})},this.disconnect=async t=>{await this.isInitialized(),await this.isValidDisconnect(t);const{topic:i}=t;this.client.session.keys.includes(i)?(await this.sendRequest({topic:i,method:"wc_sessionDelete",params:At("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession(i)):await this.client.core.pairing.disconnect({topic:i})},this.find=t=>(this.isInitialized(),this.client.session.getAll().filter(i=>Y_(i,t))),this.getPendingSessionRequests=()=>(this.isInitialized(),this.client.pendingRequest.getAll()),this.cleanupDuplicatePairings=async t=>{if(t.pairingTopic)try{const i=this.client.core.pairing.pairings.get(t.pairingTopic),o=this.client.core.pairing.pairings.getAll().filter(a=>{var u,f;return((u=a.peerMetadata)==null?void 0:u.url)&&((f=a.peerMetadata)==null?void 0:f.url)===t.peer.metadata.url&&a.topic&&a.topic!==i.topic});if(o.length===0)return;this.client.logger.info(`Cleaning up ${o.length} duplicate pairing(s)`),await Promise.all(o.map(a=>this.client.core.pairing.disconnect({topic:a.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}},this.deleteSession=async(t,i)=>{const{self:o}=this.client.session.get(t);await this.client.core.relayer.unsubscribe(t),this.client.session.delete(t,At("USER_DISCONNECTED")),this.client.core.crypto.keychain.has(o.publicKey)&&await this.client.core.crypto.deleteKeyPair(o.publicKey),this.client.core.crypto.keychain.has(t)&&await this.client.core.crypto.deleteSymKey(t),i||this.client.core.expirer.del(t),this.client.core.storage.removeItem(md).catch(a=>this.client.logger.warn(a))},this.deleteProposal=async(t,i)=>{await Promise.all([this.client.proposal.delete(t,At("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(t)])},this.deletePendingSessionRequest=async(t,i,o=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,i),o?Promise.resolve():this.client.core.expirer.del(t)]),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(a=>a.id!==t),o&&(this.sessionRequestQueue.state=fn.idle)},this.setExpiry=async(t,i)=>{this.client.session.keys.includes(t)&&await this.client.session.update(t,{expiry:i}),this.client.core.expirer.set(t,i)},this.setProposal=async(t,i)=>{await this.client.proposal.set(t,i),this.client.core.expirer.set(t,i.expiry)},this.setPendingSessionRequest=async t=>{const i=_s.wc_sessionRequest.req.ttl,{id:o,topic:a,params:u,verifyContext:f}=t;await this.client.pendingRequest.set(o,{id:o,topic:a,params:u,verifyContext:f}),i&&this.client.core.expirer.set(o,Br(i))},this.sendRequest=async t=>{const{topic:i,method:o,params:a,expiry:u,relayRpcId:f,clientRpcId:v,throwOnFailedPublish:p}=t,w=Ei(o,a,v);if(Xi()&&H3.includes(o)){const C=vi(JSON.stringify(w));this.client.core.verify.register({attestationId:C})}const I=await this.client.core.crypto.encode(i,w),S=_s[o].req;return u&&(S.ttl=u),f&&(S.id=f),this.client.core.history.set(i,w),p?(S.internal=bs(vr({},S.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,I,S)):this.client.core.relayer.publish(i,I,S).catch(C=>this.client.logger.error(C)),w.id},this.sendResult=async t=>{const{id:i,topic:o,result:a,throwOnFailedPublish:u}=t,f=Dc(i,a),v=await this.client.core.crypto.encode(o,f),p=await this.client.core.history.get(o,i),w=_s[p.request.method].res;u?(w.internal=bs(vr({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(o,v,w)):this.client.core.relayer.publish(o,v,w).catch(I=>this.client.logger.error(I)),await this.client.core.history.resolve(f)},this.sendError=async(t,i,o)=>{const a=oo(t,o),u=await this.client.core.crypto.encode(i,a),f=await this.client.core.history.get(i,t),v=_s[f.request.method].res;this.client.core.relayer.publish(i,u,v),await this.client.core.history.resolve(a)},this.cleanup=async()=>{const t=[],i=[];this.client.session.getAll().forEach(o=>{In(o.expiry)&&t.push(o.topic)}),this.client.proposal.getAll().forEach(o=>{In(o.expiry)&&i.push(o.id)}),await Promise.all([...t.map(o=>this.deleteSession(o)),...i.map(o=>this.deleteProposal(o))])},this.onRelayEventRequest=async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===fn.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=fn.active;const t=this.requestQueue.queue.shift();if(t)try{this.processRequest(t),await new Promise(i=>setTimeout(i,300))}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=fn.idle},this.processRequest=t=>{const{topic:i,payload:o}=t,a=o.method;switch(a){case"wc_sessionPropose":return this.onSessionProposeRequest(i,o);case"wc_sessionSettle":return this.onSessionSettleRequest(i,o);case"wc_sessionUpdate":return this.onSessionUpdateRequest(i,o);case"wc_sessionExtend":return this.onSessionExtendRequest(i,o);case"wc_sessionPing":return this.onSessionPingRequest(i,o);case"wc_sessionDelete":return this.onSessionDeleteRequest(i,o);case"wc_sessionRequest":return this.onSessionRequest(i,o);case"wc_sessionEvent":return this.onSessionEventRequest(i,o);default:return this.client.logger.info(`Unsupported request method ${a}`)}},this.onRelayEventResponse=async t=>{const{topic:i,payload:o}=t,a=(await this.client.core.history.get(i,o.id)).request.method;switch(a){case"wc_sessionPropose":return this.onSessionProposeResponse(i,o);case"wc_sessionSettle":return this.onSessionSettleResponse(i,o);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,o);case"wc_sessionExtend":return this.onSessionExtendResponse(i,o);case"wc_sessionPing":return this.onSessionPingResponse(i,o);case"wc_sessionRequest":return this.onSessionRequestResponse(i,o);default:return this.client.logger.info(`Unsupported response method ${a}`)}},this.onRelayEventUnknownPayload=t=>{const{topic:i}=t,{message:o}=he("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(o)},this.onSessionProposeRequest=async(t,i)=>{const{params:o,id:a}=i;try{this.isValidConnect(vr({},i.params));const u=Br(ye.FIVE_MINUTES),f=vr({id:a,pairingTopic:t,expiry:u},o);await this.setProposal(a,f);const v=vi(JSON.stringify(i)),p=await this.getVerifyContext(v,f.proposer.metadata);this.client.events.emit("session_proposal",{id:a,params:f,verifyContext:p})}catch(u){await this.sendError(a,t,u),this.client.logger.error(u)}},this.onSessionProposeResponse=async(t,i)=>{const{id:o}=i;if(un(i)){const{result:a}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:a});const u=this.client.proposal.get(o);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:u});const f=u.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:f});const v=a.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:v});const p=await this.client.core.crypto.generateSharedKey(f,v);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:p});const w=await this.client.core.relayer.subscribe(p);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:w}),await this.client.core.pairing.activate({topic:t})}else zr(i)&&(await this.client.proposal.delete(o,At("USER_DISCONNECTED")),this.events.emit(Ft("session_connect"),{error:i.error}))},this.onSessionSettleRequest=async(t,i)=>{const{id:o,params:a}=i;try{this.isValidSessionSettleRequest(a);const{relay:u,controller:f,expiry:v,namespaces:p,requiredNamespaces:w,optionalNamespaces:I,sessionProperties:S,pairingTopic:C}=i.params,R=vr({topic:t,relay:u,expiry:v,namespaces:p,acknowledged:!0,pairingTopic:C,requiredNamespaces:w,optionalNamespaces:I,controller:f.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:f.publicKey,metadata:f.metadata}},S&&{sessionProperties:S});await this.sendResult({id:i.id,topic:t,result:!0}),this.events.emit(Ft("session_connect"),{session:R}),this.cleanupDuplicatePairings(R)}catch(u){await this.sendError(o,t,u),this.client.logger.error(u)}},this.onSessionSettleResponse=async(t,i)=>{const{id:o}=i;un(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(Ft("session_approve",o),{})):zr(i)&&(await this.client.session.delete(t,At("USER_DISCONNECTED")),this.events.emit(Ft("session_approve",o),{error:i.error}))},this.onSessionUpdateRequest=async(t,i)=>{const{params:o,id:a}=i;try{const u=`${t}_session_update`,f=ro.get(u);if(f&&this.isRequestOutOfSync(f,a)){this.client.logger.info(`Discarding out of sync request - ${a}`);return}this.isValidUpdate(vr({topic:t},o)),await this.client.session.update(t,{namespaces:o.namespaces}),await this.sendResult({id:a,topic:t,result:!0}),this.client.events.emit("session_update",{id:a,topic:t,params:o}),ro.set(u,a)}catch(u){await this.sendError(a,t,u),this.client.logger.error(u)}},this.isRequestOutOfSync=(t,i)=>parseInt(i.toString().slice(0,-3))<=parseInt(t.toString().slice(0,-3)),this.onSessionUpdateResponse=(t,i)=>{const{id:o}=i;un(i)?this.events.emit(Ft("session_update",o),{}):zr(i)&&this.events.emit(Ft("session_update",o),{error:i.error})},this.onSessionExtendRequest=async(t,i)=>{const{id:o}=i;try{this.isValidExtend({topic:t}),await this.setExpiry(t,Br(ho)),await this.sendResult({id:o,topic:t,result:!0}),this.client.events.emit("session_extend",{id:o,topic:t})}catch(a){await this.sendError(o,t,a),this.client.logger.error(a)}},this.onSessionExtendResponse=(t,i)=>{const{id:o}=i;un(i)?this.events.emit(Ft("session_extend",o),{}):zr(i)&&this.events.emit(Ft("session_extend",o),{error:i.error})},this.onSessionPingRequest=async(t,i)=>{const{id:o}=i;try{this.isValidPing({topic:t}),await this.sendResult({id:o,topic:t,result:!0}),this.client.events.emit("session_ping",{id:o,topic:t})}catch(a){await this.sendError(o,t,a),this.client.logger.error(a)}},this.onSessionPingResponse=(t,i)=>{const{id:o}=i;setTimeout(()=>{un(i)?this.events.emit(Ft("session_ping",o),{}):zr(i)&&this.events.emit(Ft("session_ping",o),{error:i.error})},500)},this.onSessionDeleteRequest=async(t,i)=>{const{id:o}=i;try{this.isValidDisconnect({topic:t,reason:i.params}),await Promise.all([new Promise(a=>{this.client.core.relayer.once(er.publish,async()=>{a(await this.deleteSession(t))})}),this.sendResult({id:o,topic:t,result:!0})]),this.client.events.emit("session_delete",{id:o,topic:t})}catch(a){this.client.logger.error(a)}},this.onSessionRequest=async(t,i)=>{const{id:o,params:a}=i;try{this.isValidRequest(vr({topic:t},a));const u=vi(JSON.stringify(Ei("wc_sessionRequest",a,o))),f=this.client.session.get(t),v=await this.getVerifyContext(u,f.peer.metadata),p={id:o,topic:t,params:a,verifyContext:v};await this.setPendingSessionRequest(p),this.addSessionRequestToSessionRequestQueue(p),this.processSessionRequestQueue()}catch(u){await this.sendError(o,t,u),this.client.logger.error(u)}},this.onSessionRequestResponse=(t,i)=>{const{id:o}=i;un(i)?this.events.emit(Ft("session_request",o),{result:i.result}):zr(i)&&this.events.emit(Ft("session_request",o),{error:i.error})},this.onSessionEventRequest=async(t,i)=>{const{id:o,params:a}=i;try{const u=`${t}_session_event_${a.event.name}`,f=ro.get(u);if(f&&this.isRequestOutOfSync(f,o)){this.client.logger.info(`Discarding out of sync request - ${o}`);return}this.isValidEmit(vr({topic:t},a)),this.client.events.emit("session_event",{id:o,topic:t,params:a}),ro.set(u,o)}catch(u){await this.sendError(o,t,u),this.client.logger.error(u)}},this.addSessionRequestToSessionRequestQueue=t=>{this.sessionRequestQueue.queue.push(t)},this.cleanupAfterResponse=t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=fn.idle,this.processSessionRequestQueue()},ye.toMiliseconds(this.requestQueueDelay))},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===fn.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=fn.active,this.client.events.emit("session_request",t)}catch(i){this.client.logger.error(i)}},this.onPairingCreated=t=>{if(t.active)return;const i=this.client.proposal.getAll().find(o=>o.pairingTopic===t.topic);i&&this.onSessionProposeRequest(t.topic,Ei("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer},i.id))},this.isValidConnect=async t=>{if(!gr(t)){const{message:v}=he("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(v)}const{pairingTopic:i,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:u,relays:f}=t;if(sr(i)||await this.isValidPairingTopic(i),!a1(f,!0)){const{message:v}=he("MISSING_OR_INVALID",`connect() relays: ${f}`);throw new Error(v)}!sr(o)&&bi(o)!==0&&this.validateNamespaces(o,"requiredNamespaces"),!sr(a)&&bi(a)!==0&&this.validateNamespaces(a,"optionalNamespaces"),sr(u)||this.validateSessionProps(u,"sessionProperties")},this.validateNamespaces=(t,i)=>{const o=o1(t,"connect()",i);if(o)throw new Error(o.message)},this.isValidApprove=async t=>{if(!gr(t))throw new Error(he("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:i,namespaces:o,relayProtocol:a,sessionProperties:u}=t;await this.isValidProposalId(i);const f=this.client.proposal.get(i),v=to(o,"approve()");if(v)throw new Error(v.message);const p=Kl(f.requiredNamespaces,o,"approve()");if(p)throw new Error(p.message);if(!kt(a,!0)){const{message:w}=he("MISSING_OR_INVALID",`approve() relayProtocol: ${a}`);throw new Error(w)}sr(u)||this.validateSessionProps(u,"sessionProperties")},this.isValidReject=async t=>{if(!gr(t)){const{message:a}=he("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(a)}const{id:i,reason:o}=t;if(await this.isValidProposalId(i),!u1(o)){const{message:a}=he("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(o)}`);throw new Error(a)}},this.isValidSessionSettleRequest=t=>{if(!gr(t)){const{message:p}=he("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(p)}const{relay:i,controller:o,namespaces:a,expiry:u}=t;if(!Bl(i)){const{message:p}=he("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(p)}const f=e1(o,"onSessionSettleRequest()");if(f)throw new Error(f.message);const v=to(a,"onSessionSettleRequest()");if(v)throw new Error(v.message);if(In(u)){const{message:p}=he("EXPIRED","onSessionSettleRequest()");throw new Error(p)}},this.isValidUpdate=async t=>{if(!gr(t)){const{message:v}=he("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(v)}const{topic:i,namespaces:o}=t;await this.isValidSessionTopic(i);const a=this.client.session.get(i),u=to(o,"update()");if(u)throw new Error(u.message);const f=Kl(a.requiredNamespaces,o,"update()");if(f)throw new Error(f.message)},this.isValidExtend=async t=>{if(!gr(t)){const{message:o}=he("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(o)}const{topic:i}=t;await this.isValidSessionTopic(i)},this.isValidRequest=async t=>{if(!gr(t)){const{message:v}=he("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(v)}const{topic:i,request:o,chainId:a,expiry:u}=t;await this.isValidSessionTopic(i);const{namespaces:f}=this.client.session.get(i);if(!zl(f,a)){const{message:v}=he("MISSING_OR_INVALID",`request() chainId: ${a}`);throw new Error(v)}if(!h1(o)){const{message:v}=he("MISSING_OR_INVALID",`request() ${JSON.stringify(o)}`);throw new Error(v)}if(!d1(f,a,o.method)){const{message:v}=he("MISSING_OR_INVALID",`request() method: ${o.method}`);throw new Error(v)}if(u&&!y1(u,Lc)){const{message:v}=he("MISSING_OR_INVALID",`request() expiry: ${u}. Expiry must be a number (in seconds) between ${Lc.min} and ${Lc.max}`);throw new Error(v)}},this.isValidRespond=async t=>{if(!gr(t)){const{message:a}=he("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(a)}const{topic:i,response:o}=t;if(await this.isValidSessionTopic(i),!l1(o)){const{message:a}=he("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(o)}`);throw new Error(a)}},this.isValidPing=async t=>{if(!gr(t)){const{message:o}=he("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(o)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)},this.isValidEmit=async t=>{if(!gr(t)){const{message:f}=he("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(f)}const{topic:i,event:o,chainId:a}=t;await this.isValidSessionTopic(i);const{namespaces:u}=this.client.session.get(i);if(!zl(u,a)){const{message:f}=he("MISSING_OR_INVALID",`emit() chainId: ${a}`);throw new Error(f)}if(!f1(o)){const{message:f}=he("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(f)}if(!p1(u,a,o.name)){const{message:f}=he("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(f)}},this.isValidDisconnect=async t=>{if(!gr(t)){const{message:o}=he("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(o)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)},this.getVerifyContext=async(t,i)=>{const o={verified:{verifyUrl:i.verifyUrl||Di,validation:"UNKNOWN",origin:i.url||""}};try{const a=await this.client.core.verify.resolve({attestationId:t,verifyUrl:i.verifyUrl});a&&(o.verified.origin=a.origin,o.verified.isScam=a.isScam,o.verified.validation=a.origin===new URL(i.url).origin?"VALID":"INVALID")}catch(a){this.client.logger.info(a)}return this.client.logger.info(`Verify context: ${JSON.stringify(o)}`),o},this.validateSessionProps=(t,i)=>{Object.values(t).forEach(o=>{if(!kt(o,!1)){const{message:a}=he("MISSING_OR_INVALID",`${i} must be in Record<string, string> format. Received: ${JSON.stringify(o)}`);throw new Error(a)}})}}async isInitialized(){if(!this.initialized){const{message:e}=he("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(er.message,async e=>{const{topic:t,message:i}=e;if(this.ignoredPayloadTypes.includes(this.client.core.crypto.getPayloadType(i)))return;const o=await this.client.core.crypto.decode(t,i);try{Sc(o)?(this.client.core.history.set(t,o),this.onRelayEventRequest({topic:t,payload:o})):ao(o)?(await this.client.core.history.resolve(o),await this.onRelayEventResponse({topic:t,payload:o}),this.client.core.history.delete(t,o.id)):this.onRelayEventUnknownPayload({topic:t,payload:o})}catch(a){this.client.logger.error(a)}})}registerExpirerEvents(){this.client.core.expirer.on(Tr.expired,async e=>{const{topic:t,id:i}=Ul(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,he("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession(t,!0),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(vs.create,e=>this.onPairingCreated(e))}isValidPairingTopic(e){if(!kt(e,!1)){const{message:t}=he("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}=he("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(In(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=he("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!kt(e,!1)){const{message:t}=he("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(!this.client.session.keys.includes(e)){const{message:t}=he("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(In(this.client.session.get(e).expiry)){await this.deleteSession(e);const{message:t}=he("EXPIRED",`session topic: ${e}`);throw 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(kt(e,!1)){const{message:t}=he("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=he("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!c1(e)){const{message:t}=he("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=he("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(In(this.client.proposal.get(e).expiry)){await this.deleteProposal(e);const{message:t}=he("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class W3 extends uo{constructor(e,t){super(e,t,U3,$c),this.core=e,this.logger=t}}class Y3 extends uo{constructor(e,t){super(e,t,j3,$c),this.core=e,this.logger=t}}class J3 extends uo{constructor(e,t){super(e,t,q3,$c,i=>i.id),this.core=e,this.logger=t}}class Uc extends nm{constructor(e){super(e),this.protocol=yd,this.version=_d,this.name=Fc.name,this.events=new Yt.exports.EventEmitter,this.on=(i,o)=>this.events.on(i,o),this.once=(i,o)=>this.events.once(i,o),this.off=(i,o)=>this.events.off(i,o),this.removeListener=(i,o)=>this.events.removeListener(i,o),this.removeAllListeners=i=>this.events.removeAllListeners(i),this.connect=async i=>{try{return await this.engine.connect(i)}catch(o){throw this.logger.error(o.message),o}},this.pair=async i=>{try{return await this.engine.pair(i)}catch(o){throw this.logger.error(o.message),o}},this.approve=async i=>{try{return await this.engine.approve(i)}catch(o){throw this.logger.error(o.message),o}},this.reject=async i=>{try{return await this.engine.reject(i)}catch(o){throw this.logger.error(o.message),o}},this.update=async i=>{try{return await this.engine.update(i)}catch(o){throw this.logger.error(o.message),o}},this.extend=async i=>{try{return await this.engine.extend(i)}catch(o){throw this.logger.error(o.message),o}},this.request=async i=>{try{return await this.engine.request(i)}catch(o){throw this.logger.error(o.message),o}},this.respond=async i=>{try{return await this.engine.respond(i)}catch(o){throw this.logger.error(o.message),o}},this.ping=async i=>{try{return await this.engine.ping(i)}catch(o){throw this.logger.error(o.message),o}},this.emit=async i=>{try{return await this.engine.emit(i)}catch(o){throw this.logger.error(o.message),o}},this.disconnect=async i=>{try{return await this.engine.disconnect(i)}catch(o){throw this.logger.error(o.message),o}},this.find=i=>{try{return this.engine.find(i)}catch(o){throw this.logger.error(o.message),o}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}},this.name=e?.name||Fc.name,this.metadata=e?.metadata||x_();const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Je.pino(Je.getDefaultLoggerOptions({level:e?.logger||Fc.logger}));this.core=e?.core||new L3(e),this.logger=Je.generateChildLogger(t,this.name),this.session=new Y3(this.core,this.logger),this.proposal=new W3(this.core,this.logger),this.pendingRequest=new J3(this.core,this.logger),this.engine=new G3(this)}static async init(e){const t=new Uc(e);return await t.initialize(),t}get context(){return Je.getLoggerContext(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),this.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 jc={exports:{}};(function(r,e){var t=typeof self<"u"?self:Vt,i=function(){function a(){this.fetch=!1,this.DOMException=t.DOMException}return a.prototype=t,new a}();(function(a){(function(u){var f={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 v(m){return m&&DataView.prototype.isPrototypeOf(m)}if(f.arrayBuffer)var p=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],w=ArrayBuffer.isView||function(m){return m&&p.indexOf(Object.prototype.toString.call(m))>-1};function I(m){if(typeof m!="string"&&(m=String(m)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(m))throw new TypeError("Invalid character in header field name");return m.toLowerCase()}function S(m){return typeof m!="string"&&(m=String(m)),m}function C(m){var P={next:function(){var ee=m.shift();return{done:ee===void 0,value:ee}}};return f.iterable&&(P[Symbol.iterator]=function(){return P}),P}function R(m){this.map={},m instanceof R?m.forEach(function(P,ee){this.append(ee,P)},this):Array.isArray(m)?m.forEach(function(P){this.append(P[0],P[1])},this):m&&Object.getOwnPropertyNames(m).forEach(function(P){this.append(P,m[P])},this)}R.prototype.append=function(m,P){m=I(m),P=S(P);var ee=this.map[m];this.map[m]=ee?ee+", "+P:P},R.prototype.delete=function(m){delete this.map[I(m)]},R.prototype.get=function(m){return m=I(m),this.has(m)?this.map[m]:null},R.prototype.has=function(m){return this.map.hasOwnProperty(I(m))},R.prototype.set=function(m,P){this.map[I(m)]=S(P)},R.prototype.forEach=function(m,P){for(var ee in this.map)this.map.hasOwnProperty(ee)&&m.call(P,this.map[ee],ee,this)},R.prototype.keys=function(){var m=[];return this.forEach(function(P,ee){m.push(ee)}),C(m)},R.prototype.values=function(){var m=[];return this.forEach(function(P){m.push(P)}),C(m)},R.prototype.entries=function(){var m=[];return this.forEach(function(P,ee){m.push([ee,P])}),C(m)},f.iterable&&(R.prototype[Symbol.iterator]=R.prototype.entries);function B(m){if(m.bodyUsed)return Promise.reject(new TypeError("Already read"));m.bodyUsed=!0}function K(m){return new Promise(function(P,ee){m.onload=function(){P(m.result)},m.onerror=function(){ee(m.error)}})}function se(m){var P=new FileReader,ee=K(P);return P.readAsArrayBuffer(m),ee}function $(m){var P=new FileReader,ee=K(P);return P.readAsText(m),ee}function U(m){for(var P=new Uint8Array(m),ee=new Array(P.length),Q=0;Q<P.length;Q++)ee[Q]=String.fromCharCode(P[Q]);return ee.join("")}function x(m){if(m.slice)return m.slice(0);var P=new Uint8Array(m.byteLength);return P.set(new Uint8Array(m)),P.buffer}function T(){return this.bodyUsed=!1,this._initBody=function(m){this._bodyInit=m,m?typeof m=="string"?this._bodyText=m:f.blob&&Blob.prototype.isPrototypeOf(m)?this._bodyBlob=m:f.formData&&FormData.prototype.isPrototypeOf(m)?this._bodyFormData=m:f.searchParams&&URLSearchParams.prototype.isPrototypeOf(m)?this._bodyText=m.toString():f.arrayBuffer&&f.blob&&v(m)?(this._bodyArrayBuffer=x(m.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):f.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(m)||w(m))?this._bodyArrayBuffer=x(m):this._bodyText=m=Object.prototype.toString.call(m):this._bodyText="",this.headers.get("content-type")||(typeof m=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):f.searchParams&&URLSearchParams.prototype.isPrototypeOf(m)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},f.blob&&(this.blob=function(){var m=B(this);if(m)return m;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?B(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(se)}),this.text=function(){var m=B(this);if(m)return m;if(this._bodyBlob)return $(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(U(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},f.formData&&(this.formData=function(){return this.text().then(G)}),this.json=function(){return this.text().then(JSON.parse)},this}var E=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function h(m){var P=m.toUpperCase();return E.indexOf(P)>-1?P:m}function b(m,P){P=P||{};var ee=P.body;if(m instanceof b){if(m.bodyUsed)throw new TypeError("Already read");this.url=m.url,this.credentials=m.credentials,P.headers||(this.headers=new R(m.headers)),this.method=m.method,this.mode=m.mode,this.signal=m.signal,!ee&&m._bodyInit!=null&&(ee=m._bodyInit,m.bodyUsed=!0)}else this.url=String(m);if(this.credentials=P.credentials||this.credentials||"same-origin",(P.headers||!this.headers)&&(this.headers=new R(P.headers)),this.method=h(P.method||this.method||"GET"),this.mode=P.mode||this.mode||null,this.signal=P.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&ee)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(ee)}b.prototype.clone=function(){return new b(this,{body:this._bodyInit})};function G(m){var P=new FormData;return m.trim().split("&").forEach(function(ee){if(ee){var Q=ee.split("="),V=Q.shift().replace(/\+/g," "),k=Q.join("=").replace(/\+/g," ");P.append(decodeURIComponent(V),decodeURIComponent(k))}}),P}function Y(m){var P=new R,ee=m.replace(/\r?\n[\t ]+/g," ");return ee.split(/\r?\n/).forEach(function(Q){var V=Q.split(":"),k=V.shift().trim();if(k){var J=V.join(":").trim();P.append(k,J)}}),P}T.call(b.prototype);function ie(m,P){P||(P={}),this.type="default",this.status=P.status===void 0?200:P.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in P?P.statusText:"OK",this.headers=new R(P.headers),this.url=P.url||"",this._initBody(m)}T.call(ie.prototype),ie.prototype.clone=function(){return new ie(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new R(this.headers),url:this.url})},ie.error=function(){var m=new ie(null,{status:0,statusText:""});return m.type="error",m};var ce=[301,302,303,307,308];ie.redirect=function(m,P){if(ce.indexOf(P)===-1)throw new RangeError("Invalid status code");return new ie(null,{status:P,headers:{location:m}})},u.DOMException=a.DOMException;try{new u.DOMException}catch{u.DOMException=function(P,ee){this.message=P,this.name=ee;var Q=Error(P);this.stack=Q.stack},u.DOMException.prototype=Object.create(Error.prototype),u.DOMException.prototype.constructor=u.DOMException}function de(m,P){return new Promise(function(ee,Q){var V=new b(m,P);if(V.signal&&V.signal.aborted)return Q(new u.DOMException("Aborted","AbortError"));var k=new XMLHttpRequest;function J(){k.abort()}k.onload=function(){var re={status:k.status,statusText:k.statusText,headers:Y(k.getAllResponseHeaders()||"")};re.url="responseURL"in k?k.responseURL:re.headers.get("X-Request-URL");var me="response"in k?k.response:k.responseText;ee(new ie(me,re))},k.onerror=function(){Q(new TypeError("Network request failed"))},k.ontimeout=function(){Q(new TypeError("Network request failed"))},k.onabort=function(){Q(new u.DOMException("Aborted","AbortError"))},k.open(V.method,V.url,!0),V.credentials==="include"?k.withCredentials=!0:V.credentials==="omit"&&(k.withCredentials=!1),"responseType"in k&&f.blob&&(k.responseType="blob"),V.headers.forEach(function(re,me){k.setRequestHeader(me,re)}),V.signal&&(V.signal.addEventListener("abort",J),k.onreadystatechange=function(){k.readyState===4&&V.signal.removeEventListener("abort",J)}),k.send(typeof V._bodyInit>"u"?null:V._bodyInit)})}return de.polyfill=!0,a.fetch||(a.fetch=de,a.Headers=R,a.Request=b,a.Response=ie),u.Headers=R,u.Request=b,u.Response=ie,u.fetch=de,Object.defineProperty(u,"__esModule",{value:!0}),u})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var o=i;e=o.fetch,e.default=o.fetch,e.fetch=o.fetch,e.Headers=o.Headers,e.Request=o.Request,e.Response=o.Response,r.exports=e})(jc,jc.exports);var Sd=qg(jc.exports);const xd={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"},Od=10;class Cn{constructor(e,t=!1){if(this.url=e,this.disableProviderPing=t,this.events=new Yt.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!Rf(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 i=ls(e),a=await(await Sd(this.url,Object.assign(Object.assign({},xd),{body:i}))).json();this.onPayload({data:a})}catch(i){this.onError(e.id,i)}}async register(e=this.url){if(!Rf(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((i,o)=>{this.events.once("register_error",a=>{this.resetMaxListeners(),o(a)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return o(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const t=ls({id:1,jsonrpc:"2.0",method:"test",params:[]});await Sd(e,Object.assign(Object.assign({},xd),{body:t}))}this.onOpen()}catch(t){const i=this.parseError(t);throw this.events.emit("register_error",i),this.onClose(),i}}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"?vc(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),o=i.message||i.toString(),a=oo(e,o);this.events.emit("payload",a)}parseError(e,t=this.url){return xf(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Od&&this.events.setMaxListeners(Od)}}const Id="error",Q3="wss://relay.walletconnect.com",X3="wc",Z3="universal_provider",Pd=`${X3}@2:${Z3}:`,e2="https://rpc.walletconnect.com/v1/",dn={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var ms=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Mc={exports:{}};/**
|
|
73
73
|
* @license
|
|
74
74
|
* Lodash <https://lodash.com/>
|
|
75
75
|
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
|