@walletconnect/ethereum-provider 2.18.1-rc-1 → 2.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -40,7 +40,7 @@ ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(B_(r)).toStr
40
40
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
41
41
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
42
42
  PERFORMANCE OF THIS SOFTWARE.
43
- ***************************************************************************** */var Eu=function(t,e){return Eu=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var n in i)i.hasOwnProperty(n)&&(r[n]=i[n])},Eu(t,e)};function DS(t,e){Eu(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var $u=function(){return $u=Object.assign||function(e){for(var r,i=1,n=arguments.length;i<n;i++){r=arguments[i];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},$u.apply(this,arguments)};function RS(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(t);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(r[i[n]]=t[i[n]]);return r}function NS(t,e,r,i){var n=arguments.length,s=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(n<3?o(s):n>3?o(e,r,s):o(e,r))||s);return n>3&&s&&Object.defineProperty(e,r,s),s}function TS(t,e){return function(r,i){e(r,i,t)}}function FS(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function LS(t,e,r,i){function n(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(u){try{l(i.next(u))}catch(m){o(m)}}function c(u){try{l(i.throw(u))}catch(m){o(m)}}function l(u){u.done?s(u.value):n(u.value).then(a,c)}l((i=i.apply(t,e||[])).next())})}function BS(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,n&&(s=l[0]&2?n.return:l[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,l[1])).done)return s;switch(n=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,n=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],n=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function US(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function qS(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Su(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Qv(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function jS(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Qv(arguments[e]));return t}function kS(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),n=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,n++)i[n]=s[o];return i}function Za(t){return this instanceof Za?(this.v=t,this):new Za(t)}function zS(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),n,s=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(x){i[x]&&(n[x]=function(S){return new Promise(function(E,A){s.push([x,S,E,A])>1||a(x,S)})})}function a(x,S){try{c(i[x](S))}catch(E){m(s[0][3],E)}}function c(x){x.value instanceof Za?Promise.resolve(x.value.v).then(l,u):m(s[0][2],x)}function l(x){a("next",x)}function u(x){a("throw",x)}function m(x,S){x(S),s.shift(),s.length&&a(s[0][0],s[0][1])}}function HS(t){var e,r;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,s){e[n]=t[n]?function(o){return(r=!r)?{value:Za(t[n](o)),done:n==="return"}:s?s(o):o}:s}}function WS(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Su=="function"?Su(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),n(a,c,o.done,o.value)})}}function n(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function VS(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function KS(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function GS(t){return t&&t.__esModule?t:{default:t}}function JS(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function ZS(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var YS=Object.freeze({__proto__:null,__extends:DS,get __assign(){return $u},__rest:RS,__decorate:NS,__param:TS,__metadata:FS,__awaiter:LS,__generator:BS,__createBinding:US,__exportStar:qS,__values:Su,__read:Qv,__spread:jS,__spreadArrays:kS,__await:Za,__asyncGenerator:zS,__asyncDelegator:HS,__asyncValues:WS,__makeTemplateObject:VS,__importStar:KS,__importDefault:GS,__classPrivateFieldGet:JS,__classPrivateFieldSet:ZS}),XS=Ch(YS),vn={},em;function QS(){if(em)return vn;em=1,Object.defineProperty(vn,"__esModule",{value:!0}),vn.isBrowserCryptoAvailable=vn.getSubtleCrypto=vn.getBrowerCrypto=void 0;function t(){return Ft?.crypto||Ft?.msCrypto||{}}vn.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}vn.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return vn.isBrowserCryptoAvailable=r,vn}var mn={},tm;function eI(){if(tm)return mn;tm=1,Object.defineProperty(mn,"__esModule",{value:!0}),mn.isBrowser=mn.isNode=mn.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}mn.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}mn.isNode=e;function r(){return!t()&&!e()}return mn.isBrowser=r,mn}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=XS;e.__exportStar(QS(),t),e.__exportStar(eI(),t)})(Xv);function bn(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Ps(t=6){return BigInt(bn(t))}function Zn(t,e,r){return{id:r||bn(),jsonrpc:"2.0",method:t,params:e}}function Cl(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Dl(t,e,r){return{id:t,jsonrpc:"2.0",error:tI(e,r)}}function tI(t,e){return typeof t>"u"?Zv(Gv):(typeof t=="string"&&(t=Object.assign(Object.assign({},Zv(xu)),{message:t})),typeof e<"u"&&(t.data=e),OS(t.code)&&(t=CS(t.code)),t)}class rI{}class iI extends rI{constructor(){super()}}class nI extends iI{constructor(e){super()}}const sI="^https?:",oI="^wss?:";function aI(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function rm(t,e){const r=aI(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function im(t){return rm(t,sI)}function nm(t){return rm(t,oI)}function cI(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function sm(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Iu(t){return sm(t)&&"method"in t}function Rl(t){return sm(t)&&(Gi(t)||fi(t))}function Gi(t){return"result"in t}function fi(t){return"error"in t}class ui extends nI{constructor(e){super(e),this.events=new nr.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Zn(e.method,e.params||[],e.id||Ps().toString()),r)}async requestStrict(e,r){return new Promise(async(i,n)=>{if(!this.connection.connected)try{await this.open()}catch(s){n(s)}this.events.on(`${e.id}`,s=>{fi(s)?n(s.error):i(s.result)});try{await this.connection.send(e,r)}catch(s){n(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Rl(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 lI=()=>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"),hI=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",om=t=>t.split("?")[0],am=10,fI=lI();class uI{constructor(e){if(this.url=e,this.events=new nr.exports.EventEmitter,this.registering=!1,!nm(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ln(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!nm(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return n(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,i)=>{const n=Xv.isReactNative()?void 0:{rejectUnauthorized:!cI(e)},s=new fI(e,[],n);hI()?s.onerror=o=>{const a=o;i(this.emitError(a.error))}:s.on("error",o=>{i(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ms(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=Dl(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return Yv(e,om(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>am&&this.events.setMaxListeners(am)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${om(this.url)}`));return this.events.emit("register_error",r),r}}var Au={exports:{}};(function(t,e){var r=200,i="__lodash_hash_undefined__",n=1,s=2,o=9007199254740991,a="[object Arguments]",c="[object Array]",l="[object AsyncFunction]",u="[object Boolean]",m="[object Date]",x="[object Error]",S="[object Function]",E="[object GeneratorFunction]",A="[object Map]",R="[object Number]",O="[object Null]",C="[object Object]",N="[object Promise]",T="[object Proxy]",U="[object RegExp]",z="[object Set]",W="[object String]",V="[object Symbol]",B="[object Undefined]",K="[object WeakMap]",M="[object ArrayBuffer]",v="[object DataView]",g="[object Float32Array]",h="[object Float64Array]",f="[object Int8Array]",p="[object Int16Array]",_="[object Int32Array]",$="[object Uint8Array]",y="[object Uint8ClampedArray]",d="[object Uint16Array]",w="[object Uint32Array]",b=/[\\^$.*+?()[\]{}|]/g,P=/^\[object .+?Constructor\]$/,q=/^(?:0|[1-9]\d*)$/,I={};I[g]=I[h]=I[f]=I[p]=I[_]=I[$]=I[y]=I[d]=I[w]=!0,I[a]=I[c]=I[M]=I[u]=I[v]=I[m]=I[x]=I[S]=I[A]=I[R]=I[C]=I[U]=I[z]=I[W]=I[K]=!1;var F=typeof Ft=="object"&&Ft&&Ft.Object===Object&&Ft,j=typeof self=="object"&&self&&self.Object===Object&&self,k=F||j||Function("return this")(),H=e&&!e.nodeType&&e,Y=H&&!0&&t&&!t.nodeType&&t,Q=Y&&Y.exports===H,J=Q&&F.process,ae=function(){try{return J&&J.binding&&J.binding("util")}catch{}}(),re=ae&&ae.isTypedArray;function ie(D,L){for(var G=-1,ne=D==null?0:D.length,Pt=0,Se=[];++G<ne;){var Tt=D[G];L(Tt,G,D)&&(Se[Pt++]=Tt)}return Se}function Ze(D,L){for(var G=-1,ne=L.length,Pt=D.length;++G<ne;)D[Pt+G]=L[G];return D}function Ye(D,L){for(var G=-1,ne=D==null?0:D.length;++G<ne;)if(L(D[G],G,D))return!0;return!1}function de(D,L){for(var G=-1,ne=Array(D);++G<D;)ne[G]=L(G);return ne}function qe(D){return function(L){return D(L)}}function je(D,L){return D.has(L)}function he(D,L){return D?.[L]}function ke(D){var L=-1,G=Array(D.size);return D.forEach(function(ne,Pt){G[++L]=[Pt,ne]}),G}function ze(D,L){return function(G){return D(L(G))}}function ue(D){var L=-1,G=Array(D.size);return D.forEach(function(ne){G[++L]=ne}),G}var He=Array.prototype,We=Function.prototype,le=Object.prototype,Be=k["__core-js_shared__"],Ve=We.toString,oe=le.hasOwnProperty,nt=function(){var D=/[^.]+$/.exec(Be&&Be.keys&&Be.keys.IE_PROTO||"");return D?"Symbol(src)_1."+D:""}(),st=le.toString,me=RegExp("^"+Ve.call(oe).replace(b,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ot=Q?k.Buffer:void 0,Ke=k.Symbol,ge=k.Uint8Array,at=le.propertyIsEnumerable,ft=He.splice,ce=Ke?Ke.toStringTag:void 0,ct=Object.getOwnPropertySymbols,ut=ot?ot.isBuffer:void 0,be=ze(Object.keys,Object),Xe=ua(k,"DataView"),Ue=ua(k,"Map"),pe=ua(k,"Promise"),Qe=ua(k,"Set"),et=ua(k,"WeakMap"),fe=ua(Object,"create"),dt=Js(Xe),pt=Js(Ue),ye=Js(pe),gt=Js(Qe),vt=Js(et),ve=Ke?Ke.prototype:void 0,tt=ve?ve.valueOf:void 0;function Re(D){var L=-1,G=D==null?0:D.length;for(this.clear();++L<G;){var ne=D[L];this.set(ne[0],ne[1])}}function we(){this.__data__=fe?fe(null):{},this.size=0}function mt(D){var L=this.has(D)&&delete this.__data__[D];return this.size-=L?1:0,L}function bt(D){var L=this.__data__;if(fe){var G=L[D];return G===i?void 0:G}return oe.call(L,D)?L[D]:void 0}function _e(D){var L=this.__data__;return fe?L[D]!==void 0:oe.call(L,D)}function yt(D,L){var G=this.__data__;return this.size+=this.has(D)?0:1,G[D]=fe&&L===void 0?i:L,this}Re.prototype.clear=we,Re.prototype.delete=mt,Re.prototype.get=bt,Re.prototype.has=_e,Re.prototype.set=yt;function Ae(D){var L=-1,G=D==null?0:D.length;for(this.clear();++L<G;){var ne=D[L];this.set(ne[0],ne[1])}}function lt(){this.__data__=[],this.size=0}function qr(D){var L=this.__data__,G=Ih(L,D);if(G<0)return!1;var ne=L.length-1;return G==ne?L.pop():ft.call(L,G,1),--this.size,!0}function jr(D){var L=this.__data__,G=Ih(L,D);return G<0?void 0:L[G][1]}function kr(D){return Ih(this.__data__,D)>-1}function zr(D,L){var G=this.__data__,ne=Ih(G,D);return ne<0?(++this.size,G.push([D,L])):G[ne][1]=L,this}Ae.prototype.clear=lt,Ae.prototype.delete=qr,Ae.prototype.get=jr,Ae.prototype.has=kr,Ae.prototype.set=zr;function kt(D){var L=-1,G=D==null?0:D.length;for(this.clear();++L<G;){var ne=D[L];this.set(ne[0],ne[1])}}function En(){this.size=0,this.__data__={hash:new Re,map:new(Ue||Ae),string:new Re}}function $n(D){var L=Ah(this,D).delete(D);return this.size-=L?1:0,L}function Sn(D){return Ah(this,D).get(D)}function In(D){return Ah(this,D).has(D)}function An(D,L){var G=Ah(this,D),ne=G.size;return G.set(D,L),this.size+=G.size==ne?0:1,this}kt.prototype.clear=En,kt.prototype.delete=$n,kt.prototype.get=Sn,kt.prototype.has=In,kt.prototype.set=An;function mi(D){var L=-1,G=D==null?0:D.length;for(this.__data__=new kt;++L<G;)this.add(D[L])}function Mn(D){return this.__data__.set(D,i),this}function Pn(D){return this.__data__.has(D)}mi.prototype.add=mi.prototype.push=Mn,mi.prototype.has=Pn;function wr(D){var L=this.__data__=new Ae(D);this.size=L.size}function On(){this.__data__=new Ae,this.size=0}function Cn(D){var L=this.__data__,G=L.delete(D);return this.size=L.size,G}function Dn(D){return this.__data__.get(D)}function $c(D){return this.__data__.has(D)}function Sc(D,L){var G=this.__data__;if(G instanceof Ae){var ne=G.__data__;if(!Ue||ne.length<r-1)return ne.push([D,L]),this.size=++G.size,this;G=this.__data__=new kt(ne)}return G.set(D,L),this.size=G.size,this}wr.prototype.clear=On,wr.prototype.delete=Cn,wr.prototype.get=Dn,wr.prototype.has=$c,wr.prototype.set=Sc;function $k(D,L){var G=Mh(D),ne=!G&&Uk(D),Pt=!G&&!ne&&y0(D),Se=!G&&!ne&&!Pt&&Ty(D),Tt=G||ne||Pt||Se,ir=Tt?de(D.length,String):[],pr=ir.length;for(var Ct in D)(L||oe.call(D,Ct))&&!(Tt&&(Ct=="length"||Pt&&(Ct=="offset"||Ct=="parent")||Se&&(Ct=="buffer"||Ct=="byteLength"||Ct=="byteOffset")||Nk(Ct,pr)))&&ir.push(Ct);return ir}function Ih(D,L){for(var G=D.length;G--;)if(Cy(D[G][0],L))return G;return-1}function Sk(D,L,G){var ne=L(D);return Mh(D)?ne:Ze(ne,G(D))}function Ic(D){return D==null?D===void 0?B:O:ce&&ce in Object(D)?Dk(D):Bk(D)}function Ay(D){return Ac(D)&&Ic(D)==a}function My(D,L,G,ne,Pt){return D===L?!0:D==null||L==null||!Ac(D)&&!Ac(L)?D!==D&&L!==L:Ik(D,L,G,ne,My,Pt)}function Ik(D,L,G,ne,Pt,Se){var Tt=Mh(D),ir=Mh(L),pr=Tt?c:ls(D),Ct=ir?c:ls(L);pr=pr==a?C:pr,Ct=Ct==a?C:Ct;var ri=pr==C,Di=Ct==C,_r=pr==Ct;if(_r&&y0(D)){if(!y0(L))return!1;Tt=!0,ri=!1}if(_r&&!ri)return Se||(Se=new wr),Tt||Ty(D)?Py(D,L,G,ne,Pt,Se):Ok(D,L,pr,G,ne,Pt,Se);if(!(G&n)){var bi=ri&&oe.call(D,"__wrapped__"),yi=Di&&oe.call(L,"__wrapped__");if(bi||yi){var hs=bi?D.value():D,Rn=yi?L.value():L;return Se||(Se=new wr),Pt(hs,Rn,G,ne,Se)}}return _r?(Se||(Se=new wr),Ck(D,L,G,ne,Pt,Se)):!1}function Ak(D){if(!Ny(D)||Fk(D))return!1;var L=Dy(D)?me:P;return L.test(Js(D))}function Mk(D){return Ac(D)&&Ry(D.length)&&!!I[Ic(D)]}function Pk(D){if(!Lk(D))return be(D);var L=[];for(var G in Object(D))oe.call(D,G)&&G!="constructor"&&L.push(G);return L}function Py(D,L,G,ne,Pt,Se){var Tt=G&n,ir=D.length,pr=L.length;if(ir!=pr&&!(Tt&&pr>ir))return!1;var Ct=Se.get(D);if(Ct&&Se.get(L))return Ct==L;var ri=-1,Di=!0,_r=G&s?new mi:void 0;for(Se.set(D,L),Se.set(L,D);++ri<ir;){var bi=D[ri],yi=L[ri];if(ne)var hs=Tt?ne(yi,bi,ri,L,D,Se):ne(bi,yi,ri,D,L,Se);if(hs!==void 0){if(hs)continue;Di=!1;break}if(_r){if(!Ye(L,function(Rn,Zs){if(!je(_r,Zs)&&(bi===Rn||Pt(bi,Rn,G,ne,Se)))return _r.push(Zs)})){Di=!1;break}}else if(!(bi===yi||Pt(bi,yi,G,ne,Se))){Di=!1;break}}return Se.delete(D),Se.delete(L),Di}function Ok(D,L,G,ne,Pt,Se,Tt){switch(G){case v:if(D.byteLength!=L.byteLength||D.byteOffset!=L.byteOffset)return!1;D=D.buffer,L=L.buffer;case M:return!(D.byteLength!=L.byteLength||!Se(new ge(D),new ge(L)));case u:case m:case R:return Cy(+D,+L);case x:return D.name==L.name&&D.message==L.message;case U:case W:return D==L+"";case A:var ir=ke;case z:var pr=ne&n;if(ir||(ir=ue),D.size!=L.size&&!pr)return!1;var Ct=Tt.get(D);if(Ct)return Ct==L;ne|=s,Tt.set(D,L);var ri=Py(ir(D),ir(L),ne,Pt,Se,Tt);return Tt.delete(D),ri;case V:if(tt)return tt.call(D)==tt.call(L)}return!1}function Ck(D,L,G,ne,Pt,Se){var Tt=G&n,ir=Oy(D),pr=ir.length,Ct=Oy(L),ri=Ct.length;if(pr!=ri&&!Tt)return!1;for(var Di=pr;Di--;){var _r=ir[Di];if(!(Tt?_r in L:oe.call(L,_r)))return!1}var bi=Se.get(D);if(bi&&Se.get(L))return bi==L;var yi=!0;Se.set(D,L),Se.set(L,D);for(var hs=Tt;++Di<pr;){_r=ir[Di];var Rn=D[_r],Zs=L[_r];if(ne)var Fy=Tt?ne(Zs,Rn,_r,L,D,Se):ne(Rn,Zs,_r,D,L,Se);if(!(Fy===void 0?Rn===Zs||Pt(Rn,Zs,G,ne,Se):Fy)){yi=!1;break}hs||(hs=_r=="constructor")}if(yi&&!hs){var Ph=D.constructor,Oh=L.constructor;Ph!=Oh&&"constructor"in D&&"constructor"in L&&!(typeof Ph=="function"&&Ph instanceof Ph&&typeof Oh=="function"&&Oh instanceof Oh)&&(yi=!1)}return Se.delete(D),Se.delete(L),yi}function Oy(D){return Sk(D,kk,Rk)}function Ah(D,L){var G=D.__data__;return Tk(L)?G[typeof L=="string"?"string":"hash"]:G.map}function ua(D,L){var G=he(D,L);return Ak(G)?G:void 0}function Dk(D){var L=oe.call(D,ce),G=D[ce];try{D[ce]=void 0;var ne=!0}catch{}var Pt=st.call(D);return ne&&(L?D[ce]=G:delete D[ce]),Pt}var Rk=ct?function(D){return D==null?[]:(D=Object(D),ie(ct(D),function(L){return at.call(D,L)}))}:zk,ls=Ic;(Xe&&ls(new Xe(new ArrayBuffer(1)))!=v||Ue&&ls(new Ue)!=A||pe&&ls(pe.resolve())!=N||Qe&&ls(new Qe)!=z||et&&ls(new et)!=K)&&(ls=function(D){var L=Ic(D),G=L==C?D.constructor:void 0,ne=G?Js(G):"";if(ne)switch(ne){case dt:return v;case pt:return A;case ye:return N;case gt:return z;case vt:return K}return L});function Nk(D,L){return L=L??o,!!L&&(typeof D=="number"||q.test(D))&&D>-1&&D%1==0&&D<L}function Tk(D){var L=typeof D;return L=="string"||L=="number"||L=="symbol"||L=="boolean"?D!=="__proto__":D===null}function Fk(D){return!!nt&&nt in D}function Lk(D){var L=D&&D.constructor,G=typeof L=="function"&&L.prototype||le;return D===G}function Bk(D){return st.call(D)}function Js(D){if(D!=null){try{return Ve.call(D)}catch{}try{return D+""}catch{}}return""}function Cy(D,L){return D===L||D!==D&&L!==L}var Uk=Ay(function(){return arguments}())?Ay:function(D){return Ac(D)&&oe.call(D,"callee")&&!at.call(D,"callee")},Mh=Array.isArray;function qk(D){return D!=null&&Ry(D.length)&&!Dy(D)}var y0=ut||Hk;function jk(D,L){return My(D,L)}function Dy(D){if(!Ny(D))return!1;var L=Ic(D);return L==S||L==E||L==l||L==T}function Ry(D){return typeof D=="number"&&D>-1&&D%1==0&&D<=o}function Ny(D){var L=typeof D;return D!=null&&(L=="object"||L=="function")}function Ac(D){return D!=null&&typeof D=="object"}var Ty=re?qe(re):Mk;function kk(D){return qk(D)?$k(D):Pk(D)}function zk(){return[]}function Hk(){return!1}t.exports=jk})(Au,Au.exports);var dI=Au.exports,pI=Object.defineProperty,cm=Object.getOwnPropertySymbols,gI=Object.prototype.hasOwnProperty,vI=Object.prototype.propertyIsEnumerable,lm=(t,e,r)=>e in t?pI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ar=(t,e)=>{for(var r in e||(e={}))gI.call(e,r)&&lm(t,r,e[r]);if(cm)for(var r of cm(e))vI.call(e,r)&&lm(t,r,e[r]);return t};const hm="wc",fm=2,Nl="core",Ji=`${hm}@2:${Nl}:`,mI={name:Nl,logger:"error"},bI={database:":memory:"},yI="crypto",um="client_ed25519_seed",wI=X.ONE_DAY,_I="keychain",xI="0.3",EI="messages",$I="0.3",dm=X.SIX_HOURS,SI="publisher",pm="irn",II="error",gm="wss://relay.walletconnect.org",AI="relayer",Qt={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"},MI="_subscription",di={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},PI=.1,Mu="2.18.1-rc-1",St={link_mode:"link_mode",relay:"relay"},OI="0.3",CI="WALLETCONNECT_CLIENT_ID",vm="WALLETCONNECT_LINK_MODE_APPS",Zr={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},DI="subscription",RI="0.3",NI=X.FIVE_SECONDS*1e3,TI="pairing",FI="0.3",Ya={wc_pairingDelete:{req:{ttl:X.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:X.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:X.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:X.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:X.ONE_DAY,prompt:!1,tag:0},res:{ttl:X.ONE_DAY,prompt:!1,tag:0}}},Os={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Mi={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},LI="history",BI="0.3",UI="expirer",pi={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},qI="0.3",jI="verify-api",kI="https://verify.walletconnect.com",mm="https://verify.walletconnect.org",Xa=mm,zI=`${Xa}/v3`,HI=[kI,mm],WI="echo",VI="https://echo.walletconnect.com",Zi={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},yn={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Pi={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},Cs={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},Ds={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},Qa={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},KI=.1,GI="event-client",JI=86400,ZI="https://pulse.walletconnect.org/batch";function YI(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=n}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function m(E){if(E instanceof Uint8Array||(ArrayBuffer.isView(E)?E=new Uint8Array(E.buffer,E.byteOffset,E.byteLength):Array.isArray(E)&&(E=Uint8Array.from(E))),!(E instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(E.length===0)return"";for(var A=0,R=0,O=0,C=E.length;O!==C&&E[O]===0;)O++,A++;for(var N=(C-O)*u+1>>>0,T=new Uint8Array(N);O!==C;){for(var U=E[O],z=0,W=N-1;(U!==0||z<R)&&W!==-1;W--,z++)U+=256*T[W]>>>0,T[W]=U%a>>>0,U=U/a>>>0;if(U!==0)throw new Error("Non-zero carry");R=z,O++}for(var V=N-R;V!==N&&T[V]===0;)V++;for(var B=c.repeat(A);V<N;++V)B+=t.charAt(T[V]);return B}function x(E){if(typeof E!="string")throw new TypeError("Expected String");if(E.length===0)return new Uint8Array;var A=0;if(E[A]!==" "){for(var R=0,O=0;E[A]===c;)R++,A++;for(var C=(E.length-A)*l+1>>>0,N=new Uint8Array(C);E[A];){var T=r[E.charCodeAt(A)];if(T===255)return;for(var U=0,z=C-1;(T!==0||U<O)&&z!==-1;z--,U++)T+=a*N[z]>>>0,N[z]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");O=U,A++}if(E[A]!==" "){for(var W=C-O;W!==C&&N[W]===0;)W++;for(var V=new Uint8Array(R+(C-W)),B=R;W!==C;)V[B++]=N[W++];return V}}}function S(E){var A=x(E);if(A)return A;throw new Error(`Non-${e} character`)}return{encode:m,decodeUnsafe:x,decode:S}}var XI=YI,QI=XI;const bm=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},eA=t=>new TextEncoder().encode(t),tA=t=>new TextDecoder().decode(t);class rA{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class iA{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=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 ym(this,e)}}class nA{constructor(e){this.decoders=e}or(e){return ym(this,e)}decode(e){const r=e[0],i=this.decoders[r];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 ym=(t,e)=>new nA(Ar(Ar({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class sA{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new rA(e,r,i),this.decoder=new iA(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Tl=({name:t,prefix:e,encode:r,decode:i})=>new sA(t,e,r,i),ec=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=QI(r,e);return Tl({prefix:t,name:e,encode:i,decode:s=>bm(n(s))})},oA=(t,e,r,i)=>{const n={};for(let u=0;u<e.length;++u)n[e[u]]=u;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const m=n[t[u]];if(m===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|m,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},aA=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[n&a>>o];if(o&&(s+=e[n&a<<r-o]),i)for(;s.length*r&7;)s+="=";return s},fr=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Tl({prefix:e,name:t,encode(n){return aA(n,i,r)},decode(n){return oA(n,i,r,t)}}),cA=Tl({prefix:"\0",name:"identity",encode:t=>tA(t),decode:t=>eA(t)});var lA=Object.freeze({__proto__:null,identity:cA});const hA=fr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var fA=Object.freeze({__proto__:null,base2:hA});const uA=fr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var dA=Object.freeze({__proto__:null,base8:uA});const pA=ec({prefix:"9",name:"base10",alphabet:"0123456789"});var gA=Object.freeze({__proto__:null,base10:pA});const vA=fr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),mA=fr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var bA=Object.freeze({__proto__:null,base16:vA,base16upper:mA});const yA=fr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),wA=fr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),_A=fr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),xA=fr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),EA=fr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),$A=fr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),SA=fr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),IA=fr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),AA=fr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var MA=Object.freeze({__proto__:null,base32:yA,base32upper:wA,base32pad:_A,base32padupper:xA,base32hex:EA,base32hexupper:$A,base32hexpad:SA,base32hexpadupper:IA,base32z:AA});const PA=ec({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),OA=ec({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var CA=Object.freeze({__proto__:null,base36:PA,base36upper:OA});const DA=ec({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),RA=ec({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var NA=Object.freeze({__proto__:null,base58btc:DA,base58flickr:RA});const TA=fr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),FA=fr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),LA=fr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),BA=fr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var UA=Object.freeze({__proto__:null,base64:TA,base64pad:FA,base64url:LA,base64urlpad:BA});const wm=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}"),qA=wm.reduce((t,e,r)=>(t[r]=e,t),[]),jA=wm.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function kA(t){return t.reduce((e,r)=>(e+=qA[r],e),"")}function zA(t){const e=[];for(const r of t){const i=jA[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const HA=Tl({prefix:"\u{1F680}",name:"base256emoji",encode:kA,decode:zA});var WA=Object.freeze({__proto__:null,base256emoji:HA}),VA=xm,_m=128,KA=127,GA=~KA,JA=Math.pow(2,31);function xm(t,e,r){e=e||[],r=r||0;for(var i=r;t>=JA;)e[r++]=t&255|_m,t/=128;for(;t&GA;)e[r++]=t&255|_m,t>>>=7;return e[r]=t|0,xm.bytes=r-i+1,e}var ZA=Pu,YA=128,Em=127;function Pu(t,i){var r=0,i=i||0,n=0,s=i,o,a=t.length;do{if(s>=a)throw Pu.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=n<28?(o&Em)<<n:(o&Em)*Math.pow(2,n),n+=7}while(o>=YA);return Pu.bytes=s-i,r}var XA=Math.pow(2,7),QA=Math.pow(2,14),eM=Math.pow(2,21),tM=Math.pow(2,28),rM=Math.pow(2,35),iM=Math.pow(2,42),nM=Math.pow(2,49),sM=Math.pow(2,56),oM=Math.pow(2,63),aM=function(t){return t<XA?1:t<QA?2:t<eM?3:t<tM?4:t<rM?5:t<iM?6:t<nM?7:t<sM?8:t<oM?9:10},cM={encode:VA,decode:ZA,encodingLength:aM},$m=cM;const Sm=(t,e,r=0)=>($m.encode(t,e,r),e),Im=t=>$m.encodingLength(t),Ou=(t,e)=>{const r=e.byteLength,i=Im(t),n=i+Im(r),s=new Uint8Array(n+r);return Sm(t,s,0),Sm(r,s,i),s.set(e,n),new lM(t,r,e,s)};class lM{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const Am=({name:t,code:e,encode:r})=>new hM(t,e,r);class hM{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Ou(this.code,r):r.then(i=>Ou(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Mm=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),fM=Am({name:"sha2-256",code:18,encode:Mm("SHA-256")}),uM=Am({name:"sha2-512",code:19,encode:Mm("SHA-512")});var dM=Object.freeze({__proto__:null,sha256:fM,sha512:uM});const Pm=0,pM="identity",Om=bm;var gM=Object.freeze({__proto__:null,identity:{code:Pm,name:pM,encode:Om,digest:t=>Ou(Pm,Om(t))}});new TextEncoder,new TextDecoder;const Cm=Ar(Ar(Ar(Ar(Ar(Ar(Ar(Ar(Ar(Ar({},lA),fA),dA),gA),bA),MA),CA),NA),UA),WA);Ar(Ar({},dM),gM);function vM(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Dm(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const Rm=Dm("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Cu=Dm("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=vM(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),mM=Ar({utf8:Rm,"utf-8":Rm,hex:Cm.base16,latin1:Cu,ascii:Cu,binary:Cu},Cm);function bM(t,e="utf8"){const r=mM[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}var yM=Object.defineProperty,wM=(t,e,r)=>e in t?yM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yi=(t,e,r)=>wM(t,typeof e!="symbol"?e+"":e,r);class _M{constructor(e,r){this.core=e,this.logger=r,Yi(this,"keychain",new Map),Yi(this,"name",_I),Yi(this,"version",xI),Yi(this,"initialized",!1),Yi(this,"storagePrefix",Ji),Yi(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Yi(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Yi(this,"set",async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()}),Yi(this,"get",i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=ee("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n}),Yi(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=Ir(r,this.name)}get context(){return Tr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,xg(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Eg(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}var xM=Object.defineProperty,EM=(t,e,r)=>e in t?xM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ur=(t,e,r)=>EM(t,typeof e!="symbol"?e+"":e,r);class $M{constructor(e,r,i){this.core=e,this.logger=r,ur(this,"name",yI),ur(this,"keychain"),ur(this,"randomSessionIdentifier",hu()),ur(this,"initialized",!1),ur(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),ur(this,"hasKeys",n=>(this.isInitialized(),this.keychain.has(n))),ur(this,"getClientId",async()=>{this.isInitialized();const n=await this.getClientSeed(),s=F1(n);return T1(s.publicKey)}),ur(this,"generateKeyPair",()=>{this.isInitialized();const n=rE();return this.setPrivateKey(n.publicKey,n.privateKey)}),ur(this,"signJWT",async n=>{this.isInitialized();const s=await this.getClientSeed(),o=F1(s),a=this.randomSessionIdentifier;return await U8(a,n,wI,o)}),ur(this,"generateSharedKey",(n,s,o)=>{this.isInitialized();const a=this.getPrivateKey(n),c=iE(a,s);return this.setSymKey(c,o)}),ur(this,"setSymKey",async(n,s)=>{this.isInitialized();const o=s||bl(n);return await this.keychain.set(o,n),o}),ur(this,"deleteKeyPair",async n=>{this.isInitialized(),await this.keychain.del(n)}),ur(this,"deleteSymKey",async n=>{this.isInitialized(),await this.keychain.del(n)}),ur(this,"encode",async(n,s,o)=>{this.isInitialized();const a=wv(o),c=ln(s);if(xv(a))return oE(c,o?.encoding);if(_v(a)){const x=a.senderPublicKey,S=a.receiverPublicKey;n=await this.generateSharedKey(x,S)}const l=this.getSymKey(n),{type:u,senderPublicKey:m}=a;return nE({type:u,symKey:l,message:c,senderPublicKey:m,encoding:o?.encoding})}),ur(this,"decode",async(n,s,o)=>{this.isInitialized();const a=cE(s,o);if(xv(a)){const c=aE(s,o?.encoding);return ms(c)}if(_v(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;n=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(n),l=sE({symKey:c,encoded:s,encoding:o?.encoding});return ms(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),ur(this,"getPayloadType",(n,s=Jn)=>{const o=qa({encoded:n,encoding:s});return Is(o.type)}),ur(this,"getPayloadSenderPublicKey",(n,s=Jn)=>{const o=qa({encoded:n,encoding:s});return o.senderPublicKey?$r(o.senderPublicKey,mr):void 0}),this.core=e,this.logger=Ir(r,this.name),this.keychain=i||new _M(this.core,this.logger)}get context(){return Tr(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(um)}catch{e=hu(),await this.keychain.set(um,e)}return bM(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}var SM=Object.defineProperty,IM=(t,e,r)=>e in t?SM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Xi=(t,e,r)=>IM(t,typeof e!="symbol"?e+"":e,r);class AM extends uS{constructor(e,r){super(e,r),this.logger=e,this.core=r,Xi(this,"messages",new Map),Xi(this,"name",EI),Xi(this,"version",$I),Xi(this,"initialized",!1),Xi(this,"storagePrefix",Ji),Xi(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}}}),Xi(this,"set",async(i,n)=>{this.isInitialized();const s=gn(n);let o=this.messages.get(i);return typeof o>"u"&&(o={}),typeof o[s]<"u"||(o[s]=n,this.messages.set(i,o),await this.persist()),s}),Xi(this,"get",i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n}),Xi(this,"has",(i,n)=>{this.isInitialized();const s=this.get(i),o=gn(n);return typeof s[o]<"u"}),Xi(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()}),this.logger=Ir(e,this.name),this.core=r}get context(){return Tr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,xg(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Eg(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}var MM=Object.defineProperty,PM=Object.defineProperties,OM=Object.getOwnPropertyDescriptors,Nm=Object.getOwnPropertySymbols,CM=Object.prototype.hasOwnProperty,DM=Object.prototype.propertyIsEnumerable,Du=(t,e,r)=>e in t?MM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fl=(t,e)=>{for(var r in e||(e={}))CM.call(e,r)&&Du(t,r,e[r]);if(Nm)for(var r of Nm(e))DM.call(e,r)&&Du(t,r,e[r]);return t},Ru=(t,e)=>PM(t,OM(e)),Oi=(t,e,r)=>Du(t,typeof e!="symbol"?e+"":e,r);class RM extends dS{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,Oi(this,"events",new nr.exports.EventEmitter),Oi(this,"name",SI),Oi(this,"queue",new Map),Oi(this,"publishTimeout",X.toMiliseconds(X.ONE_MINUTE)),Oi(this,"initialPublishTimeout",X.toMiliseconds(X.ONE_SECOND*15)),Oi(this,"needsTransportRestart",!1),Oi(this,"publish",async(i,n,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:s}});const a=s?.ttl||dm,c=yl(s),l=s?.prompt||!1,u=s?.tag||0,m=s?.id||Ps().toString(),x={topic:i,message:n,opts:{ttl:a,relay:c,prompt:l,tag:u,id:m,attestation:s?.attestation,tvf:s?.tvf}},S=`Failed to publish payload, please try again. id:${m} tag:${u}`;try{const E=new Promise(async A=>{const R=({id:C})=>{x.opts.id===C&&(this.removeRequestFromQueue(C),this.relayer.events.removeListener(Qt.publish,R),A(x))};this.relayer.events.on(Qt.publish,R);const O=Hn(new Promise((C,N)=>{this.rpcPublish({topic:i,message:n,ttl:a,prompt:l,tag:u,id:m,attestation:s?.attestation,tvf:s?.tvf}).then(C).catch(T=>{this.logger.warn(T,T?.message),N(T)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${m} tag:${u}`);try{await O,this.events.removeListener(Qt.publish,R)}catch(C){this.queue.set(m,Ru(Fl({},x),{attempt:1})),this.logger.warn(C,C?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:m,topic:i,message:n,opts:s}}),await Hn(E,this.publishTimeout,S)}catch(E){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(E),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw E}finally{this.queue.delete(m)}}),Oi(this,"on",(i,n)=>{this.events.on(i,n)}),Oi(this,"once",(i,n)=>{this.events.once(i,n)}),Oi(this,"off",(i,n)=>{this.events.off(i,n)}),Oi(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.relayer=e,this.logger=Ir(r,this.name),this.registerEventListeners()}get context(){return Tr(this.logger)}async rpcPublish(e){var r,i,n,s;const{topic:o,message:a,ttl:c=dm,prompt:l,tag:u,id:m,attestation:x,tvf:S}=e,E={method:ja(yl().protocol).publish,params:Fl({topic:o,message:a,ttl:c,prompt:l,tag:u,attestation:x},S),id:m};Sr((r=E.params)==null?void 0:r.prompt)&&((i=E.params)==null||delete i.prompt),Sr((n=E.params)==null?void 0:n.tag)&&((s=E.params)==null||delete s.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:E});const A=await this.relayer.request(E);return this.relayer.events.emit(Qt.publish,e),this.logger.debug("Successfully Published Payload"),A}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const i=e.attempt+1;this.queue.set(r,Ru(Fl({},e),{attempt:i}));const{topic:n,message:s,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish(Ru(Fl({},e),{topic:n,message:s,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Io.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Qt.connection_stalled);return}this.checkQueue()}),this.relayer.on(Qt.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var NM=Object.defineProperty,TM=(t,e,r)=>e in t?NM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Po=(t,e,r)=>TM(t,typeof e!="symbol"?e+"":e,r);class FM{constructor(){Po(this,"map",new Map),Po(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),Po(this,"get",e=>this.map.get(e)||[]),Po(this,"exists",(e,r)=>this.get(e).includes(r)),Po(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,r))return;const n=i.filter(s=>s!==r);if(!n.length){this.map.delete(e);return}this.map.set(e,n)}),Po(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var LM=Object.defineProperty,BM=Object.defineProperties,UM=Object.getOwnPropertyDescriptors,Tm=Object.getOwnPropertySymbols,qM=Object.prototype.hasOwnProperty,jM=Object.prototype.propertyIsEnumerable,Nu=(t,e,r)=>e in t?LM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,tc=(t,e)=>{for(var r in e||(e={}))qM.call(e,r)&&Nu(t,r,e[r]);if(Tm)for(var r of Tm(e))jM.call(e,r)&&Nu(t,r,e[r]);return t},Tu=(t,e)=>BM(t,UM(e)),xt=(t,e,r)=>Nu(t,typeof e!="symbol"?e+"":e,r);class kM extends vS{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,xt(this,"subscriptions",new Map),xt(this,"topicMap",new FM),xt(this,"events",new nr.exports.EventEmitter),xt(this,"name",DI),xt(this,"version",RI),xt(this,"pending",new Map),xt(this,"cached",[]),xt(this,"initialized",!1),xt(this,"pendingSubscriptionWatchLabel","pending_sub_watch_label"),xt(this,"pollingInterval",20),xt(this,"storagePrefix",Ji),xt(this,"subscribeTimeout",X.toMiliseconds(X.ONE_MINUTE)),xt(this,"initialSubscribeTimeout",X.toMiliseconds(X.ONE_SECOND*15)),xt(this,"clientId"),xt(this,"batchSubscribeTopicsLimit",500),xt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),xt(this,"subscribe",async(i,n)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const s=yl(n),o={topic:i,relay:s,transportType:n?.transportType};this.pending.set(i,o);const a=await this.rpcSubscribe(i,s,n);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}})),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}}),xt(this,"unsubscribe",async(i,n)=>{await this.restartToComplete(),this.isInitialized(),typeof n?.id<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)}),xt(this,"isSubscribed",async i=>{if(this.topics.includes(i))return!0;const n=`${this.pendingSubscriptionWatchLabel}_${i}`;return await new Promise((s,o)=>{const a=new X.Watch;a.start(n);const c=setInterval(()=>{(!this.pending.has(i)&&this.topics.includes(i)||this.cached.some(l=>l.topic===i))&&(clearInterval(c),a.stop(n),s(!0)),a.elapsed(n)>=NI&&(clearInterval(c),a.stop(n),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)}),xt(this,"on",(i,n)=>{this.events.on(i,n)}),xt(this,"once",(i,n)=>{this.events.once(i,n)}),xt(this,"off",(i,n)=>{this.events.off(i,n)}),xt(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),xt(this,"start",async()=>{await this.onConnect()}),xt(this,"stop",async()=>{await this.onDisconnect()}),xt(this,"restart",async()=>{await this.restore(),await this.onRestart()}),xt(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(n=>{i.push(n)}),await this.batchSubscribe(i)}),xt(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Io.pulse,async()=>{await this.checkPending()}),this.events.on(Zr.created,async i=>{const n=Zr.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()}),this.events.on(Zr.deleted,async i=>{const n=Zr.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()})}),this.relayer=e,this.logger=Ir(r,this.name),this.clientId=""}get context(){return Tr(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,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const i=this.topicMap.get(e);await Promise.all(i.map(async n=>await this.unsubscribeById(e,n,r)))}async unsubscribeById(e,r,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}});try{const n=yl(i);await this.rpcUnsubscribe(e,r,n);const s=wt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,r,i){var n;i?.transportType===St.relay&&await this.restartToComplete();const s={method:ja(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});const o=(n=i?.internal)==null?void 0:n.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(i?.transportType===St.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(u=>this.logger.warn(u))},X.toMiliseconds(X.ONE_SECOND)),a;const c=new Promise(async u=>{const m=x=>{x.topic===e&&(this.events.removeListener(Zr.created,m),u(x.id))};this.events.on(Zr.created,m);try{const x=await Hn(new Promise((S,E)=>{this.relayer.request(s).catch(A=>{this.logger.warn(A,A?.message),E(A)}).then(S)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Zr.created,m),u(x)}catch{}}),l=await Hn(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return l?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Qt.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:ja(r.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await Hn(new Promise(n=>{this.relayer.request(i).catch(s=>this.logger.warn(s)).then(n)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Qt.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:ja(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let n;try{n=await await Hn(new Promise((s,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Qt.connection_stalled)}return n}rpcUnsubscribe(e,r,i){const n={method:ja(i.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,r){this.setSubscription(e,Tu(tc({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,tc({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,i){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,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,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,tc({},r)),this.topicMap.set(r.topic,e),this.events.emit(Zr.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:i}=ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(Zr.deleted,Tu(tc({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Zr.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<r;i++){const n=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}}this.events.emit(Zr.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async r=>Tu(tc({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await b_(X.toMiliseconds(X.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){!this.relayer.connected&&!this.relayer.connecting&&await this.relayer.transportOpen()}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return gn(e+await this.getClientId())}}var zM=Object.defineProperty,Fm=Object.getOwnPropertySymbols,HM=Object.prototype.hasOwnProperty,WM=Object.prototype.propertyIsEnumerable,Fu=(t,e,r)=>e in t?zM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lm=(t,e)=>{for(var r in e||(e={}))HM.call(e,r)&&Fu(t,r,e[r]);if(Fm)for(var r of Fm(e))WM.call(e,r)&&Fu(t,r,e[r]);return t},rt=(t,e,r)=>Fu(t,typeof e!="symbol"?e+"":e,r);class VM extends pS{constructor(e){super(e),rt(this,"protocol","wc"),rt(this,"version",2),rt(this,"core"),rt(this,"logger"),rt(this,"events",new nr.exports.EventEmitter),rt(this,"provider"),rt(this,"messages"),rt(this,"subscriber"),rt(this,"publisher"),rt(this,"name",AI),rt(this,"transportExplicitlyClosed",!1),rt(this,"initialized",!1),rt(this,"connectionAttemptInProgress",!1),rt(this,"relayUrl"),rt(this,"projectId"),rt(this,"packageName"),rt(this,"bundleId"),rt(this,"hasExperiencedNetworkDisruption",!1),rt(this,"pingTimeout"),rt(this,"heartBeatTimeout",X.toMiliseconds(X.THIRTY_SECONDS+X.FIVE_SECONDS)),rt(this,"reconnectTimeout"),rt(this,"connectPromise"),rt(this,"requestsInFlight",[]),rt(this,"connectTimeout",X.toMiliseconds(X.ONE_SECOND*15)),rt(this,"request",async r=>{var i,n;this.logger.debug("Publishing Request Payload");const s=r.id||Ps().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - publishing...");const o=`${s}:${((n=r.params)==null?void 0:n.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}}),rt(this,"resetPingTimeout",()=>{if(ll())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,i,n;this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null||n.terminate()},this.heartBeatTimeout)}catch(r){this.logger.warn(r,r?.message)}}),rt(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),rt(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Qt.connect)}),rt(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),rt(this,"onProviderErrorHandler",r=>{this.logger.fatal(r,`Fatal socket error: ${r?.message}`),this.events.emit(Qt.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),rt(this,"registerProviderListeners",()=>{this.provider.on(di.payload,this.onPayloadHandler),this.provider.on(di.connect,this.onConnectHandler),this.provider.on(di.disconnect,this.onDisconnectHandler),this.provider.on(di.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Ir(e.logger,this.name):Vi(Ol({level:e.logger||II})),this.messages=new AM(this.logger,e.core),this.subscriber=new kM(this,this.logger),this.publisher=new RM(this,this.logger),this.relayUrl=e?.relayUrl||gm,this.projectId=e.projectId,i_()?this.packageName=yg():n_()&&(this.bundleId=yg()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.cached.length>0)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return Tr(this.logger)}get connected(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===1}get connecting(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===0}async publish(e,r,i){this.isInitialized(),await this.publisher.publish(e,r,i),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:St.relay})}async subscribe(e,r){var i,n,s;this.isInitialized(),(!(r!=null&&r.transportType)||r?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((i=r?.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(n=r?.internal)==null?void 0:n.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(Zr.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(Zr.created,l)}),new Promise(async(u,m)=>{a=await this.subscriber.subscribe(e,Lm({internal:{throwOnFailedPublish:o}},r)).catch(x=>{o&&m(x)})||a,u()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Hn(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,i)=>{await this.connect(e).then(r).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Dv())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const r=e.sort((i,n)=>i.publishedAt-n.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n,"Error while processing batch message event: "+n?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const n=Wt(X.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,s)}this.events.emit(Qt.message,e),await this.recordMessageEvent(e)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(i,n)=>{const s=()=>{n(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(di.disconnect,s),await Hn(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{n(o)}).finally(()=>{this.provider.off(di.disconnect,s),clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(di.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(di.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const n=i;this.logger.warn({},n.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(i=>setTimeout(i,X.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,n,s;if(ll())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(n=(i=this.provider)==null?void 0:i.connection)==null?void 0:n.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new ui(new uI(c_({sdkVersion:Mu,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:r,message:i}=e;await this.messages.set(r,i)}async shouldIgnoreMessageEvent(e){const{topic:r,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.warn(`Ignoring message for non-subscribed topic ${r}`),!0;const n=this.messages.has(r,i);return n&&this.logger.warn(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Iu(e)){if(!e.method.endsWith(MI))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:o}=r.data,a={topic:i,message:n,publishedAt:s,transportType:St.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Lm({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Rl(e)&&this.events.emit(Qt.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Qt.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=Cl(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(di.payload,this.onPayloadHandler),this.provider.off(di.connect,this.onConnectHandler),this.provider.off(di.disconnect,this.onDisconnectHandler),this.provider.off(di.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Dv();JE(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(i=>this.logger.error(i,i?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),clearTimeout(this.pingTimeout),this.events.emit(Qt.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&(this.reconnectTimeout||this.connectPromise||(this.reconnectTimeout=setTimeout(async()=>{clearTimeout(this.reconnectTimeout),await this.transportOpen().catch(e=>this.logger.error(e,e?.message))},X.toMiliseconds(PI))))}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.transportOpen()}}var KM=Object.defineProperty,Bm=Object.getOwnPropertySymbols,GM=Object.prototype.hasOwnProperty,JM=Object.prototype.propertyIsEnumerable,Lu=(t,e,r)=>e in t?KM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Um=(t,e)=>{for(var r in e||(e={}))GM.call(e,r)&&Lu(t,r,e[r]);if(Bm)for(var r of Bm(e))JM.call(e,r)&&Lu(t,r,e[r]);return t},Fr=(t,e,r)=>Lu(t,typeof e!="symbol"?e+"":e,r);class Rs extends gS{constructor(e,r,i,n=Ji,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,Fr(this,"map",new Map),Fr(this,"version",OI),Fr(this,"cached",[]),Fr(this,"initialized",!1),Fr(this,"getKey"),Fr(this,"storagePrefix",Ji),Fr(this,"recentlyDeleted",[]),Fr(this,"recentlyDeletedLimit",200),Fr(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Sr(o)?this.map.set(this.getKey(o),o):IE(o)?this.map.set(o.id,o):AE(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Fr(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),Fr(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Fr(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>dI(a[c],o[c]))):this.values)),Fr(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Um(Um({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Fr(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=Ir(r,this.name),this.storagePrefix=n,this.getKey=s}get context(){return Tr(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())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:n}=ee("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:i}=ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}var ZM=Object.defineProperty,YM=(t,e,r)=>e in t?ZM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ne=(t,e,r)=>YM(t,typeof e!="symbol"?e+"":e,r);class XM{constructor(e,r){this.core=e,this.logger=r,Ne(this,"name",TI),Ne(this,"version",FI),Ne(this,"events",new nr.exports),Ne(this,"pairings"),Ne(this,"initialized",!1),Ne(this,"storagePrefix",Ji),Ne(this,"ignoredPayloadTypes",[pn]),Ne(this,"registeredMethods",[]),Ne(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Ne(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),Ne(this,"create",async i=>{this.isInitialized();const n=hu(),s=await this.core.crypto.setSymKey(n),o=Wt(X.FIVE_MINUTES),a={protocol:pm},c={topic:s,expiry:o,relay:a,active:!1,methods:i?.methods},l=$v({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:a,expiryTimestamp:o,methods:i?.methods});return this.events.emit(Os.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:i?.transportType}),{topic:s,uri:l}}),Ne(this,"pair",async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i?.uri,trace:[Zi.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=Ev(i.uri);n.props.properties.topic=s,n.addTrace(Zi.pairing_uri_validation_success),n.addTrace(Zi.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),n.addTrace(Zi.existing_pairing),u.active)throw n.setError(yn.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(Zi.pairing_not_expired)}const m=c||Wt(X.FIVE_MINUTES),x={topic:s,relay:a,expiry:m,active:!1,methods:l};this.core.expirer.set(s,m),await this.pairings.set(s,x),n.addTrace(Zi.store_new_pairing),i.activatePairing&&await this.activate({topic:s}),this.events.emit(Os.create,x),n.addTrace(Zi.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),n.addTrace(Zi.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(yn.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(S){throw n.setError(yn.subscribe_pairing_topic_failure),S}return n.addTrace(Zi.subscribe_pairing_topic_success),x}),Ne(this,"activate",async({topic:i})=>{this.isInitialized();const n=Wt(X.FIVE_MINUTES);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})}),Ne(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:n}=i;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=$s();this.events.once(Oe("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),Ne(this,"updateExpiry",async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})}),Ne(this,"updateMetadata",async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})}),Ne(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Ne(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:n}=i;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",wt("USER_DISCONNECTED")),await this.deletePairing(n))}),Ne(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:n,relay:s,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(n);return $v({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),Ne(this,"sendRequest",async(i,n,s)=>{const o=Zn(n,s),a=await this.core.crypto.encode(i,o),c=Ya[n].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),Ne(this,"sendResult",async(i,n,s)=>{const o=Cl(i,s),a=await this.core.crypto.encode(n,o),c=await this.core.history.get(n,i),l=Ya[c.request.method].res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),Ne(this,"sendError",async(i,n,s)=>{const o=Dl(i,s),a=await this.core.crypto.encode(n,o),c=await this.core.history.get(n,i),l=Ya[c.request.method]?Ya[c.request.method].res:Ya.unregistered_method.res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),Ne(this,"deletePairing",async(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,wt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])}),Ne(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(n=>Wn(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))}),Ne(this,"onRelayEventRequest",i=>{const{topic:n,payload:s}=i;switch(s.method){case"wc_pairingPing":return this.onPairingPingRequest(n,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(n,s);default:return this.onUnknownRpcMethodRequest(n,s)}}),Ne(this,"onRelayEventResponse",async i=>{const{topic:n,payload:s}=i,o=(await this.core.history.get(n,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(n,s);default:return this.onUnknownRpcMethodResponse(o)}}),Ne(this,"onPairingPingRequest",async(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(Os.ping,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),Ne(this,"onPairingPingResponse",(i,n)=>{const{id:s}=n;setTimeout(()=>{Gi(n)?this.events.emit(Oe("pairing_ping",s),{}):fi(n)&&this.events.emit(Oe("pairing_ping",s),{error:n.error})},500)}),Ne(this,"onPairingDeleteRequest",async(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Os.delete,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),Ne(this,"onUnknownRpcMethodRequest",async(i,n)=>{const{id:s,method:o}=n;try{if(this.registeredMethods.includes(o))return;const a=wt("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,i,a),this.logger.error(a)}catch(a){await this.sendError(s,i,a),this.logger.error(a)}}),Ne(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(wt("WC_METHOD_UNSUPPORTED",i))}),Ne(this,"isValidPair",(i,n)=>{var s;if(!Rr(i)){const{message:a}=ee("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(yn.malformed_pairing_uri),new Error(a)}if(!SE(i.uri)){const{message:a}=ee("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(yn.malformed_pairing_uri),new Error(a)}const o=Ev(i?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=ee("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(yn.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=ee("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(yn.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&X.toMiliseconds(o?.expiryTimestamp)<Date.now()){n.setError(yn.pairing_expired);const{message:a}=ee("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Ne(this,"isValidPing",async i=>{if(!Rr(i)){const{message:s}=ee("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),Ne(this,"isValidDisconnect",async i=>{if(!Rr(i)){const{message:s}=ee("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),Ne(this,"isValidPairingTopic",async i=>{if(!Ut(i,!1)){const{message:n}=ee("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=ee("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(Wn(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=ee("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}}),this.core=e,this.logger=Ir(r,this.name),this.pairings=new Rs(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Tr(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Qt.message,async e=>{const{topic:r,message:i,transportType:n}=e;if(!this.pairings.keys.includes(r)||n===St.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const s=await this.core.crypto.decode(r,i);try{Iu(s)?(this.core.history.set(r,s),this.onRelayEventRequest({topic:r,payload:s})):Rl(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id))}catch(o){this.logger.error(o)}})}registerExpirerEvents(){this.core.expirer.on(pi.expired,async e=>{const{topic:r}=Sg(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Os.expire,{topic:r}))})}}var QM=Object.defineProperty,eP=(t,e,r)=>e in t?QM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,dr=(t,e,r)=>eP(t,typeof e!="symbol"?e+"":e,r);class tP extends fS{constructor(e,r){super(e,r),this.core=e,this.logger=r,dr(this,"records",new Map),dr(this,"events",new nr.exports.EventEmitter),dr(this,"name",LI),dr(this,"version",BI),dr(this,"cached",[]),dr(this,"initialized",!1),dr(this,"storagePrefix",Ji),dr(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)}),dr(this,"set",(i,n,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:n,chainId:s}),this.records.has(n.id))return;const o={id:n.id,topic:i,request:{method:n.method,params:n.params||null},chainId:s,expiry:Wt(X.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Mi.created,o)}),dr(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 n=await this.getRecord(i.id);typeof n.response>"u"&&(n.response=fi(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(Mi.updated,n))}),dr(this,"get",async(i,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:n}),await this.getRecord(n))),dr(this,"delete",(i,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(s=>{if(s.topic===i){if(typeof n<"u"&&s.id!==n)return;this.records.delete(s.id),this.events.emit(Mi.deleted,s)}}),this.persist()}),dr(this,"exists",async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1)),dr(this,"on",(i,n)=>{this.events.on(i,n)}),dr(this,"once",(i,n)=>{this.events.once(i,n)}),dr(this,"off",(i,n)=>{this.events.off(i,n)}),dr(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=Ir(r,this.name)}get context(){return Tr(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(r=>{if(typeof r.response<"u")return;const i={topic:r.topic,request:Zn(r.request.method,r.request.params,r.id),chainId:r.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 r=this.records.get(e);if(!r){const{message:i}=ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Mi.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Mi.created,e=>{const r=Mi.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Mi.updated,e=>{const r=Mi.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Mi.deleted,e=>{const r=Mi.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(Io.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{X.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Mi.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}var rP=Object.defineProperty,iP=(t,e,r)=>e in t?rP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,br=(t,e,r)=>iP(t,typeof e!="symbol"?e+"":e,r);class nP extends mS{constructor(e,r){super(e,r),this.core=e,this.logger=r,br(this,"expirations",new Map),br(this,"events",new nr.exports.EventEmitter),br(this,"name",UI),br(this,"version",qI),br(this,"cached",[]),br(this,"initialized",!1),br(this,"storagePrefix",Ji),br(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)}),br(this,"has",i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}}),br(this,"set",(i,n)=>{this.isInitialized();const s=this.formatTarget(i),o={target:s,expiry:n};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(pi.created,{target:s,expiration:o})}),br(this,"get",i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)}),br(this,"del",i=>{if(this.isInitialized(),this.has(i)){const n=this.formatTarget(i),s=this.getExpiration(n);this.expirations.delete(n),this.events.emit(pi.deleted,{target:n,expiration:s})}}),br(this,"on",(i,n)=>{this.events.on(i,n)}),br(this,"once",(i,n)=>{this.events.once(i,n)}),br(this,"off",(i,n)=>{this.events.off(i,n)}),br(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=Ir(r,this.name)}get context(){return Tr(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 l_(e);if(typeof e=="number")return h_(e);const{message:r}=ee("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(pi.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:i}=ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;X.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(pi.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Io.pulse,()=>this.checkExpirations()),this.events.on(pi.created,e=>{const r=pi.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(pi.expired,e=>{const r=pi.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(pi.deleted,e=>{const r=pi.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}var sP=Object.defineProperty,oP=(t,e,r)=>e in t?sP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jt=(t,e,r)=>oP(t,typeof e!="symbol"?e+"":e,r);class aP extends bS{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,jt(this,"name",jI),jt(this,"abortController"),jt(this,"isDevEnv"),jt(this,"verifyUrlV3",zI),jt(this,"storagePrefix",Ji),jt(this,"version",fm),jt(this,"publicKey"),jt(this,"fetchPromise"),jt(this,"init",async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&X.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),jt(this,"register",async n=>{if(!Oa()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=n,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const l=va(),u=this.startAbortTimer(X.ONE_SECOND*5),m=await new Promise((x,S)=>{const E=()=>{window.removeEventListener("message",R),l.body.removeChild(A),S("attestation aborted")};this.abortController.signal.addEventListener("abort",E);const A=l.createElement("iframe");A.src=c,A.style.display="none",A.addEventListener("error",E,{signal:this.abortController.signal});const R=O=>{if(O.data&&typeof O.data=="string")try{const C=JSON.parse(O.data);if(C.type==="verify_attestation"){if(Pf(C.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(A),this.abortController.signal.removeEventListener("abort",E),window.removeEventListener("message",R),x(C.attestation===null?"":C.attestation)}}catch(C){this.logger.warn(C)}};l.body.appendChild(A),window.addEventListener("message",R,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",m),m}catch(l){this.logger.warn(l)}return""}),jt(this,"resolve",async n=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=n;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Pf(s).payload.id!==a)return;const l=await this.isValidJwtAttestation(s);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(n?.verifyUrl);return this.fetchAttestation(o,c)}),jt(this,"fetchAttestation",async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const o=this.startAbortTimer(X.ONE_SECOND*5),a=await fetch(`${s}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),jt(this,"getVerifyUrl",n=>{let s=n||Xa;return HI.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Xa}`),s=Xa),s}),jt(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(X.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(n),await s.json()}catch(n){this.logger.warn(n)}}),jt(this,"persistPublicKey",async n=>{this.logger.debug("persisting public key to local storage",n),await this.store.setItem(this.storeKey,n),this.publicKey=n}),jt(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),jt(this,"isValidJwtAttestation",async n=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(n,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(n,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),jt(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),jt(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const n=await this.fetchPromise;return this.fetchPromise=void 0,n}),jt(this,"validateAttestation",(n,s)=>{const o=uE(n,s.publicKey),a={hasExpired:X.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Ir(r,this.name),this.abortController=new AbortController,this.isDevEnv=Wf(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Tr(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),X.toMiliseconds(e))}}var cP=Object.defineProperty,lP=(t,e,r)=>e in t?cP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qm=(t,e,r)=>lP(t,typeof e!="symbol"?e+"":e,r);class hP extends yS{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,qm(this,"context",WI),qm(this,"registerDeviceToken",async i=>{const{clientId:n,token:s,notificationType:o,enableEncrypted:a=!1}=i,c=`${VI}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:o,token:s,always_raw:a})})}),this.logger=Ir(r,this.context)}}var fP=Object.defineProperty,jm=Object.getOwnPropertySymbols,uP=Object.prototype.hasOwnProperty,dP=Object.prototype.propertyIsEnumerable,Bu=(t,e,r)=>e in t?fP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rc=(t,e)=>{for(var r in e||(e={}))uP.call(e,r)&&Bu(t,r,e[r]);if(jm)for(var r of jm(e))dP.call(e,r)&&Bu(t,r,e[r]);return t},er=(t,e,r)=>Bu(t,typeof e!="symbol"?e+"":e,r);class pP extends wS{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,er(this,"context",GI),er(this,"storagePrefix",Ji),er(this,"storageVersion",KI),er(this,"events",new Map),er(this,"shouldPersist",!1),er(this,"init",async()=>{if(!Wf())try{const n={eventId:Ag(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:_g(this.core.relayer.protocol,this.core.relayer.version,Mu)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}}),er(this,"createEvent",n=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=n,l=Ag(),u=this.core.projectId||"",m=Date.now(),x=rc({eventId:l,timestamp:m,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,x),this.shouldPersist=!0),x}),er(this,"getEvent",n=>{const{eventId:s,topic:o}=n;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return rc(rc({},a),this.setMethods(a.eventId))}),er(this,"deleteEvent",n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0}),er(this,"setEventListeners",()=>{this.core.heartbeat.on(Io.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{X.fromMiliseconds(Date.now())-X.fromMiliseconds(n.timestamp)>JI&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})}),er(this,"setMethods",n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)})),er(this,"addTrace",(n,s)=>{const o=this.events.get(n);o&&(o.props.properties.trace.push(s),this.events.set(n,o),this.shouldPersist=!0)}),er(this,"setError",(n,s)=>{const o=this.events.get(n);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(n,o),this.shouldPersist=!0)}),er(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),er(this,"restore",async()=>{try{const n=await this.core.storage.getItem(this.storageKey)||[];if(!n.length)return;n.forEach(s=>{this.events.set(s.eventId,rc(rc({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}}),er(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[s,o]of this.events)o.props.type&&n.push(o);if(n.length!==0)try{if((await this.sendEvent(n)).ok)for(const s of n)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),er(this,"sendEvent",async n=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${ZI}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Mu}${s}`,{method:"POST",body:JSON.stringify(n)})}),er(this,"getAppDomain",()=>wg().url),this.logger=Ir(r,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var gP=Object.defineProperty,km=Object.getOwnPropertySymbols,vP=Object.prototype.hasOwnProperty,mP=Object.prototype.propertyIsEnumerable,Uu=(t,e,r)=>e in t?gP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zm=(t,e)=>{for(var r in e||(e={}))vP.call(e,r)&&Uu(t,r,e[r]);if(km)for(var r of km(e))mP.call(e,r)&&Uu(t,r,e[r]);return t},It=(t,e,r)=>Uu(t,typeof e!="symbol"?e+"":e,r);class qu extends aS{constructor(e){var r;super(e),It(this,"protocol",hm),It(this,"version",fm),It(this,"name",Nl),It(this,"relayUrl"),It(this,"projectId"),It(this,"customStoragePrefix"),It(this,"events",new nr.exports.EventEmitter),It(this,"logger"),It(this,"heartbeat"),It(this,"relayer"),It(this,"crypto"),It(this,"storage"),It(this,"history"),It(this,"expirer"),It(this,"pairing"),It(this,"verify"),It(this,"echoClient"),It(this,"linkModeSupportedApps"),It(this,"eventClient"),It(this,"initialized",!1),It(this,"logChunkController"),It(this,"on",(o,a)=>this.events.on(o,a)),It(this,"once",(o,a)=>this.events.once(o,a)),It(this,"off",(o,a)=>this.events.off(o,a)),It(this,"removeListener",(o,a)=>this.events.removeListener(o,a)),It(this,"dispatchEnvelope",({topic:o,message:a,sessionExists:c})=>{if(!o||!a)return;const l={topic:o,message:a,publishedAt:Date.now(),transportType:St.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:c})}),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||gm,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Ol({level:typeof e?.logger=="string"&&e.logger?e.logger:mI.logger,name:Nl}),{logger:n,chunkLoggerController:s}=nS({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=s,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var o,a;(o=this.logChunkController)!=null&&o.downloadLogsBlobInBrowser&&((a=this.logChunkController)==null||a.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Ir(n,this.name),this.heartbeat=new gu,this.crypto=new $M(this,this.logger,e?.keychain),this.history=new tP(this,this.logger),this.expirer=new nP(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new O$(zm(zm({},bI),e?.storageOptions)),this.relayer=new VM({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new XM(this,this.logger),this.verify=new aP(this,this.logger,this.storage),this.echoClient=new hP(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new pP(this,this.logger,e?.telemetryEnabled)}static async init(e){const r=new qu(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(CI,i),r}get context(){return Tr(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(vm,this.linkModeSupportedApps))}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.linkModeSupportedApps=await this.storage.getItem(vm)||[],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 bP=qu,Hm="wc",Wm=2,Vm="client",ju=`${Hm}@${Wm}:${Vm}:`,ku={name:Vm,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Km="WALLETCONNECT_DEEPLINK_CHOICE",yP="proposal",Gm="Proposal expired",wP="session",Oo=X.SEVEN_DAYS,_P="engine",tr={wc_sessionPropose:{req:{ttl:X.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:X.ONE_DAY,prompt:!1,tag:1104},res:{ttl:X.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:X.ONE_DAY,prompt:!1,tag:1106},res:{ttl:X.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:X.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:X.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:X.ONE_DAY,prompt:!1,tag:1112},res:{ttl:X.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:X.ONE_DAY,prompt:!1,tag:1114},res:{ttl:X.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:X.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:X.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1119}}},zu={min:X.FIVE_MINUTES,max:X.SEVEN_DAYS},Qi={idle:"IDLE",active:"ACTIVE"},Jm={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},xP="request",EP=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],$P="wc",SP="auth",IP="authKeys",AP="pairingTopics",MP="requests",Ll=`${$P}@${1.5}:${SP}:`,Bl=`${Ll}:PUB_KEY`;var PP=Object.defineProperty,OP=Object.defineProperties,CP=Object.getOwnPropertyDescriptors,Zm=Object.getOwnPropertySymbols,DP=Object.prototype.hasOwnProperty,RP=Object.prototype.propertyIsEnumerable,Hu=(t,e,r)=>e in t?PP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,At=(t,e)=>{for(var r in e||(e={}))DP.call(e,r)&&Hu(t,r,e[r]);if(Zm)for(var r of Zm(e))RP.call(e,r)&&Hu(t,r,e[r]);return t},Lr=(t,e)=>OP(t,CP(e)),Z=(t,e,r)=>Hu(t,typeof e!="symbol"?e+"":e,r);class NP extends $S{constructor(e){super(e),Z(this,"name",_P),Z(this,"events",new nr.exports),Z(this,"initialized",!1),Z(this,"requestQueue",{state:Qi.idle,queue:[]}),Z(this,"sessionRequestQueue",{state:Qi.idle,queue:[]}),Z(this,"requestQueueDelay",X.ONE_SECOND),Z(this,"expectedPairingMethodMap",new Map),Z(this,"recentlyDeletedMap",new Map),Z(this,"recentlyDeletedLimit",200),Z(this,"relayMessageCache",[]),Z(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(tr)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},X.toMiliseconds(this.requestQueueDelay)))}),Z(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Lr(At({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:n,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,relays:c}=i;let l=n,u,m=!1;try{if(l){const T=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),m=T.active}}catch(T){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),T}if(!l||!m){const{topic:T,uri:U}=await this.client.core.pairing.create();l=T,u=U}if(!l){const{message:T}=ee("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(T)}const x=await this.client.core.crypto.generateKeyPair(),S=tr.wc_sessionPropose.req.ttl||X.FIVE_MINUTES,E=Wt(S),A=At({requiredNamespaces:s,optionalNamespaces:o,relays:c??[{protocol:pm}],proposer:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:E,pairingTopic:l},a&&{sessionProperties:a}),{reject:R,resolve:O,done:C}=$s(S,Gm);this.events.once(Oe("session_connect"),async({error:T,session:U})=>{if(T)R(T);else if(U){U.self.publicKey=x;const z=Lr(At({},U),{pairingTopic:A.pairingTopic,requiredNamespaces:A.requiredNamespaces,optionalNamespaces:A.optionalNamespaces,transportType:St.relay});await this.client.session.set(U.topic,z),await this.setExpiry(U.topic,U.expiry),l&&await this.client.core.pairing.updateMetadata({topic:l,metadata:U.peer.metadata}),this.cleanupDuplicatePairings(z),O(z)}});const N=await this.sendRequest({topic:l,method:"wc_sessionPropose",params:A,throwOnFailedPublish:!0});return await this.setProposal(N,At({id:N},A)),{uri:u,approval:C}}),Z(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(i){throw this.client.logger.error("pair() failed"),i}}),Z(this,"approve",async r=>{var i,n,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=r?.id)==null?void 0:i.toString(),trace:[Pi.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(V){throw o.setError(Cs.no_internet_connection),V}try{await this.isValidProposalId(r?.id)}catch(V){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(Cs.proposal_not_found),V}try{await this.isValidApprove(r)}catch(V){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Cs.session_approve_namespace_validation_failure),V}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,sessionConfig:m}=r,x=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:S,proposer:E,requiredNamespaces:A,optionalNamespaces:R}=x;let O=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:S});O||(O=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Pi.session_approve_started,properties:{topic:S,trace:[Pi.session_approve_started,Pi.session_namespaces_validation_success]}}));const C=await this.client.core.crypto.generateKeyPair(),N=E.publicKey,T=await this.client.core.crypto.generateSharedKey(C,N),U=At(At({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:C,metadata:this.client.metadata},expiry:Wt(Oo)},u&&{sessionProperties:u}),m&&{sessionConfig:m}),z=St.relay;O.addTrace(Pi.subscribing_session_topic);try{await this.client.core.relayer.subscribe(T,{transportType:z})}catch(V){throw O.setError(Cs.subscribe_session_topic_failure),V}O.addTrace(Pi.subscribe_session_topic_success);const W=Lr(At({},U),{topic:T,requiredNamespaces:A,optionalNamespaces:R,pairingTopic:S,acknowledged:!1,self:U.controller,peer:{publicKey:E.publicKey,metadata:E.metadata},controller:C,transportType:St.relay});await this.client.session.set(T,W),O.addTrace(Pi.store_session);try{O.addTrace(Pi.publishing_session_settle),await this.sendRequest({topic:T,method:"wc_sessionSettle",params:U,throwOnFailedPublish:!0}).catch(V=>{throw O?.setError(Cs.session_settle_publish_failure),V}),O.addTrace(Pi.session_settle_publish_success),O.addTrace(Pi.publishing_session_approve),await this.sendResult({id:a,topic:S,result:{relay:{protocol:c??"irn"},responderPublicKey:C},throwOnFailedPublish:!0}).catch(V=>{throw O?.setError(Cs.session_approve_publish_failure),V}),O.addTrace(Pi.session_approve_publish_success)}catch(V){throw this.client.logger.error(V),this.client.session.delete(T,wt("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(T),V}return this.client.core.eventClient.deleteEvent({eventId:O.eventId}),await this.client.core.pairing.updateMetadata({topic:S,metadata:E.metadata}),await this.client.proposal.delete(a,wt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:S}),await this.setExpiry(T,Wt(Oo)),{topic:T,acknowledged:()=>Promise.resolve(this.client.session.get(T))}}),Z(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:n}=r;let s;try{s=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}s&&(await this.sendError({id:i,topic:s,error:n,rpcOpts:tr.wc_sessionPropose.reject}),await this.client.proposal.delete(i,wt("USER_DISCONNECTED")))}),Z(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(m){throw this.client.logger.error("update() -> isValidUpdate() failed"),m}const{topic:i,namespaces:n}=r,{done:s,resolve:o,reject:a}=$s(),c=bn(),l=Ps().toString(),u=this.client.session.get(i).namespaces;return this.events.once(Oe("session_update",c),({error:m})=>{m?a(m):o()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(m=>{this.client.logger.error(m),this.client.session.update(i,{namespaces:u}),a(m)}),{acknowledged:s}}),Z(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=r,n=bn(),{done:s,resolve:o,reject:a}=$s();return this.events.once(Oe("session_extend",n),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,Wt(Oo)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),Z(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(O){throw this.client.logger.error("request() -> isValidRequest() failed"),O}const{chainId:i,request:n,topic:s,expiry:o=tr.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===St.relay&&await this.confirmOnlineStateOrThrow();const c=bn(),l=Ps().toString(),{done:u,resolve:m,reject:x}=$s(o,"Request expired. Please try again.");this.events.once(Oe("session_request",c),({error:O,result:C})=>{O?x(O):m(C)});const S="wc_sessionRequest",E=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(E)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:S,params:{request:Lr(At({},n),{expiryTimestamp:Wt(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:E}).catch(O=>x(O)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),await u();const A={request:Lr(At({},n),{expiryTimestamp:Wt(o)}),chainId:i},R=this.shouldSetTVF(S,A);return await Promise.all([new Promise(async O=>{await this.sendRequest(At({clientRpcId:c,relayRpcId:l,topic:s,method:S,params:A,expiry:o,throwOnFailedPublish:!0},R&&{tvf:this.getTVFParams(c,A)})).catch(C=>x(C)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),O()}),new Promise(async O=>{var C;if(!((C=a.sessionConfig)!=null&&C.disableDeepLink)){const N=await p_(this.client.core.storage,Km);await f_({id:c,topic:s,wcDeepLink:N})}O()}),u()]).then(O=>O[2])}),Z(this,"respond",async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:i,response:n}=r,{id:s}=n,o=this.client.session.get(i);o.transportType===St.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);Gi(n)?await this.sendResult({id:s,topic:i,result:n.result,throwOnFailedPublish:!0,appLink:a}):fi(n)&&await this.sendError({id:s,topic:i,error:n.error,appLink:a}),this.cleanupAfterResponse(r)}),Z(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:i}=r;if(this.client.session.keys.includes(i)){const n=bn(),s=Ps().toString(),{done:o,resolve:a,reject:c}=$s();this.events.once(Oe("session_ping",n),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),Z(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,o=Ps().toString(),a=bn();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),Z(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:i}=r;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:wt("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=ee("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}}),Z(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>EE(i,r)))),Z(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),Z(this,"authenticate",async(r,i)=>{var n;this.isInitialized(),this.isValidAuthenticate(r);const s=i&&this.client.core.linkModeSupportedApps.includes(i)&&((n=this.client.metadata.redirect)==null?void 0:n.linkMode),o=s?St.link_mode:St.relay;o===St.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:m,type:x,exp:S,nbf:E,methods:A=[],expiry:R}=r,O=[...r.resources||[]],{topic:C,uri:N}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:C,uri:N}});const T=await this.client.core.crypto.generateKeyPair(),U=bl(T);if(await Promise.all([this.client.auth.authKeys.set(Bl,{responseTopic:U,publicKey:T}),this.client.auth.pairingTopics.set(U,{topic:U,pairingTopic:C})]),await this.client.core.relayer.subscribe(U,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${C}`),A.length>0){const{namespace:$}=bo(a[0]);let y=ix($,"request",A);pl(O)&&(y=sx(y,O.pop())),O.push(y)}const z=R&&R>tr.wc_sessionAuthenticate.req.ttl?R:tr.wc_sessionAuthenticate.req.ttl,W={authPayload:{type:x??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:m,iat:new Date().toISOString(),exp:S,nbf:E,resources:O},requester:{publicKey:T,metadata:this.client.metadata},expiryTimestamp:Wt(z)},V={eip155:{chains:a,methods:[...new Set(["personal_sign",...A])],events:["chainChanged","accountsChanged"]}},B={requiredNamespaces:{},optionalNamespaces:V,relays:[{protocol:"irn"}],pairingTopic:C,proposer:{publicKey:T,metadata:this.client.metadata},expiryTimestamp:Wt(tr.wc_sessionPropose.req.ttl)},{done:K,resolve:M,reject:v}=$s(z,"Request expired"),g=async({error:$,session:y})=>{if(this.events.off(Oe("session_request",f),h),$)v($);else if(y){y.self.publicKey=T,await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),C&&await this.client.core.pairing.updateMetadata({topic:C,metadata:y.peer.metadata});const d=this.client.session.get(y.topic);await this.deleteProposal(p),M({session:d})}},h=async $=>{var y,d,w;if(await this.deletePendingAuthRequest(f,{message:"fulfilled",code:0}),$.error){const k=wt("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return $.error.code===k.code?void 0:(this.events.off(Oe("session_connect"),g),v($.error.message))}await this.deleteProposal(p),this.events.off(Oe("session_connect"),g);const{cacaos:b,responder:P}=$.result,q=[],I=[];for(const k of b){await kg({cacao:k,projectId:this.client.core.projectId})||(this.client.logger.error(k,"Signature verification failed"),v(wt("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:H}=k,Y=pl(H.resources),Q=[Yf(H.iss)],J=dl(H.iss);if(Y){const ae=Wg(Y),re=Vg(Y);q.push(...ae),Q.push(...re)}for(const ae of Q)I.push(`${ae}:${J}`)}const F=await this.client.core.crypto.generateSharedKey(T,P.publicKey);let j;q.length>0&&(j={topic:F,acknowledged:!0,self:{publicKey:T,metadata:this.client.metadata},peer:P,controller:P.publicKey,expiry:Wt(Oo),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:C,namespaces:Sv([...new Set(q)],[...new Set(I)]),transportType:o},await this.client.core.relayer.subscribe(F,{transportType:o}),await this.client.session.set(F,j),C&&await this.client.core.pairing.updateMetadata({topic:C,metadata:P.metadata}),j=this.client.session.get(F)),(y=this.client.metadata.redirect)!=null&&y.linkMode&&(d=P.metadata.redirect)!=null&&d.linkMode&&(w=P.metadata.redirect)!=null&&w.universal&&i&&(this.client.core.addLinkModeSupportedApp(P.metadata.redirect.universal),this.client.session.update(F,{transportType:St.link_mode})),M({auths:b,session:j})},f=bn(),p=bn();this.events.once(Oe("session_connect"),g),this.events.once(Oe("session_request",f),h);let _;try{if(s){const $=Zn("wc_sessionAuthenticate",W,f);this.client.core.history.set(C,$);const y=await this.client.core.crypto.encode("",$,{type:Ba,encoding:Fa});_=wl(i,C,y)}else await Promise.all([this.sendRequest({topic:C,method:"wc_sessionAuthenticate",params:W,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:f}),this.sendRequest({topic:C,method:"wc_sessionPropose",params:B,expiry:tr.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:p})])}catch($){throw this.events.off(Oe("session_connect"),g),this.events.off(Oe("session_request",f),h),$}return await this.setProposal(p,At({id:p},B)),await this.setAuthRequest(f,{request:Lr(At({},W),{verifyContext:{}}),pairingTopic:C,transportType:o}),{uri:_??N,response:K}}),Z(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Ds.authenticated_session_approve_started]}});try{this.isInitialized()}catch(R){throw s.setError(Qa.no_internet_connection),R}const o=this.getPendingAuthRequest(i);if(!o)throw s.setError(Qa.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||St.relay;a===St.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=bl(c),m={type:pn,receiverPublicKey:c,senderPublicKey:l},x=[],S=[];for(const R of n){if(!await kg({cacao:R,projectId:this.client.core.projectId})){s.setError(Qa.invalid_cacao);const U=wt("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:u,error:U,encodeOpts:m}),new Error(U.message)}s.addTrace(Ds.cacaos_verified);const{p:O}=R,C=pl(O.resources),N=[Yf(O.iss)],T=dl(O.iss);if(C){const U=Wg(C),z=Vg(C);x.push(...U),N.push(...z)}for(const U of N)S.push(`${U}:${T}`)}const E=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Ds.create_authenticated_session_topic);let A;if(x?.length>0){A={topic:E,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Wt(Oo),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Sv([...new Set(x)],[...new Set(S)]),transportType:a},s.addTrace(Ds.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(E,{transportType:a})}catch(R){throw s.setError(Qa.subscribe_authenticated_session_topic_failure),R}s.addTrace(Ds.subscribe_authenticated_session_topic_success),await this.client.session.set(E,A),s.addTrace(Ds.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Ds.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:i,result:{cacaos:n,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:m,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(R){throw s.setError(Qa.authenticated_session_approve_publish_failure),R}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:A}}),Z(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:i,reason:n}=r,s=this.getPendingAuthRequest(i);if(!s)throw new Error(`Could not find pending auth request with id ${i}`);s.transportType===St.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=bl(o),l={type:pn,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:n,encodeOpts:l,rpcOpts:tr.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,wt("USER_DISCONNECTED"))}),Z(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:n}=r;return zg(i,n)}),Z(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),Z(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.pairingTopic),n=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==i.topic});if(n.length===0)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),Z(this,"deleteSession",async r=>{var i;const{topic:n,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,wt("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),s||this.client.core.expirer.del(n),this.client.core.storage.removeItem(Km).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===n&&this.deletePendingSessionRequest(l.id,wt("USER_DISCONNECTED"))}),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=Qi.idle),o&&this.client.events.emit("session_delete",{id:a,topic:n})}),Z(this,"deleteProposal",async(r,i)=>{if(i)try{const n=this.client.proposal.get(r),s=this.client.core.eventClient.getEvent({topic:n.pairingTopic});s?.setError(Cs.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,wt("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),Z(this,"deletePendingSessionRequest",async(r,i,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),n&&(this.sessionRequestQueue.state=Qi.idle,this.client.events.emit("session_request_expire",{id:r}))}),Z(this,"deletePendingAuthRequest",async(r,i,n=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)])}),Z(this,"setExpiry",async(r,i)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,i),await this.client.session.update(r,{expiry:i}))}),Z(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,Wt(tr.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),Z(this,"setAuthRequest",async(r,i)=>{const{request:n,pairingTopic:s,transportType:o=St.relay}=i;this.client.core.expirer.set(r,n.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:r,pairingTopic:s,verifyContext:n.verifyContext,transportType:o})}),Z(this,"setPendingSessionRequest",async r=>{const{id:i,topic:n,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||Wt(tr.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:n,params:s,verifyContext:o})}),Z(this,"sendRequest",async r=>{const{topic:i,method:n,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:m}=r,x=Zn(n,s,c);let S;const E=!!u;try{const O=E?Fa:Jn;S=await this.client.core.crypto.encode(i,x,{encoding:O})}catch(O){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),O}let A;if(EP.includes(n)){const O=gn(JSON.stringify(x)),C=gn(S);A=await this.client.core.verify.register({id:C,decryptedId:O})}const R=tr[n].req;if(R.attestation=A,o&&(R.ttl=o),a&&(R.id=a),this.client.core.history.set(i,x),E){const O=wl(u,i,S);await global.Linking.openURL(O,this.client.name)}else{const O=tr[n].req;o&&(O.ttl=o),a&&(O.id=a),O.tvf=Lr(At({},m),{correlationId:x.id}),l?(O.internal=Lr(At({},O.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,S,O)):this.client.core.relayer.publish(i,S,O).catch(C=>this.client.logger.error(C))}return x.id}),Z(this,"sendResult",async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,l=Cl(i,s);let u;const m=c&&typeof(global==null?void 0:global.Linking)<"u";try{const E=m?Fa:Jn;u=await this.client.core.crypto.encode(n,l,Lr(At({},a||{}),{encoding:E}))}catch(E){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),E}let x,S;try{x=await this.client.core.history.get(n,i);const E=x.request;try{this.shouldSetTVF(E.method,E.params)&&(S=this.getTVFParams(i,E.params,s))}catch(A){this.client.logger.warn("sendResult() -> getTVFParams() failed",A)}}catch(E){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),E}if(m){const E=wl(c,n,u);await global.Linking.openURL(E,this.client.name)}else{const E=tr[x.request.method].res;E.tvf=Lr(At({},S),{correlationId:i}),o?(E.internal=Lr(At({},E.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,u,E)):this.client.core.relayer.publish(n,u,E).catch(A=>this.client.logger.error(A))}await this.client.core.history.resolve(l)}),Z(this,"sendError",async r=>{const{id:i,topic:n,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,l=Dl(i,s);let u;const m=c&&typeof(global==null?void 0:global.Linking)<"u";try{const S=m?Fa:Jn;u=await this.client.core.crypto.encode(n,l,Lr(At({},o||{}),{encoding:S}))}catch(S){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),S}let x;try{x=await this.client.core.history.get(n,i)}catch(S){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),S}if(m){const S=wl(c,n,u);await global.Linking.openURL(S,this.client.name)}else{const S=a||tr[x.request.method].res;this.client.core.relayer.publish(n,u,S)}await this.client.core.history.resolve(l)}),Z(this,"cleanup",async()=>{const r=[],i=[];this.client.session.getAll().forEach(n=>{let s=!1;Wn(n.expiry)&&(s=!0),this.client.core.crypto.keychain.has(n.topic)||(s=!0),s&&r.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{Wn(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...r.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])}),Z(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),Z(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Qi.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=Qi.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=Qi.idle}),Z(this,"processRequest",async r=>{const{topic:i,payload:n,attestation:s,transportType:o,encryptedId:a}=r,c=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),Z(this,"onRelayEventResponse",async r=>{const{topic:i,payload:n,transportType:s}=r,o=(await this.client.core.history.get(i,n.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n,s);case"wc_sessionSettle":return this.onSessionSettleResponse(i,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,n);case"wc_sessionExtend":return this.onSessionExtendResponse(i,n);case"wc_sessionPing":return this.onSessionPingResponse(i,n);case"wc_sessionRequest":return this.onSessionRequestResponse(i,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,n);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),Z(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:n}=ee("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)}),Z(this,"shouldIgnorePairingRequest",r=>{const{topic:i,requestMethod:n}=r,s=this.expectedPairingMethodMap.get(i);return!s||s.includes(n)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),Z(this,"onSessionProposeRequest",async r=>{const{topic:i,payload:n,attestation:s,encryptedId:o}=r,{params:a,id:c}=n;try{const l=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(yn.proposal_listener_not_found)),this.isValidConnect(At({},n.params));const u=a.expiryTimestamp||Wt(tr.wc_sessionPropose.req.ttl),m=At({id:c,pairingTopic:i,expiryTimestamp:u},a);await this.setProposal(c,m);const x=await this.getVerifyContext({attestationId:s,hash:gn(JSON.stringify(n)),encryptedId:o,metadata:m.proposer.metadata});l?.addTrace(Zi.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:m,verifyContext:x})}catch(l){await this.sendError({id:c,topic:i,error:l,rpcOpts:tr.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),Z(this,"onSessionProposeResponse",async(r,i,n)=>{const{id:s}=i;if(Gi(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:u});const m=await this.client.core.relayer.subscribe(u,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:m}),await this.client.core.pairing.activate({topic:r})}else if(fi(i)){await this.client.proposal.delete(s,wt("USER_DISCONNECTED"));const o=Oe("session_connect");if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(Oe("session_connect"),{error:i.error})}}),Z(this,"onSessionSettleRequest",async(r,i)=>{const{id:n,params:s}=i;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,sessionConfig:m}=i.params,x=Lr(At(At({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:"",requiredNamespaces:{},optionalNamespaces:{},controller:a.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),m&&{sessionConfig:m}),{transportType:St.relay}),S=Oe("session_connect");if(this.events.listenerCount(S)===0)throw new Error(`emitting ${S} without any listeners 997`);this.events.emit(Oe("session_connect"),{session:x}),await this.sendResult({id:i.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),Z(this,"onSessionSettleResponse",async(r,i)=>{const{id:n}=i;Gi(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(Oe("session_approve",n),{})):fi(i)&&(await this.client.session.delete(r,wt("USER_DISCONNECTED")),this.events.emit(Oe("session_approve",n),{error:i.error}))}),Z(this,"onSessionUpdateRequest",async(r,i)=>{const{params:n,id:s}=i;try{const o=`${r}_session_update`,a=Ha.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:wt("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(At({topic:r},n));try{Ha.set(o,s),await this.client.session.update(r,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(c){throw Ha.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:n})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),Z(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),Z(this,"onSessionUpdateResponse",(r,i)=>{const{id:n}=i,s=Oe("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Gi(i)?this.events.emit(Oe("session_update",n),{}):fi(i)&&this.events.emit(Oe("session_update",n),{error:i.error})}),Z(this,"onSessionExtendRequest",async(r,i)=>{const{id:n}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,Wt(Oo)),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),Z(this,"onSessionExtendResponse",(r,i)=>{const{id:n}=i,s=Oe("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Gi(i)?this.events.emit(Oe("session_extend",n),{}):fi(i)&&this.events.emit(Oe("session_extend",n),{error:i.error})}),Z(this,"onSessionPingRequest",async(r,i)=>{const{id:n}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),Z(this,"onSessionPingResponse",(r,i)=>{const{id:n}=i,s=Oe("session_ping",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);setTimeout(()=>{Gi(i)?this.events.emit(Oe("session_ping",n),{}):fi(i)&&this.events.emit(Oe("session_ping",n),{error:i.error})},500)}),Z(this,"onSessionDeleteRequest",async(r,i)=>{const{id:n}=i;try{this.isValidDisconnect({topic:r,reason:i.params}),Promise.all([new Promise(s=>{this.client.core.relayer.once(Qt.publish,async()=>{s(await this.deleteSession({topic:r,id:n}))})}),this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:wt("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),Z(this,"onSessionRequest",async r=>{var i,n,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=r,{id:m,params:x}=a;try{await this.isValidRequest(At({topic:o},x));const S=this.client.session.get(o),E=await this.getVerifyContext({attestationId:c,hash:gn(JSON.stringify(Zn("wc_sessionRequest",x,m))),encryptedId:l,metadata:S.peer.metadata,transportType:u}),A={id:m,topic:o,params:x,verifyContext:E};await this.setPendingSessionRequest(A),u===St.link_mode&&(i=S.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((n=S.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(A):(this.addSessionRequestToSessionRequestQueue(A),this.processSessionRequestQueue())}catch(S){await this.sendError({id:m,topic:o,error:S}),this.client.logger.error(S)}}),Z(this,"onSessionRequestResponse",(r,i)=>{const{id:n}=i,s=Oe("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Gi(i)?this.events.emit(Oe("session_request",n),{result:i.result}):fi(i)&&this.events.emit(Oe("session_request",n),{error:i.error})}),Z(this,"onSessionEventRequest",async(r,i)=>{const{id:n,params:s}=i;try{const o=`${r}_session_event_${s.event.name}`,a=Ha.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(At({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),Ha.set(o,n)}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),Z(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),Gi(i)?this.events.emit(Oe("session_request",n),{result:i.result}):fi(i)&&this.events.emit(Oe("session_request",n),{error:i.error})}),Z(this,"onSessionAuthenticateRequest",async r=>{var i;const{topic:n,payload:s,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:l,authPayload:u,expiryTimestamp:m}=s.params,x=await this.getVerifyContext({attestationId:o,hash:gn(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),S={requester:l,pairingTopic:n,id:s.id,authPayload:u,verifyContext:x,expiryTimestamp:m};await this.setAuthRequest(s.id,{request:S,pairingTopic:n,transportType:c}),c===St.link_mode&&(i=l.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:s.params,id:s.id,verifyContext:x})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,m=await this.client.core.crypto.generateKeyPair(),x=this.getAppLinkIfEnabled(s.params.requester.metadata,c),S={type:pn,receiverPublicKey:u,senderPublicKey:m};await this.sendError({id:s.id,topic:n,error:l,encodeOpts:S,rpcOpts:tr.wc_sessionAuthenticate.autoReject,appLink:x})}}),Z(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),Z(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Qi.idle,this.processSessionRequestQueue()},X.toMiliseconds(this.requestQueueDelay))}),Z(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:i})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{const o=s.request.id,a=Oe("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Oe("session_request",s.request.id),{error:i})})}),Z(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Qi.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Qi.active,this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}}),Z(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),Z(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(n=>n.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:Zn("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})}),Z(this,"isValidConnect",async r=>{if(!Rr(r)){const{message:c}=ee("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(c)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:o,relays:a}=r;if(Sr(i)||await this.isValidPairingTopic(i),!TE(a,!0)){const{message:c}=ee("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(c)}!Sr(n)&&za(n)!==0&&this.validateNamespaces(n,"requiredNamespaces"),!Sr(s)&&za(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),Sr(o)||this.validateSessionProps(o,"sessionProperties")}),Z(this,"validateNamespaces",(r,i)=>{const n=NE(r,"connect()",i);if(n)throw new Error(n.message)}),Z(this,"isValidApprove",async r=>{if(!Rr(r))throw new Error(ee("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:n,relayProtocol:s,sessionProperties:o}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const a=this.client.proposal.get(i),c=du(n,"approve()");if(c)throw new Error(c.message);const l=Ov(a.requiredNamespaces,n,"approve()");if(l)throw new Error(l.message);if(!Ut(s,!0)){const{message:u}=ee("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(u)}Sr(o)||this.validateSessionProps(o,"sessionProperties")}),Z(this,"isValidReject",async r=>{if(!Rr(r)){const{message:s}=ee("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:i,reason:n}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!LE(n)){const{message:s}=ee("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}}),Z(this,"isValidSessionSettleRequest",r=>{if(!Rr(r)){const{message:l}=ee("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:i,controller:n,namespaces:s,expiry:o}=r;if(!Mv(i)){const{message:l}=ee("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=ME(n,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=du(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Wn(o)){const{message:l}=ee("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),Z(this,"isValidUpdate",async r=>{if(!Rr(r)){const{message:c}=ee("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:i,namespaces:n}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),o=du(n,"update()");if(o)throw new Error(o.message);const a=Ov(s.requiredNamespaces,n,"update()");if(a)throw new Error(a.message)}),Z(this,"isValidExtend",async r=>{if(!Rr(r)){const{message:n}=ee("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(n)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),Z(this,"isValidRequest",async r=>{if(!Rr(r)){const{message:c}=ee("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:i,request:n,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!Pv(a,s)){const{message:c}=ee("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!BE(n)){const{message:c}=ee("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(c)}if(!jE(a,s,n.method)){const{message:c}=ee("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(c)}if(o&&!WE(o,zu)){const{message:c}=ee("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${zu.min} and ${zu.max}`);throw new Error(c)}}),Z(this,"isValidRespond",async r=>{var i;if(!Rr(r)){const{message:o}=ee("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:n,response:s}=r;try{await this.isValidSessionTopic(n)}catch(o){throw(i=r?.response)!=null&&i.id&&this.cleanupAfterResponse(r),o}if(!UE(s)){const{message:o}=ee("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),Z(this,"isValidPing",async r=>{if(!Rr(r)){const{message:n}=ee("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),Z(this,"isValidEmit",async r=>{if(!Rr(r)){const{message:a}=ee("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:i,event:n,chainId:s}=r;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!Pv(o,s)){const{message:a}=ee("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!qE(n)){const{message:a}=ee("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}if(!kE(o,s,n.name)){const{message:a}=ee("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}}),Z(this,"isValidDisconnect",async r=>{if(!Rr(r)){const{message:n}=ee("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),Z(this,"isValidAuthenticate",r=>{const{chains:i,uri:n,domain:s,nonce:o}=r;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!Ut(n,!1))throw new Error("uri is required parameter");if(!Ut(s,!1))throw new Error("domain is required parameter");if(!Ut(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>bo(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=bo(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),Z(this,"getVerifyContext",async r=>{const{attestationId:i,hash:n,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||Xa,validation:"UNKNOWN",origin:o.url||""}};try{if(a===St.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:i,hash:n,encryptedId:s,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),Z(this,"validateSessionProps",(r,i)=>{Object.values(r).forEach(n=>{if(!Ut(n,!1)){const{message:s}=ee("MISSING_OR_INVALID",`${i} must be in Record<string, string> format. Received: ${JSON.stringify(n)}`);throw new Error(s)}})}),Z(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),Z(this,"addToRecentlyDeleted",(r,i)=>{if(this.recentlyDeletedMap.set(r,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let n=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(n++>=s)break;this.recentlyDeletedMap.delete(o)}}}),Z(this,"checkRecentlyDeleted",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:n}=ee("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(n)}}),Z(this,"isLinkModeEnabled",(r,i)=>{var n,s,o,a,c,l,u,m,x;return!r||i!==St.link_mode?!1:((s=(n=this.client.metadata)==null?void 0:n.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=r?.redirect)==null?void 0:u.universal)!==void 0&&((m=r?.redirect)==null?void 0:m.universal)!==""&&((x=r?.redirect)==null?void 0:x.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),Z(this,"getAppLinkIfEnabled",(r,i)=>{var n;return this.isLinkModeEnabled(r,i)?(n=r?.redirect)==null?void 0:n.universal:void 0}),Z(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Ig(r,"topic")||"",n=decodeURIComponent(Ig(r,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:St.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})}),Z(this,"registerLinkModeListeners",async()=>{var r;if(Wf()||zn()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const i=global==null?void 0:global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await i.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}),Z(this,"shouldSetTVF",(r,i)=>{if(!i||r!=="wc_sessionRequest")return!1;const{request:n}=i;return Object.keys(Jm).includes(n.method)}),Z(this,"getTVFParams",(r,i,n)=>{var s,o;try{const a=i.request.method,c=this.extractTxHashesFromResult(a,n);return Lr(At({correlationId:r,rpcMethods:[a],chainId:i.chainId},this.isValidContractData(i.request.params)&&{contractAddresses:[(o=(s=i.request.params)==null?void 0:s[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),Z(this,"isValidContractData",r=>{var i;if(!r)return!1;try{const n=r?.data||((i=r?.[0])==null?void 0:i.data);if(!n.startsWith("0x"))return!1;const s=n.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),Z(this,"extractTxHashesFromResult",(r,i)=>{try{const n=Jm[r];if(typeof i=="string")return[i];const s=i[n.key];if(Wi(s))return s;if(typeof s=="string")return[s]}catch(n){this.client.logger.warn("Error extracting tx hashes from result",n)}return[]})}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Qt.message,e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):this.onRelayMessage(e)})}async onRelayMessage(e){const{topic:r,message:i,attestation:n,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Bl)?this.client.auth.authKeys.get(Bl):{responseTopic:void 0,publicKey:void 0},a=await this.client.core.crypto.decode(r,i,{receiverPublicKey:o,encoding:s===St.link_mode?Fa:Jn});try{Iu(a)?(this.client.core.history.set(r,a),this.onRelayEventRequest({topic:r,payload:a,attestation:n,transportType:s,encryptedId:gn(i)})):Rl(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s})}catch(c){this.client.logger.error(c)}}registerExpirerEvents(){this.client.core.expirer.on(pi.expired,async e=>{const{topic:r,id:i}=Sg(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,ee("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,ee("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(Os.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Os.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Ut(e,!1)){const{message:r}=ee("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=ee("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(Wn(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=ee("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!Ut(e,!1)){const{message:r}=ee("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=ee("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(Wn(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=ee("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=ee("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),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(Ut(e,!1)){const{message:r}=ee("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=ee("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!FE(e)){const{message:r}=ee("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=ee("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(Wn(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=ee("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class TP extends Rs{constructor(e,r){super(e,r,yP,ju),this.core=e,this.logger=r}}class FP extends Rs{constructor(e,r){super(e,r,wP,ju),this.core=e,this.logger=r}}class LP extends Rs{constructor(e,r){super(e,r,xP,ju,i=>i.id),this.core=e,this.logger=r}}class BP extends Rs{constructor(e,r){super(e,r,IP,Ll,()=>Bl),this.core=e,this.logger=r}}class UP extends Rs{constructor(e,r){super(e,r,AP,Ll),this.core=e,this.logger=r}}class qP extends Rs{constructor(e,r){super(e,r,MP,Ll,i=>i.id),this.core=e,this.logger=r}}var jP=Object.defineProperty,kP=(t,e,r)=>e in t?jP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wu=(t,e,r)=>kP(t,typeof e!="symbol"?e+"":e,r);class zP{constructor(e,r){this.core=e,this.logger=r,Wu(this,"authKeys"),Wu(this,"pairingTopics"),Wu(this,"requests"),this.authKeys=new BP(this.core,this.logger),this.pairingTopics=new UP(this.core,this.logger),this.requests=new qP(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var HP=Object.defineProperty,WP=(t,e,r)=>e in t?HP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Te=(t,e,r)=>WP(t,typeof e!="symbol"?e+"":e,r);class Vu extends ES{constructor(e){super(e),Te(this,"protocol",Hm),Te(this,"version",Wm),Te(this,"name",ku.name),Te(this,"metadata"),Te(this,"core"),Te(this,"logger"),Te(this,"events",new nr.exports.EventEmitter),Te(this,"engine"),Te(this,"session"),Te(this,"proposal"),Te(this,"pendingRequest"),Te(this,"auth"),Te(this,"signConfig"),Te(this,"on",(i,n)=>this.events.on(i,n)),Te(this,"once",(i,n)=>this.events.once(i,n)),Te(this,"off",(i,n)=>this.events.off(i,n)),Te(this,"removeListener",(i,n)=>this.events.removeListener(i,n)),Te(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),Te(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"update",async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"request",async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"find",i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),Te(this,"authenticate",async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}}),Te(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),this.name=e?.name||ku.name,this.metadata=e?.metadata||wg(),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Vi(Ol({level:e?.logger||ku.logger}));this.core=e?.core||new bP(e),this.logger=Ir(r,this.name),this.session=new FP(this.core,this.logger),this.proposal=new TP(this.core,this.logger),this.pendingRequest=new LP(this.core,this.logger),this.engine=new NP(this),this.auth=new zP(this.core,this.logger)}static async init(e){const r=new Vu(e);return await r.initialize(),r}get context(){return Tr(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.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},X.toMiliseconds(X.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var Ku={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof Ft<"u"&&Ft,i=function(){function s(){this.fetch=!1,this.DOMException=r.DOMException}return s.prototype=r,new s}();(function(s){(function(o){var a=typeof s<"u"&&s||typeof self<"u"&&self||typeof Ft<"u"&&Ft||{},c={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 l(f){return f&&DataView.prototype.isPrototypeOf(f)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],m=ArrayBuffer.isView||function(f){return f&&u.indexOf(Object.prototype.toString.call(f))>-1};function x(f){if(typeof f!="string"&&(f=String(f)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(f)||f==="")throw new TypeError('Invalid character in header field name: "'+f+'"');return f.toLowerCase()}function S(f){return typeof f!="string"&&(f=String(f)),f}function E(f){var p={next:function(){var _=f.shift();return{done:_===void 0,value:_}}};return c.iterable&&(p[Symbol.iterator]=function(){return p}),p}function A(f){this.map={},f instanceof A?f.forEach(function(p,_){this.append(_,p)},this):Array.isArray(f)?f.forEach(function(p){if(p.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+p.length);this.append(p[0],p[1])},this):f&&Object.getOwnPropertyNames(f).forEach(function(p){this.append(p,f[p])},this)}A.prototype.append=function(f,p){f=x(f),p=S(p);var _=this.map[f];this.map[f]=_?_+", "+p:p},A.prototype.delete=function(f){delete this.map[x(f)]},A.prototype.get=function(f){return f=x(f),this.has(f)?this.map[f]:null},A.prototype.has=function(f){return this.map.hasOwnProperty(x(f))},A.prototype.set=function(f,p){this.map[x(f)]=S(p)},A.prototype.forEach=function(f,p){for(var _ in this.map)this.map.hasOwnProperty(_)&&f.call(p,this.map[_],_,this)},A.prototype.keys=function(){var f=[];return this.forEach(function(p,_){f.push(_)}),E(f)},A.prototype.values=function(){var f=[];return this.forEach(function(p){f.push(p)}),E(f)},A.prototype.entries=function(){var f=[];return this.forEach(function(p,_){f.push([_,p])}),E(f)},c.iterable&&(A.prototype[Symbol.iterator]=A.prototype.entries);function R(f){if(!f._noBody){if(f.bodyUsed)return Promise.reject(new TypeError("Already read"));f.bodyUsed=!0}}function O(f){return new Promise(function(p,_){f.onload=function(){p(f.result)},f.onerror=function(){_(f.error)}})}function C(f){var p=new FileReader,_=O(p);return p.readAsArrayBuffer(f),_}function N(f){var p=new FileReader,_=O(p),$=/charset=([A-Za-z0-9_-]+)/.exec(f.type),y=$?$[1]:"utf-8";return p.readAsText(f,y),_}function T(f){for(var p=new Uint8Array(f),_=new Array(p.length),$=0;$<p.length;$++)_[$]=String.fromCharCode(p[$]);return _.join("")}function U(f){if(f.slice)return f.slice(0);var p=new Uint8Array(f.byteLength);return p.set(new Uint8Array(f)),p.buffer}function z(){return this.bodyUsed=!1,this._initBody=function(f){this.bodyUsed=this.bodyUsed,this._bodyInit=f,f?typeof f=="string"?this._bodyText=f:c.blob&&Blob.prototype.isPrototypeOf(f)?this._bodyBlob=f:c.formData&&FormData.prototype.isPrototypeOf(f)?this._bodyFormData=f:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(f)?this._bodyText=f.toString():c.arrayBuffer&&c.blob&&l(f)?(this._bodyArrayBuffer=U(f.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(f)||m(f))?this._bodyArrayBuffer=U(f):this._bodyText=f=Object.prototype.toString.call(f):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof f=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(f)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var f=R(this);if(f)return f;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(){if(this._bodyArrayBuffer){var f=R(this);return f||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(c.blob)return this.blob().then(C);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var f=R(this);if(f)return f;if(this._bodyBlob)return N(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(T(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},c.formData&&(this.formData=function(){return this.text().then(K)}),this.json=function(){return this.text().then(JSON.parse)},this}var W=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function V(f){var p=f.toUpperCase();return W.indexOf(p)>-1?p:f}function B(f,p){if(!(this instanceof B))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');p=p||{};var _=p.body;if(f instanceof B){if(f.bodyUsed)throw new TypeError("Already read");this.url=f.url,this.credentials=f.credentials,p.headers||(this.headers=new A(f.headers)),this.method=f.method,this.mode=f.mode,this.signal=f.signal,!_&&f._bodyInit!=null&&(_=f._bodyInit,f.bodyUsed=!0)}else this.url=String(f);if(this.credentials=p.credentials||this.credentials||"same-origin",(p.headers||!this.headers)&&(this.headers=new A(p.headers)),this.method=V(p.method||this.method||"GET"),this.mode=p.mode||this.mode||null,this.signal=p.signal||this.signal||function(){if("AbortController"in a){var d=new AbortController;return d.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&_)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(_),(this.method==="GET"||this.method==="HEAD")&&(p.cache==="no-store"||p.cache==="no-cache")){var $=/([?&])_=[^&]*/;if($.test(this.url))this.url=this.url.replace($,"$1_="+new Date().getTime());else{var y=/\?/;this.url+=(y.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}B.prototype.clone=function(){return new B(this,{body:this._bodyInit})};function K(f){var p=new FormData;return f.trim().split("&").forEach(function(_){if(_){var $=_.split("="),y=$.shift().replace(/\+/g," "),d=$.join("=").replace(/\+/g," ");p.append(decodeURIComponent(y),decodeURIComponent(d))}}),p}function M(f){var p=new A,_=f.replace(/\r?\n[\t ]+/g," ");return _.split("\r").map(function($){return $.indexOf(`
43
+ ***************************************************************************** */var Eu=function(t,e){return Eu=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var n in i)i.hasOwnProperty(n)&&(r[n]=i[n])},Eu(t,e)};function DS(t,e){Eu(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var $u=function(){return $u=Object.assign||function(e){for(var r,i=1,n=arguments.length;i<n;i++){r=arguments[i];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},$u.apply(this,arguments)};function RS(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(t);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(r[i[n]]=t[i[n]]);return r}function NS(t,e,r,i){var n=arguments.length,s=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(n<3?o(s):n>3?o(e,r,s):o(e,r))||s);return n>3&&s&&Object.defineProperty(e,r,s),s}function TS(t,e){return function(r,i){e(r,i,t)}}function FS(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function LS(t,e,r,i){function n(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(u){try{l(i.next(u))}catch(m){o(m)}}function c(u){try{l(i.throw(u))}catch(m){o(m)}}function l(u){u.done?s(u.value):n(u.value).then(a,c)}l((i=i.apply(t,e||[])).next())})}function BS(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,n&&(s=l[0]&2?n.return:l[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,l[1])).done)return s;switch(n=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,n=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],n=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function US(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function qS(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Su(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Qv(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function jS(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Qv(arguments[e]));return t}function kS(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),n=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,n++)i[n]=s[o];return i}function Za(t){return this instanceof Za?(this.v=t,this):new Za(t)}function zS(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),n,s=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(x){i[x]&&(n[x]=function(S){return new Promise(function(E,A){s.push([x,S,E,A])>1||a(x,S)})})}function a(x,S){try{c(i[x](S))}catch(E){m(s[0][3],E)}}function c(x){x.value instanceof Za?Promise.resolve(x.value.v).then(l,u):m(s[0][2],x)}function l(x){a("next",x)}function u(x){a("throw",x)}function m(x,S){x(S),s.shift(),s.length&&a(s[0][0],s[0][1])}}function HS(t){var e,r;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,s){e[n]=t[n]?function(o){return(r=!r)?{value:Za(t[n](o)),done:n==="return"}:s?s(o):o}:s}}function WS(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Su=="function"?Su(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),n(a,c,o.done,o.value)})}}function n(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function VS(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function KS(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function GS(t){return t&&t.__esModule?t:{default:t}}function JS(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function ZS(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var YS=Object.freeze({__proto__:null,__extends:DS,get __assign(){return $u},__rest:RS,__decorate:NS,__param:TS,__metadata:FS,__awaiter:LS,__generator:BS,__createBinding:US,__exportStar:qS,__values:Su,__read:Qv,__spread:jS,__spreadArrays:kS,__await:Za,__asyncGenerator:zS,__asyncDelegator:HS,__asyncValues:WS,__makeTemplateObject:VS,__importStar:KS,__importDefault:GS,__classPrivateFieldGet:JS,__classPrivateFieldSet:ZS}),XS=Ch(YS),vn={},em;function QS(){if(em)return vn;em=1,Object.defineProperty(vn,"__esModule",{value:!0}),vn.isBrowserCryptoAvailable=vn.getSubtleCrypto=vn.getBrowerCrypto=void 0;function t(){return Ft?.crypto||Ft?.msCrypto||{}}vn.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}vn.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return vn.isBrowserCryptoAvailable=r,vn}var mn={},tm;function eI(){if(tm)return mn;tm=1,Object.defineProperty(mn,"__esModule",{value:!0}),mn.isBrowser=mn.isNode=mn.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}mn.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}mn.isNode=e;function r(){return!t()&&!e()}return mn.isBrowser=r,mn}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=XS;e.__exportStar(QS(),t),e.__exportStar(eI(),t)})(Xv);function bn(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Ps(t=6){return BigInt(bn(t))}function Zn(t,e,r){return{id:r||bn(),jsonrpc:"2.0",method:t,params:e}}function Cl(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Dl(t,e,r){return{id:t,jsonrpc:"2.0",error:tI(e,r)}}function tI(t,e){return typeof t>"u"?Zv(Gv):(typeof t=="string"&&(t=Object.assign(Object.assign({},Zv(xu)),{message:t})),typeof e<"u"&&(t.data=e),OS(t.code)&&(t=CS(t.code)),t)}class rI{}class iI extends rI{constructor(){super()}}class nI extends iI{constructor(e){super()}}const sI="^https?:",oI="^wss?:";function aI(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function rm(t,e){const r=aI(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function im(t){return rm(t,sI)}function nm(t){return rm(t,oI)}function cI(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function sm(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Iu(t){return sm(t)&&"method"in t}function Rl(t){return sm(t)&&(Gi(t)||fi(t))}function Gi(t){return"result"in t}function fi(t){return"error"in t}class ui extends nI{constructor(e){super(e),this.events=new nr.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Zn(e.method,e.params||[],e.id||Ps().toString()),r)}async requestStrict(e,r){return new Promise(async(i,n)=>{if(!this.connection.connected)try{await this.open()}catch(s){n(s)}this.events.on(`${e.id}`,s=>{fi(s)?n(s.error):i(s.result)});try{await this.connection.send(e,r)}catch(s){n(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Rl(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 lI=()=>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"),hI=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",om=t=>t.split("?")[0],am=10,fI=lI();class uI{constructor(e){if(this.url=e,this.events=new nr.exports.EventEmitter,this.registering=!1,!nm(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ln(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!nm(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return n(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,i)=>{const n=Xv.isReactNative()?void 0:{rejectUnauthorized:!cI(e)},s=new fI(e,[],n);hI()?s.onerror=o=>{const a=o;i(this.emitError(a.error))}:s.on("error",o=>{i(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ms(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=Dl(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return Yv(e,om(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>am&&this.events.setMaxListeners(am)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${om(this.url)}`));return this.events.emit("register_error",r),r}}var Au={exports:{}};(function(t,e){var r=200,i="__lodash_hash_undefined__",n=1,s=2,o=9007199254740991,a="[object Arguments]",c="[object Array]",l="[object AsyncFunction]",u="[object Boolean]",m="[object Date]",x="[object Error]",S="[object Function]",E="[object GeneratorFunction]",A="[object Map]",R="[object Number]",O="[object Null]",C="[object Object]",N="[object Promise]",T="[object Proxy]",U="[object RegExp]",z="[object Set]",W="[object String]",V="[object Symbol]",B="[object Undefined]",K="[object WeakMap]",M="[object ArrayBuffer]",v="[object DataView]",g="[object Float32Array]",h="[object Float64Array]",f="[object Int8Array]",p="[object Int16Array]",_="[object Int32Array]",$="[object Uint8Array]",y="[object Uint8ClampedArray]",d="[object Uint16Array]",w="[object Uint32Array]",b=/[\\^$.*+?()[\]{}|]/g,P=/^\[object .+?Constructor\]$/,q=/^(?:0|[1-9]\d*)$/,I={};I[g]=I[h]=I[f]=I[p]=I[_]=I[$]=I[y]=I[d]=I[w]=!0,I[a]=I[c]=I[M]=I[u]=I[v]=I[m]=I[x]=I[S]=I[A]=I[R]=I[C]=I[U]=I[z]=I[W]=I[K]=!1;var F=typeof Ft=="object"&&Ft&&Ft.Object===Object&&Ft,j=typeof self=="object"&&self&&self.Object===Object&&self,k=F||j||Function("return this")(),H=e&&!e.nodeType&&e,Y=H&&!0&&t&&!t.nodeType&&t,Q=Y&&Y.exports===H,J=Q&&F.process,ae=function(){try{return J&&J.binding&&J.binding("util")}catch{}}(),re=ae&&ae.isTypedArray;function ie(D,L){for(var G=-1,ne=D==null?0:D.length,Pt=0,Se=[];++G<ne;){var Tt=D[G];L(Tt,G,D)&&(Se[Pt++]=Tt)}return Se}function Ze(D,L){for(var G=-1,ne=L.length,Pt=D.length;++G<ne;)D[Pt+G]=L[G];return D}function Ye(D,L){for(var G=-1,ne=D==null?0:D.length;++G<ne;)if(L(D[G],G,D))return!0;return!1}function de(D,L){for(var G=-1,ne=Array(D);++G<D;)ne[G]=L(G);return ne}function qe(D){return function(L){return D(L)}}function je(D,L){return D.has(L)}function he(D,L){return D?.[L]}function ke(D){var L=-1,G=Array(D.size);return D.forEach(function(ne,Pt){G[++L]=[Pt,ne]}),G}function ze(D,L){return function(G){return D(L(G))}}function ue(D){var L=-1,G=Array(D.size);return D.forEach(function(ne){G[++L]=ne}),G}var He=Array.prototype,We=Function.prototype,le=Object.prototype,Be=k["__core-js_shared__"],Ve=We.toString,oe=le.hasOwnProperty,nt=function(){var D=/[^.]+$/.exec(Be&&Be.keys&&Be.keys.IE_PROTO||"");return D?"Symbol(src)_1."+D:""}(),st=le.toString,me=RegExp("^"+Ve.call(oe).replace(b,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ot=Q?k.Buffer:void 0,Ke=k.Symbol,ge=k.Uint8Array,at=le.propertyIsEnumerable,ft=He.splice,ce=Ke?Ke.toStringTag:void 0,ct=Object.getOwnPropertySymbols,ut=ot?ot.isBuffer:void 0,be=ze(Object.keys,Object),Xe=ua(k,"DataView"),Ue=ua(k,"Map"),pe=ua(k,"Promise"),Qe=ua(k,"Set"),et=ua(k,"WeakMap"),fe=ua(Object,"create"),dt=Js(Xe),pt=Js(Ue),ye=Js(pe),gt=Js(Qe),vt=Js(et),ve=Ke?Ke.prototype:void 0,tt=ve?ve.valueOf:void 0;function Re(D){var L=-1,G=D==null?0:D.length;for(this.clear();++L<G;){var ne=D[L];this.set(ne[0],ne[1])}}function we(){this.__data__=fe?fe(null):{},this.size=0}function mt(D){var L=this.has(D)&&delete this.__data__[D];return this.size-=L?1:0,L}function bt(D){var L=this.__data__;if(fe){var G=L[D];return G===i?void 0:G}return oe.call(L,D)?L[D]:void 0}function _e(D){var L=this.__data__;return fe?L[D]!==void 0:oe.call(L,D)}function yt(D,L){var G=this.__data__;return this.size+=this.has(D)?0:1,G[D]=fe&&L===void 0?i:L,this}Re.prototype.clear=we,Re.prototype.delete=mt,Re.prototype.get=bt,Re.prototype.has=_e,Re.prototype.set=yt;function Ae(D){var L=-1,G=D==null?0:D.length;for(this.clear();++L<G;){var ne=D[L];this.set(ne[0],ne[1])}}function lt(){this.__data__=[],this.size=0}function qr(D){var L=this.__data__,G=Ih(L,D);if(G<0)return!1;var ne=L.length-1;return G==ne?L.pop():ft.call(L,G,1),--this.size,!0}function jr(D){var L=this.__data__,G=Ih(L,D);return G<0?void 0:L[G][1]}function kr(D){return Ih(this.__data__,D)>-1}function zr(D,L){var G=this.__data__,ne=Ih(G,D);return ne<0?(++this.size,G.push([D,L])):G[ne][1]=L,this}Ae.prototype.clear=lt,Ae.prototype.delete=qr,Ae.prototype.get=jr,Ae.prototype.has=kr,Ae.prototype.set=zr;function kt(D){var L=-1,G=D==null?0:D.length;for(this.clear();++L<G;){var ne=D[L];this.set(ne[0],ne[1])}}function En(){this.size=0,this.__data__={hash:new Re,map:new(Ue||Ae),string:new Re}}function $n(D){var L=Ah(this,D).delete(D);return this.size-=L?1:0,L}function Sn(D){return Ah(this,D).get(D)}function In(D){return Ah(this,D).has(D)}function An(D,L){var G=Ah(this,D),ne=G.size;return G.set(D,L),this.size+=G.size==ne?0:1,this}kt.prototype.clear=En,kt.prototype.delete=$n,kt.prototype.get=Sn,kt.prototype.has=In,kt.prototype.set=An;function mi(D){var L=-1,G=D==null?0:D.length;for(this.__data__=new kt;++L<G;)this.add(D[L])}function Mn(D){return this.__data__.set(D,i),this}function Pn(D){return this.__data__.has(D)}mi.prototype.add=mi.prototype.push=Mn,mi.prototype.has=Pn;function wr(D){var L=this.__data__=new Ae(D);this.size=L.size}function On(){this.__data__=new Ae,this.size=0}function Cn(D){var L=this.__data__,G=L.delete(D);return this.size=L.size,G}function Dn(D){return this.__data__.get(D)}function $c(D){return this.__data__.has(D)}function Sc(D,L){var G=this.__data__;if(G instanceof Ae){var ne=G.__data__;if(!Ue||ne.length<r-1)return ne.push([D,L]),this.size=++G.size,this;G=this.__data__=new kt(ne)}return G.set(D,L),this.size=G.size,this}wr.prototype.clear=On,wr.prototype.delete=Cn,wr.prototype.get=Dn,wr.prototype.has=$c,wr.prototype.set=Sc;function $k(D,L){var G=Mh(D),ne=!G&&Uk(D),Pt=!G&&!ne&&y0(D),Se=!G&&!ne&&!Pt&&Ty(D),Tt=G||ne||Pt||Se,ir=Tt?de(D.length,String):[],pr=ir.length;for(var Ct in D)(L||oe.call(D,Ct))&&!(Tt&&(Ct=="length"||Pt&&(Ct=="offset"||Ct=="parent")||Se&&(Ct=="buffer"||Ct=="byteLength"||Ct=="byteOffset")||Nk(Ct,pr)))&&ir.push(Ct);return ir}function Ih(D,L){for(var G=D.length;G--;)if(Cy(D[G][0],L))return G;return-1}function Sk(D,L,G){var ne=L(D);return Mh(D)?ne:Ze(ne,G(D))}function Ic(D){return D==null?D===void 0?B:O:ce&&ce in Object(D)?Dk(D):Bk(D)}function Ay(D){return Ac(D)&&Ic(D)==a}function My(D,L,G,ne,Pt){return D===L?!0:D==null||L==null||!Ac(D)&&!Ac(L)?D!==D&&L!==L:Ik(D,L,G,ne,My,Pt)}function Ik(D,L,G,ne,Pt,Se){var Tt=Mh(D),ir=Mh(L),pr=Tt?c:ls(D),Ct=ir?c:ls(L);pr=pr==a?C:pr,Ct=Ct==a?C:Ct;var ri=pr==C,Di=Ct==C,_r=pr==Ct;if(_r&&y0(D)){if(!y0(L))return!1;Tt=!0,ri=!1}if(_r&&!ri)return Se||(Se=new wr),Tt||Ty(D)?Py(D,L,G,ne,Pt,Se):Ok(D,L,pr,G,ne,Pt,Se);if(!(G&n)){var bi=ri&&oe.call(D,"__wrapped__"),yi=Di&&oe.call(L,"__wrapped__");if(bi||yi){var hs=bi?D.value():D,Rn=yi?L.value():L;return Se||(Se=new wr),Pt(hs,Rn,G,ne,Se)}}return _r?(Se||(Se=new wr),Ck(D,L,G,ne,Pt,Se)):!1}function Ak(D){if(!Ny(D)||Fk(D))return!1;var L=Dy(D)?me:P;return L.test(Js(D))}function Mk(D){return Ac(D)&&Ry(D.length)&&!!I[Ic(D)]}function Pk(D){if(!Lk(D))return be(D);var L=[];for(var G in Object(D))oe.call(D,G)&&G!="constructor"&&L.push(G);return L}function Py(D,L,G,ne,Pt,Se){var Tt=G&n,ir=D.length,pr=L.length;if(ir!=pr&&!(Tt&&pr>ir))return!1;var Ct=Se.get(D);if(Ct&&Se.get(L))return Ct==L;var ri=-1,Di=!0,_r=G&s?new mi:void 0;for(Se.set(D,L),Se.set(L,D);++ri<ir;){var bi=D[ri],yi=L[ri];if(ne)var hs=Tt?ne(yi,bi,ri,L,D,Se):ne(bi,yi,ri,D,L,Se);if(hs!==void 0){if(hs)continue;Di=!1;break}if(_r){if(!Ye(L,function(Rn,Zs){if(!je(_r,Zs)&&(bi===Rn||Pt(bi,Rn,G,ne,Se)))return _r.push(Zs)})){Di=!1;break}}else if(!(bi===yi||Pt(bi,yi,G,ne,Se))){Di=!1;break}}return Se.delete(D),Se.delete(L),Di}function Ok(D,L,G,ne,Pt,Se,Tt){switch(G){case v:if(D.byteLength!=L.byteLength||D.byteOffset!=L.byteOffset)return!1;D=D.buffer,L=L.buffer;case M:return!(D.byteLength!=L.byteLength||!Se(new ge(D),new ge(L)));case u:case m:case R:return Cy(+D,+L);case x:return D.name==L.name&&D.message==L.message;case U:case W:return D==L+"";case A:var ir=ke;case z:var pr=ne&n;if(ir||(ir=ue),D.size!=L.size&&!pr)return!1;var Ct=Tt.get(D);if(Ct)return Ct==L;ne|=s,Tt.set(D,L);var ri=Py(ir(D),ir(L),ne,Pt,Se,Tt);return Tt.delete(D),ri;case V:if(tt)return tt.call(D)==tt.call(L)}return!1}function Ck(D,L,G,ne,Pt,Se){var Tt=G&n,ir=Oy(D),pr=ir.length,Ct=Oy(L),ri=Ct.length;if(pr!=ri&&!Tt)return!1;for(var Di=pr;Di--;){var _r=ir[Di];if(!(Tt?_r in L:oe.call(L,_r)))return!1}var bi=Se.get(D);if(bi&&Se.get(L))return bi==L;var yi=!0;Se.set(D,L),Se.set(L,D);for(var hs=Tt;++Di<pr;){_r=ir[Di];var Rn=D[_r],Zs=L[_r];if(ne)var Fy=Tt?ne(Zs,Rn,_r,L,D,Se):ne(Rn,Zs,_r,D,L,Se);if(!(Fy===void 0?Rn===Zs||Pt(Rn,Zs,G,ne,Se):Fy)){yi=!1;break}hs||(hs=_r=="constructor")}if(yi&&!hs){var Ph=D.constructor,Oh=L.constructor;Ph!=Oh&&"constructor"in D&&"constructor"in L&&!(typeof Ph=="function"&&Ph instanceof Ph&&typeof Oh=="function"&&Oh instanceof Oh)&&(yi=!1)}return Se.delete(D),Se.delete(L),yi}function Oy(D){return Sk(D,kk,Rk)}function Ah(D,L){var G=D.__data__;return Tk(L)?G[typeof L=="string"?"string":"hash"]:G.map}function ua(D,L){var G=he(D,L);return Ak(G)?G:void 0}function Dk(D){var L=oe.call(D,ce),G=D[ce];try{D[ce]=void 0;var ne=!0}catch{}var Pt=st.call(D);return ne&&(L?D[ce]=G:delete D[ce]),Pt}var Rk=ct?function(D){return D==null?[]:(D=Object(D),ie(ct(D),function(L){return at.call(D,L)}))}:zk,ls=Ic;(Xe&&ls(new Xe(new ArrayBuffer(1)))!=v||Ue&&ls(new Ue)!=A||pe&&ls(pe.resolve())!=N||Qe&&ls(new Qe)!=z||et&&ls(new et)!=K)&&(ls=function(D){var L=Ic(D),G=L==C?D.constructor:void 0,ne=G?Js(G):"";if(ne)switch(ne){case dt:return v;case pt:return A;case ye:return N;case gt:return z;case vt:return K}return L});function Nk(D,L){return L=L??o,!!L&&(typeof D=="number"||q.test(D))&&D>-1&&D%1==0&&D<L}function Tk(D){var L=typeof D;return L=="string"||L=="number"||L=="symbol"||L=="boolean"?D!=="__proto__":D===null}function Fk(D){return!!nt&&nt in D}function Lk(D){var L=D&&D.constructor,G=typeof L=="function"&&L.prototype||le;return D===G}function Bk(D){return st.call(D)}function Js(D){if(D!=null){try{return Ve.call(D)}catch{}try{return D+""}catch{}}return""}function Cy(D,L){return D===L||D!==D&&L!==L}var Uk=Ay(function(){return arguments}())?Ay:function(D){return Ac(D)&&oe.call(D,"callee")&&!at.call(D,"callee")},Mh=Array.isArray;function qk(D){return D!=null&&Ry(D.length)&&!Dy(D)}var y0=ut||Hk;function jk(D,L){return My(D,L)}function Dy(D){if(!Ny(D))return!1;var L=Ic(D);return L==S||L==E||L==l||L==T}function Ry(D){return typeof D=="number"&&D>-1&&D%1==0&&D<=o}function Ny(D){var L=typeof D;return D!=null&&(L=="object"||L=="function")}function Ac(D){return D!=null&&typeof D=="object"}var Ty=re?qe(re):Mk;function kk(D){return qk(D)?$k(D):Pk(D)}function zk(){return[]}function Hk(){return!1}t.exports=jk})(Au,Au.exports);var dI=Au.exports,pI=Object.defineProperty,cm=Object.getOwnPropertySymbols,gI=Object.prototype.hasOwnProperty,vI=Object.prototype.propertyIsEnumerable,lm=(t,e,r)=>e in t?pI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ar=(t,e)=>{for(var r in e||(e={}))gI.call(e,r)&&lm(t,r,e[r]);if(cm)for(var r of cm(e))vI.call(e,r)&&lm(t,r,e[r]);return t};const hm="wc",fm=2,Nl="core",Ji=`${hm}@2:${Nl}:`,mI={name:Nl,logger:"error"},bI={database:":memory:"},yI="crypto",um="client_ed25519_seed",wI=X.ONE_DAY,_I="keychain",xI="0.3",EI="messages",$I="0.3",dm=X.SIX_HOURS,SI="publisher",pm="irn",II="error",gm="wss://relay.walletconnect.org",AI="relayer",Qt={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"},MI="_subscription",di={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},PI=.1,Mu="2.18.1",St={link_mode:"link_mode",relay:"relay"},OI="0.3",CI="WALLETCONNECT_CLIENT_ID",vm="WALLETCONNECT_LINK_MODE_APPS",Zr={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},DI="subscription",RI="0.3",NI=X.FIVE_SECONDS*1e3,TI="pairing",FI="0.3",Ya={wc_pairingDelete:{req:{ttl:X.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:X.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:X.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:X.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:X.ONE_DAY,prompt:!1,tag:0},res:{ttl:X.ONE_DAY,prompt:!1,tag:0}}},Os={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Mi={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},LI="history",BI="0.3",UI="expirer",pi={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},qI="0.3",jI="verify-api",kI="https://verify.walletconnect.com",mm="https://verify.walletconnect.org",Xa=mm,zI=`${Xa}/v3`,HI=[kI,mm],WI="echo",VI="https://echo.walletconnect.com",Zi={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},yn={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Pi={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},Cs={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},Ds={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},Qa={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},KI=.1,GI="event-client",JI=86400,ZI="https://pulse.walletconnect.org/batch";function YI(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=n}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function m(E){if(E instanceof Uint8Array||(ArrayBuffer.isView(E)?E=new Uint8Array(E.buffer,E.byteOffset,E.byteLength):Array.isArray(E)&&(E=Uint8Array.from(E))),!(E instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(E.length===0)return"";for(var A=0,R=0,O=0,C=E.length;O!==C&&E[O]===0;)O++,A++;for(var N=(C-O)*u+1>>>0,T=new Uint8Array(N);O!==C;){for(var U=E[O],z=0,W=N-1;(U!==0||z<R)&&W!==-1;W--,z++)U+=256*T[W]>>>0,T[W]=U%a>>>0,U=U/a>>>0;if(U!==0)throw new Error("Non-zero carry");R=z,O++}for(var V=N-R;V!==N&&T[V]===0;)V++;for(var B=c.repeat(A);V<N;++V)B+=t.charAt(T[V]);return B}function x(E){if(typeof E!="string")throw new TypeError("Expected String");if(E.length===0)return new Uint8Array;var A=0;if(E[A]!==" "){for(var R=0,O=0;E[A]===c;)R++,A++;for(var C=(E.length-A)*l+1>>>0,N=new Uint8Array(C);E[A];){var T=r[E.charCodeAt(A)];if(T===255)return;for(var U=0,z=C-1;(T!==0||U<O)&&z!==-1;z--,U++)T+=a*N[z]>>>0,N[z]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");O=U,A++}if(E[A]!==" "){for(var W=C-O;W!==C&&N[W]===0;)W++;for(var V=new Uint8Array(R+(C-W)),B=R;W!==C;)V[B++]=N[W++];return V}}}function S(E){var A=x(E);if(A)return A;throw new Error(`Non-${e} character`)}return{encode:m,decodeUnsafe:x,decode:S}}var XI=YI,QI=XI;const bm=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},eA=t=>new TextEncoder().encode(t),tA=t=>new TextDecoder().decode(t);class rA{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class iA{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=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 ym(this,e)}}class nA{constructor(e){this.decoders=e}or(e){return ym(this,e)}decode(e){const r=e[0],i=this.decoders[r];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 ym=(t,e)=>new nA(Ar(Ar({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class sA{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new rA(e,r,i),this.decoder=new iA(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Tl=({name:t,prefix:e,encode:r,decode:i})=>new sA(t,e,r,i),ec=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=QI(r,e);return Tl({prefix:t,name:e,encode:i,decode:s=>bm(n(s))})},oA=(t,e,r,i)=>{const n={};for(let u=0;u<e.length;++u)n[e[u]]=u;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const m=n[t[u]];if(m===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|m,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},aA=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[n&a>>o];if(o&&(s+=e[n&a<<r-o]),i)for(;s.length*r&7;)s+="=";return s},fr=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Tl({prefix:e,name:t,encode(n){return aA(n,i,r)},decode(n){return oA(n,i,r,t)}}),cA=Tl({prefix:"\0",name:"identity",encode:t=>tA(t),decode:t=>eA(t)});var lA=Object.freeze({__proto__:null,identity:cA});const hA=fr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var fA=Object.freeze({__proto__:null,base2:hA});const uA=fr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var dA=Object.freeze({__proto__:null,base8:uA});const pA=ec({prefix:"9",name:"base10",alphabet:"0123456789"});var gA=Object.freeze({__proto__:null,base10:pA});const vA=fr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),mA=fr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var bA=Object.freeze({__proto__:null,base16:vA,base16upper:mA});const yA=fr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),wA=fr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),_A=fr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),xA=fr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),EA=fr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),$A=fr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),SA=fr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),IA=fr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),AA=fr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var MA=Object.freeze({__proto__:null,base32:yA,base32upper:wA,base32pad:_A,base32padupper:xA,base32hex:EA,base32hexupper:$A,base32hexpad:SA,base32hexpadupper:IA,base32z:AA});const PA=ec({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),OA=ec({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var CA=Object.freeze({__proto__:null,base36:PA,base36upper:OA});const DA=ec({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),RA=ec({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var NA=Object.freeze({__proto__:null,base58btc:DA,base58flickr:RA});const TA=fr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),FA=fr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),LA=fr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),BA=fr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var UA=Object.freeze({__proto__:null,base64:TA,base64pad:FA,base64url:LA,base64urlpad:BA});const wm=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}"),qA=wm.reduce((t,e,r)=>(t[r]=e,t),[]),jA=wm.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function kA(t){return t.reduce((e,r)=>(e+=qA[r],e),"")}function zA(t){const e=[];for(const r of t){const i=jA[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const HA=Tl({prefix:"\u{1F680}",name:"base256emoji",encode:kA,decode:zA});var WA=Object.freeze({__proto__:null,base256emoji:HA}),VA=xm,_m=128,KA=127,GA=~KA,JA=Math.pow(2,31);function xm(t,e,r){e=e||[],r=r||0;for(var i=r;t>=JA;)e[r++]=t&255|_m,t/=128;for(;t&GA;)e[r++]=t&255|_m,t>>>=7;return e[r]=t|0,xm.bytes=r-i+1,e}var ZA=Pu,YA=128,Em=127;function Pu(t,i){var r=0,i=i||0,n=0,s=i,o,a=t.length;do{if(s>=a)throw Pu.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=n<28?(o&Em)<<n:(o&Em)*Math.pow(2,n),n+=7}while(o>=YA);return Pu.bytes=s-i,r}var XA=Math.pow(2,7),QA=Math.pow(2,14),eM=Math.pow(2,21),tM=Math.pow(2,28),rM=Math.pow(2,35),iM=Math.pow(2,42),nM=Math.pow(2,49),sM=Math.pow(2,56),oM=Math.pow(2,63),aM=function(t){return t<XA?1:t<QA?2:t<eM?3:t<tM?4:t<rM?5:t<iM?6:t<nM?7:t<sM?8:t<oM?9:10},cM={encode:VA,decode:ZA,encodingLength:aM},$m=cM;const Sm=(t,e,r=0)=>($m.encode(t,e,r),e),Im=t=>$m.encodingLength(t),Ou=(t,e)=>{const r=e.byteLength,i=Im(t),n=i+Im(r),s=new Uint8Array(n+r);return Sm(t,s,0),Sm(r,s,i),s.set(e,n),new lM(t,r,e,s)};class lM{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const Am=({name:t,code:e,encode:r})=>new hM(t,e,r);class hM{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Ou(this.code,r):r.then(i=>Ou(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Mm=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),fM=Am({name:"sha2-256",code:18,encode:Mm("SHA-256")}),uM=Am({name:"sha2-512",code:19,encode:Mm("SHA-512")});var dM=Object.freeze({__proto__:null,sha256:fM,sha512:uM});const Pm=0,pM="identity",Om=bm;var gM=Object.freeze({__proto__:null,identity:{code:Pm,name:pM,encode:Om,digest:t=>Ou(Pm,Om(t))}});new TextEncoder,new TextDecoder;const Cm=Ar(Ar(Ar(Ar(Ar(Ar(Ar(Ar(Ar(Ar({},lA),fA),dA),gA),bA),MA),CA),NA),UA),WA);Ar(Ar({},dM),gM);function vM(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Dm(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const Rm=Dm("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Cu=Dm("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=vM(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),mM=Ar({utf8:Rm,"utf-8":Rm,hex:Cm.base16,latin1:Cu,ascii:Cu,binary:Cu},Cm);function bM(t,e="utf8"){const r=mM[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}var yM=Object.defineProperty,wM=(t,e,r)=>e in t?yM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yi=(t,e,r)=>wM(t,typeof e!="symbol"?e+"":e,r);class _M{constructor(e,r){this.core=e,this.logger=r,Yi(this,"keychain",new Map),Yi(this,"name",_I),Yi(this,"version",xI),Yi(this,"initialized",!1),Yi(this,"storagePrefix",Ji),Yi(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Yi(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Yi(this,"set",async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()}),Yi(this,"get",i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=ee("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n}),Yi(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=Ir(r,this.name)}get context(){return Tr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,xg(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Eg(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}var xM=Object.defineProperty,EM=(t,e,r)=>e in t?xM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ur=(t,e,r)=>EM(t,typeof e!="symbol"?e+"":e,r);class $M{constructor(e,r,i){this.core=e,this.logger=r,ur(this,"name",yI),ur(this,"keychain"),ur(this,"randomSessionIdentifier",hu()),ur(this,"initialized",!1),ur(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),ur(this,"hasKeys",n=>(this.isInitialized(),this.keychain.has(n))),ur(this,"getClientId",async()=>{this.isInitialized();const n=await this.getClientSeed(),s=F1(n);return T1(s.publicKey)}),ur(this,"generateKeyPair",()=>{this.isInitialized();const n=rE();return this.setPrivateKey(n.publicKey,n.privateKey)}),ur(this,"signJWT",async n=>{this.isInitialized();const s=await this.getClientSeed(),o=F1(s),a=this.randomSessionIdentifier;return await U8(a,n,wI,o)}),ur(this,"generateSharedKey",(n,s,o)=>{this.isInitialized();const a=this.getPrivateKey(n),c=iE(a,s);return this.setSymKey(c,o)}),ur(this,"setSymKey",async(n,s)=>{this.isInitialized();const o=s||bl(n);return await this.keychain.set(o,n),o}),ur(this,"deleteKeyPair",async n=>{this.isInitialized(),await this.keychain.del(n)}),ur(this,"deleteSymKey",async n=>{this.isInitialized(),await this.keychain.del(n)}),ur(this,"encode",async(n,s,o)=>{this.isInitialized();const a=wv(o),c=ln(s);if(xv(a))return oE(c,o?.encoding);if(_v(a)){const x=a.senderPublicKey,S=a.receiverPublicKey;n=await this.generateSharedKey(x,S)}const l=this.getSymKey(n),{type:u,senderPublicKey:m}=a;return nE({type:u,symKey:l,message:c,senderPublicKey:m,encoding:o?.encoding})}),ur(this,"decode",async(n,s,o)=>{this.isInitialized();const a=cE(s,o);if(xv(a)){const c=aE(s,o?.encoding);return ms(c)}if(_v(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;n=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(n),l=sE({symKey:c,encoded:s,encoding:o?.encoding});return ms(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),ur(this,"getPayloadType",(n,s=Jn)=>{const o=qa({encoded:n,encoding:s});return Is(o.type)}),ur(this,"getPayloadSenderPublicKey",(n,s=Jn)=>{const o=qa({encoded:n,encoding:s});return o.senderPublicKey?$r(o.senderPublicKey,mr):void 0}),this.core=e,this.logger=Ir(r,this.name),this.keychain=i||new _M(this.core,this.logger)}get context(){return Tr(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(um)}catch{e=hu(),await this.keychain.set(um,e)}return bM(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}var SM=Object.defineProperty,IM=(t,e,r)=>e in t?SM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Xi=(t,e,r)=>IM(t,typeof e!="symbol"?e+"":e,r);class AM extends uS{constructor(e,r){super(e,r),this.logger=e,this.core=r,Xi(this,"messages",new Map),Xi(this,"name",EI),Xi(this,"version",$I),Xi(this,"initialized",!1),Xi(this,"storagePrefix",Ji),Xi(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}}}),Xi(this,"set",async(i,n)=>{this.isInitialized();const s=gn(n);let o=this.messages.get(i);return typeof o>"u"&&(o={}),typeof o[s]<"u"||(o[s]=n,this.messages.set(i,o),await this.persist()),s}),Xi(this,"get",i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n}),Xi(this,"has",(i,n)=>{this.isInitialized();const s=this.get(i),o=gn(n);return typeof s[o]<"u"}),Xi(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()}),this.logger=Ir(e,this.name),this.core=r}get context(){return Tr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,xg(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Eg(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}var MM=Object.defineProperty,PM=Object.defineProperties,OM=Object.getOwnPropertyDescriptors,Nm=Object.getOwnPropertySymbols,CM=Object.prototype.hasOwnProperty,DM=Object.prototype.propertyIsEnumerable,Du=(t,e,r)=>e in t?MM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fl=(t,e)=>{for(var r in e||(e={}))CM.call(e,r)&&Du(t,r,e[r]);if(Nm)for(var r of Nm(e))DM.call(e,r)&&Du(t,r,e[r]);return t},Ru=(t,e)=>PM(t,OM(e)),Oi=(t,e,r)=>Du(t,typeof e!="symbol"?e+"":e,r);class RM extends dS{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,Oi(this,"events",new nr.exports.EventEmitter),Oi(this,"name",SI),Oi(this,"queue",new Map),Oi(this,"publishTimeout",X.toMiliseconds(X.ONE_MINUTE)),Oi(this,"initialPublishTimeout",X.toMiliseconds(X.ONE_SECOND*15)),Oi(this,"needsTransportRestart",!1),Oi(this,"publish",async(i,n,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:s}});const a=s?.ttl||dm,c=yl(s),l=s?.prompt||!1,u=s?.tag||0,m=s?.id||Ps().toString(),x={topic:i,message:n,opts:{ttl:a,relay:c,prompt:l,tag:u,id:m,attestation:s?.attestation,tvf:s?.tvf}},S=`Failed to publish payload, please try again. id:${m} tag:${u}`;try{const E=new Promise(async A=>{const R=({id:C})=>{x.opts.id===C&&(this.removeRequestFromQueue(C),this.relayer.events.removeListener(Qt.publish,R),A(x))};this.relayer.events.on(Qt.publish,R);const O=Hn(new Promise((C,N)=>{this.rpcPublish({topic:i,message:n,ttl:a,prompt:l,tag:u,id:m,attestation:s?.attestation,tvf:s?.tvf}).then(C).catch(T=>{this.logger.warn(T,T?.message),N(T)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${m} tag:${u}`);try{await O,this.events.removeListener(Qt.publish,R)}catch(C){this.queue.set(m,Ru(Fl({},x),{attempt:1})),this.logger.warn(C,C?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:m,topic:i,message:n,opts:s}}),await Hn(E,this.publishTimeout,S)}catch(E){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(E),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw E}finally{this.queue.delete(m)}}),Oi(this,"on",(i,n)=>{this.events.on(i,n)}),Oi(this,"once",(i,n)=>{this.events.once(i,n)}),Oi(this,"off",(i,n)=>{this.events.off(i,n)}),Oi(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.relayer=e,this.logger=Ir(r,this.name),this.registerEventListeners()}get context(){return Tr(this.logger)}async rpcPublish(e){var r,i,n,s;const{topic:o,message:a,ttl:c=dm,prompt:l,tag:u,id:m,attestation:x,tvf:S}=e,E={method:ja(yl().protocol).publish,params:Fl({topic:o,message:a,ttl:c,prompt:l,tag:u,attestation:x},S),id:m};Sr((r=E.params)==null?void 0:r.prompt)&&((i=E.params)==null||delete i.prompt),Sr((n=E.params)==null?void 0:n.tag)&&((s=E.params)==null||delete s.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:E});const A=await this.relayer.request(E);return this.relayer.events.emit(Qt.publish,e),this.logger.debug("Successfully Published Payload"),A}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const i=e.attempt+1;this.queue.set(r,Ru(Fl({},e),{attempt:i}));const{topic:n,message:s,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish(Ru(Fl({},e),{topic:n,message:s,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Io.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Qt.connection_stalled);return}this.checkQueue()}),this.relayer.on(Qt.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var NM=Object.defineProperty,TM=(t,e,r)=>e in t?NM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Po=(t,e,r)=>TM(t,typeof e!="symbol"?e+"":e,r);class FM{constructor(){Po(this,"map",new Map),Po(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),Po(this,"get",e=>this.map.get(e)||[]),Po(this,"exists",(e,r)=>this.get(e).includes(r)),Po(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,r))return;const n=i.filter(s=>s!==r);if(!n.length){this.map.delete(e);return}this.map.set(e,n)}),Po(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var LM=Object.defineProperty,BM=Object.defineProperties,UM=Object.getOwnPropertyDescriptors,Tm=Object.getOwnPropertySymbols,qM=Object.prototype.hasOwnProperty,jM=Object.prototype.propertyIsEnumerable,Nu=(t,e,r)=>e in t?LM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,tc=(t,e)=>{for(var r in e||(e={}))qM.call(e,r)&&Nu(t,r,e[r]);if(Tm)for(var r of Tm(e))jM.call(e,r)&&Nu(t,r,e[r]);return t},Tu=(t,e)=>BM(t,UM(e)),xt=(t,e,r)=>Nu(t,typeof e!="symbol"?e+"":e,r);class kM extends vS{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,xt(this,"subscriptions",new Map),xt(this,"topicMap",new FM),xt(this,"events",new nr.exports.EventEmitter),xt(this,"name",DI),xt(this,"version",RI),xt(this,"pending",new Map),xt(this,"cached",[]),xt(this,"initialized",!1),xt(this,"pendingSubscriptionWatchLabel","pending_sub_watch_label"),xt(this,"pollingInterval",20),xt(this,"storagePrefix",Ji),xt(this,"subscribeTimeout",X.toMiliseconds(X.ONE_MINUTE)),xt(this,"initialSubscribeTimeout",X.toMiliseconds(X.ONE_SECOND*15)),xt(this,"clientId"),xt(this,"batchSubscribeTopicsLimit",500),xt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),xt(this,"subscribe",async(i,n)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const s=yl(n),o={topic:i,relay:s,transportType:n?.transportType};this.pending.set(i,o);const a=await this.rpcSubscribe(i,s,n);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}})),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}}),xt(this,"unsubscribe",async(i,n)=>{await this.restartToComplete(),this.isInitialized(),typeof n?.id<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)}),xt(this,"isSubscribed",async i=>{if(this.topics.includes(i))return!0;const n=`${this.pendingSubscriptionWatchLabel}_${i}`;return await new Promise((s,o)=>{const a=new X.Watch;a.start(n);const c=setInterval(()=>{(!this.pending.has(i)&&this.topics.includes(i)||this.cached.some(l=>l.topic===i))&&(clearInterval(c),a.stop(n),s(!0)),a.elapsed(n)>=NI&&(clearInterval(c),a.stop(n),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)}),xt(this,"on",(i,n)=>{this.events.on(i,n)}),xt(this,"once",(i,n)=>{this.events.once(i,n)}),xt(this,"off",(i,n)=>{this.events.off(i,n)}),xt(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),xt(this,"start",async()=>{await this.onConnect()}),xt(this,"stop",async()=>{await this.onDisconnect()}),xt(this,"restart",async()=>{await this.restore(),await this.onRestart()}),xt(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(n=>{i.push(n)}),await this.batchSubscribe(i)}),xt(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Io.pulse,async()=>{await this.checkPending()}),this.events.on(Zr.created,async i=>{const n=Zr.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()}),this.events.on(Zr.deleted,async i=>{const n=Zr.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()})}),this.relayer=e,this.logger=Ir(r,this.name),this.clientId=""}get context(){return Tr(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,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const i=this.topicMap.get(e);await Promise.all(i.map(async n=>await this.unsubscribeById(e,n,r)))}async unsubscribeById(e,r,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}});try{const n=yl(i);await this.rpcUnsubscribe(e,r,n);const s=wt("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,r,i){var n;i?.transportType===St.relay&&await this.restartToComplete();const s={method:ja(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});const o=(n=i?.internal)==null?void 0:n.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(i?.transportType===St.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(u=>this.logger.warn(u))},X.toMiliseconds(X.ONE_SECOND)),a;const c=new Promise(async u=>{const m=x=>{x.topic===e&&(this.events.removeListener(Zr.created,m),u(x.id))};this.events.on(Zr.created,m);try{const x=await Hn(new Promise((S,E)=>{this.relayer.request(s).catch(A=>{this.logger.warn(A,A?.message),E(A)}).then(S)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Zr.created,m),u(x)}catch{}}),l=await Hn(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return l?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Qt.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:ja(r.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await Hn(new Promise(n=>{this.relayer.request(i).catch(s=>this.logger.warn(s)).then(n)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Qt.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:ja(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let n;try{n=await await Hn(new Promise((s,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Qt.connection_stalled)}return n}rpcUnsubscribe(e,r,i){const n={method:ja(i.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,r){this.setSubscription(e,Tu(tc({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,tc({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,i){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,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,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,tc({},r)),this.topicMap.set(r.topic,e),this.events.emit(Zr.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:i}=ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(Zr.deleted,Tu(tc({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Zr.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<r;i++){const n=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}}this.events.emit(Zr.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async r=>Tu(tc({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await b_(X.toMiliseconds(X.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){!this.relayer.connected&&!this.relayer.connecting&&await this.relayer.transportOpen()}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return gn(e+await this.getClientId())}}var zM=Object.defineProperty,Fm=Object.getOwnPropertySymbols,HM=Object.prototype.hasOwnProperty,WM=Object.prototype.propertyIsEnumerable,Fu=(t,e,r)=>e in t?zM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lm=(t,e)=>{for(var r in e||(e={}))HM.call(e,r)&&Fu(t,r,e[r]);if(Fm)for(var r of Fm(e))WM.call(e,r)&&Fu(t,r,e[r]);return t},rt=(t,e,r)=>Fu(t,typeof e!="symbol"?e+"":e,r);class VM extends pS{constructor(e){super(e),rt(this,"protocol","wc"),rt(this,"version",2),rt(this,"core"),rt(this,"logger"),rt(this,"events",new nr.exports.EventEmitter),rt(this,"provider"),rt(this,"messages"),rt(this,"subscriber"),rt(this,"publisher"),rt(this,"name",AI),rt(this,"transportExplicitlyClosed",!1),rt(this,"initialized",!1),rt(this,"connectionAttemptInProgress",!1),rt(this,"relayUrl"),rt(this,"projectId"),rt(this,"packageName"),rt(this,"bundleId"),rt(this,"hasExperiencedNetworkDisruption",!1),rt(this,"pingTimeout"),rt(this,"heartBeatTimeout",X.toMiliseconds(X.THIRTY_SECONDS+X.FIVE_SECONDS)),rt(this,"reconnectTimeout"),rt(this,"connectPromise"),rt(this,"requestsInFlight",[]),rt(this,"connectTimeout",X.toMiliseconds(X.ONE_SECOND*15)),rt(this,"request",async r=>{var i,n;this.logger.debug("Publishing Request Payload");const s=r.id||Ps().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - publishing...");const o=`${s}:${((n=r.params)==null?void 0:n.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}}),rt(this,"resetPingTimeout",()=>{if(ll())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,i,n;this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null||n.terminate()},this.heartBeatTimeout)}catch(r){this.logger.warn(r,r?.message)}}),rt(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),rt(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Qt.connect)}),rt(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),rt(this,"onProviderErrorHandler",r=>{this.logger.fatal(r,`Fatal socket error: ${r?.message}`),this.events.emit(Qt.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),rt(this,"registerProviderListeners",()=>{this.provider.on(di.payload,this.onPayloadHandler),this.provider.on(di.connect,this.onConnectHandler),this.provider.on(di.disconnect,this.onDisconnectHandler),this.provider.on(di.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Ir(e.logger,this.name):Vi(Ol({level:e.logger||II})),this.messages=new AM(this.logger,e.core),this.subscriber=new kM(this,this.logger),this.publisher=new RM(this,this.logger),this.relayUrl=e?.relayUrl||gm,this.projectId=e.projectId,i_()?this.packageName=yg():n_()&&(this.bundleId=yg()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.cached.length>0)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return Tr(this.logger)}get connected(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===1}get connecting(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===0}async publish(e,r,i){this.isInitialized(),await this.publisher.publish(e,r,i),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:St.relay})}async subscribe(e,r){var i,n,s;this.isInitialized(),(!(r!=null&&r.transportType)||r?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((i=r?.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(n=r?.internal)==null?void 0:n.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(Zr.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(Zr.created,l)}),new Promise(async(u,m)=>{a=await this.subscriber.subscribe(e,Lm({internal:{throwOnFailedPublish:o}},r)).catch(x=>{o&&m(x)})||a,u()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Hn(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,i)=>{await this.connect(e).then(r).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Dv())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const r=e.sort((i,n)=>i.publishedAt-n.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n,"Error while processing batch message event: "+n?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const n=Wt(X.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,s)}this.events.emit(Qt.message,e),await this.recordMessageEvent(e)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(i,n)=>{const s=()=>{n(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(di.disconnect,s),await Hn(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{n(o)}).finally(()=>{this.provider.off(di.disconnect,s),clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(di.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(di.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const n=i;this.logger.warn({},n.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(i=>setTimeout(i,X.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,n,s;if(ll())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(n=(i=this.provider)==null?void 0:i.connection)==null?void 0:n.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new ui(new uI(c_({sdkVersion:Mu,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:r,message:i}=e;await this.messages.set(r,i)}async shouldIgnoreMessageEvent(e){const{topic:r,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.warn(`Ignoring message for non-subscribed topic ${r}`),!0;const n=this.messages.has(r,i);return n&&this.logger.warn(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Iu(e)){if(!e.method.endsWith(MI))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:o}=r.data,a={topic:i,message:n,publishedAt:s,transportType:St.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Lm({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Rl(e)&&this.events.emit(Qt.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Qt.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=Cl(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(di.payload,this.onPayloadHandler),this.provider.off(di.connect,this.onConnectHandler),this.provider.off(di.disconnect,this.onDisconnectHandler),this.provider.off(di.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Dv();JE(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(i=>this.logger.error(i,i?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),clearTimeout(this.pingTimeout),this.events.emit(Qt.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&(this.reconnectTimeout||this.connectPromise||(this.reconnectTimeout=setTimeout(async()=>{clearTimeout(this.reconnectTimeout),await this.transportOpen().catch(e=>this.logger.error(e,e?.message))},X.toMiliseconds(PI))))}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.transportOpen()}}var KM=Object.defineProperty,Bm=Object.getOwnPropertySymbols,GM=Object.prototype.hasOwnProperty,JM=Object.prototype.propertyIsEnumerable,Lu=(t,e,r)=>e in t?KM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Um=(t,e)=>{for(var r in e||(e={}))GM.call(e,r)&&Lu(t,r,e[r]);if(Bm)for(var r of Bm(e))JM.call(e,r)&&Lu(t,r,e[r]);return t},Fr=(t,e,r)=>Lu(t,typeof e!="symbol"?e+"":e,r);class Rs extends gS{constructor(e,r,i,n=Ji,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,Fr(this,"map",new Map),Fr(this,"version",OI),Fr(this,"cached",[]),Fr(this,"initialized",!1),Fr(this,"getKey"),Fr(this,"storagePrefix",Ji),Fr(this,"recentlyDeleted",[]),Fr(this,"recentlyDeletedLimit",200),Fr(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Sr(o)?this.map.set(this.getKey(o),o):IE(o)?this.map.set(o.id,o):AE(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Fr(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),Fr(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Fr(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>dI(a[c],o[c]))):this.values)),Fr(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Um(Um({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Fr(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=Ir(r,this.name),this.storagePrefix=n,this.getKey=s}get context(){return Tr(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())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:n}=ee("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:i}=ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}var ZM=Object.defineProperty,YM=(t,e,r)=>e in t?ZM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ne=(t,e,r)=>YM(t,typeof e!="symbol"?e+"":e,r);class XM{constructor(e,r){this.core=e,this.logger=r,Ne(this,"name",TI),Ne(this,"version",FI),Ne(this,"events",new nr.exports),Ne(this,"pairings"),Ne(this,"initialized",!1),Ne(this,"storagePrefix",Ji),Ne(this,"ignoredPayloadTypes",[pn]),Ne(this,"registeredMethods",[]),Ne(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Ne(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),Ne(this,"create",async i=>{this.isInitialized();const n=hu(),s=await this.core.crypto.setSymKey(n),o=Wt(X.FIVE_MINUTES),a={protocol:pm},c={topic:s,expiry:o,relay:a,active:!1,methods:i?.methods},l=$v({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:a,expiryTimestamp:o,methods:i?.methods});return this.events.emit(Os.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:i?.transportType}),{topic:s,uri:l}}),Ne(this,"pair",async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i?.uri,trace:[Zi.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=Ev(i.uri);n.props.properties.topic=s,n.addTrace(Zi.pairing_uri_validation_success),n.addTrace(Zi.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),n.addTrace(Zi.existing_pairing),u.active)throw n.setError(yn.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(Zi.pairing_not_expired)}const m=c||Wt(X.FIVE_MINUTES),x={topic:s,relay:a,expiry:m,active:!1,methods:l};this.core.expirer.set(s,m),await this.pairings.set(s,x),n.addTrace(Zi.store_new_pairing),i.activatePairing&&await this.activate({topic:s}),this.events.emit(Os.create,x),n.addTrace(Zi.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),n.addTrace(Zi.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(yn.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(S){throw n.setError(yn.subscribe_pairing_topic_failure),S}return n.addTrace(Zi.subscribe_pairing_topic_success),x}),Ne(this,"activate",async({topic:i})=>{this.isInitialized();const n=Wt(X.FIVE_MINUTES);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})}),Ne(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:n}=i;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=$s();this.events.once(Oe("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),Ne(this,"updateExpiry",async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})}),Ne(this,"updateMetadata",async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})}),Ne(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Ne(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:n}=i;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",wt("USER_DISCONNECTED")),await this.deletePairing(n))}),Ne(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:n,relay:s,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(n);return $v({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),Ne(this,"sendRequest",async(i,n,s)=>{const o=Zn(n,s),a=await this.core.crypto.encode(i,o),c=Ya[n].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),Ne(this,"sendResult",async(i,n,s)=>{const o=Cl(i,s),a=await this.core.crypto.encode(n,o),c=await this.core.history.get(n,i),l=Ya[c.request.method].res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),Ne(this,"sendError",async(i,n,s)=>{const o=Dl(i,s),a=await this.core.crypto.encode(n,o),c=await this.core.history.get(n,i),l=Ya[c.request.method]?Ya[c.request.method].res:Ya.unregistered_method.res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),Ne(this,"deletePairing",async(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,wt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])}),Ne(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(n=>Wn(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))}),Ne(this,"onRelayEventRequest",i=>{const{topic:n,payload:s}=i;switch(s.method){case"wc_pairingPing":return this.onPairingPingRequest(n,s);case"wc_pairingDelete":return this.onPairingDeleteRequest(n,s);default:return this.onUnknownRpcMethodRequest(n,s)}}),Ne(this,"onRelayEventResponse",async i=>{const{topic:n,payload:s}=i,o=(await this.core.history.get(n,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(n,s);default:return this.onUnknownRpcMethodResponse(o)}}),Ne(this,"onPairingPingRequest",async(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(Os.ping,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),Ne(this,"onPairingPingResponse",(i,n)=>{const{id:s}=n;setTimeout(()=>{Gi(n)?this.events.emit(Oe("pairing_ping",s),{}):fi(n)&&this.events.emit(Oe("pairing_ping",s),{error:n.error})},500)}),Ne(this,"onPairingDeleteRequest",async(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Os.delete,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),Ne(this,"onUnknownRpcMethodRequest",async(i,n)=>{const{id:s,method:o}=n;try{if(this.registeredMethods.includes(o))return;const a=wt("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,i,a),this.logger.error(a)}catch(a){await this.sendError(s,i,a),this.logger.error(a)}}),Ne(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(wt("WC_METHOD_UNSUPPORTED",i))}),Ne(this,"isValidPair",(i,n)=>{var s;if(!Rr(i)){const{message:a}=ee("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(yn.malformed_pairing_uri),new Error(a)}if(!SE(i.uri)){const{message:a}=ee("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(yn.malformed_pairing_uri),new Error(a)}const o=Ev(i?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=ee("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(yn.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=ee("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(yn.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&X.toMiliseconds(o?.expiryTimestamp)<Date.now()){n.setError(yn.pairing_expired);const{message:a}=ee("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Ne(this,"isValidPing",async i=>{if(!Rr(i)){const{message:s}=ee("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),Ne(this,"isValidDisconnect",async i=>{if(!Rr(i)){const{message:s}=ee("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),Ne(this,"isValidPairingTopic",async i=>{if(!Ut(i,!1)){const{message:n}=ee("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=ee("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(Wn(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=ee("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}}),this.core=e,this.logger=Ir(r,this.name),this.pairings=new Rs(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Tr(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Qt.message,async e=>{const{topic:r,message:i,transportType:n}=e;if(!this.pairings.keys.includes(r)||n===St.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const s=await this.core.crypto.decode(r,i);try{Iu(s)?(this.core.history.set(r,s),this.onRelayEventRequest({topic:r,payload:s})):Rl(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id))}catch(o){this.logger.error(o)}})}registerExpirerEvents(){this.core.expirer.on(pi.expired,async e=>{const{topic:r}=Sg(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Os.expire,{topic:r}))})}}var QM=Object.defineProperty,eP=(t,e,r)=>e in t?QM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,dr=(t,e,r)=>eP(t,typeof e!="symbol"?e+"":e,r);class tP extends fS{constructor(e,r){super(e,r),this.core=e,this.logger=r,dr(this,"records",new Map),dr(this,"events",new nr.exports.EventEmitter),dr(this,"name",LI),dr(this,"version",BI),dr(this,"cached",[]),dr(this,"initialized",!1),dr(this,"storagePrefix",Ji),dr(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)}),dr(this,"set",(i,n,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:n,chainId:s}),this.records.has(n.id))return;const o={id:n.id,topic:i,request:{method:n.method,params:n.params||null},chainId:s,expiry:Wt(X.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Mi.created,o)}),dr(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 n=await this.getRecord(i.id);typeof n.response>"u"&&(n.response=fi(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(Mi.updated,n))}),dr(this,"get",async(i,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:n}),await this.getRecord(n))),dr(this,"delete",(i,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(s=>{if(s.topic===i){if(typeof n<"u"&&s.id!==n)return;this.records.delete(s.id),this.events.emit(Mi.deleted,s)}}),this.persist()}),dr(this,"exists",async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1)),dr(this,"on",(i,n)=>{this.events.on(i,n)}),dr(this,"once",(i,n)=>{this.events.once(i,n)}),dr(this,"off",(i,n)=>{this.events.off(i,n)}),dr(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=Ir(r,this.name)}get context(){return Tr(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(r=>{if(typeof r.response<"u")return;const i={topic:r.topic,request:Zn(r.request.method,r.request.params,r.id),chainId:r.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 r=this.records.get(e);if(!r){const{message:i}=ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Mi.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Mi.created,e=>{const r=Mi.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Mi.updated,e=>{const r=Mi.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Mi.deleted,e=>{const r=Mi.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(Io.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{X.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Mi.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}var rP=Object.defineProperty,iP=(t,e,r)=>e in t?rP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,br=(t,e,r)=>iP(t,typeof e!="symbol"?e+"":e,r);class nP extends mS{constructor(e,r){super(e,r),this.core=e,this.logger=r,br(this,"expirations",new Map),br(this,"events",new nr.exports.EventEmitter),br(this,"name",UI),br(this,"version",qI),br(this,"cached",[]),br(this,"initialized",!1),br(this,"storagePrefix",Ji),br(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)}),br(this,"has",i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}}),br(this,"set",(i,n)=>{this.isInitialized();const s=this.formatTarget(i),o={target:s,expiry:n};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(pi.created,{target:s,expiration:o})}),br(this,"get",i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)}),br(this,"del",i=>{if(this.isInitialized(),this.has(i)){const n=this.formatTarget(i),s=this.getExpiration(n);this.expirations.delete(n),this.events.emit(pi.deleted,{target:n,expiration:s})}}),br(this,"on",(i,n)=>{this.events.on(i,n)}),br(this,"once",(i,n)=>{this.events.once(i,n)}),br(this,"off",(i,n)=>{this.events.off(i,n)}),br(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=Ir(r,this.name)}get context(){return Tr(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 l_(e);if(typeof e=="number")return h_(e);const{message:r}=ee("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(pi.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:i}=ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;X.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(pi.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Io.pulse,()=>this.checkExpirations()),this.events.on(pi.created,e=>{const r=pi.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(pi.expired,e=>{const r=pi.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(pi.deleted,e=>{const r=pi.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}var sP=Object.defineProperty,oP=(t,e,r)=>e in t?sP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jt=(t,e,r)=>oP(t,typeof e!="symbol"?e+"":e,r);class aP extends bS{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,jt(this,"name",jI),jt(this,"abortController"),jt(this,"isDevEnv"),jt(this,"verifyUrlV3",zI),jt(this,"storagePrefix",Ji),jt(this,"version",fm),jt(this,"publicKey"),jt(this,"fetchPromise"),jt(this,"init",async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&X.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),jt(this,"register",async n=>{if(!Oa()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=n,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const l=va(),u=this.startAbortTimer(X.ONE_SECOND*5),m=await new Promise((x,S)=>{const E=()=>{window.removeEventListener("message",R),l.body.removeChild(A),S("attestation aborted")};this.abortController.signal.addEventListener("abort",E);const A=l.createElement("iframe");A.src=c,A.style.display="none",A.addEventListener("error",E,{signal:this.abortController.signal});const R=O=>{if(O.data&&typeof O.data=="string")try{const C=JSON.parse(O.data);if(C.type==="verify_attestation"){if(Pf(C.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(A),this.abortController.signal.removeEventListener("abort",E),window.removeEventListener("message",R),x(C.attestation===null?"":C.attestation)}}catch(C){this.logger.warn(C)}};l.body.appendChild(A),window.addEventListener("message",R,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",m),m}catch(l){this.logger.warn(l)}return""}),jt(this,"resolve",async n=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=n;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Pf(s).payload.id!==a)return;const l=await this.isValidJwtAttestation(s);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(n?.verifyUrl);return this.fetchAttestation(o,c)}),jt(this,"fetchAttestation",async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const o=this.startAbortTimer(X.ONE_SECOND*5),a=await fetch(`${s}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),jt(this,"getVerifyUrl",n=>{let s=n||Xa;return HI.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Xa}`),s=Xa),s}),jt(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(X.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(n),await s.json()}catch(n){this.logger.warn(n)}}),jt(this,"persistPublicKey",async n=>{this.logger.debug("persisting public key to local storage",n),await this.store.setItem(this.storeKey,n),this.publicKey=n}),jt(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),jt(this,"isValidJwtAttestation",async n=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(n,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(n,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),jt(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),jt(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const n=await this.fetchPromise;return this.fetchPromise=void 0,n}),jt(this,"validateAttestation",(n,s)=>{const o=uE(n,s.publicKey),a={hasExpired:X.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Ir(r,this.name),this.abortController=new AbortController,this.isDevEnv=Wf(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Tr(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),X.toMiliseconds(e))}}var cP=Object.defineProperty,lP=(t,e,r)=>e in t?cP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qm=(t,e,r)=>lP(t,typeof e!="symbol"?e+"":e,r);class hP extends yS{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,qm(this,"context",WI),qm(this,"registerDeviceToken",async i=>{const{clientId:n,token:s,notificationType:o,enableEncrypted:a=!1}=i,c=`${VI}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:o,token:s,always_raw:a})})}),this.logger=Ir(r,this.context)}}var fP=Object.defineProperty,jm=Object.getOwnPropertySymbols,uP=Object.prototype.hasOwnProperty,dP=Object.prototype.propertyIsEnumerable,Bu=(t,e,r)=>e in t?fP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rc=(t,e)=>{for(var r in e||(e={}))uP.call(e,r)&&Bu(t,r,e[r]);if(jm)for(var r of jm(e))dP.call(e,r)&&Bu(t,r,e[r]);return t},er=(t,e,r)=>Bu(t,typeof e!="symbol"?e+"":e,r);class pP extends wS{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,er(this,"context",GI),er(this,"storagePrefix",Ji),er(this,"storageVersion",KI),er(this,"events",new Map),er(this,"shouldPersist",!1),er(this,"init",async()=>{if(!Wf())try{const n={eventId:Ag(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:_g(this.core.relayer.protocol,this.core.relayer.version,Mu)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}}),er(this,"createEvent",n=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=n,l=Ag(),u=this.core.projectId||"",m=Date.now(),x=rc({eventId:l,timestamp:m,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,x),this.shouldPersist=!0),x}),er(this,"getEvent",n=>{const{eventId:s,topic:o}=n;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return rc(rc({},a),this.setMethods(a.eventId))}),er(this,"deleteEvent",n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0}),er(this,"setEventListeners",()=>{this.core.heartbeat.on(Io.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{X.fromMiliseconds(Date.now())-X.fromMiliseconds(n.timestamp)>JI&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})}),er(this,"setMethods",n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)})),er(this,"addTrace",(n,s)=>{const o=this.events.get(n);o&&(o.props.properties.trace.push(s),this.events.set(n,o),this.shouldPersist=!0)}),er(this,"setError",(n,s)=>{const o=this.events.get(n);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(n,o),this.shouldPersist=!0)}),er(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),er(this,"restore",async()=>{try{const n=await this.core.storage.getItem(this.storageKey)||[];if(!n.length)return;n.forEach(s=>{this.events.set(s.eventId,rc(rc({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}}),er(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[s,o]of this.events)o.props.type&&n.push(o);if(n.length!==0)try{if((await this.sendEvent(n)).ok)for(const s of n)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),er(this,"sendEvent",async n=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${ZI}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Mu}${s}`,{method:"POST",body:JSON.stringify(n)})}),er(this,"getAppDomain",()=>wg().url),this.logger=Ir(r,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var gP=Object.defineProperty,km=Object.getOwnPropertySymbols,vP=Object.prototype.hasOwnProperty,mP=Object.prototype.propertyIsEnumerable,Uu=(t,e,r)=>e in t?gP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zm=(t,e)=>{for(var r in e||(e={}))vP.call(e,r)&&Uu(t,r,e[r]);if(km)for(var r of km(e))mP.call(e,r)&&Uu(t,r,e[r]);return t},It=(t,e,r)=>Uu(t,typeof e!="symbol"?e+"":e,r);class qu extends aS{constructor(e){var r;super(e),It(this,"protocol",hm),It(this,"version",fm),It(this,"name",Nl),It(this,"relayUrl"),It(this,"projectId"),It(this,"customStoragePrefix"),It(this,"events",new nr.exports.EventEmitter),It(this,"logger"),It(this,"heartbeat"),It(this,"relayer"),It(this,"crypto"),It(this,"storage"),It(this,"history"),It(this,"expirer"),It(this,"pairing"),It(this,"verify"),It(this,"echoClient"),It(this,"linkModeSupportedApps"),It(this,"eventClient"),It(this,"initialized",!1),It(this,"logChunkController"),It(this,"on",(o,a)=>this.events.on(o,a)),It(this,"once",(o,a)=>this.events.once(o,a)),It(this,"off",(o,a)=>this.events.off(o,a)),It(this,"removeListener",(o,a)=>this.events.removeListener(o,a)),It(this,"dispatchEnvelope",({topic:o,message:a,sessionExists:c})=>{if(!o||!a)return;const l={topic:o,message:a,publishedAt:Date.now(),transportType:St.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:c})}),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||gm,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Ol({level:typeof e?.logger=="string"&&e.logger?e.logger:mI.logger,name:Nl}),{logger:n,chunkLoggerController:s}=nS({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=s,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var o,a;(o=this.logChunkController)!=null&&o.downloadLogsBlobInBrowser&&((a=this.logChunkController)==null||a.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Ir(n,this.name),this.heartbeat=new gu,this.crypto=new $M(this,this.logger,e?.keychain),this.history=new tP(this,this.logger),this.expirer=new nP(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new O$(zm(zm({},bI),e?.storageOptions)),this.relayer=new VM({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new XM(this,this.logger),this.verify=new aP(this,this.logger,this.storage),this.echoClient=new hP(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new pP(this,this.logger,e?.telemetryEnabled)}static async init(e){const r=new qu(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(CI,i),r}get context(){return Tr(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(vm,this.linkModeSupportedApps))}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.linkModeSupportedApps=await this.storage.getItem(vm)||[],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 bP=qu,Hm="wc",Wm=2,Vm="client",ju=`${Hm}@${Wm}:${Vm}:`,ku={name:Vm,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Km="WALLETCONNECT_DEEPLINK_CHOICE",yP="proposal",Gm="Proposal expired",wP="session",Oo=X.SEVEN_DAYS,_P="engine",tr={wc_sessionPropose:{req:{ttl:X.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:X.ONE_DAY,prompt:!1,tag:1104},res:{ttl:X.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:X.ONE_DAY,prompt:!1,tag:1106},res:{ttl:X.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:X.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:X.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:X.ONE_DAY,prompt:!1,tag:1112},res:{ttl:X.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:X.ONE_DAY,prompt:!1,tag:1114},res:{ttl:X.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:X.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:X.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:X.FIVE_MINUTES,prompt:!1,tag:1119}}},zu={min:X.FIVE_MINUTES,max:X.SEVEN_DAYS},Qi={idle:"IDLE",active:"ACTIVE"},Jm={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},xP="request",EP=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],$P="wc",SP="auth",IP="authKeys",AP="pairingTopics",MP="requests",Ll=`${$P}@${1.5}:${SP}:`,Bl=`${Ll}:PUB_KEY`;var PP=Object.defineProperty,OP=Object.defineProperties,CP=Object.getOwnPropertyDescriptors,Zm=Object.getOwnPropertySymbols,DP=Object.prototype.hasOwnProperty,RP=Object.prototype.propertyIsEnumerable,Hu=(t,e,r)=>e in t?PP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,At=(t,e)=>{for(var r in e||(e={}))DP.call(e,r)&&Hu(t,r,e[r]);if(Zm)for(var r of Zm(e))RP.call(e,r)&&Hu(t,r,e[r]);return t},Lr=(t,e)=>OP(t,CP(e)),Z=(t,e,r)=>Hu(t,typeof e!="symbol"?e+"":e,r);class NP extends $S{constructor(e){super(e),Z(this,"name",_P),Z(this,"events",new nr.exports),Z(this,"initialized",!1),Z(this,"requestQueue",{state:Qi.idle,queue:[]}),Z(this,"sessionRequestQueue",{state:Qi.idle,queue:[]}),Z(this,"requestQueueDelay",X.ONE_SECOND),Z(this,"expectedPairingMethodMap",new Map),Z(this,"recentlyDeletedMap",new Map),Z(this,"recentlyDeletedLimit",200),Z(this,"relayMessageCache",[]),Z(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(tr)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},X.toMiliseconds(this.requestQueueDelay)))}),Z(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Lr(At({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:n,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,relays:c}=i;let l=n,u,m=!1;try{if(l){const T=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),m=T.active}}catch(T){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),T}if(!l||!m){const{topic:T,uri:U}=await this.client.core.pairing.create();l=T,u=U}if(!l){const{message:T}=ee("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(T)}const x=await this.client.core.crypto.generateKeyPair(),S=tr.wc_sessionPropose.req.ttl||X.FIVE_MINUTES,E=Wt(S),A=At({requiredNamespaces:s,optionalNamespaces:o,relays:c??[{protocol:pm}],proposer:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:E,pairingTopic:l},a&&{sessionProperties:a}),{reject:R,resolve:O,done:C}=$s(S,Gm);this.events.once(Oe("session_connect"),async({error:T,session:U})=>{if(T)R(T);else if(U){U.self.publicKey=x;const z=Lr(At({},U),{pairingTopic:A.pairingTopic,requiredNamespaces:A.requiredNamespaces,optionalNamespaces:A.optionalNamespaces,transportType:St.relay});await this.client.session.set(U.topic,z),await this.setExpiry(U.topic,U.expiry),l&&await this.client.core.pairing.updateMetadata({topic:l,metadata:U.peer.metadata}),this.cleanupDuplicatePairings(z),O(z)}});const N=await this.sendRequest({topic:l,method:"wc_sessionPropose",params:A,throwOnFailedPublish:!0});return await this.setProposal(N,At({id:N},A)),{uri:u,approval:C}}),Z(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(i){throw this.client.logger.error("pair() failed"),i}}),Z(this,"approve",async r=>{var i,n,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=r?.id)==null?void 0:i.toString(),trace:[Pi.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(V){throw o.setError(Cs.no_internet_connection),V}try{await this.isValidProposalId(r?.id)}catch(V){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(Cs.proposal_not_found),V}try{await this.isValidApprove(r)}catch(V){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Cs.session_approve_namespace_validation_failure),V}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,sessionConfig:m}=r,x=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:S,proposer:E,requiredNamespaces:A,optionalNamespaces:R}=x;let O=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:S});O||(O=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Pi.session_approve_started,properties:{topic:S,trace:[Pi.session_approve_started,Pi.session_namespaces_validation_success]}}));const C=await this.client.core.crypto.generateKeyPair(),N=E.publicKey,T=await this.client.core.crypto.generateSharedKey(C,N),U=At(At({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:C,metadata:this.client.metadata},expiry:Wt(Oo)},u&&{sessionProperties:u}),m&&{sessionConfig:m}),z=St.relay;O.addTrace(Pi.subscribing_session_topic);try{await this.client.core.relayer.subscribe(T,{transportType:z})}catch(V){throw O.setError(Cs.subscribe_session_topic_failure),V}O.addTrace(Pi.subscribe_session_topic_success);const W=Lr(At({},U),{topic:T,requiredNamespaces:A,optionalNamespaces:R,pairingTopic:S,acknowledged:!1,self:U.controller,peer:{publicKey:E.publicKey,metadata:E.metadata},controller:C,transportType:St.relay});await this.client.session.set(T,W),O.addTrace(Pi.store_session);try{O.addTrace(Pi.publishing_session_settle),await this.sendRequest({topic:T,method:"wc_sessionSettle",params:U,throwOnFailedPublish:!0}).catch(V=>{throw O?.setError(Cs.session_settle_publish_failure),V}),O.addTrace(Pi.session_settle_publish_success),O.addTrace(Pi.publishing_session_approve),await this.sendResult({id:a,topic:S,result:{relay:{protocol:c??"irn"},responderPublicKey:C},throwOnFailedPublish:!0}).catch(V=>{throw O?.setError(Cs.session_approve_publish_failure),V}),O.addTrace(Pi.session_approve_publish_success)}catch(V){throw this.client.logger.error(V),this.client.session.delete(T,wt("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(T),V}return this.client.core.eventClient.deleteEvent({eventId:O.eventId}),await this.client.core.pairing.updateMetadata({topic:S,metadata:E.metadata}),await this.client.proposal.delete(a,wt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:S}),await this.setExpiry(T,Wt(Oo)),{topic:T,acknowledged:()=>Promise.resolve(this.client.session.get(T))}}),Z(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:n}=r;let s;try{s=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}s&&(await this.sendError({id:i,topic:s,error:n,rpcOpts:tr.wc_sessionPropose.reject}),await this.client.proposal.delete(i,wt("USER_DISCONNECTED")))}),Z(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(m){throw this.client.logger.error("update() -> isValidUpdate() failed"),m}const{topic:i,namespaces:n}=r,{done:s,resolve:o,reject:a}=$s(),c=bn(),l=Ps().toString(),u=this.client.session.get(i).namespaces;return this.events.once(Oe("session_update",c),({error:m})=>{m?a(m):o()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(m=>{this.client.logger.error(m),this.client.session.update(i,{namespaces:u}),a(m)}),{acknowledged:s}}),Z(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=r,n=bn(),{done:s,resolve:o,reject:a}=$s();return this.events.once(Oe("session_extend",n),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,Wt(Oo)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),Z(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(O){throw this.client.logger.error("request() -> isValidRequest() failed"),O}const{chainId:i,request:n,topic:s,expiry:o=tr.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===St.relay&&await this.confirmOnlineStateOrThrow();const c=bn(),l=Ps().toString(),{done:u,resolve:m,reject:x}=$s(o,"Request expired. Please try again.");this.events.once(Oe("session_request",c),({error:O,result:C})=>{O?x(O):m(C)});const S="wc_sessionRequest",E=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(E)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:S,params:{request:Lr(At({},n),{expiryTimestamp:Wt(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:E}).catch(O=>x(O)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),await u();const A={request:Lr(At({},n),{expiryTimestamp:Wt(o)}),chainId:i},R=this.shouldSetTVF(S,A);return await Promise.all([new Promise(async O=>{await this.sendRequest(At({clientRpcId:c,relayRpcId:l,topic:s,method:S,params:A,expiry:o,throwOnFailedPublish:!0},R&&{tvf:this.getTVFParams(c,A)})).catch(C=>x(C)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),O()}),new Promise(async O=>{var C;if(!((C=a.sessionConfig)!=null&&C.disableDeepLink)){const N=await p_(this.client.core.storage,Km);await f_({id:c,topic:s,wcDeepLink:N})}O()}),u()]).then(O=>O[2])}),Z(this,"respond",async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:i,response:n}=r,{id:s}=n,o=this.client.session.get(i);o.transportType===St.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);Gi(n)?await this.sendResult({id:s,topic:i,result:n.result,throwOnFailedPublish:!0,appLink:a}):fi(n)&&await this.sendError({id:s,topic:i,error:n.error,appLink:a}),this.cleanupAfterResponse(r)}),Z(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:i}=r;if(this.client.session.keys.includes(i)){const n=bn(),s=Ps().toString(),{done:o,resolve:a,reject:c}=$s();this.events.once(Oe("session_ping",n),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),Z(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,o=Ps().toString(),a=bn();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),Z(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:i}=r;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:wt("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=ee("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}}),Z(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>EE(i,r)))),Z(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),Z(this,"authenticate",async(r,i)=>{var n;this.isInitialized(),this.isValidAuthenticate(r);const s=i&&this.client.core.linkModeSupportedApps.includes(i)&&((n=this.client.metadata.redirect)==null?void 0:n.linkMode),o=s?St.link_mode:St.relay;o===St.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:m,type:x,exp:S,nbf:E,methods:A=[],expiry:R}=r,O=[...r.resources||[]],{topic:C,uri:N}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:C,uri:N}});const T=await this.client.core.crypto.generateKeyPair(),U=bl(T);if(await Promise.all([this.client.auth.authKeys.set(Bl,{responseTopic:U,publicKey:T}),this.client.auth.pairingTopics.set(U,{topic:U,pairingTopic:C})]),await this.client.core.relayer.subscribe(U,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${C}`),A.length>0){const{namespace:$}=bo(a[0]);let y=ix($,"request",A);pl(O)&&(y=sx(y,O.pop())),O.push(y)}const z=R&&R>tr.wc_sessionAuthenticate.req.ttl?R:tr.wc_sessionAuthenticate.req.ttl,W={authPayload:{type:x??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:m,iat:new Date().toISOString(),exp:S,nbf:E,resources:O},requester:{publicKey:T,metadata:this.client.metadata},expiryTimestamp:Wt(z)},V={eip155:{chains:a,methods:[...new Set(["personal_sign",...A])],events:["chainChanged","accountsChanged"]}},B={requiredNamespaces:{},optionalNamespaces:V,relays:[{protocol:"irn"}],pairingTopic:C,proposer:{publicKey:T,metadata:this.client.metadata},expiryTimestamp:Wt(tr.wc_sessionPropose.req.ttl)},{done:K,resolve:M,reject:v}=$s(z,"Request expired"),g=async({error:$,session:y})=>{if(this.events.off(Oe("session_request",f),h),$)v($);else if(y){y.self.publicKey=T,await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),C&&await this.client.core.pairing.updateMetadata({topic:C,metadata:y.peer.metadata});const d=this.client.session.get(y.topic);await this.deleteProposal(p),M({session:d})}},h=async $=>{var y,d,w;if(await this.deletePendingAuthRequest(f,{message:"fulfilled",code:0}),$.error){const k=wt("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return $.error.code===k.code?void 0:(this.events.off(Oe("session_connect"),g),v($.error.message))}await this.deleteProposal(p),this.events.off(Oe("session_connect"),g);const{cacaos:b,responder:P}=$.result,q=[],I=[];for(const k of b){await kg({cacao:k,projectId:this.client.core.projectId})||(this.client.logger.error(k,"Signature verification failed"),v(wt("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:H}=k,Y=pl(H.resources),Q=[Yf(H.iss)],J=dl(H.iss);if(Y){const ae=Wg(Y),re=Vg(Y);q.push(...ae),Q.push(...re)}for(const ae of Q)I.push(`${ae}:${J}`)}const F=await this.client.core.crypto.generateSharedKey(T,P.publicKey);let j;q.length>0&&(j={topic:F,acknowledged:!0,self:{publicKey:T,metadata:this.client.metadata},peer:P,controller:P.publicKey,expiry:Wt(Oo),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:C,namespaces:Sv([...new Set(q)],[...new Set(I)]),transportType:o},await this.client.core.relayer.subscribe(F,{transportType:o}),await this.client.session.set(F,j),C&&await this.client.core.pairing.updateMetadata({topic:C,metadata:P.metadata}),j=this.client.session.get(F)),(y=this.client.metadata.redirect)!=null&&y.linkMode&&(d=P.metadata.redirect)!=null&&d.linkMode&&(w=P.metadata.redirect)!=null&&w.universal&&i&&(this.client.core.addLinkModeSupportedApp(P.metadata.redirect.universal),this.client.session.update(F,{transportType:St.link_mode})),M({auths:b,session:j})},f=bn(),p=bn();this.events.once(Oe("session_connect"),g),this.events.once(Oe("session_request",f),h);let _;try{if(s){const $=Zn("wc_sessionAuthenticate",W,f);this.client.core.history.set(C,$);const y=await this.client.core.crypto.encode("",$,{type:Ba,encoding:Fa});_=wl(i,C,y)}else await Promise.all([this.sendRequest({topic:C,method:"wc_sessionAuthenticate",params:W,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:f}),this.sendRequest({topic:C,method:"wc_sessionPropose",params:B,expiry:tr.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:p})])}catch($){throw this.events.off(Oe("session_connect"),g),this.events.off(Oe("session_request",f),h),$}return await this.setProposal(p,At({id:p},B)),await this.setAuthRequest(f,{request:Lr(At({},W),{verifyContext:{}}),pairingTopic:C,transportType:o}),{uri:_??N,response:K}}),Z(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Ds.authenticated_session_approve_started]}});try{this.isInitialized()}catch(R){throw s.setError(Qa.no_internet_connection),R}const o=this.getPendingAuthRequest(i);if(!o)throw s.setError(Qa.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||St.relay;a===St.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=bl(c),m={type:pn,receiverPublicKey:c,senderPublicKey:l},x=[],S=[];for(const R of n){if(!await kg({cacao:R,projectId:this.client.core.projectId})){s.setError(Qa.invalid_cacao);const U=wt("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:u,error:U,encodeOpts:m}),new Error(U.message)}s.addTrace(Ds.cacaos_verified);const{p:O}=R,C=pl(O.resources),N=[Yf(O.iss)],T=dl(O.iss);if(C){const U=Wg(C),z=Vg(C);x.push(...U),N.push(...z)}for(const U of N)S.push(`${U}:${T}`)}const E=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Ds.create_authenticated_session_topic);let A;if(x?.length>0){A={topic:E,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Wt(Oo),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Sv([...new Set(x)],[...new Set(S)]),transportType:a},s.addTrace(Ds.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(E,{transportType:a})}catch(R){throw s.setError(Qa.subscribe_authenticated_session_topic_failure),R}s.addTrace(Ds.subscribe_authenticated_session_topic_success),await this.client.session.set(E,A),s.addTrace(Ds.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Ds.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:i,result:{cacaos:n,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:m,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(R){throw s.setError(Qa.authenticated_session_approve_publish_failure),R}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:A}}),Z(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:i,reason:n}=r,s=this.getPendingAuthRequest(i);if(!s)throw new Error(`Could not find pending auth request with id ${i}`);s.transportType===St.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=bl(o),l={type:pn,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:n,encodeOpts:l,rpcOpts:tr.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,wt("USER_DISCONNECTED"))}),Z(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:n}=r;return zg(i,n)}),Z(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),Z(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.pairingTopic),n=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==i.topic});if(n.length===0)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),Z(this,"deleteSession",async r=>{var i;const{topic:n,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,wt("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),s||this.client.core.expirer.del(n),this.client.core.storage.removeItem(Km).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===n&&this.deletePendingSessionRequest(l.id,wt("USER_DISCONNECTED"))}),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=Qi.idle),o&&this.client.events.emit("session_delete",{id:a,topic:n})}),Z(this,"deleteProposal",async(r,i)=>{if(i)try{const n=this.client.proposal.get(r),s=this.client.core.eventClient.getEvent({topic:n.pairingTopic});s?.setError(Cs.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,wt("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),Z(this,"deletePendingSessionRequest",async(r,i,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),n&&(this.sessionRequestQueue.state=Qi.idle,this.client.events.emit("session_request_expire",{id:r}))}),Z(this,"deletePendingAuthRequest",async(r,i,n=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)])}),Z(this,"setExpiry",async(r,i)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,i),await this.client.session.update(r,{expiry:i}))}),Z(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,Wt(tr.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),Z(this,"setAuthRequest",async(r,i)=>{const{request:n,pairingTopic:s,transportType:o=St.relay}=i;this.client.core.expirer.set(r,n.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:r,pairingTopic:s,verifyContext:n.verifyContext,transportType:o})}),Z(this,"setPendingSessionRequest",async r=>{const{id:i,topic:n,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||Wt(tr.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:n,params:s,verifyContext:o})}),Z(this,"sendRequest",async r=>{const{topic:i,method:n,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:m}=r,x=Zn(n,s,c);let S;const E=!!u;try{const O=E?Fa:Jn;S=await this.client.core.crypto.encode(i,x,{encoding:O})}catch(O){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),O}let A;if(EP.includes(n)){const O=gn(JSON.stringify(x)),C=gn(S);A=await this.client.core.verify.register({id:C,decryptedId:O})}const R=tr[n].req;if(R.attestation=A,o&&(R.ttl=o),a&&(R.id=a),this.client.core.history.set(i,x),E){const O=wl(u,i,S);await global.Linking.openURL(O,this.client.name)}else{const O=tr[n].req;o&&(O.ttl=o),a&&(O.id=a),O.tvf=Lr(At({},m),{correlationId:x.id}),l?(O.internal=Lr(At({},O.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,S,O)):this.client.core.relayer.publish(i,S,O).catch(C=>this.client.logger.error(C))}return x.id}),Z(this,"sendResult",async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,l=Cl(i,s);let u;const m=c&&typeof(global==null?void 0:global.Linking)<"u";try{const E=m?Fa:Jn;u=await this.client.core.crypto.encode(n,l,Lr(At({},a||{}),{encoding:E}))}catch(E){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),E}let x,S;try{x=await this.client.core.history.get(n,i);const E=x.request;try{this.shouldSetTVF(E.method,E.params)&&(S=this.getTVFParams(i,E.params,s))}catch(A){this.client.logger.warn("sendResult() -> getTVFParams() failed",A)}}catch(E){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),E}if(m){const E=wl(c,n,u);await global.Linking.openURL(E,this.client.name)}else{const E=tr[x.request.method].res;E.tvf=Lr(At({},S),{correlationId:i}),o?(E.internal=Lr(At({},E.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,u,E)):this.client.core.relayer.publish(n,u,E).catch(A=>this.client.logger.error(A))}await this.client.core.history.resolve(l)}),Z(this,"sendError",async r=>{const{id:i,topic:n,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,l=Dl(i,s);let u;const m=c&&typeof(global==null?void 0:global.Linking)<"u";try{const S=m?Fa:Jn;u=await this.client.core.crypto.encode(n,l,Lr(At({},o||{}),{encoding:S}))}catch(S){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),S}let x;try{x=await this.client.core.history.get(n,i)}catch(S){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),S}if(m){const S=wl(c,n,u);await global.Linking.openURL(S,this.client.name)}else{const S=a||tr[x.request.method].res;this.client.core.relayer.publish(n,u,S)}await this.client.core.history.resolve(l)}),Z(this,"cleanup",async()=>{const r=[],i=[];this.client.session.getAll().forEach(n=>{let s=!1;Wn(n.expiry)&&(s=!0),this.client.core.crypto.keychain.has(n.topic)||(s=!0),s&&r.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{Wn(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...r.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])}),Z(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),Z(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Qi.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=Qi.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=Qi.idle}),Z(this,"processRequest",async r=>{const{topic:i,payload:n,attestation:s,transportType:o,encryptedId:a}=r,c=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),Z(this,"onRelayEventResponse",async r=>{const{topic:i,payload:n,transportType:s}=r,o=(await this.client.core.history.get(i,n.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n,s);case"wc_sessionSettle":return this.onSessionSettleResponse(i,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,n);case"wc_sessionExtend":return this.onSessionExtendResponse(i,n);case"wc_sessionPing":return this.onSessionPingResponse(i,n);case"wc_sessionRequest":return this.onSessionRequestResponse(i,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,n);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),Z(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:n}=ee("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)}),Z(this,"shouldIgnorePairingRequest",r=>{const{topic:i,requestMethod:n}=r,s=this.expectedPairingMethodMap.get(i);return!s||s.includes(n)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),Z(this,"onSessionProposeRequest",async r=>{const{topic:i,payload:n,attestation:s,encryptedId:o}=r,{params:a,id:c}=n;try{const l=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(yn.proposal_listener_not_found)),this.isValidConnect(At({},n.params));const u=a.expiryTimestamp||Wt(tr.wc_sessionPropose.req.ttl),m=At({id:c,pairingTopic:i,expiryTimestamp:u},a);await this.setProposal(c,m);const x=await this.getVerifyContext({attestationId:s,hash:gn(JSON.stringify(n)),encryptedId:o,metadata:m.proposer.metadata});l?.addTrace(Zi.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:m,verifyContext:x})}catch(l){await this.sendError({id:c,topic:i,error:l,rpcOpts:tr.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),Z(this,"onSessionProposeResponse",async(r,i,n)=>{const{id:s}=i;if(Gi(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:u});const m=await this.client.core.relayer.subscribe(u,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:m}),await this.client.core.pairing.activate({topic:r})}else if(fi(i)){await this.client.proposal.delete(s,wt("USER_DISCONNECTED"));const o=Oe("session_connect");if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(Oe("session_connect"),{error:i.error})}}),Z(this,"onSessionSettleRequest",async(r,i)=>{const{id:n,params:s}=i;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,sessionConfig:m}=i.params,x=Lr(At(At({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:"",requiredNamespaces:{},optionalNamespaces:{},controller:a.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),m&&{sessionConfig:m}),{transportType:St.relay}),S=Oe("session_connect");if(this.events.listenerCount(S)===0)throw new Error(`emitting ${S} without any listeners 997`);this.events.emit(Oe("session_connect"),{session:x}),await this.sendResult({id:i.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),Z(this,"onSessionSettleResponse",async(r,i)=>{const{id:n}=i;Gi(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(Oe("session_approve",n),{})):fi(i)&&(await this.client.session.delete(r,wt("USER_DISCONNECTED")),this.events.emit(Oe("session_approve",n),{error:i.error}))}),Z(this,"onSessionUpdateRequest",async(r,i)=>{const{params:n,id:s}=i;try{const o=`${r}_session_update`,a=Ha.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:wt("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(At({topic:r},n));try{Ha.set(o,s),await this.client.session.update(r,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(c){throw Ha.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:n})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),Z(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),Z(this,"onSessionUpdateResponse",(r,i)=>{const{id:n}=i,s=Oe("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Gi(i)?this.events.emit(Oe("session_update",n),{}):fi(i)&&this.events.emit(Oe("session_update",n),{error:i.error})}),Z(this,"onSessionExtendRequest",async(r,i)=>{const{id:n}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,Wt(Oo)),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),Z(this,"onSessionExtendResponse",(r,i)=>{const{id:n}=i,s=Oe("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Gi(i)?this.events.emit(Oe("session_extend",n),{}):fi(i)&&this.events.emit(Oe("session_extend",n),{error:i.error})}),Z(this,"onSessionPingRequest",async(r,i)=>{const{id:n}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),Z(this,"onSessionPingResponse",(r,i)=>{const{id:n}=i,s=Oe("session_ping",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);setTimeout(()=>{Gi(i)?this.events.emit(Oe("session_ping",n),{}):fi(i)&&this.events.emit(Oe("session_ping",n),{error:i.error})},500)}),Z(this,"onSessionDeleteRequest",async(r,i)=>{const{id:n}=i;try{this.isValidDisconnect({topic:r,reason:i.params}),Promise.all([new Promise(s=>{this.client.core.relayer.once(Qt.publish,async()=>{s(await this.deleteSession({topic:r,id:n}))})}),this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:wt("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),Z(this,"onSessionRequest",async r=>{var i,n,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=r,{id:m,params:x}=a;try{await this.isValidRequest(At({topic:o},x));const S=this.client.session.get(o),E=await this.getVerifyContext({attestationId:c,hash:gn(JSON.stringify(Zn("wc_sessionRequest",x,m))),encryptedId:l,metadata:S.peer.metadata,transportType:u}),A={id:m,topic:o,params:x,verifyContext:E};await this.setPendingSessionRequest(A),u===St.link_mode&&(i=S.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((n=S.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(A):(this.addSessionRequestToSessionRequestQueue(A),this.processSessionRequestQueue())}catch(S){await this.sendError({id:m,topic:o,error:S}),this.client.logger.error(S)}}),Z(this,"onSessionRequestResponse",(r,i)=>{const{id:n}=i,s=Oe("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Gi(i)?this.events.emit(Oe("session_request",n),{result:i.result}):fi(i)&&this.events.emit(Oe("session_request",n),{error:i.error})}),Z(this,"onSessionEventRequest",async(r,i)=>{const{id:n,params:s}=i;try{const o=`${r}_session_event_${s.event.name}`,a=Ha.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(At({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),Ha.set(o,n)}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),Z(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),Gi(i)?this.events.emit(Oe("session_request",n),{result:i.result}):fi(i)&&this.events.emit(Oe("session_request",n),{error:i.error})}),Z(this,"onSessionAuthenticateRequest",async r=>{var i;const{topic:n,payload:s,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:l,authPayload:u,expiryTimestamp:m}=s.params,x=await this.getVerifyContext({attestationId:o,hash:gn(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),S={requester:l,pairingTopic:n,id:s.id,authPayload:u,verifyContext:x,expiryTimestamp:m};await this.setAuthRequest(s.id,{request:S,pairingTopic:n,transportType:c}),c===St.link_mode&&(i=l.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:s.params,id:s.id,verifyContext:x})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,m=await this.client.core.crypto.generateKeyPair(),x=this.getAppLinkIfEnabled(s.params.requester.metadata,c),S={type:pn,receiverPublicKey:u,senderPublicKey:m};await this.sendError({id:s.id,topic:n,error:l,encodeOpts:S,rpcOpts:tr.wc_sessionAuthenticate.autoReject,appLink:x})}}),Z(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),Z(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Qi.idle,this.processSessionRequestQueue()},X.toMiliseconds(this.requestQueueDelay))}),Z(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:i})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{const o=s.request.id,a=Oe("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Oe("session_request",s.request.id),{error:i})})}),Z(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Qi.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Qi.active,this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}}),Z(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),Z(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(n=>n.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:Zn("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})}),Z(this,"isValidConnect",async r=>{if(!Rr(r)){const{message:c}=ee("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(c)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:o,relays:a}=r;if(Sr(i)||await this.isValidPairingTopic(i),!TE(a,!0)){const{message:c}=ee("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(c)}!Sr(n)&&za(n)!==0&&this.validateNamespaces(n,"requiredNamespaces"),!Sr(s)&&za(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),Sr(o)||this.validateSessionProps(o,"sessionProperties")}),Z(this,"validateNamespaces",(r,i)=>{const n=NE(r,"connect()",i);if(n)throw new Error(n.message)}),Z(this,"isValidApprove",async r=>{if(!Rr(r))throw new Error(ee("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:n,relayProtocol:s,sessionProperties:o}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const a=this.client.proposal.get(i),c=du(n,"approve()");if(c)throw new Error(c.message);const l=Ov(a.requiredNamespaces,n,"approve()");if(l)throw new Error(l.message);if(!Ut(s,!0)){const{message:u}=ee("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(u)}Sr(o)||this.validateSessionProps(o,"sessionProperties")}),Z(this,"isValidReject",async r=>{if(!Rr(r)){const{message:s}=ee("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:i,reason:n}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!LE(n)){const{message:s}=ee("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}}),Z(this,"isValidSessionSettleRequest",r=>{if(!Rr(r)){const{message:l}=ee("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:i,controller:n,namespaces:s,expiry:o}=r;if(!Mv(i)){const{message:l}=ee("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=ME(n,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=du(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Wn(o)){const{message:l}=ee("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),Z(this,"isValidUpdate",async r=>{if(!Rr(r)){const{message:c}=ee("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:i,namespaces:n}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),o=du(n,"update()");if(o)throw new Error(o.message);const a=Ov(s.requiredNamespaces,n,"update()");if(a)throw new Error(a.message)}),Z(this,"isValidExtend",async r=>{if(!Rr(r)){const{message:n}=ee("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(n)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),Z(this,"isValidRequest",async r=>{if(!Rr(r)){const{message:c}=ee("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:i,request:n,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!Pv(a,s)){const{message:c}=ee("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!BE(n)){const{message:c}=ee("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(c)}if(!jE(a,s,n.method)){const{message:c}=ee("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(c)}if(o&&!WE(o,zu)){const{message:c}=ee("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${zu.min} and ${zu.max}`);throw new Error(c)}}),Z(this,"isValidRespond",async r=>{var i;if(!Rr(r)){const{message:o}=ee("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:n,response:s}=r;try{await this.isValidSessionTopic(n)}catch(o){throw(i=r?.response)!=null&&i.id&&this.cleanupAfterResponse(r),o}if(!UE(s)){const{message:o}=ee("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),Z(this,"isValidPing",async r=>{if(!Rr(r)){const{message:n}=ee("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),Z(this,"isValidEmit",async r=>{if(!Rr(r)){const{message:a}=ee("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:i,event:n,chainId:s}=r;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!Pv(o,s)){const{message:a}=ee("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!qE(n)){const{message:a}=ee("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}if(!kE(o,s,n.name)){const{message:a}=ee("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}}),Z(this,"isValidDisconnect",async r=>{if(!Rr(r)){const{message:n}=ee("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),Z(this,"isValidAuthenticate",r=>{const{chains:i,uri:n,domain:s,nonce:o}=r;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!Ut(n,!1))throw new Error("uri is required parameter");if(!Ut(s,!1))throw new Error("domain is required parameter");if(!Ut(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>bo(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=bo(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),Z(this,"getVerifyContext",async r=>{const{attestationId:i,hash:n,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||Xa,validation:"UNKNOWN",origin:o.url||""}};try{if(a===St.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:i,hash:n,encryptedId:s,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),Z(this,"validateSessionProps",(r,i)=>{Object.values(r).forEach(n=>{if(!Ut(n,!1)){const{message:s}=ee("MISSING_OR_INVALID",`${i} must be in Record<string, string> format. Received: ${JSON.stringify(n)}`);throw new Error(s)}})}),Z(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),Z(this,"addToRecentlyDeleted",(r,i)=>{if(this.recentlyDeletedMap.set(r,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let n=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(n++>=s)break;this.recentlyDeletedMap.delete(o)}}}),Z(this,"checkRecentlyDeleted",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:n}=ee("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(n)}}),Z(this,"isLinkModeEnabled",(r,i)=>{var n,s,o,a,c,l,u,m,x;return!r||i!==St.link_mode?!1:((s=(n=this.client.metadata)==null?void 0:n.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=r?.redirect)==null?void 0:u.universal)!==void 0&&((m=r?.redirect)==null?void 0:m.universal)!==""&&((x=r?.redirect)==null?void 0:x.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),Z(this,"getAppLinkIfEnabled",(r,i)=>{var n;return this.isLinkModeEnabled(r,i)?(n=r?.redirect)==null?void 0:n.universal:void 0}),Z(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Ig(r,"topic")||"",n=decodeURIComponent(Ig(r,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:St.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})}),Z(this,"registerLinkModeListeners",async()=>{var r;if(Wf()||zn()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const i=global==null?void 0:global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await i.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}),Z(this,"shouldSetTVF",(r,i)=>{if(!i||r!=="wc_sessionRequest")return!1;const{request:n}=i;return Object.keys(Jm).includes(n.method)}),Z(this,"getTVFParams",(r,i,n)=>{var s,o;try{const a=i.request.method,c=this.extractTxHashesFromResult(a,n);return Lr(At({correlationId:r,rpcMethods:[a],chainId:i.chainId},this.isValidContractData(i.request.params)&&{contractAddresses:[(o=(s=i.request.params)==null?void 0:s[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),Z(this,"isValidContractData",r=>{var i;if(!r)return!1;try{const n=r?.data||((i=r?.[0])==null?void 0:i.data);if(!n.startsWith("0x"))return!1;const s=n.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),Z(this,"extractTxHashesFromResult",(r,i)=>{try{const n=Jm[r];if(typeof i=="string")return[i];const s=i[n.key];if(Wi(s))return s;if(typeof s=="string")return[s]}catch(n){this.client.logger.warn("Error extracting tx hashes from result",n)}return[]})}isInitialized(){if(!this.initialized){const{message:e}=ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Qt.message,e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):this.onRelayMessage(e)})}async onRelayMessage(e){const{topic:r,message:i,attestation:n,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Bl)?this.client.auth.authKeys.get(Bl):{responseTopic:void 0,publicKey:void 0},a=await this.client.core.crypto.decode(r,i,{receiverPublicKey:o,encoding:s===St.link_mode?Fa:Jn});try{Iu(a)?(this.client.core.history.set(r,a),this.onRelayEventRequest({topic:r,payload:a,attestation:n,transportType:s,encryptedId:gn(i)})):Rl(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s})}catch(c){this.client.logger.error(c)}}registerExpirerEvents(){this.client.core.expirer.on(pi.expired,async e=>{const{topic:r,id:i}=Sg(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,ee("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,ee("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(Os.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Os.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Ut(e,!1)){const{message:r}=ee("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=ee("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(Wn(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=ee("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!Ut(e,!1)){const{message:r}=ee("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=ee("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(Wn(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=ee("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=ee("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),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(Ut(e,!1)){const{message:r}=ee("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=ee("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!FE(e)){const{message:r}=ee("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=ee("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(Wn(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=ee("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class TP extends Rs{constructor(e,r){super(e,r,yP,ju),this.core=e,this.logger=r}}class FP extends Rs{constructor(e,r){super(e,r,wP,ju),this.core=e,this.logger=r}}class LP extends Rs{constructor(e,r){super(e,r,xP,ju,i=>i.id),this.core=e,this.logger=r}}class BP extends Rs{constructor(e,r){super(e,r,IP,Ll,()=>Bl),this.core=e,this.logger=r}}class UP extends Rs{constructor(e,r){super(e,r,AP,Ll),this.core=e,this.logger=r}}class qP extends Rs{constructor(e,r){super(e,r,MP,Ll,i=>i.id),this.core=e,this.logger=r}}var jP=Object.defineProperty,kP=(t,e,r)=>e in t?jP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wu=(t,e,r)=>kP(t,typeof e!="symbol"?e+"":e,r);class zP{constructor(e,r){this.core=e,this.logger=r,Wu(this,"authKeys"),Wu(this,"pairingTopics"),Wu(this,"requests"),this.authKeys=new BP(this.core,this.logger),this.pairingTopics=new UP(this.core,this.logger),this.requests=new qP(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var HP=Object.defineProperty,WP=(t,e,r)=>e in t?HP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Te=(t,e,r)=>WP(t,typeof e!="symbol"?e+"":e,r);class Vu extends ES{constructor(e){super(e),Te(this,"protocol",Hm),Te(this,"version",Wm),Te(this,"name",ku.name),Te(this,"metadata"),Te(this,"core"),Te(this,"logger"),Te(this,"events",new nr.exports.EventEmitter),Te(this,"engine"),Te(this,"session"),Te(this,"proposal"),Te(this,"pendingRequest"),Te(this,"auth"),Te(this,"signConfig"),Te(this,"on",(i,n)=>this.events.on(i,n)),Te(this,"once",(i,n)=>this.events.once(i,n)),Te(this,"off",(i,n)=>this.events.off(i,n)),Te(this,"removeListener",(i,n)=>this.events.removeListener(i,n)),Te(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),Te(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"update",async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"request",async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"find",i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),Te(this,"authenticate",async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}}),Te(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),Te(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),this.name=e?.name||ku.name,this.metadata=e?.metadata||wg(),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Vi(Ol({level:e?.logger||ku.logger}));this.core=e?.core||new bP(e),this.logger=Ir(r,this.name),this.session=new FP(this.core,this.logger),this.proposal=new TP(this.core,this.logger),this.pendingRequest=new LP(this.core,this.logger),this.engine=new NP(this),this.auth=new zP(this.core,this.logger)}static async init(e){const r=new Vu(e);return await r.initialize(),r}get context(){return Tr(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.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},X.toMiliseconds(X.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var Ku={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof Ft<"u"&&Ft,i=function(){function s(){this.fetch=!1,this.DOMException=r.DOMException}return s.prototype=r,new s}();(function(s){(function(o){var a=typeof s<"u"&&s||typeof self<"u"&&self||typeof Ft<"u"&&Ft||{},c={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 l(f){return f&&DataView.prototype.isPrototypeOf(f)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],m=ArrayBuffer.isView||function(f){return f&&u.indexOf(Object.prototype.toString.call(f))>-1};function x(f){if(typeof f!="string"&&(f=String(f)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(f)||f==="")throw new TypeError('Invalid character in header field name: "'+f+'"');return f.toLowerCase()}function S(f){return typeof f!="string"&&(f=String(f)),f}function E(f){var p={next:function(){var _=f.shift();return{done:_===void 0,value:_}}};return c.iterable&&(p[Symbol.iterator]=function(){return p}),p}function A(f){this.map={},f instanceof A?f.forEach(function(p,_){this.append(_,p)},this):Array.isArray(f)?f.forEach(function(p){if(p.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+p.length);this.append(p[0],p[1])},this):f&&Object.getOwnPropertyNames(f).forEach(function(p){this.append(p,f[p])},this)}A.prototype.append=function(f,p){f=x(f),p=S(p);var _=this.map[f];this.map[f]=_?_+", "+p:p},A.prototype.delete=function(f){delete this.map[x(f)]},A.prototype.get=function(f){return f=x(f),this.has(f)?this.map[f]:null},A.prototype.has=function(f){return this.map.hasOwnProperty(x(f))},A.prototype.set=function(f,p){this.map[x(f)]=S(p)},A.prototype.forEach=function(f,p){for(var _ in this.map)this.map.hasOwnProperty(_)&&f.call(p,this.map[_],_,this)},A.prototype.keys=function(){var f=[];return this.forEach(function(p,_){f.push(_)}),E(f)},A.prototype.values=function(){var f=[];return this.forEach(function(p){f.push(p)}),E(f)},A.prototype.entries=function(){var f=[];return this.forEach(function(p,_){f.push([_,p])}),E(f)},c.iterable&&(A.prototype[Symbol.iterator]=A.prototype.entries);function R(f){if(!f._noBody){if(f.bodyUsed)return Promise.reject(new TypeError("Already read"));f.bodyUsed=!0}}function O(f){return new Promise(function(p,_){f.onload=function(){p(f.result)},f.onerror=function(){_(f.error)}})}function C(f){var p=new FileReader,_=O(p);return p.readAsArrayBuffer(f),_}function N(f){var p=new FileReader,_=O(p),$=/charset=([A-Za-z0-9_-]+)/.exec(f.type),y=$?$[1]:"utf-8";return p.readAsText(f,y),_}function T(f){for(var p=new Uint8Array(f),_=new Array(p.length),$=0;$<p.length;$++)_[$]=String.fromCharCode(p[$]);return _.join("")}function U(f){if(f.slice)return f.slice(0);var p=new Uint8Array(f.byteLength);return p.set(new Uint8Array(f)),p.buffer}function z(){return this.bodyUsed=!1,this._initBody=function(f){this.bodyUsed=this.bodyUsed,this._bodyInit=f,f?typeof f=="string"?this._bodyText=f:c.blob&&Blob.prototype.isPrototypeOf(f)?this._bodyBlob=f:c.formData&&FormData.prototype.isPrototypeOf(f)?this._bodyFormData=f:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(f)?this._bodyText=f.toString():c.arrayBuffer&&c.blob&&l(f)?(this._bodyArrayBuffer=U(f.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(f)||m(f))?this._bodyArrayBuffer=U(f):this._bodyText=f=Object.prototype.toString.call(f):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof f=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(f)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var f=R(this);if(f)return f;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(){if(this._bodyArrayBuffer){var f=R(this);return f||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(c.blob)return this.blob().then(C);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var f=R(this);if(f)return f;if(this._bodyBlob)return N(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(T(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},c.formData&&(this.formData=function(){return this.text().then(K)}),this.json=function(){return this.text().then(JSON.parse)},this}var W=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function V(f){var p=f.toUpperCase();return W.indexOf(p)>-1?p:f}function B(f,p){if(!(this instanceof B))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');p=p||{};var _=p.body;if(f instanceof B){if(f.bodyUsed)throw new TypeError("Already read");this.url=f.url,this.credentials=f.credentials,p.headers||(this.headers=new A(f.headers)),this.method=f.method,this.mode=f.mode,this.signal=f.signal,!_&&f._bodyInit!=null&&(_=f._bodyInit,f.bodyUsed=!0)}else this.url=String(f);if(this.credentials=p.credentials||this.credentials||"same-origin",(p.headers||!this.headers)&&(this.headers=new A(p.headers)),this.method=V(p.method||this.method||"GET"),this.mode=p.mode||this.mode||null,this.signal=p.signal||this.signal||function(){if("AbortController"in a){var d=new AbortController;return d.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&_)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(_),(this.method==="GET"||this.method==="HEAD")&&(p.cache==="no-store"||p.cache==="no-cache")){var $=/([?&])_=[^&]*/;if($.test(this.url))this.url=this.url.replace($,"$1_="+new Date().getTime());else{var y=/\?/;this.url+=(y.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}B.prototype.clone=function(){return new B(this,{body:this._bodyInit})};function K(f){var p=new FormData;return f.trim().split("&").forEach(function(_){if(_){var $=_.split("="),y=$.shift().replace(/\+/g," "),d=$.join("=").replace(/\+/g," ");p.append(decodeURIComponent(y),decodeURIComponent(d))}}),p}function M(f){var p=new A,_=f.replace(/\r?\n[\t ]+/g," ");return _.split("\r").map(function($){return $.indexOf(`
44
44
  `)===0?$.substr(1,$.length):$}).forEach(function($){var y=$.split(":"),d=y.shift().trim();if(d){var w=y.join(":").trim();try{p.append(d,w)}catch(b){console.warn("Response "+b.message)}}}),p}z.call(B.prototype);function v(f,p){if(!(this instanceof v))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(p||(p={}),this.type="default",this.status=p.status===void 0?200:p.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=p.statusText===void 0?"":""+p.statusText,this.headers=new A(p.headers),this.url=p.url||"",this._initBody(f)}z.call(v.prototype),v.prototype.clone=function(){return new v(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new A(this.headers),url:this.url})},v.error=function(){var f=new v(null,{status:200,statusText:""});return f.ok=!1,f.status=0,f.type="error",f};var g=[301,302,303,307,308];v.redirect=function(f,p){if(g.indexOf(p)===-1)throw new RangeError("Invalid status code");return new v(null,{status:p,headers:{location:f}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(p,_){this.message=p,this.name=_;var $=Error(p);this.stack=$.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function h(f,p){return new Promise(function(_,$){var y=new B(f,p);if(y.signal&&y.signal.aborted)return $(new o.DOMException("Aborted","AbortError"));var d=new XMLHttpRequest;function w(){d.abort()}d.onload=function(){var q={statusText:d.statusText,headers:M(d.getAllResponseHeaders()||"")};y.url.indexOf("file://")===0&&(d.status<200||d.status>599)?q.status=200:q.status=d.status,q.url="responseURL"in d?d.responseURL:q.headers.get("X-Request-URL");var I="response"in d?d.response:d.responseText;setTimeout(function(){_(new v(I,q))},0)},d.onerror=function(){setTimeout(function(){$(new TypeError("Network request failed"))},0)},d.ontimeout=function(){setTimeout(function(){$(new TypeError("Network request timed out"))},0)},d.onabort=function(){setTimeout(function(){$(new o.DOMException("Aborted","AbortError"))},0)};function b(q){try{return q===""&&a.location.href?a.location.href:q}catch{return q}}if(d.open(y.method,b(y.url),!0),y.credentials==="include"?d.withCredentials=!0:y.credentials==="omit"&&(d.withCredentials=!1),"responseType"in d&&(c.blob?d.responseType="blob":c.arrayBuffer&&(d.responseType="arraybuffer")),p&&typeof p.headers=="object"&&!(p.headers instanceof A||a.Headers&&p.headers instanceof a.Headers)){var P=[];Object.getOwnPropertyNames(p.headers).forEach(function(q){P.push(x(q)),d.setRequestHeader(q,S(p.headers[q]))}),y.headers.forEach(function(q,I){P.indexOf(I)===-1&&d.setRequestHeader(I,q)})}else y.headers.forEach(function(q,I){d.setRequestHeader(I,q)});y.signal&&(y.signal.addEventListener("abort",w),d.onreadystatechange=function(){d.readyState===4&&y.signal.removeEventListener("abort",w)}),d.send(typeof y._bodyInit>"u"?null:y._bodyInit)})}return h.polyfill=!0,a.fetch||(a.fetch=h,a.Headers=A,a.Request=B,a.Response=v),o.Headers=A,o.Request=B,o.Response=v,o.fetch=h,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var n=r.fetch?r:i;e=n.fetch,e.default=n.fetch,e.fetch=n.fetch,e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response,t.exports=e})(Ku,Ku.exports);var Ym=Ly(Ku.exports),VP=Object.defineProperty,KP=Object.defineProperties,GP=Object.getOwnPropertyDescriptors,Xm=Object.getOwnPropertySymbols,JP=Object.prototype.hasOwnProperty,ZP=Object.prototype.propertyIsEnumerable,Qm=(t,e,r)=>e in t?VP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,eb=(t,e)=>{for(var r in e||(e={}))JP.call(e,r)&&Qm(t,r,e[r]);if(Xm)for(var r of Xm(e))ZP.call(e,r)&&Qm(t,r,e[r]);return t},tb=(t,e)=>KP(t,GP(e));const YP={Accept:"application/json","Content-Type":"application/json"},XP="POST",rb={headers:YP,method:XP},ib=10;class Ci{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new nr.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!im(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const r=ln(e),i=await(await Ym(this.url,tb(eb({},rb),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!im(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return n(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=ln({id:1,jsonrpc:"2.0",method:"test",params:[]});await Ym(e,tb(eb({},rb),{body:r}))}this.onOpen()}catch(r){const i=this.parseError(r);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 r=typeof e.data=="string"?ms(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=Dl(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return Yv(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>ib&&this.events.setMaxListeners(ib)}}const nb="error",QP="wss://relay.walletconnect.org",eO="wc",tO="universal_provider",sb=`${eO}@2:${tO}:`,ob="https://rpc.walletconnect.org/v1/",Co="generic",rO=`${ob}bundler`,gi={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Ul=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function iO(){this.__data__=[],this.size=0}var nO=iO;function sO(t,e){return t===e||t!==t&&e!==e}var ql=sO,oO=ql;function aO(t,e){for(var r=t.length;r--;)if(oO(t[r][0],e))return r;return-1}var jl=aO,cO=jl,lO=Array.prototype,hO=lO.splice;function fO(t){var e=this.__data__,r=cO(e,t);if(r<0)return!1;var i=e.length-1;return r==i?e.pop():hO.call(e,r,1),--this.size,!0}var uO=fO,dO=jl;function pO(t){var e=this.__data__,r=dO(e,t);return r<0?void 0:e[r][1]}var gO=pO,vO=jl;function mO(t){return vO(this.__data__,t)>-1}var bO=mO,yO=jl;function wO(t,e){var r=this.__data__,i=yO(r,t);return i<0?(++this.size,r.push([t,e])):r[i][1]=e,this}var _O=wO,xO=nO,EO=uO,$O=gO,SO=bO,IO=_O;function Do(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var i=t[e];this.set(i[0],i[1])}}Do.prototype.clear=xO,Do.prototype.delete=EO,Do.prototype.get=$O,Do.prototype.has=SO,Do.prototype.set=IO;var kl=Do,AO=kl;function MO(){this.__data__=new AO,this.size=0}var PO=MO;function OO(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}var CO=OO;function DO(t){return this.__data__.get(t)}var RO=DO;function NO(t){return this.__data__.has(t)}var TO=NO,FO=typeof Ul=="object"&&Ul&&Ul.Object===Object&&Ul,ab=FO,LO=ab,BO=typeof self=="object"&&self&&self.Object===Object&&self,UO=LO||BO||Function("return this")(),Ro=UO,qO=Ro,jO=qO.Symbol,cb=jO,lb=cb,hb=Object.prototype,kO=hb.hasOwnProperty,zO=hb.toString,ic=lb?lb.toStringTag:void 0;function HO(t){var e=kO.call(t,ic),r=t[ic];try{t[ic]=void 0;var i=!0}catch{}var n=zO.call(t);return i&&(e?t[ic]=r:delete t[ic]),n}var WO=HO,VO=Object.prototype,KO=VO.toString;function GO(t){return KO.call(t)}var JO=GO,fb=cb,ZO=WO,YO=JO,XO="[object Null]",QO="[object Undefined]",ub=fb?fb.toStringTag:void 0;function eC(t){return t==null?t===void 0?QO:XO:ub&&ub in Object(t)?ZO(t):YO(t)}var zl=eC;function tC(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var Ns=tC,rC=zl,iC=Ns,nC="[object AsyncFunction]",sC="[object Function]",oC="[object GeneratorFunction]",aC="[object Proxy]";function cC(t){if(!iC(t))return!1;var e=rC(t);return e==sC||e==oC||e==nC||e==aC}var Gu=cC,lC=Ro,hC=lC["__core-js_shared__"],fC=hC,Ju=fC,db=function(){var t=/[^.]+$/.exec(Ju&&Ju.keys&&Ju.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function uC(t){return!!db&&db in t}var dC=uC,pC=Function.prototype,gC=pC.toString;function vC(t){if(t!=null){try{return gC.call(t)}catch{}try{return t+""}catch{}}return""}var mC=vC,bC=Gu,yC=dC,wC=Ns,_C=mC,xC=/[\\^$.*+?()[\]{}|]/g,EC=/^\[object .+?Constructor\]$/,$C=Function.prototype,SC=Object.prototype,IC=$C.toString,AC=SC.hasOwnProperty,MC=RegExp("^"+IC.call(AC).replace(xC,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function PC(t){if(!wC(t)||yC(t))return!1;var e=bC(t)?MC:EC;return e.test(_C(t))}var OC=PC;function CC(t,e){return t?.[e]}var DC=CC,RC=OC,NC=DC;function TC(t,e){var r=NC(t,e);return RC(r)?r:void 0}var Zu=TC,FC=Zu,LC=Ro,BC=FC(LC,"Map"),pb=BC,UC=Zu,qC=UC(Object,"create"),Hl=qC,gb=Hl;function jC(){this.__data__=gb?gb(null):{},this.size=0}var kC=jC;function zC(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var HC=zC,WC=Hl,VC="__lodash_hash_undefined__",KC=Object.prototype,GC=KC.hasOwnProperty;function JC(t){var e=this.__data__;if(WC){var r=e[t];return r===VC?void 0:r}return GC.call(e,t)?e[t]:void 0}var ZC=JC,YC=Hl,XC=Object.prototype,QC=XC.hasOwnProperty;function eD(t){var e=this.__data__;return YC?e[t]!==void 0:QC.call(e,t)}var tD=eD,rD=Hl,iD="__lodash_hash_undefined__";function nD(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=rD&&e===void 0?iD:e,this}var sD=nD,oD=kC,aD=HC,cD=ZC,lD=tD,hD=sD;function No(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var i=t[e];this.set(i[0],i[1])}}No.prototype.clear=oD,No.prototype.delete=aD,No.prototype.get=cD,No.prototype.has=lD,No.prototype.set=hD;var fD=No,vb=fD,uD=kl,dD=pb;function pD(){this.size=0,this.__data__={hash:new vb,map:new(dD||uD),string:new vb}}var gD=pD;function vD(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}var mD=vD,bD=mD;function yD(t,e){var r=t.__data__;return bD(e)?r[typeof e=="string"?"string":"hash"]:r.map}var Wl=yD,wD=Wl;function _D(t){var e=wD(this,t).delete(t);return this.size-=e?1:0,e}var xD=_D,ED=Wl;function $D(t){return ED(this,t).get(t)}var SD=$D,ID=Wl;function AD(t){return ID(this,t).has(t)}var MD=AD,PD=Wl;function OD(t,e){var r=PD(this,t),i=r.size;return r.set(t,e),this.size+=r.size==i?0:1,this}var CD=OD,DD=gD,RD=xD,ND=SD,TD=MD,FD=CD;function To(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var i=t[e];this.set(i[0],i[1])}}To.prototype.clear=DD,To.prototype.delete=RD,To.prototype.get=ND,To.prototype.has=TD,To.prototype.set=FD;var LD=To,BD=kl,UD=pb,qD=LD,jD=200;function kD(t,e){var r=this.__data__;if(r instanceof BD){var i=r.__data__;if(!UD||i.length<jD-1)return i.push([t,e]),this.size=++r.size,this;r=this.__data__=new qD(i)}return r.set(t,e),this.size=r.size,this}var zD=kD,HD=kl,WD=PO,VD=CO,KD=RO,GD=TO,JD=zD;function Fo(t){var e=this.__data__=new HD(t);this.size=e.size}Fo.prototype.clear=WD,Fo.prototype.delete=VD,Fo.prototype.get=KD,Fo.prototype.has=GD,Fo.prototype.set=JD;var ZD=Fo,YD=Zu,XD=function(){try{var t=YD(Object,"defineProperty");return t({},"",{}),t}catch{}}(),mb=XD,bb=mb;function QD(t,e,r){e=="__proto__"&&bb?bb(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var Yu=QD,eR=Yu,tR=ql;function rR(t,e,r){(r!==void 0&&!tR(t[e],r)||r===void 0&&!(e in t))&&eR(t,e,r)}var yb=rR;function iR(t){return function(e,r,i){for(var n=-1,s=Object(e),o=i(e),a=o.length;a--;){var c=o[t?a:++n];if(r(s[c],c,s)===!1)break}return e}}var nR=iR,sR=nR,oR=sR(),aR=oR,Xu={exports:{}};(function(t,e){var r=Ro,i=e&&!e.nodeType&&e,n=i&&!0&&t&&!t.nodeType&&t,s=n&&n.exports===i,o=s?r.Buffer:void 0,a=o?o.allocUnsafe:void 0;function c(l,u){if(u)return l.slice();var m=l.length,x=a?a(m):new l.constructor(m);return l.copy(x),x}t.exports=c})(Xu,Xu.exports);var cR=Ro,lR=cR.Uint8Array,hR=lR,wb=hR;function fR(t){var e=new t.constructor(t.byteLength);return new wb(e).set(new wb(t)),e}var uR=fR,dR=uR;function pR(t,e){var r=e?dR(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}var gR=pR;function vR(t,e){var r=-1,i=t.length;for(e||(e=Array(i));++r<i;)e[r]=t[r];return e}var mR=vR,bR=Ns,_b=Object.create,yR=function(){function t(){}return function(e){if(!bR(e))return{};if(_b)return _b(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}(),wR=yR;function _R(t,e){return function(r){return t(e(r))}}var xR=_R,ER=xR,$R=ER(Object.getPrototypeOf,Object),xb=$R,SR=Object.prototype;function IR(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||SR;return t===r}var Eb=IR,AR=wR,MR=xb,PR=Eb;function OR(t){return typeof t.constructor=="function"&&!PR(t)?AR(MR(t)):{}}var CR=OR;function DR(t){return t!=null&&typeof t=="object"}var nc=DR,RR=zl,NR=nc,TR="[object Arguments]";function FR(t){return NR(t)&&RR(t)==TR}var LR=FR,$b=LR,BR=nc,Sb=Object.prototype,UR=Sb.hasOwnProperty,qR=Sb.propertyIsEnumerable,jR=$b(function(){return arguments}())?$b:function(t){return BR(t)&&UR.call(t,"callee")&&!qR.call(t,"callee")},Ib=jR,kR=Array.isArray,Ab=kR,zR=9007199254740991;function HR(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=zR}var Mb=HR,WR=Gu,VR=Mb;function KR(t){return t!=null&&VR(t.length)&&!WR(t)}var Qu=KR,GR=Qu,JR=nc;function ZR(t){return JR(t)&&GR(t)}var YR=ZR,Vl={exports:{}};function XR(){return!1}var QR=XR;(function(t,e){var r=Ro,i=QR,n=e&&!e.nodeType&&e,s=n&&!0&&t&&!t.nodeType&&t,o=s&&s.exports===n,a=o?r.Buffer:void 0,c=a?a.isBuffer:void 0,l=c||i;t.exports=l})(Vl,Vl.exports);var eN=zl,tN=xb,rN=nc,iN="[object Object]",nN=Function.prototype,sN=Object.prototype,Pb=nN.toString,oN=sN.hasOwnProperty,aN=Pb.call(Object);function cN(t){if(!rN(t)||eN(t)!=iN)return!1;var e=tN(t);if(e===null)return!0;var r=oN.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&Pb.call(r)==aN}var lN=cN,hN=zl,fN=Mb,uN=nc,dN="[object Arguments]",pN="[object Array]",gN="[object Boolean]",vN="[object Date]",mN="[object Error]",bN="[object Function]",yN="[object Map]",wN="[object Number]",_N="[object Object]",xN="[object RegExp]",EN="[object Set]",$N="[object String]",SN="[object WeakMap]",IN="[object ArrayBuffer]",AN="[object DataView]",MN="[object Float32Array]",PN="[object Float64Array]",ON="[object Int8Array]",CN="[object Int16Array]",DN="[object Int32Array]",RN="[object Uint8Array]",NN="[object Uint8ClampedArray]",TN="[object Uint16Array]",FN="[object Uint32Array]",Mt={};Mt[MN]=Mt[PN]=Mt[ON]=Mt[CN]=Mt[DN]=Mt[RN]=Mt[NN]=Mt[TN]=Mt[FN]=!0,Mt[dN]=Mt[pN]=Mt[IN]=Mt[gN]=Mt[AN]=Mt[vN]=Mt[mN]=Mt[bN]=Mt[yN]=Mt[wN]=Mt[_N]=Mt[xN]=Mt[EN]=Mt[$N]=Mt[SN]=!1;function LN(t){return uN(t)&&fN(t.length)&&!!Mt[hN(t)]}var BN=LN;function UN(t){return function(e){return t(e)}}var qN=UN,ed={exports:{}};(function(t,e){var r=ab,i=e&&!e.nodeType&&e,n=i&&!0&&t&&!t.nodeType&&t,s=n&&n.exports===i,o=s&&r.process,a=function(){try{var c=n&&n.require&&n.require("util").types;return c||o&&o.binding&&o.binding("util")}catch{}}();t.exports=a})(ed,ed.exports);var jN=BN,kN=qN,Ob=ed.exports,Cb=Ob&&Ob.isTypedArray,zN=Cb?kN(Cb):jN,Db=zN;function HN(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}var Rb=HN,WN=Yu,VN=ql,KN=Object.prototype,GN=KN.hasOwnProperty;function JN(t,e,r){var i=t[e];(!(GN.call(t,e)&&VN(i,r))||r===void 0&&!(e in t))&&WN(t,e,r)}var ZN=JN,YN=ZN,XN=Yu;function QN(t,e,r,i){var n=!r;r||(r={});for(var s=-1,o=e.length;++s<o;){var a=e[s],c=i?i(r[a],t[a],a,r,t):void 0;c===void 0&&(c=t[a]),n?XN(r,a,c):YN(r,a,c)}return r}var eT=QN;function tT(t,e){for(var r=-1,i=Array(t);++r<t;)i[r]=e(r);return i}var rT=tT,iT=9007199254740991,nT=/^(?:0|[1-9]\d*)$/;function sT(t,e){var r=typeof t;return e=e??iT,!!e&&(r=="number"||r!="symbol"&&nT.test(t))&&t>-1&&t%1==0&&t<e}var Nb=sT,oT=rT,aT=Ib,cT=Ab,lT=Vl.exports,hT=Nb,fT=Db,uT=Object.prototype,dT=uT.hasOwnProperty;function pT(t,e){var r=cT(t),i=!r&&aT(t),n=!r&&!i&&lT(t),s=!r&&!i&&!n&&fT(t),o=r||i||n||s,a=o?oT(t.length,String):[],c=a.length;for(var l in t)(e||dT.call(t,l))&&!(o&&(l=="length"||n&&(l=="offset"||l=="parent")||s&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||hT(l,c)))&&a.push(l);return a}var gT=pT;function vT(t){var e=[];if(t!=null)for(var r in Object(t))e.push(r);return e}var mT=vT,bT=Ns,yT=Eb,wT=mT,_T=Object.prototype,xT=_T.hasOwnProperty;function ET(t){if(!bT(t))return wT(t);var e=yT(t),r=[];for(var i in t)i=="constructor"&&(e||!xT.call(t,i))||r.push(i);return r}var $T=ET,ST=gT,IT=$T,AT=Qu;function MT(t){return AT(t)?ST(t,!0):IT(t)}var Tb=MT,PT=eT,OT=Tb;function CT(t){return PT(t,OT(t))}var DT=CT,Fb=yb,RT=Xu.exports,NT=gR,TT=mR,FT=CR,Lb=Ib,Bb=Ab,LT=YR,BT=Vl.exports,UT=Gu,qT=Ns,jT=lN,kT=Db,Ub=Rb,zT=DT;function HT(t,e,r,i,n,s,o){var a=Ub(t,r),c=Ub(e,r),l=o.get(c);if(l){Fb(t,r,l);return}var u=s?s(a,c,r+"",t,e,o):void 0,m=u===void 0;if(m){var x=Bb(c),S=!x&&BT(c),E=!x&&!S&&kT(c);u=c,x||S||E?Bb(a)?u=a:LT(a)?u=TT(a):S?(m=!1,u=RT(c,!0)):E?(m=!1,u=NT(c,!0)):u=[]:jT(c)||Lb(c)?(u=a,Lb(a)?u=zT(a):(!qT(a)||UT(a))&&(u=FT(c))):m=!1}m&&(o.set(c,u),n(u,c,i,s,o),o.delete(c)),Fb(t,r,u)}var WT=HT,VT=ZD,KT=yb,GT=aR,JT=WT,ZT=Ns,YT=Tb,XT=Rb;function qb(t,e,r,i,n){t!==e&&GT(e,function(s,o){if(n||(n=new VT),ZT(s))JT(t,e,o,r,qb,i,n);else{var a=i?i(XT(t,o),s,o+"",t,e,n):void 0;a===void 0&&(a=s),KT(t,o,a)}},YT)}var QT=qb;function eF(t){return t}var jb=eF;function tF(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}var rF=tF,iF=rF,kb=Math.max;function nF(t,e,r){return e=kb(e===void 0?t.length-1:e,0),function(){for(var i=arguments,n=-1,s=kb(i.length-e,0),o=Array(s);++n<s;)o[n]=i[e+n];n=-1;for(var a=Array(e+1);++n<e;)a[n]=i[n];return a[e]=r(o),iF(t,this,a)}}var sF=nF;function oF(t){return function(){return t}}var aF=oF,cF=aF,zb=mb,lF=jb,hF=zb?function(t,e){return zb(t,"toString",{configurable:!0,enumerable:!1,value:cF(e),writable:!0})}:lF,fF=hF,uF=800,dF=16,pF=Date.now;function gF(t){var e=0,r=0;return function(){var i=pF(),n=dF-(i-r);if(r=i,n>0){if(++e>=uF)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}var vF=gF,mF=fF,bF=vF,yF=bF(mF),wF=yF,_F=jb,xF=sF,EF=wF;function $F(t,e){return EF(xF(t,e,_F),t+"")}var SF=$F,IF=ql,AF=Qu,MF=Nb,PF=Ns;function OF(t,e,r){if(!PF(r))return!1;var i=typeof e;return(i=="number"?AF(r)&&MF(e,r.length):i=="string"&&e in r)?IF(r[e],t):!1}var CF=OF,DF=SF,RF=CF;function NF(t){return DF(function(e,r){var i=-1,n=r.length,s=n>1?r[n-1]:void 0,o=n>2?r[2]:void 0;for(s=t.length>3&&typeof s=="function"?(n--,s):void 0,o&&RF(r[0],r[1],o)&&(s=n<3?void 0:s,n=1),e=Object(e);++i<n;){var a=r[i];a&&t(e,a,i,s)}return e})}var TF=NF,FF=QT,LF=TF,BF=LF(function(t,e,r){FF(t,e,r)}),UF=BF,qF=Object.defineProperty,jF=Object.defineProperties,kF=Object.getOwnPropertyDescriptors,Hb=Object.getOwnPropertySymbols,zF=Object.prototype.hasOwnProperty,HF=Object.prototype.propertyIsEnumerable,Wb=(t,e,r)=>e in t?qF(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Kl=(t,e)=>{for(var r in e||(e={}))zF.call(e,r)&&Wb(t,r,e[r]);if(Hb)for(var r of Hb(e))HF.call(e,r)&&Wb(t,r,e[r]);return t},WF=(t,e)=>jF(t,kF(e));function Yr(t,e,r){var i;const n=bo(t);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${ob}?chainId=${n.namespace}:${n.reference}&projectId=${r}`}function Ts(t){return t.includes(":")?t.split(":")[1]:t}function Vb(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function VF(t,e){const r=Object.keys(e.namespaces).filter(n=>n.includes(t));if(!r.length)return[];const i=[];return r.forEach(n=>{const s=e.namespaces[n].accounts;i.push(...s)}),i}function td(t={},e={}){const r=Kb(t),i=Kb(e);return UF(r,i)}function Kb(t){var e,r,i,n;const s={};if(!za(t))return s;for(const[o,a]of Object.entries(t)){const c=fu(o)?[o]:a.chains,l=a.methods||[],u=a.events||[],m=a.rpcMap||{},x=ka(o);s[x]=WF(Kl(Kl({},s[x]),a),{chains:hl(c,(e=s[x])==null?void 0:e.chains),methods:hl(l,(r=s[x])==null?void 0:r.methods),events:hl(u,(i=s[x])==null?void 0:i.events),rpcMap:Kl(Kl({},m),(n=s[x])==null?void 0:n.rpcMap)})}return s}function KF(t){return t.includes(":")?t.split(":")[2]:t}function Gb(t){const e={};for(const[r,i]of Object.entries(t)){const n=i.methods||[],s=i.events||[],o=i.accounts||[],a=fu(r)?[r]:i.chains?i.chains:Vb(i.accounts);e[r]={chains:a,methods:n,events:s,accounts:o}}return e}function rd(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}const Jb={},Je=t=>Jb[t],id=(t,e)=>{Jb[t]=e};var GF=Object.defineProperty,JF=(t,e,r)=>e in t?GF(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lo=(t,e,r)=>JF(t,typeof e!="symbol"?e+"":e,r);class ZF{constructor(e){Lo(this,"name","polkadot"),Lo(this,"client"),Lo(this,"httpProviders"),Lo(this,"events"),Lo(this,"namespace"),Lo(this,"chainId"),this.namespace=e.namespace,this.events=Je("events"),this.client=Je("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=Ts(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Yr(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ui(new Ci(i,Je("disableProviderPing")))}}var YF=Object.defineProperty,XF=Object.defineProperties,QF=Object.getOwnPropertyDescriptors,Zb=Object.getOwnPropertySymbols,eL=Object.prototype.hasOwnProperty,tL=Object.prototype.propertyIsEnumerable,nd=(t,e,r)=>e in t?YF(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yb=(t,e)=>{for(var r in e||(e={}))eL.call(e,r)&&nd(t,r,e[r]);if(Zb)for(var r of Zb(e))tL.call(e,r)&&nd(t,r,e[r]);return t},Xb=(t,e)=>XF(t,QF(e)),Bo=(t,e,r)=>nd(t,typeof e!="symbol"?e+"":e,r);class rL{constructor(e){Bo(this,"name","eip155"),Bo(this,"client"),Bo(this,"chainId"),Bo(this,"namespace"),Bo(this,"httpProviders"),Bo(this,"events"),this.namespace=e.namespace,this.events=Je("events"),this.client=Je("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r),this.chainId=parseInt(e),this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,r){const i=r||Yr(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ui(new Ci(i,Je("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=parseInt(Ts(r));e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}async handleSwitchChain(e){var r,i;let n=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";n=n.startsWith("0x")?n:`0x${n}`;const s=parseInt(n,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:n}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var r,i,n;const s=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0];if(!s)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const o=this.client.session.get(e.topic),a=((n=o?.sessionProperties)==null?void 0:n.capabilities)||{};if(a!=null&&a[s])return a?.[s];const c=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Xb(Yb({},o.sessionProperties||{}),{capabilities:Xb(Yb({},a||{}),{[s]:c})})})}catch(l){console.warn("Failed to update session with capabilities",l)}return c}async getCallStatus(e){var r,i;const n=this.client.session.get(e.topic),s=(r=n.sessionProperties)==null?void 0:r.bundler_name;if(s){const a=this.getBundlerUrl(e.chainId,s);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(i=n.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,r){var i;const n=new URL(e),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Zn("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,r){return`${rO}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}}var iL=Object.defineProperty,nL=(t,e,r)=>e in t?iL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Uo=(t,e,r)=>nL(t,typeof e!="symbol"?e+"":e,r);class sL{constructor(e){Uo(this,"name","solana"),Uo(this,"client"),Uo(this,"httpProviders"),Uo(this,"events"),Uo(this,"namespace"),Uo(this,"chainId"),this.namespace=e.namespace,this.events=Je("events"),this.client=Je("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=Ts(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Yr(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ui(new Ci(i,Je("disableProviderPing")))}}var oL=Object.defineProperty,aL=(t,e,r)=>e in t?oL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qo=(t,e,r)=>aL(t,typeof e!="symbol"?e+"":e,r);class cL{constructor(e){qo(this,"name","cosmos"),qo(this,"client"),qo(this,"httpProviders"),qo(this,"events"),qo(this,"namespace"),qo(this,"chainId"),this.namespace=e.namespace,this.events=Je("events"),this.client=Je("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=Ts(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Yr(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ui(new Ci(i,Je("disableProviderPing")))}}var lL=Object.defineProperty,hL=(t,e,r)=>e in t?lL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jo=(t,e,r)=>hL(t,typeof e!="symbol"?e+"":e,r);class fL{constructor(e){jo(this,"name","algorand"),jo(this,"client"),jo(this,"httpProviders"),jo(this,"events"),jo(this,"namespace"),jo(this,"chainId"),this.namespace=e.namespace,this.events=Je("events"),this.client=Je("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const i=r||Yr(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Yr(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new ui(new Ci(i,Je("disableProviderPing")))}}var uL=Object.defineProperty,dL=(t,e,r)=>e in t?uL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ko=(t,e,r)=>dL(t,typeof e!="symbol"?e+"":e,r);class pL{constructor(e){ko(this,"name","cip34"),ko(this,"client"),ko(this,"httpProviders"),ko(this,"events"),ko(this,"namespace"),ko(this,"chainId"),this.namespace=e.namespace,this.events=Je("events"),this.client=Je("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const i=this.getCardanoRPCUrl(r),n=Ts(r);e[n]=this.createHttpProvider(n,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ui(new Ci(i,Je("disableProviderPing")))}}var gL=Object.defineProperty,vL=(t,e,r)=>e in t?gL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zo=(t,e,r)=>vL(t,typeof e!="symbol"?e+"":e,r);class mL{constructor(e){zo(this,"name","elrond"),zo(this,"client"),zo(this,"httpProviders"),zo(this,"events"),zo(this,"namespace"),zo(this,"chainId"),this.namespace=e.namespace,this.events=Je("events"),this.client=Je("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=Ts(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Yr(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ui(new Ci(i,Je("disableProviderPing")))}}var bL=Object.defineProperty,yL=(t,e,r)=>e in t?bL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ho=(t,e,r)=>yL(t,typeof e!="symbol"?e+"":e,r);class wL{constructor(e){Ho(this,"name","multiversx"),Ho(this,"client"),Ho(this,"httpProviders"),Ho(this,"events"),Ho(this,"namespace"),Ho(this,"chainId"),this.namespace=e.namespace,this.events=Je("events"),this.client=Je("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=Ts(r);e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Yr(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ui(new Ci(i,Je("disableProviderPing")))}}var _L=Object.defineProperty,xL=(t,e,r)=>e in t?_L(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wo=(t,e,r)=>xL(t,typeof e!="symbol"?e+"":e,r);class EL{constructor(e){Wo(this,"name","near"),Wo(this,"client"),Wo(this,"httpProviders"),Wo(this,"events"),Wo(this,"namespace"),Wo(this,"chainId"),this.namespace=e.namespace,this.events=Je("events"),this.client=Je("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const i=r||Yr(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Yr(e,this.namespace);return typeof i>"u"?void 0:new ui(new Ci(i,Je("disableProviderPing")))}}var $L=Object.defineProperty,SL=(t,e,r)=>e in t?$L(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Vo=(t,e,r)=>SL(t,typeof e!="symbol"?e+"":e,r);class IL{constructor(e){Vo(this,"name","tezos"),Vo(this,"client"),Vo(this,"httpProviders"),Vo(this,"events"),Vo(this,"namespace"),Vo(this,"chainId"),this.namespace=e.namespace,this.events=Je("events"),this.client=Je("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const i=r||Yr(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{e[r]=this.createHttpProvider(r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Yr(e,this.namespace);return typeof i>"u"?void 0:new ui(new Ci(i))}}var AL=Object.defineProperty,ML=(t,e,r)=>e in t?AL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ko=(t,e,r)=>ML(t,typeof e!="symbol"?e+"":e,r);class PL{constructor(e){Ko(this,"name",Co),Ko(this,"client"),Ko(this,"httpProviders"),Ko(this,"events"),Ko(this,"namespace"),Ko(this,"chainId"),this.namespace=e.namespace,this.events=Je("events"),this.client=Je("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(gi.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const i={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(n=>{const s=bo(n);i[`${s.namespace}:${s.reference}`]=this.createHttpProvider(n)}),i}getHttpProvider(e){const r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Yr(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new ui(new Ci(i,Je("disableProviderPing")))}}var OL=Object.defineProperty,CL=Object.defineProperties,DL=Object.getOwnPropertyDescriptors,Qb=Object.getOwnPropertySymbols,RL=Object.prototype.hasOwnProperty,NL=Object.prototype.propertyIsEnumerable,sd=(t,e,r)=>e in t?OL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Gl=(t,e)=>{for(var r in e||(e={}))RL.call(e,r)&&sd(t,r,e[r]);if(Qb)for(var r of Qb(e))NL.call(e,r)&&sd(t,r,e[r]);return t},od=(t,e)=>CL(t,DL(e)),Xr=(t,e,r)=>sd(t,typeof e!="symbol"?e+"":e,r);class ad{constructor(e){Xr(this,"client"),Xr(this,"namespaces"),Xr(this,"optionalNamespaces"),Xr(this,"sessionProperties"),Xr(this,"events",new nr.exports),Xr(this,"rpcProviders",{}),Xr(this,"session"),Xr(this,"providerOpts"),Xr(this,"logger"),Xr(this,"uri"),Xr(this,"shouldAbortPairingAttempt",!1),Xr(this,"maxPairingAttempts",10),Xr(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Vi(Ol({level:e?.logger||nb})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new ad(e);return await r.initialize(),r}async request(e,r,i){const[n,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:Gl({},e),chainId:`${n}:${s}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,n){const s=new Date().getTime();this.request(e,i,n).then(o=>r(null,Cl(s,o))).catch(o=>r(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:wt("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:n}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const s=await n();if(this.session=s.session,this.session){const o=Gb(this.session.namespaces);this.namespaces=td(this.namespaces,o),this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){this.shouldAbortPairingAttempt=!1;let r=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(r>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:i,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});i&&(this.uri=i,this.events.emit("display_uri",i)),await n().then(s=>{this.session=s;const o=Gb(s.namespaces);this.namespaces=td(this.namespaces,o),this.persist("namespaces",this.namespaces)}).catch(s=>{if(s.message!==Gm)throw s;r++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[i,n]=this.validateChain(e),s=this.getProvider(i);s.name===Co?s.setDefaultChain(`${i}:${n}`,r):s.setDefaultChain(n,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(Wi(r)){for(const i of r)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await Vu.init({core:this.providerOpts.core,logger:this.providerOpts.logger||nb,relayUrl:this.providerOpts.relayUrl||QP,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(r=>ka(r)))];id("client",this.client),id("events",this.events),id("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=VF(r,this.session),n=Vb(i),s=td(this.namespaces,this.optionalNamespaces),o=od(Gl({},s[r]),{accounts:i,chains:n});switch(r){case"eip155":this.rpcProviders[r]=new rL({namespace:o});break;case"algorand":this.rpcProviders[r]=new fL({namespace:o});break;case"solana":this.rpcProviders[r]=new sL({namespace:o});break;case"cosmos":this.rpcProviders[r]=new cL({namespace:o});break;case"polkadot":this.rpcProviders[r]=new ZF({namespace:o});break;case"cip34":this.rpcProviders[r]=new pL({namespace:o});break;case"elrond":this.rpcProviders[r]=new mL({namespace:o});break;case"multiversx":this.rpcProviders[r]=new wL({namespace:o});break;case"near":this.rpcProviders[r]=new EL({namespace:o});break;case"tezos":this.rpcProviders[r]=new IL({namespace:o});break;default:this.rpcProviders[Co]?this.rpcProviders[Co].updateNamespace(o):this.rpcProviders[Co]=new PL({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:r}=e,{event:i}=r;if(i.name==="accountsChanged"){const n=i.data;n&&Wi(n)&&this.events.emit("accountsChanged",n.map(KF))}else if(i.name==="chainChanged"){const n=r.chainId,s=r.event.data,o=ka(n),a=rd(n)!==rd(s)?`${o}:${rd(s)}`:n;this.onChainChanged(a)}else this.events.emit(i.name,i.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var i;const{namespaces:n}=r,s=(i=this.client)==null?void 0:i.session.get(e);this.session=od(Gl({},s),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",od(Gl({},wt("USER_DISCONNECTED")),{data:e.topic}))}),this.on(gi.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Co]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r,optionalNamespaces:i,sessionProperties:n}=e;r&&Object.keys(r).length&&(this.namespaces=r),i&&Object.keys(i).length&&(this.optionalNamespaces=i),this.sessionProperties=n,this.persist("namespaces",r),this.persist("optionalNamespaces",i)}validateChain(e){const[r,i]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(o=>ka(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const n=ka(Object.keys(this.namespaces)[0]),s=this.rpcProviders[n].getDefaultChain();return[n,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,r=!1){if(!this.namespaces)return;const[i,n]=this.validateChain(e);n&&(r||this.getProvider(i).setDefaultChain(n),this.namespaces[i]?this.namespaces[i].defaultChain=n:this.namespaces[`${i}:${n}`]?this.namespaces[`${i}:${n}`].defaultChain=n:this.namespaces[`${i}:${n}`]={defaultChain:n},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",n))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(e,r){this.client.core.storage.setItem(`${sb}/${e}`,r)}async getFromStore(e){return await this.client.core.storage.getItem(`${sb}/${e}`)}}const TL=ad,FL="wc",LL="ethereum_provider",BL=`${FL}@2:${LL}:`,UL="https://rpc.walletconnect.org/v1/",Jl=["eth_sendTransaction","personal_sign"],e2=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],Zl=["chainChanged","accountsChanged"],t2=["chainChanged","accountsChanged","message","disconnect","connect"];var qL=Object.defineProperty,jL=Object.defineProperties,kL=Object.getOwnPropertyDescriptors,r2=Object.getOwnPropertySymbols,zL=Object.prototype.hasOwnProperty,HL=Object.prototype.propertyIsEnumerable,cd=(t,e,r)=>e in t?qL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Go=(t,e)=>{for(var r in e||(e={}))zL.call(e,r)&&cd(t,r,e[r]);if(r2)for(var r of r2(e))HL.call(e,r)&&cd(t,r,e[r]);return t},ld=(t,e)=>jL(t,kL(e)),Qr=(t,e,r)=>cd(t,typeof e!="symbol"?e+"":e,r);function Yl(t){return Number(t[0].split(":")[1])}function Xl(t){return`0x${t.toString(16)}`}function WL(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:n,events:s,optionalEvents:o,rpcMap:a}=t;if(!Wi(e))throw new Error("Invalid chains");const c={chains:e,methods:i||Jl,events:s||Zl,rpcMap:Go({},e.length?{[Yl(e)]:a[Yl(e)]}:{})},l=s?.filter(S=>!Zl.includes(S)),u=i?.filter(S=>!Jl.includes(S));if(!r&&!o&&!n&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:e.length?c:void 0};const m=l?.length&&u?.length||!r,x={chains:[...new Set(m?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(n!=null&&n.length?n:e2))],events:[...new Set(c.events.concat(o!=null&&o.length?o:t2))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?x:void 0}}class Ql{constructor(){Qr(this,"events",new nr.exports.EventEmitter),Qr(this,"namespace","eip155"),Qr(this,"accounts",[]),Qr(this,"signer"),Qr(this,"chainId",1),Qr(this,"modal"),Qr(this,"rpc"),Qr(this,"STORAGE_KEY",BL),Qr(this,"on",(e,r)=>(this.events.on(e,r),this)),Qr(this,"once",(e,r)=>(this.events.once(e,r),this)),Qr(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),Qr(this,"off",(e,r)=>(this.events.off(e,r),this)),Qr(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new Ql;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:i}=WL(this.rpc);try{const n=await new Promise(async(o,a)=>{var c;this.rpc.showQrModal&&((c=this.modal)==null||c.subscribeModal(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(ld(Go({namespaces:Go({},r&&{[this.namespace]:r})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:e?.pairingTopic})).then(l=>{o(l)}).catch(l=>{a(new Error(l.message))})});if(!n)return;const s=mg(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:Xl(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{this.modal&&this.modal.closeModal()}}async authenticate(e,r){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const i=await new Promise(async(s,o)=>{var a;this.rpc.showQrModal&&((a=this.modal)==null||a.subscribeModal(c=>{!c.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),o(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(ld(Go({},e),{chains:this.rpc.chains}),r).then(c=>{s(c)}).catch(c=>{o(new Error(c.message))})}),n=i.session;if(n){const s=mg(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:Xl(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:i}=r;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",Xl(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",ld(Go({},wt("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var r,i;this.rpc.showQrModal&&((r=this.modal)==null||r.closeModal(),(i=this.modal)==null||i.openModal({uri:e})),this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",Xl(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,i,n]=e.split(":");return{chainId:`${r}:${i}`,address:n}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,i;const n=(r=e?.chains)!=null?r:[],s=(i=e?.optionalChains)!=null?i:[],o=n.concat(s);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=n.length?e?.methods||Jl:[],c=n.length?e?.events||Zl:[],l=e?.optionalMethods||[],u=e?.optionalEvents||[],m=e?.rpcMap||this.buildRpcMap(o,e.projectId),x=e?.qrModalOptions||void 0;return{chains:n?.map(S=>this.formatChainId(S)),optionalChains:s.map(S=>this.formatChainId(S)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:m,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:x,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(n=>{i[n]=this.getRpcUrl(n,r)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Yl(this.rpc.chains):Yl(this.rpc.optionalChains),this.signer=await TL.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const{WalletConnectModal:i}=await Promise.resolve().then(function(){return pB});r=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(r)try{this.modal=new r(Go({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:n}=e;r&&Wi(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=n?.[s]||this.getRpcUrl(s)})),i&&Wi(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(s=>this.formatChainId(s)),i.forEach(s=>{this.rpc.rpcMap[s]=n?.[s]||this.getRpcUrl(s)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${UL}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r?.accounts),this.setAccounts(r?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const VL=Ql,KL=Symbol(),i2=Object.getPrototypeOf,hd=new WeakMap,GL=t=>t&&(hd.has(t)?hd.get(t):i2(t)===Object.prototype||i2(t)===Array.prototype),JL=t=>GL(t)&&t[KL]||null,n2=(t,e=!0)=>{hd.set(t,e)},fd=t=>typeof t=="object"&&t!==null,Yn=new WeakMap,eh=new WeakSet,ZL=(t=Object.is,e=(l,u)=>new Proxy(l,u),r=l=>fd(l)&&!eh.has(l)&&(Array.isArray(l)||!(Symbol.iterator in l))&&!(l instanceof WeakMap)&&!(l instanceof WeakSet)&&!(l instanceof Error)&&!(l instanceof Number)&&!(l instanceof Date)&&!(l instanceof String)&&!(l instanceof RegExp)&&!(l instanceof ArrayBuffer),i=l=>{switch(l.status){case"fulfilled":return l.value;case"rejected":throw l.reason;default:throw l}},n=new WeakMap,s=(l,u,m=i)=>{const x=n.get(l);if(x?.[0]===u)return x[1];const S=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return n2(S,!0),n.set(l,[u,S]),Reflect.ownKeys(l).forEach(E=>{if(Object.getOwnPropertyDescriptor(S,E))return;const A=Reflect.get(l,E),R={value:A,enumerable:!0,configurable:!0};if(eh.has(A))n2(A,!1);else if(A instanceof Promise)delete R.value,R.get=()=>m(A);else if(Yn.has(A)){const[O,C]=Yn.get(A);R.value=s(O,C(),m)}Object.defineProperty(S,E,R)}),Object.preventExtensions(S)},o=new WeakMap,a=[1,1],c=l=>{if(!fd(l))throw new Error("object required");const u=o.get(l);if(u)return u;let m=a[0];const x=new Set,S=(B,K=++a[0])=>{m!==K&&(m=K,x.forEach(M=>M(B,K)))};let E=a[1];const A=(B=++a[1])=>(E!==B&&!x.size&&(E=B,O.forEach(([K])=>{const M=K[1](B);M>m&&(m=M)})),m),R=B=>(K,M)=>{const v=[...K];v[1]=[B,...v[1]],S(v,M)},O=new Map,C=(B,K)=>{if(O.has(B))throw new Error("prop listener already exists");if(x.size){const M=K[3](R(B));O.set(B,[K,M])}else O.set(B,[K])},N=B=>{var K;const M=O.get(B);M&&(O.delete(B),(K=M[1])==null||K.call(M))},T=B=>(x.add(B),x.size===1&&O.forEach(([M,v],g)=>{if(v)throw new Error("remove already exists");const h=M[3](R(g));O.set(g,[M,h])}),()=>{x.delete(B),x.size===0&&O.forEach(([M,v],g)=>{v&&(v(),O.set(g,[M]))})}),U=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),W=e(U,{deleteProperty(B,K){const M=Reflect.get(B,K);N(K);const v=Reflect.deleteProperty(B,K);return v&&S(["delete",[K],M]),v},set(B,K,M,v){const g=Reflect.has(B,K),h=Reflect.get(B,K,v);if(g&&(t(h,M)||o.has(M)&&t(h,o.get(M))))return!0;N(K),fd(M)&&(M=JL(M)||M);let f=M;if(M instanceof Promise)M.then(p=>{M.status="fulfilled",M.value=p,S(["resolve",[K],p])}).catch(p=>{M.status="rejected",M.reason=p,S(["reject",[K],p])});else{!Yn.has(M)&&r(M)&&(f=c(M));const p=!eh.has(f)&&Yn.get(f);p&&C(K,p)}return Reflect.set(B,K,f,v),S(["set",[K],M,h]),!0}});o.set(l,W);const V=[U,A,s,T];return Yn.set(W,V),Reflect.ownKeys(l).forEach(B=>{const K=Object.getOwnPropertyDescriptor(l,B);"value"in K&&(W[B]=l[B],delete K.value,delete K.writable),Object.defineProperty(U,B,K)}),W})=>[c,Yn,eh,t,e,r,i,n,s,o,a],[YL]=ZL();function Xn(t={}){return YL(t)}function Fs(t,e,r){const i=Yn.get(t);i||console.warn("Please use proxy object");let n;const s=[],o=i[3];let a=!1;const l=o(u=>{if(s.push(u),r){e(s.splice(0));return}n||(n=Promise.resolve().then(()=>{n=void 0,a&&e(s.splice(0))}))});return a=!0,()=>{a=!1,l()}}function XL(t,e){const r=Yn.get(t);r||console.warn("Please use proxy object");const[i,n,s]=r;return s(i,n(),e)}const rr=Xn({history:["ConnectWallet"],view:"ConnectWallet",data:void 0}),Ot={state:rr,subscribe(t){return Fs(rr,()=>t(rr))},push(t,e){t!==rr.view&&(rr.view=t,e&&(rr.data=e),rr.history.push(t))},reset(t){rr.view=t,rr.history=[t]},replace(t){rr.history.length>1&&(rr.history[rr.history.length-1]=t,rr.view=t)},goBack(){if(rr.history.length>1){rr.history.pop();const[t]=rr.history.slice(-1);rr.view=t}},setData(t){rr.data=t}},se={WALLETCONNECT_DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",WCM_VERSION:"WCM_VERSION",RECOMMENDED_WALLET_AMOUNT:9,isMobile(){return typeof window<"u"?!!(window.matchMedia("(pointer:coarse)").matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},isAndroid(){return se.isMobile()&&navigator.userAgent.toLowerCase().includes("android")},isIos(){const t=navigator.userAgent.toLowerCase();return se.isMobile()&&(t.includes("iphone")||t.includes("ipad"))},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},isArray(t){return Array.isArray(t)&&t.length>0},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},formatNativeUrl(t,e,r){if(se.isHttpUrl(t))return this.formatUniversalUrl(t,e,r);let i=t;i.includes("://")||(i=t.replaceAll("/","").replaceAll(":",""),i=`${i}://`),i.endsWith("/")||(i=`${i}/`),this.setWalletConnectDeepLink(i,r);const n=encodeURIComponent(e);return`${i}wc?uri=${n}`},formatUniversalUrl(t,e,r){if(!se.isHttpUrl(t))return this.formatNativeUrl(t,e,r);let i=t;if(i.startsWith("https://t.me")){const s=Buffer.from(e).toString("base64").replace(/[=]/g,"");i.endsWith("/")&&(i=i.slice(0,-1)),this.setWalletConnectDeepLink(i,r);const o=new URL(i);return o.searchParams.set("startapp",s),o.toString()}i.endsWith("/")||(i=`${i}/`),this.setWalletConnectDeepLink(i,r);const n=encodeURIComponent(e);return`${i}wc?uri=${n}`},async wait(t){return new Promise(e=>{setTimeout(e,t)})},openHref(t,e){const r=this.isTelegram()?"_blank":e;window.open(t,r,"noreferrer noopener")},setWalletConnectDeepLink(t,e){try{localStorage.setItem(se.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},setWalletConnectAndroidDeepLink(t){try{const[e]=t.split("?");localStorage.setItem(se.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:e,name:"Android"}))}catch{console.info("Unable to set WalletConnect android deep link")}},removeWalletConnectDeepLink(){try{localStorage.removeItem(se.WALLETCONNECT_DEEPLINK_CHOICE)}catch{console.info("Unable to remove WalletConnect deep link")}},setModalVersionInStorage(){try{typeof localStorage<"u"&&localStorage.setItem(se.WCM_VERSION,"2.7.0")}catch{console.info("Unable to set Web3Modal version in storage")}},getWalletRouterData(){var t;const e=(t=Ot.state.data)==null?void 0:t.Wallet;if(!e)throw new Error('Missing "Wallet" view data');return e}},QL=typeof location<"u"&&(location.hostname.includes("localhost")||location.protocol.includes("https")),yr=Xn({enabled:QL,userSessionId:"",events:[],connectedWalletId:void 0}),s2={state:yr,subscribe(t){return Fs(yr.events,()=>t(XL(yr.events[yr.events.length-1])))},initialize(){yr.enabled&&typeof(crypto==null?void 0:crypto.randomUUID)<"u"&&(yr.userSessionId=crypto.randomUUID())},setConnectedWalletId(t){yr.connectedWalletId=t},click(t){if(yr.enabled){const e={type:"CLICK",name:t.name,userSessionId:yr.userSessionId,timestamp:Date.now(),data:t};yr.events.push(e)}},track(t){if(yr.enabled){const e={type:"TRACK",name:t.name,userSessionId:yr.userSessionId,timestamp:Date.now(),data:t};yr.events.push(e)}},view(t){if(yr.enabled){const e={type:"VIEW",name:t.name,userSessionId:yr.userSessionId,timestamp:Date.now(),data:t};yr.events.push(e)}}},en=Xn({chains:void 0,walletConnectUri:void 0,isAuth:!1,isCustomDesktop:!1,isCustomMobile:!1,isDataLoaded:!1,isUiLoaded:!1}),qt={state:en,subscribe(t){return Fs(en,()=>t(en))},setChains(t){en.chains=t},setWalletConnectUri(t){en.walletConnectUri=t},setIsCustomDesktop(t){en.isCustomDesktop=t},setIsCustomMobile(t){en.isCustomMobile=t},setIsDataLoaded(t){en.isDataLoaded=t},setIsUiLoaded(t){en.isUiLoaded=t},setIsAuth(t){en.isAuth=t}},th=Xn({projectId:"",mobileWallets:void 0,desktopWallets:void 0,walletImages:void 0,chains:void 0,enableAuthMode:!1,enableExplorer:!0,explorerExcludedWalletIds:void 0,explorerRecommendedWalletIds:void 0,termsOfServiceUrl:void 0,privacyPolicyUrl:void 0}),ei={state:th,subscribe(t){return Fs(th,()=>t(th))},setConfig(t){var e,r;s2.initialize(),qt.setChains(t.chains),qt.setIsAuth(!!t.enableAuthMode),qt.setIsCustomMobile(!!((e=t.mobileWallets)!=null&&e.length)),qt.setIsCustomDesktop(!!((r=t.desktopWallets)!=null&&r.length)),se.setModalVersionInStorage(),Object.assign(th,t)}};var eB=Object.defineProperty,o2=Object.getOwnPropertySymbols,tB=Object.prototype.hasOwnProperty,rB=Object.prototype.propertyIsEnumerable,a2=(t,e,r)=>e in t?eB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,iB=(t,e)=>{for(var r in e||(e={}))tB.call(e,r)&&a2(t,r,e[r]);if(o2)for(var r of o2(e))rB.call(e,r)&&a2(t,r,e[r]);return t};const ud="https://explorer-api.walletconnect.com",dd="wcm",pd="js-2.7.0";async function rh(t,e){const r=iB({sdkType:dd,sdkVersion:pd},e),i=new URL(t,ud);return i.searchParams.append("projectId",ei.state.projectId),Object.entries(r).forEach(([s,o])=>{o&&i.searchParams.append(s,String(o))}),(await fetch(i)).json()}const Ls={async getDesktopListings(t){return rh("/w3m/v1/getDesktopListings",t)},async getMobileListings(t){return rh("/w3m/v1/getMobileListings",t)},async getInjectedListings(t){return rh("/w3m/v1/getInjectedListings",t)},async getAllListings(t){return rh("/w3m/v1/getAllListings",t)},getWalletImageUrl(t){return`${ud}/w3m/v1/getWalletImage/${t}?projectId=${ei.state.projectId}&sdkType=${dd}&sdkVersion=${pd}`},getAssetImageUrl(t){return`${ud}/w3m/v1/getAssetImage/${t}?projectId=${ei.state.projectId}&sdkType=${dd}&sdkVersion=${pd}`}};var nB=Object.defineProperty,c2=Object.getOwnPropertySymbols,sB=Object.prototype.hasOwnProperty,oB=Object.prototype.propertyIsEnumerable,l2=(t,e,r)=>e in t?nB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,aB=(t,e)=>{for(var r in e||(e={}))sB.call(e,r)&&l2(t,r,e[r]);if(c2)for(var r of c2(e))oB.call(e,r)&&l2(t,r,e[r]);return t};const h2=se.isMobile(),tn=Xn({wallets:{listings:[],total:0,page:1},search:{listings:[],total:0,page:1},recomendedWallets:[]}),Br={state:tn,async getRecomendedWallets(){const{explorerRecommendedWalletIds:t,explorerExcludedWalletIds:e}=ei.state;if(t==="NONE"||e==="ALL"&&!t)return tn.recomendedWallets;if(se.isArray(t)){const i={recommendedIds:t.join(",")},{listings:n}=await Ls.getAllListings(i),s=Object.values(n);s.sort((o,a)=>{const c=t.indexOf(o.id),l=t.indexOf(a.id);return c-l}),tn.recomendedWallets=s}else{const{chains:r,isAuth:i}=qt.state,n=r?.join(","),s=se.isArray(e),o={page:1,sdks:i?"auth_v1":void 0,entries:se.RECOMMENDED_WALLET_AMOUNT,chains:n,version:2,excludedIds:s?e.join(","):void 0},{listings:a}=h2?await Ls.getMobileListings(o):await Ls.getDesktopListings(o);tn.recomendedWallets=Object.values(a)}return tn.recomendedWallets},async getWallets(t){const e=aB({},t),{explorerRecommendedWalletIds:r,explorerExcludedWalletIds:i}=ei.state,{recomendedWallets:n}=tn;if(i==="ALL")return tn.wallets;n.length?e.excludedIds=n.map(m=>m.id).join(","):se.isArray(r)&&(e.excludedIds=r.join(",")),se.isArray(i)&&(e.excludedIds=[e.excludedIds,i].filter(Boolean).join(",")),qt.state.isAuth&&(e.sdks="auth_v1");const{page:s,search:o}=t,{listings:a,total:c}=h2?await Ls.getMobileListings(e):await Ls.getDesktopListings(e),l=Object.values(a),u=o?"search":"wallets";return tn[u]={listings:[...tn[u].listings,...l],total:c,page:s??1},{listings:l,total:c}},getWalletImageUrl(t){return Ls.getWalletImageUrl(t)},getAssetImageUrl(t){return Ls.getAssetImageUrl(t)},resetSearch(){tn.search={listings:[],total:0,page:1}}},Jo=Xn({open:!1}),Bs={state:Jo,subscribe(t){return Fs(Jo,()=>t(Jo))},async open(t){return new Promise(e=>{const{isUiLoaded:r,isDataLoaded:i}=qt.state;if(se.removeWalletConnectDeepLink(),qt.setWalletConnectUri(t?.uri),qt.setChains(t?.chains),Ot.reset("ConnectWallet"),r&&i)Jo.open=!0,e();else{const n=setInterval(()=>{const s=qt.state;s.isUiLoaded&&s.isDataLoaded&&(clearInterval(n),Jo.open=!0,e())},200)}})},close(){Jo.open=!1}};var cB=Object.defineProperty,f2=Object.getOwnPropertySymbols,lB=Object.prototype.hasOwnProperty,hB=Object.prototype.propertyIsEnumerable,u2=(t,e,r)=>e in t?cB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fB=(t,e)=>{for(var r in e||(e={}))lB.call(e,r)&&u2(t,r,e[r]);if(f2)for(var r of f2(e))hB.call(e,r)&&u2(t,r,e[r]);return t};function uB(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: dark)").matches}const sc=Xn({themeMode:uB()?"dark":"light"}),Qn={state:sc,subscribe(t){return Fs(sc,()=>t(sc))},setThemeConfig(t){const{themeMode:e,themeVariables:r}=t;e&&(sc.themeMode=e),r&&(sc.themeVariables=fB({},r))}},Us=Xn({open:!1,message:"",variant:"success"}),es={state:Us,subscribe(t){return Fs(Us,()=>t(Us))},openToast(t,e){Us.open=!0,Us.message=t,Us.variant=e},closeToast(){Us.open=!1}};class dB{constructor(e){this.openModal=Bs.open,this.closeModal=Bs.close,this.subscribeModal=Bs.subscribe,this.setTheme=Qn.setThemeConfig,Qn.setThemeConfig(e),ei.setConfig(e),this.initUi()}async initUi(){if(typeof window<"u"){await Promise.resolve().then(function(){return Ek});const e=document.createElement("wcm-modal");document.body.insertAdjacentElement("beforeend",e),qt.setIsUiLoaded(!0)}}}var pB=Object.freeze({__proto__:null,WalletConnectModal:dB});/**
45
45
  * @license
46
46
  * Copyright 2019 Google LLC