@walletconnect/ethereum-provider 2.16.0 → 2.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +5 -5
package/dist/index.umd.js
CHANGED
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
41
41
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
42
42
|
PERFORMANCE OF THIS SOFTWARE.
|
|
43
|
-
***************************************************************************** */var Gd=function(t,e){return Gd=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])},Gd(t,e)};function TC(t,e){Gd(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Yd=function(){return Yd=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},Yd.apply(this,arguments)};function LC(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 BC(t,e,r,i){var n=arguments.length,s=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,i);else for(var u=t.length-1;u>=0;u--)(a=t[u])&&(s=(n<3?a(s):n>3?a(e,r,s):a(e,r))||s);return n>3&&s&&Object.defineProperty(e,r,s),s}function FC(t,e){return function(r,i){e(r,i,t)}}function kC(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function UC(t,e,r,i){function n(s){return s instanceof r?s:new r(function(a){a(s)})}return new(r||(r=Promise))(function(s,a){function u(b){try{l(i.next(b))}catch(w){a(w)}}function h(b){try{l(i.throw(b))}catch(w){a(w)}}function l(b){b.done?s(b.value):n(b.value).then(u,h)}l((i=i.apply(t,e||[])).next())})}function jC(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,a;return a={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function u(l){return function(b){return h([l,b])}}function h(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(b){l=[6,b],n=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function qC(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function zC(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Jd(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 Wb(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),n,s=[],a;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(u){a={error:u}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(a)throw a.error}}return s}function HC(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Wb(arguments[e]));return t}function KC(){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],a=0,u=s.length;a<u;a++,n++)i[n]=s[a];return i}function Ru(t){return this instanceof Ru?(this.v=t,this):new Ru(t)}function WC(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),n,s=[];return n={},a("next"),a("throw"),a("return"),n[Symbol.asyncIterator]=function(){return this},n;function a(I){i[I]&&(n[I]=function(S){return new Promise(function(D,T){s.push([I,S,D,T])>1||u(I,S)})})}function u(I,S){try{h(i[I](S))}catch(D){w(s[0][3],D)}}function h(I){I.value instanceof Ru?Promise.resolve(I.value.v).then(l,b):w(s[0][2],I)}function l(I){u("next",I)}function b(I){u("throw",I)}function w(I,S){I(S),s.shift(),s.length&&u(s[0][0],s[0][1])}}function VC(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(a){return(r=!r)?{value:Ru(t[n](a)),done:n==="return"}:s?s(a):a}:s}}function GC(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 Jd=="function"?Jd(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(a){return new Promise(function(u,h){a=t[s](a),n(u,h,a.done,a.value)})}}function n(s,a,u,h){Promise.resolve(h).then(function(l){s({value:l,done:u})},a)}}function YC(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function JC(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 QC(t){return t&&t.__esModule?t:{default:t}}function ZC(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function XC(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 eD=Object.freeze({__proto__:null,__extends:TC,get __assign(){return Yd},__rest:LC,__decorate:BC,__param:FC,__metadata:kC,__awaiter:UC,__generator:jC,__createBinding:qC,__exportStar:zC,__values:Jd,__read:Wb,__spread:HC,__spreadArrays:KC,__await:Ru,__asyncGenerator:WC,__asyncDelegator:VC,__asyncValues:GC,__makeTemplateObject:YC,__importStar:JC,__importDefault:QC,__classPrivateFieldGet:ZC,__classPrivateFieldSet:XC}),tD=m0(eD),Ts={},Vb;function rD(){if(Vb)return Ts;Vb=1,Object.defineProperty(Ts,"__esModule",{value:!0}),Ts.isBrowserCryptoAvailable=Ts.getSubtleCrypto=Ts.getBrowerCrypto=void 0;function t(){return Vr?.crypto||Vr?.msCrypto||{}}Ts.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}Ts.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Ts.isBrowserCryptoAvailable=r,Ts}var Ls={},Gb;function iD(){if(Gb)return Ls;Gb=1,Object.defineProperty(Ls,"__esModule",{value:!0}),Ls.isBrowser=Ls.isNode=Ls.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ls.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Ls.isNode=e;function r(){return!t()&&!e()}return Ls.isBrowser=r,Ls}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=tD;e.__exportStar(rD(),t),e.__exportStar(iD(),t)})(Kb);function co(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Jo(t=6){return BigInt(co(t))}function Qo(t,e,r){return{id:r||co(),jsonrpc:"2.0",method:t,params:e}}function Oh(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Ph(t,e,r){return{id:t,jsonrpc:"2.0",error:nD(e,r)}}function nD(t,e){return typeof t>"u"?zb(jb):(typeof t=="string"&&(t=Object.assign(Object.assign({},zb(Vd)),{message:t})),typeof e<"u"&&(t.data=e),RC(t.code)&&(t=NC(t.code)),t)}class sD{}class oD extends sD{constructor(){super()}}class aD extends oD{constructor(e){super()}}const cD="^https?:",uD="^wss?:";function fD(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Yb(t,e){const r=fD(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Jb(t){return Yb(t,cD)}function Qb(t){return Yb(t,uD)}function hD(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Zb(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Qd(t){return Zb(t)&&"method"in t}function $h(t){return Zb(t)&&(fs(t)||rn(t))}function fs(t){return"result"in t}function rn(t){return"error"in t}class xn extends aD{constructor(e){super(e),this.events=new Ur.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(Qo(e.method,e.params||[],e.id||Jo().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=>{rn(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),$h(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 lD=()=>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"),dD=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Xb=t=>t.split("?")[0],e3=10,pD=lD();class gD{constructor(e){if(this.url=e,this.events=new Ur.exports.EventEmitter,this.registering=!1,!Qb(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(Cs(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Qb(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=new URLSearchParams(e).get("origin"),s=Kb.isReactNative()?{headers:{origin:n}}:{rejectUnauthorized:!hD(e)},a=new pD(e,[],s);dD()?a.onerror=u=>{const h=u;i(this.emitError(h.error))}:a.on("error",u=>{i(this.emitError(u))}),a.onopen=()=>{this.onOpen(a),r(a)}})}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"?jo(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=Ph(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return Hb(e,Xb(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>e3&&this.events.setMaxListeners(e3)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Xb(this.url)}`));return this.events.emit("register_error",r),r}}var Zd={exports:{}};(function(t,e){var r=200,i="__lodash_hash_undefined__",n=1,s=2,a=9007199254740991,u="[object Arguments]",h="[object Array]",l="[object AsyncFunction]",b="[object Boolean]",w="[object Date]",I="[object Error]",S="[object Function]",D="[object GeneratorFunction]",T="[object Map]",j="[object Number]",K="[object Null]",F="[object Object]",W="[object Promise]",R="[object Proxy]",U="[object RegExp]",H="[object Set]",_="[object String]",B="[object Symbol]",ee="[object Undefined]",ie="[object WeakMap]",L="[object ArrayBuffer]",y="[object DataView]",f="[object Float32Array]",d="[object Float64Array]",v="[object Int8Array]",E="[object Int16Array]",C="[object Int32Array]",O="[object Uint8Array]",M="[object Uint8ClampedArray]",g="[object Uint16Array]",m="[object Uint32Array]",N=/[\\^$.*+?()[\]{}|]/g,X=/^\[object .+?Constructor\]$/,ae=/^(?:0|[1-9]\d*)$/,P={};P[f]=P[d]=P[v]=P[E]=P[C]=P[O]=P[M]=P[g]=P[m]=!0,P[u]=P[h]=P[L]=P[b]=P[y]=P[w]=P[I]=P[S]=P[T]=P[j]=P[F]=P[U]=P[H]=P[_]=P[ie]=!1;var te=typeof Vr=="object"&&Vr&&Vr.Object===Object&&Vr,z=typeof self=="object"&&self&&self.Object===Object&&self,G=te||z||Function("return this")(),Y=e&&!e.nodeType&&e,A=Y&&!0&&t&&!t.nodeType&&t,V=A&&A.exports===Y,oe=V&&te.process,ue=function(){try{return oe&&oe.binding&&oe.binding("util")}catch{}}(),he=ue&&ue.isTypedArray;function ye(J,re){for(var pe=-1,Ue=J==null?0:J.length,er=0,bt=[];++pe<Ue;){var ar=J[pe];re(ar,pe,J)&&(bt[er++]=ar)}return bt}function we(J,re){for(var pe=-1,Ue=re.length,er=J.length;++pe<Ue;)J[er+pe]=re[pe];return J}function Re(J,re){for(var pe=-1,Ue=J==null?0:J.length;++pe<Ue;)if(re(J[pe],pe,J))return!0;return!1}function Xe(J,re){for(var pe=-1,Ue=Array(J);++pe<J;)Ue[pe]=re(pe);return Ue}function Oe(J){return function(re){return J(re)}}function Ne(J,re){return J.has(re)}function Me(J,re){return J?.[re]}function be(J){var re=-1,pe=Array(J.size);return J.forEach(function(Ue,er){pe[++re]=[er,Ue]}),pe}function Pe(J,re){return function(pe){return J(re(pe))}}function Te(J){var re=-1,pe=Array(J.size);return J.forEach(function(Ue){pe[++re]=Ue}),pe}var ve=Array.prototype,$e=Function.prototype,Se=Object.prototype,me=G["__core-js_shared__"],ke=$e.toString,Ce=Se.hasOwnProperty,_e=function(){var J=/[^.]+$/.exec(me&&me.keys&&me.keys.IE_PROTO||"");return J?"Symbol(src)_1."+J:""}(),Ke=Se.toString,Ve=RegExp("^"+ke.call(Ce).replace(N,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ae=V?G.Buffer:void 0,We=G.Symbol,pt=G.Uint8Array,Ge=Se.propertyIsEnumerable,It=ve.splice,gt=We?We.toStringTag:void 0,Je=Object.getOwnPropertySymbols,Ot=Ae?Ae.isBuffer:void 0,Tt=Pe(Object.keys,Object),Le=qi(G,"DataView"),et=qi(G,"Map"),it=qi(G,"Promise"),Be=qi(G,"Set"),rt=qi(G,"WeakMap"),tt=qi(Object,"create"),je=js(Le),ht=js(et),nt=js(it),qe=js(Be),st=js(rt),at=We?We.prototype:void 0,Fe=at?at.valueOf:void 0;function Ze(J){var re=-1,pe=J==null?0:J.length;for(this.clear();++re<pe;){var Ue=J[re];this.set(Ue[0],Ue[1])}}function lt(){this.__data__=tt?tt(null):{},this.size=0}function ze(J){var re=this.has(J)&&delete this.__data__[J];return this.size-=re?1:0,re}function jt(J){var re=this.__data__;if(tt){var pe=re[J];return pe===i?void 0:pe}return Ce.call(re,J)?re[J]:void 0}function qt(J){var re=this.__data__;return tt?re[J]!==void 0:Ce.call(re,J)}function ct(J,re){var pe=this.__data__;return this.size+=this.has(J)?0:1,pe[J]=tt&&re===void 0?i:re,this}Ze.prototype.clear=lt,Ze.prototype.delete=ze,Ze.prototype.get=jt,Ze.prototype.has=qt,Ze.prototype.set=ct;function _t(J){var re=-1,pe=J==null?0:J.length;for(this.clear();++re<pe;){var Ue=J[re];this.set(Ue[0],Ue[1])}}function Zr(){this.__data__=[],this.size=0}function Xr(J){var re=this.__data__,pe=ma(re,J);if(pe<0)return!1;var Ue=re.length-1;return pe==Ue?re.pop():It.call(re,pe,1),--this.size,!0}function ei(J){var re=this.__data__,pe=ma(re,J);return pe<0?void 0:re[pe][1]}function ti(J){return ma(this.__data__,J)>-1}function ri(J,re){var pe=this.__data__,Ue=ma(pe,J);return Ue<0?(++this.size,pe.push([J,re])):pe[Ue][1]=re,this}_t.prototype.clear=Zr,_t.prototype.delete=Xr,_t.prototype.get=ei,_t.prototype.has=ti,_t.prototype.set=ri;function vr(J){var re=-1,pe=J==null?0:J.length;for(this.clear();++re<pe;){var Ue=J[re];this.set(Ue[0],Ue[1])}}function Ii(){this.size=0,this.__data__={hash:new Ze,map:new(et||_t),string:new Ze}}function On(J){var re=Eo(this,J).delete(J);return this.size-=re?1:0,re}function Mi(J){return Eo(this,J).get(J)}function Pn(J){return Eo(this,J).has(J)}function $n(J,re){var pe=Eo(this,J),Ue=pe.size;return pe.set(J,re),this.size+=pe.size==Ue?0:1,this}vr.prototype.clear=Ii,vr.prototype.delete=On,vr.prototype.get=Mi,vr.prototype.has=Pn,vr.prototype.set=$n;function Ci(J){var re=-1,pe=J==null?0:J.length;for(this.__data__=new vr;++re<pe;)this.add(J[re])}function an(J){return this.__data__.set(J,i),this}function cn(J){return this.__data__.has(J)}Ci.prototype.add=Ci.prototype.push=an,Ci.prototype.has=cn;function Cr(J){var re=this.__data__=new _t(J);this.size=re.size}function Rn(){this.__data__=new _t,this.size=0}function Nn(J){var re=this.__data__,pe=re.delete(J);return this.size=re.size,pe}function Tn(J){return this.__data__.get(J)}function va(J){return this.__data__.has(J)}function gl(J,re){var pe=this.__data__;if(pe instanceof _t){var Ue=pe.__data__;if(!et||Ue.length<r-1)return Ue.push([J,re]),this.size=++pe.size,this;pe=this.__data__=new vr(Ue)}return pe.set(J,re),this.size=pe.size,this}Cr.prototype.clear=Rn,Cr.prototype.delete=Nn,Cr.prototype.get=Tn,Cr.prototype.has=va,Cr.prototype.set=gl;function vl(J,re){var pe=Nc(J),Ue=!pe&&Cl(J),er=!pe&&!Ue&&uf(J),bt=!pe&&!Ue&&!er&&Pl(J),ar=pe||Ue||er||bt,xr=ar?Xe(J.length,String):[],Ft=xr.length;for(var tr in J)(re||Ce.call(J,tr))&&!(ar&&(tr=="length"||er&&(tr=="offset"||tr=="parent")||bt&&(tr=="buffer"||tr=="byteLength"||tr=="byteOffset")||Al(tr,Ft)))&&xr.push(tr);return xr}function ma(J,re){for(var pe=J.length;pe--;)if(Ml(J[pe][0],re))return pe;return-1}function af(J,re,pe){var Ue=re(J);return Nc(J)?Ue:we(Ue,pe(J))}function ba(J){return J==null?J===void 0?ee:K:gt&> in Object(J)?_l(J):Cp(J)}function cf(J){return wa(J)&&ba(J)==u}function ya(J,re,pe,Ue,er){return J===re?!0:J==null||re==null||!wa(J)&&!wa(re)?J!==J&&re!==re:ml(J,re,pe,Ue,ya,er)}function ml(J,re,pe,Ue,er,bt){var ar=Nc(J),xr=Nc(re),Ft=ar?h:ws(J),tr=xr?h:ws(re);Ft=Ft==u?F:Ft,tr=tr==u?F:tr;var _r=Ft==F,Di=tr==F,Sr=Ft==tr;if(Sr&&uf(J)){if(!uf(re))return!1;ar=!0,_r=!1}if(Sr&&!_r)return bt||(bt=new Cr),ar||Pl(J)?$c(J,re,pe,Ue,er,bt):Mp(J,re,Ft,pe,Ue,er,bt);if(!(pe&n)){var cr=_r&&Ce.call(J,"__wrapped__"),di=Di&&Ce.call(re,"__wrapped__");if(cr||di){var Ln=cr?J.value():J,un=di?re.value():re;return bt||(bt=new Cr),er(Ln,un,pe,Ue,bt)}}return Sr?(bt||(bt=new Cr),wl(J,re,pe,Ue,er,bt)):!1}function Ip(J){if(!Ol(J)||Sl(J))return!1;var re=Tc(J)?Ve:X;return re.test(js(J))}function bl(J){return wa(J)&&Dl(J.length)&&!!P[ba(J)]}function yl(J){if(!Il(J))return Tt(J);var re=[];for(var pe in Object(J))Ce.call(J,pe)&&pe!="constructor"&&re.push(pe);return re}function $c(J,re,pe,Ue,er,bt){var ar=pe&n,xr=J.length,Ft=re.length;if(xr!=Ft&&!(ar&&Ft>xr))return!1;var tr=bt.get(J);if(tr&&bt.get(re))return tr==re;var _r=-1,Di=!0,Sr=pe&s?new Ci:void 0;for(bt.set(J,re),bt.set(re,J);++_r<xr;){var cr=J[_r],di=re[_r];if(Ue)var Ln=ar?Ue(di,cr,_r,re,J,bt):Ue(cr,di,_r,J,re,bt);if(Ln!==void 0){if(Ln)continue;Di=!1;break}if(Sr){if(!Re(re,function(un,_s){if(!Ne(Sr,_s)&&(cr===un||er(cr,un,pe,Ue,bt)))return Sr.push(_s)})){Di=!1;break}}else if(!(cr===di||er(cr,di,pe,Ue,bt))){Di=!1;break}}return bt.delete(J),bt.delete(re),Di}function Mp(J,re,pe,Ue,er,bt,ar){switch(pe){case y:if(J.byteLength!=re.byteLength||J.byteOffset!=re.byteOffset)return!1;J=J.buffer,re=re.buffer;case L:return!(J.byteLength!=re.byteLength||!bt(new pt(J),new pt(re)));case b:case w:case j:return Ml(+J,+re);case I:return J.name==re.name&&J.message==re.message;case U:case _:return J==re+"";case T:var xr=be;case H:var Ft=Ue&n;if(xr||(xr=Te),J.size!=re.size&&!Ft)return!1;var tr=ar.get(J);if(tr)return tr==re;Ue|=s,ar.set(J,re);var _r=$c(xr(J),xr(re),Ue,er,bt,ar);return ar.delete(J),_r;case B:if(Fe)return Fe.call(J)==Fe.call(re)}return!1}function wl(J,re,pe,Ue,er,bt){var ar=pe&n,xr=Rc(J),Ft=xr.length,tr=Rc(re),_r=tr.length;if(Ft!=_r&&!ar)return!1;for(var Di=Ft;Di--;){var Sr=xr[Di];if(!(ar?Sr in re:Ce.call(re,Sr)))return!1}var cr=bt.get(J);if(cr&&bt.get(re))return cr==re;var di=!0;bt.set(J,re),bt.set(re,J);for(var Ln=ar;++Di<Ft;){Sr=xr[Di];var un=J[Sr],_s=re[Sr];if(Ue)var ff=ar?Ue(_s,un,Sr,re,J,bt):Ue(un,_s,Sr,J,re,bt);if(!(ff===void 0?un===_s||er(un,_s,pe,Ue,bt):ff)){di=!1;break}Ln||(Ln=Sr=="constructor")}if(di&&!Ln){var _a=J.constructor,Fr=re.constructor;_a!=Fr&&"constructor"in J&&"constructor"in re&&!(typeof _a=="function"&&_a instanceof _a&&typeof Fr=="function"&&Fr instanceof Fr)&&(di=!1)}return bt.delete(J),bt.delete(re),di}function Rc(J){return af(J,Pp,El)}function Eo(J,re){var pe=J.__data__;return xl(re)?pe[typeof re=="string"?"string":"hash"]:pe.map}function qi(J,re){var pe=Me(J,re);return Ip(pe)?pe:void 0}function _l(J){var re=Ce.call(J,gt),pe=J[gt];try{J[gt]=void 0;var Ue=!0}catch{}var er=Ke.call(J);return Ue&&(re?J[gt]=pe:delete J[gt]),er}var El=Je?function(J){return J==null?[]:(J=Object(J),ye(Je(J),function(re){return Ge.call(J,re)}))}:Xt,ws=ba;(Le&&ws(new Le(new ArrayBuffer(1)))!=y||et&&ws(new et)!=T||it&&ws(it.resolve())!=W||Be&&ws(new Be)!=H||rt&&ws(new rt)!=ie)&&(ws=function(J){var re=ba(J),pe=re==F?J.constructor:void 0,Ue=pe?js(pe):"";if(Ue)switch(Ue){case je:return y;case ht:return T;case nt:return W;case qe:return H;case st:return ie}return re});function Al(J,re){return re=re??a,!!re&&(typeof J=="number"||ae.test(J))&&J>-1&&J%1==0&&J<re}function xl(J){var re=typeof J;return re=="string"||re=="number"||re=="symbol"||re=="boolean"?J!=="__proto__":J===null}function Sl(J){return!!_e&&_e in J}function Il(J){var re=J&&J.constructor,pe=typeof re=="function"&&re.prototype||Se;return J===pe}function Cp(J){return Ke.call(J)}function js(J){if(J!=null){try{return ke.call(J)}catch{}try{return J+""}catch{}}return""}function Ml(J,re){return J===re||J!==J&&re!==re}var Cl=cf(function(){return arguments}())?cf:function(J){return wa(J)&&Ce.call(J,"callee")&&!Ge.call(J,"callee")},Nc=Array.isArray;function Dp(J){return J!=null&&Dl(J.length)&&!Tc(J)}var uf=Ot||Qt;function Op(J,re){return ya(J,re)}function Tc(J){if(!Ol(J))return!1;var re=ba(J);return re==S||re==D||re==l||re==R}function Dl(J){return typeof J=="number"&&J>-1&&J%1==0&&J<=a}function Ol(J){var re=typeof J;return J!=null&&(re=="object"||re=="function")}function wa(J){return J!=null&&typeof J=="object"}var Pl=he?Oe(he):bl;function Pp(J){return Dp(J)?vl(J):yl(J)}function Xt(){return[]}function Qt(){return!1}t.exports=Op})(Zd,Zd.exports);var vD=Zd.exports,mD=Object.defineProperty,t3=Object.getOwnPropertySymbols,bD=Object.prototype.hasOwnProperty,yD=Object.prototype.propertyIsEnumerable,r3=(t,e,r)=>e in t?mD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fi=(t,e)=>{for(var r in e||(e={}))bD.call(e,r)&&r3(t,r,e[r]);if(t3)for(var r of t3(e))yD.call(e,r)&&r3(t,r,e[r]);return t};function wD(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),a=s.charCodeAt(0);if(r[a]!==255)throw new TypeError(s+" is ambiguous");r[a]=n}var u=t.length,h=t.charAt(0),l=Math.log(u)/Math.log(256),b=Math.log(256)/Math.log(u);function w(D){if(D instanceof Uint8Array||(ArrayBuffer.isView(D)?D=new Uint8Array(D.buffer,D.byteOffset,D.byteLength):Array.isArray(D)&&(D=Uint8Array.from(D))),!(D instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(D.length===0)return"";for(var T=0,j=0,K=0,F=D.length;K!==F&&D[K]===0;)K++,T++;for(var W=(F-K)*b+1>>>0,R=new Uint8Array(W);K!==F;){for(var U=D[K],H=0,_=W-1;(U!==0||H<j)&&_!==-1;_--,H++)U+=256*R[_]>>>0,R[_]=U%u>>>0,U=U/u>>>0;if(U!==0)throw new Error("Non-zero carry");j=H,K++}for(var B=W-j;B!==W&&R[B]===0;)B++;for(var ee=h.repeat(T);B<W;++B)ee+=t.charAt(R[B]);return ee}function I(D){if(typeof D!="string")throw new TypeError("Expected String");if(D.length===0)return new Uint8Array;var T=0;if(D[T]!==" "){for(var j=0,K=0;D[T]===h;)j++,T++;for(var F=(D.length-T)*l+1>>>0,W=new Uint8Array(F);D[T];){var R=r[D.charCodeAt(T)];if(R===255)return;for(var U=0,H=F-1;(R!==0||U<K)&&H!==-1;H--,U++)R+=u*W[H]>>>0,W[H]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");K=U,T++}if(D[T]!==" "){for(var _=F-K;_!==F&&W[_]===0;)_++;for(var B=new Uint8Array(j+(F-_)),ee=j;_!==F;)B[ee++]=W[_++];return B}}}function S(D){var T=I(D);if(T)return T;throw new Error(`Non-${e} character`)}return{encode:w,decodeUnsafe:I,decode:S}}var _D=wD,ED=_D;const i3=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")},AD=t=>new TextEncoder().encode(t),xD=t=>new TextDecoder().decode(t);class SD{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 ID{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 n3(this,e)}}class MD{constructor(e){this.decoders=e}or(e){return n3(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 n3=(t,e)=>new MD(fi(fi({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class CD{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new SD(e,r,i),this.decoder=new ID(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Rh=({name:t,prefix:e,encode:r,decode:i})=>new CD(t,e,r,i),Nu=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=ED(r,e);return Rh({prefix:t,name:e,encode:i,decode:s=>i3(n(s))})},DD=(t,e,r,i)=>{const n={};for(let b=0;b<e.length;++b)n[e[b]]=b;let s=t.length;for(;t[s-1]==="=";)--s;const a=new Uint8Array(s*r/8|0);let u=0,h=0,l=0;for(let b=0;b<s;++b){const w=n[t[b]];if(w===void 0)throw new SyntaxError(`Non-${i} character`);h=h<<r|w,u+=r,u>=8&&(u-=8,a[l++]=255&h>>u)}if(u>=r||255&h<<8-u)throw new SyntaxError("Unexpected end of data");return a},OD=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",a=0,u=0;for(let h=0;h<t.length;++h)for(u=u<<8|t[h],a+=8;a>r;)a-=r,s+=e[n&u>>a];if(a&&(s+=e[n&u<<r-a]),i)for(;s.length*r&7;)s+="=";return s},Kr=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Rh({prefix:e,name:t,encode(n){return OD(n,i,r)},decode(n){return DD(n,i,r,t)}}),PD=Rh({prefix:"\0",name:"identity",encode:t=>xD(t),decode:t=>AD(t)});var $D=Object.freeze({__proto__:null,identity:PD});const RD=Kr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ND=Object.freeze({__proto__:null,base2:RD});const TD=Kr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var LD=Object.freeze({__proto__:null,base8:TD});const BD=Nu({prefix:"9",name:"base10",alphabet:"0123456789"});var FD=Object.freeze({__proto__:null,base10:BD});const kD=Kr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),UD=Kr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var jD=Object.freeze({__proto__:null,base16:kD,base16upper:UD});const qD=Kr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),zD=Kr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),HD=Kr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),KD=Kr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),WD=Kr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),VD=Kr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),GD=Kr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),YD=Kr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),JD=Kr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var QD=Object.freeze({__proto__:null,base32:qD,base32upper:zD,base32pad:HD,base32padupper:KD,base32hex:WD,base32hexupper:VD,base32hexpad:GD,base32hexpadupper:YD,base32z:JD});const ZD=Nu({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),XD=Nu({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var eO=Object.freeze({__proto__:null,base36:ZD,base36upper:XD});const tO=Nu({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),rO=Nu({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var iO=Object.freeze({__proto__:null,base58btc:tO,base58flickr:rO});const nO=Kr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),sO=Kr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),oO=Kr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),aO=Kr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var cO=Object.freeze({__proto__:null,base64:nO,base64pad:sO,base64url:oO,base64urlpad:aO});const s3=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}"),uO=s3.reduce((t,e,r)=>(t[r]=e,t),[]),fO=s3.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function hO(t){return t.reduce((e,r)=>(e+=uO[r],e),"")}function lO(t){const e=[];for(const r of t){const i=fO[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const dO=Rh({prefix:"\u{1F680}",name:"base256emoji",encode:hO,decode:lO});var pO=Object.freeze({__proto__:null,base256emoji:dO}),gO=a3,o3=128,vO=127,mO=~vO,bO=Math.pow(2,31);function a3(t,e,r){e=e||[],r=r||0;for(var i=r;t>=bO;)e[r++]=t&255|o3,t/=128;for(;t&mO;)e[r++]=t&255|o3,t>>>=7;return e[r]=t|0,a3.bytes=r-i+1,e}var yO=Xd,wO=128,c3=127;function Xd(t,i){var r=0,i=i||0,n=0,s=i,a,u=t.length;do{if(s>=u)throw Xd.bytes=0,new RangeError("Could not decode varint");a=t[s++],r+=n<28?(a&c3)<<n:(a&c3)*Math.pow(2,n),n+=7}while(a>=wO);return Xd.bytes=s-i,r}var _O=Math.pow(2,7),EO=Math.pow(2,14),AO=Math.pow(2,21),xO=Math.pow(2,28),SO=Math.pow(2,35),IO=Math.pow(2,42),MO=Math.pow(2,49),CO=Math.pow(2,56),DO=Math.pow(2,63),OO=function(t){return t<_O?1:t<EO?2:t<AO?3:t<xO?4:t<SO?5:t<IO?6:t<MO?7:t<CO?8:t<DO?9:10},PO={encode:gO,decode:yO,encodingLength:OO},u3=PO;const f3=(t,e,r=0)=>(u3.encode(t,e,r),e),h3=t=>u3.encodingLength(t),e1=(t,e)=>{const r=e.byteLength,i=h3(t),n=i+h3(r),s=new Uint8Array(n+r);return f3(t,s,0),f3(r,s,i),s.set(e,n),new $O(t,r,e,s)};class $O{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const l3=({name:t,code:e,encode:r})=>new RO(t,e,r);class RO{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?e1(this.code,r):r.then(i=>e1(this.code,i))}else throw Error("Unknown type, must be binary type")}}const d3=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),NO=l3({name:"sha2-256",code:18,encode:d3("SHA-256")}),TO=l3({name:"sha2-512",code:19,encode:d3("SHA-512")});var LO=Object.freeze({__proto__:null,sha256:NO,sha512:TO});const p3=0,BO="identity",g3=i3;var FO=Object.freeze({__proto__:null,identity:{code:p3,name:BO,encode:g3,digest:t=>e1(p3,g3(t))}});new TextEncoder,new TextDecoder;const v3=fi(fi(fi(fi(fi(fi(fi(fi(fi(fi({},$D),ND),LD),FD),jD),QD),eO),iO),cO),pO);fi(fi({},LO),FO);function kO(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function m3(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const b3=m3("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),t1=m3("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=kO(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),UO=fi({utf8:b3,"utf-8":b3,hex:v3.base16,latin1:t1,ascii:t1,binary:t1},v3);function jO(t,e="utf8"){const r=UO[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}`)}const y3="wc",w3=2,r1="core",hs=`${y3}@2:${r1}:`,qO={name:r1,logger:"error"},zO={database:":memory:"},HO="crypto",_3="client_ed25519_seed",KO=xe.ONE_DAY,WO="keychain",VO="0.3",GO="messages",YO="0.3",JO=xe.SIX_HOURS,QO="publisher",E3="irn",ZO="error",A3="wss://relay.walletconnect.org",XO="relayer",hi={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"},eP="_subscription",nn={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},tP=.1,x3="2.16.0",Zt={link_mode:"link_mode",relay:"relay"},rP="0.3",iP="WALLETCONNECT_CLIENT_ID",S3="WALLETCONNECT_LINK_MODE_APPS",ls={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},nP="subscription",sP="0.3",oP=xe.FIVE_SECONDS*1e3,aP="pairing",cP="0.3",Tu={wc_pairingDelete:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:xe.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:xe.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:0},res:{ttl:xe.ONE_DAY,prompt:!1,tag:0}}},fc={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Sn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},uP="history",fP="0.3",hP="expirer",sn={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},lP="0.3",dP="verify-api",pP="https://verify.walletconnect.com",I3="https://verify.walletconnect.org",Lu=I3,gP=`${Lu}/v3`,vP=[pP,I3],mP="echo",bP="https://echo.walletconnect.com",ds={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"},Bs={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"},In={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"},Zo={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"},Xo={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"},Bu={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"},yP=.1,wP="event-client",_P=86400,EP="https://pulse.walletconnect.com/batch";class AP{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=WO,this.version=VO,this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}},this.has=i=>(this.isInitialized(),this.keychain.has(i)),this.set=async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()},this.get=i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=Ee("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n},this.del=async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()},this.core=e,this.logger=ui(r,this.name)}get context(){return Ai(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,q2(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?z2(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class xP{constructor(e,r,i){this.core=e,this.logger=r,this.name=HO,this.randomSessionIdentifier=Rd(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=n=>(this.isInitialized(),this.keychain.has(n)),this.getClientId=async()=>{this.isInitialized();const n=await this.getClientSeed(),s=L2(n);return T2(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const n=nI();return this.setPrivateKey(n.publicKey,n.privateKey)},this.signJWT=async n=>{this.isInitialized();const s=await this.getClientSeed(),a=L2(s),u=this.randomSessionIdentifier;return await FE(u,n,KO,a)},this.generateSharedKey=(n,s,a)=>{this.isInitialized();const u=this.getPrivateKey(n),h=sI(u,s);return this.setSymKey(h,a)},this.setSymKey=async(n,s)=>{this.isInitialized();const a=s||bh(n);return await this.keychain.set(a,n),a},this.deleteKeyPair=async n=>{this.isInitialized(),await this.keychain.del(n)},this.deleteSymKey=async n=>{this.isInitialized(),await this.keychain.del(n)},this.encode=async(n,s,a)=>{this.isInitialized();const u=fb(a),h=Cs(s);if(lb(u))return aI(h,a?.encoding);if(hb(u)){const I=u.senderPublicKey,S=u.receiverPublicKey;n=await this.generateSharedKey(I,S)}const l=this.getSymKey(n),{type:b,senderPublicKey:w}=u;return oI({type:b,symKey:l,message:h,senderPublicKey:w,encoding:a?.encoding})},this.decode=async(n,s,a)=>{this.isInitialized();const u=fI(s,a);if(lb(u)){const h=uI(s,a?.encoding);return jo(h)}if(hb(u)){const h=u.receiverPublicKey,l=u.senderPublicKey;n=await this.generateSharedKey(h,l)}try{const h=this.getSymKey(n),l=cI({symKey:h,encoded:s,encoding:a?.encoding});return jo(l)}catch(h){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(h)}},this.getPayloadType=(n,s=ao)=>{const a=Au({encoded:n,encoding:s});return Vo(a.type)},this.getPayloadSenderPublicKey=(n,s=ao)=>{const a=Au({encoded:n,encoding:s});return a.senderPublicKey?MC(a.senderPublicKey,ai):void 0},this.core=e,this.logger=ui(r,this.name),this.keychain=i||new AP(this.core,this.logger)}get context(){return Ai(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(_3)}catch{e=Rd(),await this.keychain.set(_3,e)}return jO(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class SP extends pC{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=GO,this.version=YO,this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}},this.set=async(i,n)=>{this.isInitialized();const s=Ns(n);let a=this.messages.get(i);return typeof a>"u"&&(a={}),typeof a[s]<"u"||(a[s]=n,this.messages.set(i,a),await this.persist()),s},this.get=i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n},this.has=(i,n)=>{this.isInitialized();const s=this.get(i),a=Ns(n);return typeof s[a]<"u"},this.del=async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()},this.logger=ui(e,this.name),this.core=r}get context(){return Ai(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,q2(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?z2(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class IP extends gC{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new Ur.exports.EventEmitter,this.name=QO,this.queue=new Map,this.publishTimeout=xe.toMiliseconds(xe.ONE_MINUTE),this.failedPublishTimeout=xe.toMiliseconds(xe.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(i,n,s)=>{var a;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:s}});const u=s?.ttl||JO,h=Nd(s),l=s?.prompt||!1,b=s?.tag||0,w=s?.id||Jo().toString(),I={topic:i,message:n,opts:{ttl:u,relay:h,prompt:l,tag:b,id:w,attestation:s?.attestation}},S=`Failed to publish payload, please try again. id:${w} tag:${b}`,D=Date.now();let T,j=1;try{for(;T===void 0;){if(Date.now()-D>this.publishTimeout)throw new Error(S);this.logger.trace({id:w,attempts:j},`publisher.publish - attempt ${j}`),T=await await Ga(this.rpcPublish(i,n,u,h,l,b,w,s?.attestation).catch(K=>this.logger.warn(K)),this.publishTimeout,S),j++,T||await new Promise(K=>setTimeout(K,this.failedPublishTimeout))}this.relayer.events.emit(hi.publish,I),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{id:w,topic:i,message:n,opts:s}})}catch(K){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(K),(a=s?.internal)!=null&&a.throwOnFailedPublish)throw K;this.queue.set(w,I)}},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.relayer=e,this.logger=ui(r,this.name),this.registerEventListeners()}get context(){return Ai(this.logger)}rpcPublish(e,r,i,n,s,a,u,h){var l,b,w,I;const S={method:xu(n.protocol).publish,params:{topic:e,message:r,ttl:i,prompt:s,tag:a,attestation:h},id:u};return ci((l=S.params)==null?void 0:l.prompt)&&((b=S.params)==null||delete b.prompt),ci((w=S.params)==null?void 0:w.tag)&&((I=S.params)==null||delete I.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:S}),this.relayer.request(S)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:r,message:i,opts:n}=e;await this.publish(r,i,n)})}registerEventListeners(){this.relayer.core.heartbeat.on(ac.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(hi.connection_stalled);return}this.checkQueue()}),this.relayer.on(hi.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class MP{constructor(){this.map=new Map,this.set=(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const 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)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var CP=Object.defineProperty,DP=Object.defineProperties,OP=Object.getOwnPropertyDescriptors,M3=Object.getOwnPropertySymbols,PP=Object.prototype.hasOwnProperty,$P=Object.prototype.propertyIsEnumerable,C3=(t,e,r)=>e in t?CP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fu=(t,e)=>{for(var r in e||(e={}))PP.call(e,r)&&C3(t,r,e[r]);if(M3)for(var r of M3(e))$P.call(e,r)&&C3(t,r,e[r]);return t},i1=(t,e)=>DP(t,OP(e));class RP extends bC{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new MP,this.events=new Ur.exports.EventEmitter,this.name=nP,this.version=sP,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=hs,this.subscribeTimeout=xe.toMiliseconds(xe.ONE_MINUTE),this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.pendingBatchMessages=[],this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId(),await this.restore()),this.initialized=!0},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=Nd(n),a={topic:i,relay:s,transportType:n?.transportType};this.pending.set(i,a);const u=await this.rpcSubscribe(i,s,n?.transportType);return typeof u=="string"&&(this.onSubscribe(u,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}})),u}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(i,n)=>{await this.restartToComplete(),this.isInitialized(),typeof n?.id<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)},this.isSubscribed=async i=>{if(this.topics.includes(i))return!0;const n=`${this.pendingSubscriptionWatchLabel}_${i}`;return await new Promise((s,a)=>{const u=new xe.Watch;u.start(n);const h=setInterval(()=>{!this.pending.has(i)&&this.topics.includes(i)&&(clearInterval(h),u.stop(n),s(!0)),u.elapsed(n)>=oP&&(clearInterval(h),u.stop(n),a(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=ui(r,this.name),this.clientId=""}get context(){return Ai(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}onEnable(){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=Nd(i);await this.rpcUnsubscribe(e,r,n);const s=Gt("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=Zt.relay){i===Zt.relay&&await this.restartToComplete();const n={method:xu(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{const s=Ns(e+this.clientId);return i===Zt.link_mode?(setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(a=>this.logger.warn(a))},xe.toMiliseconds(xe.ONE_SECOND)),s):await await Ga(this.relayer.request(n).catch(a=>this.logger.warn(a)),this.subscribeTimeout)?s:null}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(hi.connection_stalled)}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:xu(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{return await await Ga(this.relayer.request(i).catch(n=>this.logger.warn(n)),this.subscribeTimeout)}catch{this.relayer.events.emit(hi.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:xu(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 Ga(this.relayer.request(i).catch(s=>this.logger.warn(s)),this.subscribeTimeout)}catch{this.relayer.events.emit(hi.connection_stalled)}return n}rpcUnsubscribe(e,r,i){const n={method:xu(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,i1(Fu({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Fu({},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,Fu({},r)),this.topicMap.set(r.topic,e),this.events.emit(ls.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:i}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(ls.deleted,i1(Fu({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(ls.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<e;r++){const i=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchFetchMessages(i),await this.batchSubscribe(i)}}this.events.emit(ls.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;const r=await this.rpcBatchSubscribe(e);as(r)&&this.onBatchSubscribe(r.map((i,n)=>i1(Fu({},e[n]),{id:i})))}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&&(this.pendingBatchMessages=this.pendingBatchMessages.concat(r.messages))}async onConnect(){await this.restart(),this.onEnable()}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||!this.relayer.connected)return;const e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e),this.pendingBatchMessages.length&&(await this.relayer.handleBatchMessageEvents(this.pendingBatchMessages),this.pendingBatchMessages=[])}registerEventListeners(){this.relayer.core.heartbeat.on(ac.pulse,async()=>{await this.checkPending()}),this.events.on(ls.created,async e=>{const r=ls.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(ls.deleted,async e=>{const r=ls.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){!this.relayer.connected&&!this.relayer.connecting&&await this.relayer.transportOpen(),this.restartInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}}var NP=Object.defineProperty,D3=Object.getOwnPropertySymbols,TP=Object.prototype.hasOwnProperty,LP=Object.prototype.propertyIsEnumerable,O3=(t,e,r)=>e in t?NP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,BP=(t,e)=>{for(var r in e||(e={}))TP.call(e,r)&&O3(t,r,e[r]);if(D3)for(var r of D3(e))LP.call(e,r)&&O3(t,r,e[r]);return t};class FP extends vC{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new Ur.exports.EventEmitter,this.name=XO,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","stalled","interrupted"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.heartBeatTimeout=xe.toMiliseconds(xe.THIRTY_SECONDS+xe.ONE_SECOND),this.request=async r=>{var i,n;this.logger.debug("Publishing Request Payload");const s=r.id||Jo().toString();await this.toEstablishConnection();try{const a=this.provider.request(r);this.requestsInFlight.set(s,{promise:a,request:r}),this.logger.trace({id:s,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - attempt to publish...");const u=await new Promise(async(h,l)=>{const b=()=>{l(new Error(`relayer.request - publish interrupted, id: ${s}`))};this.provider.on(nn.disconnect,b);const w=await a;this.provider.off(nn.disconnect,b),h(w)});return this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - published"),u}catch(a){throw this.logger.debug(`Failed to Publish Request: ${s}`),a}finally{this.requestsInFlight.delete(s)}},this.resetPingTimeout=()=>{if(au())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,i,n;(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)}},this.onPayloadHandler=r=>{this.onProviderPayload(r),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.trace("relayer connected"),this.startPingTimeout(),this.events.emit(hi.connect)},this.onDisconnectHandler=()=>{this.logger.trace("relayer disconnected"),this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(hi.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(nn.payload,this.onPayloadHandler),this.provider.on(nn.connect,this.onConnectHandler),this.provider.on(nn.disconnect,this.onDisconnectHandler),this.provider.on(nn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?ui(e.logger,this.name):cs(Dh({level:e.logger||ZO})),this.messages=new SP(this.logger,e.core),this.subscriber=new RP(this,this.logger),this.publisher=new IP(this,this.logger),this.relayUrl=e?.relayUrl||A3,this.projectId=e.projectId,this.bundleId=WE(),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.cached.length>0)try{await this.transportOpen()}catch(e){this.logger.warn(e)}}get context(){return Ai(this.logger)}get connected(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===1}get connecting(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===0}async publish(e,r,i){this.isInitialized(),await this.publisher.publish(e,r,i),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:Zt.relay})}async subscribe(e,r){var i;this.isInitialized(),r?.transportType==="relay"&&await this.toEstablishConnection();let n=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"",s;const a=u=>{u.topic===e&&(this.subscriber.off(ls.created,a),s())};return await Promise.all([new Promise(u=>{s=u,this.subscriber.on(ls.created,a)}),new Promise(async u=>{n=await this.subscriber.subscribe(e,r)||n,u()})]),n}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(){if(!this.hasExperiencedNetworkDisruption&&this.connected&&this.requestsInFlight.size>0)try{await Promise.all(Array.from(this.requestsInFlight.values()).map(e=>e.promise))}catch(e){this.logger.warn(e)}this.hasExperiencedNetworkDisruption||this.connected?await Ga(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),await this.createProvider(),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;try{await new Promise(async(r,i)=>{const n=()=>{this.provider.off(nn.disconnect,n),i(new Error("Connection interrupted while trying to subscribe"))};this.provider.on(nn.disconnect,n),await Ga(this.provider.connect(),xe.toMiliseconds(xe.ONE_MINUTE),`Socket stalled when trying to connect to ${this.relayUrl}`).catch(s=>{i(s)}).finally(()=>{clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0}),this.subscriber.start().catch(s=>{this.logger.error(s),this.onDisconnectHandler()}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){this.logger.error(r);const i=r;if(this.hasExperiencedNetworkDisruption=!0,!this.isConnectionStalled(i.message))throw r}finally{this.connectionAttemptInProgress=!1}}async restartTransport(e){this.connectionAttemptInProgress||(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await xb())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.trace(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const n=Ir(xe.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,s)}this.events.emit(hi.message,e),await this.recordMessageEvent(e)}startPingTimeout(){var e,r,i,n,s;if(au())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.once("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(a){this.logger.warn(a)}}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new xn(new gD(ZE({sdkVersion:x3,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic: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.debug(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;const n=this.messages.has(r,i);return n&&this.logger.debug(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Qd(e)){if(!e.method.endsWith(eP))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:a}=r.data,u={topic:i,message:n,publishedAt:s,transportType:Zt.relay,attestation:a};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(BP({type:"event",event:r.id},u)),this.events.emit(r.id,u),await this.acknowledgePayload(e),await this.onMessageEvent(u)}else $h(e)&&this.events.emit(hi.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(hi.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=Oh(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(nn.payload,this.onPayloadHandler),this.provider.off(nn.connect,this.onConnectHandler),this.provider.off(nn.disconnect,this.onDisconnectHandler),this.provider.off(nn.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await xb();nM(async r=>{e!==r&&(e=r,r?await this.restartTransport().catch(i=>this.logger.error(i)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),this.requestsInFlight.clear(),clearTimeout(this.pingTimeout),this.events.emit(hi.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&(this.reconnectTimeout||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},xe.toMiliseconds(tP))))}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&(this.connectionAttemptInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)}),await this.transportOpen())}}var kP=Object.defineProperty,P3=Object.getOwnPropertySymbols,UP=Object.prototype.hasOwnProperty,jP=Object.prototype.propertyIsEnumerable,$3=(t,e,r)=>e in t?kP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,R3=(t,e)=>{for(var r in e||(e={}))UP.call(e,r)&&$3(t,r,e[r]);if(P3)for(var r of P3(e))jP.call(e,r)&&$3(t,r,e[r]);return t};class ea extends mC{constructor(e,r,i,n=hs,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,this.map=new Map,this.version=rP,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(a=>{this.getKey&&a!==null&&!ci(a)?this.map.set(this.getKey(a),a):TI(a)?this.map.set(a.id,a):LI(a)&&this.map.set(a.topic,a)}),this.cached=[],this.initialized=!0)},this.set=async(a,u)=>{this.isInitialized(),this.map.has(a)?await this.update(a,u):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:a,value:u}),this.map.set(a,u),await this.persist())},this.get=a=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:a}),this.getData(a)),this.getAll=a=>(this.isInitialized(),a?this.values.filter(u=>Object.keys(a).every(h=>vD(u[h],a[h]))):this.values),this.update=async(a,u)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:a,update:u});const h=R3(R3({},this.getData(a)),u);this.map.set(a,h),await this.persist()},this.delete=async(a,u)=>{this.isInitialized(),this.map.has(a)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:a,reason:u}),this.map.delete(a),this.addToRecentlyDeleted(a),await this.persist())},this.logger=ui(r,this.name),this.storagePrefix=n,this.getKey=s}get context(){return Ai(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:n}=Ee("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:i}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class qP{constructor(e,r){this.core=e,this.logger=r,this.name=aP,this.version=cP,this.events=new Ur.exports,this.initialized=!1,this.storagePrefix=hs,this.ignoredPayloadTypes=[Rs],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]},this.create=async i=>{this.isInitialized();const n=Rd(),s=await this.core.crypto.setSymKey(n),a=Ir(xe.FIVE_MINUTES),u={protocol:E3},h={topic:s,expiry:a,relay:u,active:!1},l=SI({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:u,expiryTimestamp:a,methods:i?.methods});return this.core.expirer.set(s,a),await this.pairings.set(s,h),await this.core.relayer.subscribe(s,{transportType:i?.transportType}),{topic:s,uri:l}},this.pair=async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i?.uri,trace:[ds.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:a,relay:u,expiryTimestamp:h,methods:l}=vb(i.uri);n.props.properties.topic=s,n.addTrace(ds.pairing_uri_validation_success),n.addTrace(ds.pairing_uri_not_expired);let b;if(this.pairings.keys.includes(s)){if(b=this.pairings.get(s),n.addTrace(ds.existing_pairing),b.active)throw n.setError(Bs.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(ds.pairing_not_expired)}const w=h||Ir(xe.FIVE_MINUTES),I={topic:s,relay:u,expiry:w,active:!1,methods:l};this.core.expirer.set(s,w),await this.pairings.set(s,I),n.addTrace(ds.store_new_pairing),i.activatePairing&&await this.activate({topic:s}),this.events.emit(fc.create,I),n.addTrace(ds.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(a,s),n.addTrace(ds.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(Bs.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:u})}catch(S){throw n.setError(Bs.subscribe_pairing_topic_failure),S}return n.addTrace(ds.subscribe_pairing_topic_success),I},this.activate=async({topic:i})=>{this.isInitialized();const n=Ir(xe.THIRTY_DAYS);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})},this.ping=async i=>{this.isInitialized(),await this.isValidPing(i);const{topic:n}=i;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:a,resolve:u,reject:h}=zo();this.events.once(Dt("pairing_ping",s),({error:l})=>{l?h(l):u()}),await a()}},this.updateExpiry=async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})},this.updateMetadata=async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),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",Gt("USER_DISCONNECTED")),await this.deletePairing(n))},this.sendRequest=async(i,n,s)=>{const a=Qo(n,s),u=await this.core.crypto.encode(i,a),h=Tu[n].req;return this.core.history.set(i,a),this.core.relayer.publish(i,u,h),a.id},this.sendResult=async(i,n,s)=>{const a=Oh(i,s),u=await this.core.crypto.encode(n,a),h=await this.core.history.get(n,i),l=Tu[h.request.method].res;await this.core.relayer.publish(n,u,l),await this.core.history.resolve(a)},this.sendError=async(i,n,s)=>{const a=Ph(i,s),u=await this.core.crypto.encode(n,a),h=await this.core.history.get(n,i),l=Tu[h.request.method]?Tu[h.request.method].res:Tu.unregistered_method.res;await this.core.relayer.publish(n,u,l),await this.core.history.resolve(a)},this.deletePairing=async(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,Gt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])},this.cleanup=async()=>{const i=this.pairings.getAll().filter(n=>io(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))},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)}},this.onRelayEventResponse=async i=>{const{topic:n,payload:s}=i,a=(await this.core.history.get(n,s.id)).request.method;switch(a){case"wc_pairingPing":return this.onPairingPingResponse(n,s);default:return this.onUnknownRpcMethodResponse(a)}},this.onPairingPingRequest=async(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(fc.ping,{id:s,topic:i})}catch(a){await this.sendError(s,i,a),this.logger.error(a)}},this.onPairingPingResponse=(i,n)=>{const{id:s}=n;setTimeout(()=>{fs(n)?this.events.emit(Dt("pairing_ping",s),{}):rn(n)&&this.events.emit(Dt("pairing_ping",s),{error:n.error})},500)},this.onPairingDeleteRequest=async(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(fc.delete,{id:s,topic:i})}catch(a){await this.sendError(s,i,a),this.logger.error(a)}},this.onUnknownRpcMethodRequest=async(i,n)=>{const{id:s,method:a}=n;try{if(this.registeredMethods.includes(a))return;const u=Gt("WC_METHOD_UNSUPPORTED",a);await this.sendError(s,i,u),this.logger.error(u)}catch(u){await this.sendError(s,i,u),this.logger.error(u)}},this.onUnknownRpcMethodResponse=i=>{this.registeredMethods.includes(i)||this.logger.error(Gt("WC_METHOD_UNSUPPORTED",i))},this.isValidPair=(i,n)=>{var s;if(!_i(i)){const{message:u}=Ee("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(Bs.malformed_pairing_uri),new Error(u)}if(!NI(i.uri)){const{message:u}=Ee("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(Bs.malformed_pairing_uri),new Error(u)}const a=vb(i?.uri);if(!((s=a?.relay)!=null&&s.protocol)){const{message:u}=Ee("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(Bs.malformed_pairing_uri),new Error(u)}if(!(a!=null&&a.symKey)){const{message:u}=Ee("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(Bs.malformed_pairing_uri),new Error(u)}if(a!=null&&a.expiryTimestamp&&xe.toMiliseconds(a?.expiryTimestamp)<Date.now()){n.setError(Bs.pairing_expired);const{message:u}=Ee("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(u)}},this.isValidPing=async i=>{if(!_i(i)){const{message:s}=Ee("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)},this.isValidDisconnect=async i=>{if(!_i(i)){const{message:s}=Ee("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)},this.isValidPairingTopic=async i=>{if(!yr(i,!1)){const{message:n}=Ee("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=Ee("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(io(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=Ee("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}},this.core=e,this.logger=ui(r,this.name),this.pairings=new ea(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Ai(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(hi.message,async e=>{const{topic:r,message:i,transportType:n}=e;if(!this.pairings.keys.includes(r)||n===Zt.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const s=await this.core.crypto.decode(r,i);try{Qd(s)?(this.core.history.set(r,s),this.onRelayEventRequest({topic:r,payload:s})):$h(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id))}catch(a){this.logger.error(a)}})}registerExpirerEvents(){this.core.expirer.on(sn.expired,async e=>{const{topic:r}=K2(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(fc.expire,{topic:r}))})}}class zP extends dC{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new Ur.exports.EventEmitter,this.name=uP,this.version=fP,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(i,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 a={id:n.id,topic:i,request:{method:n.method,params:n.params||null},chainId:s,expiry:Ir(xe.THIRTY_DAYS)};this.records.set(a.id,a),this.persist(),this.events.emit(Sn.created,a)},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=rn(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(Sn.updated,n))},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)),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(Sn.deleted,s)}}),this.persist()},this.exists=async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1),this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.logger=ui(r,this.name)}get context(){return Ai(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:Qo(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:i}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Sn.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Sn.created,e=>{const r=Sn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Sn.updated,e=>{const r=Sn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Sn.deleted,e=>{const r=Sn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(ac.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{xe.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Sn.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class HP extends yC{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new Ur.exports.EventEmitter,this.name=hP,this.version=lP,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}},this.set=(i,n)=>{this.isInitialized();const s=this.formatTarget(i),a={target:s,expiry:n};this.expirations.set(s,a),this.checkExpiry(s,a),this.events.emit(sn.created,{target:s,expiration:a})},this.get=i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)},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(sn.deleted,{target:n,expiration:s})}},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.logger=ui(r,this.name)}get context(){return Ai(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 XE(e);if(typeof e=="number")return eA(e);const{message:r}=Ee("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(sn.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:i}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;xe.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(sn.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(ac.pulse,()=>this.checkExpirations()),this.events.on(sn.created,e=>{const r=sn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(sn.expired,e=>{const r=sn.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(sn.deleted,e=>{const r=sn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}var or={};Object.defineProperty(or,"__esModule",{value:!0}),or.getLocalStorage=or.getLocalStorageOrThrow=or.getCrypto=or.getCryptoOrThrow=or.getLocation=or.getLocationOrThrow=or.getNavigator=or.getNavigatorOrThrow=N3=or.getDocument=or.getDocumentOrThrow=or.getFromWindowOrThrow=or.getFromWindow=void 0;function ta(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}or.getFromWindow=ta;function hc(t){const e=ta(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}or.getFromWindowOrThrow=hc;function KP(){return hc("document")}or.getDocumentOrThrow=KP;function WP(){return ta("document")}var N3=or.getDocument=WP;function VP(){return hc("navigator")}or.getNavigatorOrThrow=VP;function GP(){return ta("navigator")}or.getNavigator=GP;function YP(){return hc("location")}or.getLocationOrThrow=YP;function JP(){return ta("location")}or.getLocation=JP;function QP(){return hc("crypto")}or.getCryptoOrThrow=QP;function ZP(){return ta("crypto")}or.getCrypto=ZP;function XP(){return hc("localStorage")}or.getLocalStorageOrThrow=XP;function e$(){return ta("localStorage")}or.getLocalStorage=e$;class t$ extends wC{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,this.name=dP,this.verifyUrlV3=gP,this.storagePrefix=hs,this.version=w3,this.init=async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&xe.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))},this.register=async n=>{if(!cu()||this.isDevEnv)return;const s=window.location.origin,{id:a,decryptedId:u}=n,h=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${a}&decryptedId=${u}`;try{const l=N3(),b=this.startAbortTimer(xe.ONE_SECOND*5),w=await new Promise((I,S)=>{const D=()=>{window.removeEventListener("message",j),l.body.removeChild(T),S("attestation aborted")};this.abortController.signal.addEventListener("abort",D);const T=l.createElement("iframe");T.src=h,T.style.display="none",T.addEventListener("error",D,{signal:this.abortController.signal});const j=K=>{if(!K.data)return;const F=JSON.parse(K.data);if(F.type==="verify_attestation"){if(od(F.attestation).payload.id!==a)return;clearInterval(b),l.body.removeChild(T),this.abortController.signal.removeEventListener("abort",D),window.removeEventListener("message",j),I(F.attestation===null?"":F.attestation)}};l.body.appendChild(T),window.addEventListener("message",j,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",w),w}catch(l){this.logger.warn(l)}return""},this.resolve=async n=>{if(this.isDevEnv)return"";const{attestationId:s,hash:a,encryptedId:u}=n;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(od(s).payload.id!==u)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(!a)return;const h=this.getVerifyUrl(n?.verifyUrl);return this.fetchAttestation(a,h)},this.fetchAttestation=async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const a=this.startAbortTimer(xe.ONE_SECOND*5),u=await fetch(`${s}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(a),u.status===200?await u.json():void 0},this.getVerifyUrl=n=>{let s=n||Lu;return vP.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Lu}`),s=Lu),s},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(xe.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)}},this.persistPublicKey=async n=>{this.logger.debug("persisting public key to local storage",n),await this.store.setItem(this.storeKey,n),this.publicKey=n},this.removePublicKey=async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async n=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(n,s)}catch(u){this.logger.error(u),this.logger.warn("error validating attestation")}const a=await this.fetchAndPersistPublicKey();try{if(a)return this.validateAttestation(n,a)}catch(u){this.logger.error(u),this.logger.warn("error validating attestation")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const a=await this.fetchPublicKey();a&&(await this.persistPublicKey(a),s(a))});const n=await this.fetchPromise;return this.fetchPromise=void 0,n},this.validateAttestation=(n,s)=>{const a=pI(n,s.publicKey),u={hasExpired:xe.toMiliseconds(a.exp)<Date.now(),payload:a};if(u.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:u.payload.origin,isScam:u.payload.isScam,isVerified:u.payload.isVerified}},this.logger=ui(r,this.name),this.abortController=new AbortController,this.isDevEnv=au()&&process.env.IS_VITEST,this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Ai(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),xe.toMiliseconds(e))}}class r$ extends _C{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.context=mP,this.registerDeviceToken=async i=>{const{clientId:n,token:s,notificationType:a,enableEncrypted:u=!1}=i,h=`${bP}/${this.projectId}/clients`;await fetch(h,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:a,token:s,always_raw:u})})},this.logger=ui(r,this.context)}}var i$=Object.defineProperty,T3=Object.getOwnPropertySymbols,n$=Object.prototype.hasOwnProperty,s$=Object.prototype.propertyIsEnumerable,L3=(t,e,r)=>e in t?i$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ku=(t,e)=>{for(var r in e||(e={}))n$.call(e,r)&&L3(t,r,e[r]);if(T3)for(var r of T3(e))s$.call(e,r)&&L3(t,r,e[r]);return t};class o$ extends EC{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,this.context=wP,this.storagePrefix=hs,this.storageVersion=yP,this.events=new Map,this.shouldPersist=!1,this.createEvent=n=>{const{event:s="ERROR",type:a="",properties:{topic:u,trace:h}}=n,l=iA(),b=this.core.projectId||"",w=Date.now(),I=ku({eventId:l,bundleId:b,timestamp:w,props:{event:s,type:a,properties:{topic:u,trace:h}}},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,I),this.shouldPersist=!0),I},this.getEvent=n=>{const{eventId:s,topic:a}=n;if(s)return this.events.get(s);const u=Array.from(this.events.values()).find(h=>h.props.properties.topic===a);if(u)return ku(ku({},u),this.setMethods(u.eventId))},this.deleteEvent=n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(ac.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{xe.fromMiliseconds(Date.now())-xe.fromMiliseconds(n.timestamp)>_P&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})},this.setMethods=n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)}),this.addTrace=(n,s)=>{const a=this.events.get(n);a&&(a.props.properties.trace.push(s),this.events.set(n,a),this.shouldPersist=!0)},this.setError=(n,s)=>{const a=this.events.get(n);a&&(a.props.type=s,a.timestamp=Date.now(),this.events.set(n,a),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},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,ku(ku({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}},this.submit=async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[s,a]of this.events)a.props.type&&n.push(a);if(n.length!==0)try{if((await fetch(`${EP}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${x3}`,{method:"POST",body:JSON.stringify(n)})).ok)for(const s of n)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}},this.logger=ui(r,this.context),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 a$=Object.defineProperty,B3=Object.getOwnPropertySymbols,c$=Object.prototype.hasOwnProperty,u$=Object.prototype.propertyIsEnumerable,F3=(t,e,r)=>e in t?a$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,k3=(t,e)=>{for(var r in e||(e={}))c$.call(e,r)&&F3(t,r,e[r]);if(B3)for(var r of B3(e))u$.call(e,r)&&F3(t,r,e[r]);return t};class n1 extends lC{constructor(e){var r;super(e),this.protocol=y3,this.version=w3,this.name=r1,this.events=new Ur.exports.EventEmitter,this.initialized=!1,this.on=(a,u)=>this.events.on(a,u),this.once=(a,u)=>this.events.once(a,u),this.off=(a,u)=>this.events.off(a,u),this.removeListener=(a,u)=>this.events.removeListener(a,u),this.dispatchEnvelope=({topic:a,message:u,sessionExists:h})=>{if(!a||!u)return;const l={topic:a,message:u,publishedAt:Date.now(),transportType:Zt.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})},this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||A3,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Dh({level:typeof e?.logger=="string"&&e.logger?e.logger:qO.logger}),{logger:n,chunkLoggerController:s}=hC({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=s,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,u;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((u=this.logChunkController)==null||u.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=ui(n,this.name),this.heartbeat=new qd,this.crypto=new xP(this,this.logger,e?.keychain),this.history=new zP(this,this.logger),this.expirer=new HP(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new LM(k3(k3({},zO),e?.storageOptions)),this.relayer=new FP({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new qP(this,this.logger),this.verify=new t$(this,this.logger,this.storage),this.echoClient=new r$(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new o$(this,this.logger,e?.telemetryEnabled)}static async init(e){const r=new n1(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(iP,i),r}get context(){return Ai(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(S3,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(S3)||[],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 f$=n1,U3="wc",j3=2,q3="client",s1=`${U3}@${j3}:${q3}:`,o1={name:q3,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},z3="WALLETCONNECT_DEEPLINK_CHOICE",h$="proposal",H3="Proposal expired",l$="session",lc=xe.SEVEN_DAYS,d$="engine",Lr={wc_sessionPropose:{req:{ttl:xe.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1104},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1106},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:xe.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:xe.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1112},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1114},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:xe.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:xe.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1119}}},a1={min:xe.FIVE_MINUTES,max:xe.SEVEN_DAYS},ps={idle:"IDLE",active:"ACTIVE"},p$="request",g$=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],v$="wc",m$="auth",b$="authKeys",y$="pairingTopics",w$="requests",Nh=`${v$}@${1.5}:${m$}:`,Th=`${Nh}:PUB_KEY`;var _$=Object.defineProperty,E$=Object.defineProperties,A$=Object.getOwnPropertyDescriptors,K3=Object.getOwnPropertySymbols,x$=Object.prototype.hasOwnProperty,S$=Object.prototype.propertyIsEnumerable,W3=(t,e,r)=>e in t?_$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pr=(t,e)=>{for(var r in e||(e={}))x$.call(e,r)&&W3(t,r,e[r]);if(K3)for(var r of K3(e))S$.call(e,r)&&W3(t,r,e[r]);return t},Mn=(t,e)=>E$(t,A$(e));class I$ extends xC{constructor(e){super(e),this.name=d$,this.events=new Ur.exports,this.initialized=!1,this.requestQueue={state:ps.idle,queue:[]},this.sessionRequestQueue={state:ps.idle,queue:[]},this.requestQueueDelay=xe.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],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(Lr)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},xe.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Mn(pr({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:n,requiredNamespaces:s,optionalNamespaces:a,sessionProperties:u,relays:h}=i;let l=n,b,w=!1;try{l&&(w=this.client.core.pairing.pairings.get(l).active)}catch(R){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),R}if(!l||!w){const{topic:R,uri:U}=await this.client.core.pairing.create();l=R,b=U}if(!l){const{message:R}=Ee("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(R)}const I=await this.client.core.crypto.generateKeyPair(),S=Lr.wc_sessionPropose.req.ttl||xe.FIVE_MINUTES,D=Ir(S),T=pr({requiredNamespaces:s,optionalNamespaces:a,relays:h??[{protocol:E3}],proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:D,pairingTopic:l},u&&{sessionProperties:u}),{reject:j,resolve:K,done:F}=zo(S,H3);this.events.once(Dt("session_connect"),async({error:R,session:U})=>{if(R)j(R);else if(U){U.self.publicKey=I;const H=Mn(pr({},U),{pairingTopic:T.pairingTopic,requiredNamespaces:T.requiredNamespaces,optionalNamespaces:T.optionalNamespaces,transportType:Zt.relay});await this.client.session.set(U.topic,H),await this.setExpiry(U.topic,U.expiry),l&&await this.client.core.pairing.updateMetadata({topic:l,metadata:U.peer.metadata}),this.cleanupDuplicatePairings(H),K(H)}});const W=await this.sendRequest({topic:l,method:"wc_sessionPropose",params:T,throwOnFailedPublish:!0});return await this.setProposal(W,pr({id:W},T)),{uri:b,approval:F}},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}},this.approve=async r=>{var i,n,s;const a=this.client.core.eventClient.createEvent({properties:{topic:(i=r?.id)==null?void 0:i.toString(),trace:[In.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(B){throw a.setError(Zo.no_internet_connection),B}try{await this.isValidProposalId(r?.id)}catch(B){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),a.setError(Zo.proposal_not_found),B}try{await this.isValidApprove(r)}catch(B){throw this.client.logger.error("approve() -> isValidApprove() failed"),a.setError(Zo.session_approve_namespace_validation_failure),B}const{id:u,relayProtocol:h,namespaces:l,sessionProperties:b,sessionConfig:w}=r,I=this.client.proposal.get(u);this.client.core.eventClient.deleteEvent({eventId:a.eventId});const{pairingTopic:S,proposer:D,requiredNamespaces:T,optionalNamespaces:j}=I;let K=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:S});K||(K=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:In.session_approve_started,properties:{topic:S,trace:[In.session_approve_started,In.session_namespaces_validation_success]}}));const F=await this.client.core.crypto.generateKeyPair(),W=D.publicKey,R=await this.client.core.crypto.generateSharedKey(F,W),U=pr(pr({relay:{protocol:h??"irn"},namespaces:l,controller:{publicKey:F,metadata:this.client.metadata},expiry:Ir(lc)},b&&{sessionProperties:b}),w&&{sessionConfig:w}),H=Zt.relay;K.addTrace(In.subscribing_session_topic);try{await this.client.core.relayer.subscribe(R,{transportType:H})}catch(B){throw K.setError(Zo.subscribe_session_topic_failure),B}K.addTrace(In.subscribe_session_topic_success);const _=Mn(pr({},U),{topic:R,requiredNamespaces:T,optionalNamespaces:j,pairingTopic:S,acknowledged:!1,self:U.controller,peer:{publicKey:D.publicKey,metadata:D.metadata},controller:F,transportType:Zt.relay});await this.client.session.set(R,_),K.addTrace(In.store_session);try{K.addTrace(In.publishing_session_settle),await this.sendRequest({topic:R,method:"wc_sessionSettle",params:U,throwOnFailedPublish:!0}).catch(B=>{throw K?.setError(Zo.session_settle_publish_failure),B}),K.addTrace(In.session_settle_publish_success),K.addTrace(In.publishing_session_approve),await this.sendResult({id:u,topic:S,result:{relay:{protocol:h??"irn"},responderPublicKey:F},throwOnFailedPublish:!0}).catch(B=>{throw K?.setError(Zo.session_approve_publish_failure),B}),K.addTrace(In.session_approve_publish_success)}catch(B){throw this.client.logger.error(B),this.client.session.delete(R,Gt("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(R),B}return this.client.core.eventClient.deleteEvent({eventId:K.eventId}),await this.client.core.pairing.updateMetadata({topic:S,metadata:D.metadata}),await this.client.proposal.delete(u,Gt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:S}),await this.setExpiry(R,Ir(lc)),{topic:R,acknowledged:()=>Promise.resolve(this.client.session.get(R))}},this.reject=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(a){throw this.client.logger.error("reject() -> isValidReject() failed"),a}const{id:i,reason:n}=r;let s;try{s=this.client.proposal.get(i).pairingTopic}catch(a){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),a}s&&(await this.sendError({id:i,topic:s,error:n,rpcOpts:Lr.wc_sessionPropose.reject}),await this.client.proposal.delete(i,Gt("USER_DISCONNECTED")))},this.update=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(w){throw this.client.logger.error("update() -> isValidUpdate() failed"),w}const{topic:i,namespaces:n}=r,{done:s,resolve:a,reject:u}=zo(),h=co(),l=Jo().toString(),b=this.client.session.get(i).namespaces;return this.events.once(Dt("session_update",h),({error:w})=>{w?u(w):a()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:h,relayRpcId:l}).catch(w=>{this.client.logger.error(w),this.client.session.update(i,{namespaces:b}),u(w)}),{acknowledged:s}},this.extend=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(h){throw this.client.logger.error("extend() -> isValidExtend() failed"),h}const{topic:i}=r,n=co(),{done:s,resolve:a,reject:u}=zo();return this.events.once(Dt("session_extend",n),({error:h})=>{h?u(h):a()}),await this.setExpiry(i,Ir(lc)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(h=>{u(h)}),{acknowledged:s}},this.request=async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(D){throw this.client.logger.error("request() -> isValidRequest() failed"),D}const{chainId:i,request:n,topic:s,expiry:a=Lr.wc_sessionRequest.req.ttl}=r,u=this.client.session.get(s);u?.transportType===Zt.relay&&await this.confirmOnlineStateOrThrow();const h=co(),l=Jo().toString(),{done:b,resolve:w,reject:I}=zo(a,"Request expired. Please try again.");this.events.once(Dt("session_request",h),({error:D,result:T})=>{D?I(D):w(T)});const S=this.getAppLinkIfEnabled(u.peer.metadata,u.transportType);return S?(await this.sendRequest({clientRpcId:h,relayRpcId:l,topic:s,method:"wc_sessionRequest",params:{request:Mn(pr({},n),{expiryTimestamp:Ir(a)}),chainId:i},expiry:a,throwOnFailedPublish:!0,appLink:S}).catch(D=>I(D)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:h}),await b()):await Promise.all([new Promise(async D=>{await this.sendRequest({clientRpcId:h,relayRpcId:l,topic:s,method:"wc_sessionRequest",params:{request:Mn(pr({},n),{expiryTimestamp:Ir(a)}),chainId:i},expiry:a,throwOnFailedPublish:!0}).catch(T=>I(T)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:h}),D()}),new Promise(async D=>{var T;if(!((T=u.sessionConfig)!=null&&T.disableDeepLink)){const j=await rA(this.client.core.storage,z3);tA({id:h,topic:s,wcDeepLink:j})}D()}),b()]).then(D=>D[2])},this.respond=async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:i,response:n}=r,{id:s}=n,a=this.client.session.get(i);a.transportType===Zt.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);fs(n)?await this.sendResult({id:s,topic:i,result:n.result,throwOnFailedPublish:!0,appLink:u}):rn(n)&&await this.sendError({id:s,topic:i,error:n.error,appLink:u}),this.cleanupAfterResponse(r)},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=co(),s=Jo().toString(),{done:a,resolve:u,reject:h}=zo();this.events.once(Dt("session_ping",n),({error:l})=>{l?h(l):u()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),a()])}else this.client.core.pairing.pairings.keys.includes(i)&&await this.client.core.pairing.ping({topic:i})},this.emit=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,a=Jo().toString();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:a})},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:Gt("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=Ee("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(i=>$I(i,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),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),a=s?Zt.link_mode:Zt.relay;a===Zt.relay&&await this.confirmOnlineStateOrThrow();const{chains:u,statement:h="",uri:l,domain:b,nonce:w,type:I,exp:S,nbf:D,methods:T=[],expiry:j}=r,K=[...r.resources||[]],{topic:F,uri:W}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:a});this.client.logger.info({message:"Generated new pairing",pairing:{topic:F,uri:W}});const R=await this.client.core.crypto.generateKeyPair(),U=bh(R);if(await Promise.all([this.client.auth.authKeys.set(Th,{responseTopic:U,publicKey:R}),this.client.auth.pairingTopics.set(U,{topic:U,pairingTopic:F})]),await this.client.core.relayer.subscribe(U,{transportType:a}),this.client.logger.info(`sending request to new pairing topic: ${F}`),T.length>0){const{namespace:O}=ou(u[0]);let M=ZS(O,"request",T);mh(K)&&(M=eI(M,K.pop())),K.push(M)}const H=j&&j>Lr.wc_sessionAuthenticate.req.ttl?j:Lr.wc_sessionAuthenticate.req.ttl,_={authPayload:{type:I??"caip122",chains:u,statement:h,aud:l,domain:b,version:"1",nonce:w,iat:new Date().toISOString(),exp:S,nbf:D,resources:K},requester:{publicKey:R,metadata:this.client.metadata},expiryTimestamp:Ir(H)},B={eip155:{chains:u,methods:[...new Set(["personal_sign",...T])],events:["chainChanged","accountsChanged"]}},ee={requiredNamespaces:{},optionalNamespaces:B,relays:[{protocol:"irn"}],pairingTopic:F,proposer:{publicKey:R,metadata:this.client.metadata},expiryTimestamp:Ir(Lr.wc_sessionPropose.req.ttl)},{done:ie,resolve:L,reject:y}=zo(H,"Request expired"),f=async({error:O,session:M})=>{if(this.events.off(Dt("session_request",v),d),O)y(O);else if(M){M.self.publicKey=R,await this.client.session.set(M.topic,M),await this.setExpiry(M.topic,M.expiry),F&&await this.client.core.pairing.updateMetadata({topic:F,metadata:M.peer.metadata});const g=this.client.session.get(M.topic);await this.deleteProposal(E),L({session:g})}},d=async O=>{var M,g,m;if(await this.deletePendingAuthRequest(v,{message:"fulfilled",code:0}),O.error){const G=Gt("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return O.error.code===G.code?void 0:(this.events.off(Dt("session_connect"),f),y(O.error.message))}await this.deleteProposal(E),this.events.off(Dt("session_connect"),f);const{cacaos:N,responder:X}=O.result,ae=[],P=[];for(const G of N){await eb({cacao:G,projectId:this.client.core.projectId})||(this.client.logger.error(G,"Signature verification failed"),y(Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Y}=G,A=mh(Y.resources),V=[Xm(Y.iss)],oe=vh(Y.iss);if(A){const ue=ib(A),he=nb(A);ae.push(...ue),V.push(...he)}for(const ue of V)P.push(`${ue}:${oe}`)}const te=await this.client.core.crypto.generateSharedKey(R,X.publicKey);let z;ae.length>0&&(z={topic:te,acknowledged:!0,self:{publicKey:R,metadata:this.client.metadata},peer:X,controller:X.publicKey,expiry:Ir(lc),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:F,namespaces:mb([...new Set(ae)],[...new Set(P)]),transportType:a},await this.client.core.relayer.subscribe(te,{transportType:a}),await this.client.session.set(te,z),F&&await this.client.core.pairing.updateMetadata({topic:F,metadata:X.metadata}),z=this.client.session.get(te)),(M=this.client.metadata.redirect)!=null&&M.linkMode&&(g=X.metadata.redirect)!=null&&g.linkMode&&(m=X.metadata.redirect)!=null&&m.universal&&i&&(this.client.core.addLinkModeSupportedApp(X.metadata.redirect.universal),this.client.session.update(te,{transportType:Zt.link_mode})),L({auths:N,session:z})},v=co(),E=co();this.events.once(Dt("session_connect"),f),this.events.once(Dt("session_request",v),d);let C;try{if(s){const O=Qo("wc_sessionAuthenticate",_,v);this.client.core.history.set(F,O);const M=await this.client.core.crypto.encode("",O,{type:_u,encoding:yu});C=yh(i,F,M)}else await Promise.all([this.sendRequest({topic:F,method:"wc_sessionAuthenticate",params:_,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:v}),this.sendRequest({topic:F,method:"wc_sessionPropose",params:ee,expiry:Lr.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:E})])}catch(O){throw this.events.off(Dt("session_connect"),f),this.events.off(Dt("session_request",v),d),O}return await this.setProposal(E,pr({id:E},ee)),await this.setAuthRequest(v,{request:Mn(pr({},_),{verifyContext:{}}),pairingTopic:F,transportType:a}),{uri:C??W,response:ie}},this.approveSessionAuthenticate=async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Xo.authenticated_session_approve_started]}});try{this.isInitialized()}catch(j){throw s.setError(Bu.no_internet_connection),j}const a=this.getPendingAuthRequest(i);if(!a)throw s.setError(Bu.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const u=a.transportType||Zt.relay;u===Zt.relay&&await this.confirmOnlineStateOrThrow();const h=a.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),b=bh(h),w={type:Rs,receiverPublicKey:h,senderPublicKey:l},I=[],S=[];for(const j of n){if(!await eb({cacao:j,projectId:this.client.core.projectId})){s.setError(Bu.invalid_cacao);const U=Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:b,error:U,encodeOpts:w}),new Error(U.message)}s.addTrace(Xo.cacaos_verified);const{p:K}=j,F=mh(K.resources),W=[Xm(K.iss)],R=vh(K.iss);if(F){const U=ib(F),H=nb(F);I.push(...U),W.push(...H)}for(const U of W)S.push(`${U}:${R}`)}const D=await this.client.core.crypto.generateSharedKey(l,h);s.addTrace(Xo.create_authenticated_session_topic);let T;if(I?.length>0){T={topic:D,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:h,metadata:a.requester.metadata},controller:h,expiry:Ir(lc),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:a.pairingTopic,namespaces:mb([...new Set(I)],[...new Set(S)]),transportType:u},s.addTrace(Xo.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(D,{transportType:u})}catch(j){throw s.setError(Bu.subscribe_authenticated_session_topic_failure),j}s.addTrace(Xo.subscribe_authenticated_session_topic_success),await this.client.session.set(D,T),s.addTrace(Xo.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:a.pairingTopic,metadata:a.requester.metadata})}s.addTrace(Xo.publishing_authenticated_session_approve);try{await this.sendResult({topic:b,id:i,result:{cacaos:n,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:w,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(a.requester.metadata,u)})}catch(j){throw s.setError(Bu.authenticated_session_approve_publish_failure),j}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:a.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:T}},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===Zt.relay&&await this.confirmOnlineStateOrThrow();const a=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),h=bh(a),l={type:Rs,receiverPublicKey:a,senderPublicKey:u};await this.sendError({id:i,topic:h,error:n,encodeOpts:l,rpcOpts:Lr.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,Gt("USER_DISCONNECTED"))},this.formatAuthMessage=r=>{this.isInitialized();const{request:i,iss:n}=r;return tb(i,n)},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)},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 a,u;return((a=s.peerMetadata)==null?void 0:a.url)&&((u=s.peerMetadata)==null?void 0:u.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)}},this.deleteSession=async r=>{var i;const{topic:n,expirerHasDeleted:s=!1,emitEvent:a=!0,id:u=0}=r,{self:h}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,Gt("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(h.publicKey)&&await this.client.core.crypto.deleteKeyPair(h.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(z3).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===n&&this.deletePendingSessionRequest(l.id,Gt("USER_DISCONNECTED"))}),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=ps.idle),a&&this.client.events.emit("session_delete",{id:u,topic:n})},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(Zo.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,Gt("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")},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=ps.idle,this.client.events.emit("session_request_expire",{id:r}))},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)])},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}))},this.setProposal=async(r,i)=>{this.client.core.expirer.set(r,Ir(Lr.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)},this.setAuthRequest=async(r,i)=>{const{request:n,pairingTopic:s,transportType:a=Zt.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:a})},this.setPendingSessionRequest=async r=>{const{id:i,topic:n,params:s,verifyContext:a}=r,u=s.request.expiryTimestamp||Ir(Lr.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,u),await this.client.pendingRequest.set(i,{id:i,topic:n,params:s,verifyContext:a})},this.sendRequest=async r=>{const{topic:i,method:n,params:s,expiry:a,relayRpcId:u,clientRpcId:h,throwOnFailedPublish:l,appLink:b}=r,w=Qo(n,s,h);let I;const S=!!b;try{const j=S?yu:ao;I=await this.client.core.crypto.encode(i,w,{encoding:j})}catch(j){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),j}let D;if(g$.includes(n)){const j=Ns(JSON.stringify(w)),K=Ns(I);D=await this.client.core.verify.register({id:K,decryptedId:j})}const T=Lr[n].req;if(T.attestation=D,a&&(T.ttl=a),u&&(T.id=u),this.client.core.history.set(i,w),S){const j=yh(b,i,I);await global.Linking.openURL(j,this.client.name)}else{const j=Lr[n].req;a&&(j.ttl=a),u&&(j.id=u),l?(j.internal=Mn(pr({},j.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,I,j)):this.client.core.relayer.publish(i,I,j).catch(K=>this.client.logger.error(K))}return w.id},this.sendResult=async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:a,encodeOpts:u,appLink:h}=r,l=Oh(i,s);let b;const w=h&&typeof(global==null?void 0:global.Linking)<"u";try{const S=w?yu:ao;b=await this.client.core.crypto.encode(n,l,Mn(pr({},u||{}),{encoding:S}))}catch(S){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),S}let I;try{I=await this.client.core.history.get(n,i)}catch(S){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),S}if(w){const S=yh(h,n,b);await global.Linking.openURL(S,this.client.name)}else{const S=Lr[I.request.method].res;a?(S.internal=Mn(pr({},S.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,b,S)):this.client.core.relayer.publish(n,b,S).catch(D=>this.client.logger.error(D))}await this.client.core.history.resolve(l)},this.sendError=async r=>{const{id:i,topic:n,error:s,encodeOpts:a,rpcOpts:u,appLink:h}=r,l=Ph(i,s);let b;const w=h&&typeof(global==null?void 0:global.Linking)<"u";try{const S=w?yu:ao;b=await this.client.core.crypto.encode(n,l,Mn(pr({},a||{}),{encoding:S}))}catch(S){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),S}let I;try{I=await this.client.core.history.get(n,i)}catch(S){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),S}if(w){const S=yh(h,n,b);await global.Linking.openURL(S,this.client.name)}else{const S=u||Lr[I.request.method].res;this.client.core.relayer.publish(n,b,S)}await this.client.core.history.resolve(l)},this.cleanup=async()=>{const r=[],i=[];this.client.session.getAll().forEach(n=>{let s=!1;io(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=>{io(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...r.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===ps.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=ps.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=ps.idle},this.processRequest=async r=>{const{topic:i,payload:n,attestation:s,transportType:a,encryptedId:u}=r,h=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:h}))switch(h){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:u});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:u,transportType:a});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:u,transportType:a});default:return this.client.logger.info(`Unsupported request method ${h}`)}},this.onRelayEventResponse=async r=>{const{topic:i,payload:n,transportType:s}=r,a=(await this.client.core.history.get(i,n.id)).request.method;switch(a){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 ${a}`)}},this.onRelayEventUnknownPayload=r=>{const{topic:i}=r,{message:n}=Ee("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)},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)},this.onSessionProposeRequest=async r=>{const{topic:i,payload:n,attestation:s,encryptedId:a}=r,{params:u,id:h}=n;try{const l=this.client.core.eventClient.getEvent({topic:i});this.isValidConnect(pr({},n.params));const b=u.expiryTimestamp||Ir(Lr.wc_sessionPropose.req.ttl),w=pr({id:h,pairingTopic:i,expiryTimestamp:b},u);await this.setProposal(h,w);const I=await this.getVerifyContext({attestationId:s,hash:Ns(JSON.stringify(n)),encryptedId:a,metadata:w.proposer.metadata});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(Bs.proposal_listener_not_found)),l?.addTrace(ds.emit_session_proposal),this.client.events.emit("session_proposal",{id:h,params:w,verifyContext:I})}catch(l){await this.sendError({id:h,topic:i,error:l,rpcOpts:Lr.wc_sessionPropose.autoReject}),this.client.logger.error(l)}},this.onSessionProposeResponse=async(r,i,n)=>{const{id:s}=i;if(fs(i)){const{result:a}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:a});const u=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:u});const h=u.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:h});const l=a.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const b=await this.client.core.crypto.generateSharedKey(h,l);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:b});const w=await this.client.core.relayer.subscribe(b,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:w}),await this.client.core.pairing.activate({topic:r})}else if(rn(i)){await this.client.proposal.delete(s,Gt("USER_DISCONNECTED"));const a=Dt("session_connect");if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners, 954`);this.events.emit(Dt("session_connect"),{error:i.error})}},this.onSessionSettleRequest=async(r,i)=>{const{id:n,params:s}=i;try{this.isValidSessionSettleRequest(s);const{relay:a,controller:u,expiry:h,namespaces:l,sessionProperties:b,sessionConfig:w}=i.params,I=Mn(pr(pr({topic:r,relay:a,expiry:h,namespaces:l,acknowledged:!0,pairingTopic:"",requiredNamespaces:{},optionalNamespaces:{},controller:u.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:u.publicKey,metadata:u.metadata}},b&&{sessionProperties:b}),w&&{sessionConfig:w}),{transportType:Zt.relay}),S=Dt("session_connect");if(this.events.listenerCount(S)===0)throw new Error(`emitting ${S} without any listeners 997`);this.events.emit(Dt("session_connect"),{session:I}),await this.sendResult({id:i.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(a){await this.sendError({id:n,topic:r,error:a}),this.client.logger.error(a)}},this.onSessionSettleResponse=async(r,i)=>{const{id:n}=i;fs(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(Dt("session_approve",n),{})):rn(i)&&(await this.client.session.delete(r,Gt("USER_DISCONNECTED")),this.events.emit(Dt("session_approve",n),{error:i.error}))},this.onSessionUpdateRequest=async(r,i)=>{const{params:n,id:s}=i;try{const a=`${r}_session_update`,u=Mu.get(a);if(u&&this.isRequestOutOfSync(u,s)){this.client.logger.info(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:Gt("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(pr({topic:r},n));try{Mu.set(a,s),await this.client.session.update(r,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(h){throw Mu.delete(a),h}this.client.events.emit("session_update",{id:s,topic:r,params:n})}catch(a){await this.sendError({id:s,topic:r,error:a}),this.client.logger.error(a)}},this.isRequestOutOfSync=(r,i)=>parseInt(i.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,i)=>{const{id:n}=i,s=Dt("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);fs(i)?this.events.emit(Dt("session_update",n),{}):rn(i)&&this.events.emit(Dt("session_update",n),{error:i.error})},this.onSessionExtendRequest=async(r,i)=>{const{id:n}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,Ir(lc)),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)}},this.onSessionExtendResponse=(r,i)=>{const{id:n}=i,s=Dt("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);fs(i)?this.events.emit(Dt("session_extend",n),{}):rn(i)&&this.events.emit(Dt("session_extend",n),{error:i.error})},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)}},this.onSessionPingResponse=(r,i)=>{const{id:n}=i,s=Dt("session_ping",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);setTimeout(()=>{fs(i)?this.events.emit(Dt("session_ping",n),{}):rn(i)&&this.events.emit(Dt("session_ping",n),{error:i.error})},500)},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(hi.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:Gt("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async r=>{var i,n,s;const{topic:a,payload:u,attestation:h,encryptedId:l,transportType:b}=r,{id:w,params:I}=u;try{await this.isValidRequest(pr({topic:a},I));const S=this.client.session.get(a),D=await this.getVerifyContext({attestationId:h,hash:Ns(JSON.stringify(Qo("wc_sessionRequest",I,w))),encryptedId:l,metadata:S.peer.metadata,transportType:b}),T={id:w,topic:a,params:I,verifyContext:D};await this.setPendingSessionRequest(T),b===Zt.link_mode&&(i=S.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((n=S.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(T):(this.addSessionRequestToSessionRequestQueue(T),this.processSessionRequestQueue())}catch(S){await this.sendError({id:w,topic:a,error:S}),this.client.logger.error(S)}},this.onSessionRequestResponse=(r,i)=>{const{id:n}=i,s=Dt("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);fs(i)?this.events.emit(Dt("session_request",n),{result:i.result}):rn(i)&&this.events.emit(Dt("session_request",n),{error:i.error})},this.onSessionEventRequest=async(r,i)=>{const{id:n,params:s}=i;try{const a=`${r}_session_event_${s.event.name}`,u=Mu.get(a);if(u&&this.isRequestOutOfSync(u,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(pr({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),Mu.set(a,n)}catch(a){await this.sendError({id:n,topic:r,error:a}),this.client.logger.error(a)}},this.onSessionAuthenticateResponse=(r,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),fs(i)?this.events.emit(Dt("session_request",n),{result:i.result}):rn(i)&&this.events.emit(Dt("session_request",n),{error:i.error})},this.onSessionAuthenticateRequest=async r=>{var i;const{topic:n,payload:s,attestation:a,encryptedId:u,transportType:h}=r;try{const{requester:l,authPayload:b,expiryTimestamp:w}=s.params,I=await this.getVerifyContext({attestationId:a,hash:Ns(JSON.stringify(s)),encryptedId:u,metadata:l.metadata,transportType:h}),S={requester:l,pairingTopic:n,id:s.id,authPayload:b,verifyContext:I,expiryTimestamp:w};await this.setAuthRequest(s.id,{request:S,pairingTopic:n,transportType:h}),h===Zt.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:I})}catch(l){this.client.logger.error(l);const b=s.params.requester.publicKey,w=await this.client.core.crypto.generateKeyPair(),I=this.getAppLinkIfEnabled(s.params.requester.metadata,h),S={type:Rs,receiverPublicKey:b,senderPublicKey:w};await this.sendError({id:s.id,topic:n,error:l,encodeOpts:S,rpcOpts:Lr.wc_sessionAuthenticate.autoReject,appLink:I})}},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=ps.idle,this.processSessionRequestQueue()},xe.toMiliseconds(this.requestQueueDelay))},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 a=s.request.id,u=Dt("session_request",a);if(this.events.listenerCount(u)===0)throw new Error(`emitting ${u} without any listeners`);this.events.emit(Dt("session_request",s.request.id),{error:i})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===ps.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=ps.active,this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}},this.emitSessionRequest=r=>{this.client.events.emit("session_request",r)},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:Qo("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})},this.isValidConnect=async r=>{if(!_i(r)){const{message:h}=Ee("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(h)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:a,relays:u}=r;if(ci(i)||await this.isValidPairingTopic(i),!HI(u,!0)){const{message:h}=Ee("MISSING_OR_INVALID",`connect() relays: ${u}`);throw new Error(h)}!ci(n)&&Iu(n)!==0&&this.validateNamespaces(n,"requiredNamespaces"),!ci(s)&&Iu(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),ci(a)||this.validateSessionProps(a,"sessionProperties")},this.validateNamespaces=(r,i)=>{const n=zI(r,"connect()",i);if(n)throw new Error(n.message)},this.isValidApprove=async r=>{if(!_i(r))throw new Error(Ee("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:n,relayProtocol:s,sessionProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const u=this.client.proposal.get(i),h=Bd(n,"approve()");if(h)throw new Error(h.message);const l=Eb(u.requiredNamespaces,n,"approve()");if(l)throw new Error(l.message);if(!yr(s,!0)){const{message:b}=Ee("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(b)}ci(a)||this.validateSessionProps(a,"sessionProperties")},this.isValidReject=async r=>{if(!_i(r)){const{message:s}=Ee("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:i,reason:n}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!WI(n)){const{message:s}=Ee("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!_i(r)){const{message:l}=Ee("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:i,controller:n,namespaces:s,expiry:a}=r;if(!wb(i)){const{message:l}=Ee("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const u=BI(n,"onSessionSettleRequest()");if(u)throw new Error(u.message);const h=Bd(s,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(io(a)){const{message:l}=Ee("EXPIRED","onSessionSettleRequest()");throw new Error(l)}},this.isValidUpdate=async r=>{if(!_i(r)){const{message:h}=Ee("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(h)}const{topic:i,namespaces:n}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),a=Bd(n,"update()");if(a)throw new Error(a.message);const u=Eb(s.requiredNamespaces,n,"update()");if(u)throw new Error(u.message)},this.isValidExtend=async r=>{if(!_i(r)){const{message:n}=Ee("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(n)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)},this.isValidRequest=async r=>{if(!_i(r)){const{message:h}=Ee("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(h)}const{topic:i,request:n,chainId:s,expiry:a}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:u}=this.client.session.get(i);if(!_b(u,s)){const{message:h}=Ee("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(h)}if(!VI(n)){const{message:h}=Ee("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(h)}if(!JI(u,s,n.method)){const{message:h}=Ee("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(h)}if(a&&!eM(a,a1)){const{message:h}=Ee("MISSING_OR_INVALID",`request() expiry: ${a}. Expiry must be a number (in seconds) between ${a1.min} and ${a1.max}`);throw new Error(h)}},this.isValidRespond=async r=>{var i;if(!_i(r)){const{message:a}=Ee("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}const{topic:n,response:s}=r;try{await this.isValidSessionTopic(n)}catch(a){throw(i=r?.response)!=null&&i.id&&this.cleanupAfterResponse(r),a}if(!GI(s)){const{message:a}=Ee("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}},this.isValidPing=async r=>{if(!_i(r)){const{message:n}=Ee("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)},this.isValidEmit=async r=>{if(!_i(r)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(u)}const{topic:i,event:n,chainId:s}=r;await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!_b(a,s)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(u)}if(!YI(n)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(u)}if(!QI(a,s,n.name)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(u)}},this.isValidDisconnect=async r=>{if(!_i(r)){const{message:n}=Ee("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)},this.isValidAuthenticate=r=>{const{chains:i,uri:n,domain:s,nonce:a}=r;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!yr(n,!1))throw new Error("uri is required parameter");if(!yr(s,!1))throw new Error("domain is required parameter");if(!yr(a,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(h=>ou(h).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:u}=ou(i[0]);if(u!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async r=>{const{attestationId:i,hash:n,encryptedId:s,metadata:a,transportType:u}=r,h={verified:{verifyUrl:a.verifyUrl||Lu,validation:"UNKNOWN",origin:a.url||""}};try{if(u===Zt.link_mode){const b=this.getAppLinkIfEnabled(a,u);return h.verified.validation=b&&new URL(b).origin===new URL(a.url).origin?"VALID":"INVALID",h}const l=await this.client.core.verify.resolve({attestationId:i,hash:n,encryptedId:s,verifyUrl:a.verifyUrl});l&&(h.verified.origin=l.origin,h.verified.isScam=l.isScam,h.verified.validation=l.origin===new URL(a.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(h)}`),h},this.validateSessionProps=(r,i)=>{Object.values(r).forEach(n=>{if(!yr(n,!1)){const{message:s}=Ee("MISSING_OR_INVALID",`${i} must be in Record<string, string> format. Received: ${JSON.stringify(n)}`);throw new Error(s)}})},this.getPendingAuthRequest=r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0},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 a of this.recentlyDeletedMap.keys()){if(n++>=s)break;this.recentlyDeletedMap.delete(a)}}},this.checkRecentlyDeleted=r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:n}=Ee("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(n)}},this.isLinkModeEnabled=(r,i)=>{var n,s,a,u,h,l,b,w,I;return!r||i!==Zt.link_mode?!1:((s=(n=this.client.metadata)==null?void 0:n.redirect)==null?void 0:s.linkMode)===!0&&((u=(a=this.client.metadata)==null?void 0:a.redirect)==null?void 0:u.universal)!==void 0&&((l=(h=this.client.metadata)==null?void 0:h.redirect)==null?void 0:l.universal)!==""&&((b=r?.redirect)==null?void 0:b.universal)!==void 0&&((w=r?.redirect)==null?void 0:w.universal)!==""&&((I=r?.redirect)==null?void 0:I.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"},this.getAppLinkIfEnabled=(r,i)=>{var n;return this.isLinkModeEnabled(r,i)?(n=r?.redirect)==null?void 0:n.universal:void 0},this.handleLinkModeMessage=({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=W2(r,"topic")||"",n=decodeURIComponent(W2(r,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:Zt.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})},this.registerLinkModeListeners=async()=>{var r,i;if((r=process==null?void 0:process.env)!=null&&r.IS_VITEST||Va()&&(i=this.client.metadata.redirect)!=null&&i.linkMode){const n=global==null?void 0:global.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);const s=await n.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(hi.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:a}=this.client.auth.authKeys.keys.includes(Th)?this.client.auth.authKeys.get(Th):{responseTopic:void 0,publicKey:void 0},u=await this.client.core.crypto.decode(r,i,{receiverPublicKey:a,encoding:s===Zt.link_mode?yu:ao});try{Qd(u)?(this.client.core.history.set(r,u),this.onRelayEventRequest({topic:r,payload:u,attestation:n,transportType:s,encryptedId:Ns(i)})):$h(u)?(await this.client.core.history.resolve(u),await this.onRelayEventResponse({topic:r,payload:u,transportType:s}),this.client.core.history.delete(r,u.id)):this.onRelayEventUnknownPayload({topic:r,payload:u,transportType:s})}catch(h){this.client.logger.error(h)}}registerExpirerEvents(){this.client.core.expirer.on(sn.expired,async e=>{const{topic:r,id:i}=K2(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,Ee("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,Ee("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(fc.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(fc.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!yr(e,!1)){const{message:r}=Ee("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=Ee("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(io(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=Ee("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!yr(e,!1)){const{message:r}=Ee("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=Ee("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(io(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=Ee("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=Ee("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(yr(e,!1)){const{message:r}=Ee("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=Ee("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!KI(e)){const{message:r}=Ee("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=Ee("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(io(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=Ee("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class M$ extends ea{constructor(e,r){super(e,r,h$,s1),this.core=e,this.logger=r}}class C$ extends ea{constructor(e,r){super(e,r,l$,s1),this.core=e,this.logger=r}}class D$ extends ea{constructor(e,r){super(e,r,p$,s1,i=>i.id),this.core=e,this.logger=r}}class O$ extends ea{constructor(e,r){super(e,r,b$,Nh,()=>Th),this.core=e,this.logger=r}}class P$ extends ea{constructor(e,r){super(e,r,y$,Nh),this.core=e,this.logger=r}}class $$ extends ea{constructor(e,r){super(e,r,w$,Nh,i=>i.id),this.core=e,this.logger=r}}class R${constructor(e,r){this.core=e,this.logger=r,this.authKeys=new O$(this.core,this.logger),this.pairingTopics=new P$(this.core,this.logger),this.requests=new $$(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}class c1 extends AC{constructor(e){super(e),this.protocol=U3,this.version=j3,this.name=o1.name,this.events=new Ur.exports.EventEmitter,this.on=(i,n)=>this.events.on(i,n),this.once=(i,n)=>this.events.once(i,n),this.off=(i,n)=>this.events.off(i,n),this.removeListener=(i,n)=>this.events.removeListener(i,n),this.removeAllListeners=i=>this.events.removeAllListeners(i),this.connect=async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}},this.pair=async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}},this.approve=async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}},this.reject=async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}},this.update=async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}},this.extend=async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}},this.request=async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}},this.respond=async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}},this.ping=async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}},this.emit=async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}},this.disconnect=async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}},this.find=i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}},this.authenticate=async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}},this.formatAuthMessage=i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}},this.approveSessionAuthenticate=async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}},this.rejectSessionAuthenticate=async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}},this.name=e?.name||o1.name,this.metadata=e?.metadata||GE(),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:cs(Dh({level:e?.logger||o1.logger}));this.core=e?.core||new f$(e),this.logger=ui(r,this.name),this.session=new C$(this.core,this.logger),this.proposal=new M$(this.core,this.logger),this.pendingRequest=new D$(this.core,this.logger),this.engine=new I$(this),this.auth=new R$(this.core,this.logger)}static async init(e){const r=new c1(e);return await r.initialize(),r}get context(){return Ai(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"),this.engine.processRelayMessageCache()}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var u1={exports:{}};(function(t,e){var r=typeof self<"u"?self:Vr,i=function(){function s(){this.fetch=!1,this.DOMException=r.DOMException}return s.prototype=r,new s}();(function(s){(function(a){var u={searchParams:"URLSearchParams"in s,iterable:"Symbol"in s&&"iterator"in Symbol,blob:"FileReader"in s&&"Blob"in s&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in s,arrayBuffer:"ArrayBuffer"in s};function h(d){return d&&DataView.prototype.isPrototypeOf(d)}if(u.arrayBuffer)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],b=ArrayBuffer.isView||function(d){return d&&l.indexOf(Object.prototype.toString.call(d))>-1};function w(d){if(typeof d!="string"&&(d=String(d)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(d))throw new TypeError("Invalid character in header field name");return d.toLowerCase()}function I(d){return typeof d!="string"&&(d=String(d)),d}function S(d){var v={next:function(){var E=d.shift();return{done:E===void 0,value:E}}};return u.iterable&&(v[Symbol.iterator]=function(){return v}),v}function D(d){this.map={},d instanceof D?d.forEach(function(v,E){this.append(E,v)},this):Array.isArray(d)?d.forEach(function(v){this.append(v[0],v[1])},this):d&&Object.getOwnPropertyNames(d).forEach(function(v){this.append(v,d[v])},this)}D.prototype.append=function(d,v){d=w(d),v=I(v);var E=this.map[d];this.map[d]=E?E+", "+v:v},D.prototype.delete=function(d){delete this.map[w(d)]},D.prototype.get=function(d){return d=w(d),this.has(d)?this.map[d]:null},D.prototype.has=function(d){return this.map.hasOwnProperty(w(d))},D.prototype.set=function(d,v){this.map[w(d)]=I(v)},D.prototype.forEach=function(d,v){for(var E in this.map)this.map.hasOwnProperty(E)&&d.call(v,this.map[E],E,this)},D.prototype.keys=function(){var d=[];return this.forEach(function(v,E){d.push(E)}),S(d)},D.prototype.values=function(){var d=[];return this.forEach(function(v){d.push(v)}),S(d)},D.prototype.entries=function(){var d=[];return this.forEach(function(v,E){d.push([E,v])}),S(d)},u.iterable&&(D.prototype[Symbol.iterator]=D.prototype.entries);function T(d){if(d.bodyUsed)return Promise.reject(new TypeError("Already read"));d.bodyUsed=!0}function j(d){return new Promise(function(v,E){d.onload=function(){v(d.result)},d.onerror=function(){E(d.error)}})}function K(d){var v=new FileReader,E=j(v);return v.readAsArrayBuffer(d),E}function F(d){var v=new FileReader,E=j(v);return v.readAsText(d),E}function W(d){for(var v=new Uint8Array(d),E=new Array(v.length),C=0;C<v.length;C++)E[C]=String.fromCharCode(v[C]);return E.join("")}function R(d){if(d.slice)return d.slice(0);var v=new Uint8Array(d.byteLength);return v.set(new Uint8Array(d)),v.buffer}function U(){return this.bodyUsed=!1,this._initBody=function(d){this._bodyInit=d,d?typeof d=="string"?this._bodyText=d:u.blob&&Blob.prototype.isPrototypeOf(d)?this._bodyBlob=d:u.formData&&FormData.prototype.isPrototypeOf(d)?this._bodyFormData=d:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(d)?this._bodyText=d.toString():u.arrayBuffer&&u.blob&&h(d)?(this._bodyArrayBuffer=R(d.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(d)||b(d))?this._bodyArrayBuffer=R(d):this._bodyText=d=Object.prototype.toString.call(d):this._bodyText="",this.headers.get("content-type")||(typeof d=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(d)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var d=T(this);if(d)return d;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?T(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(K)}),this.text=function(){var d=T(this);if(d)return d;if(this._bodyBlob)return F(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(W(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(ee)}),this.json=function(){return this.text().then(JSON.parse)},this}var H=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function _(d){var v=d.toUpperCase();return H.indexOf(v)>-1?v:d}function B(d,v){v=v||{};var E=v.body;if(d instanceof B){if(d.bodyUsed)throw new TypeError("Already read");this.url=d.url,this.credentials=d.credentials,v.headers||(this.headers=new D(d.headers)),this.method=d.method,this.mode=d.mode,this.signal=d.signal,!E&&d._bodyInit!=null&&(E=d._bodyInit,d.bodyUsed=!0)}else this.url=String(d);if(this.credentials=v.credentials||this.credentials||"same-origin",(v.headers||!this.headers)&&(this.headers=new D(v.headers)),this.method=_(v.method||this.method||"GET"),this.mode=v.mode||this.mode||null,this.signal=v.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&E)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(E)}B.prototype.clone=function(){return new B(this,{body:this._bodyInit})};function ee(d){var v=new FormData;return d.trim().split("&").forEach(function(E){if(E){var C=E.split("="),O=C.shift().replace(/\+/g," "),M=C.join("=").replace(/\+/g," ");v.append(decodeURIComponent(O),decodeURIComponent(M))}}),v}function ie(d){var v=new D,E=d.replace(/\r?\n[\t ]+/g," ");return E.split(/\r?\n/).forEach(function(C){var O=C.split(":"),M=O.shift().trim();if(M){var g=O.join(":").trim();v.append(M,g)}}),v}U.call(B.prototype);function L(d,v){v||(v={}),this.type="default",this.status=v.status===void 0?200:v.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in v?v.statusText:"OK",this.headers=new D(v.headers),this.url=v.url||"",this._initBody(d)}U.call(L.prototype),L.prototype.clone=function(){return new L(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new D(this.headers),url:this.url})},L.error=function(){var d=new L(null,{status:0,statusText:""});return d.type="error",d};var y=[301,302,303,307,308];L.redirect=function(d,v){if(y.indexOf(v)===-1)throw new RangeError("Invalid status code");return new L(null,{status:v,headers:{location:d}})},a.DOMException=s.DOMException;try{new a.DOMException}catch{a.DOMException=function(v,E){this.message=v,this.name=E;var C=Error(v);this.stack=C.stack},a.DOMException.prototype=Object.create(Error.prototype),a.DOMException.prototype.constructor=a.DOMException}function f(d,v){return new Promise(function(E,C){var O=new B(d,v);if(O.signal&&O.signal.aborted)return C(new a.DOMException("Aborted","AbortError"));var M=new XMLHttpRequest;function g(){M.abort()}M.onload=function(){var m={status:M.status,statusText:M.statusText,headers:ie(M.getAllResponseHeaders()||"")};m.url="responseURL"in M?M.responseURL:m.headers.get("X-Request-URL");var N="response"in M?M.response:M.responseText;E(new L(N,m))},M.onerror=function(){C(new TypeError("Network request failed"))},M.ontimeout=function(){C(new TypeError("Network request failed"))},M.onabort=function(){C(new a.DOMException("Aborted","AbortError"))},M.open(O.method,O.url,!0),O.credentials==="include"?M.withCredentials=!0:O.credentials==="omit"&&(M.withCredentials=!1),"responseType"in M&&u.blob&&(M.responseType="blob"),O.headers.forEach(function(m,N){M.setRequestHeader(N,m)}),O.signal&&(O.signal.addEventListener("abort",g),M.onreadystatechange=function(){M.readyState===4&&O.signal.removeEventListener("abort",g)}),M.send(typeof O._bodyInit>"u"?null:O._bodyInit)})}return f.polyfill=!0,s.fetch||(s.fetch=f,s.Headers=D,s.Request=B,s.Response=L),a.Headers=D,a.Request=B,a.Response=L,a.fetch=f,Object.defineProperty(a,"__esModule",{value:!0}),a})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var n=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})(u1,u1.exports);var V3=q5(u1.exports),N$=Object.defineProperty,T$=Object.defineProperties,L$=Object.getOwnPropertyDescriptors,G3=Object.getOwnPropertySymbols,B$=Object.prototype.hasOwnProperty,F$=Object.prototype.propertyIsEnumerable,Y3=(t,e,r)=>e in t?N$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,J3=(t,e)=>{for(var r in e||(e={}))B$.call(e,r)&&Y3(t,r,e[r]);if(G3)for(var r of G3(e))F$.call(e,r)&&Y3(t,r,e[r]);return t},Q3=(t,e)=>T$(t,L$(e));const k$={Accept:"application/json","Content-Type":"application/json"},U$="POST",Z3={headers:k$,method:U$},X3=10;class gs{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new Ur.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!Jb(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=Cs(e),i=await(await V3(this.url,Q3(J3({},Z3),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!Jb(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=Cs({id:1,jsonrpc:"2.0",method:"test",params:[]});await V3(e,Q3(J3({},Z3),{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"?jo(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=Ph(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return Hb(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>X3&&this.events.setMaxListeners(X3)}}const e6="error",j$="wss://relay.walletconnect.com",q$="wc",z$="universal_provider",t6=`${q$}@2:${z$}:`,H$="https://rpc.walletconnect.com/v1/",dc="generic",Cn={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Uu=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},f1={exports:{}};/**
|
|
43
|
+
***************************************************************************** */var Gd=function(t,e){return Gd=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])},Gd(t,e)};function TC(t,e){Gd(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Yd=function(){return Yd=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},Yd.apply(this,arguments)};function LC(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 BC(t,e,r,i){var n=arguments.length,s=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,i);else for(var u=t.length-1;u>=0;u--)(a=t[u])&&(s=(n<3?a(s):n>3?a(e,r,s):a(e,r))||s);return n>3&&s&&Object.defineProperty(e,r,s),s}function FC(t,e){return function(r,i){e(r,i,t)}}function kC(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function UC(t,e,r,i){function n(s){return s instanceof r?s:new r(function(a){a(s)})}return new(r||(r=Promise))(function(s,a){function u(b){try{l(i.next(b))}catch(w){a(w)}}function h(b){try{l(i.throw(b))}catch(w){a(w)}}function l(b){b.done?s(b.value):n(b.value).then(u,h)}l((i=i.apply(t,e||[])).next())})}function jC(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,a;return a={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function u(l){return function(b){return h([l,b])}}function h(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(b){l=[6,b],n=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function qC(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function zC(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Jd(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 Wb(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),n,s=[],a;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(u){a={error:u}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(a)throw a.error}}return s}function HC(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Wb(arguments[e]));return t}function KC(){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],a=0,u=s.length;a<u;a++,n++)i[n]=s[a];return i}function Ru(t){return this instanceof Ru?(this.v=t,this):new Ru(t)}function WC(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),n,s=[];return n={},a("next"),a("throw"),a("return"),n[Symbol.asyncIterator]=function(){return this},n;function a(I){i[I]&&(n[I]=function(S){return new Promise(function(D,T){s.push([I,S,D,T])>1||u(I,S)})})}function u(I,S){try{h(i[I](S))}catch(D){w(s[0][3],D)}}function h(I){I.value instanceof Ru?Promise.resolve(I.value.v).then(l,b):w(s[0][2],I)}function l(I){u("next",I)}function b(I){u("throw",I)}function w(I,S){I(S),s.shift(),s.length&&u(s[0][0],s[0][1])}}function VC(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(a){return(r=!r)?{value:Ru(t[n](a)),done:n==="return"}:s?s(a):a}:s}}function GC(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 Jd=="function"?Jd(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(a){return new Promise(function(u,h){a=t[s](a),n(u,h,a.done,a.value)})}}function n(s,a,u,h){Promise.resolve(h).then(function(l){s({value:l,done:u})},a)}}function YC(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function JC(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 QC(t){return t&&t.__esModule?t:{default:t}}function ZC(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function XC(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 eD=Object.freeze({__proto__:null,__extends:TC,get __assign(){return Yd},__rest:LC,__decorate:BC,__param:FC,__metadata:kC,__awaiter:UC,__generator:jC,__createBinding:qC,__exportStar:zC,__values:Jd,__read:Wb,__spread:HC,__spreadArrays:KC,__await:Ru,__asyncGenerator:WC,__asyncDelegator:VC,__asyncValues:GC,__makeTemplateObject:YC,__importStar:JC,__importDefault:QC,__classPrivateFieldGet:ZC,__classPrivateFieldSet:XC}),tD=m0(eD),Ts={},Vb;function rD(){if(Vb)return Ts;Vb=1,Object.defineProperty(Ts,"__esModule",{value:!0}),Ts.isBrowserCryptoAvailable=Ts.getSubtleCrypto=Ts.getBrowerCrypto=void 0;function t(){return Vr?.crypto||Vr?.msCrypto||{}}Ts.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}Ts.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Ts.isBrowserCryptoAvailable=r,Ts}var Ls={},Gb;function iD(){if(Gb)return Ls;Gb=1,Object.defineProperty(Ls,"__esModule",{value:!0}),Ls.isBrowser=Ls.isNode=Ls.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ls.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Ls.isNode=e;function r(){return!t()&&!e()}return Ls.isBrowser=r,Ls}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=tD;e.__exportStar(rD(),t),e.__exportStar(iD(),t)})(Kb);function co(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Jo(t=6){return BigInt(co(t))}function Qo(t,e,r){return{id:r||co(),jsonrpc:"2.0",method:t,params:e}}function Oh(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Ph(t,e,r){return{id:t,jsonrpc:"2.0",error:nD(e,r)}}function nD(t,e){return typeof t>"u"?zb(jb):(typeof t=="string"&&(t=Object.assign(Object.assign({},zb(Vd)),{message:t})),typeof e<"u"&&(t.data=e),RC(t.code)&&(t=NC(t.code)),t)}class sD{}class oD extends sD{constructor(){super()}}class aD extends oD{constructor(e){super()}}const cD="^https?:",uD="^wss?:";function fD(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Yb(t,e){const r=fD(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Jb(t){return Yb(t,cD)}function Qb(t){return Yb(t,uD)}function hD(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Zb(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Qd(t){return Zb(t)&&"method"in t}function $h(t){return Zb(t)&&(fs(t)||rn(t))}function fs(t){return"result"in t}function rn(t){return"error"in t}class xn extends aD{constructor(e){super(e),this.events=new Ur.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(Qo(e.method,e.params||[],e.id||Jo().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=>{rn(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),$h(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 lD=()=>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"),dD=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Xb=t=>t.split("?")[0],e3=10,pD=lD();class gD{constructor(e){if(this.url=e,this.events=new Ur.exports.EventEmitter,this.registering=!1,!Qb(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(Cs(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Qb(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=new URLSearchParams(e).get("origin"),s=Kb.isReactNative()?{headers:{origin:n}}:{rejectUnauthorized:!hD(e)},a=new pD(e,[],s);dD()?a.onerror=u=>{const h=u;i(this.emitError(h.error))}:a.on("error",u=>{i(this.emitError(u))}),a.onopen=()=>{this.onOpen(a),r(a)}})}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"?jo(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=Ph(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return Hb(e,Xb(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>e3&&this.events.setMaxListeners(e3)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Xb(this.url)}`));return this.events.emit("register_error",r),r}}var Zd={exports:{}};(function(t,e){var r=200,i="__lodash_hash_undefined__",n=1,s=2,a=9007199254740991,u="[object Arguments]",h="[object Array]",l="[object AsyncFunction]",b="[object Boolean]",w="[object Date]",I="[object Error]",S="[object Function]",D="[object GeneratorFunction]",T="[object Map]",j="[object Number]",K="[object Null]",F="[object Object]",W="[object Promise]",R="[object Proxy]",U="[object RegExp]",H="[object Set]",_="[object String]",B="[object Symbol]",ee="[object Undefined]",ie="[object WeakMap]",L="[object ArrayBuffer]",y="[object DataView]",f="[object Float32Array]",d="[object Float64Array]",v="[object Int8Array]",E="[object Int16Array]",C="[object Int32Array]",O="[object Uint8Array]",M="[object Uint8ClampedArray]",g="[object Uint16Array]",m="[object Uint32Array]",N=/[\\^$.*+?()[\]{}|]/g,X=/^\[object .+?Constructor\]$/,ae=/^(?:0|[1-9]\d*)$/,P={};P[f]=P[d]=P[v]=P[E]=P[C]=P[O]=P[M]=P[g]=P[m]=!0,P[u]=P[h]=P[L]=P[b]=P[y]=P[w]=P[I]=P[S]=P[T]=P[j]=P[F]=P[U]=P[H]=P[_]=P[ie]=!1;var te=typeof Vr=="object"&&Vr&&Vr.Object===Object&&Vr,z=typeof self=="object"&&self&&self.Object===Object&&self,G=te||z||Function("return this")(),Y=e&&!e.nodeType&&e,A=Y&&!0&&t&&!t.nodeType&&t,V=A&&A.exports===Y,oe=V&&te.process,ue=function(){try{return oe&&oe.binding&&oe.binding("util")}catch{}}(),he=ue&&ue.isTypedArray;function ye(J,re){for(var pe=-1,Ue=J==null?0:J.length,er=0,bt=[];++pe<Ue;){var ar=J[pe];re(ar,pe,J)&&(bt[er++]=ar)}return bt}function we(J,re){for(var pe=-1,Ue=re.length,er=J.length;++pe<Ue;)J[er+pe]=re[pe];return J}function Re(J,re){for(var pe=-1,Ue=J==null?0:J.length;++pe<Ue;)if(re(J[pe],pe,J))return!0;return!1}function Xe(J,re){for(var pe=-1,Ue=Array(J);++pe<J;)Ue[pe]=re(pe);return Ue}function Oe(J){return function(re){return J(re)}}function Ne(J,re){return J.has(re)}function Me(J,re){return J?.[re]}function be(J){var re=-1,pe=Array(J.size);return J.forEach(function(Ue,er){pe[++re]=[er,Ue]}),pe}function Pe(J,re){return function(pe){return J(re(pe))}}function Te(J){var re=-1,pe=Array(J.size);return J.forEach(function(Ue){pe[++re]=Ue}),pe}var ve=Array.prototype,$e=Function.prototype,Se=Object.prototype,me=G["__core-js_shared__"],ke=$e.toString,Ce=Se.hasOwnProperty,_e=function(){var J=/[^.]+$/.exec(me&&me.keys&&me.keys.IE_PROTO||"");return J?"Symbol(src)_1."+J:""}(),Ke=Se.toString,Ve=RegExp("^"+ke.call(Ce).replace(N,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ae=V?G.Buffer:void 0,We=G.Symbol,pt=G.Uint8Array,Ge=Se.propertyIsEnumerable,It=ve.splice,gt=We?We.toStringTag:void 0,Je=Object.getOwnPropertySymbols,Ot=Ae?Ae.isBuffer:void 0,Tt=Pe(Object.keys,Object),Le=qi(G,"DataView"),et=qi(G,"Map"),it=qi(G,"Promise"),Be=qi(G,"Set"),rt=qi(G,"WeakMap"),tt=qi(Object,"create"),je=js(Le),ht=js(et),nt=js(it),qe=js(Be),st=js(rt),at=We?We.prototype:void 0,Fe=at?at.valueOf:void 0;function Ze(J){var re=-1,pe=J==null?0:J.length;for(this.clear();++re<pe;){var Ue=J[re];this.set(Ue[0],Ue[1])}}function lt(){this.__data__=tt?tt(null):{},this.size=0}function ze(J){var re=this.has(J)&&delete this.__data__[J];return this.size-=re?1:0,re}function jt(J){var re=this.__data__;if(tt){var pe=re[J];return pe===i?void 0:pe}return Ce.call(re,J)?re[J]:void 0}function qt(J){var re=this.__data__;return tt?re[J]!==void 0:Ce.call(re,J)}function ct(J,re){var pe=this.__data__;return this.size+=this.has(J)?0:1,pe[J]=tt&&re===void 0?i:re,this}Ze.prototype.clear=lt,Ze.prototype.delete=ze,Ze.prototype.get=jt,Ze.prototype.has=qt,Ze.prototype.set=ct;function _t(J){var re=-1,pe=J==null?0:J.length;for(this.clear();++re<pe;){var Ue=J[re];this.set(Ue[0],Ue[1])}}function Zr(){this.__data__=[],this.size=0}function Xr(J){var re=this.__data__,pe=ma(re,J);if(pe<0)return!1;var Ue=re.length-1;return pe==Ue?re.pop():It.call(re,pe,1),--this.size,!0}function ei(J){var re=this.__data__,pe=ma(re,J);return pe<0?void 0:re[pe][1]}function ti(J){return ma(this.__data__,J)>-1}function ri(J,re){var pe=this.__data__,Ue=ma(pe,J);return Ue<0?(++this.size,pe.push([J,re])):pe[Ue][1]=re,this}_t.prototype.clear=Zr,_t.prototype.delete=Xr,_t.prototype.get=ei,_t.prototype.has=ti,_t.prototype.set=ri;function vr(J){var re=-1,pe=J==null?0:J.length;for(this.clear();++re<pe;){var Ue=J[re];this.set(Ue[0],Ue[1])}}function Ii(){this.size=0,this.__data__={hash:new Ze,map:new(et||_t),string:new Ze}}function On(J){var re=Eo(this,J).delete(J);return this.size-=re?1:0,re}function Mi(J){return Eo(this,J).get(J)}function Pn(J){return Eo(this,J).has(J)}function $n(J,re){var pe=Eo(this,J),Ue=pe.size;return pe.set(J,re),this.size+=pe.size==Ue?0:1,this}vr.prototype.clear=Ii,vr.prototype.delete=On,vr.prototype.get=Mi,vr.prototype.has=Pn,vr.prototype.set=$n;function Ci(J){var re=-1,pe=J==null?0:J.length;for(this.__data__=new vr;++re<pe;)this.add(J[re])}function an(J){return this.__data__.set(J,i),this}function cn(J){return this.__data__.has(J)}Ci.prototype.add=Ci.prototype.push=an,Ci.prototype.has=cn;function Cr(J){var re=this.__data__=new _t(J);this.size=re.size}function Rn(){this.__data__=new _t,this.size=0}function Nn(J){var re=this.__data__,pe=re.delete(J);return this.size=re.size,pe}function Tn(J){return this.__data__.get(J)}function va(J){return this.__data__.has(J)}function gl(J,re){var pe=this.__data__;if(pe instanceof _t){var Ue=pe.__data__;if(!et||Ue.length<r-1)return Ue.push([J,re]),this.size=++pe.size,this;pe=this.__data__=new vr(Ue)}return pe.set(J,re),this.size=pe.size,this}Cr.prototype.clear=Rn,Cr.prototype.delete=Nn,Cr.prototype.get=Tn,Cr.prototype.has=va,Cr.prototype.set=gl;function vl(J,re){var pe=Nc(J),Ue=!pe&&Cl(J),er=!pe&&!Ue&&uf(J),bt=!pe&&!Ue&&!er&&Pl(J),ar=pe||Ue||er||bt,xr=ar?Xe(J.length,String):[],Ft=xr.length;for(var tr in J)(re||Ce.call(J,tr))&&!(ar&&(tr=="length"||er&&(tr=="offset"||tr=="parent")||bt&&(tr=="buffer"||tr=="byteLength"||tr=="byteOffset")||Al(tr,Ft)))&&xr.push(tr);return xr}function ma(J,re){for(var pe=J.length;pe--;)if(Ml(J[pe][0],re))return pe;return-1}function af(J,re,pe){var Ue=re(J);return Nc(J)?Ue:we(Ue,pe(J))}function ba(J){return J==null?J===void 0?ee:K:gt&> in Object(J)?_l(J):Cp(J)}function cf(J){return wa(J)&&ba(J)==u}function ya(J,re,pe,Ue,er){return J===re?!0:J==null||re==null||!wa(J)&&!wa(re)?J!==J&&re!==re:ml(J,re,pe,Ue,ya,er)}function ml(J,re,pe,Ue,er,bt){var ar=Nc(J),xr=Nc(re),Ft=ar?h:ws(J),tr=xr?h:ws(re);Ft=Ft==u?F:Ft,tr=tr==u?F:tr;var _r=Ft==F,Di=tr==F,Sr=Ft==tr;if(Sr&&uf(J)){if(!uf(re))return!1;ar=!0,_r=!1}if(Sr&&!_r)return bt||(bt=new Cr),ar||Pl(J)?$c(J,re,pe,Ue,er,bt):Mp(J,re,Ft,pe,Ue,er,bt);if(!(pe&n)){var cr=_r&&Ce.call(J,"__wrapped__"),di=Di&&Ce.call(re,"__wrapped__");if(cr||di){var Ln=cr?J.value():J,un=di?re.value():re;return bt||(bt=new Cr),er(Ln,un,pe,Ue,bt)}}return Sr?(bt||(bt=new Cr),wl(J,re,pe,Ue,er,bt)):!1}function Ip(J){if(!Ol(J)||Sl(J))return!1;var re=Tc(J)?Ve:X;return re.test(js(J))}function bl(J){return wa(J)&&Dl(J.length)&&!!P[ba(J)]}function yl(J){if(!Il(J))return Tt(J);var re=[];for(var pe in Object(J))Ce.call(J,pe)&&pe!="constructor"&&re.push(pe);return re}function $c(J,re,pe,Ue,er,bt){var ar=pe&n,xr=J.length,Ft=re.length;if(xr!=Ft&&!(ar&&Ft>xr))return!1;var tr=bt.get(J);if(tr&&bt.get(re))return tr==re;var _r=-1,Di=!0,Sr=pe&s?new Ci:void 0;for(bt.set(J,re),bt.set(re,J);++_r<xr;){var cr=J[_r],di=re[_r];if(Ue)var Ln=ar?Ue(di,cr,_r,re,J,bt):Ue(cr,di,_r,J,re,bt);if(Ln!==void 0){if(Ln)continue;Di=!1;break}if(Sr){if(!Re(re,function(un,_s){if(!Ne(Sr,_s)&&(cr===un||er(cr,un,pe,Ue,bt)))return Sr.push(_s)})){Di=!1;break}}else if(!(cr===di||er(cr,di,pe,Ue,bt))){Di=!1;break}}return bt.delete(J),bt.delete(re),Di}function Mp(J,re,pe,Ue,er,bt,ar){switch(pe){case y:if(J.byteLength!=re.byteLength||J.byteOffset!=re.byteOffset)return!1;J=J.buffer,re=re.buffer;case L:return!(J.byteLength!=re.byteLength||!bt(new pt(J),new pt(re)));case b:case w:case j:return Ml(+J,+re);case I:return J.name==re.name&&J.message==re.message;case U:case _:return J==re+"";case T:var xr=be;case H:var Ft=Ue&n;if(xr||(xr=Te),J.size!=re.size&&!Ft)return!1;var tr=ar.get(J);if(tr)return tr==re;Ue|=s,ar.set(J,re);var _r=$c(xr(J),xr(re),Ue,er,bt,ar);return ar.delete(J),_r;case B:if(Fe)return Fe.call(J)==Fe.call(re)}return!1}function wl(J,re,pe,Ue,er,bt){var ar=pe&n,xr=Rc(J),Ft=xr.length,tr=Rc(re),_r=tr.length;if(Ft!=_r&&!ar)return!1;for(var Di=Ft;Di--;){var Sr=xr[Di];if(!(ar?Sr in re:Ce.call(re,Sr)))return!1}var cr=bt.get(J);if(cr&&bt.get(re))return cr==re;var di=!0;bt.set(J,re),bt.set(re,J);for(var Ln=ar;++Di<Ft;){Sr=xr[Di];var un=J[Sr],_s=re[Sr];if(Ue)var ff=ar?Ue(_s,un,Sr,re,J,bt):Ue(un,_s,Sr,J,re,bt);if(!(ff===void 0?un===_s||er(un,_s,pe,Ue,bt):ff)){di=!1;break}Ln||(Ln=Sr=="constructor")}if(di&&!Ln){var _a=J.constructor,Fr=re.constructor;_a!=Fr&&"constructor"in J&&"constructor"in re&&!(typeof _a=="function"&&_a instanceof _a&&typeof Fr=="function"&&Fr instanceof Fr)&&(di=!1)}return bt.delete(J),bt.delete(re),di}function Rc(J){return af(J,Pp,El)}function Eo(J,re){var pe=J.__data__;return xl(re)?pe[typeof re=="string"?"string":"hash"]:pe.map}function qi(J,re){var pe=Me(J,re);return Ip(pe)?pe:void 0}function _l(J){var re=Ce.call(J,gt),pe=J[gt];try{J[gt]=void 0;var Ue=!0}catch{}var er=Ke.call(J);return Ue&&(re?J[gt]=pe:delete J[gt]),er}var El=Je?function(J){return J==null?[]:(J=Object(J),ye(Je(J),function(re){return Ge.call(J,re)}))}:Xt,ws=ba;(Le&&ws(new Le(new ArrayBuffer(1)))!=y||et&&ws(new et)!=T||it&&ws(it.resolve())!=W||Be&&ws(new Be)!=H||rt&&ws(new rt)!=ie)&&(ws=function(J){var re=ba(J),pe=re==F?J.constructor:void 0,Ue=pe?js(pe):"";if(Ue)switch(Ue){case je:return y;case ht:return T;case nt:return W;case qe:return H;case st:return ie}return re});function Al(J,re){return re=re??a,!!re&&(typeof J=="number"||ae.test(J))&&J>-1&&J%1==0&&J<re}function xl(J){var re=typeof J;return re=="string"||re=="number"||re=="symbol"||re=="boolean"?J!=="__proto__":J===null}function Sl(J){return!!_e&&_e in J}function Il(J){var re=J&&J.constructor,pe=typeof re=="function"&&re.prototype||Se;return J===pe}function Cp(J){return Ke.call(J)}function js(J){if(J!=null){try{return ke.call(J)}catch{}try{return J+""}catch{}}return""}function Ml(J,re){return J===re||J!==J&&re!==re}var Cl=cf(function(){return arguments}())?cf:function(J){return wa(J)&&Ce.call(J,"callee")&&!Ge.call(J,"callee")},Nc=Array.isArray;function Dp(J){return J!=null&&Dl(J.length)&&!Tc(J)}var uf=Ot||Qt;function Op(J,re){return ya(J,re)}function Tc(J){if(!Ol(J))return!1;var re=ba(J);return re==S||re==D||re==l||re==R}function Dl(J){return typeof J=="number"&&J>-1&&J%1==0&&J<=a}function Ol(J){var re=typeof J;return J!=null&&(re=="object"||re=="function")}function wa(J){return J!=null&&typeof J=="object"}var Pl=he?Oe(he):bl;function Pp(J){return Dp(J)?vl(J):yl(J)}function Xt(){return[]}function Qt(){return!1}t.exports=Op})(Zd,Zd.exports);var vD=Zd.exports,mD=Object.defineProperty,t3=Object.getOwnPropertySymbols,bD=Object.prototype.hasOwnProperty,yD=Object.prototype.propertyIsEnumerable,r3=(t,e,r)=>e in t?mD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fi=(t,e)=>{for(var r in e||(e={}))bD.call(e,r)&&r3(t,r,e[r]);if(t3)for(var r of t3(e))yD.call(e,r)&&r3(t,r,e[r]);return t};function wD(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),a=s.charCodeAt(0);if(r[a]!==255)throw new TypeError(s+" is ambiguous");r[a]=n}var u=t.length,h=t.charAt(0),l=Math.log(u)/Math.log(256),b=Math.log(256)/Math.log(u);function w(D){if(D instanceof Uint8Array||(ArrayBuffer.isView(D)?D=new Uint8Array(D.buffer,D.byteOffset,D.byteLength):Array.isArray(D)&&(D=Uint8Array.from(D))),!(D instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(D.length===0)return"";for(var T=0,j=0,K=0,F=D.length;K!==F&&D[K]===0;)K++,T++;for(var W=(F-K)*b+1>>>0,R=new Uint8Array(W);K!==F;){for(var U=D[K],H=0,_=W-1;(U!==0||H<j)&&_!==-1;_--,H++)U+=256*R[_]>>>0,R[_]=U%u>>>0,U=U/u>>>0;if(U!==0)throw new Error("Non-zero carry");j=H,K++}for(var B=W-j;B!==W&&R[B]===0;)B++;for(var ee=h.repeat(T);B<W;++B)ee+=t.charAt(R[B]);return ee}function I(D){if(typeof D!="string")throw new TypeError("Expected String");if(D.length===0)return new Uint8Array;var T=0;if(D[T]!==" "){for(var j=0,K=0;D[T]===h;)j++,T++;for(var F=(D.length-T)*l+1>>>0,W=new Uint8Array(F);D[T];){var R=r[D.charCodeAt(T)];if(R===255)return;for(var U=0,H=F-1;(R!==0||U<K)&&H!==-1;H--,U++)R+=u*W[H]>>>0,W[H]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");K=U,T++}if(D[T]!==" "){for(var _=F-K;_!==F&&W[_]===0;)_++;for(var B=new Uint8Array(j+(F-_)),ee=j;_!==F;)B[ee++]=W[_++];return B}}}function S(D){var T=I(D);if(T)return T;throw new Error(`Non-${e} character`)}return{encode:w,decodeUnsafe:I,decode:S}}var _D=wD,ED=_D;const i3=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")},AD=t=>new TextEncoder().encode(t),xD=t=>new TextDecoder().decode(t);class SD{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 ID{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 n3(this,e)}}class MD{constructor(e){this.decoders=e}or(e){return n3(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 n3=(t,e)=>new MD(fi(fi({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class CD{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new SD(e,r,i),this.decoder=new ID(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Rh=({name:t,prefix:e,encode:r,decode:i})=>new CD(t,e,r,i),Nu=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=ED(r,e);return Rh({prefix:t,name:e,encode:i,decode:s=>i3(n(s))})},DD=(t,e,r,i)=>{const n={};for(let b=0;b<e.length;++b)n[e[b]]=b;let s=t.length;for(;t[s-1]==="=";)--s;const a=new Uint8Array(s*r/8|0);let u=0,h=0,l=0;for(let b=0;b<s;++b){const w=n[t[b]];if(w===void 0)throw new SyntaxError(`Non-${i} character`);h=h<<r|w,u+=r,u>=8&&(u-=8,a[l++]=255&h>>u)}if(u>=r||255&h<<8-u)throw new SyntaxError("Unexpected end of data");return a},OD=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",a=0,u=0;for(let h=0;h<t.length;++h)for(u=u<<8|t[h],a+=8;a>r;)a-=r,s+=e[n&u>>a];if(a&&(s+=e[n&u<<r-a]),i)for(;s.length*r&7;)s+="=";return s},Kr=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Rh({prefix:e,name:t,encode(n){return OD(n,i,r)},decode(n){return DD(n,i,r,t)}}),PD=Rh({prefix:"\0",name:"identity",encode:t=>xD(t),decode:t=>AD(t)});var $D=Object.freeze({__proto__:null,identity:PD});const RD=Kr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ND=Object.freeze({__proto__:null,base2:RD});const TD=Kr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var LD=Object.freeze({__proto__:null,base8:TD});const BD=Nu({prefix:"9",name:"base10",alphabet:"0123456789"});var FD=Object.freeze({__proto__:null,base10:BD});const kD=Kr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),UD=Kr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var jD=Object.freeze({__proto__:null,base16:kD,base16upper:UD});const qD=Kr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),zD=Kr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),HD=Kr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),KD=Kr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),WD=Kr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),VD=Kr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),GD=Kr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),YD=Kr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),JD=Kr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var QD=Object.freeze({__proto__:null,base32:qD,base32upper:zD,base32pad:HD,base32padupper:KD,base32hex:WD,base32hexupper:VD,base32hexpad:GD,base32hexpadupper:YD,base32z:JD});const ZD=Nu({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),XD=Nu({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var eO=Object.freeze({__proto__:null,base36:ZD,base36upper:XD});const tO=Nu({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),rO=Nu({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var iO=Object.freeze({__proto__:null,base58btc:tO,base58flickr:rO});const nO=Kr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),sO=Kr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),oO=Kr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),aO=Kr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var cO=Object.freeze({__proto__:null,base64:nO,base64pad:sO,base64url:oO,base64urlpad:aO});const s3=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}"),uO=s3.reduce((t,e,r)=>(t[r]=e,t),[]),fO=s3.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function hO(t){return t.reduce((e,r)=>(e+=uO[r],e),"")}function lO(t){const e=[];for(const r of t){const i=fO[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const dO=Rh({prefix:"\u{1F680}",name:"base256emoji",encode:hO,decode:lO});var pO=Object.freeze({__proto__:null,base256emoji:dO}),gO=a3,o3=128,vO=127,mO=~vO,bO=Math.pow(2,31);function a3(t,e,r){e=e||[],r=r||0;for(var i=r;t>=bO;)e[r++]=t&255|o3,t/=128;for(;t&mO;)e[r++]=t&255|o3,t>>>=7;return e[r]=t|0,a3.bytes=r-i+1,e}var yO=Xd,wO=128,c3=127;function Xd(t,i){var r=0,i=i||0,n=0,s=i,a,u=t.length;do{if(s>=u)throw Xd.bytes=0,new RangeError("Could not decode varint");a=t[s++],r+=n<28?(a&c3)<<n:(a&c3)*Math.pow(2,n),n+=7}while(a>=wO);return Xd.bytes=s-i,r}var _O=Math.pow(2,7),EO=Math.pow(2,14),AO=Math.pow(2,21),xO=Math.pow(2,28),SO=Math.pow(2,35),IO=Math.pow(2,42),MO=Math.pow(2,49),CO=Math.pow(2,56),DO=Math.pow(2,63),OO=function(t){return t<_O?1:t<EO?2:t<AO?3:t<xO?4:t<SO?5:t<IO?6:t<MO?7:t<CO?8:t<DO?9:10},PO={encode:gO,decode:yO,encodingLength:OO},u3=PO;const f3=(t,e,r=0)=>(u3.encode(t,e,r),e),h3=t=>u3.encodingLength(t),e1=(t,e)=>{const r=e.byteLength,i=h3(t),n=i+h3(r),s=new Uint8Array(n+r);return f3(t,s,0),f3(r,s,i),s.set(e,n),new $O(t,r,e,s)};class $O{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const l3=({name:t,code:e,encode:r})=>new RO(t,e,r);class RO{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?e1(this.code,r):r.then(i=>e1(this.code,i))}else throw Error("Unknown type, must be binary type")}}const d3=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),NO=l3({name:"sha2-256",code:18,encode:d3("SHA-256")}),TO=l3({name:"sha2-512",code:19,encode:d3("SHA-512")});var LO=Object.freeze({__proto__:null,sha256:NO,sha512:TO});const p3=0,BO="identity",g3=i3;var FO=Object.freeze({__proto__:null,identity:{code:p3,name:BO,encode:g3,digest:t=>e1(p3,g3(t))}});new TextEncoder,new TextDecoder;const v3=fi(fi(fi(fi(fi(fi(fi(fi(fi(fi({},$D),ND),LD),FD),jD),QD),eO),iO),cO),pO);fi(fi({},LO),FO);function kO(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function m3(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const b3=m3("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),t1=m3("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=kO(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),UO=fi({utf8:b3,"utf-8":b3,hex:v3.base16,latin1:t1,ascii:t1,binary:t1},v3);function jO(t,e="utf8"){const r=UO[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}`)}const y3="wc",w3=2,r1="core",hs=`${y3}@2:${r1}:`,qO={name:r1,logger:"error"},zO={database:":memory:"},HO="crypto",_3="client_ed25519_seed",KO=xe.ONE_DAY,WO="keychain",VO="0.3",GO="messages",YO="0.3",JO=xe.SIX_HOURS,QO="publisher",E3="irn",ZO="error",A3="wss://relay.walletconnect.org",XO="relayer",hi={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"},eP="_subscription",nn={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},tP=.1,x3="2.16.1",Zt={link_mode:"link_mode",relay:"relay"},rP="0.3",iP="WALLETCONNECT_CLIENT_ID",S3="WALLETCONNECT_LINK_MODE_APPS",ls={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},nP="subscription",sP="0.3",oP=xe.FIVE_SECONDS*1e3,aP="pairing",cP="0.3",Tu={wc_pairingDelete:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:xe.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:xe.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:0},res:{ttl:xe.ONE_DAY,prompt:!1,tag:0}}},fc={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Sn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},uP="history",fP="0.3",hP="expirer",sn={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},lP="0.3",dP="verify-api",pP="https://verify.walletconnect.com",I3="https://verify.walletconnect.org",Lu=I3,gP=`${Lu}/v3`,vP=[pP,I3],mP="echo",bP="https://echo.walletconnect.com",ds={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"},Bs={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"},In={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"},Zo={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"},Xo={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"},Bu={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"},yP=.1,wP="event-client",_P=86400,EP="https://pulse.walletconnect.com/batch";class AP{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=WO,this.version=VO,this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}},this.has=i=>(this.isInitialized(),this.keychain.has(i)),this.set=async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()},this.get=i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=Ee("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n},this.del=async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()},this.core=e,this.logger=ui(r,this.name)}get context(){return Ai(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,q2(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?z2(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class xP{constructor(e,r,i){this.core=e,this.logger=r,this.name=HO,this.randomSessionIdentifier=Rd(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=n=>(this.isInitialized(),this.keychain.has(n)),this.getClientId=async()=>{this.isInitialized();const n=await this.getClientSeed(),s=L2(n);return T2(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const n=nI();return this.setPrivateKey(n.publicKey,n.privateKey)},this.signJWT=async n=>{this.isInitialized();const s=await this.getClientSeed(),a=L2(s),u=this.randomSessionIdentifier;return await FE(u,n,KO,a)},this.generateSharedKey=(n,s,a)=>{this.isInitialized();const u=this.getPrivateKey(n),h=sI(u,s);return this.setSymKey(h,a)},this.setSymKey=async(n,s)=>{this.isInitialized();const a=s||bh(n);return await this.keychain.set(a,n),a},this.deleteKeyPair=async n=>{this.isInitialized(),await this.keychain.del(n)},this.deleteSymKey=async n=>{this.isInitialized(),await this.keychain.del(n)},this.encode=async(n,s,a)=>{this.isInitialized();const u=fb(a),h=Cs(s);if(lb(u))return aI(h,a?.encoding);if(hb(u)){const I=u.senderPublicKey,S=u.receiverPublicKey;n=await this.generateSharedKey(I,S)}const l=this.getSymKey(n),{type:b,senderPublicKey:w}=u;return oI({type:b,symKey:l,message:h,senderPublicKey:w,encoding:a?.encoding})},this.decode=async(n,s,a)=>{this.isInitialized();const u=fI(s,a);if(lb(u)){const h=uI(s,a?.encoding);return jo(h)}if(hb(u)){const h=u.receiverPublicKey,l=u.senderPublicKey;n=await this.generateSharedKey(h,l)}try{const h=this.getSymKey(n),l=cI({symKey:h,encoded:s,encoding:a?.encoding});return jo(l)}catch(h){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(h)}},this.getPayloadType=(n,s=ao)=>{const a=Au({encoded:n,encoding:s});return Vo(a.type)},this.getPayloadSenderPublicKey=(n,s=ao)=>{const a=Au({encoded:n,encoding:s});return a.senderPublicKey?MC(a.senderPublicKey,ai):void 0},this.core=e,this.logger=ui(r,this.name),this.keychain=i||new AP(this.core,this.logger)}get context(){return Ai(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(_3)}catch{e=Rd(),await this.keychain.set(_3,e)}return jO(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class SP extends pC{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=GO,this.version=YO,this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}},this.set=async(i,n)=>{this.isInitialized();const s=Ns(n);let a=this.messages.get(i);return typeof a>"u"&&(a={}),typeof a[s]<"u"||(a[s]=n,this.messages.set(i,a),await this.persist()),s},this.get=i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n},this.has=(i,n)=>{this.isInitialized();const s=this.get(i),a=Ns(n);return typeof s[a]<"u"},this.del=async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()},this.logger=ui(e,this.name),this.core=r}get context(){return Ai(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,q2(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?z2(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class IP extends gC{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new Ur.exports.EventEmitter,this.name=QO,this.queue=new Map,this.publishTimeout=xe.toMiliseconds(xe.ONE_MINUTE),this.failedPublishTimeout=xe.toMiliseconds(xe.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(i,n,s)=>{var a;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:s}});const u=s?.ttl||JO,h=Nd(s),l=s?.prompt||!1,b=s?.tag||0,w=s?.id||Jo().toString(),I={topic:i,message:n,opts:{ttl:u,relay:h,prompt:l,tag:b,id:w,attestation:s?.attestation}},S=`Failed to publish payload, please try again. id:${w} tag:${b}`,D=Date.now();let T,j=1;try{for(;T===void 0;){if(Date.now()-D>this.publishTimeout)throw new Error(S);this.logger.trace({id:w,attempts:j},`publisher.publish - attempt ${j}`),T=await await Ga(this.rpcPublish(i,n,u,h,l,b,w,s?.attestation).catch(K=>this.logger.warn(K)),this.publishTimeout,S),j++,T||await new Promise(K=>setTimeout(K,this.failedPublishTimeout))}this.relayer.events.emit(hi.publish,I),this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{id:w,topic:i,message:n,opts:s}})}catch(K){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(K),(a=s?.internal)!=null&&a.throwOnFailedPublish)throw K;this.queue.set(w,I)}},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.relayer=e,this.logger=ui(r,this.name),this.registerEventListeners()}get context(){return Ai(this.logger)}rpcPublish(e,r,i,n,s,a,u,h){var l,b,w,I;const S={method:xu(n.protocol).publish,params:{topic:e,message:r,ttl:i,prompt:s,tag:a,attestation:h},id:u};return ci((l=S.params)==null?void 0:l.prompt)&&((b=S.params)==null||delete b.prompt),ci((w=S.params)==null?void 0:w.tag)&&((I=S.params)==null||delete I.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:S}),this.relayer.request(S)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:r,message:i,opts:n}=e;await this.publish(r,i,n)})}registerEventListeners(){this.relayer.core.heartbeat.on(ac.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(hi.connection_stalled);return}this.checkQueue()}),this.relayer.on(hi.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class MP{constructor(){this.map=new Map,this.set=(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])},this.get=e=>this.map.get(e)||[],this.exists=(e,r)=>this.get(e).includes(r),this.delete=(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const 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)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var CP=Object.defineProperty,DP=Object.defineProperties,OP=Object.getOwnPropertyDescriptors,M3=Object.getOwnPropertySymbols,PP=Object.prototype.hasOwnProperty,$P=Object.prototype.propertyIsEnumerable,C3=(t,e,r)=>e in t?CP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fu=(t,e)=>{for(var r in e||(e={}))PP.call(e,r)&&C3(t,r,e[r]);if(M3)for(var r of M3(e))$P.call(e,r)&&C3(t,r,e[r]);return t},i1=(t,e)=>DP(t,OP(e));class RP extends bC{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new MP,this.events=new Ur.exports.EventEmitter,this.name=nP,this.version=sP,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=hs,this.subscribeTimeout=xe.toMiliseconds(xe.ONE_MINUTE),this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.pendingBatchMessages=[],this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId(),await this.restore()),this.initialized=!0},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=Nd(n),a={topic:i,relay:s,transportType:n?.transportType};this.pending.set(i,a);const u=await this.rpcSubscribe(i,s,n?.transportType);return typeof u=="string"&&(this.onSubscribe(u,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}})),u}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(i,n)=>{await this.restartToComplete(),this.isInitialized(),typeof n?.id<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)},this.isSubscribed=async i=>{if(this.topics.includes(i))return!0;const n=`${this.pendingSubscriptionWatchLabel}_${i}`;return await new Promise((s,a)=>{const u=new xe.Watch;u.start(n);const h=setInterval(()=>{!this.pending.has(i)&&this.topics.includes(i)&&(clearInterval(h),u.stop(n),s(!0)),u.elapsed(n)>=oP&&(clearInterval(h),u.stop(n),a(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=ui(r,this.name),this.clientId=""}get context(){return Ai(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}onEnable(){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=Nd(i);await this.rpcUnsubscribe(e,r,n);const s=Gt("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=Zt.relay){i===Zt.relay&&await this.restartToComplete();const n={method:xu(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{const s=Ns(e+this.clientId);return i===Zt.link_mode?(setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(a=>this.logger.warn(a))},xe.toMiliseconds(xe.ONE_SECOND)),s):await await Ga(this.relayer.request(n).catch(a=>this.logger.warn(a)),this.subscribeTimeout)?s:null}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(hi.connection_stalled)}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:xu(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{return await await Ga(this.relayer.request(i).catch(n=>this.logger.warn(n)),this.subscribeTimeout)}catch{this.relayer.events.emit(hi.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:xu(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 Ga(this.relayer.request(i).catch(s=>this.logger.warn(s)),this.subscribeTimeout)}catch{this.relayer.events.emit(hi.connection_stalled)}return n}rpcUnsubscribe(e,r,i){const n={method:xu(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,i1(Fu({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Fu({},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,Fu({},r)),this.topicMap.set(r.topic,e),this.events.emit(ls.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:i}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(ls.deleted,i1(Fu({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(ls.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<e;r++){const i=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchFetchMessages(i),await this.batchSubscribe(i)}}this.events.emit(ls.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;const r=await this.rpcBatchSubscribe(e);as(r)&&this.onBatchSubscribe(r.map((i,n)=>i1(Fu({},e[n]),{id:i})))}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&&(this.pendingBatchMessages=this.pendingBatchMessages.concat(r.messages))}async onConnect(){await this.restart(),this.onEnable()}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||!this.relayer.connected)return;const e=[];this.pending.forEach(r=>{e.push(r)}),await this.batchSubscribe(e),this.pendingBatchMessages.length&&(await this.relayer.handleBatchMessageEvents(this.pendingBatchMessages),this.pendingBatchMessages=[])}registerEventListeners(){this.relayer.core.heartbeat.on(ac.pulse,async()=>{await this.checkPending()}),this.events.on(ls.created,async e=>{const r=ls.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(ls.deleted,async e=>{const r=ls.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){!this.relayer.connected&&!this.relayer.connecting&&await this.relayer.transportOpen(),this.restartInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}}var NP=Object.defineProperty,D3=Object.getOwnPropertySymbols,TP=Object.prototype.hasOwnProperty,LP=Object.prototype.propertyIsEnumerable,O3=(t,e,r)=>e in t?NP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,BP=(t,e)=>{for(var r in e||(e={}))TP.call(e,r)&&O3(t,r,e[r]);if(D3)for(var r of D3(e))LP.call(e,r)&&O3(t,r,e[r]);return t};class FP extends vC{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new Ur.exports.EventEmitter,this.name=XO,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","stalled","interrupted"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.heartBeatTimeout=xe.toMiliseconds(xe.THIRTY_SECONDS+xe.ONE_SECOND),this.request=async r=>{var i,n;this.logger.debug("Publishing Request Payload");const s=r.id||Jo().toString();await this.toEstablishConnection();try{const a=this.provider.request(r);this.requestsInFlight.set(s,{promise:a,request:r}),this.logger.trace({id:s,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - attempt to publish...");const u=await new Promise(async(h,l)=>{const b=()=>{l(new Error(`relayer.request - publish interrupted, id: ${s}`))};this.provider.on(nn.disconnect,b);const w=await a;this.provider.off(nn.disconnect,b),h(w)});return this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - published"),u}catch(a){throw this.logger.debug(`Failed to Publish Request: ${s}`),a}finally{this.requestsInFlight.delete(s)}},this.resetPingTimeout=()=>{if(au())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,i,n;(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)}},this.onPayloadHandler=r=>{this.onProviderPayload(r),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.trace("relayer connected"),this.startPingTimeout(),this.events.emit(hi.connect)},this.onDisconnectHandler=()=>{this.logger.trace("relayer disconnected"),this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(hi.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(nn.payload,this.onPayloadHandler),this.provider.on(nn.connect,this.onConnectHandler),this.provider.on(nn.disconnect,this.onDisconnectHandler),this.provider.on(nn.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?ui(e.logger,this.name):cs(Dh({level:e.logger||ZO})),this.messages=new SP(this.logger,e.core),this.subscriber=new RP(this,this.logger),this.publisher=new IP(this,this.logger),this.relayUrl=e?.relayUrl||A3,this.projectId=e.projectId,this.bundleId=WE(),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.cached.length>0)try{await this.transportOpen()}catch(e){this.logger.warn(e)}}get context(){return Ai(this.logger)}get connected(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===1}get connecting(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===0}async publish(e,r,i){this.isInitialized(),await this.publisher.publish(e,r,i),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:Zt.relay})}async subscribe(e,r){var i;this.isInitialized(),r?.transportType==="relay"&&await this.toEstablishConnection();let n=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"",s;const a=u=>{u.topic===e&&(this.subscriber.off(ls.created,a),s())};return await Promise.all([new Promise(u=>{s=u,this.subscriber.on(ls.created,a)}),new Promise(async u=>{n=await this.subscriber.subscribe(e,r)||n,u()})]),n}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(){if(!this.hasExperiencedNetworkDisruption&&this.connected&&this.requestsInFlight.size>0)try{await Promise.all(Array.from(this.requestsInFlight.values()).map(e=>e.promise))}catch(e){this.logger.warn(e)}this.hasExperiencedNetworkDisruption||this.connected?await Ga(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),await this.createProvider(),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;try{await new Promise(async(r,i)=>{const n=()=>{this.provider.off(nn.disconnect,n),i(new Error("Connection interrupted while trying to subscribe"))};this.provider.on(nn.disconnect,n),await Ga(this.provider.connect(),xe.toMiliseconds(xe.ONE_MINUTE),`Socket stalled when trying to connect to ${this.relayUrl}`).catch(s=>{i(s)}).finally(()=>{clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0}),this.subscriber.start().catch(s=>{this.logger.error(s),this.onDisconnectHandler()}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){this.logger.error(r);const i=r;if(this.hasExperiencedNetworkDisruption=!0,!this.isConnectionStalled(i.message))throw r}finally{this.connectionAttemptInProgress=!1}}async restartTransport(e){this.connectionAttemptInProgress||(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await xb())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.trace(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const n=Ir(xe.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,s)}this.events.emit(hi.message,e),await this.recordMessageEvent(e)}startPingTimeout(){var e,r,i,n,s;if(au())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.once("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(a){this.logger.warn(a)}}isConnectionStalled(e){return this.staleConnectionErrors.some(r=>e.includes(r))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new xn(new gD(ZE({sdkVersion:x3,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic: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.debug(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(r))return this.logger.debug(`Ignoring message for non-subscribed topic ${r}`),!0;const n=this.messages.has(r,i);return n&&this.logger.debug(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Qd(e)){if(!e.method.endsWith(eP))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:a}=r.data,u={topic:i,message:n,publishedAt:s,transportType:Zt.relay,attestation:a};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(BP({type:"event",event:r.id},u)),this.events.emit(r.id,u),await this.acknowledgePayload(e),await this.onMessageEvent(u)}else $h(e)&&this.events.emit(hi.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(hi.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=Oh(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(nn.payload,this.onPayloadHandler),this.provider.off(nn.connect,this.onConnectHandler),this.provider.off(nn.disconnect,this.onDisconnectHandler),this.provider.off(nn.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await xb();nM(async r=>{e!==r&&(e=r,r?await this.restartTransport().catch(i=>this.logger.error(i)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),this.requestsInFlight.clear(),clearTimeout(this.pingTimeout),this.events.emit(hi.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&(this.reconnectTimeout||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},xe.toMiliseconds(tP))))}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&(this.connectionAttemptInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.connected&&(clearInterval(r),e())},this.connectionStatusPollingInterval)}),await this.transportOpen())}}var kP=Object.defineProperty,P3=Object.getOwnPropertySymbols,UP=Object.prototype.hasOwnProperty,jP=Object.prototype.propertyIsEnumerable,$3=(t,e,r)=>e in t?kP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,R3=(t,e)=>{for(var r in e||(e={}))UP.call(e,r)&&$3(t,r,e[r]);if(P3)for(var r of P3(e))jP.call(e,r)&&$3(t,r,e[r]);return t};class ea extends mC{constructor(e,r,i,n=hs,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,this.map=new Map,this.version=rP,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(a=>{this.getKey&&a!==null&&!ci(a)?this.map.set(this.getKey(a),a):TI(a)?this.map.set(a.id,a):LI(a)&&this.map.set(a.topic,a)}),this.cached=[],this.initialized=!0)},this.set=async(a,u)=>{this.isInitialized(),this.map.has(a)?await this.update(a,u):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:a,value:u}),this.map.set(a,u),await this.persist())},this.get=a=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:a}),this.getData(a)),this.getAll=a=>(this.isInitialized(),a?this.values.filter(u=>Object.keys(a).every(h=>vD(u[h],a[h]))):this.values),this.update=async(a,u)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:a,update:u});const h=R3(R3({},this.getData(a)),u);this.map.set(a,h),await this.persist()},this.delete=async(a,u)=>{this.isInitialized(),this.map.has(a)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:a,reason:u}),this.map.delete(a),this.addToRecentlyDeleted(a),await this.persist())},this.logger=ui(r,this.name),this.storagePrefix=n,this.getKey=s}get context(){return Ai(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:n}=Ee("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:i}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class qP{constructor(e,r){this.core=e,this.logger=r,this.name=aP,this.version=cP,this.events=new Ur.exports,this.initialized=!1,this.storagePrefix=hs,this.ignoredPayloadTypes=[Rs],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]},this.create=async i=>{this.isInitialized();const n=Rd(),s=await this.core.crypto.setSymKey(n),a=Ir(xe.FIVE_MINUTES),u={protocol:E3},h={topic:s,expiry:a,relay:u,active:!1},l=SI({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:u,expiryTimestamp:a,methods:i?.methods});return this.core.expirer.set(s,a),await this.pairings.set(s,h),await this.core.relayer.subscribe(s,{transportType:i?.transportType}),{topic:s,uri:l}},this.pair=async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i?.uri,trace:[ds.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:a,relay:u,expiryTimestamp:h,methods:l}=vb(i.uri);n.props.properties.topic=s,n.addTrace(ds.pairing_uri_validation_success),n.addTrace(ds.pairing_uri_not_expired);let b;if(this.pairings.keys.includes(s)){if(b=this.pairings.get(s),n.addTrace(ds.existing_pairing),b.active)throw n.setError(Bs.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(ds.pairing_not_expired)}const w=h||Ir(xe.FIVE_MINUTES),I={topic:s,relay:u,expiry:w,active:!1,methods:l};this.core.expirer.set(s,w),await this.pairings.set(s,I),n.addTrace(ds.store_new_pairing),i.activatePairing&&await this.activate({topic:s}),this.events.emit(fc.create,I),n.addTrace(ds.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(a,s),n.addTrace(ds.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(Bs.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:u})}catch(S){throw n.setError(Bs.subscribe_pairing_topic_failure),S}return n.addTrace(ds.subscribe_pairing_topic_success),I},this.activate=async({topic:i})=>{this.isInitialized();const n=Ir(xe.THIRTY_DAYS);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})},this.ping=async i=>{this.isInitialized(),await this.isValidPing(i);const{topic:n}=i;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:a,resolve:u,reject:h}=zo();this.events.once(Dt("pairing_ping",s),({error:l})=>{l?h(l):u()}),await a()}},this.updateExpiry=async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})},this.updateMetadata=async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),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",Gt("USER_DISCONNECTED")),await this.deletePairing(n))},this.sendRequest=async(i,n,s)=>{const a=Qo(n,s),u=await this.core.crypto.encode(i,a),h=Tu[n].req;return this.core.history.set(i,a),this.core.relayer.publish(i,u,h),a.id},this.sendResult=async(i,n,s)=>{const a=Oh(i,s),u=await this.core.crypto.encode(n,a),h=await this.core.history.get(n,i),l=Tu[h.request.method].res;await this.core.relayer.publish(n,u,l),await this.core.history.resolve(a)},this.sendError=async(i,n,s)=>{const a=Ph(i,s),u=await this.core.crypto.encode(n,a),h=await this.core.history.get(n,i),l=Tu[h.request.method]?Tu[h.request.method].res:Tu.unregistered_method.res;await this.core.relayer.publish(n,u,l),await this.core.history.resolve(a)},this.deletePairing=async(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,Gt("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])},this.cleanup=async()=>{const i=this.pairings.getAll().filter(n=>io(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))},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)}},this.onRelayEventResponse=async i=>{const{topic:n,payload:s}=i,a=(await this.core.history.get(n,s.id)).request.method;switch(a){case"wc_pairingPing":return this.onPairingPingResponse(n,s);default:return this.onUnknownRpcMethodResponse(a)}},this.onPairingPingRequest=async(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(fc.ping,{id:s,topic:i})}catch(a){await this.sendError(s,i,a),this.logger.error(a)}},this.onPairingPingResponse=(i,n)=>{const{id:s}=n;setTimeout(()=>{fs(n)?this.events.emit(Dt("pairing_ping",s),{}):rn(n)&&this.events.emit(Dt("pairing_ping",s),{error:n.error})},500)},this.onPairingDeleteRequest=async(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(fc.delete,{id:s,topic:i})}catch(a){await this.sendError(s,i,a),this.logger.error(a)}},this.onUnknownRpcMethodRequest=async(i,n)=>{const{id:s,method:a}=n;try{if(this.registeredMethods.includes(a))return;const u=Gt("WC_METHOD_UNSUPPORTED",a);await this.sendError(s,i,u),this.logger.error(u)}catch(u){await this.sendError(s,i,u),this.logger.error(u)}},this.onUnknownRpcMethodResponse=i=>{this.registeredMethods.includes(i)||this.logger.error(Gt("WC_METHOD_UNSUPPORTED",i))},this.isValidPair=(i,n)=>{var s;if(!_i(i)){const{message:u}=Ee("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(Bs.malformed_pairing_uri),new Error(u)}if(!NI(i.uri)){const{message:u}=Ee("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(Bs.malformed_pairing_uri),new Error(u)}const a=vb(i?.uri);if(!((s=a?.relay)!=null&&s.protocol)){const{message:u}=Ee("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(Bs.malformed_pairing_uri),new Error(u)}if(!(a!=null&&a.symKey)){const{message:u}=Ee("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(Bs.malformed_pairing_uri),new Error(u)}if(a!=null&&a.expiryTimestamp&&xe.toMiliseconds(a?.expiryTimestamp)<Date.now()){n.setError(Bs.pairing_expired);const{message:u}=Ee("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(u)}},this.isValidPing=async i=>{if(!_i(i)){const{message:s}=Ee("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)},this.isValidDisconnect=async i=>{if(!_i(i)){const{message:s}=Ee("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)},this.isValidPairingTopic=async i=>{if(!yr(i,!1)){const{message:n}=Ee("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=Ee("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(io(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=Ee("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}},this.core=e,this.logger=ui(r,this.name),this.pairings=new ea(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Ai(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(hi.message,async e=>{const{topic:r,message:i,transportType:n}=e;if(!this.pairings.keys.includes(r)||n===Zt.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const s=await this.core.crypto.decode(r,i);try{Qd(s)?(this.core.history.set(r,s),this.onRelayEventRequest({topic:r,payload:s})):$h(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id))}catch(a){this.logger.error(a)}})}registerExpirerEvents(){this.core.expirer.on(sn.expired,async e=>{const{topic:r}=K2(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(fc.expire,{topic:r}))})}}class zP extends dC{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new Ur.exports.EventEmitter,this.name=uP,this.version=fP,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(i,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 a={id:n.id,topic:i,request:{method:n.method,params:n.params||null},chainId:s,expiry:Ir(xe.THIRTY_DAYS)};this.records.set(a.id,a),this.persist(),this.events.emit(Sn.created,a)},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=rn(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(Sn.updated,n))},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)),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(Sn.deleted,s)}}),this.persist()},this.exists=async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1),this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.logger=ui(r,this.name)}get context(){return Ai(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:Qo(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:i}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Sn.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Sn.created,e=>{const r=Sn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Sn.updated,e=>{const r=Sn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Sn.deleted,e=>{const r=Sn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(ac.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{xe.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Sn.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}class HP extends yC{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new Ur.exports.EventEmitter,this.name=hP,this.version=lP,this.cached=[],this.initialized=!1,this.storagePrefix=hs,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}},this.set=(i,n)=>{this.isInitialized();const s=this.formatTarget(i),a={target:s,expiry:n};this.expirations.set(s,a),this.checkExpiry(s,a),this.events.emit(sn.created,{target:s,expiration:a})},this.get=i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)},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(sn.deleted,{target:n,expiration:s})}},this.on=(i,n)=>{this.events.on(i,n)},this.once=(i,n)=>{this.events.once(i,n)},this.off=(i,n)=>{this.events.off(i,n)},this.removeListener=(i,n)=>{this.events.removeListener(i,n)},this.logger=ui(r,this.name)}get context(){return Ai(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 XE(e);if(typeof e=="number")return eA(e);const{message:r}=Ee("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(sn.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=Ee("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:i}=Ee("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;xe.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(sn.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(ac.pulse,()=>this.checkExpirations()),this.events.on(sn.created,e=>{const r=sn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(sn.expired,e=>{const r=sn.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(sn.deleted,e=>{const r=sn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}}var or={};Object.defineProperty(or,"__esModule",{value:!0}),or.getLocalStorage=or.getLocalStorageOrThrow=or.getCrypto=or.getCryptoOrThrow=or.getLocation=or.getLocationOrThrow=or.getNavigator=or.getNavigatorOrThrow=N3=or.getDocument=or.getDocumentOrThrow=or.getFromWindowOrThrow=or.getFromWindow=void 0;function ta(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}or.getFromWindow=ta;function hc(t){const e=ta(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}or.getFromWindowOrThrow=hc;function KP(){return hc("document")}or.getDocumentOrThrow=KP;function WP(){return ta("document")}var N3=or.getDocument=WP;function VP(){return hc("navigator")}or.getNavigatorOrThrow=VP;function GP(){return ta("navigator")}or.getNavigator=GP;function YP(){return hc("location")}or.getLocationOrThrow=YP;function JP(){return ta("location")}or.getLocation=JP;function QP(){return hc("crypto")}or.getCryptoOrThrow=QP;function ZP(){return ta("crypto")}or.getCrypto=ZP;function XP(){return hc("localStorage")}or.getLocalStorageOrThrow=XP;function e$(){return ta("localStorage")}or.getLocalStorage=e$;class t$ extends wC{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,this.name=dP,this.verifyUrlV3=gP,this.storagePrefix=hs,this.version=w3,this.init=async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&xe.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))},this.register=async n=>{if(!cu()||this.isDevEnv)return;const s=window.location.origin,{id:a,decryptedId:u}=n,h=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${a}&decryptedId=${u}`;try{const l=N3(),b=this.startAbortTimer(xe.ONE_SECOND*5),w=await new Promise((I,S)=>{const D=()=>{window.removeEventListener("message",j),l.body.removeChild(T),S("attestation aborted")};this.abortController.signal.addEventListener("abort",D);const T=l.createElement("iframe");T.src=h,T.style.display="none",T.addEventListener("error",D,{signal:this.abortController.signal});const j=K=>{if(!K.data)return;const F=JSON.parse(K.data);if(F.type==="verify_attestation"){if(od(F.attestation).payload.id!==a)return;clearInterval(b),l.body.removeChild(T),this.abortController.signal.removeEventListener("abort",D),window.removeEventListener("message",j),I(F.attestation===null?"":F.attestation)}};l.body.appendChild(T),window.addEventListener("message",j,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",w),w}catch(l){this.logger.warn(l)}return""},this.resolve=async n=>{if(this.isDevEnv)return"";const{attestationId:s,hash:a,encryptedId:u}=n;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(od(s).payload.id!==u)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(!a)return;const h=this.getVerifyUrl(n?.verifyUrl);return this.fetchAttestation(a,h)},this.fetchAttestation=async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const a=this.startAbortTimer(xe.ONE_SECOND*5),u=await fetch(`${s}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(a),u.status===200?await u.json():void 0},this.getVerifyUrl=n=>{let s=n||Lu;return vP.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Lu}`),s=Lu),s},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(xe.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)}},this.persistPublicKey=async n=>{this.logger.debug("persisting public key to local storage",n),await this.store.setItem(this.storeKey,n),this.publicKey=n},this.removePublicKey=async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async n=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(n,s)}catch(u){this.logger.error(u),this.logger.warn("error validating attestation")}const a=await this.fetchAndPersistPublicKey();try{if(a)return this.validateAttestation(n,a)}catch(u){this.logger.error(u),this.logger.warn("error validating attestation")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const a=await this.fetchPublicKey();a&&(await this.persistPublicKey(a),s(a))});const n=await this.fetchPromise;return this.fetchPromise=void 0,n},this.validateAttestation=(n,s)=>{const a=pI(n,s.publicKey),u={hasExpired:xe.toMiliseconds(a.exp)<Date.now(),payload:a};if(u.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:u.payload.origin,isScam:u.payload.isScam,isVerified:u.payload.isVerified}},this.logger=ui(r,this.name),this.abortController=new AbortController,this.isDevEnv=au()&&process.env.IS_VITEST,this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Ai(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),xe.toMiliseconds(e))}}class r$ extends _C{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.context=mP,this.registerDeviceToken=async i=>{const{clientId:n,token:s,notificationType:a,enableEncrypted:u=!1}=i,h=`${bP}/${this.projectId}/clients`;await fetch(h,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:a,token:s,always_raw:u})})},this.logger=ui(r,this.context)}}var i$=Object.defineProperty,T3=Object.getOwnPropertySymbols,n$=Object.prototype.hasOwnProperty,s$=Object.prototype.propertyIsEnumerable,L3=(t,e,r)=>e in t?i$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ku=(t,e)=>{for(var r in e||(e={}))n$.call(e,r)&&L3(t,r,e[r]);if(T3)for(var r of T3(e))s$.call(e,r)&&L3(t,r,e[r]);return t};class o$ extends EC{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,this.context=wP,this.storagePrefix=hs,this.storageVersion=yP,this.events=new Map,this.shouldPersist=!1,this.createEvent=n=>{const{event:s="ERROR",type:a="",properties:{topic:u,trace:h}}=n,l=iA(),b=this.core.projectId||"",w=Date.now(),I=ku({eventId:l,bundleId:b,timestamp:w,props:{event:s,type:a,properties:{topic:u,trace:h}}},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,I),this.shouldPersist=!0),I},this.getEvent=n=>{const{eventId:s,topic:a}=n;if(s)return this.events.get(s);const u=Array.from(this.events.values()).find(h=>h.props.properties.topic===a);if(u)return ku(ku({},u),this.setMethods(u.eventId))},this.deleteEvent=n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(ac.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{xe.fromMiliseconds(Date.now())-xe.fromMiliseconds(n.timestamp)>_P&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})},this.setMethods=n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)}),this.addTrace=(n,s)=>{const a=this.events.get(n);a&&(a.props.properties.trace.push(s),this.events.set(n,a),this.shouldPersist=!0)},this.setError=(n,s)=>{const a=this.events.get(n);a&&(a.props.type=s,a.timestamp=Date.now(),this.events.set(n,a),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},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,ku(ku({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}},this.submit=async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[s,a]of this.events)a.props.type&&n.push(a);if(n.length!==0)try{if((await fetch(`${EP}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${x3}`,{method:"POST",body:JSON.stringify(n)})).ok)for(const s of n)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}},this.logger=ui(r,this.context),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 a$=Object.defineProperty,B3=Object.getOwnPropertySymbols,c$=Object.prototype.hasOwnProperty,u$=Object.prototype.propertyIsEnumerable,F3=(t,e,r)=>e in t?a$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,k3=(t,e)=>{for(var r in e||(e={}))c$.call(e,r)&&F3(t,r,e[r]);if(B3)for(var r of B3(e))u$.call(e,r)&&F3(t,r,e[r]);return t};class n1 extends lC{constructor(e){var r;super(e),this.protocol=y3,this.version=w3,this.name=r1,this.events=new Ur.exports.EventEmitter,this.initialized=!1,this.on=(a,u)=>this.events.on(a,u),this.once=(a,u)=>this.events.once(a,u),this.off=(a,u)=>this.events.off(a,u),this.removeListener=(a,u)=>this.events.removeListener(a,u),this.dispatchEnvelope=({topic:a,message:u,sessionExists:h})=>{if(!a||!u)return;const l={topic:a,message:u,publishedAt:Date.now(),transportType:Zt.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})},this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||A3,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Dh({level:typeof e?.logger=="string"&&e.logger?e.logger:qO.logger}),{logger:n,chunkLoggerController:s}=hC({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=s,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,u;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((u=this.logChunkController)==null||u.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=ui(n,this.name),this.heartbeat=new qd,this.crypto=new xP(this,this.logger,e?.keychain),this.history=new zP(this,this.logger),this.expirer=new HP(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new LM(k3(k3({},zO),e?.storageOptions)),this.relayer=new FP({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new qP(this,this.logger),this.verify=new t$(this,this.logger,this.storage),this.echoClient=new r$(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new o$(this,this.logger,e?.telemetryEnabled)}static async init(e){const r=new n1(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(iP,i),r}get context(){return Ai(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(S3,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(S3)||[],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 f$=n1,U3="wc",j3=2,q3="client",s1=`${U3}@${j3}:${q3}:`,o1={name:q3,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},z3="WALLETCONNECT_DEEPLINK_CHOICE",h$="proposal",H3="Proposal expired",l$="session",lc=xe.SEVEN_DAYS,d$="engine",Lr={wc_sessionPropose:{req:{ttl:xe.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1104},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1106},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:xe.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:xe.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1112},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:xe.ONE_DAY,prompt:!1,tag:1114},res:{ttl:xe.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:xe.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:xe.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:xe.FIVE_MINUTES,prompt:!1,tag:1119}}},a1={min:xe.FIVE_MINUTES,max:xe.SEVEN_DAYS},ps={idle:"IDLE",active:"ACTIVE"},p$="request",g$=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],v$="wc",m$="auth",b$="authKeys",y$="pairingTopics",w$="requests",Nh=`${v$}@${1.5}:${m$}:`,Th=`${Nh}:PUB_KEY`;var _$=Object.defineProperty,E$=Object.defineProperties,A$=Object.getOwnPropertyDescriptors,K3=Object.getOwnPropertySymbols,x$=Object.prototype.hasOwnProperty,S$=Object.prototype.propertyIsEnumerable,W3=(t,e,r)=>e in t?_$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pr=(t,e)=>{for(var r in e||(e={}))x$.call(e,r)&&W3(t,r,e[r]);if(K3)for(var r of K3(e))S$.call(e,r)&&W3(t,r,e[r]);return t},Mn=(t,e)=>E$(t,A$(e));class I$ extends xC{constructor(e){super(e),this.name=d$,this.events=new Ur.exports,this.initialized=!1,this.requestQueue={state:ps.idle,queue:[]},this.sessionRequestQueue={state:ps.idle,queue:[]},this.requestQueueDelay=xe.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],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(Lr)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},xe.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Mn(pr({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:n,requiredNamespaces:s,optionalNamespaces:a,sessionProperties:u,relays:h}=i;let l=n,b,w=!1;try{l&&(w=this.client.core.pairing.pairings.get(l).active)}catch(R){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),R}if(!l||!w){const{topic:R,uri:U}=await this.client.core.pairing.create();l=R,b=U}if(!l){const{message:R}=Ee("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(R)}const I=await this.client.core.crypto.generateKeyPair(),S=Lr.wc_sessionPropose.req.ttl||xe.FIVE_MINUTES,D=Ir(S),T=pr({requiredNamespaces:s,optionalNamespaces:a,relays:h??[{protocol:E3}],proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:D,pairingTopic:l},u&&{sessionProperties:u}),{reject:j,resolve:K,done:F}=zo(S,H3);this.events.once(Dt("session_connect"),async({error:R,session:U})=>{if(R)j(R);else if(U){U.self.publicKey=I;const H=Mn(pr({},U),{pairingTopic:T.pairingTopic,requiredNamespaces:T.requiredNamespaces,optionalNamespaces:T.optionalNamespaces,transportType:Zt.relay});await this.client.session.set(U.topic,H),await this.setExpiry(U.topic,U.expiry),l&&await this.client.core.pairing.updateMetadata({topic:l,metadata:U.peer.metadata}),this.cleanupDuplicatePairings(H),K(H)}});const W=await this.sendRequest({topic:l,method:"wc_sessionPropose",params:T,throwOnFailedPublish:!0});return await this.setProposal(W,pr({id:W},T)),{uri:b,approval:F}},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}},this.approve=async r=>{var i,n,s;const a=this.client.core.eventClient.createEvent({properties:{topic:(i=r?.id)==null?void 0:i.toString(),trace:[In.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(B){throw a.setError(Zo.no_internet_connection),B}try{await this.isValidProposalId(r?.id)}catch(B){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),a.setError(Zo.proposal_not_found),B}try{await this.isValidApprove(r)}catch(B){throw this.client.logger.error("approve() -> isValidApprove() failed"),a.setError(Zo.session_approve_namespace_validation_failure),B}const{id:u,relayProtocol:h,namespaces:l,sessionProperties:b,sessionConfig:w}=r,I=this.client.proposal.get(u);this.client.core.eventClient.deleteEvent({eventId:a.eventId});const{pairingTopic:S,proposer:D,requiredNamespaces:T,optionalNamespaces:j}=I;let K=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:S});K||(K=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:In.session_approve_started,properties:{topic:S,trace:[In.session_approve_started,In.session_namespaces_validation_success]}}));const F=await this.client.core.crypto.generateKeyPair(),W=D.publicKey,R=await this.client.core.crypto.generateSharedKey(F,W),U=pr(pr({relay:{protocol:h??"irn"},namespaces:l,controller:{publicKey:F,metadata:this.client.metadata},expiry:Ir(lc)},b&&{sessionProperties:b}),w&&{sessionConfig:w}),H=Zt.relay;K.addTrace(In.subscribing_session_topic);try{await this.client.core.relayer.subscribe(R,{transportType:H})}catch(B){throw K.setError(Zo.subscribe_session_topic_failure),B}K.addTrace(In.subscribe_session_topic_success);const _=Mn(pr({},U),{topic:R,requiredNamespaces:T,optionalNamespaces:j,pairingTopic:S,acknowledged:!1,self:U.controller,peer:{publicKey:D.publicKey,metadata:D.metadata},controller:F,transportType:Zt.relay});await this.client.session.set(R,_),K.addTrace(In.store_session);try{K.addTrace(In.publishing_session_settle),await this.sendRequest({topic:R,method:"wc_sessionSettle",params:U,throwOnFailedPublish:!0}).catch(B=>{throw K?.setError(Zo.session_settle_publish_failure),B}),K.addTrace(In.session_settle_publish_success),K.addTrace(In.publishing_session_approve),await this.sendResult({id:u,topic:S,result:{relay:{protocol:h??"irn"},responderPublicKey:F},throwOnFailedPublish:!0}).catch(B=>{throw K?.setError(Zo.session_approve_publish_failure),B}),K.addTrace(In.session_approve_publish_success)}catch(B){throw this.client.logger.error(B),this.client.session.delete(R,Gt("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(R),B}return this.client.core.eventClient.deleteEvent({eventId:K.eventId}),await this.client.core.pairing.updateMetadata({topic:S,metadata:D.metadata}),await this.client.proposal.delete(u,Gt("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:S}),await this.setExpiry(R,Ir(lc)),{topic:R,acknowledged:()=>Promise.resolve(this.client.session.get(R))}},this.reject=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(a){throw this.client.logger.error("reject() -> isValidReject() failed"),a}const{id:i,reason:n}=r;let s;try{s=this.client.proposal.get(i).pairingTopic}catch(a){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),a}s&&(await this.sendError({id:i,topic:s,error:n,rpcOpts:Lr.wc_sessionPropose.reject}),await this.client.proposal.delete(i,Gt("USER_DISCONNECTED")))},this.update=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(w){throw this.client.logger.error("update() -> isValidUpdate() failed"),w}const{topic:i,namespaces:n}=r,{done:s,resolve:a,reject:u}=zo(),h=co(),l=Jo().toString(),b=this.client.session.get(i).namespaces;return this.events.once(Dt("session_update",h),({error:w})=>{w?u(w):a()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:h,relayRpcId:l}).catch(w=>{this.client.logger.error(w),this.client.session.update(i,{namespaces:b}),u(w)}),{acknowledged:s}},this.extend=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(h){throw this.client.logger.error("extend() -> isValidExtend() failed"),h}const{topic:i}=r,n=co(),{done:s,resolve:a,reject:u}=zo();return this.events.once(Dt("session_extend",n),({error:h})=>{h?u(h):a()}),await this.setExpiry(i,Ir(lc)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(h=>{u(h)}),{acknowledged:s}},this.request=async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(D){throw this.client.logger.error("request() -> isValidRequest() failed"),D}const{chainId:i,request:n,topic:s,expiry:a=Lr.wc_sessionRequest.req.ttl}=r,u=this.client.session.get(s);u?.transportType===Zt.relay&&await this.confirmOnlineStateOrThrow();const h=co(),l=Jo().toString(),{done:b,resolve:w,reject:I}=zo(a,"Request expired. Please try again.");this.events.once(Dt("session_request",h),({error:D,result:T})=>{D?I(D):w(T)});const S=this.getAppLinkIfEnabled(u.peer.metadata,u.transportType);return S?(await this.sendRequest({clientRpcId:h,relayRpcId:l,topic:s,method:"wc_sessionRequest",params:{request:Mn(pr({},n),{expiryTimestamp:Ir(a)}),chainId:i},expiry:a,throwOnFailedPublish:!0,appLink:S}).catch(D=>I(D)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:h}),await b()):await Promise.all([new Promise(async D=>{await this.sendRequest({clientRpcId:h,relayRpcId:l,topic:s,method:"wc_sessionRequest",params:{request:Mn(pr({},n),{expiryTimestamp:Ir(a)}),chainId:i},expiry:a,throwOnFailedPublish:!0}).catch(T=>I(T)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:h}),D()}),new Promise(async D=>{var T;if(!((T=u.sessionConfig)!=null&&T.disableDeepLink)){const j=await rA(this.client.core.storage,z3);tA({id:h,topic:s,wcDeepLink:j})}D()}),b()]).then(D=>D[2])},this.respond=async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:i,response:n}=r,{id:s}=n,a=this.client.session.get(i);a.transportType===Zt.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);fs(n)?await this.sendResult({id:s,topic:i,result:n.result,throwOnFailedPublish:!0,appLink:u}):rn(n)&&await this.sendError({id:s,topic:i,error:n.error,appLink:u}),this.cleanupAfterResponse(r)},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=co(),s=Jo().toString(),{done:a,resolve:u,reject:h}=zo();this.events.once(Dt("session_ping",n),({error:l})=>{l?h(l):u()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),a()])}else this.client.core.pairing.pairings.keys.includes(i)&&await this.client.core.pairing.ping({topic:i})},this.emit=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,a=Jo().toString();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:a})},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:Gt("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=Ee("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(i=>$I(i,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),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),a=s?Zt.link_mode:Zt.relay;a===Zt.relay&&await this.confirmOnlineStateOrThrow();const{chains:u,statement:h="",uri:l,domain:b,nonce:w,type:I,exp:S,nbf:D,methods:T=[],expiry:j}=r,K=[...r.resources||[]],{topic:F,uri:W}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:a});this.client.logger.info({message:"Generated new pairing",pairing:{topic:F,uri:W}});const R=await this.client.core.crypto.generateKeyPair(),U=bh(R);if(await Promise.all([this.client.auth.authKeys.set(Th,{responseTopic:U,publicKey:R}),this.client.auth.pairingTopics.set(U,{topic:U,pairingTopic:F})]),await this.client.core.relayer.subscribe(U,{transportType:a}),this.client.logger.info(`sending request to new pairing topic: ${F}`),T.length>0){const{namespace:O}=ou(u[0]);let M=ZS(O,"request",T);mh(K)&&(M=eI(M,K.pop())),K.push(M)}const H=j&&j>Lr.wc_sessionAuthenticate.req.ttl?j:Lr.wc_sessionAuthenticate.req.ttl,_={authPayload:{type:I??"caip122",chains:u,statement:h,aud:l,domain:b,version:"1",nonce:w,iat:new Date().toISOString(),exp:S,nbf:D,resources:K},requester:{publicKey:R,metadata:this.client.metadata},expiryTimestamp:Ir(H)},B={eip155:{chains:u,methods:[...new Set(["personal_sign",...T])],events:["chainChanged","accountsChanged"]}},ee={requiredNamespaces:{},optionalNamespaces:B,relays:[{protocol:"irn"}],pairingTopic:F,proposer:{publicKey:R,metadata:this.client.metadata},expiryTimestamp:Ir(Lr.wc_sessionPropose.req.ttl)},{done:ie,resolve:L,reject:y}=zo(H,"Request expired"),f=async({error:O,session:M})=>{if(this.events.off(Dt("session_request",v),d),O)y(O);else if(M){M.self.publicKey=R,await this.client.session.set(M.topic,M),await this.setExpiry(M.topic,M.expiry),F&&await this.client.core.pairing.updateMetadata({topic:F,metadata:M.peer.metadata});const g=this.client.session.get(M.topic);await this.deleteProposal(E),L({session:g})}},d=async O=>{var M,g,m;if(await this.deletePendingAuthRequest(v,{message:"fulfilled",code:0}),O.error){const G=Gt("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return O.error.code===G.code?void 0:(this.events.off(Dt("session_connect"),f),y(O.error.message))}await this.deleteProposal(E),this.events.off(Dt("session_connect"),f);const{cacaos:N,responder:X}=O.result,ae=[],P=[];for(const G of N){await eb({cacao:G,projectId:this.client.core.projectId})||(this.client.logger.error(G,"Signature verification failed"),y(Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Y}=G,A=mh(Y.resources),V=[Xm(Y.iss)],oe=vh(Y.iss);if(A){const ue=ib(A),he=nb(A);ae.push(...ue),V.push(...he)}for(const ue of V)P.push(`${ue}:${oe}`)}const te=await this.client.core.crypto.generateSharedKey(R,X.publicKey);let z;ae.length>0&&(z={topic:te,acknowledged:!0,self:{publicKey:R,metadata:this.client.metadata},peer:X,controller:X.publicKey,expiry:Ir(lc),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:F,namespaces:mb([...new Set(ae)],[...new Set(P)]),transportType:a},await this.client.core.relayer.subscribe(te,{transportType:a}),await this.client.session.set(te,z),F&&await this.client.core.pairing.updateMetadata({topic:F,metadata:X.metadata}),z=this.client.session.get(te)),(M=this.client.metadata.redirect)!=null&&M.linkMode&&(g=X.metadata.redirect)!=null&&g.linkMode&&(m=X.metadata.redirect)!=null&&m.universal&&i&&(this.client.core.addLinkModeSupportedApp(X.metadata.redirect.universal),this.client.session.update(te,{transportType:Zt.link_mode})),L({auths:N,session:z})},v=co(),E=co();this.events.once(Dt("session_connect"),f),this.events.once(Dt("session_request",v),d);let C;try{if(s){const O=Qo("wc_sessionAuthenticate",_,v);this.client.core.history.set(F,O);const M=await this.client.core.crypto.encode("",O,{type:_u,encoding:yu});C=yh(i,F,M)}else await Promise.all([this.sendRequest({topic:F,method:"wc_sessionAuthenticate",params:_,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:v}),this.sendRequest({topic:F,method:"wc_sessionPropose",params:ee,expiry:Lr.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:E})])}catch(O){throw this.events.off(Dt("session_connect"),f),this.events.off(Dt("session_request",v),d),O}return await this.setProposal(E,pr({id:E},ee)),await this.setAuthRequest(v,{request:Mn(pr({},_),{verifyContext:{}}),pairingTopic:F,transportType:a}),{uri:C??W,response:ie}},this.approveSessionAuthenticate=async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Xo.authenticated_session_approve_started]}});try{this.isInitialized()}catch(j){throw s.setError(Bu.no_internet_connection),j}const a=this.getPendingAuthRequest(i);if(!a)throw s.setError(Bu.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const u=a.transportType||Zt.relay;u===Zt.relay&&await this.confirmOnlineStateOrThrow();const h=a.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),b=bh(h),w={type:Rs,receiverPublicKey:h,senderPublicKey:l},I=[],S=[];for(const j of n){if(!await eb({cacao:j,projectId:this.client.core.projectId})){s.setError(Bu.invalid_cacao);const U=Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:b,error:U,encodeOpts:w}),new Error(U.message)}s.addTrace(Xo.cacaos_verified);const{p:K}=j,F=mh(K.resources),W=[Xm(K.iss)],R=vh(K.iss);if(F){const U=ib(F),H=nb(F);I.push(...U),W.push(...H)}for(const U of W)S.push(`${U}:${R}`)}const D=await this.client.core.crypto.generateSharedKey(l,h);s.addTrace(Xo.create_authenticated_session_topic);let T;if(I?.length>0){T={topic:D,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:h,metadata:a.requester.metadata},controller:h,expiry:Ir(lc),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:a.pairingTopic,namespaces:mb([...new Set(I)],[...new Set(S)]),transportType:u},s.addTrace(Xo.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(D,{transportType:u})}catch(j){throw s.setError(Bu.subscribe_authenticated_session_topic_failure),j}s.addTrace(Xo.subscribe_authenticated_session_topic_success),await this.client.session.set(D,T),s.addTrace(Xo.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:a.pairingTopic,metadata:a.requester.metadata})}s.addTrace(Xo.publishing_authenticated_session_approve);try{await this.sendResult({topic:b,id:i,result:{cacaos:n,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:w,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(a.requester.metadata,u)})}catch(j){throw s.setError(Bu.authenticated_session_approve_publish_failure),j}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:a.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:T}},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===Zt.relay&&await this.confirmOnlineStateOrThrow();const a=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),h=bh(a),l={type:Rs,receiverPublicKey:a,senderPublicKey:u};await this.sendError({id:i,topic:h,error:n,encodeOpts:l,rpcOpts:Lr.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,Gt("USER_DISCONNECTED"))},this.formatAuthMessage=r=>{this.isInitialized();const{request:i,iss:n}=r;return tb(i,n)},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)},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 a,u;return((a=s.peerMetadata)==null?void 0:a.url)&&((u=s.peerMetadata)==null?void 0:u.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)}},this.deleteSession=async r=>{var i;const{topic:n,expirerHasDeleted:s=!1,emitEvent:a=!0,id:u=0}=r,{self:h}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,Gt("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(h.publicKey)&&await this.client.core.crypto.deleteKeyPair(h.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(z3).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===n&&this.deletePendingSessionRequest(l.id,Gt("USER_DISCONNECTED"))}),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=ps.idle),a&&this.client.events.emit("session_delete",{id:u,topic:n})},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(Zo.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,Gt("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")},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=ps.idle,this.client.events.emit("session_request_expire",{id:r}))},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)])},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}))},this.setProposal=async(r,i)=>{this.client.core.expirer.set(r,Ir(Lr.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)},this.setAuthRequest=async(r,i)=>{const{request:n,pairingTopic:s,transportType:a=Zt.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:a})},this.setPendingSessionRequest=async r=>{const{id:i,topic:n,params:s,verifyContext:a}=r,u=s.request.expiryTimestamp||Ir(Lr.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,u),await this.client.pendingRequest.set(i,{id:i,topic:n,params:s,verifyContext:a})},this.sendRequest=async r=>{const{topic:i,method:n,params:s,expiry:a,relayRpcId:u,clientRpcId:h,throwOnFailedPublish:l,appLink:b}=r,w=Qo(n,s,h);let I;const S=!!b;try{const j=S?yu:ao;I=await this.client.core.crypto.encode(i,w,{encoding:j})}catch(j){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),j}let D;if(g$.includes(n)){const j=Ns(JSON.stringify(w)),K=Ns(I);D=await this.client.core.verify.register({id:K,decryptedId:j})}const T=Lr[n].req;if(T.attestation=D,a&&(T.ttl=a),u&&(T.id=u),this.client.core.history.set(i,w),S){const j=yh(b,i,I);await global.Linking.openURL(j,this.client.name)}else{const j=Lr[n].req;a&&(j.ttl=a),u&&(j.id=u),l?(j.internal=Mn(pr({},j.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,I,j)):this.client.core.relayer.publish(i,I,j).catch(K=>this.client.logger.error(K))}return w.id},this.sendResult=async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:a,encodeOpts:u,appLink:h}=r,l=Oh(i,s);let b;const w=h&&typeof(global==null?void 0:global.Linking)<"u";try{const S=w?yu:ao;b=await this.client.core.crypto.encode(n,l,Mn(pr({},u||{}),{encoding:S}))}catch(S){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),S}let I;try{I=await this.client.core.history.get(n,i)}catch(S){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),S}if(w){const S=yh(h,n,b);await global.Linking.openURL(S,this.client.name)}else{const S=Lr[I.request.method].res;a?(S.internal=Mn(pr({},S.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,b,S)):this.client.core.relayer.publish(n,b,S).catch(D=>this.client.logger.error(D))}await this.client.core.history.resolve(l)},this.sendError=async r=>{const{id:i,topic:n,error:s,encodeOpts:a,rpcOpts:u,appLink:h}=r,l=Ph(i,s);let b;const w=h&&typeof(global==null?void 0:global.Linking)<"u";try{const S=w?yu:ao;b=await this.client.core.crypto.encode(n,l,Mn(pr({},a||{}),{encoding:S}))}catch(S){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),S}let I;try{I=await this.client.core.history.get(n,i)}catch(S){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),S}if(w){const S=yh(h,n,b);await global.Linking.openURL(S,this.client.name)}else{const S=u||Lr[I.request.method].res;this.client.core.relayer.publish(n,b,S)}await this.client.core.history.resolve(l)},this.cleanup=async()=>{const r=[],i=[];this.client.session.getAll().forEach(n=>{let s=!1;io(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=>{io(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...r.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===ps.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=ps.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=ps.idle},this.processRequest=async r=>{const{topic:i,payload:n,attestation:s,transportType:a,encryptedId:u}=r,h=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:h}))switch(h){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:u});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:u,transportType:a});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:u,transportType:a});default:return this.client.logger.info(`Unsupported request method ${h}`)}},this.onRelayEventResponse=async r=>{const{topic:i,payload:n,transportType:s}=r,a=(await this.client.core.history.get(i,n.id)).request.method;switch(a){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 ${a}`)}},this.onRelayEventUnknownPayload=r=>{const{topic:i}=r,{message:n}=Ee("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)},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)},this.onSessionProposeRequest=async r=>{const{topic:i,payload:n,attestation:s,encryptedId:a}=r,{params:u,id:h}=n;try{const l=this.client.core.eventClient.getEvent({topic:i});this.isValidConnect(pr({},n.params));const b=u.expiryTimestamp||Ir(Lr.wc_sessionPropose.req.ttl),w=pr({id:h,pairingTopic:i,expiryTimestamp:b},u);await this.setProposal(h,w);const I=await this.getVerifyContext({attestationId:s,hash:Ns(JSON.stringify(n)),encryptedId:a,metadata:w.proposer.metadata});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(Bs.proposal_listener_not_found)),l?.addTrace(ds.emit_session_proposal),this.client.events.emit("session_proposal",{id:h,params:w,verifyContext:I})}catch(l){await this.sendError({id:h,topic:i,error:l,rpcOpts:Lr.wc_sessionPropose.autoReject}),this.client.logger.error(l)}},this.onSessionProposeResponse=async(r,i,n)=>{const{id:s}=i;if(fs(i)){const{result:a}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:a});const u=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:u});const h=u.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:h});const l=a.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const b=await this.client.core.crypto.generateSharedKey(h,l);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:b});const w=await this.client.core.relayer.subscribe(b,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:w}),await this.client.core.pairing.activate({topic:r})}else if(rn(i)){await this.client.proposal.delete(s,Gt("USER_DISCONNECTED"));const a=Dt("session_connect");if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners, 954`);this.events.emit(Dt("session_connect"),{error:i.error})}},this.onSessionSettleRequest=async(r,i)=>{const{id:n,params:s}=i;try{this.isValidSessionSettleRequest(s);const{relay:a,controller:u,expiry:h,namespaces:l,sessionProperties:b,sessionConfig:w}=i.params,I=Mn(pr(pr({topic:r,relay:a,expiry:h,namespaces:l,acknowledged:!0,pairingTopic:"",requiredNamespaces:{},optionalNamespaces:{},controller:u.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:u.publicKey,metadata:u.metadata}},b&&{sessionProperties:b}),w&&{sessionConfig:w}),{transportType:Zt.relay}),S=Dt("session_connect");if(this.events.listenerCount(S)===0)throw new Error(`emitting ${S} without any listeners 997`);this.events.emit(Dt("session_connect"),{session:I}),await this.sendResult({id:i.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(a){await this.sendError({id:n,topic:r,error:a}),this.client.logger.error(a)}},this.onSessionSettleResponse=async(r,i)=>{const{id:n}=i;fs(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(Dt("session_approve",n),{})):rn(i)&&(await this.client.session.delete(r,Gt("USER_DISCONNECTED")),this.events.emit(Dt("session_approve",n),{error:i.error}))},this.onSessionUpdateRequest=async(r,i)=>{const{params:n,id:s}=i;try{const a=`${r}_session_update`,u=Mu.get(a);if(u&&this.isRequestOutOfSync(u,s)){this.client.logger.info(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:Gt("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(pr({topic:r},n));try{Mu.set(a,s),await this.client.session.update(r,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(h){throw Mu.delete(a),h}this.client.events.emit("session_update",{id:s,topic:r,params:n})}catch(a){await this.sendError({id:s,topic:r,error:a}),this.client.logger.error(a)}},this.isRequestOutOfSync=(r,i)=>parseInt(i.toString().slice(0,-3))<=parseInt(r.toString().slice(0,-3)),this.onSessionUpdateResponse=(r,i)=>{const{id:n}=i,s=Dt("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);fs(i)?this.events.emit(Dt("session_update",n),{}):rn(i)&&this.events.emit(Dt("session_update",n),{error:i.error})},this.onSessionExtendRequest=async(r,i)=>{const{id:n}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,Ir(lc)),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)}},this.onSessionExtendResponse=(r,i)=>{const{id:n}=i,s=Dt("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);fs(i)?this.events.emit(Dt("session_extend",n),{}):rn(i)&&this.events.emit(Dt("session_extend",n),{error:i.error})},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)}},this.onSessionPingResponse=(r,i)=>{const{id:n}=i,s=Dt("session_ping",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);setTimeout(()=>{fs(i)?this.events.emit(Dt("session_ping",n),{}):rn(i)&&this.events.emit(Dt("session_ping",n),{error:i.error})},500)},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(hi.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:Gt("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async r=>{var i,n,s;const{topic:a,payload:u,attestation:h,encryptedId:l,transportType:b}=r,{id:w,params:I}=u;try{await this.isValidRequest(pr({topic:a},I));const S=this.client.session.get(a),D=await this.getVerifyContext({attestationId:h,hash:Ns(JSON.stringify(Qo("wc_sessionRequest",I,w))),encryptedId:l,metadata:S.peer.metadata,transportType:b}),T={id:w,topic:a,params:I,verifyContext:D};await this.setPendingSessionRequest(T),b===Zt.link_mode&&(i=S.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((n=S.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(T):(this.addSessionRequestToSessionRequestQueue(T),this.processSessionRequestQueue())}catch(S){await this.sendError({id:w,topic:a,error:S}),this.client.logger.error(S)}},this.onSessionRequestResponse=(r,i)=>{const{id:n}=i,s=Dt("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);fs(i)?this.events.emit(Dt("session_request",n),{result:i.result}):rn(i)&&this.events.emit(Dt("session_request",n),{error:i.error})},this.onSessionEventRequest=async(r,i)=>{const{id:n,params:s}=i;try{const a=`${r}_session_event_${s.event.name}`,u=Mu.get(a);if(u&&this.isRequestOutOfSync(u,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(pr({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),Mu.set(a,n)}catch(a){await this.sendError({id:n,topic:r,error:a}),this.client.logger.error(a)}},this.onSessionAuthenticateResponse=(r,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),fs(i)?this.events.emit(Dt("session_request",n),{result:i.result}):rn(i)&&this.events.emit(Dt("session_request",n),{error:i.error})},this.onSessionAuthenticateRequest=async r=>{var i;const{topic:n,payload:s,attestation:a,encryptedId:u,transportType:h}=r;try{const{requester:l,authPayload:b,expiryTimestamp:w}=s.params,I=await this.getVerifyContext({attestationId:a,hash:Ns(JSON.stringify(s)),encryptedId:u,metadata:l.metadata,transportType:h}),S={requester:l,pairingTopic:n,id:s.id,authPayload:b,verifyContext:I,expiryTimestamp:w};await this.setAuthRequest(s.id,{request:S,pairingTopic:n,transportType:h}),h===Zt.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:I})}catch(l){this.client.logger.error(l);const b=s.params.requester.publicKey,w=await this.client.core.crypto.generateKeyPair(),I=this.getAppLinkIfEnabled(s.params.requester.metadata,h),S={type:Rs,receiverPublicKey:b,senderPublicKey:w};await this.sendError({id:s.id,topic:n,error:l,encodeOpts:S,rpcOpts:Lr.wc_sessionAuthenticate.autoReject,appLink:I})}},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=ps.idle,this.processSessionRequestQueue()},xe.toMiliseconds(this.requestQueueDelay))},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 a=s.request.id,u=Dt("session_request",a);if(this.events.listenerCount(u)===0)throw new Error(`emitting ${u} without any listeners`);this.events.emit(Dt("session_request",s.request.id),{error:i})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===ps.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=ps.active,this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}},this.emitSessionRequest=r=>{this.client.events.emit("session_request",r)},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:Qo("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})},this.isValidConnect=async r=>{if(!_i(r)){const{message:h}=Ee("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(h)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:a,relays:u}=r;if(ci(i)||await this.isValidPairingTopic(i),!HI(u,!0)){const{message:h}=Ee("MISSING_OR_INVALID",`connect() relays: ${u}`);throw new Error(h)}!ci(n)&&Iu(n)!==0&&this.validateNamespaces(n,"requiredNamespaces"),!ci(s)&&Iu(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),ci(a)||this.validateSessionProps(a,"sessionProperties")},this.validateNamespaces=(r,i)=>{const n=zI(r,"connect()",i);if(n)throw new Error(n.message)},this.isValidApprove=async r=>{if(!_i(r))throw new Error(Ee("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:n,relayProtocol:s,sessionProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const u=this.client.proposal.get(i),h=Bd(n,"approve()");if(h)throw new Error(h.message);const l=Eb(u.requiredNamespaces,n,"approve()");if(l)throw new Error(l.message);if(!yr(s,!0)){const{message:b}=Ee("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(b)}ci(a)||this.validateSessionProps(a,"sessionProperties")},this.isValidReject=async r=>{if(!_i(r)){const{message:s}=Ee("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:i,reason:n}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!WI(n)){const{message:s}=Ee("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!_i(r)){const{message:l}=Ee("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:i,controller:n,namespaces:s,expiry:a}=r;if(!wb(i)){const{message:l}=Ee("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const u=BI(n,"onSessionSettleRequest()");if(u)throw new Error(u.message);const h=Bd(s,"onSessionSettleRequest()");if(h)throw new Error(h.message);if(io(a)){const{message:l}=Ee("EXPIRED","onSessionSettleRequest()");throw new Error(l)}},this.isValidUpdate=async r=>{if(!_i(r)){const{message:h}=Ee("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(h)}const{topic:i,namespaces:n}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),a=Bd(n,"update()");if(a)throw new Error(a.message);const u=Eb(s.requiredNamespaces,n,"update()");if(u)throw new Error(u.message)},this.isValidExtend=async r=>{if(!_i(r)){const{message:n}=Ee("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(n)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)},this.isValidRequest=async r=>{if(!_i(r)){const{message:h}=Ee("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(h)}const{topic:i,request:n,chainId:s,expiry:a}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:u}=this.client.session.get(i);if(!_b(u,s)){const{message:h}=Ee("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(h)}if(!VI(n)){const{message:h}=Ee("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(h)}if(!JI(u,s,n.method)){const{message:h}=Ee("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(h)}if(a&&!eM(a,a1)){const{message:h}=Ee("MISSING_OR_INVALID",`request() expiry: ${a}. Expiry must be a number (in seconds) between ${a1.min} and ${a1.max}`);throw new Error(h)}},this.isValidRespond=async r=>{var i;if(!_i(r)){const{message:a}=Ee("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}const{topic:n,response:s}=r;try{await this.isValidSessionTopic(n)}catch(a){throw(i=r?.response)!=null&&i.id&&this.cleanupAfterResponse(r),a}if(!GI(s)){const{message:a}=Ee("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}},this.isValidPing=async r=>{if(!_i(r)){const{message:n}=Ee("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)},this.isValidEmit=async r=>{if(!_i(r)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(u)}const{topic:i,event:n,chainId:s}=r;await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!_b(a,s)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(u)}if(!YI(n)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(u)}if(!QI(a,s,n.name)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(u)}},this.isValidDisconnect=async r=>{if(!_i(r)){const{message:n}=Ee("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)},this.isValidAuthenticate=r=>{const{chains:i,uri:n,domain:s,nonce:a}=r;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!yr(n,!1))throw new Error("uri is required parameter");if(!yr(s,!1))throw new Error("domain is required parameter");if(!yr(a,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(h=>ou(h).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:u}=ou(i[0]);if(u!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async r=>{const{attestationId:i,hash:n,encryptedId:s,metadata:a,transportType:u}=r,h={verified:{verifyUrl:a.verifyUrl||Lu,validation:"UNKNOWN",origin:a.url||""}};try{if(u===Zt.link_mode){const b=this.getAppLinkIfEnabled(a,u);return h.verified.validation=b&&new URL(b).origin===new URL(a.url).origin?"VALID":"INVALID",h}const l=await this.client.core.verify.resolve({attestationId:i,hash:n,encryptedId:s,verifyUrl:a.verifyUrl});l&&(h.verified.origin=l.origin,h.verified.isScam=l.isScam,h.verified.validation=l.origin===new URL(a.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(h)}`),h},this.validateSessionProps=(r,i)=>{Object.values(r).forEach(n=>{if(!yr(n,!1)){const{message:s}=Ee("MISSING_OR_INVALID",`${i} must be in Record<string, string> format. Received: ${JSON.stringify(n)}`);throw new Error(s)}})},this.getPendingAuthRequest=r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0},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 a of this.recentlyDeletedMap.keys()){if(n++>=s)break;this.recentlyDeletedMap.delete(a)}}},this.checkRecentlyDeleted=r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:n}=Ee("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(n)}},this.isLinkModeEnabled=(r,i)=>{var n,s,a,u,h,l,b,w,I;return!r||i!==Zt.link_mode?!1:((s=(n=this.client.metadata)==null?void 0:n.redirect)==null?void 0:s.linkMode)===!0&&((u=(a=this.client.metadata)==null?void 0:a.redirect)==null?void 0:u.universal)!==void 0&&((l=(h=this.client.metadata)==null?void 0:h.redirect)==null?void 0:l.universal)!==""&&((b=r?.redirect)==null?void 0:b.universal)!==void 0&&((w=r?.redirect)==null?void 0:w.universal)!==""&&((I=r?.redirect)==null?void 0:I.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"},this.getAppLinkIfEnabled=(r,i)=>{var n;return this.isLinkModeEnabled(r,i)?(n=r?.redirect)==null?void 0:n.universal:void 0},this.handleLinkModeMessage=({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=W2(r,"topic")||"",n=decodeURIComponent(W2(r,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:Zt.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})},this.registerLinkModeListeners=async()=>{var r;if(typeof process<"u"&&process.env.IS_VITEST||Va()&&(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)}}}}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(hi.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:a}=this.client.auth.authKeys.keys.includes(Th)?this.client.auth.authKeys.get(Th):{responseTopic:void 0,publicKey:void 0},u=await this.client.core.crypto.decode(r,i,{receiverPublicKey:a,encoding:s===Zt.link_mode?yu:ao});try{Qd(u)?(this.client.core.history.set(r,u),this.onRelayEventRequest({topic:r,payload:u,attestation:n,transportType:s,encryptedId:Ns(i)})):$h(u)?(await this.client.core.history.resolve(u),await this.onRelayEventResponse({topic:r,payload:u,transportType:s}),this.client.core.history.delete(r,u.id)):this.onRelayEventUnknownPayload({topic:r,payload:u,transportType:s})}catch(h){this.client.logger.error(h)}}registerExpirerEvents(){this.client.core.expirer.on(sn.expired,async e=>{const{topic:r,id:i}=K2(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,Ee("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,Ee("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(fc.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(fc.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!yr(e,!1)){const{message:r}=Ee("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=Ee("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(io(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=Ee("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!yr(e,!1)){const{message:r}=Ee("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=Ee("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(io(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=Ee("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=Ee("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(yr(e,!1)){const{message:r}=Ee("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=Ee("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!KI(e)){const{message:r}=Ee("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=Ee("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(io(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=Ee("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class M$ extends ea{constructor(e,r){super(e,r,h$,s1),this.core=e,this.logger=r}}class C$ extends ea{constructor(e,r){super(e,r,l$,s1),this.core=e,this.logger=r}}class D$ extends ea{constructor(e,r){super(e,r,p$,s1,i=>i.id),this.core=e,this.logger=r}}class O$ extends ea{constructor(e,r){super(e,r,b$,Nh,()=>Th),this.core=e,this.logger=r}}class P$ extends ea{constructor(e,r){super(e,r,y$,Nh),this.core=e,this.logger=r}}class $$ extends ea{constructor(e,r){super(e,r,w$,Nh,i=>i.id),this.core=e,this.logger=r}}class R${constructor(e,r){this.core=e,this.logger=r,this.authKeys=new O$(this.core,this.logger),this.pairingTopics=new P$(this.core,this.logger),this.requests=new $$(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}class c1 extends AC{constructor(e){super(e),this.protocol=U3,this.version=j3,this.name=o1.name,this.events=new Ur.exports.EventEmitter,this.on=(i,n)=>this.events.on(i,n),this.once=(i,n)=>this.events.once(i,n),this.off=(i,n)=>this.events.off(i,n),this.removeListener=(i,n)=>this.events.removeListener(i,n),this.removeAllListeners=i=>this.events.removeAllListeners(i),this.connect=async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}},this.pair=async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}},this.approve=async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}},this.reject=async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}},this.update=async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}},this.extend=async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}},this.request=async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}},this.respond=async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}},this.ping=async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}},this.emit=async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}},this.disconnect=async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}},this.find=i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}},this.authenticate=async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}},this.formatAuthMessage=i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}},this.approveSessionAuthenticate=async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}},this.rejectSessionAuthenticate=async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}},this.name=e?.name||o1.name,this.metadata=e?.metadata||GE(),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:cs(Dh({level:e?.logger||o1.logger}));this.core=e?.core||new f$(e),this.logger=ui(r,this.name),this.session=new C$(this.core,this.logger),this.proposal=new M$(this.core,this.logger),this.pendingRequest=new D$(this.core,this.logger),this.engine=new I$(this),this.auth=new R$(this.core,this.logger)}static async init(e){const r=new c1(e);return await r.initialize(),r}get context(){return Ai(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"),this.engine.processRelayMessageCache()}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}var u1={exports:{}};(function(t,e){var r=typeof self<"u"?self:Vr,i=function(){function s(){this.fetch=!1,this.DOMException=r.DOMException}return s.prototype=r,new s}();(function(s){(function(a){var u={searchParams:"URLSearchParams"in s,iterable:"Symbol"in s&&"iterator"in Symbol,blob:"FileReader"in s&&"Blob"in s&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in s,arrayBuffer:"ArrayBuffer"in s};function h(d){return d&&DataView.prototype.isPrototypeOf(d)}if(u.arrayBuffer)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],b=ArrayBuffer.isView||function(d){return d&&l.indexOf(Object.prototype.toString.call(d))>-1};function w(d){if(typeof d!="string"&&(d=String(d)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(d))throw new TypeError("Invalid character in header field name");return d.toLowerCase()}function I(d){return typeof d!="string"&&(d=String(d)),d}function S(d){var v={next:function(){var E=d.shift();return{done:E===void 0,value:E}}};return u.iterable&&(v[Symbol.iterator]=function(){return v}),v}function D(d){this.map={},d instanceof D?d.forEach(function(v,E){this.append(E,v)},this):Array.isArray(d)?d.forEach(function(v){this.append(v[0],v[1])},this):d&&Object.getOwnPropertyNames(d).forEach(function(v){this.append(v,d[v])},this)}D.prototype.append=function(d,v){d=w(d),v=I(v);var E=this.map[d];this.map[d]=E?E+", "+v:v},D.prototype.delete=function(d){delete this.map[w(d)]},D.prototype.get=function(d){return d=w(d),this.has(d)?this.map[d]:null},D.prototype.has=function(d){return this.map.hasOwnProperty(w(d))},D.prototype.set=function(d,v){this.map[w(d)]=I(v)},D.prototype.forEach=function(d,v){for(var E in this.map)this.map.hasOwnProperty(E)&&d.call(v,this.map[E],E,this)},D.prototype.keys=function(){var d=[];return this.forEach(function(v,E){d.push(E)}),S(d)},D.prototype.values=function(){var d=[];return this.forEach(function(v){d.push(v)}),S(d)},D.prototype.entries=function(){var d=[];return this.forEach(function(v,E){d.push([E,v])}),S(d)},u.iterable&&(D.prototype[Symbol.iterator]=D.prototype.entries);function T(d){if(d.bodyUsed)return Promise.reject(new TypeError("Already read"));d.bodyUsed=!0}function j(d){return new Promise(function(v,E){d.onload=function(){v(d.result)},d.onerror=function(){E(d.error)}})}function K(d){var v=new FileReader,E=j(v);return v.readAsArrayBuffer(d),E}function F(d){var v=new FileReader,E=j(v);return v.readAsText(d),E}function W(d){for(var v=new Uint8Array(d),E=new Array(v.length),C=0;C<v.length;C++)E[C]=String.fromCharCode(v[C]);return E.join("")}function R(d){if(d.slice)return d.slice(0);var v=new Uint8Array(d.byteLength);return v.set(new Uint8Array(d)),v.buffer}function U(){return this.bodyUsed=!1,this._initBody=function(d){this._bodyInit=d,d?typeof d=="string"?this._bodyText=d:u.blob&&Blob.prototype.isPrototypeOf(d)?this._bodyBlob=d:u.formData&&FormData.prototype.isPrototypeOf(d)?this._bodyFormData=d:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(d)?this._bodyText=d.toString():u.arrayBuffer&&u.blob&&h(d)?(this._bodyArrayBuffer=R(d.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(d)||b(d))?this._bodyArrayBuffer=R(d):this._bodyText=d=Object.prototype.toString.call(d):this._bodyText="",this.headers.get("content-type")||(typeof d=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(d)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var d=T(this);if(d)return d;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?T(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(K)}),this.text=function(){var d=T(this);if(d)return d;if(this._bodyBlob)return F(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(W(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(ee)}),this.json=function(){return this.text().then(JSON.parse)},this}var H=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function _(d){var v=d.toUpperCase();return H.indexOf(v)>-1?v:d}function B(d,v){v=v||{};var E=v.body;if(d instanceof B){if(d.bodyUsed)throw new TypeError("Already read");this.url=d.url,this.credentials=d.credentials,v.headers||(this.headers=new D(d.headers)),this.method=d.method,this.mode=d.mode,this.signal=d.signal,!E&&d._bodyInit!=null&&(E=d._bodyInit,d.bodyUsed=!0)}else this.url=String(d);if(this.credentials=v.credentials||this.credentials||"same-origin",(v.headers||!this.headers)&&(this.headers=new D(v.headers)),this.method=_(v.method||this.method||"GET"),this.mode=v.mode||this.mode||null,this.signal=v.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&E)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(E)}B.prototype.clone=function(){return new B(this,{body:this._bodyInit})};function ee(d){var v=new FormData;return d.trim().split("&").forEach(function(E){if(E){var C=E.split("="),O=C.shift().replace(/\+/g," "),M=C.join("=").replace(/\+/g," ");v.append(decodeURIComponent(O),decodeURIComponent(M))}}),v}function ie(d){var v=new D,E=d.replace(/\r?\n[\t ]+/g," ");return E.split(/\r?\n/).forEach(function(C){var O=C.split(":"),M=O.shift().trim();if(M){var g=O.join(":").trim();v.append(M,g)}}),v}U.call(B.prototype);function L(d,v){v||(v={}),this.type="default",this.status=v.status===void 0?200:v.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in v?v.statusText:"OK",this.headers=new D(v.headers),this.url=v.url||"",this._initBody(d)}U.call(L.prototype),L.prototype.clone=function(){return new L(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new D(this.headers),url:this.url})},L.error=function(){var d=new L(null,{status:0,statusText:""});return d.type="error",d};var y=[301,302,303,307,308];L.redirect=function(d,v){if(y.indexOf(v)===-1)throw new RangeError("Invalid status code");return new L(null,{status:v,headers:{location:d}})},a.DOMException=s.DOMException;try{new a.DOMException}catch{a.DOMException=function(v,E){this.message=v,this.name=E;var C=Error(v);this.stack=C.stack},a.DOMException.prototype=Object.create(Error.prototype),a.DOMException.prototype.constructor=a.DOMException}function f(d,v){return new Promise(function(E,C){var O=new B(d,v);if(O.signal&&O.signal.aborted)return C(new a.DOMException("Aborted","AbortError"));var M=new XMLHttpRequest;function g(){M.abort()}M.onload=function(){var m={status:M.status,statusText:M.statusText,headers:ie(M.getAllResponseHeaders()||"")};m.url="responseURL"in M?M.responseURL:m.headers.get("X-Request-URL");var N="response"in M?M.response:M.responseText;E(new L(N,m))},M.onerror=function(){C(new TypeError("Network request failed"))},M.ontimeout=function(){C(new TypeError("Network request failed"))},M.onabort=function(){C(new a.DOMException("Aborted","AbortError"))},M.open(O.method,O.url,!0),O.credentials==="include"?M.withCredentials=!0:O.credentials==="omit"&&(M.withCredentials=!1),"responseType"in M&&u.blob&&(M.responseType="blob"),O.headers.forEach(function(m,N){M.setRequestHeader(N,m)}),O.signal&&(O.signal.addEventListener("abort",g),M.onreadystatechange=function(){M.readyState===4&&O.signal.removeEventListener("abort",g)}),M.send(typeof O._bodyInit>"u"?null:O._bodyInit)})}return f.polyfill=!0,s.fetch||(s.fetch=f,s.Headers=D,s.Request=B,s.Response=L),a.Headers=D,a.Request=B,a.Response=L,a.fetch=f,Object.defineProperty(a,"__esModule",{value:!0}),a})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var n=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})(u1,u1.exports);var V3=q5(u1.exports),N$=Object.defineProperty,T$=Object.defineProperties,L$=Object.getOwnPropertyDescriptors,G3=Object.getOwnPropertySymbols,B$=Object.prototype.hasOwnProperty,F$=Object.prototype.propertyIsEnumerable,Y3=(t,e,r)=>e in t?N$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,J3=(t,e)=>{for(var r in e||(e={}))B$.call(e,r)&&Y3(t,r,e[r]);if(G3)for(var r of G3(e))F$.call(e,r)&&Y3(t,r,e[r]);return t},Q3=(t,e)=>T$(t,L$(e));const k$={Accept:"application/json","Content-Type":"application/json"},U$="POST",Z3={headers:k$,method:U$},X3=10;class gs{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new Ur.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!Jb(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=Cs(e),i=await(await V3(this.url,Q3(J3({},Z3),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!Jb(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=Cs({id:1,jsonrpc:"2.0",method:"test",params:[]});await V3(e,Q3(J3({},Z3),{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"?jo(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=Ph(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return Hb(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>X3&&this.events.setMaxListeners(X3)}}const e6="error",j$="wss://relay.walletconnect.com",q$="wc",z$="universal_provider",t6=`${q$}@2:${z$}:`,H$="https://rpc.walletconnect.com/v1/",dc="generic",Cn={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Uu=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},f1={exports:{}};/**
|
|
44
44
|
* @license
|
|
45
45
|
* Lodash <https://lodash.com/>
|
|
46
46
|
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
|