@walletconnect/ethereum-provider 2.15.3-rc.0 → 2.15.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -40,7 +40,7 @@
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 zd=function(t,e){return zd=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])},zd(t,e)};function IC(t,e){zd(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Hd=function(){return Hd=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},Hd.apply(this,arguments)};function MC(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 CC(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 DC(t,e){return function(r,i){e(r,i,t)}}function OC(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function PC(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{d(i.next(b))}catch(w){a(w)}}function l(b){try{d(i.throw(b))}catch(w){a(w)}}function d(b){b.done?s(b.value):n(b.value).then(u,l)}d((i=i.apply(t,e||[])).next())})}function $C(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(d){return function(b){return l([d,b])}}function l(d){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,n&&(s=d[0]&2?n.return:d[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,d[1])).done)return s;switch(n=0,s&&(d=[d[0]&2,s.value]),d[0]){case 0:case 1:s=d;break;case 4:return r.label++,{value:d[1],done:!1};case 5:r.label++,n=d[1],d=[0];continue;case 7:d=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(d[0]===6||d[0]===2)){r=0;continue}if(d[0]===3&&(!s||d[1]>s[0]&&d[1]<s[3])){r.label=d[1];break}if(d[0]===6&&r.label<s[1]){r.label=s[1],s=d;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(d);break}s[2]&&r.ops.pop(),r.trys.pop();continue}d=e.call(t,r)}catch(b){d=[6,b],n=0}finally{i=s=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}function RC(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function NC(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Kd(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 Fb(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 TC(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Fb(arguments[e]));return t}function LC(){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 Iu(t){return this instanceof Iu?(this.v=t,this):new Iu(t)}function BC(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,L){s.push([I,S,D,L])>1||u(I,S)})})}function u(I,S){try{l(i[I](S))}catch(D){w(s[0][3],D)}}function l(I){I.value instanceof Iu?Promise.resolve(I.value.v).then(d,b):w(s[0][2],I)}function d(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 FC(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:Iu(t[n](a)),done:n==="return"}:s?s(a):a}:s}}function UC(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 Kd=="function"?Kd(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,l){a=t[s](a),n(u,l,a.done,a.value)})}}function n(s,a,u,l){Promise.resolve(l).then(function(d){s({value:d,done:u})},a)}}function kC(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 HC(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 KC=Object.freeze({__proto__:null,__extends:IC,get __assign(){return Hd},__rest:MC,__decorate:CC,__param:DC,__metadata:OC,__awaiter:PC,__generator:$C,__createBinding:RC,__exportStar:NC,__values:Kd,__read:Fb,__spread:TC,__spreadArrays:LC,__await:Iu,__asyncGenerator:BC,__asyncDelegator:FC,__asyncValues:UC,__makeTemplateObject:kC,__importStar:jC,__importDefault:qC,__classPrivateFieldGet:zC,__classPrivateFieldSet:HC}),WC=f0(KC),Rs={},Ub;function VC(){if(Ub)return Rs;Ub=1,Object.defineProperty(Rs,"__esModule",{value:!0}),Rs.isBrowserCryptoAvailable=Rs.getSubtleCrypto=Rs.getBrowerCrypto=void 0;function t(){return Wr?.crypto||Wr?.msCrypto||{}}Rs.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}Rs.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Rs.isBrowserCryptoAvailable=r,Rs}var Ns={},kb;function GC(){if(kb)return Ns;kb=1,Object.defineProperty(Ns,"__esModule",{value:!0}),Ns.isBrowser=Ns.isNode=Ns.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ns.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Ns.isNode=e;function r(){return!t()&&!e()}return Ns.isBrowser=r,Ns}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=WC;e.__exportStar(VC(),t),e.__exportStar(GC(),t)})(Bb);function no(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Ho(t=6){return BigInt(no(t))}function sc(t,e,r){return{id:r||no(),jsonrpc:"2.0",method:t,params:e}}function Ah(t,e){return{id:t,jsonrpc:"2.0",result:e}}function xh(t,e,r){return{id:t,jsonrpc:"2.0",error:YC(e,r)}}function YC(t,e){return typeof t>"u"?Tb(Rb):(typeof t=="string"&&(t=Object.assign(Object.assign({},Tb(qd)),{message:t})),typeof e<"u"&&(t.data=e),xC(t.code)&&(t=SC(t.code)),t)}class JC{}class QC extends JC{constructor(){super()}}class ZC extends QC{constructor(e){super()}}const XC="^https?:",eD="^wss?:";function tD(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function jb(t,e){const r=tD(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function qb(t){return jb(t,XC)}function zb(t){return jb(t,eD)}function rD(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Hb(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Wd(t){return Hb(t)&&"method"in t}function Sh(t){return Hb(t)&&(cs(t)||Xi(t))}function cs(t){return"result"in t}function Xi(t){return"error"in t}class An extends ZC{constructor(e){super(e),this.events=new Br.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(sc(e.method,e.params||[],e.id||Ho().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=>{Xi(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),Sh(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 iD=()=>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"),nD=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Kb=t=>t.split("?")[0],Wb=10,sD=iD();class oD{constructor(e){if(this.url=e,this.events=new Br.exports.EventEmitter,this.registering=!1,!zb(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(Is(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!zb(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=Bb.isReactNative()?{headers:{origin:n}}:{rejectUnauthorized:!rD(e)},a=new sD(e,[],s);nD()?a.onerror=u=>{const l=u;i(this.emitError(l.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"?qa(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=xh(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return Lb(e,Kb(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Wb&&this.events.setMaxListeners(Wb)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Kb(this.url)}`));return this.events.emit("register_error",r),r}}var Vd={exports:{}};(function(t,e){var r=200,i="__lodash_hash_undefined__",n=1,s=2,a=9007199254740991,u="[object Arguments]",l="[object Array]",d="[object AsyncFunction]",b="[object Boolean]",w="[object Date]",I="[object Error]",S="[object Function]",D="[object GeneratorFunction]",L="[object Map]",K="[object Number]",H="[object Null]",U="[object Object]",W="[object Promise]",R="[object Proxy]",k="[object RegExp]",z="[object Set]",_="[object String]",B="[object Symbol]",X="[object Undefined]",re="[object WeakMap]",T="[object ArrayBuffer]",y="[object DataView]",f="[object Float32Array]",h="[object Float64Array]",v="[object Int8Array]",E="[object Int16Array]",C="[object Int32Array]",P="[object Uint8Array]",M="[object Uint8ClampedArray]",g="[object Uint16Array]",m="[object Uint32Array]",N=/[\\^$.*+?()[\]{}|]/g,ee=/^\[object .+?Constructor\]$/,ae=/^(?:0|[1-9]\d*)$/,O={};O[f]=O[h]=O[v]=O[E]=O[C]=O[P]=O[M]=O[g]=O[m]=!0,O[u]=O[l]=O[T]=O[b]=O[y]=O[w]=O[I]=O[S]=O[L]=O[K]=O[U]=O[k]=O[z]=O[_]=O[re]=!1;var te=typeof Wr=="object"&&Wr&&Wr.Object===Object&&Wr,q=typeof self=="object"&&self&&self.Object===Object&&self,G=te||q||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,ie){for(var pe=-1,ke=J==null?0:J.length,Xt=0,bt=[];++pe<ke;){var or=J[pe];ie(or,pe,J)&&(bt[Xt++]=or)}return bt}function we(J,ie){for(var pe=-1,ke=ie.length,Xt=J.length;++pe<ke;)J[Xt+pe]=ie[pe];return J}function Re(J,ie){for(var pe=-1,ke=J==null?0:J.length;++pe<ke;)if(ie(J[pe],pe,J))return!0;return!1}function Xe(J,ie){for(var pe=-1,ke=Array(J);++pe<J;)ke[pe]=ie(pe);return ke}function Oe(J){return function(ie){return J(ie)}}function Ne(J,ie){return J.has(ie)}function Me(J,ie){return J?.[ie]}function be(J){var ie=-1,pe=Array(J.size);return J.forEach(function(ke,Xt){pe[++ie]=[Xt,ke]}),pe}function Pe(J,ie){return function(pe){return J(ie(pe))}}function Te(J){var ie=-1,pe=Array(J.size);return J.forEach(function(ke){pe[++ie]=ke}),pe}var ve=Array.prototype,$e=Function.prototype,xe=Object.prototype,me=G["__core-js_shared__"],Ue=$e.toString,Ce=xe.hasOwnProperty,_e=function(){var J=/[^.]+$/.exec(me&&me.keys&&me.keys.IE_PROTO||"");return J?"Symbol(src)_1."+J:""}(),Ke=xe.toString,Ve=RegExp("^"+Ue.call(Ce).replace(N,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ae=V?G.Buffer:void 0,We=G.Symbol,pt=G.Uint8Array,Ge=xe.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=ki(G,"DataView"),et=ki(G,"Map"),it=ki(G,"Promise"),Be=ki(G,"Set"),rt=ki(G,"WeakMap"),tt=ki(Object,"create"),je=Us(Le),ht=Us(et),nt=Us(it),qe=Us(Be),st=Us(rt),at=We?We.prototype:void 0,Fe=at?at.valueOf:void 0;function Ze(J){var ie=-1,pe=J==null?0:J.length;for(this.clear();++ie<pe;){var ke=J[ie];this.set(ke[0],ke[1])}}function lt(){this.__data__=tt?tt(null):{},this.size=0}function ze(J){var ie=this.has(J)&&delete this.__data__[J];return this.size-=ie?1:0,ie}function jt(J){var ie=this.__data__;if(tt){var pe=ie[J];return pe===i?void 0:pe}return Ce.call(ie,J)?ie[J]:void 0}function qt(J){var ie=this.__data__;return tt?ie[J]!==void 0:Ce.call(ie,J)}function ct(J,ie){var pe=this.__data__;return this.size+=this.has(J)?0:1,pe[J]=tt&&ie===void 0?i:ie,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 ie=-1,pe=J==null?0:J.length;for(this.clear();++ie<pe;){var ke=J[ie];this.set(ke[0],ke[1])}}function Qr(){this.__data__=[],this.size=0}function Zr(J){var ie=this.__data__,pe=ha(ie,J);if(pe<0)return!1;var ke=ie.length-1;return pe==ke?ie.pop():It.call(ie,pe,1),--this.size,!0}function Xr(J){var ie=this.__data__,pe=ha(ie,J);return pe<0?void 0:ie[pe][1]}function ei(J){return ha(this.__data__,J)>-1}function ti(J,ie){var pe=this.__data__,ke=ha(pe,J);return ke<0?(++this.size,pe.push([J,ie])):pe[ke][1]=ie,this}_t.prototype.clear=Qr,_t.prototype.delete=Zr,_t.prototype.get=Xr,_t.prototype.has=ei,_t.prototype.set=ti;function pr(J){var ie=-1,pe=J==null?0:J.length;for(this.clear();++ie<pe;){var ke=J[ie];this.set(ke[0],ke[1])}}function Si(){this.size=0,this.__data__={hash:new Ze,map:new(et||_t),string:new Ze}}function Cn(J){var ie=bo(this,J).delete(J);return this.size-=ie?1:0,ie}function Ii(J){return bo(this,J).get(J)}function Dn(J){return bo(this,J).has(J)}function On(J,ie){var pe=bo(this,J),ke=pe.size;return pe.set(J,ie),this.size+=pe.size==ke?0:1,this}pr.prototype.clear=Si,pr.prototype.delete=Cn,pr.prototype.get=Ii,pr.prototype.has=Dn,pr.prototype.set=On;function Mi(J){var ie=-1,pe=J==null?0:J.length;for(this.__data__=new pr;++ie<pe;)this.add(J[ie])}function nn(J){return this.__data__.set(J,i),this}function sn(J){return this.__data__.has(J)}Mi.prototype.add=Mi.prototype.push=nn,Mi.prototype.has=sn;function Ir(J){var ie=this.__data__=new _t(J);this.size=ie.size}function Pn(){this.__data__=new _t,this.size=0}function $n(J){var ie=this.__data__,pe=ie.delete(J);return this.size=ie.size,pe}function Rn(J){return this.__data__.get(J)}function fa(J){return this.__data__.has(J)}function cl(J,ie){var pe=this.__data__;if(pe instanceof _t){var ke=pe.__data__;if(!et||ke.length<r-1)return ke.push([J,ie]),this.size=++pe.size,this;pe=this.__data__=new pr(ke)}return pe.set(J,ie),this.size=pe.size,this}Ir.prototype.clear=Pn,Ir.prototype.delete=$n,Ir.prototype.get=Rn,Ir.prototype.has=fa,Ir.prototype.set=cl;function ul(J,ie){var pe=Oc(J),ke=!pe&&_l(J),Xt=!pe&&!ke&&tf(J),bt=!pe&&!ke&&!Xt&&xl(J),or=pe||ke||Xt||bt,Er=or?Xe(J.length,String):[],Ft=Er.length;for(var er in J)(ie||Ce.call(J,er))&&!(or&&(er=="length"||Xt&&(er=="offset"||er=="parent")||bt&&(er=="buffer"||er=="byteLength"||er=="byteOffset")||vl(er,Ft)))&&Er.push(er);return Er}function ha(J,ie){for(var pe=J.length;pe--;)if(wl(J[pe][0],ie))return pe;return-1}function Xu(J,ie,pe){var ke=ie(J);return Oc(J)?ke:we(ke,pe(J))}function la(J){return J==null?J===void 0?X:H:gt&&gt in Object(J)?pl(J):Ap(J)}function ef(J){return pa(J)&&la(J)==u}function da(J,ie,pe,ke,Xt){return J===ie?!0:J==null||ie==null||!pa(J)&&!pa(ie)?J!==J&&ie!==ie:fl(J,ie,pe,ke,da,Xt)}function fl(J,ie,pe,ke,Xt,bt){var or=Oc(J),Er=Oc(ie),Ft=or?l:bs(J),er=Er?l:bs(ie);Ft=Ft==u?U:Ft,er=er==u?U:er;var yr=Ft==U,Ci=er==U,Ar=Ft==er;if(Ar&&tf(J)){if(!tf(ie))return!1;or=!0,yr=!1}if(Ar&&!yr)return bt||(bt=new Ir),or||xl(J)?Cc(J,ie,pe,ke,Xt,bt):Ep(J,ie,Ft,pe,ke,Xt,bt);if(!(pe&n)){var ar=yr&&Ce.call(J,"__wrapped__"),hi=Ci&&Ce.call(ie,"__wrapped__");if(ar||hi){var Nn=ar?J.value():J,on=hi?ie.value():ie;return bt||(bt=new Ir),Xt(Nn,on,pe,ke,bt)}}return Ar?(bt||(bt=new Ir),dl(J,ie,pe,ke,Xt,bt)):!1}function _p(J){if(!Al(J)||bl(J))return!1;var ie=Pc(J)?Ve:ee;return ie.test(Us(J))}function hl(J){return pa(J)&&El(J.length)&&!!O[la(J)]}function ll(J){if(!yl(J))return Tt(J);var ie=[];for(var pe in Object(J))Ce.call(J,pe)&&pe!="constructor"&&ie.push(pe);return ie}function Cc(J,ie,pe,ke,Xt,bt){var or=pe&n,Er=J.length,Ft=ie.length;if(Er!=Ft&&!(or&&Ft>Er))return!1;var er=bt.get(J);if(er&&bt.get(ie))return er==ie;var yr=-1,Ci=!0,Ar=pe&s?new Mi:void 0;for(bt.set(J,ie),bt.set(ie,J);++yr<Er;){var ar=J[yr],hi=ie[yr];if(ke)var Nn=or?ke(hi,ar,yr,ie,J,bt):ke(ar,hi,yr,J,ie,bt);if(Nn!==void 0){if(Nn)continue;Ci=!1;break}if(Ar){if(!Re(ie,function(on,ys){if(!Ne(Ar,ys)&&(ar===on||Xt(ar,on,pe,ke,bt)))return Ar.push(ys)})){Ci=!1;break}}else if(!(ar===hi||Xt(ar,hi,pe,ke,bt))){Ci=!1;break}}return bt.delete(J),bt.delete(ie),Ci}function Ep(J,ie,pe,ke,Xt,bt,or){switch(pe){case y:if(J.byteLength!=ie.byteLength||J.byteOffset!=ie.byteOffset)return!1;J=J.buffer,ie=ie.buffer;case T:return!(J.byteLength!=ie.byteLength||!bt(new pt(J),new pt(ie)));case b:case w:case K:return wl(+J,+ie);case I:return J.name==ie.name&&J.message==ie.message;case k:case _:return J==ie+"";case L:var Er=be;case z:var Ft=ke&n;if(Er||(Er=Te),J.size!=ie.size&&!Ft)return!1;var er=or.get(J);if(er)return er==ie;ke|=s,or.set(J,ie);var yr=Cc(Er(J),Er(ie),ke,Xt,bt,or);return or.delete(J),yr;case B:if(Fe)return Fe.call(J)==Fe.call(ie)}return!1}function dl(J,ie,pe,ke,Xt,bt){var or=pe&n,Er=Dc(J),Ft=Er.length,er=Dc(ie),yr=er.length;if(Ft!=yr&&!or)return!1;for(var Ci=Ft;Ci--;){var Ar=Er[Ci];if(!(or?Ar in ie:Ce.call(ie,Ar)))return!1}var ar=bt.get(J);if(ar&&bt.get(ie))return ar==ie;var hi=!0;bt.set(J,ie),bt.set(ie,J);for(var Nn=or;++Ci<Ft;){Ar=Er[Ci];var on=J[Ar],ys=ie[Ar];if(ke)var rf=or?ke(ys,on,Ar,ie,J,bt):ke(on,ys,Ar,J,ie,bt);if(!(rf===void 0?on===ys||Xt(on,ys,pe,ke,bt):rf)){hi=!1;break}Nn||(Nn=Ar=="constructor")}if(hi&&!Nn){var ga=J.constructor,Tr=ie.constructor;ga!=Tr&&"constructor"in J&&"constructor"in ie&&!(typeof ga=="function"&&ga instanceof ga&&typeof Tr=="function"&&Tr instanceof Tr)&&(hi=!1)}return bt.delete(J),bt.delete(ie),hi}function Dc(J){return Xu(J,Ip,gl)}function bo(J,ie){var pe=J.__data__;return ml(ie)?pe[typeof ie=="string"?"string":"hash"]:pe.map}function ki(J,ie){var pe=Me(J,ie);return _p(pe)?pe:void 0}function pl(J){var ie=Ce.call(J,gt),pe=J[gt];try{J[gt]=void 0;var ke=!0}catch{}var Xt=Ke.call(J);return ke&&(ie?J[gt]=pe:delete J[gt]),Xt}var gl=Je?function(J){return J==null?[]:(J=Object(J),ye(Je(J),function(ie){return Ge.call(J,ie)}))}:Zt,bs=la;(Le&&bs(new Le(new ArrayBuffer(1)))!=y||et&&bs(new et)!=L||it&&bs(it.resolve())!=W||Be&&bs(new Be)!=z||rt&&bs(new rt)!=re)&&(bs=function(J){var ie=la(J),pe=ie==U?J.constructor:void 0,ke=pe?Us(pe):"";if(ke)switch(ke){case je:return y;case ht:return L;case nt:return W;case qe:return z;case st:return re}return ie});function vl(J,ie){return ie=ie??a,!!ie&&(typeof J=="number"||ae.test(J))&&J>-1&&J%1==0&&J<ie}function ml(J){var ie=typeof J;return ie=="string"||ie=="number"||ie=="symbol"||ie=="boolean"?J!=="__proto__":J===null}function bl(J){return!!_e&&_e in J}function yl(J){var ie=J&&J.constructor,pe=typeof ie=="function"&&ie.prototype||xe;return J===pe}function Ap(J){return Ke.call(J)}function Us(J){if(J!=null){try{return Ue.call(J)}catch{}try{return J+""}catch{}}return""}function wl(J,ie){return J===ie||J!==J&&ie!==ie}var _l=ef(function(){return arguments}())?ef:function(J){return pa(J)&&Ce.call(J,"callee")&&!Ge.call(J,"callee")},Oc=Array.isArray;function xp(J){return J!=null&&El(J.length)&&!Pc(J)}var tf=Ot||Qt;function Sp(J,ie){return da(J,ie)}function Pc(J){if(!Al(J))return!1;var ie=la(J);return ie==S||ie==D||ie==d||ie==R}function El(J){return typeof J=="number"&&J>-1&&J%1==0&&J<=a}function Al(J){var ie=typeof J;return J!=null&&(ie=="object"||ie=="function")}function pa(J){return J!=null&&typeof J=="object"}var xl=he?Oe(he):hl;function Ip(J){return xp(J)?ul(J):ll(J)}function Zt(){return[]}function Qt(){return!1}t.exports=Sp})(Vd,Vd.exports);var aD=Vd.exports,cD=Object.defineProperty,Vb=Object.getOwnPropertySymbols,uD=Object.prototype.hasOwnProperty,fD=Object.prototype.propertyIsEnumerable,Gb=(t,e,r)=>e in t?cD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ui=(t,e)=>{for(var r in e||(e={}))uD.call(e,r)&&Gb(t,r,e[r]);if(Vb)for(var r of Vb(e))fD.call(e,r)&&Gb(t,r,e[r]);return t};function hD(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,l=t.charAt(0),d=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 L=0,K=0,H=0,U=D.length;H!==U&&D[H]===0;)H++,L++;for(var W=(U-H)*b+1>>>0,R=new Uint8Array(W);H!==U;){for(var k=D[H],z=0,_=W-1;(k!==0||z<K)&&_!==-1;_--,z++)k+=256*R[_]>>>0,R[_]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");K=z,H++}for(var B=W-K;B!==W&&R[B]===0;)B++;for(var X=l.repeat(L);B<W;++B)X+=t.charAt(R[B]);return X}function I(D){if(typeof D!="string")throw new TypeError("Expected String");if(D.length===0)return new Uint8Array;var L=0;if(D[L]!==" "){for(var K=0,H=0;D[L]===l;)K++,L++;for(var U=(D.length-L)*d+1>>>0,W=new Uint8Array(U);D[L];){var R=r[D.charCodeAt(L)];if(R===255)return;for(var k=0,z=U-1;(R!==0||k<H)&&z!==-1;z--,k++)R+=u*W[z]>>>0,W[z]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");H=k,L++}if(D[L]!==" "){for(var _=U-H;_!==U&&W[_]===0;)_++;for(var B=new Uint8Array(K+(U-_)),X=K;_!==U;)B[X++]=W[_++];return B}}}function S(D){var L=I(D);if(L)return L;throw new Error(`Non-${e} character`)}return{encode:w,decodeUnsafe:I,decode:S}}var lD=hD,dD=lD;const Yb=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")},pD=t=>new TextEncoder().encode(t),gD=t=>new TextDecoder().decode(t);class vD{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 mD{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 Jb(this,e)}}class bD{constructor(e){this.decoders=e}or(e){return Jb(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 Jb=(t,e)=>new bD(ui(ui({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class yD{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new vD(e,r,i),this.decoder=new mD(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ih=({name:t,prefix:e,encode:r,decode:i})=>new yD(t,e,r,i),Mu=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=dD(r,e);return Ih({prefix:t,name:e,encode:i,decode:s=>Yb(n(s))})},wD=(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,l=0,d=0;for(let b=0;b<s;++b){const w=n[t[b]];if(w===void 0)throw new SyntaxError(`Non-${i} character`);l=l<<r|w,u+=r,u>=8&&(u-=8,a[d++]=255&l>>u)}if(u>=r||255&l<<8-u)throw new SyntaxError("Unexpected end of data");return a},_D=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",a=0,u=0;for(let l=0;l<t.length;++l)for(u=u<<8|t[l],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},zr=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Ih({prefix:e,name:t,encode(n){return _D(n,i,r)},decode(n){return wD(n,i,r,t)}}),ED=Ih({prefix:"\0",name:"identity",encode:t=>gD(t),decode:t=>pD(t)});var AD=Object.freeze({__proto__:null,identity:ED});const xD=zr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var SD=Object.freeze({__proto__:null,base2:xD});const ID=zr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var MD=Object.freeze({__proto__:null,base8:ID});const CD=Mu({prefix:"9",name:"base10",alphabet:"0123456789"});var DD=Object.freeze({__proto__:null,base10:CD});const OD=zr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),PD=zr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var $D=Object.freeze({__proto__:null,base16:OD,base16upper:PD});const RD=zr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ND=zr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),TD=zr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),LD=zr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),BD=zr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),FD=zr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),UD=zr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),kD=zr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),jD=zr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var qD=Object.freeze({__proto__:null,base32:RD,base32upper:ND,base32pad:TD,base32padupper:LD,base32hex:BD,base32hexupper:FD,base32hexpad:UD,base32hexpadupper:kD,base32z:jD});const zD=Mu({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),HD=Mu({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var KD=Object.freeze({__proto__:null,base36:zD,base36upper:HD});const WD=Mu({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),VD=Mu({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var GD=Object.freeze({__proto__:null,base58btc:WD,base58flickr:VD});const YD=zr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),JD=zr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),QD=zr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ZD=zr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var XD=Object.freeze({__proto__:null,base64:YD,base64pad:JD,base64url:QD,base64urlpad:ZD});const Qb=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}"),eO=Qb.reduce((t,e,r)=>(t[r]=e,t),[]),tO=Qb.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function rO(t){return t.reduce((e,r)=>(e+=eO[r],e),"")}function iO(t){const e=[];for(const r of t){const i=tO[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const nO=Ih({prefix:"\u{1F680}",name:"base256emoji",encode:rO,decode:iO});var sO=Object.freeze({__proto__:null,base256emoji:nO}),oO=Xb,Zb=128,aO=127,cO=~aO,uO=Math.pow(2,31);function Xb(t,e,r){e=e||[],r=r||0;for(var i=r;t>=uO;)e[r++]=t&255|Zb,t/=128;for(;t&cO;)e[r++]=t&255|Zb,t>>>=7;return e[r]=t|0,Xb.bytes=r-i+1,e}var fO=Gd,hO=128,e3=127;function Gd(t,i){var r=0,i=i||0,n=0,s=i,a,u=t.length;do{if(s>=u)throw Gd.bytes=0,new RangeError("Could not decode varint");a=t[s++],r+=n<28?(a&e3)<<n:(a&e3)*Math.pow(2,n),n+=7}while(a>=hO);return Gd.bytes=s-i,r}var lO=Math.pow(2,7),dO=Math.pow(2,14),pO=Math.pow(2,21),gO=Math.pow(2,28),vO=Math.pow(2,35),mO=Math.pow(2,42),bO=Math.pow(2,49),yO=Math.pow(2,56),wO=Math.pow(2,63),_O=function(t){return t<lO?1:t<dO?2:t<pO?3:t<gO?4:t<vO?5:t<mO?6:t<bO?7:t<yO?8:t<wO?9:10},EO={encode:oO,decode:fO,encodingLength:_O},t3=EO;const r3=(t,e,r=0)=>(t3.encode(t,e,r),e),i3=t=>t3.encodingLength(t),Yd=(t,e)=>{const r=e.byteLength,i=i3(t),n=i+i3(r),s=new Uint8Array(n+r);return r3(t,s,0),r3(r,s,i),s.set(e,n),new AO(t,r,e,s)};class AO{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const n3=({name:t,code:e,encode:r})=>new xO(t,e,r);class xO{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?Yd(this.code,r):r.then(i=>Yd(this.code,i))}else throw Error("Unknown type, must be binary type")}}const s3=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),SO=n3({name:"sha2-256",code:18,encode:s3("SHA-256")}),IO=n3({name:"sha2-512",code:19,encode:s3("SHA-512")});var MO=Object.freeze({__proto__:null,sha256:SO,sha512:IO});const o3=0,CO="identity",a3=Yb;var DO=Object.freeze({__proto__:null,identity:{code:o3,name:CO,encode:a3,digest:t=>Yd(o3,a3(t))}});new TextEncoder,new TextDecoder;const c3=ui(ui(ui(ui(ui(ui(ui(ui(ui(ui({},AD),SD),MD),DD),$D),qD),KD),GD),XD),sO);ui(ui({},MO),DO);function OO(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function u3(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const f3=u3("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Jd=u3("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=OO(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),PO=ui({utf8:f3,"utf-8":f3,hex:c3.base16,latin1:Jd,ascii:Jd,binary:Jd},c3);function $O(t,e="utf8"){const r=PO[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 h3="wc",l3=2,Qd="core",us=`${h3}@2:${Qd}:`,RO={name:Qd,logger:"error"},NO={database:":memory:"},TO="crypto",d3="client_ed25519_seed",LO=Ie.ONE_DAY,BO="keychain",FO="0.3",UO="messages",kO="0.3",jO=Ie.SIX_HOURS,qO="publisher",p3="irn",zO="error",g3="wss://relay.walletconnect.org",HO="relayer",Ei={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"},KO="_subscription",en={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},WO=.1,v3="2.15.3-rc.0",VO=1e4,GO="0.3",YO="WALLETCONNECT_CLIENT_ID",fs={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},JO="subscription",QO="0.3",ZO=Ie.FIVE_SECONDS*1e3,XO="pairing",eP="0.3",Cu={wc_pairingDelete:{req:{ttl:Ie.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:Ie.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:Ie.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:Ie.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:Ie.ONE_DAY,prompt:!1,tag:0},res:{ttl:Ie.ONE_DAY,prompt:!1,tag:0}}},oc={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},xn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},tP="history",rP="0.3",iP="expirer",tn={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},nP="0.3",sP="verify-api",oP="https://verify.walletconnect.com",m3="https://verify.walletconnect.org",Du=m3,aP=`${Du}/v3`,cP=[oP,m3],uP="echo",fP="https://echo.walletconnect.com",hs={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"},Ts={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"},Sn={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"},Ko={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"},Wo={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"},Ou={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"},hP=.1,lP="event-client",dP=86400,pP="https://pulse.walletconnect.com/batch";class gP{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=BO,this.version=FO,this.initialized=!1,this.storagePrefix=us,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=ci(r,this.name)}get context(){return _i(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Fv(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Uv(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 vP{constructor(e,r,i){this.core=e,this.logger=r,this.name=TO,this.randomSessionIdentifier=Cd(),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=$v(n);return Pv(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const n=YS();return this.setPrivateKey(n.publicKey,n.privateKey)},this.signJWT=async n=>{this.isInitialized();const s=await this.getClientSeed(),a=$v(s),u=this.randomSessionIdentifier;return await DE(u,n,LO,a)},this.generateSharedKey=(n,s,a)=>{this.isInitialized();const u=this.getPrivateKey(n),l=JS(u,s);return this.setSymKey(l,a)},this.setSymKey=async(n,s)=>{this.isInitialized();const a=s||hh(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=ib(a),l=Is(s);if(nb(u)){const I=u.senderPublicKey,S=u.receiverPublicKey;n=await this.generateSharedKey(I,S)}const d=this.getSymKey(n),{type:b,senderPublicKey:w}=u;return ZS({type:b,symKey:d,message:l,senderPublicKey:w})},this.decode=async(n,s,a)=>{this.isInitialized();const u=tI(s,a);if(nb(u)){const l=u.receiverPublicKey,d=u.senderPublicKey;n=await this.generateSharedKey(l,d)}try{const l=this.getSymKey(n),d=XS({symKey:l,encoded:s});return qa(d)}catch(l){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(l)}},this.getPayloadType=n=>{const s=lh(n);return vu(s.type)},this.getPayloadSenderPublicKey=n=>{const s=lh(n);return s.senderPublicKey?bC(s.senderPublicKey,oi):void 0},this.core=e,this.logger=ci(r,this.name),this.keychain=i||new gP(this.core,this.logger)}get context(){return _i(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(d3)}catch{e=Cd(),await this.keychain.set(d3,e)}return $O(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 mP extends sC{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=UO,this.version=kO,this.initialized=!1,this.storagePrefix=us,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=$s(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=$s(n);return typeof s[a]<"u"},this.del=async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()},this.logger=ci(e,this.name),this.core=r}get context(){return _i(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Fv(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Uv(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 bP extends oC{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new Br.exports.EventEmitter,this.name=qO,this.queue=new Map,this.publishTimeout=Ie.toMiliseconds(Ie.ONE_MINUTE),this.failedPublishTimeout=Ie.toMiliseconds(Ie.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,l=Dd(s),d=s?.prompt||!1,b=s?.tag||0,w=s?.id||Ho().toString(),I={topic:i,message:n,opts:{ttl:u,relay:l,prompt:d,tag:b,id:w,attestation:s?.attestation}},S=`Failed to publish payload, please try again. id:${w} tag:${b}`,D=Date.now();let L,K=1;try{for(;L===void 0;){if(Date.now()-D>this.publishTimeout)throw new Error(S);this.logger.trace({id:w,attempts:K},`publisher.publish - attempt ${K}`),L=await await za(this.rpcPublish(i,n,u,l,d,b,w,s?.attestation).catch(H=>this.logger.warn(H)),this.publishTimeout,S),K++,L||await new Promise(H=>setTimeout(H,this.failedPublishTimeout))}this.relayer.events.emit(Ei.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(H){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(H),(a=s?.internal)!=null&&a.throwOnFailedPublish)throw H;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=ci(r,this.name),this.registerEventListeners()}get context(){return _i(this.logger)}rpcPublish(e,r,i,n,s,a,u,l){var d,b,w,I;const S={method:mu(n.protocol).publish,params:{topic:e,message:r,ttl:i,prompt:s,tag:a,attestation:l},id:u};return ai((d=S.params)==null?void 0:d.prompt)&&((b=S.params)==null||delete b.prompt),ai((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(rc.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Ei.connection_stalled);return}this.checkQueue()}),this.relayer.on(Ei.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class yP{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 wP=Object.defineProperty,_P=Object.defineProperties,EP=Object.getOwnPropertyDescriptors,b3=Object.getOwnPropertySymbols,AP=Object.prototype.hasOwnProperty,xP=Object.prototype.propertyIsEnumerable,y3=(t,e,r)=>e in t?wP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pu=(t,e)=>{for(var r in e||(e={}))AP.call(e,r)&&y3(t,r,e[r]);if(b3)for(var r of b3(e))xP.call(e,r)&&y3(t,r,e[r]);return t},Zd=(t,e)=>_P(t,EP(e));class SP extends uC{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new yP,this.events=new Br.exports.EventEmitter,this.name=JO,this.version=QO,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=us,this.subscribeTimeout=Ie.toMiliseconds(Ie.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())},this.subscribe=async(i,n)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const s=Dd(n),a={topic:i,relay:s};this.pending.set(i,a);const u=await this.rpcSubscribe(i,s);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 Ie.Watch;u.start(n);const l=setInterval(()=>{!this.pending.has(i)&&this.topics.includes(i)&&(clearInterval(l),u.stop(n),s(!0)),u.elapsed(n)>=ZO&&(clearInterval(l),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=ci(r,this.name),this.clientId=""}get context(){return _i(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=Dd(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){const i={method:mu(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{return await await za(this.relayer.request(i).catch(n=>this.logger.warn(n)),this.subscribeTimeout)?$s(e+this.clientId):null}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Ei.connection_stalled)}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:mu(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 za(this.relayer.request(i).catch(n=>this.logger.warn(n)),this.subscribeTimeout)}catch{this.relayer.events.emit(Ei.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:mu(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 za(this.relayer.request(i).catch(s=>this.logger.warn(s)),this.subscribeTimeout)}catch{this.relayer.events.emit(Ei.connection_stalled)}return n}rpcUnsubscribe(e,r,i){const n={method:mu(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,Zd(Pu({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Pu({},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,Pu({},r)),this.topicMap.set(r.topic,e),this.events.emit(fs.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(fs.deleted,Zd(Pu({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(fs.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(fs.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);ss(r)&&this.onBatchSubscribe(r.map((i,n)=>Zd(Pu({},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(rc.pulse,async()=>{await this.checkPending()}),this.events.on(fs.created,async e=>{const r=fs.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(fs.deleted,async e=>{const r=fs.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.restartInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}}var IP=Object.defineProperty,w3=Object.getOwnPropertySymbols,MP=Object.prototype.hasOwnProperty,CP=Object.prototype.propertyIsEnumerable,_3=(t,e,r)=>e in t?IP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,DP=(t,e)=>{for(var r in e||(e={}))MP.call(e,r)&&_3(t,r,e[r]);if(w3)for(var r of w3(e))CP.call(e,r)&&_3(t,r,e[r]);return t};class OP extends aC{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new Br.exports.EventEmitter,this.name=HO,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=Ie.toMiliseconds(Ie.THIRTY_SECONDS+Ie.ONE_SECOND),this.request=async r=>{var i,n;this.logger.debug("Publishing Request Payload");const s=r.id||Ho().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(l,d)=>{const b=()=>{d(new Error(`relayer.request - publish interrupted, id: ${s}`))};this.provider.on(en.disconnect,b);const w=await a;this.provider.off(en.disconnect,b),l(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(iu())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(Ei.connect)},this.onDisconnectHandler=()=>{this.logger.trace("relayer disconnected"),this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(Ei.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(en.payload,this.onPayloadHandler),this.provider.on(en.connect,this.onConnectHandler),this.provider.on(en.disconnect,this.onDisconnectHandler),this.provider.on(en.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?ci(e.logger,this.name):os(Eh({level:e.logger||zO})),this.messages=new mP(this.logger,e.core),this.subscriber=new SP(this,this.logger),this.publisher=new bP(this,this.logger),this.relayUrl=e?.relayUrl||g3,this.projectId=e.projectId,this.bundleId=BE(),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),await this.transportOpen(),this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&this.subscriber.pending.size===0&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},VO)}get context(){return _i(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()})}async subscribe(e,r){var i;this.isInitialized();let n=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"",s;const a=u=>{u.topic===e&&(this.subscriber.off(fs.created,a),s())};return await Promise.all([new Promise(u=>{s=u,this.subscriber.on(fs.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 za(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(en.disconnect,n),i(new Error("Connection interrupted while trying to subscribe"))};this.provider.on(en.disconnect,n),await za(this.provider.connect(),Ie.toMiliseconds(Ie.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 vb())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`)}startPingTimeout(){var e,r,i,n,s;if(iu())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 An(new oD(zE({sdkVersion:v3,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}),Wd(e)){if(!e.method.endsWith(KO))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:a}=r.data,u={topic:i,message:n,publishedAt:s,attestation:a};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(DP({type:"event",event:r.id},u)),this.events.emit(r.id,u),await this.acknowledgePayload(e),await this.onMessageEvent(u)}else Sh(e)&&this.events.emit(Ei.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Ei.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=Ah(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(en.payload,this.onPayloadHandler),this.provider.off(en.connect,this.onConnectHandler),this.provider.off(en.disconnect,this.onDisconnectHandler),this.provider.off(en.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await vb();YI(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(Ei.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&(this.reconnectTimeout||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},Ie.toMiliseconds(WO))))}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 PP=Object.defineProperty,E3=Object.getOwnPropertySymbols,$P=Object.prototype.hasOwnProperty,RP=Object.prototype.propertyIsEnumerable,A3=(t,e,r)=>e in t?PP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,x3=(t,e)=>{for(var r in e||(e={}))$P.call(e,r)&&A3(t,r,e[r]);if(E3)for(var r of E3(e))RP.call(e,r)&&A3(t,r,e[r]);return t};class Vo extends cC{constructor(e,r,i,n=us,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,this.map=new Map,this.version=GO,this.cached=[],this.initialized=!1,this.storagePrefix=us,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&&!ai(a)?this.map.set(this.getKey(a),a):II(a)?this.map.set(a.id,a):MI(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(l=>aD(u[l],a[l]))):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 l=x3(x3({},this.getData(a)),u);this.map.set(a,l),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=ci(r,this.name),this.storagePrefix=n,this.getKey=s}get context(){return _i(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 NP{constructor(e,r){this.core=e,this.logger=r,this.name=XO,this.version=eP,this.events=new Br.exports,this.initialized=!1,this.storagePrefix=us,this.ignoredPayloadTypes=[Ps],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=Cd(),s=await this.core.crypto.setSymKey(n),a=kr(Ie.FIVE_MINUTES),u={protocol:p3},l={topic:s,expiry:a,relay:u,active:!1},d=vI({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,l),await this.core.relayer.subscribe(s),{topic:s,uri:d}},this.pair=async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i?.uri,trace:[hs.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:a,relay:u,expiryTimestamp:l,methods:d}=cb(i.uri);n.props.properties.topic=s,n.addTrace(hs.pairing_uri_validation_success),n.addTrace(hs.pairing_uri_not_expired);let b;if(this.pairings.keys.includes(s)){if(b=this.pairings.get(s),n.addTrace(hs.existing_pairing),b.active)throw n.setError(Ts.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(hs.pairing_not_expired)}const w=l||kr(Ie.FIVE_MINUTES),I={topic:s,relay:u,expiry:w,active:!1,methods:d};this.core.expirer.set(s,w),await this.pairings.set(s,I),n.addTrace(hs.store_new_pairing),i.activatePairing&&await this.activate({topic:s}),this.events.emit(oc.create,I),n.addTrace(hs.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(a,s),n.addTrace(hs.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(Ts.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:u})}catch(S){throw n.setError(Ts.subscribe_pairing_topic_failure),S}return n.addTrace(hs.subscribe_pairing_topic_success),I},this.activate=async({topic:i})=>{this.isInitialized();const n=kr(Ie.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:l}=Fo();this.events.once(Dt("pairing_ping",s),({error:d})=>{d?l(d):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=sc(n,s),u=await this.core.crypto.encode(i,a),l=Cu[n].req;return this.core.history.set(i,a),this.core.relayer.publish(i,u,l),a.id},this.sendResult=async(i,n,s)=>{const a=Ah(i,s),u=await this.core.crypto.encode(n,a),l=await this.core.history.get(n,i),d=Cu[l.request.method].res;await this.core.relayer.publish(n,u,d),await this.core.history.resolve(a)},this.sendError=async(i,n,s)=>{const a=xh(i,s),u=await this.core.crypto.encode(n,a),l=await this.core.history.get(n,i),d=Cu[l.request.method]?Cu[l.request.method].res:Cu.unregistered_method.res;await this.core.relayer.publish(n,u,d),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=>eo(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(oc.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(()=>{cs(n)?this.events.emit(Dt("pairing_ping",s),{}):Xi(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(oc.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(!yi(i)){const{message:u}=Ee("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(Ts.malformed_pairing_uri),new Error(u)}if(!SI(i.uri)){const{message:u}=Ee("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(Ts.malformed_pairing_uri),new Error(u)}const a=cb(i?.uri);if(!((s=a?.relay)!=null&&s.protocol)){const{message:u}=Ee("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(Ts.malformed_pairing_uri),new Error(u)}if(!(a!=null&&a.symKey)){const{message:u}=Ee("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(Ts.malformed_pairing_uri),new Error(u)}if(a!=null&&a.expiryTimestamp&&Ie.toMiliseconds(a?.expiryTimestamp)<Date.now()){n.setError(Ts.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(!yi(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(!yi(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(!mr(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(eo(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=ci(r,this.name),this.pairings=new Vo(this.core,this.logger,this.name,this.storagePrefix)}get context(){return _i(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Ei.message,async e=>{const{topic:r,message:i}=e;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const n=await this.core.crypto.decode(r,i);try{Wd(n)?(this.core.history.set(r,n),this.onRelayEventRequest({topic:r,payload:n})):Sh(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:r,payload:n}),this.core.history.delete(r,n.id))}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(tn.expired,async e=>{const{topic:r}=jv(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(oc.expire,{topic:r}))})}}class TP extends nC{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new Br.exports.EventEmitter,this.name=tP,this.version=rP,this.cached=[],this.initialized=!1,this.storagePrefix=us,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:kr(Ie.THIRTY_DAYS)};this.records.set(a.id,a),this.persist(),this.events.emit(xn.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=Xi(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(xn.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(xn.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=ci(r,this.name)}get context(){return _i(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:sc(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(xn.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(xn.created,e=>{const r=xn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(xn.updated,e=>{const r=xn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(xn.deleted,e=>{const r=xn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(rc.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{Ie.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(xn.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 LP extends fC{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new Br.exports.EventEmitter,this.name=iP,this.version=nP,this.cached=[],this.initialized=!1,this.storagePrefix=us,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(tn.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(tn.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=ci(r,this.name)}get context(){return _i(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 HE(e);if(typeof e=="number")return KE(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(tn.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;Ie.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(tn.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(rc.pulse,()=>this.checkExpirations()),this.events.on(tn.created,e=>{const r=tn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(tn.expired,e=>{const r=tn.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(tn.deleted,e=>{const r=tn.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 sr={};Object.defineProperty(sr,"__esModule",{value:!0}),sr.getLocalStorage=sr.getLocalStorageOrThrow=sr.getCrypto=sr.getCryptoOrThrow=sr.getLocation=sr.getLocationOrThrow=sr.getNavigator=sr.getNavigatorOrThrow=S3=sr.getDocument=sr.getDocumentOrThrow=sr.getFromWindowOrThrow=sr.getFromWindow=void 0;function Go(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}sr.getFromWindow=Go;function ac(t){const e=Go(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}sr.getFromWindowOrThrow=ac;function BP(){return ac("document")}sr.getDocumentOrThrow=BP;function FP(){return Go("document")}var S3=sr.getDocument=FP;function UP(){return ac("navigator")}sr.getNavigatorOrThrow=UP;function kP(){return Go("navigator")}sr.getNavigator=kP;function jP(){return ac("location")}sr.getLocationOrThrow=jP;function qP(){return Go("location")}sr.getLocation=qP;function zP(){return ac("crypto")}sr.getCryptoOrThrow=zP;function HP(){return Go("crypto")}sr.getCrypto=HP;function KP(){return ac("localStorage")}sr.getLocalStorageOrThrow=KP;function WP(){return Go("localStorage")}sr.getLocalStorage=WP;class VP extends hC{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,this.name=sP,this.verifyUrlV3=aP,this.storagePrefix=us,this.version=l3,this.init=async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&Ie.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(!su()||this.isDevEnv)return;const s=window.location.origin,{id:a,decryptedId:u}=n,l=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${a}&decryptedId=${u}`;try{const d=S3(),b=this.startAbortTimer(Ie.ONE_SECOND*5),w=await new Promise((I,S)=>{const D=()=>{window.removeEventListener("message",K),d.body.removeChild(L),S("attestation aborted")};this.abortController.signal.addEventListener("abort",D);const L=d.createElement("iframe");L.src=l,L.style.display="none",L.addEventListener("error",D,{signal:this.abortController.signal});const K=H=>{if(!H.data)return;const U=JSON.parse(H.data);if(U.type==="verify_attestation"){if(Z0(U.attestation).payload.id!==a)return;clearInterval(b),d.body.removeChild(L),this.abortController.signal.removeEventListener("abort",D),window.removeEventListener("message",K),I(U.attestation===null?"":U.attestation)}};d.body.appendChild(L),window.addEventListener("message",K,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",w),w}catch(d){this.logger.warn(d)}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(Z0(s).payload.id!==u)return;const d=await this.isValidJwtAttestation(s);if(d){if(!d.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return d}}if(!a)return;const l=this.getVerifyUrl(n?.verifyUrl);return this.fetchAttestation(a,l)},this.fetchAttestation=async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const a=this.startAbortTimer(Ie.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||Du;return cP.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Du}`),s=Du),s},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(Ie.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=sI(n,s.publicKey),u={hasExpired:Ie.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=ci(r,this.name),this.abortController=new AbortController,this.isDevEnv=iu()&&process.env.IS_VITEST,this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return _i(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),Ie.toMiliseconds(e))}}class GP extends lC{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.context=uP,this.registerDeviceToken=async i=>{const{clientId:n,token:s,notificationType:a,enableEncrypted:u=!1}=i,l=`${fP}/${this.projectId}/clients`;await fetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:a,token:s,always_raw:u})})},this.logger=ci(r,this.context)}}var YP=Object.defineProperty,I3=Object.getOwnPropertySymbols,JP=Object.prototype.hasOwnProperty,QP=Object.prototype.propertyIsEnumerable,M3=(t,e,r)=>e in t?YP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$u=(t,e)=>{for(var r in e||(e={}))JP.call(e,r)&&M3(t,r,e[r]);if(I3)for(var r of I3(e))QP.call(e,r)&&M3(t,r,e[r]);return t};class ZP extends dC{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,this.context=lP,this.storagePrefix=us,this.storageVersion=hP,this.events=new Map,this.shouldPersist=!1,this.createEvent=n=>{const{event:s="ERROR",type:a="",properties:{topic:u,trace:l}}=n,d=GE(),b=this.core.projectId||"",w=Date.now(),I=$u({eventId:d,bundleId:b,timestamp:w,props:{event:s,type:a,properties:{topic:u,trace:l}}},this.setMethods(d));return this.telemetryEnabled&&(this.events.set(d,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(l=>l.props.properties.topic===a);if(u)return $u($u({},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(rc.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{Ie.fromMiliseconds(Date.now())-Ie.fromMiliseconds(n.timestamp)>dP&&(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,$u($u({},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(`${pP}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${v3}`,{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=ci(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 XP=Object.defineProperty,C3=Object.getOwnPropertySymbols,e$=Object.prototype.hasOwnProperty,t$=Object.prototype.propertyIsEnumerable,D3=(t,e,r)=>e in t?XP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,O3=(t,e)=>{for(var r in e||(e={}))e$.call(e,r)&&D3(t,r,e[r]);if(C3)for(var r of C3(e))t$.call(e,r)&&D3(t,r,e[r]);return t};class Xd extends iC{constructor(e){var r;super(e),this.protocol=h3,this.version=l3,this.name=Qd,this.events=new Br.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.projectId=e?.projectId,this.relayUrl=e?.relayUrl||g3,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Eh({level:typeof e?.logger=="string"&&e.logger?e.logger:RO.logger}),{logger:n,chunkLoggerController:s}=rC({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=ci(n,this.name),this.heartbeat=new Bd,this.crypto=new vP(this,this.logger,e?.keychain),this.history=new TP(this,this.logger),this.expirer=new LP(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new MM(O3(O3({},NO),e?.storageOptions)),this.relayer=new OP({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new NP(this,this.logger),this.verify=new VP(this,this.logger,this.storage),this.echoClient=new GP(this.projectId||"",this.logger),this.eventClient=new ZP(this,this.logger,e?.telemetryEnabled)}static async init(e){const r=new Xd(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(YO,i),r}get context(){return _i(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 initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const r$=Xd,P3="wc",$3=2,R3="client",e1=`${P3}@${$3}:${R3}:`,t1={name:R3,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},N3="WALLETCONNECT_DEEPLINK_CHOICE",i$="proposal",T3="Proposal expired",n$="session",cc=Ie.SEVEN_DAYS,s$="engine",Hr={wc_sessionPropose:{req:{ttl:Ie.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Ie.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Ie.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Ie.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Ie.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Ie.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Ie.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Ie.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Ie.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Ie.ONE_DAY,prompt:!1,tag:1114},res:{ttl:Ie.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:Ie.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:Ie.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1119}}},r1={min:Ie.FIVE_MINUTES,max:Ie.SEVEN_DAYS},ls={idle:"IDLE",active:"ACTIVE"},o$="request",a$=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],c$="wc",u$="auth",f$="authKeys",h$="pairingTopics",l$="requests",Mh=`${c$}@${1.5}:${u$}:`,Ch=`${Mh}:PUB_KEY`;var d$=Object.defineProperty,p$=Object.defineProperties,g$=Object.getOwnPropertyDescriptors,L3=Object.getOwnPropertySymbols,v$=Object.prototype.hasOwnProperty,m$=Object.prototype.propertyIsEnumerable,B3=(t,e,r)=>e in t?d$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xr=(t,e)=>{for(var r in e||(e={}))v$.call(e,r)&&B3(t,r,e[r]);if(L3)for(var r of L3(e))m$.call(e,r)&&B3(t,r,e[r]);return t},Yo=(t,e)=>p$(t,g$(e));class b$ extends gC{constructor(e){super(e),this.name=s$,this.events=new Br.exports,this.initialized=!1,this.requestQueue={state:ls.idle,queue:[]},this.sessionRequestQueue={state:ls.idle,queue:[]},this.requestQueueDelay=Ie.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(),this.client.core.pairing.register({methods:Object.keys(Hr)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},Ie.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{await this.isInitialized();const i=Yo(xr({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:n,requiredNamespaces:s,optionalNamespaces:a,sessionProperties:u,relays:l}=i;let d=n,b,w=!1;try{d&&(w=this.client.core.pairing.pairings.get(d).active)}catch(R){throw this.client.logger.error(`connect() -> pairing.get(${d}) failed`),R}if(!d||!w){const{topic:R,uri:k}=await this.client.core.pairing.create();d=R,b=k}if(!d){const{message:R}=Ee("NO_MATCHING_KEY",`connect() pairing topic: ${d}`);throw new Error(R)}const I=await this.client.core.crypto.generateKeyPair(),S=Hr.wc_sessionPropose.req.ttl||Ie.FIVE_MINUTES,D=kr(S),L=xr({requiredNamespaces:s,optionalNamespaces:a,relays:l??[{protocol:p3}],proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:D,pairingTopic:d},u&&{sessionProperties:u}),{reject:K,resolve:H,done:U}=Fo(S,T3);this.events.once(Dt("session_connect"),async({error:R,session:k})=>{if(R)K(R);else if(k){k.self.publicKey=I;const z=Yo(xr({},k),{pairingTopic:L.pairingTopic,requiredNamespaces:L.requiredNamespaces,optionalNamespaces:L.optionalNamespaces});await this.client.session.set(k.topic,z),await this.setExpiry(k.topic,k.expiry),d&&await this.client.core.pairing.updateMetadata({topic:d,metadata:k.peer.metadata}),this.cleanupDuplicatePairings(z),H(z)}});const W=await this.sendRequest({topic:d,method:"wc_sessionPropose",params:L,throwOnFailedPublish:!0});return await this.setProposal(W,xr({id:W},L)),{uri:b,approval:U}},this.pair=async r=>{await this.isInitialized();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:[Sn.session_approve_started]}});try{await this.isInitialized()}catch(_){throw a.setError(Ko.no_internet_connection),_}try{await this.isValidProposalId(r?.id)}catch(_){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),a.setError(Ko.proposal_not_found),_}try{await this.isValidApprove(r)}catch(_){throw this.client.logger.error("approve() -> isValidApprove() failed"),a.setError(Ko.session_approve_namespace_validation_failure),_}const{id:u,relayProtocol:l,namespaces:d,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:L,optionalNamespaces:K}=I;let H=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:S});H||(H=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Sn.session_approve_started,properties:{topic:S,trace:[Sn.session_approve_started,Sn.session_namespaces_validation_success]}}));const U=await this.client.core.crypto.generateKeyPair(),W=D.publicKey,R=await this.client.core.crypto.generateSharedKey(U,W),k=xr(xr({relay:{protocol:l??"irn"},namespaces:d,controller:{publicKey:U,metadata:this.client.metadata},expiry:kr(cc)},b&&{sessionProperties:b}),w&&{sessionConfig:w});H.addTrace(Sn.subscribing_session_topic);try{await this.client.core.relayer.subscribe(R)}catch(_){throw H.setError(Ko.subscribe_session_topic_failure),_}H.addTrace(Sn.subscribe_session_topic_success);const z=Yo(xr({},k),{topic:R,requiredNamespaces:L,optionalNamespaces:K,pairingTopic:S,acknowledged:!1,self:k.controller,peer:{publicKey:D.publicKey,metadata:D.metadata},controller:U});await this.client.session.set(R,z),H.addTrace(Sn.store_session);try{H.addTrace(Sn.publishing_session_settle),await this.sendRequest({topic:R,method:"wc_sessionSettle",params:k,throwOnFailedPublish:!0}).catch(_=>{throw H?.setError(Ko.session_settle_publish_failure),_}),H.addTrace(Sn.session_settle_publish_success),H.addTrace(Sn.publishing_session_approve),await this.sendResult({id:u,topic:S,result:{relay:{protocol:l??"irn"},responderPublicKey:U},throwOnFailedPublish:!0}).catch(_=>{throw H?.setError(Ko.session_approve_publish_failure),_}),H.addTrace(Sn.session_approve_publish_success)}catch(_){throw this.client.logger.error(_),this.client.session.delete(R,Gt("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(R),_}return this.client.core.eventClient.deleteEvent({eventId:H.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,kr(cc)),{topic:R,acknowledged:()=>Promise.resolve(this.client.session.get(R))}},this.reject=async r=>{await this.isInitialized();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:Hr.wc_sessionPropose.reject}),await this.client.proposal.delete(i,Gt("USER_DISCONNECTED")))},this.update=async r=>{await this.isInitialized();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}=Fo(),l=no(),d=Ho().toString(),b=this.client.session.get(i).namespaces;return this.events.once(Dt("session_update",l),({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:l,relayRpcId:d}).catch(w=>{this.client.logger.error(w),this.client.session.update(i,{namespaces:b}),u(w)}),{acknowledged:s}},this.extend=async r=>{await this.isInitialized();try{await this.isValidExtend(r)}catch(l){throw this.client.logger.error("extend() -> isValidExtend() failed"),l}const{topic:i}=r,n=no(),{done:s,resolve:a,reject:u}=Fo();return this.events.once(Dt("session_extend",n),({error:l})=>{l?u(l):a()}),await this.setExpiry(i,kr(cc)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(l=>{u(l)}),{acknowledged:s}},this.request=async r=>{await this.isInitialized();try{await this.isValidRequest(r)}catch(S){throw this.client.logger.error("request() -> isValidRequest() failed"),S}const{chainId:i,request:n,topic:s,expiry:a=Hr.wc_sessionRequest.req.ttl}=r,u=this.client.session.get(s),l=no(),d=Ho().toString(),{done:b,resolve:w,reject:I}=Fo(a,"Request expired. Please try again.");return this.events.once(Dt("session_request",l),({error:S,result:D})=>{S?I(S):w(D)}),await Promise.all([new Promise(async S=>{await this.sendRequest({clientRpcId:l,relayRpcId:d,topic:s,method:"wc_sessionRequest",params:{request:Yo(xr({},n),{expiryTimestamp:kr(a)}),chainId:i},expiry:a,throwOnFailedPublish:!0}).catch(D=>I(D)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:l}),S()}),new Promise(async S=>{var D;if(!((D=u.sessionConfig)!=null&&D.disableDeepLink)){const L=await VE(this.client.core.storage,N3);WE({id:l,topic:s,wcDeepLink:L})}S()}),b()]).then(S=>S[2])},this.respond=async r=>{await this.isInitialized(),await this.isValidRespond(r);const{topic:i,response:n}=r,{id:s}=n;cs(n)?await this.sendResult({id:s,topic:i,result:n.result,throwOnFailedPublish:!0}):Xi(n)&&await this.sendError({id:s,topic:i,error:n.error}),this.cleanupAfterResponse(r)},this.ping=async r=>{await this.isInitialized();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=no(),s=Ho().toString(),{done:a,resolve:u,reject:l}=Fo();this.events.once(Dt("session_ping",n),({error:d})=>{d?l(d):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=>{await this.isInitialized(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,a=Ho().toString();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:a})},this.disconnect=async r=>{await this.isInitialized(),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=>AI(i,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async r=>{this.isInitialized(),this.isValidAuthenticate(r);const{chains:i,statement:n="",uri:s,domain:a,nonce:u,type:l,exp:d,nbf:b,methods:w=[],expiry:I}=r,S=[...r.resources||[]],{topic:D,uri:L}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"]});this.client.logger.info({message:"Generated new pairing",pairing:{topic:D,uri:L}});const K=await this.client.core.crypto.generateKeyPair(),H=hh(K);if(await Promise.all([this.client.auth.authKeys.set(Ch,{responseTopic:H,publicKey:K}),this.client.auth.pairingTopics.set(H,{topic:H,pairingTopic:D})]),await this.client.core.relayer.subscribe(H),this.client.logger.info(`sending request to new pairing topic: ${D}`),w.length>0){const{namespace:f}=ru(i[0]);let h=zS(f,"request",w);fh(S)&&(h=KS(h,S.pop())),S.push(h)}const U=I&&I>Hr.wc_sessionAuthenticate.req.ttl?I:Hr.wc_sessionAuthenticate.req.ttl,W={authPayload:{type:l??"caip122",chains:i,statement:n,aud:s,domain:a,version:"1",nonce:u,iat:new Date().toISOString(),exp:d,nbf:b,resources:S},requester:{publicKey:K,metadata:this.client.metadata},expiryTimestamp:kr(U)},R={eip155:{chains:i,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},k={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:D,proposer:{publicKey:K,metadata:this.client.metadata},expiryTimestamp:kr(Hr.wc_sessionPropose.req.ttl)},{done:z,resolve:_,reject:B}=Fo(U,"Request expired"),X=async({error:f,session:h})=>{if(this.events.off(Dt("session_request",T),re),f)B(f);else if(h){h.self.publicKey=K,await this.client.session.set(h.topic,h),await this.setExpiry(h.topic,h.expiry),D&&await this.client.core.pairing.updateMetadata({topic:D,metadata:h.peer.metadata});const v=this.client.session.get(h.topic);await this.deleteProposal(y),_({session:v})}},re=async f=>{if(await this.deletePendingAuthRequest(T,{message:"fulfilled",code:0}),f.error){const g=Gt("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return f.error.code===g.code?void 0:(this.events.off(Dt("session_connect"),X),B(f.error.message))}await this.deleteProposal(y),this.events.off(Dt("session_connect"),X);const{cacaos:h,responder:v}=f.result,E=[],C=[];for(const g of h){await Ym({cacao:g,projectId:this.client.core.projectId})||(this.client.logger.error(g,"Signature verification failed"),B(Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:m}=g,N=fh(m.resources),ee=[Gm(m.iss)],ae=uh(m.iss);if(N){const O=Zm(N),te=Xm(N);E.push(...O),ee.push(...te)}for(const O of ee)C.push(`${O}:${ae}`)}const P=await this.client.core.crypto.generateSharedKey(K,v.publicKey);let M;E.length>0&&(M={topic:P,acknowledged:!0,self:{publicKey:K,metadata:this.client.metadata},peer:v,controller:v.publicKey,expiry:kr(cc),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:D,namespaces:ub([...new Set(E)],[...new Set(C)])},await this.client.core.relayer.subscribe(P),await this.client.session.set(P,M),D&&await this.client.core.pairing.updateMetadata({topic:D,metadata:v.metadata}),M=this.client.session.get(P)),_({auths:h,session:M})},T=no(),y=no();this.events.once(Dt("session_connect"),X),this.events.once(Dt("session_request",T),re);try{await Promise.all([this.sendRequest({topic:D,method:"wc_sessionAuthenticate",params:W,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:T}),this.sendRequest({topic:D,method:"wc_sessionPropose",params:k,expiry:Hr.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:y})])}catch(f){throw this.events.off(Dt("session_connect"),X),this.events.off(Dt("session_request",T),re),f}return await this.setProposal(y,xr({id:y},k)),await this.setAuthRequest(T,{request:Yo(xr({},W),{verifyContext:{}}),pairingTopic:D}),{uri:L,response:z}},this.approveSessionAuthenticate=async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Wo.authenticated_session_approve_started]}});try{this.isInitialized()}catch(L){throw s.setError(Ou.no_internet_connection),L}const a=this.getPendingAuthRequest(i);if(!a)throw s.setError(Ou.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const u=a.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),d=hh(u),b={type:Ps,receiverPublicKey:u,senderPublicKey:l},w=[],I=[];for(const L of n){if(!await Ym({cacao:L,projectId:this.client.core.projectId})){s.setError(Ou.invalid_cacao);const R=Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:d,error:R,encodeOpts:b}),new Error(R.message)}s.addTrace(Wo.cacaos_verified);const{p:K}=L,H=fh(K.resources),U=[Gm(K.iss)],W=uh(K.iss);if(H){const R=Zm(H),k=Xm(H);w.push(...R),U.push(...k)}for(const R of U)I.push(`${R}:${W}`)}const S=await this.client.core.crypto.generateSharedKey(l,u);s.addTrace(Wo.create_authenticated_session_topic);let D;if(w?.length>0){D={topic:S,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:u,metadata:a.requester.metadata},controller:u,expiry:kr(cc),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:a.pairingTopic,namespaces:ub([...new Set(w)],[...new Set(I)])},s.addTrace(Wo.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(S)}catch(L){throw s.setError(Ou.subscribe_authenticated_session_topic_failure),L}s.addTrace(Wo.subscribe_authenticated_session_topic_success),await this.client.session.set(S,D),s.addTrace(Wo.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:a.pairingTopic,metadata:a.requester.metadata})}s.addTrace(Wo.publishing_authenticated_session_approve);try{await this.sendResult({topic:d,id:i,result:{cacaos:n,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:b,throwOnFailedPublish:!0})}catch(L){throw s.setError(Ou.authenticated_session_approve_publish_failure),L}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:D}},this.rejectSessionAuthenticate=async r=>{await 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}`);const a=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=hh(a),d={type:Ps,receiverPublicKey:a,senderPublicKey:u};await this.sendError({id:i,topic:l,error:n,encodeOpts:d,rpcOpts:Hr.wc_sessionAuthenticate.reject}),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 Jm(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:l}=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(l.publicKey)&&await this.client.core.crypto.deleteKeyPair(l.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(N3).catch(d=>this.client.logger.warn(d)),this.getPendingSessionRequests().forEach(d=>{d.topic===n&&this.deletePendingSessionRequest(d.id,Gt("USER_DISCONNECTED"))}),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=ls.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(Ko.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=ls.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,kr(Hr.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)},this.setAuthRequest=async(r,i)=>{const{request:n,pairingTopic:s}=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})},this.setPendingSessionRequest=async r=>{const{id:i,topic:n,params:s,verifyContext:a}=r,u=s.request.expiryTimestamp||kr(Hr.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:l,throwOnFailedPublish:d}=r,b=sc(n,s,l);let w;try{w=await this.client.core.crypto.encode(i,b)}catch(D){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),D}let I;if(a$.includes(n)){const D=$s(JSON.stringify(b)),L=$s(w);I=await this.client.core.verify.register({id:L,decryptedId:D})}const S=Hr[n].req;return S.attestation=I,a&&(S.ttl=a),u&&(S.id=u),this.client.core.history.set(i,b),d?(S.internal=Yo(xr({},S.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,w,S)):this.client.core.relayer.publish(i,w,S).catch(D=>this.client.logger.error(D)),b.id},this.sendResult=async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:a,encodeOpts:u}=r,l=Ah(i,s);let d;try{d=await this.client.core.crypto.encode(n,l,u)}catch(I){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),I}let b;try{b=await this.client.core.history.get(n,i)}catch(I){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),I}const w=Hr[b.request.method].res;a?(w.internal=Yo(xr({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,d,w)):this.client.core.relayer.publish(n,d,w).catch(I=>this.client.logger.error(I)),await this.client.core.history.resolve(l)},this.sendError=async r=>{const{id:i,topic:n,error:s,encodeOpts:a,rpcOpts:u}=r,l=xh(i,s);let d;try{d=await this.client.core.crypto.encode(n,l,a)}catch(I){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),I}let b;try{b=await this.client.core.history.get(n,i)}catch(I){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),I}const w=u||Hr[b.request.method].res;this.client.core.relayer.publish(n,d,w),await this.client.core.history.resolve(l)},this.cleanup=async()=>{const r=[],i=[];this.client.session.getAll().forEach(n=>{let s=!1;eo(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=>{eo(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===ls.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=ls.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=ls.idle},this.processRequest=async r=>{const{topic:i,payload:n,attestation:s,encryptedId:a}=r,u=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:u}))switch(u){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:s,encryptedId:a});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:a});default:return this.client.logger.info(`Unsupported request method ${u}`)}},this.onRelayEventResponse=async r=>{const{topic:i,payload:n}=r,s=(await this.client.core.history.get(i,n.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n);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 ${s}`)}},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:l}=n;try{const d=this.client.core.eventClient.getEvent({topic:i});this.isValidConnect(xr({},n.params));const b=u.expiryTimestamp||kr(Hr.wc_sessionPropose.req.ttl),w=xr({id:l,pairingTopic:i,expiryTimestamp:b},u);await this.setProposal(l,w);const I=await this.getVerifyContext({attestationId:s,hash:$s(JSON.stringify(n)),encryptedId:a,metadata:w.proposer.metadata});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),d?.setError(Ts.proposal_listener_not_found)),d?.addTrace(hs.emit_session_proposal),this.client.events.emit("session_proposal",{id:l,params:w,verifyContext:I})}catch(d){await this.sendError({id:l,topic:i,error:d,rpcOpts:Hr.wc_sessionPropose.autoReject}),this.client.logger.error(d)}},this.onSessionProposeResponse=async(r,i)=>{const{id:n}=i;if(cs(i)){const{result:s}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const u=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:u});const l=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const d=await this.client.core.crypto.generateSharedKey(u,l);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:d});const b=await this.client.core.relayer.subscribe(d);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:b}),await this.client.core.pairing.activate({topic:r})}else if(Xi(i)){await this.client.proposal.delete(n,Gt("USER_DISCONNECTED"));const s=Dt("session_connect");if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} 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:l,namespaces:d,sessionProperties:b,sessionConfig:w}=i.params,I=xr(xr({topic:r,relay:a,expiry:l,namespaces:d,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}),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;cs(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(Dt("session_approve",n),{})):Xi(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=wu.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(xr({topic:r},n));try{wu.set(a,s),await this.client.session.update(r,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(l){throw wu.delete(a),l}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`);cs(i)?this.events.emit(Dt("session_update",n),{}):Xi(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,kr(cc)),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`);cs(i)?this.events.emit(Dt("session_extend",n),{}):Xi(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(()=>{cs(i)?this.events.emit(Dt("session_ping",n),{}):Xi(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}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(Ei.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)}},this.onSessionRequest=async r=>{var i;const{topic:n,payload:s,attestation:a,encryptedId:u}=r,{id:l,params:d}=s;try{await this.isValidRequest(xr({topic:n},d));const b=this.client.session.get(n),w=await this.getVerifyContext({attestationId:a,hash:$s(JSON.stringify(sc("wc_sessionRequest",d,l))),encryptedId:u,metadata:b.peer.metadata}),I={id:l,topic:n,params:d,verifyContext:w};await this.setPendingSessionRequest(I),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(I):(this.addSessionRequestToSessionRequestQueue(I),this.processSessionRequestQueue())}catch(b){await this.sendError({id:l,topic:n,error:b}),this.client.logger.error(b)}},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`);cs(i)?this.events.emit(Dt("session_request",n),{result:i.result}):Xi(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=wu.get(a);if(u&&this.isRequestOutOfSync(u,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(xr({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),wu.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}),cs(i)?this.events.emit(Dt("session_request",n),{result:i.result}):Xi(i)&&this.events.emit(Dt("session_request",n),{error:i.error})},this.onSessionAuthenticateRequest=async r=>{const{topic:i,payload:n,attestation:s,encryptedId:a}=r;try{const{requester:u,authPayload:l,expiryTimestamp:d}=n.params,b=await this.getVerifyContext({attestationId:s,hash:$s(JSON.stringify(n)),encryptedId:a,metadata:u.metadata}),w={requester:u,pairingTopic:i,id:n.id,authPayload:l,verifyContext:b,expiryTimestamp:d};await this.setAuthRequest(n.id,{request:w,pairingTopic:i}),this.client.events.emit("session_authenticate",{topic:i,params:n.params,id:n.id,verifyContext:b})}catch(u){this.client.logger.error(u);const l=n.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),b={type:Ps,receiverPublicKey:l,senderPublicKey:d};await this.sendError({id:n.id,topic:i,error:u,encodeOpts:b,rpcOpts:Hr.wc_sessionAuthenticate.autoReject})}},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=ls.idle,this.processSessionRequestQueue()},Ie.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===ls.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=ls.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:sc("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})},this.isValidConnect=async r=>{if(!yi(r)){const{message:l}=Ee("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(l)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:a,relays:u}=r;if(ai(i)||await this.isValidPairingTopic(i),!TI(u,!0)){const{message:l}=Ee("MISSING_OR_INVALID",`connect() relays: ${u}`);throw new Error(l)}!ai(n)&&yu(n)!==0&&this.validateNamespaces(n,"requiredNamespaces"),!ai(s)&&yu(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),ai(a)||this.validateSessionProps(a,"sessionProperties")},this.validateNamespaces=(r,i)=>{const n=NI(r,"connect()",i);if(n)throw new Error(n.message)},this.isValidApprove=async r=>{if(!yi(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),l=$d(n,"approve()");if(l)throw new Error(l.message);const d=pb(u.requiredNamespaces,n,"approve()");if(d)throw new Error(d.message);if(!mr(s,!0)){const{message:b}=Ee("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(b)}ai(a)||this.validateSessionProps(a,"sessionProperties")},this.isValidReject=async r=>{if(!yi(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),!BI(n)){const{message:s}=Ee("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!yi(r)){const{message:d}=Ee("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(d)}const{relay:i,controller:n,namespaces:s,expiry:a}=r;if(!lb(i)){const{message:d}=Ee("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(d)}const u=CI(n,"onSessionSettleRequest()");if(u)throw new Error(u.message);const l=$d(s,"onSessionSettleRequest()");if(l)throw new Error(l.message);if(eo(a)){const{message:d}=Ee("EXPIRED","onSessionSettleRequest()");throw new Error(d)}},this.isValidUpdate=async r=>{if(!yi(r)){const{message:l}=Ee("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(l)}const{topic:i,namespaces:n}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),a=$d(n,"update()");if(a)throw new Error(a.message);const u=pb(s.requiredNamespaces,n,"update()");if(u)throw new Error(u.message)},this.isValidExtend=async r=>{if(!yi(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(!yi(r)){const{message:l}=Ee("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(l)}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(!db(u,s)){const{message:l}=Ee("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(l)}if(!FI(n)){const{message:l}=Ee("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(l)}if(!jI(u,s,n.method)){const{message:l}=Ee("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(l)}if(a&&!KI(a,r1)){const{message:l}=Ee("MISSING_OR_INVALID",`request() expiry: ${a}. Expiry must be a number (in seconds) between ${r1.min} and ${r1.max}`);throw new Error(l)}},this.isValidRespond=async r=>{var i;if(!yi(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(!UI(s)){const{message:a}=Ee("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}},this.isValidPing=async r=>{if(!yi(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(!yi(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(!db(a,s)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(u)}if(!kI(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(!yi(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(!mr(n,!1))throw new Error("uri is required parameter");if(!mr(s,!1))throw new Error("domain is required parameter");if(!mr(a,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(l=>ru(l).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:u}=ru(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}=r,u={verified:{verifyUrl:a.verifyUrl||Du,validation:"UNKNOWN",origin:a.url||""}};try{const l=await this.client.core.verify.resolve({attestationId:i,hash:n,encryptedId:s,verifyUrl:a.verifyUrl});l&&(u.verified.origin=l.origin,u.verified.isScam=l.isScam,u.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(u)}`),u},this.validateSessionProps=(r,i)=>{Object.values(r).forEach(n=>{if(!mr(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)}}}async isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ei.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}=e,{publicKey:s}=this.client.auth.authKeys.keys.includes(Ch)?this.client.auth.authKeys.get(Ch):{responseTopic:void 0,publicKey:void 0},a=await this.client.core.crypto.decode(r,i,{receiverPublicKey:s});try{Wd(a)?(this.client.core.history.set(r,a),this.onRelayEventRequest({topic:r,payload:a,attestation:n,encryptedId:$s(i)})):Sh(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a}),this.client.core.history.delete(r,a.id)):this.onRelayEventUnknownPayload({topic:r,payload:a})}catch(u){this.client.logger.error(u)}}registerExpirerEvents(){this.client.core.expirer.on(tn.expired,async e=>{const{topic:r,id:i}=jv(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(oc.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(oc.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!mr(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(eo(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=Ee("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!mr(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(eo(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(mr(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(!LI(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(eo(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=Ee("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class y$ extends Vo{constructor(e,r){super(e,r,i$,e1),this.core=e,this.logger=r}}class w$ extends Vo{constructor(e,r){super(e,r,n$,e1),this.core=e,this.logger=r}}class _$ extends Vo{constructor(e,r){super(e,r,o$,e1,i=>i.id),this.core=e,this.logger=r}}class E$ extends Vo{constructor(e,r){super(e,r,f$,Mh,()=>Ch),this.core=e,this.logger=r}}class A$ extends Vo{constructor(e,r){super(e,r,h$,Mh),this.core=e,this.logger=r}}class x$ extends Vo{constructor(e,r){super(e,r,l$,Mh,i=>i.id),this.core=e,this.logger=r}}class S${constructor(e,r){this.core=e,this.logger=r,this.authKeys=new E$(this.core,this.logger),this.pairingTopics=new A$(this.core,this.logger),this.requests=new x$(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}class i1 extends pC{constructor(e){super(e),this.protocol=P3,this.version=$3,this.name=t1.name,this.events=new Br.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=>{try{return await this.engine.authenticate(i)}catch(n){throw this.logger.error(n.message),n}},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||t1.name,this.metadata=e?.metadata||UE(),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:os(Eh({level:e?.logger||t1.logger}));this.core=e?.core||new r$(e),this.logger=ci(r,this.name),this.session=new w$(this.core,this.logger),this.proposal=new y$(this.core,this.logger),this.pendingRequest=new _$(this.core,this.logger),this.engine=new b$(this),this.auth=new S$(this.core,this.logger)}static async init(e){const r=new i1(e);return await r.initialize(),r}get context(){return _i(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),await this.auth.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 n1={exports:{}};(function(t,e){var r=typeof self<"u"?self:Wr,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 l(h){return h&&DataView.prototype.isPrototypeOf(h)}if(u.arrayBuffer)var d=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],b=ArrayBuffer.isView||function(h){return h&&d.indexOf(Object.prototype.toString.call(h))>-1};function w(h){if(typeof h!="string"&&(h=String(h)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(h))throw new TypeError("Invalid character in header field name");return h.toLowerCase()}function I(h){return typeof h!="string"&&(h=String(h)),h}function S(h){var v={next:function(){var E=h.shift();return{done:E===void 0,value:E}}};return u.iterable&&(v[Symbol.iterator]=function(){return v}),v}function D(h){this.map={},h instanceof D?h.forEach(function(v,E){this.append(E,v)},this):Array.isArray(h)?h.forEach(function(v){this.append(v[0],v[1])},this):h&&Object.getOwnPropertyNames(h).forEach(function(v){this.append(v,h[v])},this)}D.prototype.append=function(h,v){h=w(h),v=I(v);var E=this.map[h];this.map[h]=E?E+", "+v:v},D.prototype.delete=function(h){delete this.map[w(h)]},D.prototype.get=function(h){return h=w(h),this.has(h)?this.map[h]:null},D.prototype.has=function(h){return this.map.hasOwnProperty(w(h))},D.prototype.set=function(h,v){this.map[w(h)]=I(v)},D.prototype.forEach=function(h,v){for(var E in this.map)this.map.hasOwnProperty(E)&&h.call(v,this.map[E],E,this)},D.prototype.keys=function(){var h=[];return this.forEach(function(v,E){h.push(E)}),S(h)},D.prototype.values=function(){var h=[];return this.forEach(function(v){h.push(v)}),S(h)},D.prototype.entries=function(){var h=[];return this.forEach(function(v,E){h.push([E,v])}),S(h)},u.iterable&&(D.prototype[Symbol.iterator]=D.prototype.entries);function L(h){if(h.bodyUsed)return Promise.reject(new TypeError("Already read"));h.bodyUsed=!0}function K(h){return new Promise(function(v,E){h.onload=function(){v(h.result)},h.onerror=function(){E(h.error)}})}function H(h){var v=new FileReader,E=K(v);return v.readAsArrayBuffer(h),E}function U(h){var v=new FileReader,E=K(v);return v.readAsText(h),E}function W(h){for(var v=new Uint8Array(h),E=new Array(v.length),C=0;C<v.length;C++)E[C]=String.fromCharCode(v[C]);return E.join("")}function R(h){if(h.slice)return h.slice(0);var v=new Uint8Array(h.byteLength);return v.set(new Uint8Array(h)),v.buffer}function k(){return this.bodyUsed=!1,this._initBody=function(h){this._bodyInit=h,h?typeof h=="string"?this._bodyText=h:u.blob&&Blob.prototype.isPrototypeOf(h)?this._bodyBlob=h:u.formData&&FormData.prototype.isPrototypeOf(h)?this._bodyFormData=h:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(h)?this._bodyText=h.toString():u.arrayBuffer&&u.blob&&l(h)?(this._bodyArrayBuffer=R(h.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(h)||b(h))?this._bodyArrayBuffer=R(h):this._bodyText=h=Object.prototype.toString.call(h):this._bodyText="",this.headers.get("content-type")||(typeof h=="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(h)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var h=L(this);if(h)return h;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?L(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(H)}),this.text=function(){var h=L(this);if(h)return h;if(this._bodyBlob)return U(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(X)}),this.json=function(){return this.text().then(JSON.parse)},this}var z=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function _(h){var v=h.toUpperCase();return z.indexOf(v)>-1?v:h}function B(h,v){v=v||{};var E=v.body;if(h instanceof B){if(h.bodyUsed)throw new TypeError("Already read");this.url=h.url,this.credentials=h.credentials,v.headers||(this.headers=new D(h.headers)),this.method=h.method,this.mode=h.mode,this.signal=h.signal,!E&&h._bodyInit!=null&&(E=h._bodyInit,h.bodyUsed=!0)}else this.url=String(h);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 X(h){var v=new FormData;return h.trim().split("&").forEach(function(E){if(E){var C=E.split("="),P=C.shift().replace(/\+/g," "),M=C.join("=").replace(/\+/g," ");v.append(decodeURIComponent(P),decodeURIComponent(M))}}),v}function re(h){var v=new D,E=h.replace(/\r?\n[\t ]+/g," ");return E.split(/\r?\n/).forEach(function(C){var P=C.split(":"),M=P.shift().trim();if(M){var g=P.join(":").trim();v.append(M,g)}}),v}k.call(B.prototype);function T(h,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(h)}k.call(T.prototype),T.prototype.clone=function(){return new T(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new D(this.headers),url:this.url})},T.error=function(){var h=new T(null,{status:0,statusText:""});return h.type="error",h};var y=[301,302,303,307,308];T.redirect=function(h,v){if(y.indexOf(v)===-1)throw new RangeError("Invalid status code");return new T(null,{status:v,headers:{location:h}})},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(h,v){return new Promise(function(E,C){var P=new B(h,v);if(P.signal&&P.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:re(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 T(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(P.method,P.url,!0),P.credentials==="include"?M.withCredentials=!0:P.credentials==="omit"&&(M.withCredentials=!1),"responseType"in M&&u.blob&&(M.responseType="blob"),P.headers.forEach(function(m,N){M.setRequestHeader(N,m)}),P.signal&&(P.signal.addEventListener("abort",g),M.onreadystatechange=function(){M.readyState===4&&P.signal.removeEventListener("abort",g)}),M.send(typeof P._bodyInit>"u"?null:P._bodyInit)})}return f.polyfill=!0,s.fetch||(s.fetch=f,s.Headers=D,s.Request=B,s.Response=T),a.Headers=D,a.Request=B,a.Response=T,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})(n1,n1.exports);var F3=Rw(n1.exports),I$=Object.defineProperty,M$=Object.defineProperties,C$=Object.getOwnPropertyDescriptors,U3=Object.getOwnPropertySymbols,D$=Object.prototype.hasOwnProperty,O$=Object.prototype.propertyIsEnumerable,k3=(t,e,r)=>e in t?I$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,j3=(t,e)=>{for(var r in e||(e={}))D$.call(e,r)&&k3(t,r,e[r]);if(U3)for(var r of U3(e))O$.call(e,r)&&k3(t,r,e[r]);return t},q3=(t,e)=>M$(t,C$(e));const P$={Accept:"application/json","Content-Type":"application/json"},$$="POST",z3={headers:P$,method:$$},H3=10;class ds{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new Br.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!qb(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=Is(e),i=await(await F3(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(!qb(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=Is({id:1,jsonrpc:"2.0",method:"test",params:[]});await F3(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"?qa(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=xh(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return Lb(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>H3&&this.events.setMaxListeners(H3)}}const K3="error",R$="wss://relay.walletconnect.com",N$="wc",T$="universal_provider",W3=`${N$}@2:${T$}:`,L$="https://rpc.walletconnect.com/v1/",uc="generic",In={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Ru=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},s1={exports:{}};/**
43
+ ***************************************************************************** */var zd=function(t,e){return zd=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])},zd(t,e)};function IC(t,e){zd(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Hd=function(){return Hd=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},Hd.apply(this,arguments)};function MC(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 CC(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 DC(t,e){return function(r,i){e(r,i,t)}}function OC(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function PC(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{d(i.next(b))}catch(w){a(w)}}function l(b){try{d(i.throw(b))}catch(w){a(w)}}function d(b){b.done?s(b.value):n(b.value).then(u,l)}d((i=i.apply(t,e||[])).next())})}function $C(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(d){return function(b){return l([d,b])}}function l(d){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,n&&(s=d[0]&2?n.return:d[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,d[1])).done)return s;switch(n=0,s&&(d=[d[0]&2,s.value]),d[0]){case 0:case 1:s=d;break;case 4:return r.label++,{value:d[1],done:!1};case 5:r.label++,n=d[1],d=[0];continue;case 7:d=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(d[0]===6||d[0]===2)){r=0;continue}if(d[0]===3&&(!s||d[1]>s[0]&&d[1]<s[3])){r.label=d[1];break}if(d[0]===6&&r.label<s[1]){r.label=s[1],s=d;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(d);break}s[2]&&r.ops.pop(),r.trys.pop();continue}d=e.call(t,r)}catch(b){d=[6,b],n=0}finally{i=s=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}function RC(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function NC(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Kd(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 Fb(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 TC(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Fb(arguments[e]));return t}function LC(){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 Iu(t){return this instanceof Iu?(this.v=t,this):new Iu(t)}function BC(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,L){s.push([I,S,D,L])>1||u(I,S)})})}function u(I,S){try{l(i[I](S))}catch(D){w(s[0][3],D)}}function l(I){I.value instanceof Iu?Promise.resolve(I.value.v).then(d,b):w(s[0][2],I)}function d(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 FC(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:Iu(t[n](a)),done:n==="return"}:s?s(a):a}:s}}function UC(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 Kd=="function"?Kd(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,l){a=t[s](a),n(u,l,a.done,a.value)})}}function n(s,a,u,l){Promise.resolve(l).then(function(d){s({value:d,done:u})},a)}}function kC(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 HC(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 KC=Object.freeze({__proto__:null,__extends:IC,get __assign(){return Hd},__rest:MC,__decorate:CC,__param:DC,__metadata:OC,__awaiter:PC,__generator:$C,__createBinding:RC,__exportStar:NC,__values:Kd,__read:Fb,__spread:TC,__spreadArrays:LC,__await:Iu,__asyncGenerator:BC,__asyncDelegator:FC,__asyncValues:UC,__makeTemplateObject:kC,__importStar:jC,__importDefault:qC,__classPrivateFieldGet:zC,__classPrivateFieldSet:HC}),WC=f0(KC),Rs={},Ub;function VC(){if(Ub)return Rs;Ub=1,Object.defineProperty(Rs,"__esModule",{value:!0}),Rs.isBrowserCryptoAvailable=Rs.getSubtleCrypto=Rs.getBrowerCrypto=void 0;function t(){return Wr?.crypto||Wr?.msCrypto||{}}Rs.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}Rs.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Rs.isBrowserCryptoAvailable=r,Rs}var Ns={},kb;function GC(){if(kb)return Ns;kb=1,Object.defineProperty(Ns,"__esModule",{value:!0}),Ns.isBrowser=Ns.isNode=Ns.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ns.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Ns.isNode=e;function r(){return!t()&&!e()}return Ns.isBrowser=r,Ns}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=WC;e.__exportStar(VC(),t),e.__exportStar(GC(),t)})(Bb);function no(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Ho(t=6){return BigInt(no(t))}function sc(t,e,r){return{id:r||no(),jsonrpc:"2.0",method:t,params:e}}function Ah(t,e){return{id:t,jsonrpc:"2.0",result:e}}function xh(t,e,r){return{id:t,jsonrpc:"2.0",error:YC(e,r)}}function YC(t,e){return typeof t>"u"?Tb(Rb):(typeof t=="string"&&(t=Object.assign(Object.assign({},Tb(qd)),{message:t})),typeof e<"u"&&(t.data=e),xC(t.code)&&(t=SC(t.code)),t)}class JC{}class QC extends JC{constructor(){super()}}class ZC extends QC{constructor(e){super()}}const XC="^https?:",eD="^wss?:";function tD(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function jb(t,e){const r=tD(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function qb(t){return jb(t,XC)}function zb(t){return jb(t,eD)}function rD(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Hb(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Wd(t){return Hb(t)&&"method"in t}function Sh(t){return Hb(t)&&(cs(t)||Xi(t))}function cs(t){return"result"in t}function Xi(t){return"error"in t}class An extends ZC{constructor(e){super(e),this.events=new Br.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(sc(e.method,e.params||[],e.id||Ho().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=>{Xi(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),Sh(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 iD=()=>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"),nD=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Kb=t=>t.split("?")[0],Wb=10,sD=iD();class oD{constructor(e){if(this.url=e,this.events=new Br.exports.EventEmitter,this.registering=!1,!zb(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(Is(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!zb(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=Bb.isReactNative()?{headers:{origin:n}}:{rejectUnauthorized:!rD(e)},a=new sD(e,[],s);nD()?a.onerror=u=>{const l=u;i(this.emitError(l.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"?qa(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=xh(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return Lb(e,Kb(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Wb&&this.events.setMaxListeners(Wb)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Kb(this.url)}`));return this.events.emit("register_error",r),r}}var Vd={exports:{}};(function(t,e){var r=200,i="__lodash_hash_undefined__",n=1,s=2,a=9007199254740991,u="[object Arguments]",l="[object Array]",d="[object AsyncFunction]",b="[object Boolean]",w="[object Date]",I="[object Error]",S="[object Function]",D="[object GeneratorFunction]",L="[object Map]",K="[object Number]",H="[object Null]",U="[object Object]",W="[object Promise]",R="[object Proxy]",k="[object RegExp]",z="[object Set]",_="[object String]",B="[object Symbol]",X="[object Undefined]",re="[object WeakMap]",T="[object ArrayBuffer]",y="[object DataView]",f="[object Float32Array]",h="[object Float64Array]",v="[object Int8Array]",E="[object Int16Array]",C="[object Int32Array]",P="[object Uint8Array]",M="[object Uint8ClampedArray]",g="[object Uint16Array]",m="[object Uint32Array]",N=/[\\^$.*+?()[\]{}|]/g,ee=/^\[object .+?Constructor\]$/,ae=/^(?:0|[1-9]\d*)$/,O={};O[f]=O[h]=O[v]=O[E]=O[C]=O[P]=O[M]=O[g]=O[m]=!0,O[u]=O[l]=O[T]=O[b]=O[y]=O[w]=O[I]=O[S]=O[L]=O[K]=O[U]=O[k]=O[z]=O[_]=O[re]=!1;var te=typeof Wr=="object"&&Wr&&Wr.Object===Object&&Wr,q=typeof self=="object"&&self&&self.Object===Object&&self,G=te||q||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,ie){for(var pe=-1,ke=J==null?0:J.length,Xt=0,bt=[];++pe<ke;){var or=J[pe];ie(or,pe,J)&&(bt[Xt++]=or)}return bt}function we(J,ie){for(var pe=-1,ke=ie.length,Xt=J.length;++pe<ke;)J[Xt+pe]=ie[pe];return J}function Re(J,ie){for(var pe=-1,ke=J==null?0:J.length;++pe<ke;)if(ie(J[pe],pe,J))return!0;return!1}function Xe(J,ie){for(var pe=-1,ke=Array(J);++pe<J;)ke[pe]=ie(pe);return ke}function Oe(J){return function(ie){return J(ie)}}function Ne(J,ie){return J.has(ie)}function Me(J,ie){return J?.[ie]}function be(J){var ie=-1,pe=Array(J.size);return J.forEach(function(ke,Xt){pe[++ie]=[Xt,ke]}),pe}function Pe(J,ie){return function(pe){return J(ie(pe))}}function Te(J){var ie=-1,pe=Array(J.size);return J.forEach(function(ke){pe[++ie]=ke}),pe}var ve=Array.prototype,$e=Function.prototype,xe=Object.prototype,me=G["__core-js_shared__"],Ue=$e.toString,Ce=xe.hasOwnProperty,_e=function(){var J=/[^.]+$/.exec(me&&me.keys&&me.keys.IE_PROTO||"");return J?"Symbol(src)_1."+J:""}(),Ke=xe.toString,Ve=RegExp("^"+Ue.call(Ce).replace(N,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ae=V?G.Buffer:void 0,We=G.Symbol,pt=G.Uint8Array,Ge=xe.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=ki(G,"DataView"),et=ki(G,"Map"),it=ki(G,"Promise"),Be=ki(G,"Set"),rt=ki(G,"WeakMap"),tt=ki(Object,"create"),je=Us(Le),ht=Us(et),nt=Us(it),qe=Us(Be),st=Us(rt),at=We?We.prototype:void 0,Fe=at?at.valueOf:void 0;function Ze(J){var ie=-1,pe=J==null?0:J.length;for(this.clear();++ie<pe;){var ke=J[ie];this.set(ke[0],ke[1])}}function lt(){this.__data__=tt?tt(null):{},this.size=0}function ze(J){var ie=this.has(J)&&delete this.__data__[J];return this.size-=ie?1:0,ie}function jt(J){var ie=this.__data__;if(tt){var pe=ie[J];return pe===i?void 0:pe}return Ce.call(ie,J)?ie[J]:void 0}function qt(J){var ie=this.__data__;return tt?ie[J]!==void 0:Ce.call(ie,J)}function ct(J,ie){var pe=this.__data__;return this.size+=this.has(J)?0:1,pe[J]=tt&&ie===void 0?i:ie,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 ie=-1,pe=J==null?0:J.length;for(this.clear();++ie<pe;){var ke=J[ie];this.set(ke[0],ke[1])}}function Qr(){this.__data__=[],this.size=0}function Zr(J){var ie=this.__data__,pe=ha(ie,J);if(pe<0)return!1;var ke=ie.length-1;return pe==ke?ie.pop():It.call(ie,pe,1),--this.size,!0}function Xr(J){var ie=this.__data__,pe=ha(ie,J);return pe<0?void 0:ie[pe][1]}function ei(J){return ha(this.__data__,J)>-1}function ti(J,ie){var pe=this.__data__,ke=ha(pe,J);return ke<0?(++this.size,pe.push([J,ie])):pe[ke][1]=ie,this}_t.prototype.clear=Qr,_t.prototype.delete=Zr,_t.prototype.get=Xr,_t.prototype.has=ei,_t.prototype.set=ti;function pr(J){var ie=-1,pe=J==null?0:J.length;for(this.clear();++ie<pe;){var ke=J[ie];this.set(ke[0],ke[1])}}function Si(){this.size=0,this.__data__={hash:new Ze,map:new(et||_t),string:new Ze}}function Cn(J){var ie=bo(this,J).delete(J);return this.size-=ie?1:0,ie}function Ii(J){return bo(this,J).get(J)}function Dn(J){return bo(this,J).has(J)}function On(J,ie){var pe=bo(this,J),ke=pe.size;return pe.set(J,ie),this.size+=pe.size==ke?0:1,this}pr.prototype.clear=Si,pr.prototype.delete=Cn,pr.prototype.get=Ii,pr.prototype.has=Dn,pr.prototype.set=On;function Mi(J){var ie=-1,pe=J==null?0:J.length;for(this.__data__=new pr;++ie<pe;)this.add(J[ie])}function nn(J){return this.__data__.set(J,i),this}function sn(J){return this.__data__.has(J)}Mi.prototype.add=Mi.prototype.push=nn,Mi.prototype.has=sn;function Ir(J){var ie=this.__data__=new _t(J);this.size=ie.size}function Pn(){this.__data__=new _t,this.size=0}function $n(J){var ie=this.__data__,pe=ie.delete(J);return this.size=ie.size,pe}function Rn(J){return this.__data__.get(J)}function fa(J){return this.__data__.has(J)}function cl(J,ie){var pe=this.__data__;if(pe instanceof _t){var ke=pe.__data__;if(!et||ke.length<r-1)return ke.push([J,ie]),this.size=++pe.size,this;pe=this.__data__=new pr(ke)}return pe.set(J,ie),this.size=pe.size,this}Ir.prototype.clear=Pn,Ir.prototype.delete=$n,Ir.prototype.get=Rn,Ir.prototype.has=fa,Ir.prototype.set=cl;function ul(J,ie){var pe=Oc(J),ke=!pe&&_l(J),Xt=!pe&&!ke&&tf(J),bt=!pe&&!ke&&!Xt&&xl(J),or=pe||ke||Xt||bt,Er=or?Xe(J.length,String):[],Ft=Er.length;for(var er in J)(ie||Ce.call(J,er))&&!(or&&(er=="length"||Xt&&(er=="offset"||er=="parent")||bt&&(er=="buffer"||er=="byteLength"||er=="byteOffset")||vl(er,Ft)))&&Er.push(er);return Er}function ha(J,ie){for(var pe=J.length;pe--;)if(wl(J[pe][0],ie))return pe;return-1}function Xu(J,ie,pe){var ke=ie(J);return Oc(J)?ke:we(ke,pe(J))}function la(J){return J==null?J===void 0?X:H:gt&&gt in Object(J)?pl(J):Ap(J)}function ef(J){return pa(J)&&la(J)==u}function da(J,ie,pe,ke,Xt){return J===ie?!0:J==null||ie==null||!pa(J)&&!pa(ie)?J!==J&&ie!==ie:fl(J,ie,pe,ke,da,Xt)}function fl(J,ie,pe,ke,Xt,bt){var or=Oc(J),Er=Oc(ie),Ft=or?l:bs(J),er=Er?l:bs(ie);Ft=Ft==u?U:Ft,er=er==u?U:er;var yr=Ft==U,Ci=er==U,Ar=Ft==er;if(Ar&&tf(J)){if(!tf(ie))return!1;or=!0,yr=!1}if(Ar&&!yr)return bt||(bt=new Ir),or||xl(J)?Cc(J,ie,pe,ke,Xt,bt):Ep(J,ie,Ft,pe,ke,Xt,bt);if(!(pe&n)){var ar=yr&&Ce.call(J,"__wrapped__"),hi=Ci&&Ce.call(ie,"__wrapped__");if(ar||hi){var Nn=ar?J.value():J,on=hi?ie.value():ie;return bt||(bt=new Ir),Xt(Nn,on,pe,ke,bt)}}return Ar?(bt||(bt=new Ir),dl(J,ie,pe,ke,Xt,bt)):!1}function _p(J){if(!Al(J)||bl(J))return!1;var ie=Pc(J)?Ve:ee;return ie.test(Us(J))}function hl(J){return pa(J)&&El(J.length)&&!!O[la(J)]}function ll(J){if(!yl(J))return Tt(J);var ie=[];for(var pe in Object(J))Ce.call(J,pe)&&pe!="constructor"&&ie.push(pe);return ie}function Cc(J,ie,pe,ke,Xt,bt){var or=pe&n,Er=J.length,Ft=ie.length;if(Er!=Ft&&!(or&&Ft>Er))return!1;var er=bt.get(J);if(er&&bt.get(ie))return er==ie;var yr=-1,Ci=!0,Ar=pe&s?new Mi:void 0;for(bt.set(J,ie),bt.set(ie,J);++yr<Er;){var ar=J[yr],hi=ie[yr];if(ke)var Nn=or?ke(hi,ar,yr,ie,J,bt):ke(ar,hi,yr,J,ie,bt);if(Nn!==void 0){if(Nn)continue;Ci=!1;break}if(Ar){if(!Re(ie,function(on,ys){if(!Ne(Ar,ys)&&(ar===on||Xt(ar,on,pe,ke,bt)))return Ar.push(ys)})){Ci=!1;break}}else if(!(ar===hi||Xt(ar,hi,pe,ke,bt))){Ci=!1;break}}return bt.delete(J),bt.delete(ie),Ci}function Ep(J,ie,pe,ke,Xt,bt,or){switch(pe){case y:if(J.byteLength!=ie.byteLength||J.byteOffset!=ie.byteOffset)return!1;J=J.buffer,ie=ie.buffer;case T:return!(J.byteLength!=ie.byteLength||!bt(new pt(J),new pt(ie)));case b:case w:case K:return wl(+J,+ie);case I:return J.name==ie.name&&J.message==ie.message;case k:case _:return J==ie+"";case L:var Er=be;case z:var Ft=ke&n;if(Er||(Er=Te),J.size!=ie.size&&!Ft)return!1;var er=or.get(J);if(er)return er==ie;ke|=s,or.set(J,ie);var yr=Cc(Er(J),Er(ie),ke,Xt,bt,or);return or.delete(J),yr;case B:if(Fe)return Fe.call(J)==Fe.call(ie)}return!1}function dl(J,ie,pe,ke,Xt,bt){var or=pe&n,Er=Dc(J),Ft=Er.length,er=Dc(ie),yr=er.length;if(Ft!=yr&&!or)return!1;for(var Ci=Ft;Ci--;){var Ar=Er[Ci];if(!(or?Ar in ie:Ce.call(ie,Ar)))return!1}var ar=bt.get(J);if(ar&&bt.get(ie))return ar==ie;var hi=!0;bt.set(J,ie),bt.set(ie,J);for(var Nn=or;++Ci<Ft;){Ar=Er[Ci];var on=J[Ar],ys=ie[Ar];if(ke)var rf=or?ke(ys,on,Ar,ie,J,bt):ke(on,ys,Ar,J,ie,bt);if(!(rf===void 0?on===ys||Xt(on,ys,pe,ke,bt):rf)){hi=!1;break}Nn||(Nn=Ar=="constructor")}if(hi&&!Nn){var ga=J.constructor,Tr=ie.constructor;ga!=Tr&&"constructor"in J&&"constructor"in ie&&!(typeof ga=="function"&&ga instanceof ga&&typeof Tr=="function"&&Tr instanceof Tr)&&(hi=!1)}return bt.delete(J),bt.delete(ie),hi}function Dc(J){return Xu(J,Ip,gl)}function bo(J,ie){var pe=J.__data__;return ml(ie)?pe[typeof ie=="string"?"string":"hash"]:pe.map}function ki(J,ie){var pe=Me(J,ie);return _p(pe)?pe:void 0}function pl(J){var ie=Ce.call(J,gt),pe=J[gt];try{J[gt]=void 0;var ke=!0}catch{}var Xt=Ke.call(J);return ke&&(ie?J[gt]=pe:delete J[gt]),Xt}var gl=Je?function(J){return J==null?[]:(J=Object(J),ye(Je(J),function(ie){return Ge.call(J,ie)}))}:Zt,bs=la;(Le&&bs(new Le(new ArrayBuffer(1)))!=y||et&&bs(new et)!=L||it&&bs(it.resolve())!=W||Be&&bs(new Be)!=z||rt&&bs(new rt)!=re)&&(bs=function(J){var ie=la(J),pe=ie==U?J.constructor:void 0,ke=pe?Us(pe):"";if(ke)switch(ke){case je:return y;case ht:return L;case nt:return W;case qe:return z;case st:return re}return ie});function vl(J,ie){return ie=ie??a,!!ie&&(typeof J=="number"||ae.test(J))&&J>-1&&J%1==0&&J<ie}function ml(J){var ie=typeof J;return ie=="string"||ie=="number"||ie=="symbol"||ie=="boolean"?J!=="__proto__":J===null}function bl(J){return!!_e&&_e in J}function yl(J){var ie=J&&J.constructor,pe=typeof ie=="function"&&ie.prototype||xe;return J===pe}function Ap(J){return Ke.call(J)}function Us(J){if(J!=null){try{return Ue.call(J)}catch{}try{return J+""}catch{}}return""}function wl(J,ie){return J===ie||J!==J&&ie!==ie}var _l=ef(function(){return arguments}())?ef:function(J){return pa(J)&&Ce.call(J,"callee")&&!Ge.call(J,"callee")},Oc=Array.isArray;function xp(J){return J!=null&&El(J.length)&&!Pc(J)}var tf=Ot||Qt;function Sp(J,ie){return da(J,ie)}function Pc(J){if(!Al(J))return!1;var ie=la(J);return ie==S||ie==D||ie==d||ie==R}function El(J){return typeof J=="number"&&J>-1&&J%1==0&&J<=a}function Al(J){var ie=typeof J;return J!=null&&(ie=="object"||ie=="function")}function pa(J){return J!=null&&typeof J=="object"}var xl=he?Oe(he):hl;function Ip(J){return xp(J)?ul(J):ll(J)}function Zt(){return[]}function Qt(){return!1}t.exports=Sp})(Vd,Vd.exports);var aD=Vd.exports,cD=Object.defineProperty,Vb=Object.getOwnPropertySymbols,uD=Object.prototype.hasOwnProperty,fD=Object.prototype.propertyIsEnumerable,Gb=(t,e,r)=>e in t?cD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ui=(t,e)=>{for(var r in e||(e={}))uD.call(e,r)&&Gb(t,r,e[r]);if(Vb)for(var r of Vb(e))fD.call(e,r)&&Gb(t,r,e[r]);return t};function hD(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,l=t.charAt(0),d=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 L=0,K=0,H=0,U=D.length;H!==U&&D[H]===0;)H++,L++;for(var W=(U-H)*b+1>>>0,R=new Uint8Array(W);H!==U;){for(var k=D[H],z=0,_=W-1;(k!==0||z<K)&&_!==-1;_--,z++)k+=256*R[_]>>>0,R[_]=k%u>>>0,k=k/u>>>0;if(k!==0)throw new Error("Non-zero carry");K=z,H++}for(var B=W-K;B!==W&&R[B]===0;)B++;for(var X=l.repeat(L);B<W;++B)X+=t.charAt(R[B]);return X}function I(D){if(typeof D!="string")throw new TypeError("Expected String");if(D.length===0)return new Uint8Array;var L=0;if(D[L]!==" "){for(var K=0,H=0;D[L]===l;)K++,L++;for(var U=(D.length-L)*d+1>>>0,W=new Uint8Array(U);D[L];){var R=r[D.charCodeAt(L)];if(R===255)return;for(var k=0,z=U-1;(R!==0||k<H)&&z!==-1;z--,k++)R+=u*W[z]>>>0,W[z]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");H=k,L++}if(D[L]!==" "){for(var _=U-H;_!==U&&W[_]===0;)_++;for(var B=new Uint8Array(K+(U-_)),X=K;_!==U;)B[X++]=W[_++];return B}}}function S(D){var L=I(D);if(L)return L;throw new Error(`Non-${e} character`)}return{encode:w,decodeUnsafe:I,decode:S}}var lD=hD,dD=lD;const Yb=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")},pD=t=>new TextEncoder().encode(t),gD=t=>new TextDecoder().decode(t);class vD{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 mD{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 Jb(this,e)}}class bD{constructor(e){this.decoders=e}or(e){return Jb(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 Jb=(t,e)=>new bD(ui(ui({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class yD{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new vD(e,r,i),this.decoder=new mD(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ih=({name:t,prefix:e,encode:r,decode:i})=>new yD(t,e,r,i),Mu=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=dD(r,e);return Ih({prefix:t,name:e,encode:i,decode:s=>Yb(n(s))})},wD=(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,l=0,d=0;for(let b=0;b<s;++b){const w=n[t[b]];if(w===void 0)throw new SyntaxError(`Non-${i} character`);l=l<<r|w,u+=r,u>=8&&(u-=8,a[d++]=255&l>>u)}if(u>=r||255&l<<8-u)throw new SyntaxError("Unexpected end of data");return a},_D=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",a=0,u=0;for(let l=0;l<t.length;++l)for(u=u<<8|t[l],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},zr=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Ih({prefix:e,name:t,encode(n){return _D(n,i,r)},decode(n){return wD(n,i,r,t)}}),ED=Ih({prefix:"\0",name:"identity",encode:t=>gD(t),decode:t=>pD(t)});var AD=Object.freeze({__proto__:null,identity:ED});const xD=zr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var SD=Object.freeze({__proto__:null,base2:xD});const ID=zr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var MD=Object.freeze({__proto__:null,base8:ID});const CD=Mu({prefix:"9",name:"base10",alphabet:"0123456789"});var DD=Object.freeze({__proto__:null,base10:CD});const OD=zr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),PD=zr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var $D=Object.freeze({__proto__:null,base16:OD,base16upper:PD});const RD=zr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ND=zr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),TD=zr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),LD=zr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),BD=zr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),FD=zr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),UD=zr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),kD=zr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),jD=zr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var qD=Object.freeze({__proto__:null,base32:RD,base32upper:ND,base32pad:TD,base32padupper:LD,base32hex:BD,base32hexupper:FD,base32hexpad:UD,base32hexpadupper:kD,base32z:jD});const zD=Mu({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),HD=Mu({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var KD=Object.freeze({__proto__:null,base36:zD,base36upper:HD});const WD=Mu({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),VD=Mu({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var GD=Object.freeze({__proto__:null,base58btc:WD,base58flickr:VD});const YD=zr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),JD=zr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),QD=zr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ZD=zr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var XD=Object.freeze({__proto__:null,base64:YD,base64pad:JD,base64url:QD,base64urlpad:ZD});const Qb=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}"),eO=Qb.reduce((t,e,r)=>(t[r]=e,t),[]),tO=Qb.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function rO(t){return t.reduce((e,r)=>(e+=eO[r],e),"")}function iO(t){const e=[];for(const r of t){const i=tO[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const nO=Ih({prefix:"\u{1F680}",name:"base256emoji",encode:rO,decode:iO});var sO=Object.freeze({__proto__:null,base256emoji:nO}),oO=Xb,Zb=128,aO=127,cO=~aO,uO=Math.pow(2,31);function Xb(t,e,r){e=e||[],r=r||0;for(var i=r;t>=uO;)e[r++]=t&255|Zb,t/=128;for(;t&cO;)e[r++]=t&255|Zb,t>>>=7;return e[r]=t|0,Xb.bytes=r-i+1,e}var fO=Gd,hO=128,e3=127;function Gd(t,i){var r=0,i=i||0,n=0,s=i,a,u=t.length;do{if(s>=u)throw Gd.bytes=0,new RangeError("Could not decode varint");a=t[s++],r+=n<28?(a&e3)<<n:(a&e3)*Math.pow(2,n),n+=7}while(a>=hO);return Gd.bytes=s-i,r}var lO=Math.pow(2,7),dO=Math.pow(2,14),pO=Math.pow(2,21),gO=Math.pow(2,28),vO=Math.pow(2,35),mO=Math.pow(2,42),bO=Math.pow(2,49),yO=Math.pow(2,56),wO=Math.pow(2,63),_O=function(t){return t<lO?1:t<dO?2:t<pO?3:t<gO?4:t<vO?5:t<mO?6:t<bO?7:t<yO?8:t<wO?9:10},EO={encode:oO,decode:fO,encodingLength:_O},t3=EO;const r3=(t,e,r=0)=>(t3.encode(t,e,r),e),i3=t=>t3.encodingLength(t),Yd=(t,e)=>{const r=e.byteLength,i=i3(t),n=i+i3(r),s=new Uint8Array(n+r);return r3(t,s,0),r3(r,s,i),s.set(e,n),new AO(t,r,e,s)};class AO{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const n3=({name:t,code:e,encode:r})=>new xO(t,e,r);class xO{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?Yd(this.code,r):r.then(i=>Yd(this.code,i))}else throw Error("Unknown type, must be binary type")}}const s3=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),SO=n3({name:"sha2-256",code:18,encode:s3("SHA-256")}),IO=n3({name:"sha2-512",code:19,encode:s3("SHA-512")});var MO=Object.freeze({__proto__:null,sha256:SO,sha512:IO});const o3=0,CO="identity",a3=Yb;var DO=Object.freeze({__proto__:null,identity:{code:o3,name:CO,encode:a3,digest:t=>Yd(o3,a3(t))}});new TextEncoder,new TextDecoder;const c3=ui(ui(ui(ui(ui(ui(ui(ui(ui(ui({},AD),SD),MD),DD),$D),qD),KD),GD),XD),sO);ui(ui({},MO),DO);function OO(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function u3(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const f3=u3("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Jd=u3("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=OO(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),PO=ui({utf8:f3,"utf-8":f3,hex:c3.base16,latin1:Jd,ascii:Jd,binary:Jd},c3);function $O(t,e="utf8"){const r=PO[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 h3="wc",l3=2,Qd="core",us=`${h3}@2:${Qd}:`,RO={name:Qd,logger:"error"},NO={database:":memory:"},TO="crypto",d3="client_ed25519_seed",LO=Ie.ONE_DAY,BO="keychain",FO="0.3",UO="messages",kO="0.3",jO=Ie.SIX_HOURS,qO="publisher",p3="irn",zO="error",g3="wss://relay.walletconnect.org",HO="relayer",Ei={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"},KO="_subscription",en={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},WO=.1,v3="2.15.3",VO=1e4,GO="0.3",YO="WALLETCONNECT_CLIENT_ID",fs={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},JO="subscription",QO="0.3",ZO=Ie.FIVE_SECONDS*1e3,XO="pairing",eP="0.3",Cu={wc_pairingDelete:{req:{ttl:Ie.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:Ie.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:Ie.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:Ie.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:Ie.ONE_DAY,prompt:!1,tag:0},res:{ttl:Ie.ONE_DAY,prompt:!1,tag:0}}},oc={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},xn={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},tP="history",rP="0.3",iP="expirer",tn={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},nP="0.3",sP="verify-api",oP="https://verify.walletconnect.com",m3="https://verify.walletconnect.org",Du=m3,aP=`${Du}/v3`,cP=[oP,m3],uP="echo",fP="https://echo.walletconnect.com",hs={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"},Ts={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"},Sn={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"},Ko={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"},Wo={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"},Ou={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"},hP=.1,lP="event-client",dP=86400,pP="https://pulse.walletconnect.com/batch";class gP{constructor(e,r){this.core=e,this.logger=r,this.keychain=new Map,this.name=BO,this.version=FO,this.initialized=!1,this.storagePrefix=us,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=ci(r,this.name)}get context(){return _i(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Fv(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Uv(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 vP{constructor(e,r,i){this.core=e,this.logger=r,this.name=TO,this.randomSessionIdentifier=Cd(),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=$v(n);return Pv(s.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const n=YS();return this.setPrivateKey(n.publicKey,n.privateKey)},this.signJWT=async n=>{this.isInitialized();const s=await this.getClientSeed(),a=$v(s),u=this.randomSessionIdentifier;return await DE(u,n,LO,a)},this.generateSharedKey=(n,s,a)=>{this.isInitialized();const u=this.getPrivateKey(n),l=JS(u,s);return this.setSymKey(l,a)},this.setSymKey=async(n,s)=>{this.isInitialized();const a=s||hh(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=ib(a),l=Is(s);if(nb(u)){const I=u.senderPublicKey,S=u.receiverPublicKey;n=await this.generateSharedKey(I,S)}const d=this.getSymKey(n),{type:b,senderPublicKey:w}=u;return ZS({type:b,symKey:d,message:l,senderPublicKey:w})},this.decode=async(n,s,a)=>{this.isInitialized();const u=tI(s,a);if(nb(u)){const l=u.receiverPublicKey,d=u.senderPublicKey;n=await this.generateSharedKey(l,d)}try{const l=this.getSymKey(n),d=XS({symKey:l,encoded:s});return qa(d)}catch(l){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(l)}},this.getPayloadType=n=>{const s=lh(n);return vu(s.type)},this.getPayloadSenderPublicKey=n=>{const s=lh(n);return s.senderPublicKey?bC(s.senderPublicKey,oi):void 0},this.core=e,this.logger=ci(r,this.name),this.keychain=i||new gP(this.core,this.logger)}get context(){return _i(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(d3)}catch{e=Cd(),await this.keychain.set(d3,e)}return $O(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 mP extends sC{constructor(e,r){super(e,r),this.logger=e,this.core=r,this.messages=new Map,this.name=UO,this.version=kO,this.initialized=!1,this.storagePrefix=us,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=$s(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=$s(n);return typeof s[a]<"u"},this.del=async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()},this.logger=ci(e,this.name),this.core=r}get context(){return _i(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Fv(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Uv(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 bP extends oC{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.events=new Br.exports.EventEmitter,this.name=qO,this.queue=new Map,this.publishTimeout=Ie.toMiliseconds(Ie.ONE_MINUTE),this.failedPublishTimeout=Ie.toMiliseconds(Ie.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,l=Dd(s),d=s?.prompt||!1,b=s?.tag||0,w=s?.id||Ho().toString(),I={topic:i,message:n,opts:{ttl:u,relay:l,prompt:d,tag:b,id:w,attestation:s?.attestation}},S=`Failed to publish payload, please try again. id:${w} tag:${b}`,D=Date.now();let L,K=1;try{for(;L===void 0;){if(Date.now()-D>this.publishTimeout)throw new Error(S);this.logger.trace({id:w,attempts:K},`publisher.publish - attempt ${K}`),L=await await za(this.rpcPublish(i,n,u,l,d,b,w,s?.attestation).catch(H=>this.logger.warn(H)),this.publishTimeout,S),K++,L||await new Promise(H=>setTimeout(H,this.failedPublishTimeout))}this.relayer.events.emit(Ei.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(H){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(H),(a=s?.internal)!=null&&a.throwOnFailedPublish)throw H;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=ci(r,this.name),this.registerEventListeners()}get context(){return _i(this.logger)}rpcPublish(e,r,i,n,s,a,u,l){var d,b,w,I;const S={method:mu(n.protocol).publish,params:{topic:e,message:r,ttl:i,prompt:s,tag:a,attestation:l},id:u};return ai((d=S.params)==null?void 0:d.prompt)&&((b=S.params)==null||delete b.prompt),ai((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(rc.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Ei.connection_stalled);return}this.checkQueue()}),this.relayer.on(Ei.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class yP{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 wP=Object.defineProperty,_P=Object.defineProperties,EP=Object.getOwnPropertyDescriptors,b3=Object.getOwnPropertySymbols,AP=Object.prototype.hasOwnProperty,xP=Object.prototype.propertyIsEnumerable,y3=(t,e,r)=>e in t?wP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pu=(t,e)=>{for(var r in e||(e={}))AP.call(e,r)&&y3(t,r,e[r]);if(b3)for(var r of b3(e))xP.call(e,r)&&y3(t,r,e[r]);return t},Zd=(t,e)=>_P(t,EP(e));class SP extends uC{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,this.subscriptions=new Map,this.topicMap=new yP,this.events=new Br.exports.EventEmitter,this.name=JO,this.version=QO,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=us,this.subscribeTimeout=Ie.toMiliseconds(Ie.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())},this.subscribe=async(i,n)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const s=Dd(n),a={topic:i,relay:s};this.pending.set(i,a);const u=await this.rpcSubscribe(i,s);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 Ie.Watch;u.start(n);const l=setInterval(()=>{!this.pending.has(i)&&this.topics.includes(i)&&(clearInterval(l),u.stop(n),s(!0)),u.elapsed(n)>=ZO&&(clearInterval(l),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=ci(r,this.name),this.clientId=""}get context(){return _i(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=Dd(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){const i={method:mu(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{return await await za(this.relayer.request(i).catch(n=>this.logger.warn(n)),this.subscribeTimeout)?$s(e+this.clientId):null}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Ei.connection_stalled)}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:mu(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 za(this.relayer.request(i).catch(n=>this.logger.warn(n)),this.subscribeTimeout)}catch{this.relayer.events.emit(Ei.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:mu(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 za(this.relayer.request(i).catch(s=>this.logger.warn(s)),this.subscribeTimeout)}catch{this.relayer.events.emit(Ei.connection_stalled)}return n}rpcUnsubscribe(e,r,i){const n={method:mu(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,Zd(Pu({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Pu({},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,Pu({},r)),this.topicMap.set(r.topic,e),this.events.emit(fs.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(fs.deleted,Zd(Pu({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(fs.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(fs.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);ss(r)&&this.onBatchSubscribe(r.map((i,n)=>Zd(Pu({},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(rc.pulse,async()=>{await this.checkPending()}),this.events.on(fs.created,async e=>{const r=fs.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),await this.persist()}),this.events.on(fs.deleted,async e=>{const r=fs.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.restartInProgress&&await new Promise(e=>{const r=setInterval(()=>{this.restartInProgress||(clearInterval(r),e())},this.pollingInterval)})}}var IP=Object.defineProperty,w3=Object.getOwnPropertySymbols,MP=Object.prototype.hasOwnProperty,CP=Object.prototype.propertyIsEnumerable,_3=(t,e,r)=>e in t?IP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,DP=(t,e)=>{for(var r in e||(e={}))MP.call(e,r)&&_3(t,r,e[r]);if(w3)for(var r of w3(e))CP.call(e,r)&&_3(t,r,e[r]);return t};class OP extends aC{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new Br.exports.EventEmitter,this.name=HO,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=Ie.toMiliseconds(Ie.THIRTY_SECONDS+Ie.ONE_SECOND),this.request=async r=>{var i,n;this.logger.debug("Publishing Request Payload");const s=r.id||Ho().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(l,d)=>{const b=()=>{d(new Error(`relayer.request - publish interrupted, id: ${s}`))};this.provider.on(en.disconnect,b);const w=await a;this.provider.off(en.disconnect,b),l(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(iu())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(Ei.connect)},this.onDisconnectHandler=()=>{this.logger.trace("relayer disconnected"),this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.error(r),this.events.emit(Ei.error,r),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(en.payload,this.onPayloadHandler),this.provider.on(en.connect,this.onConnectHandler),this.provider.on(en.disconnect,this.onDisconnectHandler),this.provider.on(en.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?ci(e.logger,this.name):os(Eh({level:e.logger||zO})),this.messages=new mP(this.logger,e.core),this.subscriber=new SP(this,this.logger),this.publisher=new bP(this,this.logger),this.relayUrl=e?.relayUrl||g3,this.projectId=e.projectId,this.bundleId=BE(),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),await this.transportOpen(),this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&this.subscriber.pending.size===0&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},VO)}get context(){return _i(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()})}async subscribe(e,r){var i;this.isInitialized();let n=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"",s;const a=u=>{u.topic===e&&(this.subscriber.off(fs.created,a),s())};return await Promise.all([new Promise(u=>{s=u,this.subscriber.on(fs.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 za(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(en.disconnect,n),i(new Error("Connection interrupted while trying to subscribe"))};this.provider.on(en.disconnect,n),await za(this.provider.connect(),Ie.toMiliseconds(Ie.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 vb())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`)}startPingTimeout(){var e,r,i,n,s;if(iu())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 An(new oD(zE({sdkVersion:v3,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}),Wd(e)){if(!e.method.endsWith(KO))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:a}=r.data,u={topic:i,message:n,publishedAt:s,attestation:a};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(DP({type:"event",event:r.id},u)),this.events.emit(r.id,u),await this.acknowledgePayload(e),await this.onMessageEvent(u)}else Sh(e)&&this.events.emit(Ei.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Ei.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const r=Ah(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(en.payload,this.onPayloadHandler),this.provider.off(en.connect,this.onConnectHandler),this.provider.off(en.disconnect,this.onDisconnectHandler),this.provider.off(en.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await vb();YI(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(Ei.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&(this.reconnectTimeout||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e))},Ie.toMiliseconds(WO))))}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 PP=Object.defineProperty,E3=Object.getOwnPropertySymbols,$P=Object.prototype.hasOwnProperty,RP=Object.prototype.propertyIsEnumerable,A3=(t,e,r)=>e in t?PP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,x3=(t,e)=>{for(var r in e||(e={}))$P.call(e,r)&&A3(t,r,e[r]);if(E3)for(var r of E3(e))RP.call(e,r)&&A3(t,r,e[r]);return t};class Vo extends cC{constructor(e,r,i,n=us,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,this.map=new Map,this.version=GO,this.cached=[],this.initialized=!1,this.storagePrefix=us,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&&!ai(a)?this.map.set(this.getKey(a),a):II(a)?this.map.set(a.id,a):MI(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(l=>aD(u[l],a[l]))):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 l=x3(x3({},this.getData(a)),u);this.map.set(a,l),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=ci(r,this.name),this.storagePrefix=n,this.getKey=s}get context(){return _i(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 NP{constructor(e,r){this.core=e,this.logger=r,this.name=XO,this.version=eP,this.events=new Br.exports,this.initialized=!1,this.storagePrefix=us,this.ignoredPayloadTypes=[Ps],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=Cd(),s=await this.core.crypto.setSymKey(n),a=kr(Ie.FIVE_MINUTES),u={protocol:p3},l={topic:s,expiry:a,relay:u,active:!1},d=vI({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,l),await this.core.relayer.subscribe(s),{topic:s,uri:d}},this.pair=async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i?.uri,trace:[hs.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:a,relay:u,expiryTimestamp:l,methods:d}=cb(i.uri);n.props.properties.topic=s,n.addTrace(hs.pairing_uri_validation_success),n.addTrace(hs.pairing_uri_not_expired);let b;if(this.pairings.keys.includes(s)){if(b=this.pairings.get(s),n.addTrace(hs.existing_pairing),b.active)throw n.setError(Ts.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(hs.pairing_not_expired)}const w=l||kr(Ie.FIVE_MINUTES),I={topic:s,relay:u,expiry:w,active:!1,methods:d};this.core.expirer.set(s,w),await this.pairings.set(s,I),n.addTrace(hs.store_new_pairing),i.activatePairing&&await this.activate({topic:s}),this.events.emit(oc.create,I),n.addTrace(hs.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(a,s),n.addTrace(hs.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(Ts.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:u})}catch(S){throw n.setError(Ts.subscribe_pairing_topic_failure),S}return n.addTrace(hs.subscribe_pairing_topic_success),I},this.activate=async({topic:i})=>{this.isInitialized();const n=kr(Ie.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:l}=Fo();this.events.once(Dt("pairing_ping",s),({error:d})=>{d?l(d):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=sc(n,s),u=await this.core.crypto.encode(i,a),l=Cu[n].req;return this.core.history.set(i,a),this.core.relayer.publish(i,u,l),a.id},this.sendResult=async(i,n,s)=>{const a=Ah(i,s),u=await this.core.crypto.encode(n,a),l=await this.core.history.get(n,i),d=Cu[l.request.method].res;await this.core.relayer.publish(n,u,d),await this.core.history.resolve(a)},this.sendError=async(i,n,s)=>{const a=xh(i,s),u=await this.core.crypto.encode(n,a),l=await this.core.history.get(n,i),d=Cu[l.request.method]?Cu[l.request.method].res:Cu.unregistered_method.res;await this.core.relayer.publish(n,u,d),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=>eo(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(oc.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(()=>{cs(n)?this.events.emit(Dt("pairing_ping",s),{}):Xi(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(oc.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(!yi(i)){const{message:u}=Ee("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(Ts.malformed_pairing_uri),new Error(u)}if(!SI(i.uri)){const{message:u}=Ee("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(Ts.malformed_pairing_uri),new Error(u)}const a=cb(i?.uri);if(!((s=a?.relay)!=null&&s.protocol)){const{message:u}=Ee("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(Ts.malformed_pairing_uri),new Error(u)}if(!(a!=null&&a.symKey)){const{message:u}=Ee("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(Ts.malformed_pairing_uri),new Error(u)}if(a!=null&&a.expiryTimestamp&&Ie.toMiliseconds(a?.expiryTimestamp)<Date.now()){n.setError(Ts.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(!yi(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(!yi(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(!mr(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(eo(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=ci(r,this.name),this.pairings=new Vo(this.core,this.logger,this.name,this.storagePrefix)}get context(){return _i(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Ei.message,async e=>{const{topic:r,message:i}=e;if(!this.pairings.keys.includes(r)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const n=await this.core.crypto.decode(r,i);try{Wd(n)?(this.core.history.set(r,n),this.onRelayEventRequest({topic:r,payload:n})):Sh(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:r,payload:n}),this.core.history.delete(r,n.id))}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(tn.expired,async e=>{const{topic:r}=jv(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(oc.expire,{topic:r}))})}}class TP extends nC{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.records=new Map,this.events=new Br.exports.EventEmitter,this.name=tP,this.version=rP,this.cached=[],this.initialized=!1,this.storagePrefix=us,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:kr(Ie.THIRTY_DAYS)};this.records.set(a.id,a),this.persist(),this.events.emit(xn.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=Xi(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(xn.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(xn.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=ci(r,this.name)}get context(){return _i(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:sc(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(xn.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(xn.created,e=>{const r=xn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(xn.updated,e=>{const r=xn.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(xn.deleted,e=>{const r=xn.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(rc.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{Ie.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(xn.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 LP extends fC{constructor(e,r){super(e,r),this.core=e,this.logger=r,this.expirations=new Map,this.events=new Br.exports.EventEmitter,this.name=iP,this.version=nP,this.cached=[],this.initialized=!1,this.storagePrefix=us,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(tn.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(tn.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=ci(r,this.name)}get context(){return _i(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 HE(e);if(typeof e=="number")return KE(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(tn.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;Ie.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(tn.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(rc.pulse,()=>this.checkExpirations()),this.events.on(tn.created,e=>{const r=tn.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(tn.expired,e=>{const r=tn.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(tn.deleted,e=>{const r=tn.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 sr={};Object.defineProperty(sr,"__esModule",{value:!0}),sr.getLocalStorage=sr.getLocalStorageOrThrow=sr.getCrypto=sr.getCryptoOrThrow=sr.getLocation=sr.getLocationOrThrow=sr.getNavigator=sr.getNavigatorOrThrow=S3=sr.getDocument=sr.getDocumentOrThrow=sr.getFromWindowOrThrow=sr.getFromWindow=void 0;function Go(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}sr.getFromWindow=Go;function ac(t){const e=Go(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}sr.getFromWindowOrThrow=ac;function BP(){return ac("document")}sr.getDocumentOrThrow=BP;function FP(){return Go("document")}var S3=sr.getDocument=FP;function UP(){return ac("navigator")}sr.getNavigatorOrThrow=UP;function kP(){return Go("navigator")}sr.getNavigator=kP;function jP(){return ac("location")}sr.getLocationOrThrow=jP;function qP(){return Go("location")}sr.getLocation=qP;function zP(){return ac("crypto")}sr.getCryptoOrThrow=zP;function HP(){return Go("crypto")}sr.getCrypto=HP;function KP(){return ac("localStorage")}sr.getLocalStorageOrThrow=KP;function WP(){return Go("localStorage")}sr.getLocalStorage=WP;class VP extends hC{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,this.name=sP,this.verifyUrlV3=aP,this.storagePrefix=us,this.version=l3,this.init=async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&Ie.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(!su()||this.isDevEnv)return;const s=window.location.origin,{id:a,decryptedId:u}=n,l=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${a}&decryptedId=${u}`;try{const d=S3(),b=this.startAbortTimer(Ie.ONE_SECOND*5),w=await new Promise((I,S)=>{const D=()=>{window.removeEventListener("message",K),d.body.removeChild(L),S("attestation aborted")};this.abortController.signal.addEventListener("abort",D);const L=d.createElement("iframe");L.src=l,L.style.display="none",L.addEventListener("error",D,{signal:this.abortController.signal});const K=H=>{if(!H.data)return;const U=JSON.parse(H.data);if(U.type==="verify_attestation"){if(Z0(U.attestation).payload.id!==a)return;clearInterval(b),d.body.removeChild(L),this.abortController.signal.removeEventListener("abort",D),window.removeEventListener("message",K),I(U.attestation===null?"":U.attestation)}};d.body.appendChild(L),window.addEventListener("message",K,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",w),w}catch(d){this.logger.warn(d)}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(Z0(s).payload.id!==u)return;const d=await this.isValidJwtAttestation(s);if(d){if(!d.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return d}}if(!a)return;const l=this.getVerifyUrl(n?.verifyUrl);return this.fetchAttestation(a,l)},this.fetchAttestation=async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const a=this.startAbortTimer(Ie.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||Du;return cP.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Du}`),s=Du),s},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(Ie.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=sI(n,s.publicKey),u={hasExpired:Ie.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=ci(r,this.name),this.abortController=new AbortController,this.isDevEnv=iu()&&process.env.IS_VITEST,this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return _i(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),Ie.toMiliseconds(e))}}class GP extends lC{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,this.context=uP,this.registerDeviceToken=async i=>{const{clientId:n,token:s,notificationType:a,enableEncrypted:u=!1}=i,l=`${fP}/${this.projectId}/clients`;await fetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:a,token:s,always_raw:u})})},this.logger=ci(r,this.context)}}var YP=Object.defineProperty,I3=Object.getOwnPropertySymbols,JP=Object.prototype.hasOwnProperty,QP=Object.prototype.propertyIsEnumerable,M3=(t,e,r)=>e in t?YP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$u=(t,e)=>{for(var r in e||(e={}))JP.call(e,r)&&M3(t,r,e[r]);if(I3)for(var r of I3(e))QP.call(e,r)&&M3(t,r,e[r]);return t};class ZP extends dC{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,this.context=lP,this.storagePrefix=us,this.storageVersion=hP,this.events=new Map,this.shouldPersist=!1,this.createEvent=n=>{const{event:s="ERROR",type:a="",properties:{topic:u,trace:l}}=n,d=GE(),b=this.core.projectId||"",w=Date.now(),I=$u({eventId:d,bundleId:b,timestamp:w,props:{event:s,type:a,properties:{topic:u,trace:l}}},this.setMethods(d));return this.telemetryEnabled&&(this.events.set(d,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(l=>l.props.properties.topic===a);if(u)return $u($u({},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(rc.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{Ie.fromMiliseconds(Date.now())-Ie.fromMiliseconds(n.timestamp)>dP&&(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,$u($u({},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(`${pP}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${v3}`,{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=ci(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 XP=Object.defineProperty,C3=Object.getOwnPropertySymbols,e$=Object.prototype.hasOwnProperty,t$=Object.prototype.propertyIsEnumerable,D3=(t,e,r)=>e in t?XP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,O3=(t,e)=>{for(var r in e||(e={}))e$.call(e,r)&&D3(t,r,e[r]);if(C3)for(var r of C3(e))t$.call(e,r)&&D3(t,r,e[r]);return t};class Xd extends iC{constructor(e){var r;super(e),this.protocol=h3,this.version=l3,this.name=Qd,this.events=new Br.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.projectId=e?.projectId,this.relayUrl=e?.relayUrl||g3,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Eh({level:typeof e?.logger=="string"&&e.logger?e.logger:RO.logger}),{logger:n,chunkLoggerController:s}=rC({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=ci(n,this.name),this.heartbeat=new Bd,this.crypto=new vP(this,this.logger,e?.keychain),this.history=new TP(this,this.logger),this.expirer=new LP(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new MM(O3(O3({},NO),e?.storageOptions)),this.relayer=new OP({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new NP(this,this.logger),this.verify=new VP(this,this.logger,this.storage),this.echoClient=new GP(this.projectId||"",this.logger),this.eventClient=new ZP(this,this.logger,e?.telemetryEnabled)}static async init(e){const r=new Xd(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(YO,i),r}get context(){return _i(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 initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const r$=Xd,P3="wc",$3=2,R3="client",e1=`${P3}@${$3}:${R3}:`,t1={name:R3,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.com"},N3="WALLETCONNECT_DEEPLINK_CHOICE",i$="proposal",T3="Proposal expired",n$="session",cc=Ie.SEVEN_DAYS,s$="engine",Hr={wc_sessionPropose:{req:{ttl:Ie.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Ie.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Ie.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Ie.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Ie.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Ie.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Ie.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Ie.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Ie.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Ie.ONE_DAY,prompt:!1,tag:1114},res:{ttl:Ie.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:Ie.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:Ie.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:Ie.FIVE_MINUTES,prompt:!1,tag:1119}}},r1={min:Ie.FIVE_MINUTES,max:Ie.SEVEN_DAYS},ls={idle:"IDLE",active:"ACTIVE"},o$="request",a$=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],c$="wc",u$="auth",f$="authKeys",h$="pairingTopics",l$="requests",Mh=`${c$}@${1.5}:${u$}:`,Ch=`${Mh}:PUB_KEY`;var d$=Object.defineProperty,p$=Object.defineProperties,g$=Object.getOwnPropertyDescriptors,L3=Object.getOwnPropertySymbols,v$=Object.prototype.hasOwnProperty,m$=Object.prototype.propertyIsEnumerable,B3=(t,e,r)=>e in t?d$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xr=(t,e)=>{for(var r in e||(e={}))v$.call(e,r)&&B3(t,r,e[r]);if(L3)for(var r of L3(e))m$.call(e,r)&&B3(t,r,e[r]);return t},Yo=(t,e)=>p$(t,g$(e));class b$ extends gC{constructor(e){super(e),this.name=s$,this.events=new Br.exports,this.initialized=!1,this.requestQueue={state:ls.idle,queue:[]},this.sessionRequestQueue={state:ls.idle,queue:[]},this.requestQueueDelay=Ie.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(),this.client.core.pairing.register({methods:Object.keys(Hr)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},Ie.toMiliseconds(this.requestQueueDelay)))},this.connect=async r=>{await this.isInitialized();const i=Yo(xr({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:n,requiredNamespaces:s,optionalNamespaces:a,sessionProperties:u,relays:l}=i;let d=n,b,w=!1;try{d&&(w=this.client.core.pairing.pairings.get(d).active)}catch(R){throw this.client.logger.error(`connect() -> pairing.get(${d}) failed`),R}if(!d||!w){const{topic:R,uri:k}=await this.client.core.pairing.create();d=R,b=k}if(!d){const{message:R}=Ee("NO_MATCHING_KEY",`connect() pairing topic: ${d}`);throw new Error(R)}const I=await this.client.core.crypto.generateKeyPair(),S=Hr.wc_sessionPropose.req.ttl||Ie.FIVE_MINUTES,D=kr(S),L=xr({requiredNamespaces:s,optionalNamespaces:a,relays:l??[{protocol:p3}],proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:D,pairingTopic:d},u&&{sessionProperties:u}),{reject:K,resolve:H,done:U}=Fo(S,T3);this.events.once(Dt("session_connect"),async({error:R,session:k})=>{if(R)K(R);else if(k){k.self.publicKey=I;const z=Yo(xr({},k),{pairingTopic:L.pairingTopic,requiredNamespaces:L.requiredNamespaces,optionalNamespaces:L.optionalNamespaces});await this.client.session.set(k.topic,z),await this.setExpiry(k.topic,k.expiry),d&&await this.client.core.pairing.updateMetadata({topic:d,metadata:k.peer.metadata}),this.cleanupDuplicatePairings(z),H(z)}});const W=await this.sendRequest({topic:d,method:"wc_sessionPropose",params:L,throwOnFailedPublish:!0});return await this.setProposal(W,xr({id:W},L)),{uri:b,approval:U}},this.pair=async r=>{await this.isInitialized();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:[Sn.session_approve_started]}});try{await this.isInitialized()}catch(_){throw a.setError(Ko.no_internet_connection),_}try{await this.isValidProposalId(r?.id)}catch(_){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),a.setError(Ko.proposal_not_found),_}try{await this.isValidApprove(r)}catch(_){throw this.client.logger.error("approve() -> isValidApprove() failed"),a.setError(Ko.session_approve_namespace_validation_failure),_}const{id:u,relayProtocol:l,namespaces:d,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:L,optionalNamespaces:K}=I;let H=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:S});H||(H=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Sn.session_approve_started,properties:{topic:S,trace:[Sn.session_approve_started,Sn.session_namespaces_validation_success]}}));const U=await this.client.core.crypto.generateKeyPair(),W=D.publicKey,R=await this.client.core.crypto.generateSharedKey(U,W),k=xr(xr({relay:{protocol:l??"irn"},namespaces:d,controller:{publicKey:U,metadata:this.client.metadata},expiry:kr(cc)},b&&{sessionProperties:b}),w&&{sessionConfig:w});H.addTrace(Sn.subscribing_session_topic);try{await this.client.core.relayer.subscribe(R)}catch(_){throw H.setError(Ko.subscribe_session_topic_failure),_}H.addTrace(Sn.subscribe_session_topic_success);const z=Yo(xr({},k),{topic:R,requiredNamespaces:L,optionalNamespaces:K,pairingTopic:S,acknowledged:!1,self:k.controller,peer:{publicKey:D.publicKey,metadata:D.metadata},controller:U});await this.client.session.set(R,z),H.addTrace(Sn.store_session);try{H.addTrace(Sn.publishing_session_settle),await this.sendRequest({topic:R,method:"wc_sessionSettle",params:k,throwOnFailedPublish:!0}).catch(_=>{throw H?.setError(Ko.session_settle_publish_failure),_}),H.addTrace(Sn.session_settle_publish_success),H.addTrace(Sn.publishing_session_approve),await this.sendResult({id:u,topic:S,result:{relay:{protocol:l??"irn"},responderPublicKey:U},throwOnFailedPublish:!0}).catch(_=>{throw H?.setError(Ko.session_approve_publish_failure),_}),H.addTrace(Sn.session_approve_publish_success)}catch(_){throw this.client.logger.error(_),this.client.session.delete(R,Gt("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(R),_}return this.client.core.eventClient.deleteEvent({eventId:H.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,kr(cc)),{topic:R,acknowledged:()=>Promise.resolve(this.client.session.get(R))}},this.reject=async r=>{await this.isInitialized();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:Hr.wc_sessionPropose.reject}),await this.client.proposal.delete(i,Gt("USER_DISCONNECTED")))},this.update=async r=>{await this.isInitialized();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}=Fo(),l=no(),d=Ho().toString(),b=this.client.session.get(i).namespaces;return this.events.once(Dt("session_update",l),({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:l,relayRpcId:d}).catch(w=>{this.client.logger.error(w),this.client.session.update(i,{namespaces:b}),u(w)}),{acknowledged:s}},this.extend=async r=>{await this.isInitialized();try{await this.isValidExtend(r)}catch(l){throw this.client.logger.error("extend() -> isValidExtend() failed"),l}const{topic:i}=r,n=no(),{done:s,resolve:a,reject:u}=Fo();return this.events.once(Dt("session_extend",n),({error:l})=>{l?u(l):a()}),await this.setExpiry(i,kr(cc)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(l=>{u(l)}),{acknowledged:s}},this.request=async r=>{await this.isInitialized();try{await this.isValidRequest(r)}catch(S){throw this.client.logger.error("request() -> isValidRequest() failed"),S}const{chainId:i,request:n,topic:s,expiry:a=Hr.wc_sessionRequest.req.ttl}=r,u=this.client.session.get(s),l=no(),d=Ho().toString(),{done:b,resolve:w,reject:I}=Fo(a,"Request expired. Please try again.");return this.events.once(Dt("session_request",l),({error:S,result:D})=>{S?I(S):w(D)}),await Promise.all([new Promise(async S=>{await this.sendRequest({clientRpcId:l,relayRpcId:d,topic:s,method:"wc_sessionRequest",params:{request:Yo(xr({},n),{expiryTimestamp:kr(a)}),chainId:i},expiry:a,throwOnFailedPublish:!0}).catch(D=>I(D)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:l}),S()}),new Promise(async S=>{var D;if(!((D=u.sessionConfig)!=null&&D.disableDeepLink)){const L=await VE(this.client.core.storage,N3);WE({id:l,topic:s,wcDeepLink:L})}S()}),b()]).then(S=>S[2])},this.respond=async r=>{await this.isInitialized(),await this.isValidRespond(r);const{topic:i,response:n}=r,{id:s}=n;cs(n)?await this.sendResult({id:s,topic:i,result:n.result,throwOnFailedPublish:!0}):Xi(n)&&await this.sendError({id:s,topic:i,error:n.error}),this.cleanupAfterResponse(r)},this.ping=async r=>{await this.isInitialized();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=no(),s=Ho().toString(),{done:a,resolve:u,reject:l}=Fo();this.events.once(Dt("session_ping",n),({error:d})=>{d?l(d):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=>{await this.isInitialized(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,a=Ho().toString();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:a})},this.disconnect=async r=>{await this.isInitialized(),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=>AI(i,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async r=>{this.isInitialized(),this.isValidAuthenticate(r);const{chains:i,statement:n="",uri:s,domain:a,nonce:u,type:l,exp:d,nbf:b,methods:w=[],expiry:I}=r,S=[...r.resources||[]],{topic:D,uri:L}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"]});this.client.logger.info({message:"Generated new pairing",pairing:{topic:D,uri:L}});const K=await this.client.core.crypto.generateKeyPair(),H=hh(K);if(await Promise.all([this.client.auth.authKeys.set(Ch,{responseTopic:H,publicKey:K}),this.client.auth.pairingTopics.set(H,{topic:H,pairingTopic:D})]),await this.client.core.relayer.subscribe(H),this.client.logger.info(`sending request to new pairing topic: ${D}`),w.length>0){const{namespace:f}=ru(i[0]);let h=zS(f,"request",w);fh(S)&&(h=KS(h,S.pop())),S.push(h)}const U=I&&I>Hr.wc_sessionAuthenticate.req.ttl?I:Hr.wc_sessionAuthenticate.req.ttl,W={authPayload:{type:l??"caip122",chains:i,statement:n,aud:s,domain:a,version:"1",nonce:u,iat:new Date().toISOString(),exp:d,nbf:b,resources:S},requester:{publicKey:K,metadata:this.client.metadata},expiryTimestamp:kr(U)},R={eip155:{chains:i,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},k={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:D,proposer:{publicKey:K,metadata:this.client.metadata},expiryTimestamp:kr(Hr.wc_sessionPropose.req.ttl)},{done:z,resolve:_,reject:B}=Fo(U,"Request expired"),X=async({error:f,session:h})=>{if(this.events.off(Dt("session_request",T),re),f)B(f);else if(h){h.self.publicKey=K,await this.client.session.set(h.topic,h),await this.setExpiry(h.topic,h.expiry),D&&await this.client.core.pairing.updateMetadata({topic:D,metadata:h.peer.metadata});const v=this.client.session.get(h.topic);await this.deleteProposal(y),_({session:v})}},re=async f=>{if(await this.deletePendingAuthRequest(T,{message:"fulfilled",code:0}),f.error){const g=Gt("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return f.error.code===g.code?void 0:(this.events.off(Dt("session_connect"),X),B(f.error.message))}await this.deleteProposal(y),this.events.off(Dt("session_connect"),X);const{cacaos:h,responder:v}=f.result,E=[],C=[];for(const g of h){await Ym({cacao:g,projectId:this.client.core.projectId})||(this.client.logger.error(g,"Signature verification failed"),B(Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:m}=g,N=fh(m.resources),ee=[Gm(m.iss)],ae=uh(m.iss);if(N){const O=Zm(N),te=Xm(N);E.push(...O),ee.push(...te)}for(const O of ee)C.push(`${O}:${ae}`)}const P=await this.client.core.crypto.generateSharedKey(K,v.publicKey);let M;E.length>0&&(M={topic:P,acknowledged:!0,self:{publicKey:K,metadata:this.client.metadata},peer:v,controller:v.publicKey,expiry:kr(cc),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:D,namespaces:ub([...new Set(E)],[...new Set(C)])},await this.client.core.relayer.subscribe(P),await this.client.session.set(P,M),D&&await this.client.core.pairing.updateMetadata({topic:D,metadata:v.metadata}),M=this.client.session.get(P)),_({auths:h,session:M})},T=no(),y=no();this.events.once(Dt("session_connect"),X),this.events.once(Dt("session_request",T),re);try{await Promise.all([this.sendRequest({topic:D,method:"wc_sessionAuthenticate",params:W,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:T}),this.sendRequest({topic:D,method:"wc_sessionPropose",params:k,expiry:Hr.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:y})])}catch(f){throw this.events.off(Dt("session_connect"),X),this.events.off(Dt("session_request",T),re),f}return await this.setProposal(y,xr({id:y},k)),await this.setAuthRequest(T,{request:Yo(xr({},W),{verifyContext:{}}),pairingTopic:D}),{uri:L,response:z}},this.approveSessionAuthenticate=async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Wo.authenticated_session_approve_started]}});try{this.isInitialized()}catch(L){throw s.setError(Ou.no_internet_connection),L}const a=this.getPendingAuthRequest(i);if(!a)throw s.setError(Ou.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const u=a.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),d=hh(u),b={type:Ps,receiverPublicKey:u,senderPublicKey:l},w=[],I=[];for(const L of n){if(!await Ym({cacao:L,projectId:this.client.core.projectId})){s.setError(Ou.invalid_cacao);const R=Gt("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:d,error:R,encodeOpts:b}),new Error(R.message)}s.addTrace(Wo.cacaos_verified);const{p:K}=L,H=fh(K.resources),U=[Gm(K.iss)],W=uh(K.iss);if(H){const R=Zm(H),k=Xm(H);w.push(...R),U.push(...k)}for(const R of U)I.push(`${R}:${W}`)}const S=await this.client.core.crypto.generateSharedKey(l,u);s.addTrace(Wo.create_authenticated_session_topic);let D;if(w?.length>0){D={topic:S,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:u,metadata:a.requester.metadata},controller:u,expiry:kr(cc),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:a.pairingTopic,namespaces:ub([...new Set(w)],[...new Set(I)])},s.addTrace(Wo.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(S)}catch(L){throw s.setError(Ou.subscribe_authenticated_session_topic_failure),L}s.addTrace(Wo.subscribe_authenticated_session_topic_success),await this.client.session.set(S,D),s.addTrace(Wo.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:a.pairingTopic,metadata:a.requester.metadata})}s.addTrace(Wo.publishing_authenticated_session_approve);try{await this.sendResult({topic:d,id:i,result:{cacaos:n,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:b,throwOnFailedPublish:!0})}catch(L){throw s.setError(Ou.authenticated_session_approve_publish_failure),L}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:D}},this.rejectSessionAuthenticate=async r=>{await 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}`);const a=s.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=hh(a),d={type:Ps,receiverPublicKey:a,senderPublicKey:u};await this.sendError({id:i,topic:l,error:n,encodeOpts:d,rpcOpts:Hr.wc_sessionAuthenticate.reject}),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 Jm(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:l}=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(l.publicKey)&&await this.client.core.crypto.deleteKeyPair(l.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(N3).catch(d=>this.client.logger.warn(d)),this.getPendingSessionRequests().forEach(d=>{d.topic===n&&this.deletePendingSessionRequest(d.id,Gt("USER_DISCONNECTED"))}),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=ls.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(Ko.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=ls.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,kr(Hr.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)},this.setAuthRequest=async(r,i)=>{const{request:n,pairingTopic:s}=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})},this.setPendingSessionRequest=async r=>{const{id:i,topic:n,params:s,verifyContext:a}=r,u=s.request.expiryTimestamp||kr(Hr.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:l,throwOnFailedPublish:d}=r,b=sc(n,s,l);let w;try{w=await this.client.core.crypto.encode(i,b)}catch(D){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),D}let I;if(a$.includes(n)){const D=$s(JSON.stringify(b)),L=$s(w);I=await this.client.core.verify.register({id:L,decryptedId:D})}const S=Hr[n].req;return S.attestation=I,a&&(S.ttl=a),u&&(S.id=u),this.client.core.history.set(i,b),d?(S.internal=Yo(xr({},S.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,w,S)):this.client.core.relayer.publish(i,w,S).catch(D=>this.client.logger.error(D)),b.id},this.sendResult=async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:a,encodeOpts:u}=r,l=Ah(i,s);let d;try{d=await this.client.core.crypto.encode(n,l,u)}catch(I){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),I}let b;try{b=await this.client.core.history.get(n,i)}catch(I){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),I}const w=Hr[b.request.method].res;a?(w.internal=Yo(xr({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,d,w)):this.client.core.relayer.publish(n,d,w).catch(I=>this.client.logger.error(I)),await this.client.core.history.resolve(l)},this.sendError=async r=>{const{id:i,topic:n,error:s,encodeOpts:a,rpcOpts:u}=r,l=xh(i,s);let d;try{d=await this.client.core.crypto.encode(n,l,a)}catch(I){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),I}let b;try{b=await this.client.core.history.get(n,i)}catch(I){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),I}const w=u||Hr[b.request.method].res;this.client.core.relayer.publish(n,d,w),await this.client.core.history.resolve(l)},this.cleanup=async()=>{const r=[],i=[];this.client.session.getAll().forEach(n=>{let s=!1;eo(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=>{eo(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===ls.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=ls.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=ls.idle},this.processRequest=async r=>{const{topic:i,payload:n,attestation:s,encryptedId:a}=r,u=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:u}))switch(u){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:s,encryptedId:a});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:a});default:return this.client.logger.info(`Unsupported request method ${u}`)}},this.onRelayEventResponse=async r=>{const{topic:i,payload:n}=r,s=(await this.client.core.history.get(i,n.id)).request.method;switch(s){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n);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 ${s}`)}},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:l}=n;try{const d=this.client.core.eventClient.getEvent({topic:i});this.isValidConnect(xr({},n.params));const b=u.expiryTimestamp||kr(Hr.wc_sessionPropose.req.ttl),w=xr({id:l,pairingTopic:i,expiryTimestamp:b},u);await this.setProposal(l,w);const I=await this.getVerifyContext({attestationId:s,hash:$s(JSON.stringify(n)),encryptedId:a,metadata:w.proposer.metadata});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),d?.setError(Ts.proposal_listener_not_found)),d?.addTrace(hs.emit_session_proposal),this.client.events.emit("session_proposal",{id:l,params:w,verifyContext:I})}catch(d){await this.sendError({id:l,topic:i,error:d,rpcOpts:Hr.wc_sessionPropose.autoReject}),this.client.logger.error(d)}},this.onSessionProposeResponse=async(r,i)=>{const{id:n}=i;if(cs(i)){const{result:s}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:s});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const u=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:u});const l=s.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const d=await this.client.core.crypto.generateSharedKey(u,l);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:d});const b=await this.client.core.relayer.subscribe(d);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:b}),await this.client.core.pairing.activate({topic:r})}else if(Xi(i)){await this.client.proposal.delete(n,Gt("USER_DISCONNECTED"));const s=Dt("session_connect");if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} 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:l,namespaces:d,sessionProperties:b,sessionConfig:w}=i.params,I=xr(xr({topic:r,relay:a,expiry:l,namespaces:d,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}),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;cs(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(Dt("session_approve",n),{})):Xi(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=wu.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(xr({topic:r},n));try{wu.set(a,s),await this.client.session.update(r,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(l){throw wu.delete(a),l}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`);cs(i)?this.events.emit(Dt("session_update",n),{}):Xi(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,kr(cc)),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`);cs(i)?this.events.emit(Dt("session_extend",n),{}):Xi(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(()=>{cs(i)?this.events.emit(Dt("session_ping",n),{}):Xi(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}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(Ei.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)}},this.onSessionRequest=async r=>{var i;const{topic:n,payload:s,attestation:a,encryptedId:u}=r,{id:l,params:d}=s;try{await this.isValidRequest(xr({topic:n},d));const b=this.client.session.get(n),w=await this.getVerifyContext({attestationId:a,hash:$s(JSON.stringify(sc("wc_sessionRequest",d,l))),encryptedId:u,metadata:b.peer.metadata}),I={id:l,topic:n,params:d,verifyContext:w};await this.setPendingSessionRequest(I),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(I):(this.addSessionRequestToSessionRequestQueue(I),this.processSessionRequestQueue())}catch(b){await this.sendError({id:l,topic:n,error:b}),this.client.logger.error(b)}},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`);cs(i)?this.events.emit(Dt("session_request",n),{result:i.result}):Xi(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=wu.get(a);if(u&&this.isRequestOutOfSync(u,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(xr({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),wu.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}),cs(i)?this.events.emit(Dt("session_request",n),{result:i.result}):Xi(i)&&this.events.emit(Dt("session_request",n),{error:i.error})},this.onSessionAuthenticateRequest=async r=>{const{topic:i,payload:n,attestation:s,encryptedId:a}=r;try{const{requester:u,authPayload:l,expiryTimestamp:d}=n.params,b=await this.getVerifyContext({attestationId:s,hash:$s(JSON.stringify(n)),encryptedId:a,metadata:u.metadata}),w={requester:u,pairingTopic:i,id:n.id,authPayload:l,verifyContext:b,expiryTimestamp:d};await this.setAuthRequest(n.id,{request:w,pairingTopic:i}),this.client.events.emit("session_authenticate",{topic:i,params:n.params,id:n.id,verifyContext:b})}catch(u){this.client.logger.error(u);const l=n.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),b={type:Ps,receiverPublicKey:l,senderPublicKey:d};await this.sendError({id:n.id,topic:i,error:u,encodeOpts:b,rpcOpts:Hr.wc_sessionAuthenticate.autoReject})}},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=ls.idle,this.processSessionRequestQueue()},Ie.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===ls.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=ls.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:sc("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})},this.isValidConnect=async r=>{if(!yi(r)){const{message:l}=Ee("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(l)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:a,relays:u}=r;if(ai(i)||await this.isValidPairingTopic(i),!TI(u,!0)){const{message:l}=Ee("MISSING_OR_INVALID",`connect() relays: ${u}`);throw new Error(l)}!ai(n)&&yu(n)!==0&&this.validateNamespaces(n,"requiredNamespaces"),!ai(s)&&yu(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),ai(a)||this.validateSessionProps(a,"sessionProperties")},this.validateNamespaces=(r,i)=>{const n=NI(r,"connect()",i);if(n)throw new Error(n.message)},this.isValidApprove=async r=>{if(!yi(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),l=$d(n,"approve()");if(l)throw new Error(l.message);const d=pb(u.requiredNamespaces,n,"approve()");if(d)throw new Error(d.message);if(!mr(s,!0)){const{message:b}=Ee("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(b)}ai(a)||this.validateSessionProps(a,"sessionProperties")},this.isValidReject=async r=>{if(!yi(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),!BI(n)){const{message:s}=Ee("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!yi(r)){const{message:d}=Ee("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(d)}const{relay:i,controller:n,namespaces:s,expiry:a}=r;if(!lb(i)){const{message:d}=Ee("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(d)}const u=CI(n,"onSessionSettleRequest()");if(u)throw new Error(u.message);const l=$d(s,"onSessionSettleRequest()");if(l)throw new Error(l.message);if(eo(a)){const{message:d}=Ee("EXPIRED","onSessionSettleRequest()");throw new Error(d)}},this.isValidUpdate=async r=>{if(!yi(r)){const{message:l}=Ee("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(l)}const{topic:i,namespaces:n}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),a=$d(n,"update()");if(a)throw new Error(a.message);const u=pb(s.requiredNamespaces,n,"update()");if(u)throw new Error(u.message)},this.isValidExtend=async r=>{if(!yi(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(!yi(r)){const{message:l}=Ee("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(l)}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(!db(u,s)){const{message:l}=Ee("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(l)}if(!FI(n)){const{message:l}=Ee("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(l)}if(!jI(u,s,n.method)){const{message:l}=Ee("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(l)}if(a&&!KI(a,r1)){const{message:l}=Ee("MISSING_OR_INVALID",`request() expiry: ${a}. Expiry must be a number (in seconds) between ${r1.min} and ${r1.max}`);throw new Error(l)}},this.isValidRespond=async r=>{var i;if(!yi(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(!UI(s)){const{message:a}=Ee("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}},this.isValidPing=async r=>{if(!yi(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(!yi(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(!db(a,s)){const{message:u}=Ee("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(u)}if(!kI(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(!yi(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(!mr(n,!1))throw new Error("uri is required parameter");if(!mr(s,!1))throw new Error("domain is required parameter");if(!mr(a,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(l=>ru(l).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:u}=ru(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}=r,u={verified:{verifyUrl:a.verifyUrl||Du,validation:"UNKNOWN",origin:a.url||""}};try{const l=await this.client.core.verify.resolve({attestationId:i,hash:n,encryptedId:s,verifyUrl:a.verifyUrl});l&&(u.verified.origin=l.origin,u.verified.isScam=l.isScam,u.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(u)}`),u},this.validateSessionProps=(r,i)=>{Object.values(r).forEach(n=>{if(!mr(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)}}}async isInitialized(){if(!this.initialized){const{message:e}=Ee("NOT_INITIALIZED",this.name);throw new Error(e)}await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ei.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}=e,{publicKey:s}=this.client.auth.authKeys.keys.includes(Ch)?this.client.auth.authKeys.get(Ch):{responseTopic:void 0,publicKey:void 0},a=await this.client.core.crypto.decode(r,i,{receiverPublicKey:s});try{Wd(a)?(this.client.core.history.set(r,a),this.onRelayEventRequest({topic:r,payload:a,attestation:n,encryptedId:$s(i)})):Sh(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a}),this.client.core.history.delete(r,a.id)):this.onRelayEventUnknownPayload({topic:r,payload:a})}catch(u){this.client.logger.error(u)}}registerExpirerEvents(){this.client.core.expirer.on(tn.expired,async e=>{const{topic:r,id:i}=jv(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(oc.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(oc.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!mr(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(eo(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=Ee("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!mr(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(eo(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(mr(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(!LI(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(eo(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=Ee("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class y$ extends Vo{constructor(e,r){super(e,r,i$,e1),this.core=e,this.logger=r}}class w$ extends Vo{constructor(e,r){super(e,r,n$,e1),this.core=e,this.logger=r}}class _$ extends Vo{constructor(e,r){super(e,r,o$,e1,i=>i.id),this.core=e,this.logger=r}}class E$ extends Vo{constructor(e,r){super(e,r,f$,Mh,()=>Ch),this.core=e,this.logger=r}}class A$ extends Vo{constructor(e,r){super(e,r,h$,Mh),this.core=e,this.logger=r}}class x$ extends Vo{constructor(e,r){super(e,r,l$,Mh,i=>i.id),this.core=e,this.logger=r}}class S${constructor(e,r){this.core=e,this.logger=r,this.authKeys=new E$(this.core,this.logger),this.pairingTopics=new A$(this.core,this.logger),this.requests=new x$(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}class i1 extends pC{constructor(e){super(e),this.protocol=P3,this.version=$3,this.name=t1.name,this.events=new Br.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=>{try{return await this.engine.authenticate(i)}catch(n){throw this.logger.error(n.message),n}},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||t1.name,this.metadata=e?.metadata||UE(),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:os(Eh({level:e?.logger||t1.logger}));this.core=e?.core||new r$(e),this.logger=ci(r,this.name),this.session=new w$(this.core,this.logger),this.proposal=new y$(this.core,this.logger),this.pendingRequest=new _$(this.core,this.logger),this.engine=new b$(this),this.auth=new S$(this.core,this.logger)}static async init(e){const r=new i1(e);return await r.initialize(),r}get context(){return _i(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.engine.init(),await this.auth.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 n1={exports:{}};(function(t,e){var r=typeof self<"u"?self:Wr,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 l(h){return h&&DataView.prototype.isPrototypeOf(h)}if(u.arrayBuffer)var d=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],b=ArrayBuffer.isView||function(h){return h&&d.indexOf(Object.prototype.toString.call(h))>-1};function w(h){if(typeof h!="string"&&(h=String(h)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(h))throw new TypeError("Invalid character in header field name");return h.toLowerCase()}function I(h){return typeof h!="string"&&(h=String(h)),h}function S(h){var v={next:function(){var E=h.shift();return{done:E===void 0,value:E}}};return u.iterable&&(v[Symbol.iterator]=function(){return v}),v}function D(h){this.map={},h instanceof D?h.forEach(function(v,E){this.append(E,v)},this):Array.isArray(h)?h.forEach(function(v){this.append(v[0],v[1])},this):h&&Object.getOwnPropertyNames(h).forEach(function(v){this.append(v,h[v])},this)}D.prototype.append=function(h,v){h=w(h),v=I(v);var E=this.map[h];this.map[h]=E?E+", "+v:v},D.prototype.delete=function(h){delete this.map[w(h)]},D.prototype.get=function(h){return h=w(h),this.has(h)?this.map[h]:null},D.prototype.has=function(h){return this.map.hasOwnProperty(w(h))},D.prototype.set=function(h,v){this.map[w(h)]=I(v)},D.prototype.forEach=function(h,v){for(var E in this.map)this.map.hasOwnProperty(E)&&h.call(v,this.map[E],E,this)},D.prototype.keys=function(){var h=[];return this.forEach(function(v,E){h.push(E)}),S(h)},D.prototype.values=function(){var h=[];return this.forEach(function(v){h.push(v)}),S(h)},D.prototype.entries=function(){var h=[];return this.forEach(function(v,E){h.push([E,v])}),S(h)},u.iterable&&(D.prototype[Symbol.iterator]=D.prototype.entries);function L(h){if(h.bodyUsed)return Promise.reject(new TypeError("Already read"));h.bodyUsed=!0}function K(h){return new Promise(function(v,E){h.onload=function(){v(h.result)},h.onerror=function(){E(h.error)}})}function H(h){var v=new FileReader,E=K(v);return v.readAsArrayBuffer(h),E}function U(h){var v=new FileReader,E=K(v);return v.readAsText(h),E}function W(h){for(var v=new Uint8Array(h),E=new Array(v.length),C=0;C<v.length;C++)E[C]=String.fromCharCode(v[C]);return E.join("")}function R(h){if(h.slice)return h.slice(0);var v=new Uint8Array(h.byteLength);return v.set(new Uint8Array(h)),v.buffer}function k(){return this.bodyUsed=!1,this._initBody=function(h){this._bodyInit=h,h?typeof h=="string"?this._bodyText=h:u.blob&&Blob.prototype.isPrototypeOf(h)?this._bodyBlob=h:u.formData&&FormData.prototype.isPrototypeOf(h)?this._bodyFormData=h:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(h)?this._bodyText=h.toString():u.arrayBuffer&&u.blob&&l(h)?(this._bodyArrayBuffer=R(h.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(h)||b(h))?this._bodyArrayBuffer=R(h):this._bodyText=h=Object.prototype.toString.call(h):this._bodyText="",this.headers.get("content-type")||(typeof h=="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(h)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var h=L(this);if(h)return h;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?L(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(H)}),this.text=function(){var h=L(this);if(h)return h;if(this._bodyBlob)return U(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(X)}),this.json=function(){return this.text().then(JSON.parse)},this}var z=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function _(h){var v=h.toUpperCase();return z.indexOf(v)>-1?v:h}function B(h,v){v=v||{};var E=v.body;if(h instanceof B){if(h.bodyUsed)throw new TypeError("Already read");this.url=h.url,this.credentials=h.credentials,v.headers||(this.headers=new D(h.headers)),this.method=h.method,this.mode=h.mode,this.signal=h.signal,!E&&h._bodyInit!=null&&(E=h._bodyInit,h.bodyUsed=!0)}else this.url=String(h);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 X(h){var v=new FormData;return h.trim().split("&").forEach(function(E){if(E){var C=E.split("="),P=C.shift().replace(/\+/g," "),M=C.join("=").replace(/\+/g," ");v.append(decodeURIComponent(P),decodeURIComponent(M))}}),v}function re(h){var v=new D,E=h.replace(/\r?\n[\t ]+/g," ");return E.split(/\r?\n/).forEach(function(C){var P=C.split(":"),M=P.shift().trim();if(M){var g=P.join(":").trim();v.append(M,g)}}),v}k.call(B.prototype);function T(h,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(h)}k.call(T.prototype),T.prototype.clone=function(){return new T(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new D(this.headers),url:this.url})},T.error=function(){var h=new T(null,{status:0,statusText:""});return h.type="error",h};var y=[301,302,303,307,308];T.redirect=function(h,v){if(y.indexOf(v)===-1)throw new RangeError("Invalid status code");return new T(null,{status:v,headers:{location:h}})},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(h,v){return new Promise(function(E,C){var P=new B(h,v);if(P.signal&&P.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:re(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 T(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(P.method,P.url,!0),P.credentials==="include"?M.withCredentials=!0:P.credentials==="omit"&&(M.withCredentials=!1),"responseType"in M&&u.blob&&(M.responseType="blob"),P.headers.forEach(function(m,N){M.setRequestHeader(N,m)}),P.signal&&(P.signal.addEventListener("abort",g),M.onreadystatechange=function(){M.readyState===4&&P.signal.removeEventListener("abort",g)}),M.send(typeof P._bodyInit>"u"?null:P._bodyInit)})}return f.polyfill=!0,s.fetch||(s.fetch=f,s.Headers=D,s.Request=B,s.Response=T),a.Headers=D,a.Request=B,a.Response=T,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})(n1,n1.exports);var F3=Rw(n1.exports),I$=Object.defineProperty,M$=Object.defineProperties,C$=Object.getOwnPropertyDescriptors,U3=Object.getOwnPropertySymbols,D$=Object.prototype.hasOwnProperty,O$=Object.prototype.propertyIsEnumerable,k3=(t,e,r)=>e in t?I$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,j3=(t,e)=>{for(var r in e||(e={}))D$.call(e,r)&&k3(t,r,e[r]);if(U3)for(var r of U3(e))O$.call(e,r)&&k3(t,r,e[r]);return t},q3=(t,e)=>M$(t,C$(e));const P$={Accept:"application/json","Content-Type":"application/json"},$$="POST",z3={headers:P$,method:$$},H3=10;class ds{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new Br.exports.EventEmitter,this.isAvailable=!1,this.registering=!1,!qb(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=Is(e),i=await(await F3(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(!qb(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=Is({id:1,jsonrpc:"2.0",method:"test",params:[]});await F3(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"?qa(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=xh(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return Lb(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>H3&&this.events.setMaxListeners(H3)}}const K3="error",R$="wss://relay.walletconnect.com",N$="wc",T$="universal_provider",W3=`${N$}@2:${T$}:`,L$="https://rpc.walletconnect.com/v1/",uc="generic",In={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var Ru=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},s1={exports:{}};/**
44
44
  * @license
45
45
  * Lodash <https://lodash.com/>
46
46
  * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>