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

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
@@ -36,7 +36,7 @@ ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(A$(r)).toStr
36
36
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
37
37
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
38
38
  PERFORMANCE OF THIS SOFTWARE.
39
- ***************************************************************************** */var Kd=function(t,e){return Kd=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])},Kd(t,e)};function _P(t,e){Kd(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Gd=function(){return Gd=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},Gd.apply(this,arguments)};function xP(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 EP(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 $P(t,e){return function(r,i){e(r,i,t)}}function IP(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function SP(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(d){o(d)}}function c(u){try{l(i.throw(u))}catch(d){o(d)}}function l(u){u.done?s(u.value):n(u.value).then(a,c)}l((i=i.apply(t,e||[])).next())})}function AP(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 PP(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function OP(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Zd(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 sv(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 CP(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(sv(arguments[e]));return t}function DP(){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 Ba(t){return this instanceof Ba?(this.v=t,this):new Ba(t)}function MP(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(p){i[p]&&(n[p]=function(y){return new Promise(function(m,_){s.push([p,y,m,_])>1||a(p,y)})})}function a(p,y){try{c(i[p](y))}catch(m){d(s[0][3],m)}}function c(p){p.value instanceof Ba?Promise.resolve(p.value.v).then(l,u):d(s[0][2],p)}function l(p){a("next",p)}function u(p){a("throw",p)}function d(p,y){p(y),s.shift(),s.length&&a(s[0][0],s[0][1])}}function TP(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:Ba(t[n](o)),done:n==="return"}:s?s(o):o}:s}}function RP(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 Zd=="function"?Zd(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 NP(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function BP(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 LP(t){return t&&t.__esModule?t:{default:t}}function FP(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function UP(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 jP=Object.freeze({__proto__:null,__extends:_P,get __assign(){return Gd},__rest:xP,__decorate:EP,__param:$P,__metadata:IP,__awaiter:SP,__generator:AP,__createBinding:PP,__exportStar:OP,__values:Zd,__read:sv,__spread:CP,__spreadArrays:DP,__await:Ba,__asyncGenerator:MP,__asyncDelegator:TP,__asyncValues:RP,__makeTemplateObject:NP,__importStar:BP,__importDefault:LP,__classPrivateFieldGet:FP,__classPrivateFieldSet:UP}),qP=zu(jP),qi={},ov;function zP(){if(ov)return qi;ov=1,Object.defineProperty(qi,"__esModule",{value:!0}),qi.isBrowserCryptoAvailable=qi.getSubtleCrypto=qi.getBrowerCrypto=void 0;function t(){return wt?.crypto||wt?.msCrypto||{}}qi.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}qi.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return qi.isBrowserCryptoAvailable=r,qi}var zi={},av;function kP(){if(av)return zi;av=1,Object.defineProperty(zi,"__esModule",{value:!0}),zi.isBrowser=zi.isNode=zi.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}zi.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}zi.isNode=e;function r(){return!t()&&!e()}return zi.isBrowser=r,zi}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=qP;e.__exportStar(zP(),t),e.__exportStar(kP(),t)})(nv);function bi(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Qn(t=6){return BigInt(bi(t))}function gn(t,e,r){return{id:r||bi(),jsonrpc:"2.0",method:t,params:e}}function Ll(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Fl(t,e,r){return{id:t,jsonrpc:"2.0",error:HP(e,r)}}function HP(t,e){return typeof t>"u"?rv(ev):(typeof t=="string"&&(t=Object.assign(Object.assign({},rv(Vd)),{message:t})),typeof e<"u"&&(t.data=e),yP(t.code)&&(t=wP(t.code)),t)}class WP{}class VP extends WP{constructor(){super()}}class KP extends VP{constructor(e){super()}}const GP="^https?:",ZP="^wss?:";function YP(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function cv(t,e){const r=YP(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function lv(t){return cv(t,GP)}function uv(t){return cv(t,ZP)}function JP(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function hv(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Yd(t){return hv(t)&&"method"in t}function Ul(t){return hv(t)&&(mi(t)||Cr(t))}function mi(t){return"result"in t}function Cr(t){return"error"in t}class Dr extends KP{constructor(e){super(e),this.events=new Lt.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(gn(e.method,e.params||[],e.id||Qn().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=>{Cr(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),Ul(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 QP=()=>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"),XP=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",dv=t=>t.split("?")[0],fv=10,eO=QP();class tO{constructor(e){if(this.url=e,this.events=new Lt.exports.EventEmitter,this.registering=!1,!uv(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(Mi(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!uv(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=nv.isReactNative()?void 0:{rejectUnauthorized:!JP(e)},s=new eO(e,[],n);XP()?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"?Fn(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=Fl(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return iv(e,dv(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>fv&&this.events.setMaxListeners(fv)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${dv(this.url)}`));return this.events.emit("register_error",r),r}}var Jd={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]",d="[object Date]",p="[object Error]",y="[object Function]",m="[object GeneratorFunction]",_="[object Map]",S="[object Number]",E="[object Null]",P="[object Object]",C="[object Promise]",M="[object Proxy]",R="[object RegExp]",L="[object Set]",B="[object String]",F="[object Symbol]",T="[object Undefined]",q="[object WeakMap]",$="[object ArrayBuffer]",h="[object DataView]",b="[object Float32Array]",w="[object Float64Array]",g="[object Int8Array]",v="[object Int16Array]",I="[object Int32Array]",O="[object Uint8Array]",x="[object Uint8ClampedArray]",f="[object Uint16Array]",A="[object Uint32Array]",j=/[\\^$.*+?()[\]{}|]/g,z=/^\[object .+?Constructor\]$/,U=/^(?:0|[1-9]\d*)$/,k={};k[b]=k[w]=k[g]=k[v]=k[I]=k[O]=k[x]=k[f]=k[A]=!0,k[a]=k[c]=k[$]=k[u]=k[h]=k[d]=k[p]=k[y]=k[_]=k[S]=k[P]=k[R]=k[L]=k[B]=k[q]=!1;var Z=typeof wt=="object"&&wt&&wt.Object===Object&&wt,X=typeof self=="object"&&self&&self.Object===Object&&self,ee=Z||X||Function("return this")(),Q=e&&!e.nodeType&&e,re=Q&&!0&&t&&!t.nodeType&&t,Ze=re&&re.exports===Q,oe=Ze&&Z.process,fe=function(){try{return oe&&oe.binding&&oe.binding("util")}catch{}}(),$t=fe&&fe.isTypedArray;function xe(D,N){for(var H=-1,Y=D==null?0:D.length,je=0,ne=[];++H<Y;){var pt=D[H];N(pt,H,D)&&(ne[je++]=pt)}return ne}function qe(D,N){for(var H=-1,Y=N.length,je=D.length;++H<Y;)D[je+H]=N[H];return D}function Go(D,N){for(var H=-1,Y=D==null?0:D.length;++H<Y;)if(N(D[H],H,D))return!0;return!1}function ze(D,N){for(var H=-1,Y=Array(D);++H<D;)Y[H]=N(H);return Y}function Be(D){return function(N){return D(N)}}function vs(D,N){return D.has(N)}function De(D,N){return D?.[N]}function Le(D){var N=-1,H=Array(D.size);return D.forEach(function(Y,je){H[++N]=[je,Y]}),H}function ys(D,N){return function(H){return D(N(H))}}function Fe(D){var N=-1,H=Array(D.size);return D.forEach(function(Y){H[++N]=Y}),H}var Ue=Array.prototype,ws=Function.prototype,Ae=Object.prototype,Me=ee["__core-js_shared__"],_s=ws.toString,pe=Ae.hasOwnProperty,Ye=function(){var D=/[^.]+$/.exec(Me&&Me.keys&&Me.keys.IE_PROTO||"");return D?"Symbol(src)_1."+D:""}(),uc=Ae.toString,st=RegExp("^"+_s.call(pe).replace(j,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Je=Ze?ee.Buffer:void 0,xs=ee.Symbol,Qe=ee.Uint8Array,Xe=Ae.propertyIsEnumerable,Mu=Ue.splice,Se=xs?xs.toStringTag:void 0,et=Object.getOwnPropertySymbols,Tu=Je?Je.isBuffer:void 0,ot=ys(Object.keys,Object),ke=Yo(ee,"DataView"),Pn=Yo(ee,"Map"),He=Yo(ee,"Promise"),We=Yo(ee,"Set"),Zo=Yo(ee,"WeakMap"),Te=Yo(Object,"create"),at=Es(ke),Ru=Es(Pn),ct=Es(He),lt=Es(We),Nu=Es(Zo),tt=xs?xs.prototype:void 0,Ve=tt?tt.valueOf:void 0;function Ai(D){var N=-1,H=D==null?0:D.length;for(this.clear();++N<H;){var Y=D[N];this.set(Y[0],Y[1])}}function ut(){this.__data__=Te?Te(null):{},this.size=0}function ht(D){var N=this.has(D)&&delete this.__data__[D];return this.size-=N?1:0,N}function Bu(D){var N=this.__data__;if(Te){var H=N[D];return H===i?void 0:H}return pe.call(N,D)?N[D]:void 0}function dt(D){var N=this.__data__;return Te?N[D]!==void 0:pe.call(N,D)}function ft(D,N){var H=this.__data__;return this.size+=this.has(D)?0:1,H[D]=Te&&N===void 0?i:N,this}Ai.prototype.clear=ut,Ai.prototype.delete=ht,Ai.prototype.get=Bu,Ai.prototype.has=dt,Ai.prototype.set=ft;function Er(D){var N=-1,H=D==null?0:D.length;for(this.clear();++N<H;){var Y=D[N];this.set(Y[0],Y[1])}}function hc(){this.__data__=[],this.size=0}function dc(D){var N=this.__data__,H=Lu(N,D);if(H<0)return!1;var Y=N.length-1;return H==Y?N.pop():Mu.call(N,H,1),--this.size,!0}function fc(D){var N=this.__data__,H=Lu(N,D);return H<0?void 0:N[H][1]}function pc(D){return Lu(this.__data__,D)>-1}function gc(D,N){var H=this.__data__,Y=Lu(H,D);return Y<0?(++this.size,H.push([D,N])):H[Y][1]=N,this}Er.prototype.clear=hc,Er.prototype.delete=dc,Er.prototype.get=fc,Er.prototype.has=pc,Er.prototype.set=gc;function Jr(D){var N=-1,H=D==null?0:D.length;for(this.clear();++N<H;){var Y=D[N];this.set(Y[0],Y[1])}}function bc(){this.size=0,this.__data__={hash:new Ai,map:new(Pn||Er),string:new Ai}}function mc(D){var N=Fu(this,D).delete(D);return this.size-=N?1:0,N}function vc(D){return Fu(this,D).get(D)}function yc(D){return Fu(this,D).has(D)}function wc(D,N){var H=Fu(this,D),Y=H.size;return H.set(D,N),this.size+=H.size==Y?0:1,this}Jr.prototype.clear=bc,Jr.prototype.delete=mc,Jr.prototype.get=vc,Jr.prototype.has=yc,Jr.prototype.set=wc;function On(D){var N=-1,H=D==null?0:D.length;for(this.__data__=new Jr;++N<H;)this.add(D[N])}function _c(D){return this.__data__.set(D,i),this}function xc(D){return this.__data__.has(D)}On.prototype.add=On.prototype.push=_c,On.prototype.has=xc;function Br(D){var N=this.__data__=new Er(D);this.size=N.size}function Ec(){this.__data__=new Er,this.size=0}function $c(D){var N=this.__data__,H=N.delete(D);return this.size=N.size,H}function Ic(D){return this.__data__.get(D)}function fW(D){return this.__data__.has(D)}function pW(D,N){var H=this.__data__;if(H instanceof Er){var Y=H.__data__;if(!Pn||Y.length<r-1)return Y.push([D,N]),this.size=++H.size,this;H=this.__data__=new Jr(Y)}return H.set(D,N),this.size=H.size,this}Br.prototype.clear=Ec,Br.prototype.delete=$c,Br.prototype.get=Ic,Br.prototype.has=fW,Br.prototype.set=pW;function gW(D,N){var H=Uu(D),Y=!H&&CW(D),je=!H&&!Y&&H0(D),ne=!H&&!Y&&!je&&qw(D),pt=H||Y||je||ne,Bt=pt?ze(D.length,String):[],Wt=Bt.length;for(var rt in D)(N||pe.call(D,rt))&&!(pt&&(rt=="length"||je&&(rt=="offset"||rt=="parent")||ne&&(rt=="buffer"||rt=="byteLength"||rt=="byteOffset")||IW(rt,Wt)))&&Bt.push(rt);return Bt}function Lu(D,N){for(var H=D.length;H--;)if(Lw(D[H][0],N))return H;return-1}function bW(D,N,H){var Y=N(D);return Uu(D)?Y:qe(Y,H(D))}function Sc(D){return D==null?D===void 0?T:E:Se&&Se in Object(D)?EW(D):OW(D)}function Tw(D){return Ac(D)&&Sc(D)==a}function Rw(D,N,H,Y,je){return D===N?!0:D==null||N==null||!Ac(D)&&!Ac(N)?D!==D&&N!==N:mW(D,N,H,Y,Rw,je)}function mW(D,N,H,Y,je,ne){var pt=Uu(D),Bt=Uu(N),Wt=pt?c:Cn(D),rt=Bt?c:Cn(N);Wt=Wt==a?P:Wt,rt=rt==a?P:rt;var $r=Wt==P,Qr=rt==P,Jt=Wt==rt;if(Jt&&H0(D)){if(!H0(N))return!1;pt=!0,$r=!1}if(Jt&&!$r)return ne||(ne=new Br),pt||qw(D)?Nw(D,N,H,Y,je,ne):_W(D,N,Wt,H,Y,je,ne);if(!(H&n)){var Lr=$r&&pe.call(D,"__wrapped__"),Fr=Qr&&pe.call(N,"__wrapped__");if(Lr||Fr){var Dn=Lr?D.value():D,Ki=Fr?N.value():N;return ne||(ne=new Br),je(Dn,Ki,H,Y,ne)}}return Jt?(ne||(ne=new Br),xW(D,N,H,Y,je,ne)):!1}function vW(D){if(!jw(D)||AW(D))return!1;var N=Fw(D)?st:z;return N.test(Es(D))}function yW(D){return Ac(D)&&Uw(D.length)&&!!k[Sc(D)]}function wW(D){if(!PW(D))return ot(D);var N=[];for(var H in Object(D))pe.call(D,H)&&H!="constructor"&&N.push(H);return N}function Nw(D,N,H,Y,je,ne){var pt=H&n,Bt=D.length,Wt=N.length;if(Bt!=Wt&&!(pt&&Wt>Bt))return!1;var rt=ne.get(D);if(rt&&ne.get(N))return rt==N;var $r=-1,Qr=!0,Jt=H&s?new On:void 0;for(ne.set(D,N),ne.set(N,D);++$r<Bt;){var Lr=D[$r],Fr=N[$r];if(Y)var Dn=pt?Y(Fr,Lr,$r,N,D,ne):Y(Lr,Fr,$r,D,N,ne);if(Dn!==void 0){if(Dn)continue;Qr=!1;break}if(Jt){if(!Go(N,function(Ki,$s){if(!vs(Jt,$s)&&(Lr===Ki||je(Lr,Ki,H,Y,ne)))return Jt.push($s)})){Qr=!1;break}}else if(!(Lr===Fr||je(Lr,Fr,H,Y,ne))){Qr=!1;break}}return ne.delete(D),ne.delete(N),Qr}function _W(D,N,H,Y,je,ne,pt){switch(H){case h:if(D.byteLength!=N.byteLength||D.byteOffset!=N.byteOffset)return!1;D=D.buffer,N=N.buffer;case $:return!(D.byteLength!=N.byteLength||!ne(new Qe(D),new Qe(N)));case u:case d:case S:return Lw(+D,+N);case p:return D.name==N.name&&D.message==N.message;case R:case B:return D==N+"";case _:var Bt=Le;case L:var Wt=Y&n;if(Bt||(Bt=Fe),D.size!=N.size&&!Wt)return!1;var rt=pt.get(D);if(rt)return rt==N;Y|=s,pt.set(D,N);var $r=Nw(Bt(D),Bt(N),Y,je,ne,pt);return pt.delete(D),$r;case F:if(Ve)return Ve.call(D)==Ve.call(N)}return!1}function xW(D,N,H,Y,je,ne){var pt=H&n,Bt=Bw(D),Wt=Bt.length,rt=Bw(N),$r=rt.length;if(Wt!=$r&&!pt)return!1;for(var Qr=Wt;Qr--;){var Jt=Bt[Qr];if(!(pt?Jt in N:pe.call(N,Jt)))return!1}var Lr=ne.get(D);if(Lr&&ne.get(N))return Lr==N;var Fr=!0;ne.set(D,N),ne.set(N,D);for(var Dn=pt;++Qr<Wt;){Jt=Bt[Qr];var Ki=D[Jt],$s=N[Jt];if(Y)var zw=pt?Y($s,Ki,Jt,N,D,ne):Y(Ki,$s,Jt,D,N,ne);if(!(zw===void 0?Ki===$s||je(Ki,$s,H,Y,ne):zw)){Fr=!1;break}Dn||(Dn=Jt=="constructor")}if(Fr&&!Dn){var ju=D.constructor,qu=N.constructor;ju!=qu&&"constructor"in D&&"constructor"in N&&!(typeof ju=="function"&&ju instanceof ju&&typeof qu=="function"&&qu instanceof qu)&&(Fr=!1)}return ne.delete(D),ne.delete(N),Fr}function Bw(D){return bW(D,TW,$W)}function Fu(D,N){var H=D.__data__;return SW(N)?H[typeof N=="string"?"string":"hash"]:H.map}function Yo(D,N){var H=De(D,N);return vW(H)?H:void 0}function EW(D){var N=pe.call(D,Se),H=D[Se];try{D[Se]=void 0;var Y=!0}catch{}var je=uc.call(D);return Y&&(N?D[Se]=H:delete D[Se]),je}var $W=et?function(D){return D==null?[]:(D=Object(D),xe(et(D),function(N){return Xe.call(D,N)}))}:RW,Cn=Sc;(ke&&Cn(new ke(new ArrayBuffer(1)))!=h||Pn&&Cn(new Pn)!=_||He&&Cn(He.resolve())!=C||We&&Cn(new We)!=L||Zo&&Cn(new Zo)!=q)&&(Cn=function(D){var N=Sc(D),H=N==P?D.constructor:void 0,Y=H?Es(H):"";if(Y)switch(Y){case at:return h;case Ru:return _;case ct:return C;case lt:return L;case Nu:return q}return N});function IW(D,N){return N=N??o,!!N&&(typeof D=="number"||U.test(D))&&D>-1&&D%1==0&&D<N}function SW(D){var N=typeof D;return N=="string"||N=="number"||N=="symbol"||N=="boolean"?D!=="__proto__":D===null}function AW(D){return!!Ye&&Ye in D}function PW(D){var N=D&&D.constructor,H=typeof N=="function"&&N.prototype||Ae;return D===H}function OW(D){return uc.call(D)}function Es(D){if(D!=null){try{return _s.call(D)}catch{}try{return D+""}catch{}}return""}function Lw(D,N){return D===N||D!==D&&N!==N}var CW=Tw(function(){return arguments}())?Tw:function(D){return Ac(D)&&pe.call(D,"callee")&&!Xe.call(D,"callee")},Uu=Array.isArray;function DW(D){return D!=null&&Uw(D.length)&&!Fw(D)}var H0=Tu||NW;function MW(D,N){return Rw(D,N)}function Fw(D){if(!jw(D))return!1;var N=Sc(D);return N==y||N==m||N==l||N==M}function Uw(D){return typeof D=="number"&&D>-1&&D%1==0&&D<=o}function jw(D){var N=typeof D;return D!=null&&(N=="object"||N=="function")}function Ac(D){return D!=null&&typeof D=="object"}var qw=$t?Be($t):yW;function TW(D){return DW(D)?gW(D):wW(D)}function RW(){return[]}function NW(){return!1}t.exports=MW})(Jd,Jd.exports);var rO=Jd.exports,iO=Object.defineProperty,pv=Object.getOwnPropertySymbols,nO=Object.prototype.hasOwnProperty,sO=Object.prototype.propertyIsEnumerable,gv=(t,e,r)=>e in t?iO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rr=(t,e)=>{for(var r in e||(e={}))nO.call(e,r)&&gv(t,r,e[r]);if(pv)for(var r of pv(e))sO.call(e,r)&&gv(t,r,e[r]);return t};const bv="wc",mv=2,jl="core",vi=`${bv}@2:${jl}:`,oO={name:jl,logger:"error"},aO={database:":memory:"},cO="crypto",vv="client_ed25519_seed",lO=V.ONE_DAY,uO="keychain",hO="0.3",dO="messages",fO="0.3",yv=V.SIX_HOURS,pO="publisher",wv="irn",gO="error",_v="wss://relay.walletconnect.org",bO="relayer",Mt={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"},mO="_subscription",Mr={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},vO=.1,Qd="2.19.0-rc-1",Re={link_mode:"link_mode",relay:"relay"},yO="0.3",wO="WALLETCONNECT_CLIENT_ID",xv="WALLETCONNECT_LINK_MODE_APPS",vr={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},_O="subscription",xO="0.3",EO=V.FIVE_SECONDS*1e3,$O="pairing",IO="0.3",La={wc_pairingDelete:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:V.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:V.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:V.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:V.ONE_DAY,prompt:!1,tag:0},res:{ttl:V.ONE_DAY,prompt:!1,tag:0}}},Xn={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Vr={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},SO="history",AO="0.3",PO="expirer",Tr={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},OO="0.3",CO="verify-api",DO="https://verify.walletconnect.com",Ev="https://verify.walletconnect.org",Fa=Ev,MO=`${Fa}/v3`,TO=[DO,Ev],RO="echo",NO="https://echo.walletconnect.com",yi={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"},ki={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"},Kr={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"},es={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"},ts={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"},Ua={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"},BO=.1,LO="event-client",FO=86400,UO="https://pulse.walletconnect.org/batch";function jO(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 d(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var _=0,S=0,E=0,P=m.length;E!==P&&m[E]===0;)E++,_++;for(var C=(P-E)*u+1>>>0,M=new Uint8Array(C);E!==P;){for(var R=m[E],L=0,B=C-1;(R!==0||L<S)&&B!==-1;B--,L++)R+=256*M[B]>>>0,M[B]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");S=L,E++}for(var F=C-S;F!==C&&M[F]===0;)F++;for(var T=c.repeat(_);F<C;++F)T+=t.charAt(M[F]);return T}function p(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var _=0;if(m[_]!==" "){for(var S=0,E=0;m[_]===c;)S++,_++;for(var P=(m.length-_)*l+1>>>0,C=new Uint8Array(P);m[_];){var M=r[m.charCodeAt(_)];if(M===255)return;for(var R=0,L=P-1;(M!==0||R<E)&&L!==-1;L--,R++)M+=a*C[L]>>>0,C[L]=M%256>>>0,M=M/256>>>0;if(M!==0)throw new Error("Non-zero carry");E=R,_++}if(m[_]!==" "){for(var B=P-E;B!==P&&C[B]===0;)B++;for(var F=new Uint8Array(S+(P-B)),T=S;B!==P;)F[T++]=C[B++];return F}}}function y(m){var _=p(m);if(_)return _;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:y}}var qO=jO,zO=qO;const $v=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")},kO=t=>new TextEncoder().encode(t),HO=t=>new TextDecoder().decode(t);class WO{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 VO{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 Iv(this,e)}}class KO{constructor(e){this.decoders=e}or(e){return Iv(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 Iv=(t,e)=>new KO(rr(rr({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class GO{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new WO(e,r,i),this.decoder=new VO(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ql=({name:t,prefix:e,encode:r,decode:i})=>new GO(t,e,r,i),ja=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=zO(r,e);return ql({prefix:t,name:e,encode:i,decode:s=>$v(n(s))})},ZO=(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 d=n[t[u]];if(d===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|d,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},YO=(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},zt=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>ql({prefix:e,name:t,encode(n){return YO(n,i,r)},decode(n){return ZO(n,i,r,t)}}),JO=ql({prefix:"\0",name:"identity",encode:t=>HO(t),decode:t=>kO(t)});var QO=Object.freeze({__proto__:null,identity:JO});const XO=zt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var eC=Object.freeze({__proto__:null,base2:XO});const tC=zt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var rC=Object.freeze({__proto__:null,base8:tC});const iC=ja({prefix:"9",name:"base10",alphabet:"0123456789"});var nC=Object.freeze({__proto__:null,base10:iC});const sC=zt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),oC=zt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var aC=Object.freeze({__proto__:null,base16:sC,base16upper:oC});const cC=zt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),lC=zt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),uC=zt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),hC=zt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),dC=zt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),fC=zt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),pC=zt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gC=zt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),bC=zt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var mC=Object.freeze({__proto__:null,base32:cC,base32upper:lC,base32pad:uC,base32padupper:hC,base32hex:dC,base32hexupper:fC,base32hexpad:pC,base32hexpadupper:gC,base32z:bC});const vC=ja({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),yC=ja({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var wC=Object.freeze({__proto__:null,base36:vC,base36upper:yC});const _C=ja({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xC=ja({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var EC=Object.freeze({__proto__:null,base58btc:_C,base58flickr:xC});const $C=zt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),IC=zt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),SC=zt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),AC=zt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var PC=Object.freeze({__proto__:null,base64:$C,base64pad:IC,base64url:SC,base64urlpad:AC});const Sv=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}"),OC=Sv.reduce((t,e,r)=>(t[r]=e,t),[]),CC=Sv.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function DC(t){return t.reduce((e,r)=>(e+=OC[r],e),"")}function MC(t){const e=[];for(const r of t){const i=CC[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const TC=ql({prefix:"\u{1F680}",name:"base256emoji",encode:DC,decode:MC});var RC=Object.freeze({__proto__:null,base256emoji:TC}),NC=Pv,Av=128,BC=127,LC=~BC,FC=Math.pow(2,31);function Pv(t,e,r){e=e||[],r=r||0;for(var i=r;t>=FC;)e[r++]=t&255|Av,t/=128;for(;t&LC;)e[r++]=t&255|Av,t>>>=7;return e[r]=t|0,Pv.bytes=r-i+1,e}var UC=Xd,jC=128,Ov=127;function Xd(t,i){var r=0,i=i||0,n=0,s=i,o,a=t.length;do{if(s>=a)throw Xd.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=n<28?(o&Ov)<<n:(o&Ov)*Math.pow(2,n),n+=7}while(o>=jC);return Xd.bytes=s-i,r}var qC=Math.pow(2,7),zC=Math.pow(2,14),kC=Math.pow(2,21),HC=Math.pow(2,28),WC=Math.pow(2,35),VC=Math.pow(2,42),KC=Math.pow(2,49),GC=Math.pow(2,56),ZC=Math.pow(2,63),YC=function(t){return t<qC?1:t<zC?2:t<kC?3:t<HC?4:t<WC?5:t<VC?6:t<KC?7:t<GC?8:t<ZC?9:10},JC={encode:NC,decode:UC,encodingLength:YC},Cv=JC;const Dv=(t,e,r=0)=>(Cv.encode(t,e,r),e),Mv=t=>Cv.encodingLength(t),ef=(t,e)=>{const r=e.byteLength,i=Mv(t),n=i+Mv(r),s=new Uint8Array(n+r);return Dv(t,s,0),Dv(r,s,i),s.set(e,n),new QC(t,r,e,s)};class QC{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const Tv=({name:t,code:e,encode:r})=>new XC(t,e,r);class XC{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?ef(this.code,r):r.then(i=>ef(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Rv=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),eD=Tv({name:"sha2-256",code:18,encode:Rv("SHA-256")}),tD=Tv({name:"sha2-512",code:19,encode:Rv("SHA-512")});var rD=Object.freeze({__proto__:null,sha256:eD,sha512:tD});const Nv=0,iD="identity",Bv=$v;var nD=Object.freeze({__proto__:null,identity:{code:Nv,name:iD,encode:Bv,digest:t=>ef(Nv,Bv(t))}});new TextEncoder,new TextDecoder;const Lv=rr(rr(rr(rr(rr(rr(rr(rr(rr(rr({},QO),eC),rC),nC),aC),mC),wC),EC),PC),RC);rr(rr({},rD),nD);function sD(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Fv(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const Uv=Fv("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),tf=Fv("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=sD(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),oD=rr({utf8:Uv,"utf-8":Uv,hex:Lv.base16,latin1:tf,ascii:tf,binary:tf},Lv);function aD(t,e="utf8"){const r=oD[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 cD=Object.defineProperty,lD=(t,e,r)=>e in t?cD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wi=(t,e,r)=>lD(t,typeof e!="symbol"?e+"":e,r);class uD{constructor(e,r){this.core=e,this.logger=r,wi(this,"keychain",new Map),wi(this,"name",uO),wi(this,"version",hO),wi(this,"initialized",!1),wi(this,"storagePrefix",vi),wi(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),wi(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),wi(this,"set",async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()}),wi(this,"get",i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=K("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n}),wi(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=tr(r,this.name)}get context(){return lr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Pb(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ob(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}}var hD=Object.defineProperty,dD=(t,e,r)=>e in t?hD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,kt=(t,e,r)=>dD(t,typeof e!="symbol"?e+"":e,r);class fD{constructor(e,r,i){this.core=e,this.logger=r,kt(this,"name",cO),kt(this,"keychain"),kt(this,"randomSessionIdentifier",Rd()),kt(this,"initialized",!1),kt(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),kt(this,"hasKeys",n=>(this.isInitialized(),this.keychain.has(n))),kt(this,"getClientId",async()=>{this.isInitialized();const n=await this.getClientSeed(),s=yg(n);return vg(s.publicKey)}),kt(this,"generateKeyPair",()=>{this.isInitialized();const n=WI();return this.setPrivateKey(n.publicKey,n.privateKey)}),kt(this,"signJWT",async n=>{this.isInitialized();const s=await this.getClientSeed(),o=yg(s),a=this.randomSessionIdentifier;return await e9(a,n,lO,o)}),kt(this,"generateSharedKey",(n,s,o)=>{this.isInitialized();const a=this.getPrivateKey(n),c=VI(a,s);return this.setSymKey(c,o)}),kt(this,"setSymKey",async(n,s)=>{this.isInitialized();const o=s||$l(n);return await this.keychain.set(o,n),o}),kt(this,"deleteKeyPair",async n=>{this.isInitialized(),await this.keychain.del(n)}),kt(this,"deleteSymKey",async n=>{this.isInitialized(),await this.keychain.del(n)}),kt(this,"encode",async(n,s,o)=>{this.isInitialized();const a=Sm(o),c=Mi(s);if(Pm(a))return ZI(c,o?.encoding);if(Am(a)){const p=a.senderPublicKey,y=a.receiverPublicKey;n=await this.generateSharedKey(p,y)}const l=this.getSymKey(n),{type:u,senderPublicKey:d}=a;return KI({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o?.encoding})}),kt(this,"decode",async(n,s,o)=>{this.isInitialized();const a=JI(s,o);if(Pm(a)){const c=YI(s,o?.encoding);return Fn(c)}if(Am(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;n=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(n),l=GI({symKey:c,encoded:s,encoding:o?.encoding});return Fn(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),kt(this,"getPayloadType",(n,s=pn)=>{const o=Sa({encoded:n,encoding:s});return Zn(o.type)}),kt(this,"getPayloadSenderPublicKey",(n,s=pn)=>{const o=Sa({encoded:n,encoding:s});return o.senderPublicKey?Xt(o.senderPublicKey,Gt):void 0}),this.core=e,this.logger=tr(r,this.name),this.keychain=i||new uD(this.core,this.logger)}get context(){return lr(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(vv)}catch{e=Rd(),await this.keychain.set(vv,e)}return aD(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}}var pD=Object.defineProperty,gD=(t,e,r)=>e in t?pD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_i=(t,e,r)=>gD(t,typeof e!="symbol"?e+"":e,r);class bD extends tP{constructor(e,r){super(e,r),this.logger=e,this.core=r,_i(this,"messages",new Map),_i(this,"name",dO),_i(this,"version",fO),_i(this,"initialized",!1),_i(this,"storagePrefix",vi),_i(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}}}),_i(this,"set",async(i,n)=>{this.isInitialized();const s=ji(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}),_i(this,"get",i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n}),_i(this,"has",(i,n)=>{this.isInitialized();const s=this.get(i),o=ji(n);return typeof s[o]<"u"}),_i(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()}),this.logger=tr(e,this.name),this.core=r}get context(){return lr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Pb(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ob(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}}var mD=Object.defineProperty,vD=Object.defineProperties,yD=Object.getOwnPropertyDescriptors,jv=Object.getOwnPropertySymbols,wD=Object.prototype.hasOwnProperty,_D=Object.prototype.propertyIsEnumerable,rf=(t,e,r)=>e in t?mD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zl=(t,e)=>{for(var r in e||(e={}))wD.call(e,r)&&rf(t,r,e[r]);if(jv)for(var r of jv(e))_D.call(e,r)&&rf(t,r,e[r]);return t},nf=(t,e)=>vD(t,yD(e)),Gr=(t,e,r)=>rf(t,typeof e!="symbol"?e+"":e,r);class xD extends rP{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,Gr(this,"events",new Lt.exports.EventEmitter),Gr(this,"name",pO),Gr(this,"queue",new Map),Gr(this,"publishTimeout",V.toMiliseconds(V.ONE_MINUTE)),Gr(this,"initialPublishTimeout",V.toMiliseconds(V.ONE_SECOND*15)),Gr(this,"needsTransportRestart",!1),Gr(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||yv,c=Il(s),l=s?.prompt||!1,u=s?.tag||0,d=s?.id||Qn().toString(),p={topic:i,message:n,opts:{ttl:a,relay:c,prompt:l,tag:u,id:d,attestation:s?.attestation,tvf:s?.tvf}},y=`Failed to publish payload, please try again. id:${d} tag:${u}`;try{const m=new Promise(async _=>{const S=({id:P})=>{p.opts.id===P&&(this.removeRequestFromQueue(P),this.relayer.events.removeListener(Mt.publish,S),_(p))};this.relayer.events.on(Mt.publish,S);const E=ln(new Promise((P,C)=>{this.rpcPublish({topic:i,message:n,ttl:a,prompt:l,tag:u,id:d,attestation:s?.attestation,tvf:s?.tvf}).then(P).catch(M=>{this.logger.warn(M,M?.message),C(M)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${u}`);try{await E,this.events.removeListener(Mt.publish,S)}catch(P){this.queue.set(d,nf(zl({},p),{attempt:1})),this.logger.warn(P,P?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:i,message:n,opts:s}}),await ln(m,this.publishTimeout,y)}catch(m){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(m),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw m}finally{this.queue.delete(d)}}),Gr(this,"on",(i,n)=>{this.events.on(i,n)}),Gr(this,"once",(i,n)=>{this.events.once(i,n)}),Gr(this,"off",(i,n)=>{this.events.off(i,n)}),Gr(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.relayer=e,this.logger=tr(r,this.name),this.registerEventListeners()}get context(){return lr(this.logger)}async rpcPublish(e){var r,i,n,s;const{topic:o,message:a,ttl:c=yv,prompt:l,tag:u,id:d,attestation:p,tvf:y}=e,m={method:Aa(Il().protocol).publish,params:zl({topic:o,message:a,ttl:c,prompt:l,tag:u,attestation:p},y),id:d};er((r=m.params)==null?void 0:r.prompt)&&((i=m.params)==null||delete i.prompt),er((n=m.params)==null?void 0:n.tag)&&((s=m.params)==null||delete s.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:m});const _=await this.relayer.request(m);return this.relayer.events.emit(Mt.publish,e),this.logger.debug("Successfully Published Payload"),_}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const i=e.attempt+1;this.queue.set(r,nf(zl({},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(nf(zl({},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(ao.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Mt.connection_stalled);return}this.checkQueue()}),this.relayer.on(Mt.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var ED=Object.defineProperty,$D=(t,e,r)=>e in t?ED(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,uo=(t,e,r)=>$D(t,typeof e!="symbol"?e+"":e,r);class ID{constructor(){uo(this,"map",new Map),uo(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),uo(this,"get",e=>this.map.get(e)||[]),uo(this,"exists",(e,r)=>this.get(e).includes(r)),uo(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)}),uo(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var SD=Object.defineProperty,AD=Object.defineProperties,PD=Object.getOwnPropertyDescriptors,qv=Object.getOwnPropertySymbols,OD=Object.prototype.hasOwnProperty,CD=Object.prototype.propertyIsEnumerable,sf=(t,e,r)=>e in t?SD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qa=(t,e)=>{for(var r in e||(e={}))OD.call(e,r)&&sf(t,r,e[r]);if(qv)for(var r of qv(e))CD.call(e,r)&&sf(t,r,e[r]);return t},of=(t,e)=>AD(t,PD(e)),Ie=(t,e,r)=>sf(t,typeof e!="symbol"?e+"":e,r);class DD extends sP{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,Ie(this,"subscriptions",new Map),Ie(this,"topicMap",new ID),Ie(this,"events",new Lt.exports.EventEmitter),Ie(this,"name",_O),Ie(this,"version",xO),Ie(this,"pending",new Map),Ie(this,"cached",[]),Ie(this,"initialized",!1),Ie(this,"pendingSubscriptionWatchLabel","pending_sub_watch_label"),Ie(this,"pollingInterval",20),Ie(this,"storagePrefix",vi),Ie(this,"subscribeTimeout",V.toMiliseconds(V.ONE_MINUTE)),Ie(this,"initialSubscribeTimeout",V.toMiliseconds(V.ONE_SECOND*15)),Ie(this,"clientId"),Ie(this,"batchSubscribeTopicsLimit",500),Ie(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Ie(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=Il(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}}),Ie(this,"unsubscribe",async(i,n)=>{this.isInitialized(),typeof n?.id<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)}),Ie(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 V.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)>=EO&&(clearInterval(c),a.stop(n),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)}),Ie(this,"on",(i,n)=>{this.events.on(i,n)}),Ie(this,"once",(i,n)=>{this.events.once(i,n)}),Ie(this,"off",(i,n)=>{this.events.off(i,n)}),Ie(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),Ie(this,"start",async()=>{await this.onConnect()}),Ie(this,"stop",async()=>{await this.onDisconnect()}),Ie(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Ie(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)}),Ie(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(ao.pulse,async()=>{await this.checkPending()}),this.events.on(vr.created,async i=>{const n=vr.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()}),this.events.on(vr.deleted,async i=>{const n=vr.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()})}),this.relayer=e,this.logger=tr(r,this.name),this.clientId=""}get context(){return lr(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}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}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=Il(i);await this.restartToComplete({topic:e,id:r,relay:n}),await this.rpcUnsubscribe(e,r,n);const s=_e("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||i?.transportType===Re.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const s={method:Aa(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===Re.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(u=>this.logger.warn(u))},V.toMiliseconds(V.ONE_SECOND)),a;const c=new Promise(async u=>{const d=p=>{p.topic===e&&(this.events.removeListener(vr.created,d),u(p.id))};this.events.on(vr.created,d);try{const p=await ln(new Promise((y,m)=>{this.relayer.request(s).catch(_=>{this.logger.warn(_,_?.message),m(_)}).then(y)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(vr.created,d),u(p)}catch{}}),l=await ln(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(Mt.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:Aa(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 ln(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(Mt.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:Aa(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 ln(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(Mt.connection_stalled)}return n}rpcUnsubscribe(e,r,i){const n={method:Aa(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,of(qa({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,qa({},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,qa({},r)),this.topicMap.set(r.topic,e),this.events.emit(vr.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}=K("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(vr.deleted,of(qa({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(vr.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(vr.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=K("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=>of(qa({},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 a$(V.toMiliseconds(V.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}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return ji(e+await this.getClientId())}}var MD=Object.defineProperty,zv=Object.getOwnPropertySymbols,TD=Object.prototype.hasOwnProperty,RD=Object.prototype.propertyIsEnumerable,af=(t,e,r)=>e in t?MD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,kv=(t,e)=>{for(var r in e||(e={}))TD.call(e,r)&&af(t,r,e[r]);if(zv)for(var r of zv(e))RD.call(e,r)&&af(t,r,e[r]);return t},be=(t,e,r)=>af(t,typeof e!="symbol"?e+"":e,r);class ND extends iP{constructor(e){super(e),be(this,"protocol","wc"),be(this,"version",2),be(this,"core"),be(this,"logger"),be(this,"events",new Lt.exports.EventEmitter),be(this,"provider"),be(this,"messages"),be(this,"subscriber"),be(this,"publisher"),be(this,"name",bO),be(this,"transportExplicitlyClosed",!1),be(this,"initialized",!1),be(this,"connectionAttemptInProgress",!1),be(this,"relayUrl"),be(this,"projectId"),be(this,"packageName"),be(this,"bundleId"),be(this,"hasExperiencedNetworkDisruption",!1),be(this,"pingTimeout"),be(this,"heartBeatTimeout",V.toMiliseconds(V.THIRTY_SECONDS+V.FIVE_SECONDS)),be(this,"reconnectTimeout"),be(this,"connectPromise"),be(this,"reconnectInProgress",!1),be(this,"requestsInFlight",[]),be(this,"connectTimeout",V.toMiliseconds(V.ONE_SECOND*15)),be(this,"request",async r=>{var i,n;this.logger.debug("Publishing Request Payload");const s=r.id||Qn().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}}),be(this,"resetPingTimeout",()=>{if(gl())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)}}),be(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),be(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Mt.connect)}),be(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),be(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(Mt.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),be(this,"registerProviderListeners",()=>{this.provider.on(Mr.payload,this.onPayloadHandler),this.provider.on(Mr.connect,this.onConnectHandler),this.provider.on(Mr.disconnect,this.onDisconnectHandler),this.provider.on(Mr.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?tr(e.logger,this.name):pi(Bl({level:e.logger||gO})),this.messages=new bD(this.logger,e.core),this.subscriber=new DD(this,this.logger),this.publisher=new xD(this,this.logger),this.relayUrl=e?.relayUrl||_v,this.projectId=e.projectId,VE()?this.packageName=Ib():KE()&&(this.bundleId=Ib()),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.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return lr(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||!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||this.connectPromise!==void 0||!1}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:Re.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(vr.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(vr.created,l)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(e,kv({internal:{throwOnFailedPublish:o}},r)).catch(p=>{o&&d(p)})||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 ln(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}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 Fm())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=xt(V.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,s)}this.events.emit(Mt.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{if(this.transportExplicitlyClosed)break;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(Mr.disconnect,s),await ln(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(Mr.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Mr.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Mr.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,V.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,n,s;if(gl())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 Dr(new tO(JE({sdkVersion:Qd,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}),Yd(e)){if(!e.method.endsWith(mO))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:o}=r.data,a={topic:i,message:n,publishedAt:s,transportType:Re.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(kv({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Ul(e)&&this.events.emit(Mt.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Mt.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=Ll(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Mr.payload,this.onPayloadHandler),this.provider.off(Mr.connect,this.onConnectHandler),this.provider.off(Mr.disconnect,this.onDisconnectHandler),this.provider.off(Mr.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Fm();FS(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(){clearTimeout(this.pingTimeout),this.events.emit(Mt.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},V.toMiliseconds(vO)))))}isInitialized(){if(!this.initialized){const{message:e}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.connect()}}var BD=Object.defineProperty,Hv=Object.getOwnPropertySymbols,LD=Object.prototype.hasOwnProperty,FD=Object.prototype.propertyIsEnumerable,cf=(t,e,r)=>e in t?BD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wv=(t,e)=>{for(var r in e||(e={}))LD.call(e,r)&&cf(t,r,e[r]);if(Hv)for(var r of Hv(e))FD.call(e,r)&&cf(t,r,e[r]);return t},ur=(t,e,r)=>cf(t,typeof e!="symbol"?e+"":e,r);class rs extends nP{constructor(e,r,i,n=vi,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,ur(this,"map",new Map),ur(this,"version",yO),ur(this,"cached",[]),ur(this,"initialized",!1),ur(this,"getKey"),ur(this,"storagePrefix",vi),ur(this,"recentlyDeleted",[]),ur(this,"recentlyDeletedLimit",200),ur(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!er(o)?this.map.set(this.getKey(o),o):gS(o)?this.map.set(o.id,o):bS(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),ur(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())}),ur(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),ur(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>rO(a[c],o[c]))):this.values)),ur(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=Wv(Wv({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),ur(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=tr(r,this.name),this.storagePrefix=n,this.getKey=s}get context(){return lr(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}=K("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:i}=K("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}=K("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}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}}var UD=Object.defineProperty,jD=(t,e,r)=>e in t?UD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,le=(t,e,r)=>jD(t,typeof e!="symbol"?e+"":e,r);class qD{constructor(e,r){this.core=e,this.logger=r,le(this,"name",$O),le(this,"version",IO),le(this,"events",new Lt.exports),le(this,"pairings"),le(this,"initialized",!1),le(this,"storagePrefix",vi),le(this,"ignoredPayloadTypes",[Ui]),le(this,"registeredMethods",[]),le(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),le(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),le(this,"create",async i=>{this.isInitialized();const n=Rd(),s=await this.core.crypto.setSymKey(n),o=xt(V.FIVE_MINUTES),a={protocol:wv},c={topic:s,expiry:o,relay:a,active:!1,methods:i?.methods},l=Cm({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:a,expiryTimestamp:o,methods:i?.methods});return this.events.emit(Xn.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}}),le(this,"pair",async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i?.uri,trace:[yi.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=Om(i.uri);n.props.properties.topic=s,n.addTrace(yi.pairing_uri_validation_success),n.addTrace(yi.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),n.addTrace(yi.existing_pairing),u.active)throw n.setError(ki.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(yi.pairing_not_expired)}const d=c||xt(V.FIVE_MINUTES),p={topic:s,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(s,d),await this.pairings.set(s,p),n.addTrace(yi.store_new_pairing),i.activatePairing&&await this.activate({topic:s}),this.events.emit(Xn.create,p),n.addTrace(yi.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),n.addTrace(yi.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(ki.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(y){throw n.setError(ki.subscribe_pairing_topic_failure),y}return n.addTrace(yi.subscribe_pairing_topic_success),p}),le(this,"activate",async({topic:i})=>{this.isInitialized();const n=xt(V.FIVE_MINUTES);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})}),le(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}=Kn();this.events.once(ye("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),le(this,"updateExpiry",async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})}),le(this,"updateMetadata",async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})}),le(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),le(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",_e("USER_DISCONNECTED")),await this.deletePairing(n))}),le(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:n,relay:s,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(n);return Cm({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),le(this,"sendRequest",async(i,n,s)=>{const o=gn(n,s),a=await this.core.crypto.encode(i,o),c=La[n].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),le(this,"sendResult",async(i,n,s)=>{const o=Ll(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,l=La[c].res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),le(this,"sendError",async(i,n,s)=>{const o=Fl(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,l=La[c]?La[c].res:La.unregistered_method.res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),le(this,"deletePairing",async(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,_e("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])}),le(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(n=>un(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))}),le(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)}}),le(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)}}),le(this,"onPairingPingRequest",async(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(Xn.ping,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),le(this,"onPairingPingResponse",(i,n)=>{const{id:s}=n;setTimeout(()=>{mi(n)?this.events.emit(ye("pairing_ping",s),{}):Cr(n)&&this.events.emit(ye("pairing_ping",s),{error:n.error})},500)}),le(this,"onPairingDeleteRequest",async(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Xn.delete,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),le(this,"onUnknownRpcMethodRequest",async(i,n)=>{const{id:s,method:o}=n;try{if(this.registeredMethods.includes(o))return;const a=_e("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)}}),le(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(_e("WC_METHOD_UNSUPPORTED",i))}),le(this,"isValidPair",(i,n)=>{var s;if(!ar(i)){const{message:a}=K("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(ki.malformed_pairing_uri),new Error(a)}if(!pS(i.uri)){const{message:a}=K("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(ki.malformed_pairing_uri),new Error(a)}const o=Om(i?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=K("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(ki.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=K("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(ki.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&V.toMiliseconds(o?.expiryTimestamp)<Date.now()){n.setError(ki.pairing_expired);const{message:a}=K("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),le(this,"isValidPing",async i=>{if(!ar(i)){const{message:s}=K("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),le(this,"isValidDisconnect",async i=>{if(!ar(i)){const{message:s}=K("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),le(this,"isValidPairingTopic",async i=>{if(!mt(i,!1)){const{message:n}=K("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=K("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(un(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=K("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}}),this.core=e,this.logger=tr(r,this.name),this.pairings=new rs(this.core,this.logger,this.name,this.storagePrefix)}get context(){return lr(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Mt.message,async e=>{const{topic:r,message:i,transportType:n}=e;if(!this.pairings.keys.includes(r)||n===Re.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const s=await this.core.crypto.decode(r,i);try{Yd(s)?(this.core.history.set(r,s),this.onRelayEventRequest({topic:r,payload:s})):Ul(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(Tr.expired,async e=>{const{topic:r}=Db(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Xn.expire,{topic:r}))})}}var zD=Object.defineProperty,kD=(t,e,r)=>e in t?zD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ht=(t,e,r)=>kD(t,typeof e!="symbol"?e+"":e,r);class HD extends eP{constructor(e,r){super(e,r),this.core=e,this.logger=r,Ht(this,"records",new Map),Ht(this,"events",new Lt.exports.EventEmitter),Ht(this,"name",SO),Ht(this,"version",AO),Ht(this,"cached",[]),Ht(this,"initialized",!1),Ht(this,"storagePrefix",vi),Ht(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)}),Ht(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:xt(V.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Vr.created,o)}),Ht(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=Cr(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(Vr.updated,n))}),Ht(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))),Ht(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(Vr.deleted,s)}}),this.persist()}),Ht(this,"exists",async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1)),Ht(this,"on",(i,n)=>{this.events.on(i,n)}),Ht(this,"once",(i,n)=>{this.events.once(i,n)}),Ht(this,"off",(i,n)=>{this.events.off(i,n)}),Ht(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=tr(r,this.name)}get context(){return lr(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:gn(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}=K("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Vr.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=K("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(Vr.created,e=>{const r=Vr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Vr.updated,e=>{const r=Vr.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Vr.deleted,e=>{const r=Vr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(ao.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{V.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Vr.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}}var WD=Object.defineProperty,VD=(t,e,r)=>e in t?WD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zt=(t,e,r)=>VD(t,typeof e!="symbol"?e+"":e,r);class KD extends oP{constructor(e,r){super(e,r),this.core=e,this.logger=r,Zt(this,"expirations",new Map),Zt(this,"events",new Lt.exports.EventEmitter),Zt(this,"name",PO),Zt(this,"version",OO),Zt(this,"cached",[]),Zt(this,"initialized",!1),Zt(this,"storagePrefix",vi),Zt(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)}),Zt(this,"has",i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}}),Zt(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(Tr.created,{target:s,expiration:o})}),Zt(this,"get",i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)}),Zt(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(Tr.deleted,{target:n,expiration:s})}}),Zt(this,"on",(i,n)=>{this.events.on(i,n)}),Zt(this,"once",(i,n)=>{this.events.once(i,n)}),Zt(this,"off",(i,n)=>{this.events.off(i,n)}),Zt(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=tr(r,this.name)}get context(){return lr(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 QE(e);if(typeof e=="number")return XE(e);const{message:r}=K("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(Tr.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=K("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}=K("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;V.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Tr.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(ao.pulse,()=>this.checkExpirations()),this.events.on(Tr.created,e=>{const r=Tr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Tr.expired,e=>{const r=Tr.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Tr.deleted,e=>{const r=Tr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}}var GD=Object.defineProperty,ZD=(t,e,r)=>e in t?GD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yt=(t,e,r)=>ZD(t,typeof e!="symbol"?e+"":e,r);class YD extends aP{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,yt(this,"name",CO),yt(this,"abortController"),yt(this,"isDevEnv"),yt(this,"verifyUrlV3",MO),yt(this,"storagePrefix",vi),yt(this,"version",mv),yt(this,"publicKey"),yt(this,"fetchPromise"),yt(this,"init",async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&V.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),yt(this,"register",async n=>{if(!ba()||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=ea(),u=this.startAbortTimer(V.ONE_SECOND*5),d=await new Promise((p,y)=>{const m=()=>{window.removeEventListener("message",S),l.body.removeChild(_),y("attestation aborted")};this.abortController.signal.addEventListener("abort",m);const _=l.createElement("iframe");_.src=c,_.style.display="none",_.addEventListener("error",m,{signal:this.abortController.signal});const S=E=>{if(E.data&&typeof E.data=="string")try{const P=JSON.parse(E.data);if(P.type==="verify_attestation"){if(Gh(P.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(_),this.abortController.signal.removeEventListener("abort",m),window.removeEventListener("message",S),p(P.attestation===null?"":P.attestation)}}catch(P){this.logger.warn(P)}};l.body.appendChild(_),window.addEventListener("message",S,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",d),d}catch(l){this.logger.warn(l)}return""}),yt(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(Gh(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)}),yt(this,"fetchAttestation",async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const o=this.startAbortTimer(V.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}),yt(this,"getVerifyUrl",n=>{let s=n||Fa;return TO.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Fa}`),s=Fa),s}),yt(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(V.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)}}),yt(this,"persistPublicKey",async n=>{this.logger.debug("persisting public key to local storage",n),await this.store.setItem(this.storeKey,n),this.publicKey=n}),yt(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),yt(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")}}),yt(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),yt(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}),yt(this,"validateAttestation",(n,s)=>{const o=tS(n,s.publicKey),a={hasExpired:V.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=tr(r,this.name),this.abortController=new AbortController,this.isDevEnv=gd(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return lr(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),V.toMiliseconds(e))}}var JD=Object.defineProperty,QD=(t,e,r)=>e in t?JD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Vv=(t,e,r)=>QD(t,typeof e!="symbol"?e+"":e,r);class XD extends cP{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,Vv(this,"context",RO),Vv(this,"registerDeviceToken",async i=>{const{clientId:n,token:s,notificationType:o,enableEncrypted:a=!1}=i,c=`${NO}/${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=tr(r,this.context)}}var eM=Object.defineProperty,Kv=Object.getOwnPropertySymbols,tM=Object.prototype.hasOwnProperty,rM=Object.prototype.propertyIsEnumerable,lf=(t,e,r)=>e in t?eM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,za=(t,e)=>{for(var r in e||(e={}))tM.call(e,r)&&lf(t,r,e[r]);if(Kv)for(var r of Kv(e))rM.call(e,r)&&lf(t,r,e[r]);return t},Tt=(t,e,r)=>lf(t,typeof e!="symbol"?e+"":e,r);class iM extends lP{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,Tt(this,"context",LO),Tt(this,"storagePrefix",vi),Tt(this,"storageVersion",BO),Tt(this,"events",new Map),Tt(this,"shouldPersist",!1),Tt(this,"init",async()=>{if(!gd())try{const n={eventId:Tb(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Ab(this.core.relayer.protocol,this.core.relayer.version,Qd)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}}),Tt(this,"createEvent",n=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=n,l=Tb(),u=this.core.projectId||"",d=Date.now(),p=za({eventId:l,timestamp:d,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,p),this.shouldPersist=!0),p}),Tt(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 za(za({},a),this.setMethods(a.eventId))}),Tt(this,"deleteEvent",n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0}),Tt(this,"setEventListeners",()=>{this.core.heartbeat.on(ao.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{V.fromMiliseconds(Date.now())-V.fromMiliseconds(n.timestamp)>FO&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})}),Tt(this,"setMethods",n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)})),Tt(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)}),Tt(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)}),Tt(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Tt(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,za(za({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}}),Tt(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)}}),Tt(this,"sendEvent",async n=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${UO}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Qd}${s}`,{method:"POST",body:JSON.stringify(n)})}),Tt(this,"getAppDomain",()=>Sb().url),this.logger=tr(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 nM=Object.defineProperty,Gv=Object.getOwnPropertySymbols,sM=Object.prototype.hasOwnProperty,oM=Object.prototype.propertyIsEnumerable,uf=(t,e,r)=>e in t?nM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zv=(t,e)=>{for(var r in e||(e={}))sM.call(e,r)&&uf(t,r,e[r]);if(Gv)for(var r of Gv(e))oM.call(e,r)&&uf(t,r,e[r]);return t},Ce=(t,e,r)=>uf(t,typeof e!="symbol"?e+"":e,r);class hf extends YA{constructor(e){var r;super(e),Ce(this,"protocol",bv),Ce(this,"version",mv),Ce(this,"name",jl),Ce(this,"relayUrl"),Ce(this,"projectId"),Ce(this,"customStoragePrefix"),Ce(this,"events",new Lt.exports.EventEmitter),Ce(this,"logger"),Ce(this,"heartbeat"),Ce(this,"relayer"),Ce(this,"crypto"),Ce(this,"storage"),Ce(this,"history"),Ce(this,"expirer"),Ce(this,"pairing"),Ce(this,"verify"),Ce(this,"echoClient"),Ce(this,"linkModeSupportedApps"),Ce(this,"eventClient"),Ce(this,"initialized",!1),Ce(this,"logChunkController"),Ce(this,"on",(o,a)=>this.events.on(o,a)),Ce(this,"once",(o,a)=>this.events.once(o,a)),Ce(this,"off",(o,a)=>this.events.off(o,a)),Ce(this,"removeListener",(o,a)=>this.events.removeListener(o,a)),Ce(this,"dispatchEnvelope",({topic:o,message:a,sessionExists:c})=>{if(!o||!a)return;const l={topic:o,message:a,publishedAt:Date.now(),transportType:Re.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:c})}),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||_v,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Bl({level:typeof e?.logger=="string"&&e.logger?e.logger:oO.logger,name:jl}),{logger:n,chunkLoggerController:s}=KA({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=tr(n,this.name),this.heartbeat=new Ud,this.crypto=new fD(this,this.logger,e?.keychain),this.history=new HD(this,this.logger),this.expirer=new KD(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new yA(Zv(Zv({},aO),e?.storageOptions)),this.relayer=new ND({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new qD(this,this.logger),this.verify=new YD(this,this.logger,this.storage),this.echoClient=new XD(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new iM(this,this.logger,e?.telemetryEnabled)}static async init(e){const r=new hf(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(wO,i),r}get context(){return lr(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(xv,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(xv)||[],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 aM=hf,Yv="wc",Jv=2,Qv="client",df=`${Yv}@${Jv}:${Qv}:`,ff={name:Qv,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Xv="WALLETCONNECT_DEEPLINK_CHOICE",cM="proposal",e2="Proposal expired",lM="session",ho=V.SEVEN_DAYS,uM="engine",Rt={wc_sessionPropose:{req:{ttl:V.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1104},res:{ttl:V.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1106},res:{ttl:V.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:V.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:V.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1112},res:{ttl:V.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1114},res:{ttl:V.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:V.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:V.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1119}}},pf={min:V.FIVE_MINUTES,max:V.SEVEN_DAYS},xi={idle:"IDLE",active:"ACTIVE"},t2={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},hM="request",dM=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],fM="wc",pM="auth",gM="authKeys",bM="pairingTopics",mM="requests",kl=`${fM}@${1.5}:${pM}:`,Hl=`${kl}:PUB_KEY`;var vM=Object.defineProperty,yM=Object.defineProperties,wM=Object.getOwnPropertyDescriptors,r2=Object.getOwnPropertySymbols,_M=Object.prototype.hasOwnProperty,xM=Object.prototype.propertyIsEnumerable,gf=(t,e,r)=>e in t?vM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ke=(t,e)=>{for(var r in e||(e={}))_M.call(e,r)&&gf(t,r,e[r]);if(r2)for(var r of r2(e))xM.call(e,r)&&gf(t,r,e[r]);return t},hr=(t,e)=>yM(t,wM(e)),W=(t,e,r)=>gf(t,typeof e!="symbol"?e+"":e,r);class EM extends fP{constructor(e){super(e),W(this,"name",uM),W(this,"events",new Lt.exports),W(this,"initialized",!1),W(this,"requestQueue",{state:xi.idle,queue:[]}),W(this,"sessionRequestQueue",{state:xi.idle,queue:[]}),W(this,"requestQueueDelay",V.ONE_SECOND),W(this,"expectedPairingMethodMap",new Map),W(this,"recentlyDeletedMap",new Map),W(this,"recentlyDeletedLimit",200),W(this,"relayMessageCache",[]),W(this,"pendingSessions",new Map),W(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(Rt)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},V.toMiliseconds(this.requestQueueDelay)))}),W(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=hr(Ke({},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,d=!1;try{if(l){const R=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."),d=R.active}}catch(R){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),R}if(!l||!d){const{topic:R,uri:L}=await this.client.core.pairing.create();l=R,u=L}if(!l){const{message:R}=K("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(R)}const p=await this.client.core.crypto.generateKeyPair(),y=Rt.wc_sessionPropose.req.ttl||V.FIVE_MINUTES,m=xt(y),_=hr(Ke({requiredNamespaces:s,optionalNamespaces:o,relays:c??[{protocol:wv}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:m,pairingTopic:l},a&&{sessionProperties:a}),{id:bi()}),S=ye("session_connect",_.id),{reject:E,resolve:P,done:C}=Kn(y,e2),M=({id:R})=>{R===_.id&&(this.client.events.off("proposal_expire",M),this.pendingSessions.delete(_.id),this.events.emit(S,{error:{message:e2,code:0}}))};return this.client.events.on("proposal_expire",M),this.events.once(S,({error:R,session:L})=>{this.client.events.off("proposal_expire",M),R?E(R):L&&P(L)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:_,throwOnFailedPublish:!0,clientRpcId:_.id}),await this.setProposal(_.id,_),{uri:u,approval:C}}),W(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}}),W(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:[Kr.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(F){throw o.setError(es.no_internet_connection),F}try{await this.isValidProposalId(r?.id)}catch(F){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(es.proposal_not_found),F}try{await this.isValidApprove(r)}catch(F){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(es.session_approve_namespace_validation_failure),F}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,sessionConfig:d}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:y,proposer:m,requiredNamespaces:_,optionalNamespaces:S}=p;let E=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:y});E||(E=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Kr.session_approve_started,properties:{topic:y,trace:[Kr.session_approve_started,Kr.session_namespaces_validation_success]}}));const P=await this.client.core.crypto.generateKeyPair(),C=m.publicKey,M=await this.client.core.crypto.generateSharedKey(P,C),R=Ke(Ke({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:P,metadata:this.client.metadata},expiry:xt(ho)},u&&{sessionProperties:u}),d&&{sessionConfig:d}),L=Re.relay;E.addTrace(Kr.subscribing_session_topic);try{await this.client.core.relayer.subscribe(M,{transportType:L})}catch(F){throw E.setError(es.subscribe_session_topic_failure),F}E.addTrace(Kr.subscribe_session_topic_success);const B=hr(Ke({},R),{topic:M,requiredNamespaces:_,optionalNamespaces:S,pairingTopic:y,acknowledged:!1,self:R.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:P,transportType:Re.relay});await this.client.session.set(M,B),E.addTrace(Kr.store_session);try{E.addTrace(Kr.publishing_session_settle),await this.sendRequest({topic:M,method:"wc_sessionSettle",params:R,throwOnFailedPublish:!0}).catch(F=>{throw E?.setError(es.session_settle_publish_failure),F}),E.addTrace(Kr.session_settle_publish_success),E.addTrace(Kr.publishing_session_approve),await this.sendResult({id:a,topic:y,result:{relay:{protocol:c??"irn"},responderPublicKey:P},throwOnFailedPublish:!0}).catch(F=>{throw E?.setError(es.session_approve_publish_failure),F}),E.addTrace(Kr.session_approve_publish_success)}catch(F){throw this.client.logger.error(F),this.client.session.delete(M,_e("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(M),F}return this.client.core.eventClient.deleteEvent({eventId:E.eventId}),await this.client.core.pairing.updateMetadata({topic:y,metadata:m.metadata}),await this.client.proposal.delete(a,_e("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:y}),await this.setExpiry(M,xt(ho)),{topic:M,acknowledged:()=>Promise.resolve(this.client.session.get(M))}}),W(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:Rt.wc_sessionPropose.reject}),await this.client.proposal.delete(i,_e("USER_DISCONNECTED")))}),W(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:i,namespaces:n}=r,{done:s,resolve:o,reject:a}=Kn(),c=bi(),l=Qn().toString(),u=this.client.session.get(i).namespaces;return this.events.once(ye("session_update",c),({error:d})=>{d?a(d):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(d=>{this.client.logger.error(d),this.client.session.update(i,{namespaces:u}),a(d)}),{acknowledged:s}}),W(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=bi(),{done:s,resolve:o,reject:a}=Kn();return this.events.once(ye("session_extend",n),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,xt(ho)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),W(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(E){throw this.client.logger.error("request() -> isValidRequest() failed"),E}const{chainId:i,request:n,topic:s,expiry:o=Rt.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===Re.relay&&await this.confirmOnlineStateOrThrow();const c=bi(),l=Qn().toString(),{done:u,resolve:d,reject:p}=Kn(o,"Request expired. Please try again.");this.events.once(ye("session_request",c),({error:E,result:P})=>{E?p(E):d(P)});const y="wc_sessionRequest",m=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(m)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:y,params:{request:hr(Ke({},n),{expiryTimestamp:xt(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:m}).catch(E=>p(E)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),await u();const _={request:hr(Ke({},n),{expiryTimestamp:xt(o)}),chainId:i},S=this.shouldSetTVF(y,_);return await Promise.all([new Promise(async E=>{await this.sendRequest(Ke({clientRpcId:c,relayRpcId:l,topic:s,method:y,params:_,expiry:o,throwOnFailedPublish:!0},S&&{tvf:this.getTVFParams(c,_)})).catch(P=>p(P)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),E()}),new Promise(async E=>{var P;if(!((P=a.sessionConfig)!=null&&P.disableDeepLink)){const C=await i$(this.client.core.storage,Xv);await e$({id:c,topic:s,wcDeepLink:C})}E()}),u()]).then(E=>E[2])}),W(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===Re.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);mi(n)?await this.sendResult({id:s,topic:i,result:n.result,throwOnFailedPublish:!0,appLink:a}):Cr(n)&&await this.sendError({id:s,topic:i,error:n.error,appLink:a}),this.cleanupAfterResponse(r)}),W(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=bi(),s=Qn().toString(),{done:o,resolve:a,reject:c}=Kn();this.events.once(ye("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}))}),W(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,o=Qn().toString(),a=bi();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),W(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:_e("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}=K("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}}),W(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>dS(i,r)))),W(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),W(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?Re.link_mode:Re.relay;o===Re.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:p,exp:y,nbf:m,methods:_=[],expiry:S}=r,E=[...r.resources||[]],{topic:P,uri:C}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:P,uri:C}});const M=await this.client.core.crypto.generateKeyPair(),R=$l(M);if(await Promise.all([this.client.auth.authKeys.set(Hl,{responseTopic:R,publicKey:M}),this.client.auth.pairingTopics.set(R,{topic:R,pairingTopic:P})]),await this.client.core.relayer.subscribe(R,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${P}`),_.length>0){const{namespace:x}=Xs(a[0]);let f=V$(x,"request",_);wl(E)&&(f=G$(f,E.pop())),E.push(f)}const L=S&&S>Rt.wc_sessionAuthenticate.req.ttl?S:Rt.wc_sessionAuthenticate.req.ttl,B={authPayload:{type:p??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:y,nbf:m,resources:E},requester:{publicKey:M,metadata:this.client.metadata},expiryTimestamp:xt(L)},F={eip155:{chains:a,methods:[...new Set(["personal_sign",..._])],events:["chainChanged","accountsChanged"]}},T={requiredNamespaces:{},optionalNamespaces:F,relays:[{protocol:"irn"}],pairingTopic:P,proposer:{publicKey:M,metadata:this.client.metadata},expiryTimestamp:xt(Rt.wc_sessionPropose.req.ttl),id:bi()},{done:q,resolve:$,reject:h}=Kn(L,"Request expired"),b=bi(),w=ye("session_connect",T.id),g=ye("session_request",b),v=async({error:x,session:f})=>{this.events.off(g,I),x?h(x):f&&$({session:f})},I=async x=>{var f,A,j;if(await this.deletePendingAuthRequest(b,{message:"fulfilled",code:0}),x.error){const Q=_e("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return x.error.code===Q.code?void 0:(this.events.off(w,v),h(x.error.message))}await this.deleteProposal(T.id),this.events.off(w,v);const{cacaos:z,responder:U}=x.result,k=[],Z=[];for(const Q of z){await Gb({cacao:Q,projectId:this.client.core.projectId})||(this.client.logger.error(Q,"Signature verification failed"),h(_e("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:re}=Q,Ze=wl(re.resources),oe=[_d(re.iss)],fe=yl(re.iss);if(Ze){const $t=Jb(Ze),xe=Qb(Ze);k.push(...$t),oe.push(...xe)}for(const $t of oe)Z.push(`${$t}:${fe}`)}const X=await this.client.core.crypto.generateSharedKey(M,U.publicKey);let ee;k.length>0&&(ee={topic:X,acknowledged:!0,self:{publicKey:M,metadata:this.client.metadata},peer:U,controller:U.publicKey,expiry:xt(ho),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:P,namespaces:Dm([...new Set(k)],[...new Set(Z)]),transportType:o},await this.client.core.relayer.subscribe(X,{transportType:o}),await this.client.session.set(X,ee),P&&await this.client.core.pairing.updateMetadata({topic:P,metadata:U.metadata}),ee=this.client.session.get(X)),(f=this.client.metadata.redirect)!=null&&f.linkMode&&(A=U.metadata.redirect)!=null&&A.linkMode&&(j=U.metadata.redirect)!=null&&j.universal&&i&&(this.client.core.addLinkModeSupportedApp(U.metadata.redirect.universal),this.client.session.update(X,{transportType:Re.link_mode})),$({auths:z,session:ee})};this.events.once(w,v),this.events.once(g,I);let O;try{if(s){const x=gn("wc_sessionAuthenticate",B,b);this.client.core.history.set(P,x);const f=await this.client.core.crypto.encode("",x,{type:$a,encoding:xa});O=Sl(i,P,f)}else await Promise.all([this.sendRequest({topic:P,method:"wc_sessionAuthenticate",params:B,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:b}),this.sendRequest({topic:P,method:"wc_sessionPropose",params:T,expiry:Rt.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:T.id})])}catch(x){throw this.events.off(w,v),this.events.off(g,I),x}return await this.setProposal(T.id,T),await this.setAuthRequest(b,{request:hr(Ke({},B),{verifyContext:{}}),pairingTopic:P,transportType:o}),{uri:O??C,response:q}}),W(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[ts.authenticated_session_approve_started]}});try{this.isInitialized()}catch(S){throw s.setError(Ua.no_internet_connection),S}const o=this.getPendingAuthRequest(i);if(!o)throw s.setError(Ua.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||Re.relay;a===Re.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=$l(c),d={type:Ui,receiverPublicKey:c,senderPublicKey:l},p=[],y=[];for(const S of n){if(!await Gb({cacao:S,projectId:this.client.core.projectId})){s.setError(Ua.invalid_cacao);const R=_e("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:u,error:R,encodeOpts:d}),new Error(R.message)}s.addTrace(ts.cacaos_verified);const{p:E}=S,P=wl(E.resources),C=[_d(E.iss)],M=yl(E.iss);if(P){const R=Jb(P),L=Qb(P);p.push(...R),C.push(...L)}for(const R of C)y.push(`${R}:${M}`)}const m=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(ts.create_authenticated_session_topic);let _;if(p?.length>0){_={topic:m,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:xt(ho),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Dm([...new Set(p)],[...new Set(y)]),transportType:a},s.addTrace(ts.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(m,{transportType:a})}catch(S){throw s.setError(Ua.subscribe_authenticated_session_topic_failure),S}s.addTrace(ts.subscribe_authenticated_session_topic_success),await this.client.session.set(m,_),s.addTrace(ts.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(ts.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:i,result:{cacaos:n,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(S){throw s.setError(Ua.authenticated_session_approve_publish_failure),S}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:_}}),W(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===Re.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=$l(o),l={type:Ui,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:n,encodeOpts:l,rpcOpts:Rt.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,_e("USER_DISCONNECTED"))}),W(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:n}=r;return Zb(i,n)}),W(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)}),W(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)}}),W(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,_e("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(Xv).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===n&&this.deletePendingSessionRequest(l.id,_e("USER_DISCONNECTED"))}),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=xi.idle),o&&this.client.events.emit("session_delete",{id:a,topic:n})}),W(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(es.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,_e("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),W(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=xi.idle,this.client.events.emit("session_request_expire",{id:r}))}),W(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)])}),W(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}))}),W(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,xt(Rt.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),W(this,"setAuthRequest",async(r,i)=>{const{request:n,pairingTopic:s,transportType:o=Re.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})}),W(this,"setPendingSessionRequest",async r=>{const{id:i,topic:n,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||xt(Rt.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})}),W(this,"sendRequest",async r=>{const{topic:i,method:n,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:d}=r,p=gn(n,s,c);let y;const m=!!u;try{const E=m?xa:pn;y=await this.client.core.crypto.encode(i,p,{encoding:E})}catch(E){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),E}let _;if(dM.includes(n)){const E=ji(JSON.stringify(p)),P=ji(y);_=await this.client.core.verify.register({id:P,decryptedId:E})}const S=Rt[n].req;if(S.attestation=_,o&&(S.ttl=o),a&&(S.id=a),this.client.core.history.set(i,p),m){const E=Sl(u,i,y);await global.Linking.openURL(E,this.client.name)}else{const E=Rt[n].req;o&&(E.ttl=o),a&&(E.id=a),E.tvf=hr(Ke({},d),{correlationId:p.id}),l?(E.internal=hr(Ke({},E.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,y,E)):this.client.core.relayer.publish(i,y,E).catch(P=>this.client.logger.error(P))}return p.id}),W(this,"sendResult",async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,l=Ll(i,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const m=d?xa:pn;u=await this.client.core.crypto.encode(n,l,hr(Ke({},a||{}),{encoding:m}))}catch(m){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),m}let p,y;try{p=await this.client.core.history.get(n,i);const m=p.request;try{this.shouldSetTVF(m.method,m.params)&&(y=this.getTVFParams(i,m.params,s))}catch(_){this.client.logger.warn("sendResult() -> getTVFParams() failed",_)}}catch(m){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),m}if(d){const m=Sl(c,n,u);await global.Linking.openURL(m,this.client.name)}else{const m=p.request.method,_=Rt[m].res;_.tvf=hr(Ke({},y),{correlationId:i}),o?(_.internal=hr(Ke({},_.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,u,_)):this.client.core.relayer.publish(n,u,_).catch(S=>this.client.logger.error(S))}await this.client.core.history.resolve(l)}),W(this,"sendError",async r=>{const{id:i,topic:n,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,l=Fl(i,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const y=d?xa:pn;u=await this.client.core.crypto.encode(n,l,hr(Ke({},o||{}),{encoding:y}))}catch(y){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),y}let p;try{p=await this.client.core.history.get(n,i)}catch(y){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),y}if(d){const y=Sl(c,n,u);await global.Linking.openURL(y,this.client.name)}else{const y=p.request.method,m=a||Rt[y].res;this.client.core.relayer.publish(n,u,m)}await this.client.core.history.resolve(l)}),W(this,"cleanup",async()=>{const r=[],i=[];this.client.session.getAll().forEach(n=>{let s=!1;un(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=>{un(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...r.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])}),W(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),W(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===xi.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=xi.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=xi.idle}),W(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}`)}}),W(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}`)}}),W(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:n}=K("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)}),W(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)}),W(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(ki.proposal_listener_not_found)),this.isValidConnect(Ke({},n.params));const u=a.expiryTimestamp||xt(Rt.wc_sessionPropose.req.ttl),d=Ke({id:c,pairingTopic:i,expiryTimestamp:u},a);await this.setProposal(c,d);const p=await this.getVerifyContext({attestationId:s,hash:ji(JSON.stringify(n)),encryptedId:o,metadata:d.proposer.metadata});l?.addTrace(yi.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:p})}catch(l){await this.sendError({id:c,topic:i,error:l,rpcOpts:Rt.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),W(this,"onSessionProposeResponse",async(r,i,n)=>{const{id:s}=i;if(mi(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.pendingSessions.set(s,{sessionTopic:u,pairingTopic:r,proposalId:s,publicKey:c});const d=await this.client.core.relayer.subscribe(u,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:r})}else if(Cr(i)){await this.client.proposal.delete(s,_e("USER_DISCONNECTED"));const o=ye("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),W(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:d}=i.params,p=[...this.pendingSessions.values()].find(_=>_.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const y=this.client.proposal.get(p.proposalId),m=hr(Ke(Ke({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:y.requiredNamespaces,optionalNamespaces:y.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),d&&{sessionConfig:d}),{transportType:Re.relay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:m.peer.metadata}),this.client.events.emit("session_connect",{session:m}),this.events.emit(ye("session_connect",p.proposalId),{session:m}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(m),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)}}),W(this,"onSessionSettleResponse",async(r,i)=>{const{id:n}=i;mi(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ye("session_approve",n),{})):Cr(i)&&(await this.client.session.delete(r,_e("USER_DISCONNECTED")),this.events.emit(ye("session_approve",n),{error:i.error}))}),W(this,"onSessionUpdateRequest",async(r,i)=>{const{params:n,id:s}=i;try{const o=`${r}_session_update`,a=Ca.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:_e("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Ke({topic:r},n));try{Ca.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 Ca.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)}}),W(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),W(this,"onSessionUpdateResponse",(r,i)=>{const{id:n}=i,s=ye("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);mi(i)?this.events.emit(ye("session_update",n),{}):Cr(i)&&this.events.emit(ye("session_update",n),{error:i.error})}),W(this,"onSessionExtendRequest",async(r,i)=>{const{id:n}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,xt(ho)),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)}}),W(this,"onSessionExtendResponse",(r,i)=>{const{id:n}=i,s=ye("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);mi(i)?this.events.emit(ye("session_extend",n),{}):Cr(i)&&this.events.emit(ye("session_extend",n),{error:i.error})}),W(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)}}),W(this,"onSessionPingResponse",(r,i)=>{const{id:n}=i,s=ye("session_ping",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);setTimeout(()=>{mi(i)?this.events.emit(ye("session_ping",n),{}):Cr(i)&&this.events.emit(ye("session_ping",n),{error:i.error})},500)}),W(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(Mt.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:_e("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),W(this,"onSessionRequest",async r=>{var i,n,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=r,{id:d,params:p}=a;try{await this.isValidRequest(Ke({topic:o},p));const y=this.client.session.get(o),m=await this.getVerifyContext({attestationId:c,hash:ji(JSON.stringify(gn("wc_sessionRequest",p,d))),encryptedId:l,metadata:y.peer.metadata,transportType:u}),_={id:d,topic:o,params:p,verifyContext:m};await this.setPendingSessionRequest(_),u===Re.link_mode&&(i=y.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((n=y.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(_):(this.addSessionRequestToSessionRequestQueue(_),this.processSessionRequestQueue())}catch(y){await this.sendError({id:d,topic:o,error:y}),this.client.logger.error(y)}}),W(this,"onSessionRequestResponse",(r,i)=>{const{id:n}=i,s=ye("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);mi(i)?this.events.emit(ye("session_request",n),{result:i.result}):Cr(i)&&this.events.emit(ye("session_request",n),{error:i.error})}),W(this,"onSessionEventRequest",async(r,i)=>{const{id:n,params:s}=i;try{const o=`${r}_session_event_${s.event.name}`,a=Ca.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(Ke({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),Ca.set(o,n)}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),W(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),mi(i)?this.events.emit(ye("session_request",n),{result:i.result}):Cr(i)&&this.events.emit(ye("session_request",n),{error:i.error})}),W(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:d}=s.params,p=await this.getVerifyContext({attestationId:o,hash:ji(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),y={requester:l,pairingTopic:n,id:s.id,authPayload:u,verifyContext:p,expiryTimestamp:d};await this.setAuthRequest(s.id,{request:y,pairingTopic:n,transportType:c}),c===Re.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:p})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),p=this.getAppLinkIfEnabled(s.params.requester.metadata,c),y={type:Ui,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:s.id,topic:n,error:l,encodeOpts:y,rpcOpts:Rt.wc_sessionAuthenticate.autoReject,appLink:p})}}),W(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),W(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=xi.idle,this.processSessionRequestQueue()},V.toMiliseconds(this.requestQueueDelay))}),W(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=ye("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(ye("session_request",s.request.id),{error:i})})}),W(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===xi.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=xi.active,this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}}),W(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),W(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:gn("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})}),W(this,"isValidConnect",async r=>{if(!ar(r)){const{message:c}=K("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(er(i)||await this.isValidPairingTopic(i),!$S(a,!0)){const{message:c}=K("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(c)}!er(n)&&Oa(n)!==0&&this.validateNamespaces(n,"requiredNamespaces"),!er(s)&&Oa(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),er(o)||this.validateSessionProps(o,"sessionProperties")}),W(this,"validateNamespaces",(r,i)=>{const n=ES(r,"connect()",i);if(n)throw new Error(n.message)}),W(this,"isValidApprove",async r=>{if(!ar(r))throw new Error(K("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=Ld(n,"approve()");if(c)throw new Error(c.message);const l=Bm(a.requiredNamespaces,n,"approve()");if(l)throw new Error(l.message);if(!mt(s,!0)){const{message:u}=K("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(u)}er(o)||this.validateSessionProps(o,"sessionProperties")}),W(this,"isValidReject",async r=>{if(!ar(r)){const{message:s}=K("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:i,reason:n}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!SS(n)){const{message:s}=K("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}}),W(this,"isValidSessionSettleRequest",r=>{if(!ar(r)){const{message:l}=K("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:i,controller:n,namespaces:s,expiry:o}=r;if(!Rm(i)){const{message:l}=K("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=mS(n,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Ld(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(un(o)){const{message:l}=K("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),W(this,"isValidUpdate",async r=>{if(!ar(r)){const{message:c}=K("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=Ld(n,"update()");if(o)throw new Error(o.message);const a=Bm(s.requiredNamespaces,n,"update()");if(a)throw new Error(a.message)}),W(this,"isValidExtend",async r=>{if(!ar(r)){const{message:n}=K("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(n)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),W(this,"isValidRequest",async r=>{if(!ar(r)){const{message:c}=K("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(!Nm(a,s)){const{message:c}=K("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!AS(n)){const{message:c}=K("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(c)}if(!CS(a,s,n.method)){const{message:c}=K("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(c)}if(o&&!RS(o,pf)){const{message:c}=K("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${pf.min} and ${pf.max}`);throw new Error(c)}}),W(this,"isValidRespond",async r=>{var i;if(!ar(r)){const{message:o}=K("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(!PS(s)){const{message:o}=K("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),W(this,"isValidPing",async r=>{if(!ar(r)){const{message:n}=K("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),W(this,"isValidEmit",async r=>{if(!ar(r)){const{message:a}=K("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(!Nm(o,s)){const{message:a}=K("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!OS(n)){const{message:a}=K("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}if(!DS(o,s,n.name)){const{message:a}=K("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}}),W(this,"isValidDisconnect",async r=>{if(!ar(r)){const{message:n}=K("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),W(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(!mt(n,!1))throw new Error("uri is required parameter");if(!mt(s,!1))throw new Error("domain is required parameter");if(!mt(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>Xs(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Xs(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),W(this,"getVerifyContext",async r=>{const{attestationId:i,hash:n,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||Fa,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Re.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}),W(this,"validateSessionProps",(r,i)=>{Object.values(r).forEach(n=>{if(!mt(n,!1)){const{message:s}=K("MISSING_OR_INVALID",`${i} must be in Record<string, string> format. Received: ${JSON.stringify(n)}`);throw new Error(s)}})}),W(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),W(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)}}}),W(this,"checkRecentlyDeleted",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:n}=K("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(n)}}),W(this,"isLinkModeEnabled",(r,i)=>{var n,s,o,a,c,l,u,d,p;return!r||i!==Re.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&&((d=r?.redirect)==null?void 0:d.universal)!==""&&((p=r?.redirect)==null?void 0:p.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),W(this,"getAppLinkIfEnabled",(r,i)=>{var n;return this.isLinkModeEnabled(r,i)?(n=r?.redirect)==null?void 0:n.universal:void 0}),W(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Mb(r,"topic")||"",n=decodeURIComponent(Mb(r,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:Re.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})}),W(this,"registerLinkModeListeners",async()=>{var r;if(gd()||cn()&&(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)}}}),W(this,"shouldSetTVF",(r,i)=>{if(!i||r!=="wc_sessionRequest")return!1;const{request:n}=i;return Object.keys(t2).includes(n.method)}),W(this,"getTVFParams",(r,i,n)=>{var s,o;try{const a=i.request.method,c=this.extractTxHashesFromResult(a,n);return hr(Ke({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{}}),W(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}),W(this,"extractTxHashesFromResult",(r,i)=>{try{const n=t2[r];if(typeof i=="string")return[i];const s=i[n.key];if(fi(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}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Mt.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(Hl)?this.client.auth.authKeys.get(Hl):{responseTopic:void 0,publicKey:void 0},a=await this.client.core.crypto.decode(r,i,{receiverPublicKey:o,encoding:s===Re.link_mode?xa:pn});try{Yd(a)?(this.client.core.history.set(r,a),this.onRelayEventRequest({topic:r,payload:a,attestation:n,transportType:s,encryptedId:ji(i)})):Ul(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(Tr.expired,async e=>{const{topic:r,id:i}=Db(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,K("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,K("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(Xn.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Xn.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!mt(e,!1)){const{message:r}=K("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}=K("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(un(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=K("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!mt(e,!1)){const{message:r}=K("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}=K("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(un(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=K("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=K("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(mt(e,!1)){const{message:r}=K("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=K("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!IS(e)){const{message:r}=K("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=K("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(un(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=K("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class $M extends rs{constructor(e,r){super(e,r,cM,df),this.core=e,this.logger=r}}class IM extends rs{constructor(e,r){super(e,r,lM,df),this.core=e,this.logger=r}}class SM extends rs{constructor(e,r){super(e,r,hM,df,i=>i.id),this.core=e,this.logger=r}}class AM extends rs{constructor(e,r){super(e,r,gM,kl,()=>Hl),this.core=e,this.logger=r}}class PM extends rs{constructor(e,r){super(e,r,bM,kl),this.core=e,this.logger=r}}class OM extends rs{constructor(e,r){super(e,r,mM,kl,i=>i.id),this.core=e,this.logger=r}}var CM=Object.defineProperty,DM=(t,e,r)=>e in t?CM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bf=(t,e,r)=>DM(t,typeof e!="symbol"?e+"":e,r);class MM{constructor(e,r){this.core=e,this.logger=r,bf(this,"authKeys"),bf(this,"pairingTopics"),bf(this,"requests"),this.authKeys=new AM(this.core,this.logger),this.pairingTopics=new PM(this.core,this.logger),this.requests=new OM(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var TM=Object.defineProperty,RM=(t,e,r)=>e in t?TM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ue=(t,e,r)=>RM(t,typeof e!="symbol"?e+"":e,r);class mf extends dP{constructor(e){super(e),ue(this,"protocol",Yv),ue(this,"version",Jv),ue(this,"name",ff.name),ue(this,"metadata"),ue(this,"core"),ue(this,"logger"),ue(this,"events",new Lt.exports.EventEmitter),ue(this,"engine"),ue(this,"session"),ue(this,"proposal"),ue(this,"pendingRequest"),ue(this,"auth"),ue(this,"signConfig"),ue(this,"on",(i,n)=>this.events.on(i,n)),ue(this,"once",(i,n)=>this.events.once(i,n)),ue(this,"off",(i,n)=>this.events.off(i,n)),ue(this,"removeListener",(i,n)=>this.events.removeListener(i,n)),ue(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),ue(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"update",async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"request",async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"find",i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),ue(this,"authenticate",async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}}),ue(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),this.name=e?.name||ff.name,this.metadata=e?.metadata||Sb(),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pi(Bl({level:e?.logger||ff.logger}));this.core=e?.core||new aM(e),this.logger=tr(r,this.name),this.session=new IM(this.core,this.logger),this.proposal=new $M(this.core,this.logger),this.pendingRequest=new SM(this.core,this.logger),this.engine=new EM(this),this.auth=new MM(this.core,this.logger)}static async init(e){const r=new mf(e);return await r.initialize(),r}get context(){return lr(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()},V.toMiliseconds(V.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var vf={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof wt<"u"&&wt,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 wt<"u"&&wt||{},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(g){return g&&DataView.prototype.isPrototypeOf(g)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],d=ArrayBuffer.isView||function(g){return g&&u.indexOf(Object.prototype.toString.call(g))>-1};function p(g){if(typeof g!="string"&&(g=String(g)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(g)||g==="")throw new TypeError('Invalid character in header field name: "'+g+'"');return g.toLowerCase()}function y(g){return typeof g!="string"&&(g=String(g)),g}function m(g){var v={next:function(){var I=g.shift();return{done:I===void 0,value:I}}};return c.iterable&&(v[Symbol.iterator]=function(){return v}),v}function _(g){this.map={},g instanceof _?g.forEach(function(v,I){this.append(I,v)},this):Array.isArray(g)?g.forEach(function(v){if(v.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+v.length);this.append(v[0],v[1])},this):g&&Object.getOwnPropertyNames(g).forEach(function(v){this.append(v,g[v])},this)}_.prototype.append=function(g,v){g=p(g),v=y(v);var I=this.map[g];this.map[g]=I?I+", "+v:v},_.prototype.delete=function(g){delete this.map[p(g)]},_.prototype.get=function(g){return g=p(g),this.has(g)?this.map[g]:null},_.prototype.has=function(g){return this.map.hasOwnProperty(p(g))},_.prototype.set=function(g,v){this.map[p(g)]=y(v)},_.prototype.forEach=function(g,v){for(var I in this.map)this.map.hasOwnProperty(I)&&g.call(v,this.map[I],I,this)},_.prototype.keys=function(){var g=[];return this.forEach(function(v,I){g.push(I)}),m(g)},_.prototype.values=function(){var g=[];return this.forEach(function(v){g.push(v)}),m(g)},_.prototype.entries=function(){var g=[];return this.forEach(function(v,I){g.push([I,v])}),m(g)},c.iterable&&(_.prototype[Symbol.iterator]=_.prototype.entries);function S(g){if(!g._noBody){if(g.bodyUsed)return Promise.reject(new TypeError("Already read"));g.bodyUsed=!0}}function E(g){return new Promise(function(v,I){g.onload=function(){v(g.result)},g.onerror=function(){I(g.error)}})}function P(g){var v=new FileReader,I=E(v);return v.readAsArrayBuffer(g),I}function C(g){var v=new FileReader,I=E(v),O=/charset=([A-Za-z0-9_-]+)/.exec(g.type),x=O?O[1]:"utf-8";return v.readAsText(g,x),I}function M(g){for(var v=new Uint8Array(g),I=new Array(v.length),O=0;O<v.length;O++)I[O]=String.fromCharCode(v[O]);return I.join("")}function R(g){if(g.slice)return g.slice(0);var v=new Uint8Array(g.byteLength);return v.set(new Uint8Array(g)),v.buffer}function L(){return this.bodyUsed=!1,this._initBody=function(g){this.bodyUsed=this.bodyUsed,this._bodyInit=g,g?typeof g=="string"?this._bodyText=g:c.blob&&Blob.prototype.isPrototypeOf(g)?this._bodyBlob=g:c.formData&&FormData.prototype.isPrototypeOf(g)?this._bodyFormData=g:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(g)?this._bodyText=g.toString():c.arrayBuffer&&c.blob&&l(g)?(this._bodyArrayBuffer=R(g.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(g)||d(g))?this._bodyArrayBuffer=R(g):this._bodyText=g=Object.prototype.toString.call(g):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof g=="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(g)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var g=S(this);if(g)return g;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 g=S(this);return g||(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(P);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var g=S(this);if(g)return g;if(this._bodyBlob)return C(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(M(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(q)}),this.json=function(){return this.text().then(JSON.parse)},this}var B=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function F(g){var v=g.toUpperCase();return B.indexOf(v)>-1?v:g}function T(g,v){if(!(this instanceof T))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');v=v||{};var I=v.body;if(g instanceof T){if(g.bodyUsed)throw new TypeError("Already read");this.url=g.url,this.credentials=g.credentials,v.headers||(this.headers=new _(g.headers)),this.method=g.method,this.mode=g.mode,this.signal=g.signal,!I&&g._bodyInit!=null&&(I=g._bodyInit,g.bodyUsed=!0)}else this.url=String(g);if(this.credentials=v.credentials||this.credentials||"same-origin",(v.headers||!this.headers)&&(this.headers=new _(v.headers)),this.method=F(v.method||this.method||"GET"),this.mode=v.mode||this.mode||null,this.signal=v.signal||this.signal||function(){if("AbortController"in a){var f=new AbortController;return f.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&I)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(I),(this.method==="GET"||this.method==="HEAD")&&(v.cache==="no-store"||v.cache==="no-cache")){var O=/([?&])_=[^&]*/;if(O.test(this.url))this.url=this.url.replace(O,"$1_="+new Date().getTime());else{var x=/\?/;this.url+=(x.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}T.prototype.clone=function(){return new T(this,{body:this._bodyInit})};function q(g){var v=new FormData;return g.trim().split("&").forEach(function(I){if(I){var O=I.split("="),x=O.shift().replace(/\+/g," "),f=O.join("=").replace(/\+/g," ");v.append(decodeURIComponent(x),decodeURIComponent(f))}}),v}function $(g){var v=new _,I=g.replace(/\r?\n[\t ]+/g," ");return I.split("\r").map(function(O){return O.indexOf(`
39
+ ***************************************************************************** */var Kd=function(t,e){return Kd=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])},Kd(t,e)};function _P(t,e){Kd(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Gd=function(){return Gd=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},Gd.apply(this,arguments)};function xP(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 EP(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 $P(t,e){return function(r,i){e(r,i,t)}}function IP(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function SP(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(d){o(d)}}function c(u){try{l(i.throw(u))}catch(d){o(d)}}function l(u){u.done?s(u.value):n(u.value).then(a,c)}l((i=i.apply(t,e||[])).next())})}function AP(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 PP(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function OP(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Zd(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 sv(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 CP(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(sv(arguments[e]));return t}function DP(){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 Ba(t){return this instanceof Ba?(this.v=t,this):new Ba(t)}function MP(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(p){i[p]&&(n[p]=function(y){return new Promise(function(m,_){s.push([p,y,m,_])>1||a(p,y)})})}function a(p,y){try{c(i[p](y))}catch(m){d(s[0][3],m)}}function c(p){p.value instanceof Ba?Promise.resolve(p.value.v).then(l,u):d(s[0][2],p)}function l(p){a("next",p)}function u(p){a("throw",p)}function d(p,y){p(y),s.shift(),s.length&&a(s[0][0],s[0][1])}}function TP(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:Ba(t[n](o)),done:n==="return"}:s?s(o):o}:s}}function RP(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 Zd=="function"?Zd(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 NP(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function BP(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 LP(t){return t&&t.__esModule?t:{default:t}}function FP(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function UP(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 jP=Object.freeze({__proto__:null,__extends:_P,get __assign(){return Gd},__rest:xP,__decorate:EP,__param:$P,__metadata:IP,__awaiter:SP,__generator:AP,__createBinding:PP,__exportStar:OP,__values:Zd,__read:sv,__spread:CP,__spreadArrays:DP,__await:Ba,__asyncGenerator:MP,__asyncDelegator:TP,__asyncValues:RP,__makeTemplateObject:NP,__importStar:BP,__importDefault:LP,__classPrivateFieldGet:FP,__classPrivateFieldSet:UP}),qP=zu(jP),qi={},ov;function zP(){if(ov)return qi;ov=1,Object.defineProperty(qi,"__esModule",{value:!0}),qi.isBrowserCryptoAvailable=qi.getSubtleCrypto=qi.getBrowerCrypto=void 0;function t(){return wt?.crypto||wt?.msCrypto||{}}qi.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}qi.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return qi.isBrowserCryptoAvailable=r,qi}var zi={},av;function kP(){if(av)return zi;av=1,Object.defineProperty(zi,"__esModule",{value:!0}),zi.isBrowser=zi.isNode=zi.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}zi.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}zi.isNode=e;function r(){return!t()&&!e()}return zi.isBrowser=r,zi}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=qP;e.__exportStar(zP(),t),e.__exportStar(kP(),t)})(nv);function bi(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Qn(t=6){return BigInt(bi(t))}function gn(t,e,r){return{id:r||bi(),jsonrpc:"2.0",method:t,params:e}}function Ll(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Fl(t,e,r){return{id:t,jsonrpc:"2.0",error:HP(e,r)}}function HP(t,e){return typeof t>"u"?rv(ev):(typeof t=="string"&&(t=Object.assign(Object.assign({},rv(Vd)),{message:t})),typeof e<"u"&&(t.data=e),yP(t.code)&&(t=wP(t.code)),t)}class WP{}class VP extends WP{constructor(){super()}}class KP extends VP{constructor(e){super()}}const GP="^https?:",ZP="^wss?:";function YP(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function cv(t,e){const r=YP(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function lv(t){return cv(t,GP)}function uv(t){return cv(t,ZP)}function JP(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function hv(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Yd(t){return hv(t)&&"method"in t}function Ul(t){return hv(t)&&(mi(t)||Cr(t))}function mi(t){return"result"in t}function Cr(t){return"error"in t}class Dr extends KP{constructor(e){super(e),this.events=new Lt.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(gn(e.method,e.params||[],e.id||Qn().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=>{Cr(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),Ul(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 QP=()=>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"),XP=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",dv=t=>t.split("?")[0],fv=10,eO=QP();class tO{constructor(e){if(this.url=e,this.events=new Lt.exports.EventEmitter,this.registering=!1,!uv(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(Mi(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!uv(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=nv.isReactNative()?void 0:{rejectUnauthorized:!JP(e)},s=new eO(e,[],n);XP()?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"?Fn(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=Fl(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return iv(e,dv(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>fv&&this.events.setMaxListeners(fv)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${dv(this.url)}`));return this.events.emit("register_error",r),r}}var Jd={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]",d="[object Date]",p="[object Error]",y="[object Function]",m="[object GeneratorFunction]",_="[object Map]",S="[object Number]",E="[object Null]",P="[object Object]",C="[object Promise]",M="[object Proxy]",R="[object RegExp]",L="[object Set]",B="[object String]",F="[object Symbol]",T="[object Undefined]",q="[object WeakMap]",$="[object ArrayBuffer]",h="[object DataView]",b="[object Float32Array]",w="[object Float64Array]",g="[object Int8Array]",v="[object Int16Array]",I="[object Int32Array]",O="[object Uint8Array]",x="[object Uint8ClampedArray]",f="[object Uint16Array]",A="[object Uint32Array]",j=/[\\^$.*+?()[\]{}|]/g,z=/^\[object .+?Constructor\]$/,U=/^(?:0|[1-9]\d*)$/,k={};k[b]=k[w]=k[g]=k[v]=k[I]=k[O]=k[x]=k[f]=k[A]=!0,k[a]=k[c]=k[$]=k[u]=k[h]=k[d]=k[p]=k[y]=k[_]=k[S]=k[P]=k[R]=k[L]=k[B]=k[q]=!1;var Z=typeof wt=="object"&&wt&&wt.Object===Object&&wt,X=typeof self=="object"&&self&&self.Object===Object&&self,ee=Z||X||Function("return this")(),Q=e&&!e.nodeType&&e,re=Q&&!0&&t&&!t.nodeType&&t,Ze=re&&re.exports===Q,oe=Ze&&Z.process,fe=function(){try{return oe&&oe.binding&&oe.binding("util")}catch{}}(),$t=fe&&fe.isTypedArray;function xe(D,N){for(var H=-1,Y=D==null?0:D.length,je=0,ne=[];++H<Y;){var pt=D[H];N(pt,H,D)&&(ne[je++]=pt)}return ne}function qe(D,N){for(var H=-1,Y=N.length,je=D.length;++H<Y;)D[je+H]=N[H];return D}function Go(D,N){for(var H=-1,Y=D==null?0:D.length;++H<Y;)if(N(D[H],H,D))return!0;return!1}function ze(D,N){for(var H=-1,Y=Array(D);++H<D;)Y[H]=N(H);return Y}function Be(D){return function(N){return D(N)}}function vs(D,N){return D.has(N)}function De(D,N){return D?.[N]}function Le(D){var N=-1,H=Array(D.size);return D.forEach(function(Y,je){H[++N]=[je,Y]}),H}function ys(D,N){return function(H){return D(N(H))}}function Fe(D){var N=-1,H=Array(D.size);return D.forEach(function(Y){H[++N]=Y}),H}var Ue=Array.prototype,ws=Function.prototype,Ae=Object.prototype,Me=ee["__core-js_shared__"],_s=ws.toString,pe=Ae.hasOwnProperty,Ye=function(){var D=/[^.]+$/.exec(Me&&Me.keys&&Me.keys.IE_PROTO||"");return D?"Symbol(src)_1."+D:""}(),uc=Ae.toString,st=RegExp("^"+_s.call(pe).replace(j,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Je=Ze?ee.Buffer:void 0,xs=ee.Symbol,Qe=ee.Uint8Array,Xe=Ae.propertyIsEnumerable,Mu=Ue.splice,Se=xs?xs.toStringTag:void 0,et=Object.getOwnPropertySymbols,Tu=Je?Je.isBuffer:void 0,ot=ys(Object.keys,Object),ke=Yo(ee,"DataView"),Pn=Yo(ee,"Map"),He=Yo(ee,"Promise"),We=Yo(ee,"Set"),Zo=Yo(ee,"WeakMap"),Te=Yo(Object,"create"),at=Es(ke),Ru=Es(Pn),ct=Es(He),lt=Es(We),Nu=Es(Zo),tt=xs?xs.prototype:void 0,Ve=tt?tt.valueOf:void 0;function Ai(D){var N=-1,H=D==null?0:D.length;for(this.clear();++N<H;){var Y=D[N];this.set(Y[0],Y[1])}}function ut(){this.__data__=Te?Te(null):{},this.size=0}function ht(D){var N=this.has(D)&&delete this.__data__[D];return this.size-=N?1:0,N}function Bu(D){var N=this.__data__;if(Te){var H=N[D];return H===i?void 0:H}return pe.call(N,D)?N[D]:void 0}function dt(D){var N=this.__data__;return Te?N[D]!==void 0:pe.call(N,D)}function ft(D,N){var H=this.__data__;return this.size+=this.has(D)?0:1,H[D]=Te&&N===void 0?i:N,this}Ai.prototype.clear=ut,Ai.prototype.delete=ht,Ai.prototype.get=Bu,Ai.prototype.has=dt,Ai.prototype.set=ft;function Er(D){var N=-1,H=D==null?0:D.length;for(this.clear();++N<H;){var Y=D[N];this.set(Y[0],Y[1])}}function hc(){this.__data__=[],this.size=0}function dc(D){var N=this.__data__,H=Lu(N,D);if(H<0)return!1;var Y=N.length-1;return H==Y?N.pop():Mu.call(N,H,1),--this.size,!0}function fc(D){var N=this.__data__,H=Lu(N,D);return H<0?void 0:N[H][1]}function pc(D){return Lu(this.__data__,D)>-1}function gc(D,N){var H=this.__data__,Y=Lu(H,D);return Y<0?(++this.size,H.push([D,N])):H[Y][1]=N,this}Er.prototype.clear=hc,Er.prototype.delete=dc,Er.prototype.get=fc,Er.prototype.has=pc,Er.prototype.set=gc;function Jr(D){var N=-1,H=D==null?0:D.length;for(this.clear();++N<H;){var Y=D[N];this.set(Y[0],Y[1])}}function bc(){this.size=0,this.__data__={hash:new Ai,map:new(Pn||Er),string:new Ai}}function mc(D){var N=Fu(this,D).delete(D);return this.size-=N?1:0,N}function vc(D){return Fu(this,D).get(D)}function yc(D){return Fu(this,D).has(D)}function wc(D,N){var H=Fu(this,D),Y=H.size;return H.set(D,N),this.size+=H.size==Y?0:1,this}Jr.prototype.clear=bc,Jr.prototype.delete=mc,Jr.prototype.get=vc,Jr.prototype.has=yc,Jr.prototype.set=wc;function On(D){var N=-1,H=D==null?0:D.length;for(this.__data__=new Jr;++N<H;)this.add(D[N])}function _c(D){return this.__data__.set(D,i),this}function xc(D){return this.__data__.has(D)}On.prototype.add=On.prototype.push=_c,On.prototype.has=xc;function Br(D){var N=this.__data__=new Er(D);this.size=N.size}function Ec(){this.__data__=new Er,this.size=0}function $c(D){var N=this.__data__,H=N.delete(D);return this.size=N.size,H}function Ic(D){return this.__data__.get(D)}function fW(D){return this.__data__.has(D)}function pW(D,N){var H=this.__data__;if(H instanceof Er){var Y=H.__data__;if(!Pn||Y.length<r-1)return Y.push([D,N]),this.size=++H.size,this;H=this.__data__=new Jr(Y)}return H.set(D,N),this.size=H.size,this}Br.prototype.clear=Ec,Br.prototype.delete=$c,Br.prototype.get=Ic,Br.prototype.has=fW,Br.prototype.set=pW;function gW(D,N){var H=Uu(D),Y=!H&&CW(D),je=!H&&!Y&&H0(D),ne=!H&&!Y&&!je&&qw(D),pt=H||Y||je||ne,Bt=pt?ze(D.length,String):[],Wt=Bt.length;for(var rt in D)(N||pe.call(D,rt))&&!(pt&&(rt=="length"||je&&(rt=="offset"||rt=="parent")||ne&&(rt=="buffer"||rt=="byteLength"||rt=="byteOffset")||IW(rt,Wt)))&&Bt.push(rt);return Bt}function Lu(D,N){for(var H=D.length;H--;)if(Lw(D[H][0],N))return H;return-1}function bW(D,N,H){var Y=N(D);return Uu(D)?Y:qe(Y,H(D))}function Sc(D){return D==null?D===void 0?T:E:Se&&Se in Object(D)?EW(D):OW(D)}function Tw(D){return Ac(D)&&Sc(D)==a}function Rw(D,N,H,Y,je){return D===N?!0:D==null||N==null||!Ac(D)&&!Ac(N)?D!==D&&N!==N:mW(D,N,H,Y,Rw,je)}function mW(D,N,H,Y,je,ne){var pt=Uu(D),Bt=Uu(N),Wt=pt?c:Cn(D),rt=Bt?c:Cn(N);Wt=Wt==a?P:Wt,rt=rt==a?P:rt;var $r=Wt==P,Qr=rt==P,Jt=Wt==rt;if(Jt&&H0(D)){if(!H0(N))return!1;pt=!0,$r=!1}if(Jt&&!$r)return ne||(ne=new Br),pt||qw(D)?Nw(D,N,H,Y,je,ne):_W(D,N,Wt,H,Y,je,ne);if(!(H&n)){var Lr=$r&&pe.call(D,"__wrapped__"),Fr=Qr&&pe.call(N,"__wrapped__");if(Lr||Fr){var Dn=Lr?D.value():D,Ki=Fr?N.value():N;return ne||(ne=new Br),je(Dn,Ki,H,Y,ne)}}return Jt?(ne||(ne=new Br),xW(D,N,H,Y,je,ne)):!1}function vW(D){if(!jw(D)||AW(D))return!1;var N=Fw(D)?st:z;return N.test(Es(D))}function yW(D){return Ac(D)&&Uw(D.length)&&!!k[Sc(D)]}function wW(D){if(!PW(D))return ot(D);var N=[];for(var H in Object(D))pe.call(D,H)&&H!="constructor"&&N.push(H);return N}function Nw(D,N,H,Y,je,ne){var pt=H&n,Bt=D.length,Wt=N.length;if(Bt!=Wt&&!(pt&&Wt>Bt))return!1;var rt=ne.get(D);if(rt&&ne.get(N))return rt==N;var $r=-1,Qr=!0,Jt=H&s?new On:void 0;for(ne.set(D,N),ne.set(N,D);++$r<Bt;){var Lr=D[$r],Fr=N[$r];if(Y)var Dn=pt?Y(Fr,Lr,$r,N,D,ne):Y(Lr,Fr,$r,D,N,ne);if(Dn!==void 0){if(Dn)continue;Qr=!1;break}if(Jt){if(!Go(N,function(Ki,$s){if(!vs(Jt,$s)&&(Lr===Ki||je(Lr,Ki,H,Y,ne)))return Jt.push($s)})){Qr=!1;break}}else if(!(Lr===Fr||je(Lr,Fr,H,Y,ne))){Qr=!1;break}}return ne.delete(D),ne.delete(N),Qr}function _W(D,N,H,Y,je,ne,pt){switch(H){case h:if(D.byteLength!=N.byteLength||D.byteOffset!=N.byteOffset)return!1;D=D.buffer,N=N.buffer;case $:return!(D.byteLength!=N.byteLength||!ne(new Qe(D),new Qe(N)));case u:case d:case S:return Lw(+D,+N);case p:return D.name==N.name&&D.message==N.message;case R:case B:return D==N+"";case _:var Bt=Le;case L:var Wt=Y&n;if(Bt||(Bt=Fe),D.size!=N.size&&!Wt)return!1;var rt=pt.get(D);if(rt)return rt==N;Y|=s,pt.set(D,N);var $r=Nw(Bt(D),Bt(N),Y,je,ne,pt);return pt.delete(D),$r;case F:if(Ve)return Ve.call(D)==Ve.call(N)}return!1}function xW(D,N,H,Y,je,ne){var pt=H&n,Bt=Bw(D),Wt=Bt.length,rt=Bw(N),$r=rt.length;if(Wt!=$r&&!pt)return!1;for(var Qr=Wt;Qr--;){var Jt=Bt[Qr];if(!(pt?Jt in N:pe.call(N,Jt)))return!1}var Lr=ne.get(D);if(Lr&&ne.get(N))return Lr==N;var Fr=!0;ne.set(D,N),ne.set(N,D);for(var Dn=pt;++Qr<Wt;){Jt=Bt[Qr];var Ki=D[Jt],$s=N[Jt];if(Y)var zw=pt?Y($s,Ki,Jt,N,D,ne):Y(Ki,$s,Jt,D,N,ne);if(!(zw===void 0?Ki===$s||je(Ki,$s,H,Y,ne):zw)){Fr=!1;break}Dn||(Dn=Jt=="constructor")}if(Fr&&!Dn){var ju=D.constructor,qu=N.constructor;ju!=qu&&"constructor"in D&&"constructor"in N&&!(typeof ju=="function"&&ju instanceof ju&&typeof qu=="function"&&qu instanceof qu)&&(Fr=!1)}return ne.delete(D),ne.delete(N),Fr}function Bw(D){return bW(D,TW,$W)}function Fu(D,N){var H=D.__data__;return SW(N)?H[typeof N=="string"?"string":"hash"]:H.map}function Yo(D,N){var H=De(D,N);return vW(H)?H:void 0}function EW(D){var N=pe.call(D,Se),H=D[Se];try{D[Se]=void 0;var Y=!0}catch{}var je=uc.call(D);return Y&&(N?D[Se]=H:delete D[Se]),je}var $W=et?function(D){return D==null?[]:(D=Object(D),xe(et(D),function(N){return Xe.call(D,N)}))}:RW,Cn=Sc;(ke&&Cn(new ke(new ArrayBuffer(1)))!=h||Pn&&Cn(new Pn)!=_||He&&Cn(He.resolve())!=C||We&&Cn(new We)!=L||Zo&&Cn(new Zo)!=q)&&(Cn=function(D){var N=Sc(D),H=N==P?D.constructor:void 0,Y=H?Es(H):"";if(Y)switch(Y){case at:return h;case Ru:return _;case ct:return C;case lt:return L;case Nu:return q}return N});function IW(D,N){return N=N??o,!!N&&(typeof D=="number"||U.test(D))&&D>-1&&D%1==0&&D<N}function SW(D){var N=typeof D;return N=="string"||N=="number"||N=="symbol"||N=="boolean"?D!=="__proto__":D===null}function AW(D){return!!Ye&&Ye in D}function PW(D){var N=D&&D.constructor,H=typeof N=="function"&&N.prototype||Ae;return D===H}function OW(D){return uc.call(D)}function Es(D){if(D!=null){try{return _s.call(D)}catch{}try{return D+""}catch{}}return""}function Lw(D,N){return D===N||D!==D&&N!==N}var CW=Tw(function(){return arguments}())?Tw:function(D){return Ac(D)&&pe.call(D,"callee")&&!Xe.call(D,"callee")},Uu=Array.isArray;function DW(D){return D!=null&&Uw(D.length)&&!Fw(D)}var H0=Tu||NW;function MW(D,N){return Rw(D,N)}function Fw(D){if(!jw(D))return!1;var N=Sc(D);return N==y||N==m||N==l||N==M}function Uw(D){return typeof D=="number"&&D>-1&&D%1==0&&D<=o}function jw(D){var N=typeof D;return D!=null&&(N=="object"||N=="function")}function Ac(D){return D!=null&&typeof D=="object"}var qw=$t?Be($t):yW;function TW(D){return DW(D)?gW(D):wW(D)}function RW(){return[]}function NW(){return!1}t.exports=MW})(Jd,Jd.exports);var rO=Jd.exports,iO=Object.defineProperty,pv=Object.getOwnPropertySymbols,nO=Object.prototype.hasOwnProperty,sO=Object.prototype.propertyIsEnumerable,gv=(t,e,r)=>e in t?iO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rr=(t,e)=>{for(var r in e||(e={}))nO.call(e,r)&&gv(t,r,e[r]);if(pv)for(var r of pv(e))sO.call(e,r)&&gv(t,r,e[r]);return t};const bv="wc",mv=2,jl="core",vi=`${bv}@2:${jl}:`,oO={name:jl,logger:"error"},aO={database:":memory:"},cO="crypto",vv="client_ed25519_seed",lO=V.ONE_DAY,uO="keychain",hO="0.3",dO="messages",fO="0.3",yv=V.SIX_HOURS,pO="publisher",wv="irn",gO="error",_v="wss://relay.walletconnect.org",bO="relayer",Mt={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"},mO="_subscription",Mr={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},vO=.1,Qd="2.19.0",Re={link_mode:"link_mode",relay:"relay"},yO="0.3",wO="WALLETCONNECT_CLIENT_ID",xv="WALLETCONNECT_LINK_MODE_APPS",vr={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},_O="subscription",xO="0.3",EO=V.FIVE_SECONDS*1e3,$O="pairing",IO="0.3",La={wc_pairingDelete:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:V.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:V.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:V.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:V.ONE_DAY,prompt:!1,tag:0},res:{ttl:V.ONE_DAY,prompt:!1,tag:0}}},Xn={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Vr={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},SO="history",AO="0.3",PO="expirer",Tr={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},OO="0.3",CO="verify-api",DO="https://verify.walletconnect.com",Ev="https://verify.walletconnect.org",Fa=Ev,MO=`${Fa}/v3`,TO=[DO,Ev],RO="echo",NO="https://echo.walletconnect.com",yi={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"},ki={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"},Kr={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"},es={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"},ts={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"},Ua={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"},BO=.1,LO="event-client",FO=86400,UO="https://pulse.walletconnect.org/batch";function jO(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 d(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var _=0,S=0,E=0,P=m.length;E!==P&&m[E]===0;)E++,_++;for(var C=(P-E)*u+1>>>0,M=new Uint8Array(C);E!==P;){for(var R=m[E],L=0,B=C-1;(R!==0||L<S)&&B!==-1;B--,L++)R+=256*M[B]>>>0,M[B]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");S=L,E++}for(var F=C-S;F!==C&&M[F]===0;)F++;for(var T=c.repeat(_);F<C;++F)T+=t.charAt(M[F]);return T}function p(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var _=0;if(m[_]!==" "){for(var S=0,E=0;m[_]===c;)S++,_++;for(var P=(m.length-_)*l+1>>>0,C=new Uint8Array(P);m[_];){var M=r[m.charCodeAt(_)];if(M===255)return;for(var R=0,L=P-1;(M!==0||R<E)&&L!==-1;L--,R++)M+=a*C[L]>>>0,C[L]=M%256>>>0,M=M/256>>>0;if(M!==0)throw new Error("Non-zero carry");E=R,_++}if(m[_]!==" "){for(var B=P-E;B!==P&&C[B]===0;)B++;for(var F=new Uint8Array(S+(P-B)),T=S;B!==P;)F[T++]=C[B++];return F}}}function y(m){var _=p(m);if(_)return _;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:y}}var qO=jO,zO=qO;const $v=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")},kO=t=>new TextEncoder().encode(t),HO=t=>new TextDecoder().decode(t);class WO{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 VO{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 Iv(this,e)}}class KO{constructor(e){this.decoders=e}or(e){return Iv(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 Iv=(t,e)=>new KO(rr(rr({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class GO{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new WO(e,r,i),this.decoder=new VO(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ql=({name:t,prefix:e,encode:r,decode:i})=>new GO(t,e,r,i),ja=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=zO(r,e);return ql({prefix:t,name:e,encode:i,decode:s=>$v(n(s))})},ZO=(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 d=n[t[u]];if(d===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|d,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},YO=(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},zt=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>ql({prefix:e,name:t,encode(n){return YO(n,i,r)},decode(n){return ZO(n,i,r,t)}}),JO=ql({prefix:"\0",name:"identity",encode:t=>HO(t),decode:t=>kO(t)});var QO=Object.freeze({__proto__:null,identity:JO});const XO=zt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var eC=Object.freeze({__proto__:null,base2:XO});const tC=zt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var rC=Object.freeze({__proto__:null,base8:tC});const iC=ja({prefix:"9",name:"base10",alphabet:"0123456789"});var nC=Object.freeze({__proto__:null,base10:iC});const sC=zt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),oC=zt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var aC=Object.freeze({__proto__:null,base16:sC,base16upper:oC});const cC=zt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),lC=zt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),uC=zt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),hC=zt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),dC=zt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),fC=zt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),pC=zt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gC=zt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),bC=zt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var mC=Object.freeze({__proto__:null,base32:cC,base32upper:lC,base32pad:uC,base32padupper:hC,base32hex:dC,base32hexupper:fC,base32hexpad:pC,base32hexpadupper:gC,base32z:bC});const vC=ja({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),yC=ja({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var wC=Object.freeze({__proto__:null,base36:vC,base36upper:yC});const _C=ja({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xC=ja({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var EC=Object.freeze({__proto__:null,base58btc:_C,base58flickr:xC});const $C=zt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),IC=zt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),SC=zt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),AC=zt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var PC=Object.freeze({__proto__:null,base64:$C,base64pad:IC,base64url:SC,base64urlpad:AC});const Sv=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}"),OC=Sv.reduce((t,e,r)=>(t[r]=e,t),[]),CC=Sv.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function DC(t){return t.reduce((e,r)=>(e+=OC[r],e),"")}function MC(t){const e=[];for(const r of t){const i=CC[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const TC=ql({prefix:"\u{1F680}",name:"base256emoji",encode:DC,decode:MC});var RC=Object.freeze({__proto__:null,base256emoji:TC}),NC=Pv,Av=128,BC=127,LC=~BC,FC=Math.pow(2,31);function Pv(t,e,r){e=e||[],r=r||0;for(var i=r;t>=FC;)e[r++]=t&255|Av,t/=128;for(;t&LC;)e[r++]=t&255|Av,t>>>=7;return e[r]=t|0,Pv.bytes=r-i+1,e}var UC=Xd,jC=128,Ov=127;function Xd(t,i){var r=0,i=i||0,n=0,s=i,o,a=t.length;do{if(s>=a)throw Xd.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=n<28?(o&Ov)<<n:(o&Ov)*Math.pow(2,n),n+=7}while(o>=jC);return Xd.bytes=s-i,r}var qC=Math.pow(2,7),zC=Math.pow(2,14),kC=Math.pow(2,21),HC=Math.pow(2,28),WC=Math.pow(2,35),VC=Math.pow(2,42),KC=Math.pow(2,49),GC=Math.pow(2,56),ZC=Math.pow(2,63),YC=function(t){return t<qC?1:t<zC?2:t<kC?3:t<HC?4:t<WC?5:t<VC?6:t<KC?7:t<GC?8:t<ZC?9:10},JC={encode:NC,decode:UC,encodingLength:YC},Cv=JC;const Dv=(t,e,r=0)=>(Cv.encode(t,e,r),e),Mv=t=>Cv.encodingLength(t),ef=(t,e)=>{const r=e.byteLength,i=Mv(t),n=i+Mv(r),s=new Uint8Array(n+r);return Dv(t,s,0),Dv(r,s,i),s.set(e,n),new QC(t,r,e,s)};class QC{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const Tv=({name:t,code:e,encode:r})=>new XC(t,e,r);class XC{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?ef(this.code,r):r.then(i=>ef(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Rv=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),eD=Tv({name:"sha2-256",code:18,encode:Rv("SHA-256")}),tD=Tv({name:"sha2-512",code:19,encode:Rv("SHA-512")});var rD=Object.freeze({__proto__:null,sha256:eD,sha512:tD});const Nv=0,iD="identity",Bv=$v;var nD=Object.freeze({__proto__:null,identity:{code:Nv,name:iD,encode:Bv,digest:t=>ef(Nv,Bv(t))}});new TextEncoder,new TextDecoder;const Lv=rr(rr(rr(rr(rr(rr(rr(rr(rr(rr({},QO),eC),rC),nC),aC),mC),wC),EC),PC),RC);rr(rr({},rD),nD);function sD(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Fv(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const Uv=Fv("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),tf=Fv("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=sD(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),oD=rr({utf8:Uv,"utf-8":Uv,hex:Lv.base16,latin1:tf,ascii:tf,binary:tf},Lv);function aD(t,e="utf8"){const r=oD[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 cD=Object.defineProperty,lD=(t,e,r)=>e in t?cD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wi=(t,e,r)=>lD(t,typeof e!="symbol"?e+"":e,r);class uD{constructor(e,r){this.core=e,this.logger=r,wi(this,"keychain",new Map),wi(this,"name",uO),wi(this,"version",hO),wi(this,"initialized",!1),wi(this,"storagePrefix",vi),wi(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),wi(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),wi(this,"set",async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()}),wi(this,"get",i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=K("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n}),wi(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=tr(r,this.name)}get context(){return lr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Pb(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ob(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}}var hD=Object.defineProperty,dD=(t,e,r)=>e in t?hD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,kt=(t,e,r)=>dD(t,typeof e!="symbol"?e+"":e,r);class fD{constructor(e,r,i){this.core=e,this.logger=r,kt(this,"name",cO),kt(this,"keychain"),kt(this,"randomSessionIdentifier",Rd()),kt(this,"initialized",!1),kt(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),kt(this,"hasKeys",n=>(this.isInitialized(),this.keychain.has(n))),kt(this,"getClientId",async()=>{this.isInitialized();const n=await this.getClientSeed(),s=yg(n);return vg(s.publicKey)}),kt(this,"generateKeyPair",()=>{this.isInitialized();const n=WI();return this.setPrivateKey(n.publicKey,n.privateKey)}),kt(this,"signJWT",async n=>{this.isInitialized();const s=await this.getClientSeed(),o=yg(s),a=this.randomSessionIdentifier;return await e9(a,n,lO,o)}),kt(this,"generateSharedKey",(n,s,o)=>{this.isInitialized();const a=this.getPrivateKey(n),c=VI(a,s);return this.setSymKey(c,o)}),kt(this,"setSymKey",async(n,s)=>{this.isInitialized();const o=s||$l(n);return await this.keychain.set(o,n),o}),kt(this,"deleteKeyPair",async n=>{this.isInitialized(),await this.keychain.del(n)}),kt(this,"deleteSymKey",async n=>{this.isInitialized(),await this.keychain.del(n)}),kt(this,"encode",async(n,s,o)=>{this.isInitialized();const a=Sm(o),c=Mi(s);if(Pm(a))return ZI(c,o?.encoding);if(Am(a)){const p=a.senderPublicKey,y=a.receiverPublicKey;n=await this.generateSharedKey(p,y)}const l=this.getSymKey(n),{type:u,senderPublicKey:d}=a;return KI({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o?.encoding})}),kt(this,"decode",async(n,s,o)=>{this.isInitialized();const a=JI(s,o);if(Pm(a)){const c=YI(s,o?.encoding);return Fn(c)}if(Am(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;n=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(n),l=GI({symKey:c,encoded:s,encoding:o?.encoding});return Fn(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),kt(this,"getPayloadType",(n,s=pn)=>{const o=Sa({encoded:n,encoding:s});return Zn(o.type)}),kt(this,"getPayloadSenderPublicKey",(n,s=pn)=>{const o=Sa({encoded:n,encoding:s});return o.senderPublicKey?Xt(o.senderPublicKey,Gt):void 0}),this.core=e,this.logger=tr(r,this.name),this.keychain=i||new uD(this.core,this.logger)}get context(){return lr(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(vv)}catch{e=Rd(),await this.keychain.set(vv,e)}return aD(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}}var pD=Object.defineProperty,gD=(t,e,r)=>e in t?pD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_i=(t,e,r)=>gD(t,typeof e!="symbol"?e+"":e,r);class bD extends tP{constructor(e,r){super(e,r),this.logger=e,this.core=r,_i(this,"messages",new Map),_i(this,"name",dO),_i(this,"version",fO),_i(this,"initialized",!1),_i(this,"storagePrefix",vi),_i(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}}}),_i(this,"set",async(i,n)=>{this.isInitialized();const s=ji(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}),_i(this,"get",i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n}),_i(this,"has",(i,n)=>{this.isInitialized();const s=this.get(i),o=ji(n);return typeof s[o]<"u"}),_i(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()}),this.logger=tr(e,this.name),this.core=r}get context(){return lr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Pb(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ob(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}}var mD=Object.defineProperty,vD=Object.defineProperties,yD=Object.getOwnPropertyDescriptors,jv=Object.getOwnPropertySymbols,wD=Object.prototype.hasOwnProperty,_D=Object.prototype.propertyIsEnumerable,rf=(t,e,r)=>e in t?mD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zl=(t,e)=>{for(var r in e||(e={}))wD.call(e,r)&&rf(t,r,e[r]);if(jv)for(var r of jv(e))_D.call(e,r)&&rf(t,r,e[r]);return t},nf=(t,e)=>vD(t,yD(e)),Gr=(t,e,r)=>rf(t,typeof e!="symbol"?e+"":e,r);class xD extends rP{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,Gr(this,"events",new Lt.exports.EventEmitter),Gr(this,"name",pO),Gr(this,"queue",new Map),Gr(this,"publishTimeout",V.toMiliseconds(V.ONE_MINUTE)),Gr(this,"initialPublishTimeout",V.toMiliseconds(V.ONE_SECOND*15)),Gr(this,"needsTransportRestart",!1),Gr(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||yv,c=Il(s),l=s?.prompt||!1,u=s?.tag||0,d=s?.id||Qn().toString(),p={topic:i,message:n,opts:{ttl:a,relay:c,prompt:l,tag:u,id:d,attestation:s?.attestation,tvf:s?.tvf}},y=`Failed to publish payload, please try again. id:${d} tag:${u}`;try{const m=new Promise(async _=>{const S=({id:P})=>{p.opts.id===P&&(this.removeRequestFromQueue(P),this.relayer.events.removeListener(Mt.publish,S),_(p))};this.relayer.events.on(Mt.publish,S);const E=ln(new Promise((P,C)=>{this.rpcPublish({topic:i,message:n,ttl:a,prompt:l,tag:u,id:d,attestation:s?.attestation,tvf:s?.tvf}).then(P).catch(M=>{this.logger.warn(M,M?.message),C(M)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${u}`);try{await E,this.events.removeListener(Mt.publish,S)}catch(P){this.queue.set(d,nf(zl({},p),{attempt:1})),this.logger.warn(P,P?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:i,message:n,opts:s}}),await ln(m,this.publishTimeout,y)}catch(m){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(m),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw m}finally{this.queue.delete(d)}}),Gr(this,"on",(i,n)=>{this.events.on(i,n)}),Gr(this,"once",(i,n)=>{this.events.once(i,n)}),Gr(this,"off",(i,n)=>{this.events.off(i,n)}),Gr(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.relayer=e,this.logger=tr(r,this.name),this.registerEventListeners()}get context(){return lr(this.logger)}async rpcPublish(e){var r,i,n,s;const{topic:o,message:a,ttl:c=yv,prompt:l,tag:u,id:d,attestation:p,tvf:y}=e,m={method:Aa(Il().protocol).publish,params:zl({topic:o,message:a,ttl:c,prompt:l,tag:u,attestation:p},y),id:d};er((r=m.params)==null?void 0:r.prompt)&&((i=m.params)==null||delete i.prompt),er((n=m.params)==null?void 0:n.tag)&&((s=m.params)==null||delete s.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:m});const _=await this.relayer.request(m);return this.relayer.events.emit(Mt.publish,e),this.logger.debug("Successfully Published Payload"),_}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const i=e.attempt+1;this.queue.set(r,nf(zl({},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(nf(zl({},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(ao.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Mt.connection_stalled);return}this.checkQueue()}),this.relayer.on(Mt.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var ED=Object.defineProperty,$D=(t,e,r)=>e in t?ED(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,uo=(t,e,r)=>$D(t,typeof e!="symbol"?e+"":e,r);class ID{constructor(){uo(this,"map",new Map),uo(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),uo(this,"get",e=>this.map.get(e)||[]),uo(this,"exists",(e,r)=>this.get(e).includes(r)),uo(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)}),uo(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var SD=Object.defineProperty,AD=Object.defineProperties,PD=Object.getOwnPropertyDescriptors,qv=Object.getOwnPropertySymbols,OD=Object.prototype.hasOwnProperty,CD=Object.prototype.propertyIsEnumerable,sf=(t,e,r)=>e in t?SD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qa=(t,e)=>{for(var r in e||(e={}))OD.call(e,r)&&sf(t,r,e[r]);if(qv)for(var r of qv(e))CD.call(e,r)&&sf(t,r,e[r]);return t},of=(t,e)=>AD(t,PD(e)),Ie=(t,e,r)=>sf(t,typeof e!="symbol"?e+"":e,r);class DD extends sP{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,Ie(this,"subscriptions",new Map),Ie(this,"topicMap",new ID),Ie(this,"events",new Lt.exports.EventEmitter),Ie(this,"name",_O),Ie(this,"version",xO),Ie(this,"pending",new Map),Ie(this,"cached",[]),Ie(this,"initialized",!1),Ie(this,"pendingSubscriptionWatchLabel","pending_sub_watch_label"),Ie(this,"pollingInterval",20),Ie(this,"storagePrefix",vi),Ie(this,"subscribeTimeout",V.toMiliseconds(V.ONE_MINUTE)),Ie(this,"initialSubscribeTimeout",V.toMiliseconds(V.ONE_SECOND*15)),Ie(this,"clientId"),Ie(this,"batchSubscribeTopicsLimit",500),Ie(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Ie(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=Il(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}}),Ie(this,"unsubscribe",async(i,n)=>{this.isInitialized(),typeof n?.id<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)}),Ie(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 V.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)>=EO&&(clearInterval(c),a.stop(n),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)}),Ie(this,"on",(i,n)=>{this.events.on(i,n)}),Ie(this,"once",(i,n)=>{this.events.once(i,n)}),Ie(this,"off",(i,n)=>{this.events.off(i,n)}),Ie(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),Ie(this,"start",async()=>{await this.onConnect()}),Ie(this,"stop",async()=>{await this.onDisconnect()}),Ie(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Ie(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)}),Ie(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(ao.pulse,async()=>{await this.checkPending()}),this.events.on(vr.created,async i=>{const n=vr.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()}),this.events.on(vr.deleted,async i=>{const n=vr.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()})}),this.relayer=e,this.logger=tr(r,this.name),this.clientId=""}get context(){return lr(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}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}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=Il(i);await this.restartToComplete({topic:e,id:r,relay:n}),await this.rpcUnsubscribe(e,r,n);const s=_e("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||i?.transportType===Re.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const s={method:Aa(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===Re.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(u=>this.logger.warn(u))},V.toMiliseconds(V.ONE_SECOND)),a;const c=new Promise(async u=>{const d=p=>{p.topic===e&&(this.events.removeListener(vr.created,d),u(p.id))};this.events.on(vr.created,d);try{const p=await ln(new Promise((y,m)=>{this.relayer.request(s).catch(_=>{this.logger.warn(_,_?.message),m(_)}).then(y)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(vr.created,d),u(p)}catch{}}),l=await ln(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(Mt.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:Aa(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 ln(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(Mt.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:Aa(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 ln(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(Mt.connection_stalled)}return n}rpcUnsubscribe(e,r,i){const n={method:Aa(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,of(qa({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,qa({},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,qa({},r)),this.topicMap.set(r.topic,e),this.events.emit(vr.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}=K("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(vr.deleted,of(qa({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(vr.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(vr.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=K("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=>of(qa({},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 a$(V.toMiliseconds(V.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}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return ji(e+await this.getClientId())}}var MD=Object.defineProperty,zv=Object.getOwnPropertySymbols,TD=Object.prototype.hasOwnProperty,RD=Object.prototype.propertyIsEnumerable,af=(t,e,r)=>e in t?MD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,kv=(t,e)=>{for(var r in e||(e={}))TD.call(e,r)&&af(t,r,e[r]);if(zv)for(var r of zv(e))RD.call(e,r)&&af(t,r,e[r]);return t},be=(t,e,r)=>af(t,typeof e!="symbol"?e+"":e,r);class ND extends iP{constructor(e){super(e),be(this,"protocol","wc"),be(this,"version",2),be(this,"core"),be(this,"logger"),be(this,"events",new Lt.exports.EventEmitter),be(this,"provider"),be(this,"messages"),be(this,"subscriber"),be(this,"publisher"),be(this,"name",bO),be(this,"transportExplicitlyClosed",!1),be(this,"initialized",!1),be(this,"connectionAttemptInProgress",!1),be(this,"relayUrl"),be(this,"projectId"),be(this,"packageName"),be(this,"bundleId"),be(this,"hasExperiencedNetworkDisruption",!1),be(this,"pingTimeout"),be(this,"heartBeatTimeout",V.toMiliseconds(V.THIRTY_SECONDS+V.FIVE_SECONDS)),be(this,"reconnectTimeout"),be(this,"connectPromise"),be(this,"reconnectInProgress",!1),be(this,"requestsInFlight",[]),be(this,"connectTimeout",V.toMiliseconds(V.ONE_SECOND*15)),be(this,"request",async r=>{var i,n;this.logger.debug("Publishing Request Payload");const s=r.id||Qn().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}}),be(this,"resetPingTimeout",()=>{if(gl())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)}}),be(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),be(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Mt.connect)}),be(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),be(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(Mt.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),be(this,"registerProviderListeners",()=>{this.provider.on(Mr.payload,this.onPayloadHandler),this.provider.on(Mr.connect,this.onConnectHandler),this.provider.on(Mr.disconnect,this.onDisconnectHandler),this.provider.on(Mr.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?tr(e.logger,this.name):pi(Bl({level:e.logger||gO})),this.messages=new bD(this.logger,e.core),this.subscriber=new DD(this,this.logger),this.publisher=new xD(this,this.logger),this.relayUrl=e?.relayUrl||_v,this.projectId=e.projectId,VE()?this.packageName=Ib():KE()&&(this.bundleId=Ib()),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.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return lr(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||!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||this.connectPromise!==void 0||!1}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:Re.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(vr.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(vr.created,l)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(e,kv({internal:{throwOnFailedPublish:o}},r)).catch(p=>{o&&d(p)})||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 ln(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}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 Fm())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=xt(V.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,s)}this.events.emit(Mt.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{if(this.transportExplicitlyClosed)break;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(Mr.disconnect,s),await ln(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(Mr.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Mr.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Mr.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,V.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,n,s;if(gl())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 Dr(new tO(JE({sdkVersion:Qd,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}),Yd(e)){if(!e.method.endsWith(mO))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:o}=r.data,a={topic:i,message:n,publishedAt:s,transportType:Re.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(kv({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Ul(e)&&this.events.emit(Mt.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Mt.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=Ll(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Mr.payload,this.onPayloadHandler),this.provider.off(Mr.connect,this.onConnectHandler),this.provider.off(Mr.disconnect,this.onDisconnectHandler),this.provider.off(Mr.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Fm();FS(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(){clearTimeout(this.pingTimeout),this.events.emit(Mt.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},V.toMiliseconds(vO)))))}isInitialized(){if(!this.initialized){const{message:e}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.connect()}}var BD=Object.defineProperty,Hv=Object.getOwnPropertySymbols,LD=Object.prototype.hasOwnProperty,FD=Object.prototype.propertyIsEnumerable,cf=(t,e,r)=>e in t?BD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wv=(t,e)=>{for(var r in e||(e={}))LD.call(e,r)&&cf(t,r,e[r]);if(Hv)for(var r of Hv(e))FD.call(e,r)&&cf(t,r,e[r]);return t},ur=(t,e,r)=>cf(t,typeof e!="symbol"?e+"":e,r);class rs extends nP{constructor(e,r,i,n=vi,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,ur(this,"map",new Map),ur(this,"version",yO),ur(this,"cached",[]),ur(this,"initialized",!1),ur(this,"getKey"),ur(this,"storagePrefix",vi),ur(this,"recentlyDeleted",[]),ur(this,"recentlyDeletedLimit",200),ur(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!er(o)?this.map.set(this.getKey(o),o):gS(o)?this.map.set(o.id,o):bS(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),ur(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())}),ur(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),ur(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>rO(a[c],o[c]))):this.values)),ur(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=Wv(Wv({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),ur(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=tr(r,this.name),this.storagePrefix=n,this.getKey=s}get context(){return lr(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}=K("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:i}=K("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}=K("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}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}}var UD=Object.defineProperty,jD=(t,e,r)=>e in t?UD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,le=(t,e,r)=>jD(t,typeof e!="symbol"?e+"":e,r);class qD{constructor(e,r){this.core=e,this.logger=r,le(this,"name",$O),le(this,"version",IO),le(this,"events",new Lt.exports),le(this,"pairings"),le(this,"initialized",!1),le(this,"storagePrefix",vi),le(this,"ignoredPayloadTypes",[Ui]),le(this,"registeredMethods",[]),le(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),le(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),le(this,"create",async i=>{this.isInitialized();const n=Rd(),s=await this.core.crypto.setSymKey(n),o=xt(V.FIVE_MINUTES),a={protocol:wv},c={topic:s,expiry:o,relay:a,active:!1,methods:i?.methods},l=Cm({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:a,expiryTimestamp:o,methods:i?.methods});return this.events.emit(Xn.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}}),le(this,"pair",async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i?.uri,trace:[yi.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=Om(i.uri);n.props.properties.topic=s,n.addTrace(yi.pairing_uri_validation_success),n.addTrace(yi.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),n.addTrace(yi.existing_pairing),u.active)throw n.setError(ki.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(yi.pairing_not_expired)}const d=c||xt(V.FIVE_MINUTES),p={topic:s,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(s,d),await this.pairings.set(s,p),n.addTrace(yi.store_new_pairing),i.activatePairing&&await this.activate({topic:s}),this.events.emit(Xn.create,p),n.addTrace(yi.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),n.addTrace(yi.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(ki.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(y){throw n.setError(ki.subscribe_pairing_topic_failure),y}return n.addTrace(yi.subscribe_pairing_topic_success),p}),le(this,"activate",async({topic:i})=>{this.isInitialized();const n=xt(V.FIVE_MINUTES);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})}),le(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}=Kn();this.events.once(ye("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),le(this,"updateExpiry",async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})}),le(this,"updateMetadata",async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})}),le(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),le(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",_e("USER_DISCONNECTED")),await this.deletePairing(n))}),le(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:n,relay:s,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(n);return Cm({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),le(this,"sendRequest",async(i,n,s)=>{const o=gn(n,s),a=await this.core.crypto.encode(i,o),c=La[n].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),le(this,"sendResult",async(i,n,s)=>{const o=Ll(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,l=La[c].res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),le(this,"sendError",async(i,n,s)=>{const o=Fl(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,l=La[c]?La[c].res:La.unregistered_method.res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),le(this,"deletePairing",async(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,_e("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])}),le(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(n=>un(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))}),le(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)}}),le(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)}}),le(this,"onPairingPingRequest",async(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(Xn.ping,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),le(this,"onPairingPingResponse",(i,n)=>{const{id:s}=n;setTimeout(()=>{mi(n)?this.events.emit(ye("pairing_ping",s),{}):Cr(n)&&this.events.emit(ye("pairing_ping",s),{error:n.error})},500)}),le(this,"onPairingDeleteRequest",async(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Xn.delete,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),le(this,"onUnknownRpcMethodRequest",async(i,n)=>{const{id:s,method:o}=n;try{if(this.registeredMethods.includes(o))return;const a=_e("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)}}),le(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(_e("WC_METHOD_UNSUPPORTED",i))}),le(this,"isValidPair",(i,n)=>{var s;if(!ar(i)){const{message:a}=K("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(ki.malformed_pairing_uri),new Error(a)}if(!pS(i.uri)){const{message:a}=K("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(ki.malformed_pairing_uri),new Error(a)}const o=Om(i?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=K("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(ki.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=K("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(ki.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&V.toMiliseconds(o?.expiryTimestamp)<Date.now()){n.setError(ki.pairing_expired);const{message:a}=K("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),le(this,"isValidPing",async i=>{if(!ar(i)){const{message:s}=K("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),le(this,"isValidDisconnect",async i=>{if(!ar(i)){const{message:s}=K("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),le(this,"isValidPairingTopic",async i=>{if(!mt(i,!1)){const{message:n}=K("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=K("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(un(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=K("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}}),this.core=e,this.logger=tr(r,this.name),this.pairings=new rs(this.core,this.logger,this.name,this.storagePrefix)}get context(){return lr(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Mt.message,async e=>{const{topic:r,message:i,transportType:n}=e;if(!this.pairings.keys.includes(r)||n===Re.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const s=await this.core.crypto.decode(r,i);try{Yd(s)?(this.core.history.set(r,s),this.onRelayEventRequest({topic:r,payload:s})):Ul(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(Tr.expired,async e=>{const{topic:r}=Db(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Xn.expire,{topic:r}))})}}var zD=Object.defineProperty,kD=(t,e,r)=>e in t?zD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ht=(t,e,r)=>kD(t,typeof e!="symbol"?e+"":e,r);class HD extends eP{constructor(e,r){super(e,r),this.core=e,this.logger=r,Ht(this,"records",new Map),Ht(this,"events",new Lt.exports.EventEmitter),Ht(this,"name",SO),Ht(this,"version",AO),Ht(this,"cached",[]),Ht(this,"initialized",!1),Ht(this,"storagePrefix",vi),Ht(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)}),Ht(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:xt(V.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Vr.created,o)}),Ht(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=Cr(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(Vr.updated,n))}),Ht(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))),Ht(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(Vr.deleted,s)}}),this.persist()}),Ht(this,"exists",async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1)),Ht(this,"on",(i,n)=>{this.events.on(i,n)}),Ht(this,"once",(i,n)=>{this.events.once(i,n)}),Ht(this,"off",(i,n)=>{this.events.off(i,n)}),Ht(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=tr(r,this.name)}get context(){return lr(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:gn(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}=K("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Vr.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=K("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(Vr.created,e=>{const r=Vr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Vr.updated,e=>{const r=Vr.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Vr.deleted,e=>{const r=Vr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(ao.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{V.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Vr.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}}var WD=Object.defineProperty,VD=(t,e,r)=>e in t?WD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zt=(t,e,r)=>VD(t,typeof e!="symbol"?e+"":e,r);class KD extends oP{constructor(e,r){super(e,r),this.core=e,this.logger=r,Zt(this,"expirations",new Map),Zt(this,"events",new Lt.exports.EventEmitter),Zt(this,"name",PO),Zt(this,"version",OO),Zt(this,"cached",[]),Zt(this,"initialized",!1),Zt(this,"storagePrefix",vi),Zt(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)}),Zt(this,"has",i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}}),Zt(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(Tr.created,{target:s,expiration:o})}),Zt(this,"get",i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)}),Zt(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(Tr.deleted,{target:n,expiration:s})}}),Zt(this,"on",(i,n)=>{this.events.on(i,n)}),Zt(this,"once",(i,n)=>{this.events.once(i,n)}),Zt(this,"off",(i,n)=>{this.events.off(i,n)}),Zt(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=tr(r,this.name)}get context(){return lr(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 QE(e);if(typeof e=="number")return XE(e);const{message:r}=K("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(Tr.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=K("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}=K("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;V.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Tr.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(ao.pulse,()=>this.checkExpirations()),this.events.on(Tr.created,e=>{const r=Tr.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Tr.expired,e=>{const r=Tr.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Tr.deleted,e=>{const r=Tr.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}}var GD=Object.defineProperty,ZD=(t,e,r)=>e in t?GD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yt=(t,e,r)=>ZD(t,typeof e!="symbol"?e+"":e,r);class YD extends aP{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,yt(this,"name",CO),yt(this,"abortController"),yt(this,"isDevEnv"),yt(this,"verifyUrlV3",MO),yt(this,"storagePrefix",vi),yt(this,"version",mv),yt(this,"publicKey"),yt(this,"fetchPromise"),yt(this,"init",async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&V.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),yt(this,"register",async n=>{if(!ba()||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=ea(),u=this.startAbortTimer(V.ONE_SECOND*5),d=await new Promise((p,y)=>{const m=()=>{window.removeEventListener("message",S),l.body.removeChild(_),y("attestation aborted")};this.abortController.signal.addEventListener("abort",m);const _=l.createElement("iframe");_.src=c,_.style.display="none",_.addEventListener("error",m,{signal:this.abortController.signal});const S=E=>{if(E.data&&typeof E.data=="string")try{const P=JSON.parse(E.data);if(P.type==="verify_attestation"){if(Gh(P.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(_),this.abortController.signal.removeEventListener("abort",m),window.removeEventListener("message",S),p(P.attestation===null?"":P.attestation)}}catch(P){this.logger.warn(P)}};l.body.appendChild(_),window.addEventListener("message",S,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",d),d}catch(l){this.logger.warn(l)}return""}),yt(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(Gh(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)}),yt(this,"fetchAttestation",async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const o=this.startAbortTimer(V.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}),yt(this,"getVerifyUrl",n=>{let s=n||Fa;return TO.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Fa}`),s=Fa),s}),yt(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(V.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)}}),yt(this,"persistPublicKey",async n=>{this.logger.debug("persisting public key to local storage",n),await this.store.setItem(this.storeKey,n),this.publicKey=n}),yt(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),yt(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")}}),yt(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),yt(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}),yt(this,"validateAttestation",(n,s)=>{const o=tS(n,s.publicKey),a={hasExpired:V.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=tr(r,this.name),this.abortController=new AbortController,this.isDevEnv=gd(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return lr(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),V.toMiliseconds(e))}}var JD=Object.defineProperty,QD=(t,e,r)=>e in t?JD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Vv=(t,e,r)=>QD(t,typeof e!="symbol"?e+"":e,r);class XD extends cP{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,Vv(this,"context",RO),Vv(this,"registerDeviceToken",async i=>{const{clientId:n,token:s,notificationType:o,enableEncrypted:a=!1}=i,c=`${NO}/${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=tr(r,this.context)}}var eM=Object.defineProperty,Kv=Object.getOwnPropertySymbols,tM=Object.prototype.hasOwnProperty,rM=Object.prototype.propertyIsEnumerable,lf=(t,e,r)=>e in t?eM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,za=(t,e)=>{for(var r in e||(e={}))tM.call(e,r)&&lf(t,r,e[r]);if(Kv)for(var r of Kv(e))rM.call(e,r)&&lf(t,r,e[r]);return t},Tt=(t,e,r)=>lf(t,typeof e!="symbol"?e+"":e,r);class iM extends lP{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,Tt(this,"context",LO),Tt(this,"storagePrefix",vi),Tt(this,"storageVersion",BO),Tt(this,"events",new Map),Tt(this,"shouldPersist",!1),Tt(this,"init",async()=>{if(!gd())try{const n={eventId:Tb(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Ab(this.core.relayer.protocol,this.core.relayer.version,Qd)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}}),Tt(this,"createEvent",n=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=n,l=Tb(),u=this.core.projectId||"",d=Date.now(),p=za({eventId:l,timestamp:d,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,p),this.shouldPersist=!0),p}),Tt(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 za(za({},a),this.setMethods(a.eventId))}),Tt(this,"deleteEvent",n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0}),Tt(this,"setEventListeners",()=>{this.core.heartbeat.on(ao.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{V.fromMiliseconds(Date.now())-V.fromMiliseconds(n.timestamp)>FO&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})}),Tt(this,"setMethods",n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)})),Tt(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)}),Tt(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)}),Tt(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Tt(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,za(za({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}}),Tt(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)}}),Tt(this,"sendEvent",async n=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${UO}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Qd}${s}`,{method:"POST",body:JSON.stringify(n)})}),Tt(this,"getAppDomain",()=>Sb().url),this.logger=tr(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 nM=Object.defineProperty,Gv=Object.getOwnPropertySymbols,sM=Object.prototype.hasOwnProperty,oM=Object.prototype.propertyIsEnumerable,uf=(t,e,r)=>e in t?nM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zv=(t,e)=>{for(var r in e||(e={}))sM.call(e,r)&&uf(t,r,e[r]);if(Gv)for(var r of Gv(e))oM.call(e,r)&&uf(t,r,e[r]);return t},Ce=(t,e,r)=>uf(t,typeof e!="symbol"?e+"":e,r);class hf extends YA{constructor(e){var r;super(e),Ce(this,"protocol",bv),Ce(this,"version",mv),Ce(this,"name",jl),Ce(this,"relayUrl"),Ce(this,"projectId"),Ce(this,"customStoragePrefix"),Ce(this,"events",new Lt.exports.EventEmitter),Ce(this,"logger"),Ce(this,"heartbeat"),Ce(this,"relayer"),Ce(this,"crypto"),Ce(this,"storage"),Ce(this,"history"),Ce(this,"expirer"),Ce(this,"pairing"),Ce(this,"verify"),Ce(this,"echoClient"),Ce(this,"linkModeSupportedApps"),Ce(this,"eventClient"),Ce(this,"initialized",!1),Ce(this,"logChunkController"),Ce(this,"on",(o,a)=>this.events.on(o,a)),Ce(this,"once",(o,a)=>this.events.once(o,a)),Ce(this,"off",(o,a)=>this.events.off(o,a)),Ce(this,"removeListener",(o,a)=>this.events.removeListener(o,a)),Ce(this,"dispatchEnvelope",({topic:o,message:a,sessionExists:c})=>{if(!o||!a)return;const l={topic:o,message:a,publishedAt:Date.now(),transportType:Re.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:c})}),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||_v,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Bl({level:typeof e?.logger=="string"&&e.logger?e.logger:oO.logger,name:jl}),{logger:n,chunkLoggerController:s}=KA({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=tr(n,this.name),this.heartbeat=new Ud,this.crypto=new fD(this,this.logger,e?.keychain),this.history=new HD(this,this.logger),this.expirer=new KD(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new yA(Zv(Zv({},aO),e?.storageOptions)),this.relayer=new ND({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new qD(this,this.logger),this.verify=new YD(this,this.logger,this.storage),this.echoClient=new XD(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new iM(this,this.logger,e?.telemetryEnabled)}static async init(e){const r=new hf(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(wO,i),r}get context(){return lr(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(xv,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(xv)||[],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 aM=hf,Yv="wc",Jv=2,Qv="client",df=`${Yv}@${Jv}:${Qv}:`,ff={name:Qv,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Xv="WALLETCONNECT_DEEPLINK_CHOICE",cM="proposal",e2="Proposal expired",lM="session",ho=V.SEVEN_DAYS,uM="engine",Rt={wc_sessionPropose:{req:{ttl:V.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1104},res:{ttl:V.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1106},res:{ttl:V.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:V.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:V.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1112},res:{ttl:V.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1114},res:{ttl:V.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:V.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:V.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1119}}},pf={min:V.FIVE_MINUTES,max:V.SEVEN_DAYS},xi={idle:"IDLE",active:"ACTIVE"},t2={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},hM="request",dM=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],fM="wc",pM="auth",gM="authKeys",bM="pairingTopics",mM="requests",kl=`${fM}@${1.5}:${pM}:`,Hl=`${kl}:PUB_KEY`;var vM=Object.defineProperty,yM=Object.defineProperties,wM=Object.getOwnPropertyDescriptors,r2=Object.getOwnPropertySymbols,_M=Object.prototype.hasOwnProperty,xM=Object.prototype.propertyIsEnumerable,gf=(t,e,r)=>e in t?vM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ke=(t,e)=>{for(var r in e||(e={}))_M.call(e,r)&&gf(t,r,e[r]);if(r2)for(var r of r2(e))xM.call(e,r)&&gf(t,r,e[r]);return t},hr=(t,e)=>yM(t,wM(e)),W=(t,e,r)=>gf(t,typeof e!="symbol"?e+"":e,r);class EM extends fP{constructor(e){super(e),W(this,"name",uM),W(this,"events",new Lt.exports),W(this,"initialized",!1),W(this,"requestQueue",{state:xi.idle,queue:[]}),W(this,"sessionRequestQueue",{state:xi.idle,queue:[]}),W(this,"requestQueueDelay",V.ONE_SECOND),W(this,"expectedPairingMethodMap",new Map),W(this,"recentlyDeletedMap",new Map),W(this,"recentlyDeletedLimit",200),W(this,"relayMessageCache",[]),W(this,"pendingSessions",new Map),W(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(Rt)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},V.toMiliseconds(this.requestQueueDelay)))}),W(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=hr(Ke({},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,d=!1;try{if(l){const R=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."),d=R.active}}catch(R){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),R}if(!l||!d){const{topic:R,uri:L}=await this.client.core.pairing.create();l=R,u=L}if(!l){const{message:R}=K("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(R)}const p=await this.client.core.crypto.generateKeyPair(),y=Rt.wc_sessionPropose.req.ttl||V.FIVE_MINUTES,m=xt(y),_=hr(Ke({requiredNamespaces:s,optionalNamespaces:o,relays:c??[{protocol:wv}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:m,pairingTopic:l},a&&{sessionProperties:a}),{id:bi()}),S=ye("session_connect",_.id),{reject:E,resolve:P,done:C}=Kn(y,e2),M=({id:R})=>{R===_.id&&(this.client.events.off("proposal_expire",M),this.pendingSessions.delete(_.id),this.events.emit(S,{error:{message:e2,code:0}}))};return this.client.events.on("proposal_expire",M),this.events.once(S,({error:R,session:L})=>{this.client.events.off("proposal_expire",M),R?E(R):L&&P(L)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:_,throwOnFailedPublish:!0,clientRpcId:_.id}),await this.setProposal(_.id,_),{uri:u,approval:C}}),W(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}}),W(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:[Kr.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(F){throw o.setError(es.no_internet_connection),F}try{await this.isValidProposalId(r?.id)}catch(F){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(es.proposal_not_found),F}try{await this.isValidApprove(r)}catch(F){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(es.session_approve_namespace_validation_failure),F}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,sessionConfig:d}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:y,proposer:m,requiredNamespaces:_,optionalNamespaces:S}=p;let E=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:y});E||(E=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Kr.session_approve_started,properties:{topic:y,trace:[Kr.session_approve_started,Kr.session_namespaces_validation_success]}}));const P=await this.client.core.crypto.generateKeyPair(),C=m.publicKey,M=await this.client.core.crypto.generateSharedKey(P,C),R=Ke(Ke({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:P,metadata:this.client.metadata},expiry:xt(ho)},u&&{sessionProperties:u}),d&&{sessionConfig:d}),L=Re.relay;E.addTrace(Kr.subscribing_session_topic);try{await this.client.core.relayer.subscribe(M,{transportType:L})}catch(F){throw E.setError(es.subscribe_session_topic_failure),F}E.addTrace(Kr.subscribe_session_topic_success);const B=hr(Ke({},R),{topic:M,requiredNamespaces:_,optionalNamespaces:S,pairingTopic:y,acknowledged:!1,self:R.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:P,transportType:Re.relay});await this.client.session.set(M,B),E.addTrace(Kr.store_session);try{E.addTrace(Kr.publishing_session_settle),await this.sendRequest({topic:M,method:"wc_sessionSettle",params:R,throwOnFailedPublish:!0}).catch(F=>{throw E?.setError(es.session_settle_publish_failure),F}),E.addTrace(Kr.session_settle_publish_success),E.addTrace(Kr.publishing_session_approve),await this.sendResult({id:a,topic:y,result:{relay:{protocol:c??"irn"},responderPublicKey:P},throwOnFailedPublish:!0}).catch(F=>{throw E?.setError(es.session_approve_publish_failure),F}),E.addTrace(Kr.session_approve_publish_success)}catch(F){throw this.client.logger.error(F),this.client.session.delete(M,_e("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(M),F}return this.client.core.eventClient.deleteEvent({eventId:E.eventId}),await this.client.core.pairing.updateMetadata({topic:y,metadata:m.metadata}),await this.client.proposal.delete(a,_e("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:y}),await this.setExpiry(M,xt(ho)),{topic:M,acknowledged:()=>Promise.resolve(this.client.session.get(M))}}),W(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:Rt.wc_sessionPropose.reject}),await this.client.proposal.delete(i,_e("USER_DISCONNECTED")))}),W(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:i,namespaces:n}=r,{done:s,resolve:o,reject:a}=Kn(),c=bi(),l=Qn().toString(),u=this.client.session.get(i).namespaces;return this.events.once(ye("session_update",c),({error:d})=>{d?a(d):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(d=>{this.client.logger.error(d),this.client.session.update(i,{namespaces:u}),a(d)}),{acknowledged:s}}),W(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=bi(),{done:s,resolve:o,reject:a}=Kn();return this.events.once(ye("session_extend",n),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,xt(ho)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),W(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(E){throw this.client.logger.error("request() -> isValidRequest() failed"),E}const{chainId:i,request:n,topic:s,expiry:o=Rt.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===Re.relay&&await this.confirmOnlineStateOrThrow();const c=bi(),l=Qn().toString(),{done:u,resolve:d,reject:p}=Kn(o,"Request expired. Please try again.");this.events.once(ye("session_request",c),({error:E,result:P})=>{E?p(E):d(P)});const y="wc_sessionRequest",m=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(m)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:y,params:{request:hr(Ke({},n),{expiryTimestamp:xt(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:m}).catch(E=>p(E)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),await u();const _={request:hr(Ke({},n),{expiryTimestamp:xt(o)}),chainId:i},S=this.shouldSetTVF(y,_);return await Promise.all([new Promise(async E=>{await this.sendRequest(Ke({clientRpcId:c,relayRpcId:l,topic:s,method:y,params:_,expiry:o,throwOnFailedPublish:!0},S&&{tvf:this.getTVFParams(c,_)})).catch(P=>p(P)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),E()}),new Promise(async E=>{var P;if(!((P=a.sessionConfig)!=null&&P.disableDeepLink)){const C=await i$(this.client.core.storage,Xv);await e$({id:c,topic:s,wcDeepLink:C})}E()}),u()]).then(E=>E[2])}),W(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===Re.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);mi(n)?await this.sendResult({id:s,topic:i,result:n.result,throwOnFailedPublish:!0,appLink:a}):Cr(n)&&await this.sendError({id:s,topic:i,error:n.error,appLink:a}),this.cleanupAfterResponse(r)}),W(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=bi(),s=Qn().toString(),{done:o,resolve:a,reject:c}=Kn();this.events.once(ye("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}))}),W(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,o=Qn().toString(),a=bi();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),W(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:_e("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}=K("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}}),W(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>dS(i,r)))),W(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),W(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?Re.link_mode:Re.relay;o===Re.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:p,exp:y,nbf:m,methods:_=[],expiry:S}=r,E=[...r.resources||[]],{topic:P,uri:C}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:P,uri:C}});const M=await this.client.core.crypto.generateKeyPair(),R=$l(M);if(await Promise.all([this.client.auth.authKeys.set(Hl,{responseTopic:R,publicKey:M}),this.client.auth.pairingTopics.set(R,{topic:R,pairingTopic:P})]),await this.client.core.relayer.subscribe(R,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${P}`),_.length>0){const{namespace:x}=Xs(a[0]);let f=V$(x,"request",_);wl(E)&&(f=G$(f,E.pop())),E.push(f)}const L=S&&S>Rt.wc_sessionAuthenticate.req.ttl?S:Rt.wc_sessionAuthenticate.req.ttl,B={authPayload:{type:p??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:y,nbf:m,resources:E},requester:{publicKey:M,metadata:this.client.metadata},expiryTimestamp:xt(L)},F={eip155:{chains:a,methods:[...new Set(["personal_sign",..._])],events:["chainChanged","accountsChanged"]}},T={requiredNamespaces:{},optionalNamespaces:F,relays:[{protocol:"irn"}],pairingTopic:P,proposer:{publicKey:M,metadata:this.client.metadata},expiryTimestamp:xt(Rt.wc_sessionPropose.req.ttl),id:bi()},{done:q,resolve:$,reject:h}=Kn(L,"Request expired"),b=bi(),w=ye("session_connect",T.id),g=ye("session_request",b),v=async({error:x,session:f})=>{this.events.off(g,I),x?h(x):f&&$({session:f})},I=async x=>{var f,A,j;if(await this.deletePendingAuthRequest(b,{message:"fulfilled",code:0}),x.error){const Q=_e("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return x.error.code===Q.code?void 0:(this.events.off(w,v),h(x.error.message))}await this.deleteProposal(T.id),this.events.off(w,v);const{cacaos:z,responder:U}=x.result,k=[],Z=[];for(const Q of z){await Gb({cacao:Q,projectId:this.client.core.projectId})||(this.client.logger.error(Q,"Signature verification failed"),h(_e("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:re}=Q,Ze=wl(re.resources),oe=[_d(re.iss)],fe=yl(re.iss);if(Ze){const $t=Jb(Ze),xe=Qb(Ze);k.push(...$t),oe.push(...xe)}for(const $t of oe)Z.push(`${$t}:${fe}`)}const X=await this.client.core.crypto.generateSharedKey(M,U.publicKey);let ee;k.length>0&&(ee={topic:X,acknowledged:!0,self:{publicKey:M,metadata:this.client.metadata},peer:U,controller:U.publicKey,expiry:xt(ho),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:P,namespaces:Dm([...new Set(k)],[...new Set(Z)]),transportType:o},await this.client.core.relayer.subscribe(X,{transportType:o}),await this.client.session.set(X,ee),P&&await this.client.core.pairing.updateMetadata({topic:P,metadata:U.metadata}),ee=this.client.session.get(X)),(f=this.client.metadata.redirect)!=null&&f.linkMode&&(A=U.metadata.redirect)!=null&&A.linkMode&&(j=U.metadata.redirect)!=null&&j.universal&&i&&(this.client.core.addLinkModeSupportedApp(U.metadata.redirect.universal),this.client.session.update(X,{transportType:Re.link_mode})),$({auths:z,session:ee})};this.events.once(w,v),this.events.once(g,I);let O;try{if(s){const x=gn("wc_sessionAuthenticate",B,b);this.client.core.history.set(P,x);const f=await this.client.core.crypto.encode("",x,{type:$a,encoding:xa});O=Sl(i,P,f)}else await Promise.all([this.sendRequest({topic:P,method:"wc_sessionAuthenticate",params:B,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:b}),this.sendRequest({topic:P,method:"wc_sessionPropose",params:T,expiry:Rt.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:T.id})])}catch(x){throw this.events.off(w,v),this.events.off(g,I),x}return await this.setProposal(T.id,T),await this.setAuthRequest(b,{request:hr(Ke({},B),{verifyContext:{}}),pairingTopic:P,transportType:o}),{uri:O??C,response:q}}),W(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[ts.authenticated_session_approve_started]}});try{this.isInitialized()}catch(S){throw s.setError(Ua.no_internet_connection),S}const o=this.getPendingAuthRequest(i);if(!o)throw s.setError(Ua.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||Re.relay;a===Re.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=$l(c),d={type:Ui,receiverPublicKey:c,senderPublicKey:l},p=[],y=[];for(const S of n){if(!await Gb({cacao:S,projectId:this.client.core.projectId})){s.setError(Ua.invalid_cacao);const R=_e("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:u,error:R,encodeOpts:d}),new Error(R.message)}s.addTrace(ts.cacaos_verified);const{p:E}=S,P=wl(E.resources),C=[_d(E.iss)],M=yl(E.iss);if(P){const R=Jb(P),L=Qb(P);p.push(...R),C.push(...L)}for(const R of C)y.push(`${R}:${M}`)}const m=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(ts.create_authenticated_session_topic);let _;if(p?.length>0){_={topic:m,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:xt(ho),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Dm([...new Set(p)],[...new Set(y)]),transportType:a},s.addTrace(ts.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(m,{transportType:a})}catch(S){throw s.setError(Ua.subscribe_authenticated_session_topic_failure),S}s.addTrace(ts.subscribe_authenticated_session_topic_success),await this.client.session.set(m,_),s.addTrace(ts.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(ts.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:i,result:{cacaos:n,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(S){throw s.setError(Ua.authenticated_session_approve_publish_failure),S}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:_}}),W(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===Re.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=$l(o),l={type:Ui,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:n,encodeOpts:l,rpcOpts:Rt.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,_e("USER_DISCONNECTED"))}),W(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:n}=r;return Zb(i,n)}),W(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)}),W(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)}}),W(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,_e("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(Xv).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===n&&this.deletePendingSessionRequest(l.id,_e("USER_DISCONNECTED"))}),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=xi.idle),o&&this.client.events.emit("session_delete",{id:a,topic:n})}),W(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(es.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,_e("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),W(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=xi.idle,this.client.events.emit("session_request_expire",{id:r}))}),W(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)])}),W(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}))}),W(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,xt(Rt.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),W(this,"setAuthRequest",async(r,i)=>{const{request:n,pairingTopic:s,transportType:o=Re.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})}),W(this,"setPendingSessionRequest",async r=>{const{id:i,topic:n,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||xt(Rt.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})}),W(this,"sendRequest",async r=>{const{topic:i,method:n,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:d}=r,p=gn(n,s,c);let y;const m=!!u;try{const E=m?xa:pn;y=await this.client.core.crypto.encode(i,p,{encoding:E})}catch(E){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),E}let _;if(dM.includes(n)){const E=ji(JSON.stringify(p)),P=ji(y);_=await this.client.core.verify.register({id:P,decryptedId:E})}const S=Rt[n].req;if(S.attestation=_,o&&(S.ttl=o),a&&(S.id=a),this.client.core.history.set(i,p),m){const E=Sl(u,i,y);await global.Linking.openURL(E,this.client.name)}else{const E=Rt[n].req;o&&(E.ttl=o),a&&(E.id=a),E.tvf=hr(Ke({},d),{correlationId:p.id}),l?(E.internal=hr(Ke({},E.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,y,E)):this.client.core.relayer.publish(i,y,E).catch(P=>this.client.logger.error(P))}return p.id}),W(this,"sendResult",async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,l=Ll(i,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const m=d?xa:pn;u=await this.client.core.crypto.encode(n,l,hr(Ke({},a||{}),{encoding:m}))}catch(m){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),m}let p,y;try{p=await this.client.core.history.get(n,i);const m=p.request;try{this.shouldSetTVF(m.method,m.params)&&(y=this.getTVFParams(i,m.params,s))}catch(_){this.client.logger.warn("sendResult() -> getTVFParams() failed",_)}}catch(m){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),m}if(d){const m=Sl(c,n,u);await global.Linking.openURL(m,this.client.name)}else{const m=p.request.method,_=Rt[m].res;_.tvf=hr(Ke({},y),{correlationId:i}),o?(_.internal=hr(Ke({},_.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,u,_)):this.client.core.relayer.publish(n,u,_).catch(S=>this.client.logger.error(S))}await this.client.core.history.resolve(l)}),W(this,"sendError",async r=>{const{id:i,topic:n,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,l=Fl(i,s);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const y=d?xa:pn;u=await this.client.core.crypto.encode(n,l,hr(Ke({},o||{}),{encoding:y}))}catch(y){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),y}let p;try{p=await this.client.core.history.get(n,i)}catch(y){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),y}if(d){const y=Sl(c,n,u);await global.Linking.openURL(y,this.client.name)}else{const y=p.request.method,m=a||Rt[y].res;this.client.core.relayer.publish(n,u,m)}await this.client.core.history.resolve(l)}),W(this,"cleanup",async()=>{const r=[],i=[];this.client.session.getAll().forEach(n=>{let s=!1;un(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=>{un(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...r.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])}),W(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),W(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===xi.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=xi.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=xi.idle}),W(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}`)}}),W(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}`)}}),W(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:n}=K("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)}),W(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)}),W(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(ki.proposal_listener_not_found)),this.isValidConnect(Ke({},n.params));const u=a.expiryTimestamp||xt(Rt.wc_sessionPropose.req.ttl),d=Ke({id:c,pairingTopic:i,expiryTimestamp:u},a);await this.setProposal(c,d);const p=await this.getVerifyContext({attestationId:s,hash:ji(JSON.stringify(n)),encryptedId:o,metadata:d.proposer.metadata});l?.addTrace(yi.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:p})}catch(l){await this.sendError({id:c,topic:i,error:l,rpcOpts:Rt.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),W(this,"onSessionProposeResponse",async(r,i,n)=>{const{id:s}=i;if(mi(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.pendingSessions.set(s,{sessionTopic:u,pairingTopic:r,proposalId:s,publicKey:c});const d=await this.client.core.relayer.subscribe(u,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:r})}else if(Cr(i)){await this.client.proposal.delete(s,_e("USER_DISCONNECTED"));const o=ye("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),W(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:d}=i.params,p=[...this.pendingSessions.values()].find(_=>_.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const y=this.client.proposal.get(p.proposalId),m=hr(Ke(Ke({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:y.requiredNamespaces,optionalNamespaces:y.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),d&&{sessionConfig:d}),{transportType:Re.relay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:m.peer.metadata}),this.client.events.emit("session_connect",{session:m}),this.events.emit(ye("session_connect",p.proposalId),{session:m}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(m),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)}}),W(this,"onSessionSettleResponse",async(r,i)=>{const{id:n}=i;mi(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ye("session_approve",n),{})):Cr(i)&&(await this.client.session.delete(r,_e("USER_DISCONNECTED")),this.events.emit(ye("session_approve",n),{error:i.error}))}),W(this,"onSessionUpdateRequest",async(r,i)=>{const{params:n,id:s}=i;try{const o=`${r}_session_update`,a=Ca.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:_e("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Ke({topic:r},n));try{Ca.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 Ca.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)}}),W(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),W(this,"onSessionUpdateResponse",(r,i)=>{const{id:n}=i,s=ye("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);mi(i)?this.events.emit(ye("session_update",n),{}):Cr(i)&&this.events.emit(ye("session_update",n),{error:i.error})}),W(this,"onSessionExtendRequest",async(r,i)=>{const{id:n}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,xt(ho)),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)}}),W(this,"onSessionExtendResponse",(r,i)=>{const{id:n}=i,s=ye("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);mi(i)?this.events.emit(ye("session_extend",n),{}):Cr(i)&&this.events.emit(ye("session_extend",n),{error:i.error})}),W(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)}}),W(this,"onSessionPingResponse",(r,i)=>{const{id:n}=i,s=ye("session_ping",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);setTimeout(()=>{mi(i)?this.events.emit(ye("session_ping",n),{}):Cr(i)&&this.events.emit(ye("session_ping",n),{error:i.error})},500)}),W(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(Mt.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:_e("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),W(this,"onSessionRequest",async r=>{var i,n,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=r,{id:d,params:p}=a;try{await this.isValidRequest(Ke({topic:o},p));const y=this.client.session.get(o),m=await this.getVerifyContext({attestationId:c,hash:ji(JSON.stringify(gn("wc_sessionRequest",p,d))),encryptedId:l,metadata:y.peer.metadata,transportType:u}),_={id:d,topic:o,params:p,verifyContext:m};await this.setPendingSessionRequest(_),u===Re.link_mode&&(i=y.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((n=y.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(_):(this.addSessionRequestToSessionRequestQueue(_),this.processSessionRequestQueue())}catch(y){await this.sendError({id:d,topic:o,error:y}),this.client.logger.error(y)}}),W(this,"onSessionRequestResponse",(r,i)=>{const{id:n}=i,s=ye("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);mi(i)?this.events.emit(ye("session_request",n),{result:i.result}):Cr(i)&&this.events.emit(ye("session_request",n),{error:i.error})}),W(this,"onSessionEventRequest",async(r,i)=>{const{id:n,params:s}=i;try{const o=`${r}_session_event_${s.event.name}`,a=Ca.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(Ke({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),Ca.set(o,n)}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),W(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),mi(i)?this.events.emit(ye("session_request",n),{result:i.result}):Cr(i)&&this.events.emit(ye("session_request",n),{error:i.error})}),W(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:d}=s.params,p=await this.getVerifyContext({attestationId:o,hash:ji(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),y={requester:l,pairingTopic:n,id:s.id,authPayload:u,verifyContext:p,expiryTimestamp:d};await this.setAuthRequest(s.id,{request:y,pairingTopic:n,transportType:c}),c===Re.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:p})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),p=this.getAppLinkIfEnabled(s.params.requester.metadata,c),y={type:Ui,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:s.id,topic:n,error:l,encodeOpts:y,rpcOpts:Rt.wc_sessionAuthenticate.autoReject,appLink:p})}}),W(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),W(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=xi.idle,this.processSessionRequestQueue()},V.toMiliseconds(this.requestQueueDelay))}),W(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=ye("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(ye("session_request",s.request.id),{error:i})})}),W(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===xi.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=xi.active,this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}}),W(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),W(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:gn("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})}),W(this,"isValidConnect",async r=>{if(!ar(r)){const{message:c}=K("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(er(i)||await this.isValidPairingTopic(i),!$S(a,!0)){const{message:c}=K("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(c)}!er(n)&&Oa(n)!==0&&this.validateNamespaces(n,"requiredNamespaces"),!er(s)&&Oa(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),er(o)||this.validateSessionProps(o,"sessionProperties")}),W(this,"validateNamespaces",(r,i)=>{const n=ES(r,"connect()",i);if(n)throw new Error(n.message)}),W(this,"isValidApprove",async r=>{if(!ar(r))throw new Error(K("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=Ld(n,"approve()");if(c)throw new Error(c.message);const l=Bm(a.requiredNamespaces,n,"approve()");if(l)throw new Error(l.message);if(!mt(s,!0)){const{message:u}=K("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(u)}er(o)||this.validateSessionProps(o,"sessionProperties")}),W(this,"isValidReject",async r=>{if(!ar(r)){const{message:s}=K("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:i,reason:n}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!SS(n)){const{message:s}=K("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}}),W(this,"isValidSessionSettleRequest",r=>{if(!ar(r)){const{message:l}=K("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:i,controller:n,namespaces:s,expiry:o}=r;if(!Rm(i)){const{message:l}=K("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=mS(n,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Ld(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(un(o)){const{message:l}=K("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),W(this,"isValidUpdate",async r=>{if(!ar(r)){const{message:c}=K("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=Ld(n,"update()");if(o)throw new Error(o.message);const a=Bm(s.requiredNamespaces,n,"update()");if(a)throw new Error(a.message)}),W(this,"isValidExtend",async r=>{if(!ar(r)){const{message:n}=K("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(n)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),W(this,"isValidRequest",async r=>{if(!ar(r)){const{message:c}=K("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(!Nm(a,s)){const{message:c}=K("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!AS(n)){const{message:c}=K("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(c)}if(!CS(a,s,n.method)){const{message:c}=K("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(c)}if(o&&!RS(o,pf)){const{message:c}=K("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${pf.min} and ${pf.max}`);throw new Error(c)}}),W(this,"isValidRespond",async r=>{var i;if(!ar(r)){const{message:o}=K("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(!PS(s)){const{message:o}=K("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),W(this,"isValidPing",async r=>{if(!ar(r)){const{message:n}=K("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),W(this,"isValidEmit",async r=>{if(!ar(r)){const{message:a}=K("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(!Nm(o,s)){const{message:a}=K("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!OS(n)){const{message:a}=K("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}if(!DS(o,s,n.name)){const{message:a}=K("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}}),W(this,"isValidDisconnect",async r=>{if(!ar(r)){const{message:n}=K("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),W(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(!mt(n,!1))throw new Error("uri is required parameter");if(!mt(s,!1))throw new Error("domain is required parameter");if(!mt(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>Xs(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Xs(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),W(this,"getVerifyContext",async r=>{const{attestationId:i,hash:n,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||Fa,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Re.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}),W(this,"validateSessionProps",(r,i)=>{Object.values(r).forEach(n=>{if(!mt(n,!1)){const{message:s}=K("MISSING_OR_INVALID",`${i} must be in Record<string, string> format. Received: ${JSON.stringify(n)}`);throw new Error(s)}})}),W(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),W(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)}}}),W(this,"checkRecentlyDeleted",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:n}=K("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(n)}}),W(this,"isLinkModeEnabled",(r,i)=>{var n,s,o,a,c,l,u,d,p;return!r||i!==Re.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&&((d=r?.redirect)==null?void 0:d.universal)!==""&&((p=r?.redirect)==null?void 0:p.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),W(this,"getAppLinkIfEnabled",(r,i)=>{var n;return this.isLinkModeEnabled(r,i)?(n=r?.redirect)==null?void 0:n.universal:void 0}),W(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Mb(r,"topic")||"",n=decodeURIComponent(Mb(r,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:Re.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})}),W(this,"registerLinkModeListeners",async()=>{var r;if(gd()||cn()&&(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)}}}),W(this,"shouldSetTVF",(r,i)=>{if(!i||r!=="wc_sessionRequest")return!1;const{request:n}=i;return Object.keys(t2).includes(n.method)}),W(this,"getTVFParams",(r,i,n)=>{var s,o;try{const a=i.request.method,c=this.extractTxHashesFromResult(a,n);return hr(Ke({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{}}),W(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}),W(this,"extractTxHashesFromResult",(r,i)=>{try{const n=t2[r];if(typeof i=="string")return[i];const s=i[n.key];if(fi(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}=K("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Mt.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(Hl)?this.client.auth.authKeys.get(Hl):{responseTopic:void 0,publicKey:void 0},a=await this.client.core.crypto.decode(r,i,{receiverPublicKey:o,encoding:s===Re.link_mode?xa:pn});try{Yd(a)?(this.client.core.history.set(r,a),this.onRelayEventRequest({topic:r,payload:a,attestation:n,transportType:s,encryptedId:ji(i)})):Ul(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(Tr.expired,async e=>{const{topic:r,id:i}=Db(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,K("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,K("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(Xn.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Xn.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!mt(e,!1)){const{message:r}=K("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}=K("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(un(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=K("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!mt(e,!1)){const{message:r}=K("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}=K("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(un(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=K("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=K("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(mt(e,!1)){const{message:r}=K("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=K("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!IS(e)){const{message:r}=K("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=K("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(un(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=K("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class $M extends rs{constructor(e,r){super(e,r,cM,df),this.core=e,this.logger=r}}class IM extends rs{constructor(e,r){super(e,r,lM,df),this.core=e,this.logger=r}}class SM extends rs{constructor(e,r){super(e,r,hM,df,i=>i.id),this.core=e,this.logger=r}}class AM extends rs{constructor(e,r){super(e,r,gM,kl,()=>Hl),this.core=e,this.logger=r}}class PM extends rs{constructor(e,r){super(e,r,bM,kl),this.core=e,this.logger=r}}class OM extends rs{constructor(e,r){super(e,r,mM,kl,i=>i.id),this.core=e,this.logger=r}}var CM=Object.defineProperty,DM=(t,e,r)=>e in t?CM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bf=(t,e,r)=>DM(t,typeof e!="symbol"?e+"":e,r);class MM{constructor(e,r){this.core=e,this.logger=r,bf(this,"authKeys"),bf(this,"pairingTopics"),bf(this,"requests"),this.authKeys=new AM(this.core,this.logger),this.pairingTopics=new PM(this.core,this.logger),this.requests=new OM(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var TM=Object.defineProperty,RM=(t,e,r)=>e in t?TM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ue=(t,e,r)=>RM(t,typeof e!="symbol"?e+"":e,r);class mf extends dP{constructor(e){super(e),ue(this,"protocol",Yv),ue(this,"version",Jv),ue(this,"name",ff.name),ue(this,"metadata"),ue(this,"core"),ue(this,"logger"),ue(this,"events",new Lt.exports.EventEmitter),ue(this,"engine"),ue(this,"session"),ue(this,"proposal"),ue(this,"pendingRequest"),ue(this,"auth"),ue(this,"signConfig"),ue(this,"on",(i,n)=>this.events.on(i,n)),ue(this,"once",(i,n)=>this.events.once(i,n)),ue(this,"off",(i,n)=>this.events.off(i,n)),ue(this,"removeListener",(i,n)=>this.events.removeListener(i,n)),ue(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),ue(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"update",async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"request",async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"find",i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),ue(this,"authenticate",async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}}),ue(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),ue(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),this.name=e?.name||ff.name,this.metadata=e?.metadata||Sb(),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pi(Bl({level:e?.logger||ff.logger}));this.core=e?.core||new aM(e),this.logger=tr(r,this.name),this.session=new IM(this.core,this.logger),this.proposal=new $M(this.core,this.logger),this.pendingRequest=new SM(this.core,this.logger),this.engine=new EM(this),this.auth=new MM(this.core,this.logger)}static async init(e){const r=new mf(e);return await r.initialize(),r}get context(){return lr(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()},V.toMiliseconds(V.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var vf={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof wt<"u"&&wt,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 wt<"u"&&wt||{},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(g){return g&&DataView.prototype.isPrototypeOf(g)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],d=ArrayBuffer.isView||function(g){return g&&u.indexOf(Object.prototype.toString.call(g))>-1};function p(g){if(typeof g!="string"&&(g=String(g)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(g)||g==="")throw new TypeError('Invalid character in header field name: "'+g+'"');return g.toLowerCase()}function y(g){return typeof g!="string"&&(g=String(g)),g}function m(g){var v={next:function(){var I=g.shift();return{done:I===void 0,value:I}}};return c.iterable&&(v[Symbol.iterator]=function(){return v}),v}function _(g){this.map={},g instanceof _?g.forEach(function(v,I){this.append(I,v)},this):Array.isArray(g)?g.forEach(function(v){if(v.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+v.length);this.append(v[0],v[1])},this):g&&Object.getOwnPropertyNames(g).forEach(function(v){this.append(v,g[v])},this)}_.prototype.append=function(g,v){g=p(g),v=y(v);var I=this.map[g];this.map[g]=I?I+", "+v:v},_.prototype.delete=function(g){delete this.map[p(g)]},_.prototype.get=function(g){return g=p(g),this.has(g)?this.map[g]:null},_.prototype.has=function(g){return this.map.hasOwnProperty(p(g))},_.prototype.set=function(g,v){this.map[p(g)]=y(v)},_.prototype.forEach=function(g,v){for(var I in this.map)this.map.hasOwnProperty(I)&&g.call(v,this.map[I],I,this)},_.prototype.keys=function(){var g=[];return this.forEach(function(v,I){g.push(I)}),m(g)},_.prototype.values=function(){var g=[];return this.forEach(function(v){g.push(v)}),m(g)},_.prototype.entries=function(){var g=[];return this.forEach(function(v,I){g.push([I,v])}),m(g)},c.iterable&&(_.prototype[Symbol.iterator]=_.prototype.entries);function S(g){if(!g._noBody){if(g.bodyUsed)return Promise.reject(new TypeError("Already read"));g.bodyUsed=!0}}function E(g){return new Promise(function(v,I){g.onload=function(){v(g.result)},g.onerror=function(){I(g.error)}})}function P(g){var v=new FileReader,I=E(v);return v.readAsArrayBuffer(g),I}function C(g){var v=new FileReader,I=E(v),O=/charset=([A-Za-z0-9_-]+)/.exec(g.type),x=O?O[1]:"utf-8";return v.readAsText(g,x),I}function M(g){for(var v=new Uint8Array(g),I=new Array(v.length),O=0;O<v.length;O++)I[O]=String.fromCharCode(v[O]);return I.join("")}function R(g){if(g.slice)return g.slice(0);var v=new Uint8Array(g.byteLength);return v.set(new Uint8Array(g)),v.buffer}function L(){return this.bodyUsed=!1,this._initBody=function(g){this.bodyUsed=this.bodyUsed,this._bodyInit=g,g?typeof g=="string"?this._bodyText=g:c.blob&&Blob.prototype.isPrototypeOf(g)?this._bodyBlob=g:c.formData&&FormData.prototype.isPrototypeOf(g)?this._bodyFormData=g:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(g)?this._bodyText=g.toString():c.arrayBuffer&&c.blob&&l(g)?(this._bodyArrayBuffer=R(g.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(g)||d(g))?this._bodyArrayBuffer=R(g):this._bodyText=g=Object.prototype.toString.call(g):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof g=="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(g)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var g=S(this);if(g)return g;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 g=S(this);return g||(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(P);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var g=S(this);if(g)return g;if(this._bodyBlob)return C(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(M(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(q)}),this.json=function(){return this.text().then(JSON.parse)},this}var B=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function F(g){var v=g.toUpperCase();return B.indexOf(v)>-1?v:g}function T(g,v){if(!(this instanceof T))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');v=v||{};var I=v.body;if(g instanceof T){if(g.bodyUsed)throw new TypeError("Already read");this.url=g.url,this.credentials=g.credentials,v.headers||(this.headers=new _(g.headers)),this.method=g.method,this.mode=g.mode,this.signal=g.signal,!I&&g._bodyInit!=null&&(I=g._bodyInit,g.bodyUsed=!0)}else this.url=String(g);if(this.credentials=v.credentials||this.credentials||"same-origin",(v.headers||!this.headers)&&(this.headers=new _(v.headers)),this.method=F(v.method||this.method||"GET"),this.mode=v.mode||this.mode||null,this.signal=v.signal||this.signal||function(){if("AbortController"in a){var f=new AbortController;return f.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&I)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(I),(this.method==="GET"||this.method==="HEAD")&&(v.cache==="no-store"||v.cache==="no-cache")){var O=/([?&])_=[^&]*/;if(O.test(this.url))this.url=this.url.replace(O,"$1_="+new Date().getTime());else{var x=/\?/;this.url+=(x.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}T.prototype.clone=function(){return new T(this,{body:this._bodyInit})};function q(g){var v=new FormData;return g.trim().split("&").forEach(function(I){if(I){var O=I.split("="),x=O.shift().replace(/\+/g," "),f=O.join("=").replace(/\+/g," ");v.append(decodeURIComponent(x),decodeURIComponent(f))}}),v}function $(g){var v=new _,I=g.replace(/\r?\n[\t ]+/g," ");return I.split("\r").map(function(O){return O.indexOf(`
40
40
  `)===0?O.substr(1,O.length):O}).forEach(function(O){var x=O.split(":"),f=x.shift().trim();if(f){var A=x.join(":").trim();try{v.append(f,A)}catch(j){console.warn("Response "+j.message)}}}),v}L.call(T.prototype);function h(g,v){if(!(this instanceof h))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(v||(v={}),this.type="default",this.status=v.status===void 0?200:v.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=v.statusText===void 0?"":""+v.statusText,this.headers=new _(v.headers),this.url=v.url||"",this._initBody(g)}L.call(h.prototype),h.prototype.clone=function(){return new h(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new _(this.headers),url:this.url})},h.error=function(){var g=new h(null,{status:200,statusText:""});return g.ok=!1,g.status=0,g.type="error",g};var b=[301,302,303,307,308];h.redirect=function(g,v){if(b.indexOf(v)===-1)throw new RangeError("Invalid status code");return new h(null,{status:v,headers:{location:g}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(v,I){this.message=v,this.name=I;var O=Error(v);this.stack=O.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function w(g,v){return new Promise(function(I,O){var x=new T(g,v);if(x.signal&&x.signal.aborted)return O(new o.DOMException("Aborted","AbortError"));var f=new XMLHttpRequest;function A(){f.abort()}f.onload=function(){var U={statusText:f.statusText,headers:$(f.getAllResponseHeaders()||"")};x.url.indexOf("file://")===0&&(f.status<200||f.status>599)?U.status=200:U.status=f.status,U.url="responseURL"in f?f.responseURL:U.headers.get("X-Request-URL");var k="response"in f?f.response:f.responseText;setTimeout(function(){I(new h(k,U))},0)},f.onerror=function(){setTimeout(function(){O(new TypeError("Network request failed"))},0)},f.ontimeout=function(){setTimeout(function(){O(new TypeError("Network request timed out"))},0)},f.onabort=function(){setTimeout(function(){O(new o.DOMException("Aborted","AbortError"))},0)};function j(U){try{return U===""&&a.location.href?a.location.href:U}catch{return U}}if(f.open(x.method,j(x.url),!0),x.credentials==="include"?f.withCredentials=!0:x.credentials==="omit"&&(f.withCredentials=!1),"responseType"in f&&(c.blob?f.responseType="blob":c.arrayBuffer&&(f.responseType="arraybuffer")),v&&typeof v.headers=="object"&&!(v.headers instanceof _||a.Headers&&v.headers instanceof a.Headers)){var z=[];Object.getOwnPropertyNames(v.headers).forEach(function(U){z.push(p(U)),f.setRequestHeader(U,y(v.headers[U]))}),x.headers.forEach(function(U,k){z.indexOf(k)===-1&&f.setRequestHeader(k,U)})}else x.headers.forEach(function(U,k){f.setRequestHeader(k,U)});x.signal&&(x.signal.addEventListener("abort",A),f.onreadystatechange=function(){f.readyState===4&&x.signal.removeEventListener("abort",A)}),f.send(typeof x._bodyInit>"u"?null:x._bodyInit)})}return w.polyfill=!0,a.fetch||(a.fetch=w,a.Headers=_,a.Request=T,a.Response=h),o.Headers=_,o.Request=T,o.Response=h,o.fetch=w,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})(vf,vf.exports);var i2=kw(vf.exports),NM=Object.defineProperty,BM=Object.defineProperties,LM=Object.getOwnPropertyDescriptors,n2=Object.getOwnPropertySymbols,FM=Object.prototype.hasOwnProperty,UM=Object.prototype.propertyIsEnumerable,s2=(t,e,r)=>e in t?NM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,o2=(t,e)=>{for(var r in e||(e={}))FM.call(e,r)&&s2(t,r,e[r]);if(n2)for(var r of n2(e))UM.call(e,r)&&s2(t,r,e[r]);return t},a2=(t,e)=>BM(t,LM(e));const jM={Accept:"application/json","Content-Type":"application/json"},qM="POST",c2={headers:jM,method:qM},l2=10;class Zr{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new Lt.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!lv(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=Mi(e),i=await(await i2(this.url,a2(o2({},c2),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!lv(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=Mi({id:1,jsonrpc:"2.0",method:"test",params:[]});await i2(e,a2(o2({},c2),{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"?Fn(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=Fl(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return iv(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>l2&&this.events.setMaxListeners(l2)}}const u2="error",zM="wss://relay.walletconnect.org",kM="wc",HM="universal_provider",h2=`${kM}@2:${HM}:`,d2="https://rpc.walletconnect.org/v1/",fo="generic",WM=`${d2}bundler`,Rr={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Wl=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function VM(){this.__data__=[],this.size=0}var KM=VM;function GM(t,e){return t===e||t!==t&&e!==e}var Vl=GM,ZM=Vl;function YM(t,e){for(var r=t.length;r--;)if(ZM(t[r][0],e))return r;return-1}var Kl=YM,JM=Kl,QM=Array.prototype,XM=QM.splice;function eT(t){var e=this.__data__,r=JM(e,t);if(r<0)return!1;var i=e.length-1;return r==i?e.pop():XM.call(e,r,1),--this.size,!0}var tT=eT,rT=Kl;function iT(t){var e=this.__data__,r=rT(e,t);return r<0?void 0:e[r][1]}var nT=iT,sT=Kl;function oT(t){return sT(this.__data__,t)>-1}var aT=oT,cT=Kl;function lT(t,e){var r=this.__data__,i=cT(r,t);return i<0?(++this.size,r.push([t,e])):r[i][1]=e,this}var uT=lT,hT=KM,dT=tT,fT=nT,pT=aT,gT=uT;function po(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])}}po.prototype.clear=hT,po.prototype.delete=dT,po.prototype.get=fT,po.prototype.has=pT,po.prototype.set=gT;var Gl=po,bT=Gl;function mT(){this.__data__=new bT,this.size=0}var vT=mT;function yT(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}var wT=yT;function _T(t){return this.__data__.get(t)}var xT=_T;function ET(t){return this.__data__.has(t)}var $T=ET,IT=typeof Wl=="object"&&Wl&&Wl.Object===Object&&Wl,f2=IT,ST=f2,AT=typeof self=="object"&&self&&self.Object===Object&&self,PT=ST||AT||Function("return this")(),go=PT,OT=go,CT=OT.Symbol,p2=CT,g2=p2,b2=Object.prototype,DT=b2.hasOwnProperty,MT=b2.toString,ka=g2?g2.toStringTag:void 0;function TT(t){var e=DT.call(t,ka),r=t[ka];try{t[ka]=void 0;var i=!0}catch{}var n=MT.call(t);return i&&(e?t[ka]=r:delete t[ka]),n}var RT=TT,NT=Object.prototype,BT=NT.toString;function LT(t){return BT.call(t)}var FT=LT,m2=p2,UT=RT,jT=FT,qT="[object Null]",zT="[object Undefined]",v2=m2?m2.toStringTag:void 0;function kT(t){return t==null?t===void 0?zT:qT:v2&&v2 in Object(t)?UT(t):jT(t)}var Zl=kT;function HT(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var is=HT,WT=Zl,VT=is,KT="[object AsyncFunction]",GT="[object Function]",ZT="[object GeneratorFunction]",YT="[object Proxy]";function JT(t){if(!VT(t))return!1;var e=WT(t);return e==GT||e==ZT||e==KT||e==YT}var yf=JT,QT=go,XT=QT["__core-js_shared__"],eR=XT,wf=eR,y2=function(){var t=/[^.]+$/.exec(wf&&wf.keys&&wf.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function tR(t){return!!y2&&y2 in t}var rR=tR,iR=Function.prototype,nR=iR.toString;function sR(t){if(t!=null){try{return nR.call(t)}catch{}try{return t+""}catch{}}return""}var oR=sR,aR=yf,cR=rR,lR=is,uR=oR,hR=/[\\^$.*+?()[\]{}|]/g,dR=/^\[object .+?Constructor\]$/,fR=Function.prototype,pR=Object.prototype,gR=fR.toString,bR=pR.hasOwnProperty,mR=RegExp("^"+gR.call(bR).replace(hR,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function vR(t){if(!lR(t)||cR(t))return!1;var e=aR(t)?mR:dR;return e.test(uR(t))}var yR=vR;function wR(t,e){return t?.[e]}var _R=wR,xR=yR,ER=_R;function $R(t,e){var r=ER(t,e);return xR(r)?r:void 0}var _f=$R,IR=_f,SR=go,AR=IR(SR,"Map"),w2=AR,PR=_f,OR=PR(Object,"create"),Yl=OR,_2=Yl;function CR(){this.__data__=_2?_2(null):{},this.size=0}var DR=CR;function MR(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var TR=MR,RR=Yl,NR="__lodash_hash_undefined__",BR=Object.prototype,LR=BR.hasOwnProperty;function FR(t){var e=this.__data__;if(RR){var r=e[t];return r===NR?void 0:r}return LR.call(e,t)?e[t]:void 0}var UR=FR,jR=Yl,qR=Object.prototype,zR=qR.hasOwnProperty;function kR(t){var e=this.__data__;return jR?e[t]!==void 0:zR.call(e,t)}var HR=kR,WR=Yl,VR="__lodash_hash_undefined__";function KR(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=WR&&e===void 0?VR:e,this}var GR=KR,ZR=DR,YR=TR,JR=UR,QR=HR,XR=GR;function bo(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])}}bo.prototype.clear=ZR,bo.prototype.delete=YR,bo.prototype.get=JR,bo.prototype.has=QR,bo.prototype.set=XR;var eN=bo,x2=eN,tN=Gl,rN=w2;function iN(){this.size=0,this.__data__={hash:new x2,map:new(rN||tN),string:new x2}}var nN=iN;function sN(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}var oN=sN,aN=oN;function cN(t,e){var r=t.__data__;return aN(e)?r[typeof e=="string"?"string":"hash"]:r.map}var Jl=cN,lN=Jl;function uN(t){var e=lN(this,t).delete(t);return this.size-=e?1:0,e}var hN=uN,dN=Jl;function fN(t){return dN(this,t).get(t)}var pN=fN,gN=Jl;function bN(t){return gN(this,t).has(t)}var mN=bN,vN=Jl;function yN(t,e){var r=vN(this,t),i=r.size;return r.set(t,e),this.size+=r.size==i?0:1,this}var wN=yN,_N=nN,xN=hN,EN=pN,$N=mN,IN=wN;function mo(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])}}mo.prototype.clear=_N,mo.prototype.delete=xN,mo.prototype.get=EN,mo.prototype.has=$N,mo.prototype.set=IN;var SN=mo,AN=Gl,PN=w2,ON=SN,CN=200;function DN(t,e){var r=this.__data__;if(r instanceof AN){var i=r.__data__;if(!PN||i.length<CN-1)return i.push([t,e]),this.size=++r.size,this;r=this.__data__=new ON(i)}return r.set(t,e),this.size=r.size,this}var MN=DN,TN=Gl,RN=vT,NN=wT,BN=xT,LN=$T,FN=MN;function vo(t){var e=this.__data__=new TN(t);this.size=e.size}vo.prototype.clear=RN,vo.prototype.delete=NN,vo.prototype.get=BN,vo.prototype.has=LN,vo.prototype.set=FN;var UN=vo,jN=_f,qN=function(){try{var t=jN(Object,"defineProperty");return t({},"",{}),t}catch{}}(),E2=qN,$2=E2;function zN(t,e,r){e=="__proto__"&&$2?$2(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var xf=zN,kN=xf,HN=Vl;function WN(t,e,r){(r!==void 0&&!HN(t[e],r)||r===void 0&&!(e in t))&&kN(t,e,r)}var I2=WN;function VN(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 KN=VN,GN=KN,ZN=GN(),YN=ZN,Ef={exports:{}};(function(t,e){var r=go,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 d=l.length,p=a?a(d):new l.constructor(d);return l.copy(p),p}t.exports=c})(Ef,Ef.exports);var JN=go,QN=JN.Uint8Array,XN=QN,S2=XN;function eB(t){var e=new t.constructor(t.byteLength);return new S2(e).set(new S2(t)),e}var tB=eB,rB=tB;function iB(t,e){var r=e?rB(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}var nB=iB;function sB(t,e){var r=-1,i=t.length;for(e||(e=Array(i));++r<i;)e[r]=t[r];return e}var oB=sB,aB=is,A2=Object.create,cB=function(){function t(){}return function(e){if(!aB(e))return{};if(A2)return A2(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}(),lB=cB;function uB(t,e){return function(r){return t(e(r))}}var hB=uB,dB=hB,fB=dB(Object.getPrototypeOf,Object),P2=fB,pB=Object.prototype;function gB(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||pB;return t===r}var O2=gB,bB=lB,mB=P2,vB=O2;function yB(t){return typeof t.constructor=="function"&&!vB(t)?bB(mB(t)):{}}var wB=yB;function _B(t){return t!=null&&typeof t=="object"}var Ha=_B,xB=Zl,EB=Ha,$B="[object Arguments]";function IB(t){return EB(t)&&xB(t)==$B}var SB=IB,C2=SB,AB=Ha,D2=Object.prototype,PB=D2.hasOwnProperty,OB=D2.propertyIsEnumerable,CB=C2(function(){return arguments}())?C2:function(t){return AB(t)&&PB.call(t,"callee")&&!OB.call(t,"callee")},M2=CB,DB=Array.isArray,T2=DB,MB=9007199254740991;function TB(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=MB}var R2=TB,RB=yf,NB=R2;function BB(t){return t!=null&&NB(t.length)&&!RB(t)}var $f=BB,LB=$f,FB=Ha;function UB(t){return FB(t)&&LB(t)}var jB=UB,Ql={exports:{}};function qB(){return!1}var zB=qB;(function(t,e){var r=go,i=zB,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})(Ql,Ql.exports);var kB=Zl,HB=P2,WB=Ha,VB="[object Object]",KB=Function.prototype,GB=Object.prototype,N2=KB.toString,ZB=GB.hasOwnProperty,YB=N2.call(Object);function JB(t){if(!WB(t)||kB(t)!=VB)return!1;var e=HB(t);if(e===null)return!0;var r=ZB.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&N2.call(r)==YB}var QB=JB,XB=Zl,eL=R2,tL=Ha,rL="[object Arguments]",iL="[object Array]",nL="[object Boolean]",sL="[object Date]",oL="[object Error]",aL="[object Function]",cL="[object Map]",lL="[object Number]",uL="[object Object]",hL="[object RegExp]",dL="[object Set]",fL="[object String]",pL="[object WeakMap]",gL="[object ArrayBuffer]",bL="[object DataView]",mL="[object Float32Array]",vL="[object Float64Array]",yL="[object Int8Array]",wL="[object Int16Array]",_L="[object Int32Array]",xL="[object Uint8Array]",EL="[object Uint8ClampedArray]",$L="[object Uint16Array]",IL="[object Uint32Array]",Ne={};Ne[mL]=Ne[vL]=Ne[yL]=Ne[wL]=Ne[_L]=Ne[xL]=Ne[EL]=Ne[$L]=Ne[IL]=!0,Ne[rL]=Ne[iL]=Ne[gL]=Ne[nL]=Ne[bL]=Ne[sL]=Ne[oL]=Ne[aL]=Ne[cL]=Ne[lL]=Ne[uL]=Ne[hL]=Ne[dL]=Ne[fL]=Ne[pL]=!1;function SL(t){return tL(t)&&eL(t.length)&&!!Ne[XB(t)]}var AL=SL;function PL(t){return function(e){return t(e)}}var OL=PL,If={exports:{}};(function(t,e){var r=f2,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})(If,If.exports);var CL=AL,DL=OL,B2=If.exports,L2=B2&&B2.isTypedArray,ML=L2?DL(L2):CL,F2=ML;function TL(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}var U2=TL,RL=xf,NL=Vl,BL=Object.prototype,LL=BL.hasOwnProperty;function FL(t,e,r){var i=t[e];(!(LL.call(t,e)&&NL(i,r))||r===void 0&&!(e in t))&&RL(t,e,r)}var UL=FL,jL=UL,qL=xf;function zL(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?qL(r,a,c):jL(r,a,c)}return r}var kL=zL;function HL(t,e){for(var r=-1,i=Array(t);++r<t;)i[r]=e(r);return i}var WL=HL,VL=9007199254740991,KL=/^(?:0|[1-9]\d*)$/;function GL(t,e){var r=typeof t;return e=e??VL,!!e&&(r=="number"||r!="symbol"&&KL.test(t))&&t>-1&&t%1==0&&t<e}var j2=GL,ZL=WL,YL=M2,JL=T2,QL=Ql.exports,XL=j2,eF=F2,tF=Object.prototype,rF=tF.hasOwnProperty;function iF(t,e){var r=JL(t),i=!r&&YL(t),n=!r&&!i&&QL(t),s=!r&&!i&&!n&&eF(t),o=r||i||n||s,a=o?ZL(t.length,String):[],c=a.length;for(var l in t)(e||rF.call(t,l))&&!(o&&(l=="length"||n&&(l=="offset"||l=="parent")||s&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||XL(l,c)))&&a.push(l);return a}var nF=iF;function sF(t){var e=[];if(t!=null)for(var r in Object(t))e.push(r);return e}var oF=sF,aF=is,cF=O2,lF=oF,uF=Object.prototype,hF=uF.hasOwnProperty;function dF(t){if(!aF(t))return lF(t);var e=cF(t),r=[];for(var i in t)i=="constructor"&&(e||!hF.call(t,i))||r.push(i);return r}var fF=dF,pF=nF,gF=fF,bF=$f;function mF(t){return bF(t)?pF(t,!0):gF(t)}var q2=mF,vF=kL,yF=q2;function wF(t){return vF(t,yF(t))}var _F=wF,z2=I2,xF=Ef.exports,EF=nB,$F=oB,IF=wB,k2=M2,H2=T2,SF=jB,AF=Ql.exports,PF=yf,OF=is,CF=QB,DF=F2,W2=U2,MF=_F;function TF(t,e,r,i,n,s,o){var a=W2(t,r),c=W2(e,r),l=o.get(c);if(l){z2(t,r,l);return}var u=s?s(a,c,r+"",t,e,o):void 0,d=u===void 0;if(d){var p=H2(c),y=!p&&AF(c),m=!p&&!y&&DF(c);u=c,p||y||m?H2(a)?u=a:SF(a)?u=$F(a):y?(d=!1,u=xF(c,!0)):m?(d=!1,u=EF(c,!0)):u=[]:CF(c)||k2(c)?(u=a,k2(a)?u=MF(a):(!OF(a)||PF(a))&&(u=IF(c))):d=!1}d&&(o.set(c,u),n(u,c,i,s,o),o.delete(c)),z2(t,r,u)}var RF=TF,NF=UN,BF=I2,LF=YN,FF=RF,UF=is,jF=q2,qF=U2;function V2(t,e,r,i,n){t!==e&&LF(e,function(s,o){if(n||(n=new NF),UF(s))FF(t,e,o,r,V2,i,n);else{var a=i?i(qF(t,o),s,o+"",t,e,n):void 0;a===void 0&&(a=s),BF(t,o,a)}},jF)}var zF=V2;function kF(t){return t}var K2=kF;function HF(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 WF=HF,VF=WF,G2=Math.max;function KF(t,e,r){return e=G2(e===void 0?t.length-1:e,0),function(){for(var i=arguments,n=-1,s=G2(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),VF(t,this,a)}}var GF=KF;function ZF(t){return function(){return t}}var YF=ZF,JF=YF,Z2=E2,QF=K2,XF=Z2?function(t,e){return Z2(t,"toString",{configurable:!0,enumerable:!1,value:JF(e),writable:!0})}:QF,eU=XF,tU=800,rU=16,iU=Date.now;function nU(t){var e=0,r=0;return function(){var i=iU(),n=rU-(i-r);if(r=i,n>0){if(++e>=tU)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}var sU=nU,oU=eU,aU=sU,cU=aU(oU),lU=cU,uU=K2,hU=GF,dU=lU;function fU(t,e){return dU(hU(t,e,uU),t+"")}var pU=fU,gU=Vl,bU=$f,mU=j2,vU=is;function yU(t,e,r){if(!vU(r))return!1;var i=typeof e;return(i=="number"?bU(r)&&mU(e,r.length):i=="string"&&e in r)?gU(r[e],t):!1}var wU=yU,_U=pU,xU=wU;function EU(t){return _U(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&&xU(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 $U=EU,IU=zF,SU=$U,AU=SU(function(t,e,r){IU(t,e,r)}),PU=AU,OU=Object.defineProperty,CU=Object.defineProperties,DU=Object.getOwnPropertyDescriptors,Y2=Object.getOwnPropertySymbols,MU=Object.prototype.hasOwnProperty,TU=Object.prototype.propertyIsEnumerable,J2=(t,e,r)=>e in t?OU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Xl=(t,e)=>{for(var r in e||(e={}))MU.call(e,r)&&J2(t,r,e[r]);if(Y2)for(var r of Y2(e))TU.call(e,r)&&J2(t,r,e[r]);return t},RU=(t,e)=>CU(t,DU(e));function yr(t,e,r){var i;const n=Xs(t);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${d2}?chainId=${n.namespace}:${n.reference}&projectId=${r}`}function ns(t){return t.includes(":")?t.split(":")[1]:t}function Q2(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function NU(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 Sf(t={},e={}){const r=X2(t),i=X2(e);return PU(r,i)}function X2(t){var e,r,i,n;const s={};if(!Oa(t))return s;for(const[o,a]of Object.entries(t)){const c=Nd(o)?[o]:a.chains,l=a.methods||[],u=a.events||[],d=a.rpcMap||{},p=Pa(o);s[p]=RU(Xl(Xl({},s[p]),a),{chains:bl(c,(e=s[p])==null?void 0:e.chains),methods:bl(l,(r=s[p])==null?void 0:r.methods),events:bl(u,(i=s[p])==null?void 0:i.events),rpcMap:Xl(Xl({},d),(n=s[p])==null?void 0:n.rpcMap)})}return s}function BU(t){return t.includes(":")?t.split(":")[2]:t}function ey(t){const e={};for(const[r,i]of Object.entries(t)){const n=i.methods||[],s=i.events||[],o=i.accounts||[],a=Nd(r)?[r]:i.chains?i.chains:Q2(i.accounts);e[r]={chains:a,methods:n,events:s,accounts:o}}return e}function Af(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 ty={},me=t=>ty[t],Pf=(t,e)=>{ty[t]=e};var LU=Object.defineProperty,FU=(t,e,r)=>e in t?LU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yo=(t,e,r)=>FU(t,typeof e!="symbol"?e+"":e,r);class UU{constructor(e){yo(this,"name","polkadot"),yo(this,"client"),yo(this,"httpProviders"),yo(this,"events"),yo(this,"namespace"),yo(this,"chainId"),this.namespace=e.namespace,this.events=me("events"),this.client=me("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(Rr.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=ns(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 Dr(new Zr(i,me("disableProviderPing")))}}var jU=Object.defineProperty,qU=Object.defineProperties,zU=Object.getOwnPropertyDescriptors,ry=Object.getOwnPropertySymbols,kU=Object.prototype.hasOwnProperty,HU=Object.prototype.propertyIsEnumerable,Of=(t,e,r)=>e in t?jU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,iy=(t,e)=>{for(var r in e||(e={}))kU.call(e,r)&&Of(t,r,e[r]);if(ry)for(var r of ry(e))HU.call(e,r)&&Of(t,r,e[r]);return t},ny=(t,e)=>qU(t,zU(e)),wo=(t,e,r)=>Of(t,typeof e!="symbol"?e+"":e,r);class WU{constructor(e){wo(this,"name","eip155"),wo(this,"client"),wo(this,"chainId"),wo(this,"namespace"),wo(this,"httpProviders"),wo(this,"events"),this.namespace=e.namespace,this.events=me("events"),this.client=me("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(Rr.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 Dr(new Zr(i,me("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(ns(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:ny(iy({},o.sessionProperties||{}),{capabilities:ny(iy({},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(gn("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`${WM}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}}var VU=Object.defineProperty,KU=(t,e,r)=>e in t?VU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_o=(t,e,r)=>KU(t,typeof e!="symbol"?e+"":e,r);class GU{constructor(e){_o(this,"name","solana"),_o(this,"client"),_o(this,"httpProviders"),_o(this,"events"),_o(this,"namespace"),_o(this,"chainId"),this.namespace=e.namespace,this.events=me("events"),this.client=me("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(Rr.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=ns(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 Dr(new Zr(i,me("disableProviderPing")))}}var ZU=Object.defineProperty,YU=(t,e,r)=>e in t?ZU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xo=(t,e,r)=>YU(t,typeof e!="symbol"?e+"":e,r);class JU{constructor(e){xo(this,"name","cosmos"),xo(this,"client"),xo(this,"httpProviders"),xo(this,"events"),xo(this,"namespace"),xo(this,"chainId"),this.namespace=e.namespace,this.events=me("events"),this.client=me("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(Rr.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=ns(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 Dr(new Zr(i,me("disableProviderPing")))}}var QU=Object.defineProperty,XU=(t,e,r)=>e in t?QU(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Eo=(t,e,r)=>XU(t,typeof e!="symbol"?e+"":e,r);class ej{constructor(e){Eo(this,"name","algorand"),Eo(this,"client"),Eo(this,"httpProviders"),Eo(this,"events"),Eo(this,"namespace"),Eo(this,"chainId"),this.namespace=e.namespace,this.events=me("events"),this.client=me("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(Rr.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 Dr(new Zr(i,me("disableProviderPing")))}}var tj=Object.defineProperty,rj=(t,e,r)=>e in t?tj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$o=(t,e,r)=>rj(t,typeof e!="symbol"?e+"":e,r);class ij{constructor(e){$o(this,"name","cip34"),$o(this,"client"),$o(this,"httpProviders"),$o(this,"events"),$o(this,"namespace"),$o(this,"chainId"),this.namespace=e.namespace,this.events=me("events"),this.client=me("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(Rr.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=ns(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 Dr(new Zr(i,me("disableProviderPing")))}}var nj=Object.defineProperty,sj=(t,e,r)=>e in t?nj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Io=(t,e,r)=>sj(t,typeof e!="symbol"?e+"":e,r);class oj{constructor(e){Io(this,"name","elrond"),Io(this,"client"),Io(this,"httpProviders"),Io(this,"events"),Io(this,"namespace"),Io(this,"chainId"),this.namespace=e.namespace,this.events=me("events"),this.client=me("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(Rr.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=ns(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 Dr(new Zr(i,me("disableProviderPing")))}}var aj=Object.defineProperty,cj=(t,e,r)=>e in t?aj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,So=(t,e,r)=>cj(t,typeof e!="symbol"?e+"":e,r);class lj{constructor(e){So(this,"name","multiversx"),So(this,"client"),So(this,"httpProviders"),So(this,"events"),So(this,"namespace"),So(this,"chainId"),this.namespace=e.namespace,this.events=me("events"),this.client=me("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(Rr.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=ns(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 Dr(new Zr(i,me("disableProviderPing")))}}var uj=Object.defineProperty,hj=(t,e,r)=>e in t?uj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ao=(t,e,r)=>hj(t,typeof e!="symbol"?e+"":e,r);class dj{constructor(e){Ao(this,"name","near"),Ao(this,"client"),Ao(this,"httpProviders"),Ao(this,"events"),Ao(this,"namespace"),Ao(this,"chainId"),this.namespace=e.namespace,this.events=me("events"),this.client=me("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(Rr.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 Dr(new Zr(i,me("disableProviderPing")))}}var fj=Object.defineProperty,pj=(t,e,r)=>e in t?fj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Po=(t,e,r)=>pj(t,typeof e!="symbol"?e+"":e,r);class gj{constructor(e){Po(this,"name","tezos"),Po(this,"client"),Po(this,"httpProviders"),Po(this,"events"),Po(this,"namespace"),Po(this,"chainId"),this.namespace=e.namespace,this.events=me("events"),this.client=me("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(Rr.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 Dr(new Zr(i))}}var bj=Object.defineProperty,mj=(t,e,r)=>e in t?bj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Oo=(t,e,r)=>mj(t,typeof e!="symbol"?e+"":e,r);class vj{constructor(e){Oo(this,"name",fo),Oo(this,"client"),Oo(this,"httpProviders"),Oo(this,"events"),Oo(this,"namespace"),Oo(this,"chainId"),this.namespace=e.namespace,this.events=me("events"),this.client=me("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(Rr.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=Xs(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 Dr(new Zr(i,me("disableProviderPing")))}}var yj=Object.defineProperty,wj=Object.defineProperties,_j=Object.getOwnPropertyDescriptors,sy=Object.getOwnPropertySymbols,xj=Object.prototype.hasOwnProperty,Ej=Object.prototype.propertyIsEnumerable,Cf=(t,e,r)=>e in t?yj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,eu=(t,e)=>{for(var r in e||(e={}))xj.call(e,r)&&Cf(t,r,e[r]);if(sy)for(var r of sy(e))Ej.call(e,r)&&Cf(t,r,e[r]);return t},Df=(t,e)=>wj(t,_j(e)),Yr=(t,e,r)=>Cf(t,typeof e!="symbol"?e+"":e,r);class Mf{constructor(e){Yr(this,"client"),Yr(this,"namespaces"),Yr(this,"optionalNamespaces"),Yr(this,"sessionProperties"),Yr(this,"events",new Lt.exports),Yr(this,"rpcProviders",{}),Yr(this,"session"),Yr(this,"providerOpts"),Yr(this,"logger"),Yr(this,"uri"),Yr(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:pi(Bl({level:e?.logger||u2})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new Mf(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:eu({},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,Ll(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:_e("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=ey(this.session.namespaces);this.namespaces=Sf(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){const{uri:r,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});r&&(this.uri=r,this.events.emit("display_uri",r));const n=await i();this.session=n;const s=ey(n.namespaces);return this.namespaces=Sf(this.namespaces,s),this.persist("namespaces",this.namespaces),this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[i,n]=this.validateChain(e),s=this.getProvider(i);s.name===fo?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(fi(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.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}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 mf.init({core:this.providerOpts.core,logger:this.providerOpts.logger||u2,relayUrl:this.providerOpts.relayUrl||zM,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=>Pa(r)))];Pf("client",this.client),Pf("events",this.events),Pf("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=NU(r,this.session),n=Q2(i),s=Sf(this.namespaces,this.optionalNamespaces),o=Df(eu({},s[r]),{accounts:i,chains:n});switch(r){case"eip155":this.rpcProviders[r]=new WU({namespace:o});break;case"algorand":this.rpcProviders[r]=new ej({namespace:o});break;case"solana":this.rpcProviders[r]=new GU({namespace:o});break;case"cosmos":this.rpcProviders[r]=new JU({namespace:o});break;case"polkadot":this.rpcProviders[r]=new UU({namespace:o});break;case"cip34":this.rpcProviders[r]=new ij({namespace:o});break;case"elrond":this.rpcProviders[r]=new oj({namespace:o});break;case"multiversx":this.rpcProviders[r]=new lj({namespace:o});break;case"near":this.rpcProviders[r]=new dj({namespace:o});break;case"tezos":this.rpcProviders[r]=new gj({namespace:o});break;default:this.rpcProviders[fo]?this.rpcProviders[fo].updateNamespace(o):this.rpcProviders[fo]=new vj({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&&fi(n)&&this.events.emit("accountsChanged",n.map(BU))}else if(i.name==="chainChanged"){const n=r.chainId,s=r.event.data,o=Pa(n),a=Af(n)!==Af(s)?`${o}:${Af(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=Df(eu({},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",Df(eu({},_e("USER_DISCONNECTED")),{data:e.topic}))}),this.on(Rr.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[fo]}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=>Pa(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=Pa(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(`${h2}/${e}`,r)}async getFromStore(e){return await this.client.core.storage.getItem(`${h2}/${e}`)}}const $j=Mf,Ij="wc",Sj="ethereum_provider",Aj=`${Ij}@2:${Sj}:`,Pj="https://rpc.walletconnect.org/v1/",tu=["eth_sendTransaction","personal_sign"],oy=["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"],ru=["chainChanged","accountsChanged"],ay=["chainChanged","accountsChanged","message","disconnect","connect"];var Oj=Object.defineProperty,Cj=Object.defineProperties,Dj=Object.getOwnPropertyDescriptors,cy=Object.getOwnPropertySymbols,Mj=Object.prototype.hasOwnProperty,Tj=Object.prototype.propertyIsEnumerable,Tf=(t,e,r)=>e in t?Oj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Co=(t,e)=>{for(var r in e||(e={}))Mj.call(e,r)&&Tf(t,r,e[r]);if(cy)for(var r of cy(e))Tj.call(e,r)&&Tf(t,r,e[r]);return t},Rf=(t,e)=>Cj(t,Dj(e)),wr=(t,e,r)=>Tf(t,typeof e!="symbol"?e+"":e,r);function iu(t){return Number(t[0].split(":")[1])}function nu(t){return`0x${t.toString(16)}`}function Rj(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:n,events:s,optionalEvents:o,rpcMap:a}=t;if(!fi(e))throw new Error("Invalid chains");const c={chains:e,methods:i||tu,events:s||ru,rpcMap:Co({},e.length?{[iu(e)]:a[iu(e)]}:{})},l=s?.filter(y=>!ru.includes(y)),u=i?.filter(y=>!tu.includes(y));if(!r&&!o&&!n&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:e.length?c:void 0};const d=l?.length&&u?.length||!r,p={chains:[...new Set(d?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(n!=null&&n.length?n:oy))],events:[...new Set(c.events.concat(o!=null&&o.length?o:ay))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?p:void 0}}class su{constructor(){wr(this,"events",new Lt.exports.EventEmitter),wr(this,"namespace","eip155"),wr(this,"accounts",[]),wr(this,"signer"),wr(this,"chainId",1),wr(this,"modal"),wr(this,"rpc"),wr(this,"STORAGE_KEY",Aj),wr(this,"on",(e,r)=>(this.events.on(e,r),this)),wr(this,"once",(e,r)=>(this.events.once(e,r),this)),wr(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),wr(this,"off",(e,r)=>(this.events.off(e,r),this)),wr(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new su;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}=Rj(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(Rf(Co({namespaces:Co({},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=Eb(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:nu(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(Rf(Co({},e),{chains:this.rpc.chains}),r).then(c=>{s(c)}).catch(c=>{o(new Error(c.message))})}),n=i.session;if(n){const s=Eb(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:nu(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",nu(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",Rf(Co({},_e("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",nu(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||tu:[],c=n.length?e?.events||ru:[],l=e?.optionalMethods||[],u=e?.optionalEvents||[],d=e?.rpcMap||this.buildRpcMap(o,e.projectId),p=e?.qrModalOptions||void 0;return{chains:n?.map(y=>this.formatChainId(y)),optionalChains:s.map(y=>this.formatChainId(y)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:d,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:p,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?iu(this.rpc.chains):iu(this.rpc.optionalChains),this.signer=await $j.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 iq});r=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(r)try{this.modal=new r(Co({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&&fi(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=n?.[s]||this.getRpcUrl(s)})),i&&fi(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])||`${Pj}?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 Nj=su,Bj=Symbol(),ly=Object.getPrototypeOf,Nf=new WeakMap,Lj=t=>t&&(Nf.has(t)?Nf.get(t):ly(t)===Object.prototype||ly(t)===Array.prototype),Fj=t=>Lj(t)&&t[Bj]||null,uy=(t,e=!0)=>{Nf.set(t,e)},Bf=t=>typeof t=="object"&&t!==null,bn=new WeakMap,ou=new WeakSet,Uj=(t=Object.is,e=(l,u)=>new Proxy(l,u),r=l=>Bf(l)&&!ou.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,d=i)=>{const p=n.get(l);if(p?.[0]===u)return p[1];const y=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return uy(y,!0),n.set(l,[u,y]),Reflect.ownKeys(l).forEach(m=>{if(Object.getOwnPropertyDescriptor(y,m))return;const _=Reflect.get(l,m),S={value:_,enumerable:!0,configurable:!0};if(ou.has(_))uy(_,!1);else if(_ instanceof Promise)delete S.value,S.get=()=>d(_);else if(bn.has(_)){const[E,P]=bn.get(_);S.value=s(E,P(),d)}Object.defineProperty(y,m,S)}),Object.preventExtensions(y)},o=new WeakMap,a=[1,1],c=l=>{if(!Bf(l))throw new Error("object required");const u=o.get(l);if(u)return u;let d=a[0];const p=new Set,y=(T,q=++a[0])=>{d!==q&&(d=q,p.forEach($=>$(T,q)))};let m=a[1];const _=(T=++a[1])=>(m!==T&&!p.size&&(m=T,E.forEach(([q])=>{const $=q[1](T);$>d&&(d=$)})),d),S=T=>(q,$)=>{const h=[...q];h[1]=[T,...h[1]],y(h,$)},E=new Map,P=(T,q)=>{if(E.has(T))throw new Error("prop listener already exists");if(p.size){const $=q[3](S(T));E.set(T,[q,$])}else E.set(T,[q])},C=T=>{var q;const $=E.get(T);$&&(E.delete(T),(q=$[1])==null||q.call($))},M=T=>(p.add(T),p.size===1&&E.forEach(([$,h],b)=>{if(h)throw new Error("remove already exists");const w=$[3](S(b));E.set(b,[$,w])}),()=>{p.delete(T),p.size===0&&E.forEach(([$,h],b)=>{h&&(h(),E.set(b,[$]))})}),R=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),B=e(R,{deleteProperty(T,q){const $=Reflect.get(T,q);C(q);const h=Reflect.deleteProperty(T,q);return h&&y(["delete",[q],$]),h},set(T,q,$,h){const b=Reflect.has(T,q),w=Reflect.get(T,q,h);if(b&&(t(w,$)||o.has($)&&t(w,o.get($))))return!0;C(q),Bf($)&&($=Fj($)||$);let g=$;if($ instanceof Promise)$.then(v=>{$.status="fulfilled",$.value=v,y(["resolve",[q],v])}).catch(v=>{$.status="rejected",$.reason=v,y(["reject",[q],v])});else{!bn.has($)&&r($)&&(g=c($));const v=!ou.has(g)&&bn.get(g);v&&P(q,v)}return Reflect.set(T,q,g,h),y(["set",[q],$,w]),!0}});o.set(l,B);const F=[R,_,s,M];return bn.set(B,F),Reflect.ownKeys(l).forEach(T=>{const q=Object.getOwnPropertyDescriptor(l,T);"value"in q&&(B[T]=l[T],delete q.value,delete q.writable),Object.defineProperty(R,T,q)}),B})=>[c,bn,ou,t,e,r,i,n,s,o,a],[jj]=Uj();function mn(t={}){return jj(t)}function ss(t,e,r){const i=bn.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 qj(t,e){const r=bn.get(t);r||console.warn("Please use proxy object");const[i,n,s]=r;return s(i,n(),e)}const Nt=mn({history:["ConnectWallet"],view:"ConnectWallet",data:void 0}),Ge={state:Nt,subscribe(t){return ss(Nt,()=>t(Nt))},push(t,e){t!==Nt.view&&(Nt.view=t,e&&(Nt.data=e),Nt.history.push(t))},reset(t){Nt.view=t,Nt.history=[t]},replace(t){Nt.history.length>1&&(Nt.history[Nt.history.length-1]=t,Nt.view=t)},goBack(){if(Nt.history.length>1){Nt.history.pop();const[t]=Nt.history.slice(-1);Nt.view=t}},setData(t){Nt.data=t}},J={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 J.isMobile()&&navigator.userAgent.toLowerCase().includes("android")},isIos(){const t=navigator.userAgent.toLowerCase();return J.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(J.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(!J.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(J.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(J.WALLETCONNECT_DEEPLINK_CHOICE,JSON.stringify({href:e,name:"Android"}))}catch{console.info("Unable to set WalletConnect android deep link")}},removeWalletConnectDeepLink(){try{localStorage.removeItem(J.WALLETCONNECT_DEEPLINK_CHOICE)}catch{console.info("Unable to remove WalletConnect deep link")}},setModalVersionInStorage(){try{typeof localStorage<"u"&&localStorage.setItem(J.WCM_VERSION,"2.7.0")}catch{console.info("Unable to set Web3Modal version in storage")}},getWalletRouterData(){var t;const e=(t=Ge.state.data)==null?void 0:t.Wallet;if(!e)throw new Error('Missing "Wallet" view data');return e}},zj=typeof location<"u"&&(location.hostname.includes("localhost")||location.protocol.includes("https")),Yt=mn({enabled:zj,userSessionId:"",events:[],connectedWalletId:void 0}),hy={state:Yt,subscribe(t){return ss(Yt.events,()=>t(qj(Yt.events[Yt.events.length-1])))},initialize(){Yt.enabled&&typeof(crypto==null?void 0:crypto.randomUUID)<"u"&&(Yt.userSessionId=crypto.randomUUID())},setConnectedWalletId(t){Yt.connectedWalletId=t},click(t){if(Yt.enabled){const e={type:"CLICK",name:t.name,userSessionId:Yt.userSessionId,timestamp:Date.now(),data:t};Yt.events.push(e)}},track(t){if(Yt.enabled){const e={type:"TRACK",name:t.name,userSessionId:Yt.userSessionId,timestamp:Date.now(),data:t};Yt.events.push(e)}},view(t){if(Yt.enabled){const e={type:"VIEW",name:t.name,userSessionId:Yt.userSessionId,timestamp:Date.now(),data:t};Yt.events.push(e)}}},Ei=mn({chains:void 0,walletConnectUri:void 0,isAuth:!1,isCustomDesktop:!1,isCustomMobile:!1,isDataLoaded:!1,isUiLoaded:!1}),vt={state:Ei,subscribe(t){return ss(Ei,()=>t(Ei))},setChains(t){Ei.chains=t},setWalletConnectUri(t){Ei.walletConnectUri=t},setIsCustomDesktop(t){Ei.isCustomDesktop=t},setIsCustomMobile(t){Ei.isCustomMobile=t},setIsDataLoaded(t){Ei.isDataLoaded=t},setIsUiLoaded(t){Ei.isUiLoaded=t},setIsAuth(t){Ei.isAuth=t}},au=mn({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}),_r={state:au,subscribe(t){return ss(au,()=>t(au))},setConfig(t){var e,r;hy.initialize(),vt.setChains(t.chains),vt.setIsAuth(!!t.enableAuthMode),vt.setIsCustomMobile(!!((e=t.mobileWallets)!=null&&e.length)),vt.setIsCustomDesktop(!!((r=t.desktopWallets)!=null&&r.length)),J.setModalVersionInStorage(),Object.assign(au,t)}};var kj=Object.defineProperty,dy=Object.getOwnPropertySymbols,Hj=Object.prototype.hasOwnProperty,Wj=Object.prototype.propertyIsEnumerable,fy=(t,e,r)=>e in t?kj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Vj=(t,e)=>{for(var r in e||(e={}))Hj.call(e,r)&&fy(t,r,e[r]);if(dy)for(var r of dy(e))Wj.call(e,r)&&fy(t,r,e[r]);return t};const Lf="https://explorer-api.walletconnect.com",Ff="wcm",Uf="js-2.7.0";async function cu(t,e){const r=Vj({sdkType:Ff,sdkVersion:Uf},e),i=new URL(t,Lf);return i.searchParams.append("projectId",_r.state.projectId),Object.entries(r).forEach(([s,o])=>{o&&i.searchParams.append(s,String(o))}),(await fetch(i)).json()}const os={async getDesktopListings(t){return cu("/w3m/v1/getDesktopListings",t)},async getMobileListings(t){return cu("/w3m/v1/getMobileListings",t)},async getInjectedListings(t){return cu("/w3m/v1/getInjectedListings",t)},async getAllListings(t){return cu("/w3m/v1/getAllListings",t)},getWalletImageUrl(t){return`${Lf}/w3m/v1/getWalletImage/${t}?projectId=${_r.state.projectId}&sdkType=${Ff}&sdkVersion=${Uf}`},getAssetImageUrl(t){return`${Lf}/w3m/v1/getAssetImage/${t}?projectId=${_r.state.projectId}&sdkType=${Ff}&sdkVersion=${Uf}`}};var Kj=Object.defineProperty,py=Object.getOwnPropertySymbols,Gj=Object.prototype.hasOwnProperty,Zj=Object.prototype.propertyIsEnumerable,gy=(t,e,r)=>e in t?Kj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yj=(t,e)=>{for(var r in e||(e={}))Gj.call(e,r)&&gy(t,r,e[r]);if(py)for(var r of py(e))Zj.call(e,r)&&gy(t,r,e[r]);return t};const by=J.isMobile(),$i=mn({wallets:{listings:[],total:0,page:1},search:{listings:[],total:0,page:1},recomendedWallets:[]}),dr={state:$i,async getRecomendedWallets(){const{explorerRecommendedWalletIds:t,explorerExcludedWalletIds:e}=_r.state;if(t==="NONE"||e==="ALL"&&!t)return $i.recomendedWallets;if(J.isArray(t)){const i={recommendedIds:t.join(",")},{listings:n}=await os.getAllListings(i),s=Object.values(n);s.sort((o,a)=>{const c=t.indexOf(o.id),l=t.indexOf(a.id);return c-l}),$i.recomendedWallets=s}else{const{chains:r,isAuth:i}=vt.state,n=r?.join(","),s=J.isArray(e),o={page:1,sdks:i?"auth_v1":void 0,entries:J.RECOMMENDED_WALLET_AMOUNT,chains:n,version:2,excludedIds:s?e.join(","):void 0},{listings:a}=by?await os.getMobileListings(o):await os.getDesktopListings(o);$i.recomendedWallets=Object.values(a)}return $i.recomendedWallets},async getWallets(t){const e=Yj({},t),{explorerRecommendedWalletIds:r,explorerExcludedWalletIds:i}=_r.state,{recomendedWallets:n}=$i;if(i==="ALL")return $i.wallets;n.length?e.excludedIds=n.map(d=>d.id).join(","):J.isArray(r)&&(e.excludedIds=r.join(",")),J.isArray(i)&&(e.excludedIds=[e.excludedIds,i].filter(Boolean).join(",")),vt.state.isAuth&&(e.sdks="auth_v1");const{page:s,search:o}=t,{listings:a,total:c}=by?await os.getMobileListings(e):await os.getDesktopListings(e),l=Object.values(a),u=o?"search":"wallets";return $i[u]={listings:[...$i[u].listings,...l],total:c,page:s??1},{listings:l,total:c}},getWalletImageUrl(t){return os.getWalletImageUrl(t)},getAssetImageUrl(t){return os.getAssetImageUrl(t)},resetSearch(){$i.search={listings:[],total:0,page:1}}},Do=mn({open:!1}),as={state:Do,subscribe(t){return ss(Do,()=>t(Do))},async open(t){return new Promise(e=>{const{isUiLoaded:r,isDataLoaded:i}=vt.state;if(J.removeWalletConnectDeepLink(),vt.setWalletConnectUri(t?.uri),vt.setChains(t?.chains),Ge.reset("ConnectWallet"),r&&i)Do.open=!0,e();else{const n=setInterval(()=>{const s=vt.state;s.isUiLoaded&&s.isDataLoaded&&(clearInterval(n),Do.open=!0,e())},200)}})},close(){Do.open=!1}};var Jj=Object.defineProperty,my=Object.getOwnPropertySymbols,Qj=Object.prototype.hasOwnProperty,Xj=Object.prototype.propertyIsEnumerable,vy=(t,e,r)=>e in t?Jj(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,eq=(t,e)=>{for(var r in e||(e={}))Qj.call(e,r)&&vy(t,r,e[r]);if(my)for(var r of my(e))Xj.call(e,r)&&vy(t,r,e[r]);return t};function tq(){return typeof matchMedia<"u"&&matchMedia("(prefers-color-scheme: dark)").matches}const Wa=mn({themeMode:tq()?"dark":"light"}),vn={state:Wa,subscribe(t){return ss(Wa,()=>t(Wa))},setThemeConfig(t){const{themeMode:e,themeVariables:r}=t;e&&(Wa.themeMode=e),r&&(Wa.themeVariables=eq({},r))}},cs=mn({open:!1,message:"",variant:"success"}),yn={state:cs,subscribe(t){return ss(cs,()=>t(cs))},openToast(t,e){cs.open=!0,cs.message=t,cs.variant=e},closeToast(){cs.open=!1}};class rq{constructor(e){this.openModal=as.open,this.closeModal=as.close,this.subscribeModal=as.subscribe,this.setTheme=vn.setThemeConfig,vn.setThemeConfig(e),_r.setConfig(e),this.initUi()}async initUi(){if(typeof window<"u"){await Promise.resolve().then(function(){return dW});const e=document.createElement("wcm-modal");document.body.insertAdjacentElement("beforeend",e),vt.setIsUiLoaded(!0)}}}var iq=Object.freeze({__proto__:null,WalletConnectModal:rq});/**
41
41
  * @license
42
42
  * Copyright 2019 Google LLC