2025-06-21 23:30:33 +03:00

3 lines
66 KiB
JavaScript

"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var z=require("events"),It=require("@walletconnect/keyvaluestorage"),B=require("@walletconnect/heartbeat"),l=require("@walletconnect/logger"),P=require("@walletconnect/types"),oe=require("@walletconnect/safe-json"),Rt=require("@walletconnect/relay-auth"),a=require("@walletconnect/utils"),_t=require("uint8arrays"),u=require("@walletconnect/time"),Ct=require("@walletconnect/jsonrpc-provider"),m=require("@walletconnect/jsonrpc-utils"),Tt=require("@walletconnect/jsonrpc-ws-connection"),St=require("lodash.isequal"),Ot=require("isomorphic-unfetch");function V(r){return r&&typeof r=="object"&&"default"in r?r:{default:r}}function Pt(r){if(r&&r.__esModule)return r;var e=Object.create(null);return r&&Object.keys(r).forEach(function(t){if(t!=="default"){var i=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:function(){return r[t]}})}}),e.default=r,Object.freeze(e)}var At=V(z),xt=V(It),j=Pt(Rt),Nt=V(Tt),Lt=V(St),Ut=V(Ot);function zt(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var s=0;s<r.length;s++){var n=r.charAt(s),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=s}var h=r.length,c=r.charAt(0),d=Math.log(h)/Math.log(256),p=Math.log(256)/Math.log(h);function y(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var b=0,U=0,R=0,T=g.length;R!==T&&g[R]===0;)R++,b++;for(var S=(T-R)*p+1>>>0,w=new Uint8Array(S);R!==T;){for(var O=g[R],L=0,_=S-1;(O!==0||L<U)&&_!==-1;_--,L++)O+=256*w[_]>>>0,w[_]=O%h>>>0,O=O/h>>>0;if(O!==0)throw new Error("Non-zero carry");U=L,R++}for(var x=S-U;x!==S&&w[x]===0;)x++;for(var Y=c.repeat(b);x<S;++x)Y+=r.charAt(w[x]);return Y}function f(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var b=0;if(g[b]!==" "){for(var U=0,R=0;g[b]===c;)U++,b++;for(var T=(g.length-b)*d+1>>>0,S=new Uint8Array(T);g[b];){var w=t[g.charCodeAt(b)];if(w===255)return;for(var O=0,L=T-1;(w!==0||O<R)&&L!==-1;L--,O++)w+=h*S[L]>>>0,S[L]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");R=O,b++}if(g[b]!==" "){for(var _=T-R;_!==T&&S[_]===0;)_++;for(var x=new Uint8Array(U+(T-_)),Y=U;_!==T;)x[Y++]=S[_++];return x}}}function M(g){var b=f(g);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:y,decodeUnsafe:f,decode:M}}var Ft=zt,$t=Ft;const ae=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},Mt=r=>new TextEncoder().encode(r),Bt=r=>new TextDecoder().decode(r);class Vt{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class kt{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return he(this,e)}}class Kt{constructor(e){this.decoders=e}or(e){return he(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const he=(r,e)=>new Kt({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});class qt{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new Vt(e,t,i),this.decoder=new kt(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const G=({name:r,prefix:e,encode:t,decode:i})=>new qt(r,e,t,i),k=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:s}=$t(t,e);return G({prefix:r,name:e,encode:i,decode:n=>ae(s(n))})},Yt=(r,e,t,i)=>{const s={};for(let p=0;p<e.length;++p)s[e[p]]=p;let n=r.length;for(;r[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let h=0,c=0,d=0;for(let p=0;p<n;++p){const y=s[r[p]];if(y===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<t|y,h+=t,h>=8&&(h-=8,o[d++]=255&c>>h)}if(h>=t||255&c<<8-h)throw new SyntaxError("Unexpected end of data");return o},jt=(r,e,t)=>{const i=e[e.length-1]==="=",s=(1<<t)-1;let n="",o=0,h=0;for(let c=0;c<r.length;++c)for(h=h<<8|r[c],o+=8;o>t;)o-=t,n+=e[s&h>>o];if(o&&(n+=e[s&h<<t-o]),i)for(;n.length*t&7;)n+="=";return n},D=({name:r,prefix:e,bitsPerChar:t,alphabet:i})=>G({prefix:e,name:r,encode(s){return jt(s,i,t)},decode(s){return Yt(s,i,t,r)}}),Gt=G({prefix:"\0",name:"identity",encode:r=>Bt(r),decode:r=>Mt(r)});var Ht=Object.freeze({__proto__:null,identity:Gt});const Xt=D({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Jt=Object.freeze({__proto__:null,base2:Xt});const Wt=D({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Qt=Object.freeze({__proto__:null,base8:Wt});const Zt=k({prefix:"9",name:"base10",alphabet:"0123456789"});var ei=Object.freeze({__proto__:null,base10:Zt});const ti=D({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ii=D({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var si=Object.freeze({__proto__:null,base16:ti,base16upper:ii});const ri=D({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ni=D({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),oi=D({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ai=D({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),hi=D({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ci=D({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),li=D({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ui=D({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),gi=D({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var di=Object.freeze({__proto__:null,base32:ri,base32upper:ni,base32pad:oi,base32padupper:ai,base32hex:hi,base32hexupper:ci,base32hexpad:li,base32hexpadupper:ui,base32z:gi});const pi=k({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Di=k({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var yi=Object.freeze({__proto__:null,base36:pi,base36upper:Di});const Ei=k({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),fi=k({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var bi=Object.freeze({__proto__:null,base58btc:Ei,base58flickr:fi});const mi=D({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),wi=D({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),vi=D({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ii=D({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ri=Object.freeze({__proto__:null,base64:mi,base64pad:wi,base64url:vi,base64urlpad:Ii});const ce=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}"),_i=ce.reduce((r,e,t)=>(r[t]=e,r),[]),Ci=ce.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Ti(r){return r.reduce((e,t)=>(e+=_i[t],e),"")}function Si(r){const e=[];for(const t of r){const i=Ci[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const Oi=G({prefix:"\u{1F680}",name:"base256emoji",encode:Ti,decode:Si});var Pi=Object.freeze({__proto__:null,base256emoji:Oi}),Ai=ue,le=128,xi=127,Ni=~xi,Li=Math.pow(2,31);function ue(r,e,t){e=e||[],t=t||0;for(var i=t;r>=Li;)e[t++]=r&255|le,r/=128;for(;r&Ni;)e[t++]=r&255|le,r>>>=7;return e[t]=r|0,ue.bytes=t-i+1,e}var Ui=Q,zi=128,ge=127;function Q(r,i){var t=0,i=i||0,s=0,n=i,o,h=r.length;do{if(n>=h)throw Q.bytes=0,new RangeError("Could not decode varint");o=r[n++],t+=s<28?(o&ge)<<s:(o&ge)*Math.pow(2,s),s+=7}while(o>=zi);return Q.bytes=n-i,t}var Fi=Math.pow(2,7),$i=Math.pow(2,14),Mi=Math.pow(2,21),Bi=Math.pow(2,28),Vi=Math.pow(2,35),ki=Math.pow(2,42),Ki=Math.pow(2,49),qi=Math.pow(2,56),Yi=Math.pow(2,63),ji=function(r){return r<Fi?1:r<$i?2:r<Mi?3:r<Bi?4:r<Vi?5:r<ki?6:r<Ki?7:r<qi?8:r<Yi?9:10},Gi={encode:Ai,decode:Ui,encodingLength:ji},de=Gi;const pe=(r,e,t=0)=>(de.encode(r,e,t),e),De=r=>de.encodingLength(r),Z=(r,e)=>{const t=e.byteLength,i=De(r),s=i+De(t),n=new Uint8Array(s+t);return pe(r,n,0),pe(t,n,i),n.set(e,s),new Hi(r,t,e,n)};class Hi{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}}const ye=({name:r,code:e,encode:t})=>new Xi(r,e,t);class Xi{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Z(this.code,t):t.then(i=>Z(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Ee=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),Ji=ye({name:"sha2-256",code:18,encode:Ee("SHA-256")}),Wi=ye({name:"sha2-512",code:19,encode:Ee("SHA-512")});var Qi=Object.freeze({__proto__:null,sha256:Ji,sha512:Wi});const fe=0,Zi="identity",be=ae,es=r=>Z(fe,be(r)),ts={code:fe,name:Zi,encode:be,digest:es};var is=Object.freeze({__proto__:null,identity:ts});new TextEncoder,new TextDecoder;const me={...Ht,...Jt,...Qt,...ei,...si,...di,...yi,...bi,...Ri,...Pi};({...Qi,...is});function we(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function ss(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?we(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function ve(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const Ie=ve("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ee=ve("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);const e=ss(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),rs={utf8:Ie,"utf-8":Ie,hex:me.base16,latin1:ee,ascii:ee,binary:ee,...me};function ns(r,e="utf8"){const t=rs[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?we(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}const te="wc",Re=2,H="core",N=`${te}@2:${H}:`,_e={name:H,logger:"error"},Ce={database:":memory:"},Te="crypto",ie="client_ed25519_seed",Se=u.ONE_DAY,Oe="keychain",Pe="0.3",Ae="messages",xe="0.3",Ne=u.SIX_HOURS,Le="publisher",Ue="irn",ze="error",se="wss://relay.walletconnect.com",re="wss://relay.walletconnect.org",Fe="relayer",E={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"},$e="_subscription",A={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Me=u.ONE_SECOND,os={database:":memory:"},Be="2.11.2",Ve=1e4,ke="0.3",Ke="WALLETCONNECT_CLIENT_ID",v={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},as=u.THIRTY_DAYS,qe="subscription",Ye="0.3",je=u.FIVE_SECONDS*1e3,Ge="pairing",He="0.3",hs=u.THIRTY_DAYS,F={wc_pairingDelete:{req:{ttl:u.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:u.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:u.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:u.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:u.ONE_DAY,prompt:!1,tag:0},res:{ttl:u.ONE_DAY,prompt:!1,tag:0}}},K={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},C={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Xe="history",Je="0.3",We="expirer",I={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},Qe="0.3",cs=u.ONE_DAY,X="verify-api",$="https://verify.walletconnect.com",J="https://verify.walletconnect.org",Ze=[$,J],et="echo",tt="https://echo.walletconnect.com";class it{constructor(e,t){this.core=e,this.logger=t,this.keychain=new Map,this.name=Oe,this.version=Pe,this.initialized=!1,this.storagePrefix=N,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,s)=>{this.isInitialized(),this.keychain.set(i,s),await this.persist()},this.get=i=>{this.isInitialized();const s=this.keychain.get(i);if(typeof s>"u"){const{message:n}=a.getInternalError("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return s},this.del=async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()},this.core=e,this.logger=l.generateChildLogger(t,this.name)}get context(){return l.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,a.mapToObj(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?a.objToMap(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=a.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}}class st{constructor(e,t,i){this.core=e,this.logger=t,this.name=Te,this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=s=>(this.isInitialized(),this.keychain.has(s)),this.getClientId=async()=>{this.isInitialized();const s=await this.getClientSeed(),n=j.generateKeyPair(s);return j.encodeIss(n.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const s=a.generateKeyPair();return this.setPrivateKey(s.publicKey,s.privateKey)},this.signJWT=async s=>{this.isInitialized();const n=await this.getClientSeed(),o=j.generateKeyPair(n),h=a.generateRandomBytes32(),c=Se;return await j.signJWT(h,s,c,o)},this.generateSharedKey=(s,n,o)=>{this.isInitialized();const h=this.getPrivateKey(s),c=a.deriveSymKey(h,n);return this.setSymKey(c,o)},this.setSymKey=async(s,n)=>{this.isInitialized();const o=n||a.hashKey(s);return await this.keychain.set(o,s),o},this.deleteKeyPair=async s=>{this.isInitialized(),await this.keychain.del(s)},this.deleteSymKey=async s=>{this.isInitialized(),await this.keychain.del(s)},this.encode=async(s,n,o)=>{this.isInitialized();const h=a.validateEncoding(o),c=oe.safeJsonStringify(n);if(a.isTypeOneEnvelope(h)){const f=h.senderPublicKey,M=h.receiverPublicKey;s=await this.generateSharedKey(f,M)}const d=this.getSymKey(s),{type:p,senderPublicKey:y}=h;return a.encrypt({type:p,symKey:d,message:c,senderPublicKey:y})},this.decode=async(s,n,o)=>{this.isInitialized();const h=a.validateDecoding(n,o);if(a.isTypeOneEnvelope(h)){const c=h.receiverPublicKey,d=h.senderPublicKey;s=await this.generateSharedKey(c,d)}try{const c=this.getSymKey(s),d=a.decrypt({symKey:c,encoded:n});return oe.safeJsonParse(d)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}},this.getPayloadType=s=>{const n=a.deserialize(s);return a.decodeTypeByte(n.type)},this.getPayloadSenderPublicKey=s=>{const n=a.deserialize(s);return n.senderPublicKey?_t.toString(n.senderPublicKey,a.BASE16):void 0},this.core=e,this.logger=l.generateChildLogger(t,this.name),this.keychain=i||new it(this.core,this.logger)}get context(){return l.getLoggerContext(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(ie)}catch{e=a.generateRandomBytes32(),await this.keychain.set(ie,e)}return ns(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=a.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}}class rt extends P.IMessageTracker{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.name=Ae,this.version=xe,this.initialized=!1,this.storagePrefix=N,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,s)=>{this.isInitialized();const n=a.hashMessage(s);let o=this.messages.get(i);return typeof o>"u"&&(o={}),typeof o[n]<"u"||(o[n]=s,this.messages.set(i,o),await this.persist()),n},this.get=i=>{this.isInitialized();let s=this.messages.get(i);return typeof s>"u"&&(s={}),s},this.has=(i,s)=>{this.isInitialized();const n=this.get(i),o=a.hashMessage(s);return typeof n[o]<"u"},this.del=async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()},this.logger=l.generateChildLogger(e,this.name),this.core=t}get context(){return l.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,a.mapToObj(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?a.objToMap(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=a.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}}class ls extends P.IPublisher{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new z.EventEmitter,this.name=Le,this.queue=new Map,this.publishTimeout=u.toMiliseconds(u.TEN_SECONDS*2),this.needsTransportRestart=!1,this.publish=async(i,s,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:s,opts:n}});try{const h=n?.ttl||Ne,c=a.getRelayProtocolName(n),d=n?.prompt||!1,p=n?.tag||0,y=n?.id||m.getBigIntRpcId().toString(),f={topic:i,message:s,opts:{ttl:h,relay:c,prompt:d,tag:p,id:y}},M=setTimeout(()=>this.queue.set(y,f),this.publishTimeout);try{await await a.createExpiringPromise(this.rpcPublish(i,s,h,c,d,p,y),this.publishTimeout,`Failed to publish payload, please try again. id:${y} tag:${p}`),this.removeRequestFromQueue(y),this.relayer.events.emit(E.publish,f)}catch(g){if(this.logger.debug("Publishing Payload stalled"),this.needsTransportRestart=!0,(o=n?.internal)!=null&&o.throwOnFailedPublish)throw this.removeRequestFromQueue(y),g;return}finally{clearTimeout(M)}this.logger.debug("Successfully Published Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:s,opts:n}})}catch(h){throw this.logger.debug("Failed to Publish Payload"),this.logger.error(h),h}},this.on=(i,s)=>{this.events.on(i,s)},this.once=(i,s)=>{this.events.once(i,s)},this.off=(i,s)=>{this.events.off(i,s)},this.removeListener=(i,s)=>{this.events.removeListener(i,s)},this.relayer=e,this.logger=l.generateChildLogger(t,this.name),this.registerEventListeners()}get context(){return l.getLoggerContext(this.logger)}rpcPublish(e,t,i,s,n,o,h){var c,d,p,y;const f={method:a.getRelayProtocolApi(s.protocol).publish,params:{topic:e,message:t,ttl:i,prompt:n,tag:o},id:h};return a.isUndefined((c=f.params)==null?void 0:c.prompt)&&((d=f.params)==null||delete d.prompt),a.isUndefined((p=f.params)==null?void 0:p.tag)&&((y=f.params)==null||delete y.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:f}),this.relayer.request(f)}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async e=>{const{topic:t,message:i,opts:s}=e;await this.publish(t,i,s)})}registerEventListeners(){this.relayer.core.heartbeat.on(B.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(E.connection_stalled);return}this.checkQueue()}),this.relayer.on(E.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class us{constructor(){this.map=new Map,this.set=(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])},this.get=e=>this.map.get(e)||[],this.exists=(e,t)=>this.get(e).includes(t),this.delete=(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const s=i.filter(n=>n!==t);if(!s.length){this.map.delete(e);return}this.map.set(e,s)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var gs=Object.defineProperty,ds=Object.defineProperties,ps=Object.getOwnPropertyDescriptors,nt=Object.getOwnPropertySymbols,Ds=Object.prototype.hasOwnProperty,ys=Object.prototype.propertyIsEnumerable,ot=(r,e,t)=>e in r?gs(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,q=(r,e)=>{for(var t in e||(e={}))Ds.call(e,t)&&ot(r,t,e[t]);if(nt)for(var t of nt(e))ys.call(e,t)&&ot(r,t,e[t]);return r},ne=(r,e)=>ds(r,ps(e));class at extends P.ISubscriber{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new us,this.events=new z.EventEmitter,this.name=qe,this.version=Ye,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=N,this.subscribeTimeout=1e4,this.restartInProgress=!1,this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId())},this.subscribe=async(i,s)=>{await this.restartToComplete(),this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}});try{const n=a.getRelayProtocolName(s),o={topic:i,relay:n};this.pending.set(i,o);const h=await this.rpcSubscribe(i,n);return this.onSubscribe(h,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}}),h}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}},this.unsubscribe=async(i,s)=>{await this.restartToComplete(),this.isInitialized(),typeof s?.id<"u"?await this.unsubscribeById(i,s.id,s):await this.unsubscribeByTopic(i,s)},this.isSubscribed=async i=>{if(this.topics.includes(i))return!0;const s=`${this.pendingSubscriptionWatchLabel}_${i}`;return await new Promise((n,o)=>{const h=new u.Watch;h.start(s);const c=setInterval(()=>{!this.pending.has(i)&&this.topics.includes(i)&&(clearInterval(c),h.stop(s),n(!0)),h.elapsed(s)>=je&&(clearInterval(c),h.stop(s),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(i,s)=>{this.events.on(i,s)},this.once=(i,s)=>{this.events.once(i,s)},this.off=(i,s)=>{this.events.off(i,s)},this.removeListener=(i,s)=>{this.events.removeListener(i,s)},this.restart=async()=>{this.restartInProgress=!0,await this.restore(),await this.reset(),this.restartInProgress=!1},this.relayer=e,this.logger=l.generateChildLogger(t,this.name),this.clientId=""}get context(){return l.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}hasSubscription(e,t){let i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}onEnable(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map(async s=>await this.unsubscribeById(e,s,t)))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const s=a.getRelayProtocolName(i);await this.rpcUnsubscribe(e,t,s);const n=a.getSdkError("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,t){const i={method:a.getRelayProtocolApi(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await a.createExpiringPromise(this.relayer.request(i),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(E.connection_stalled)}return a.hashMessage(e+this.clientId)}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:a.getRelayProtocolApi(t.protocol).batchSubscribe,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{return await await a.createExpiringPromise(this.relayer.request(i),this.subscribeTimeout)}catch{this.logger.debug("Outgoing Relay Payload stalled"),this.relayer.events.emit(E.connection_stalled)}}rpcUnsubscribe(e,t,i){const s={method:a.getRelayProtocolApi(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,t){this.setSubscription(e,ne(q({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,q({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.subscriptions.has(e)||(this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t))}addSubscription(e,t){this.subscriptions.set(e,q({},t)),this.topicMap.set(t.topic,e),this.events.emit(v.created,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:i}=a.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(v.deleted,ne(q({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(v.sync)}async reset(){if(this.cached.length){const e=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let t=0;t<e;t++){const i=this.cached.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(v.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=a.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(!e.length)return;const t=await this.rpcBatchSubscribe(e);a.isValidArray(t)&&this.onBatchSubscribe(t.map((i,s)=>ne(q({},e[s]),{id:i})))}async onConnect(){this.restartInProgress||(await this.restart(),this.onEnable())}onDisconnect(){this.onDisable()}async checkPending(){if(!this.initialized||this.relayer.transportExplicitlyClosed)return;const e=[];this.pending.forEach(t=>{e.push(t)}),await this.batchSubscribe(e)}registerEventListeners(){this.relayer.core.heartbeat.on(B.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.relayer.on(E.connect,async()=>{await this.onConnect()}),this.relayer.on(E.disconnect,()=>{this.onDisconnect()}),this.events.on(v.created,async e=>{const t=v.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}),this.events.on(v.deleted,async e=>{const t=v.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=a.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){this.restartInProgress&&await new Promise(e=>{const t=setInterval(()=>{this.restartInProgress||(clearInterval(t),e())},this.pollingInterval)})}}var Es=Object.defineProperty,ht=Object.getOwnPropertySymbols,fs=Object.prototype.hasOwnProperty,bs=Object.prototype.propertyIsEnumerable,ct=(r,e,t)=>e in r?Es(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ms=(r,e)=>{for(var t in e||(e={}))fs.call(e,t)&&ct(r,t,e[t]);if(ht)for(var t of ht(e))bs.call(e,t)&&ct(r,t,e[t]);return r};class lt extends P.IRelayer{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new z.EventEmitter,this.name=Fe,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.connectionStatusPollingInterval=20,this.staleConnectionErrors=["socket hang up","socket stalled"],this.hasExperiencedNetworkDisruption=!1,this.requestsInFlight=new Map,this.request=async t=>{this.logger.debug("Publishing Request Payload");const i=t.id;try{await this.toEstablishConnection();const s=this.provider.request(t);return this.requestsInFlight.set(i,{promise:s,request:t}),await s}catch(s){throw this.logger.debug("Failed to Publish Request"),this.logger.error(s),s}finally{this.requestsInFlight.delete(i)}},this.onPayloadHandler=t=>{this.onProviderPayload(t)},this.onConnectHandler=()=>{this.events.emit(E.connect)},this.onDisconnectHandler=()=>{this.onProviderDisconnect()},this.onProviderErrorHandler=t=>{this.logger.error(t),this.events.emit(E.error,t),this.logger.info("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(A.payload,this.onPayloadHandler),this.provider.on(A.connect,this.onConnectHandler),this.provider.on(A.disconnect,this.onDisconnectHandler),this.provider.on(A.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?l.generateChildLogger(e.logger,this.name):l.pino(l.getDefaultLoggerOptions({level:e.logger||ze})),this.messages=new rt(this.logger,e.core),this.subscriber=new at(this,this.logger),this.publisher=new ls(this,this.logger),this.relayUrl=e?.relayUrl||se,this.projectId=e.projectId,this.bundleId=a.getBundleId(),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await this.createProvider(),await Promise.all([this.messages.init(),this.subscriber.init()]);try{await this.transportOpen()}catch{this.logger.warn(`Connection via ${this.relayUrl} failed, attempting to connect via failover domain ${re}...`),await this.restartTransport(re)}this.initialized=!0,setTimeout(async()=>{this.subscriber.topics.length===0&&(this.logger.info("No topics subscribed to after init, closing transport"),await this.transportClose(),this.transportExplicitlyClosed=!1)},Ve)}get context(){return l.getLoggerContext(this.logger)}get connected(){return this.provider.connection.connected}get connecting(){return this.provider.connection.connecting}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now()})}async subscribe(e,t){var i;this.isInitialized();let s=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"";if(s)return s;let n;const o=h=>{h.topic===e&&(this.subscriber.off(v.created,o),n())};return await Promise.all([new Promise(h=>{n=h,this.subscriber.on(v.created,o)}),new Promise(async h=>{s=await this.subscriber.subscribe(e,t),h()})]),s}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportClose(){this.requestsInFlight.size>0&&(this.logger.debug("Waiting for all in-flight requests to finish before closing transport..."),this.requestsInFlight.forEach(async e=>{await e.promise})),this.transportExplicitlyClosed=!0,this.hasExperiencedNetworkDisruption&&this.connected?await a.createExpiringPromise(this.provider.disconnect(),1e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.connected&&await this.provider.disconnect()}async transportOpen(e){if(this.transportExplicitlyClosed=!1,await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress){e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportClose(),await this.createProvider()),this.connectionAttemptInProgress=!0;try{await Promise.all([new Promise(t=>{if(!this.initialized)return t();this.subscriber.once(v.resubscribed,()=>{t()})}),new Promise(async(t,i)=>{try{await a.createExpiringPromise(this.provider.connect(),1e4,`Socket stalled when trying to connect to ${this.relayUrl}`)}catch(s){i(s);return}t()})])}catch(t){this.logger.error(t);const i=t;if(!this.isConnectionStalled(i.message))throw t;this.provider.events.emit(A.disconnect)}finally{this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1}}}async restartTransport(e){await this.confirmOnlineStateOrThrow(),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.transportClose(),await this.createProvider(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await a.isOnline())throw new Error("No internet connection detected. Please restart your network and try again.")}isConnectionStalled(e){return this.staleConnectionErrors.some(t=>e.includes(t))}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Ct.JsonRpcProvider(new Nt.default(a.formatRelayRpcUrl({sdkVersion:Be,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:t,message:i}=e;await this.messages.set(t,i)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||i.length===0)return this.logger.debug(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.debug(`Ignoring message for non-subscribed topic ${t}`),!0;const s=this.messages.has(t,i);return s&&this.logger.debug(`Ignoring duplicate message: ${i}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),m.isJsonRpcRequest(e)){if(!e.method.endsWith($e))return;const t=e.params,{topic:i,message:s,publishedAt:n}=t.data,o={topic:i,message:s,publishedAt:n};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(ms({type:"event",event:t.id},o)),this.events.emit(t.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else m.isJsonRpcResponse(e)&&this.events.emit(E.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(E.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=m.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(A.payload,this.onPayloadHandler),this.provider.off(A.connect,this.onConnectHandler),this.provider.off(A.disconnect,this.onDisconnectHandler),this.provider.off(A.error,this.onProviderErrorHandler)}async registerEventListeners(){this.events.on(E.connection_stalled,()=>{this.restartTransport().catch(t=>this.logger.error(t))});let e=await a.isOnline();a.subscribeToNetworkChange(async t=>{this.initialized&&e!==t&&(e=t,t?await this.restartTransport().catch(i=>this.logger.error(i)):(this.hasExperiencedNetworkDisruption=!0,await this.transportClose().catch(i=>this.logger.error(i))))})}onProviderDisconnect(){this.events.emit(E.disconnect),this.attemptToReconnect()}attemptToReconnect(){this.transportExplicitlyClosed||(this.logger.info("attemptToReconnect called. Connecting..."),setTimeout(async()=>{await this.restartTransport().catch(e=>this.logger.error(e))},u.toMiliseconds(Me)))}isInitialized(){if(!this.initialized){const{message:e}=a.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectionAttemptInProgress)return await new Promise(e=>{const t=setInterval(()=>{this.connected&&(clearInterval(t),e())},this.connectionStatusPollingInterval)});await this.restartTransport()}}}var ws=Object.defineProperty,ut=Object.getOwnPropertySymbols,vs=Object.prototype.hasOwnProperty,Is=Object.prototype.propertyIsEnumerable,gt=(r,e,t)=>e in r?ws(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,dt=(r,e)=>{for(var t in e||(e={}))vs.call(e,t)&&gt(r,t,e[t]);if(ut)for(var t of ut(e))Is.call(e,t)&&gt(r,t,e[t]);return r};class pt extends P.IStore{constructor(e,t,i,s=N,n=void 0){super(e,t,i,s),this.core=e,this.logger=t,this.name=i,this.map=new Map,this.version=ke,this.cached=[],this.initialized=!1,this.storagePrefix=N,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!a.isUndefined(o)?this.map.set(this.getKey(o),o):a.isProposalStruct(o)?this.map.set(o.id,o):a.isSessionStruct(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)},this.set=async(o,h)=>{this.isInitialized(),this.map.has(o)?await this.update(o,h):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:h}),this.map.set(o,h),await this.persist())},this.get=o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o)),this.getAll=o=>(this.isInitialized(),o?this.values.filter(h=>Object.keys(o).every(c=>Lt.default(h[c],o[c]))):this.values),this.update=async(o,h)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:h});const c=dt(dt({},this.getData(o)),h);this.map.set(o,c),await this.persist()},this.delete=async(o,h)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:h}),this.map.delete(o),await this.persist())},this.logger=l.generateChildLogger(t,this.name),this.storagePrefix=s,this.getKey=n}get context(){return l.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){const{message:i}=a.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:t}=a.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=a.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Dt{constructor(e,t){this.core=e,this.logger=t,this.name=Ge,this.version=He,this.events=new At.default,this.initialized=!1,this.storagePrefix=N,this.ignoredPayloadTypes=[a.TYPE_1],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]},this.create=async()=>{this.isInitialized();const i=a.generateRandomBytes32(),s=await this.core.crypto.setSymKey(i),n=a.calcExpiry(u.FIVE_MINUTES),o={protocol:Ue},h={topic:s,expiry:n,relay:o,active:!1},c=a.formatUri({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:o,expiryTimestamp:n});return await this.pairings.set(s,h),await this.core.relayer.subscribe(s),this.core.expirer.set(s,n),{topic:s,uri:c}},this.pair=async i=>{this.isInitialized(),this.isValidPair(i);const{topic:s,symKey:n,relay:o,expiryTimestamp:h}=a.parseUri(i.uri);let c;if(this.pairings.keys.includes(s)&&(c=this.pairings.get(s),c.active))throw new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);const d=h||a.calcExpiry(u.FIVE_MINUTES),p={topic:s,relay:o,expiry:d,active:!1};return await this.pairings.set(s,p),this.core.expirer.set(s,d),i.activatePairing&&await this.activate({topic:s}),this.events.emit(K.create,p),this.core.crypto.keychain.has(s)||(await this.core.crypto.setSymKey(n,s),await this.core.relayer.subscribe(s,{relay:o})),p},this.activate=async({topic:i})=>{this.isInitialized();const s=a.calcExpiry(u.THIRTY_DAYS);await this.pairings.update(i,{active:!0,expiry:s}),this.core.expirer.set(i,s)},this.ping=async i=>{this.isInitialized(),await this.isValidPing(i);const{topic:s}=i;if(this.pairings.keys.includes(s)){const n=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:h,reject:c}=a.createDelayedPromise();this.events.once(a.engineEvent("pairing_ping",n),({error:d})=>{d?c(d):h()}),await o()}},this.updateExpiry=async({topic:i,expiry:s})=>{this.isInitialized(),await this.pairings.update(i,{expiry:s})},this.updateMetadata=async({topic:i,metadata:s})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:s})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:s}=i;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",a.getSdkError("USER_DISCONNECTED")),await this.deletePairing(s))},this.sendRequest=async(i,s,n)=>{const o=m.formatJsonRpcRequest(s,n),h=await this.core.crypto.encode(i,o),c=F[s].req;return this.core.history.set(i,o),this.core.relayer.publish(i,h,c),o.id},this.sendResult=async(i,s,n)=>{const o=m.formatJsonRpcResult(i,n),h=await this.core.crypto.encode(s,o),c=await this.core.history.get(s,i),d=F[c.request.method].res;await this.core.relayer.publish(s,h,d),await this.core.history.resolve(o)},this.sendError=async(i,s,n)=>{const o=m.formatJsonRpcError(i,n),h=await this.core.crypto.encode(s,o),c=await this.core.history.get(s,i),d=F[c.request.method]?F[c.request.method].res:F.unregistered_method.res;await this.core.relayer.publish(s,h,d),await this.core.history.resolve(o)},this.deletePairing=async(i,s)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,a.getSdkError("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),s?Promise.resolve():this.core.expirer.del(i)])},this.cleanup=async()=>{const i=this.pairings.getAll().filter(s=>a.isExpired(s.expiry));await Promise.all(i.map(s=>this.deletePairing(s.topic)))},this.onRelayEventRequest=i=>{const{topic:s,payload:n}=i;switch(n.method){case"wc_pairingPing":return this.onPairingPingRequest(s,n);case"wc_pairingDelete":return this.onPairingDeleteRequest(s,n);default:return this.onUnknownRpcMethodRequest(s,n)}},this.onRelayEventResponse=async i=>{const{topic:s,payload:n}=i,o=(await this.core.history.get(s,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(s,n);default:return this.onUnknownRpcMethodResponse(o)}},this.onPairingPingRequest=async(i,s)=>{const{id:n}=s;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(K.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}},this.onPairingPingResponse=(i,s)=>{const{id:n}=s;setTimeout(()=>{m.isJsonRpcResult(s)?this.events.emit(a.engineEvent("pairing_ping",n),{}):m.isJsonRpcError(s)&&this.events.emit(a.engineEvent("pairing_ping",n),{error:s.error})},500)},this.onPairingDeleteRequest=async(i,s)=>{const{id:n}=s;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(K.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}},this.onUnknownRpcMethodRequest=async(i,s)=>{const{id:n,method:o}=s;try{if(this.registeredMethods.includes(o))return;const h=a.getSdkError("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,i,h),this.logger.error(h)}catch(h){await this.sendError(n,i,h),this.logger.error(h)}},this.onUnknownRpcMethodResponse=i=>{this.registeredMethods.includes(i)||this.logger.error(a.getSdkError("WC_METHOD_UNSUPPORTED",i))},this.isValidPair=i=>{var s;if(!a.isValidParams(i)){const{message:o}=a.getInternalError("MISSING_OR_INVALID",`pair() params: ${i}`);throw new Error(o)}if(!a.isValidUrl(i.uri)){const{message:o}=a.getInternalError("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw new Error(o)}const n=a.parseUri(i.uri);if(!((s=n?.relay)!=null&&s.protocol)){const{message:o}=a.getInternalError("MISSING_OR_INVALID","pair() uri#relay-protocol");throw new Error(o)}if(!(n!=null&&n.symKey)){const{message:o}=a.getInternalError("MISSING_OR_INVALID","pair() uri#symKey");throw new Error(o)}if(n!=null&&n.expiryTimestamp&&u.toMiliseconds(n?.expiryTimestamp)<Date.now()){const{message:o}=a.getInternalError("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(o)}},this.isValidPing=async i=>{if(!a.isValidParams(i)){const{message:n}=a.getInternalError("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)},this.isValidDisconnect=async i=>{if(!a.isValidParams(i)){const{message:n}=a.getInternalError("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)},this.isValidPairingTopic=async i=>{if(!a.isValidString(i,!1)){const{message:s}=a.getInternalError("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(s)}if(!this.pairings.keys.includes(i)){const{message:s}=a.getInternalError("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(s)}if(a.isExpired(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:s}=a.getInternalError("EXPIRED",`pairing topic: ${i}`);throw new Error(s)}},this.core=e,this.logger=l.generateChildLogger(t,this.name),this.pairings=new pt(this.core,this.logger,this.name,this.storagePrefix)}get context(){return l.getLoggerContext(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=a.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(E.message,async e=>{const{topic:t,message:i}=e;if(!this.pairings.keys.includes(t)||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const s=await this.core.crypto.decode(t,i);try{m.isJsonRpcRequest(s)?(this.core.history.set(t,s),this.onRelayEventRequest({topic:t,payload:s})):m.isJsonRpcResponse(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:t,payload:s}),this.core.history.delete(t,s.id))}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(I.expired,async e=>{const{topic:t}=a.parseExpirerTarget(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(K.expire,{topic:t}))})}}class yt extends P.IJsonRpcHistory{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new z.EventEmitter,this.name=Xe,this.version=Je,this.cached=[],this.initialized=!1,this.storagePrefix=N,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,s,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:s,chainId:n}),this.records.has(s.id))return;const o={id:s.id,topic:i,request:{method:s.method,params:s.params||null},chainId:n,expiry:a.calcExpiry(u.THIRTY_DAYS)};this.records.set(o.id,o),this.events.emit(C.created,o)},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 s=await this.getRecord(i.id);typeof s.response>"u"&&(s.response=m.isJsonRpcError(i)?{error:i.error}:{result:i.result},this.records.set(s.id,s),this.events.emit(C.updated,s))},this.get=async(i,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:s}),await this.getRecord(s)),this.delete=(i,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(n=>{if(n.topic===i){if(typeof s<"u"&&n.id!==s)return;this.records.delete(n.id),this.events.emit(C.deleted,n)}})},this.exists=async(i,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===i:!1),this.on=(i,s)=>{this.events.on(i,s)},this.once=(i,s)=>{this.events.once(i,s)},this.off=(i,s)=>{this.events.off(i,s)},this.removeListener=(i,s)=>{this.events.removeListener(i,s)},this.logger=l.generateChildLogger(t,this.name)}get context(){return l.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:m.formatJsonRpcRequest(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:i}=a.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(C.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=a.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(C.created,e=>{const t=C.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()}),this.events.on(C.updated,e=>{const t=C.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()}),this.events.on(C.deleted,e=>{const t=C.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e}),this.persist()}),this.core.heartbeat.on(B.HEARTBEAT_EVENTS.pulse,()=>{this.cleanup()})}cleanup(){try{this.records.forEach(e=>{u.toMiliseconds(e.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${e.id}`),this.delete(e.topic,e.id))})}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=a.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Et extends P.IExpirer{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new z.EventEmitter,this.name=We,this.version=Qe,this.cached=[],this.initialized=!1,this.storagePrefix=N,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 s=this.formatTarget(i);return typeof this.getExpiration(s)<"u"}catch{return!1}},this.set=(i,s)=>{this.isInitialized();const n=this.formatTarget(i),o={target:n,expiry:s};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(I.created,{target:n,expiration:o})},this.get=i=>{this.isInitialized();const s=this.formatTarget(i);return this.getExpiration(s)},this.del=i=>{if(this.isInitialized(),this.has(i)){const s=this.formatTarget(i),n=this.getExpiration(s);this.expirations.delete(s),this.events.emit(I.deleted,{target:s,expiration:n})}},this.on=(i,s)=>{this.events.on(i,s)},this.once=(i,s)=>{this.events.once(i,s)},this.off=(i,s)=>{this.events.off(i,s)},this.removeListener=(i,s)=>{this.events.removeListener(i,s)},this.logger=l.generateChildLogger(t,this.name)}get context(){return l.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return a.formatTopicTarget(e);if(typeof e=="number")return a.formatIdTarget(e);const{message:t}=a.getInternalError("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(I.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=a.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:i}=a.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;u.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(I.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(B.HEARTBEAT_EVENTS.pulse,()=>this.checkExpirations()),this.events.on(I.created,e=>{const t=I.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(I.expired,e=>{const t=I.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(I.deleted,e=>{const t=I.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=a.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}}class ft extends P.IVerify{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.name=X,this.initialized=!1,this.queue=[],this.verifyDisabled=!1,this.init=async i=>{if(this.verifyDisabled||a.isReactNative()||!a.isBrowser())return;const s=this.getVerifyUrl(i?.verifyUrl);this.verifyUrl!==s&&this.removeIframe(),this.verifyUrl=s;try{await this.createIframe()}catch(n){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(n)}if(!this.initialized){this.removeIframe(),this.verifyUrl=J;try{await this.createIframe()}catch(n){this.logger.info(`Verify iframe failed to load: ${this.verifyUrl}`),this.logger.info(n),this.verifyDisabled=!0}}},this.register=async i=>{this.initialized?this.sendPost(i.attestationId):(this.addToQueue(i.attestationId),await this.init())},this.resolve=async i=>{if(this.isDevEnv)return"";const s=this.getVerifyUrl(i?.verifyUrl);let n;try{n=await this.fetchAttestation(i.attestationId,s)}catch(o){this.logger.info(`failed to resolve attestation: ${i.attestationId} from url: ${s}`),this.logger.info(o),n=await this.fetchAttestation(i.attestationId,J)}return n},this.fetchAttestation=async(i,s)=>{this.logger.info(`resolving attestation: ${i} from url: ${s}`);const n=this.startAbortTimer(u.ONE_SECOND*2),o=await fetch(`${s}/attestation/${i}`,{signal:this.abortController.signal});return clearTimeout(n),o.status===200?await o.json():void 0},this.addToQueue=i=>{this.queue.push(i)},this.processQueue=()=>{this.queue.length!==0&&(this.queue.forEach(i=>this.sendPost(i)),this.queue=[])},this.sendPost=i=>{var s;try{if(!this.iframe)return;(s=this.iframe.contentWindow)==null||s.postMessage(i,"*"),this.logger.info(`postMessage sent: ${i} ${this.verifyUrl}`)}catch{}},this.createIframe=async()=>{let i;const s=n=>{n.data==="verify_ready"&&(this.initialized=!0,this.processQueue(),window.removeEventListener("message",s),i())};await Promise.race([new Promise(n=>{if(document.getElementById(X))return n();window.addEventListener("message",s);const o=document.createElement("iframe");o.id=X,o.src=`${this.verifyUrl}/${this.projectId}`,o.style.display="none",document.body.append(o),this.iframe=o,i=n}),new Promise((n,o)=>setTimeout(()=>{window.removeEventListener("message",s),o("verify iframe load timeout")},u.toMiliseconds(u.FIVE_SECONDS)))])},this.removeIframe=()=>{this.iframe&&(this.iframe.remove(),this.iframe=void 0,this.initialized=!1)},this.getVerifyUrl=i=>{let s=i||$;return Ze.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${$}`),s=$),s},this.logger=l.generateChildLogger(t,this.name),this.verifyUrl=$,this.abortController=new AbortController,this.isDevEnv=a.isNode()&&process.env.IS_VITEST}get context(){return l.getLoggerContext(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),u.toMiliseconds(e))}}class bt extends P.IEchoClient{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.context=et,this.registerDeviceToken=async i=>{const{clientId:s,token:n,notificationType:o,enableEncrypted:h=!1}=i,c=`${tt}/${this.projectId}/clients`;await Ut.default(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:s,type:o,token:n,always_raw:h})})},this.logger=l.generateChildLogger(t,this.context)}}var Rs=Object.defineProperty,mt=Object.getOwnPropertySymbols,_s=Object.prototype.hasOwnProperty,Cs=Object.prototype.propertyIsEnumerable,wt=(r,e,t)=>e in r?Rs(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,vt=(r,e)=>{for(var t in e||(e={}))_s.call(e,t)&&wt(r,t,e[t]);if(mt)for(var t of mt(e))Cs.call(e,t)&&wt(r,t,e[t]);return r};class W extends P.ICore{constructor(e){super(e),this.protocol=te,this.version=Re,this.name=H,this.events=new z.EventEmitter,this.initialized=!1,this.on=(i,s)=>this.events.on(i,s),this.once=(i,s)=>this.events.once(i,s),this.off=(i,s)=>this.events.off(i,s),this.removeListener=(i,s)=>this.events.removeListener(i,s),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||se,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:l.pino(l.getDefaultLoggerOptions({level:e?.logger||_e.logger}));this.logger=l.generateChildLogger(t,this.name),this.heartbeat=new B.HeartBeat,this.crypto=new st(this,this.logger,e?.keychain),this.history=new yt(this,this.logger),this.expirer=new Et(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new xt.default(vt(vt({},Ce),e?.storageOptions)),this.relayer=new lt({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Dt(this,this.logger),this.verify=new ft(this.projectId||"",this.logger),this.echoClient=new bt(this.projectId||"",this.logger)}static async init(e){const t=new W(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(Ke,i),t}get context(){return l.getLoggerContext(this.logger)}async start(){this.initialized||await this.initialize()}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const Ts=W;exports.CORE_CONTEXT=H,exports.CORE_DEFAULT=_e,exports.CORE_PROTOCOL=te,exports.CORE_STORAGE_OPTIONS=Ce,exports.CORE_STORAGE_PREFIX=N,exports.CORE_VERSION=Re,exports.CRYPTO_CLIENT_SEED=ie,exports.CRYPTO_CONTEXT=Te,exports.CRYPTO_JWT_TTL=Se,exports.Core=Ts,exports.Crypto=st,exports.ECHO_CONTEXT=et,exports.ECHO_URL=tt,exports.EXPIRER_CONTEXT=We,exports.EXPIRER_DEFAULT_TTL=cs,exports.EXPIRER_EVENTS=I,exports.EXPIRER_STORAGE_VERSION=Qe,exports.EchoClient=bt,exports.Expirer=Et,exports.HISTORY_CONTEXT=Xe,exports.HISTORY_EVENTS=C,exports.HISTORY_STORAGE_VERSION=Je,exports.JsonRpcHistory=yt,exports.KEYCHAIN_CONTEXT=Oe,exports.KEYCHAIN_STORAGE_VERSION=Pe,exports.KeyChain=it,exports.MESSAGES_CONTEXT=Ae,exports.MESSAGES_STORAGE_VERSION=xe,exports.MessageTracker=rt,exports.PAIRING_CONTEXT=Ge,exports.PAIRING_DEFAULT_TTL=hs,exports.PAIRING_EVENTS=K,exports.PAIRING_RPC_OPTS=F,exports.PAIRING_STORAGE_VERSION=He,exports.PENDING_SUB_RESOLUTION_TIMEOUT=je,exports.PUBLISHER_CONTEXT=Le,exports.PUBLISHER_DEFAULT_TTL=Ne,exports.Pairing=Dt,exports.RELAYER_CONTEXT=Fe,exports.RELAYER_DEFAULT_LOGGER=ze,exports.RELAYER_DEFAULT_PROTOCOL=Ue,exports.RELAYER_DEFAULT_RELAY_URL=se,exports.RELAYER_EVENTS=E,exports.RELAYER_FAILOVER_RELAY_URL=re,exports.RELAYER_PROVIDER_EVENTS=A,exports.RELAYER_RECONNECT_TIMEOUT=Me,exports.RELAYER_SDK_VERSION=Be,exports.RELAYER_STORAGE_OPTIONS=os,exports.RELAYER_SUBSCRIBER_SUFFIX=$e,exports.RELAYER_TRANSPORT_CUTOFF=Ve,exports.Relayer=lt,exports.STORE_STORAGE_VERSION=ke,exports.SUBSCRIBER_CONTEXT=qe,exports.SUBSCRIBER_DEFAULT_TTL=as,exports.SUBSCRIBER_EVENTS=v,exports.SUBSCRIBER_STORAGE_VERSION=Ye,exports.Store=pt,exports.Subscriber=at,exports.TRUSTED_VERIFY_URLS=Ze,exports.VERIFY_CONTEXT=X,exports.VERIFY_FALLBACK_SERVER=J,exports.VERIFY_SERVER=$,exports.Verify=ft,exports.WALLETCONNECT_CLIENT_ID=Ke,exports.default=W;
//# sourceMappingURL=index.cjs.js.map