"use strict";(self.webpackChunkfrog=self.webpackChunkfrog||[]).push([[2573],{32573:(e,t,i)=>{i.d(t,{$I:()=>te,$w:()=>X,Jf:()=>A,S$:()=>ee,Tn:()=>re,U:()=>ie,U$:()=>se,WB:()=>W,cV:()=>N,iJ:()=>ki,il:()=>ui,sD:()=>S,wn:()=>J,zN:()=>V});var s=i(37007),r=i.n(s),n=i(93532),o=i(55669),a=i(29838),h=i(72225),c=i(88900),l=i(13554),g=i(38236),p=i(36525),d=i(65661),u=i(27907),y=i(39031),m=i(84365),b=i(8142),f=i.n(b),w=i(38196);const v="core",_=`wc@2:${v}:`,E="error",I={database:":memory:"},P="client_ed25519_seed",x=c.ONE_DAY,T=c.SIX_HOURS,S="irn",O="wss://relay.walletconnect.org",A={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"},R="payload",z="connect",C="disconnect",D="error",k="2.18.0",N={link_mode:"link_mode",relay:"relay"},M="WALLETCONNECT_LINK_MODE_APPS",U="subscription_created",K="subscription_deleted",$="subscription_sync",L="subscription_resubscribed",j=1e3*c.FIVE_SECONDS,q={wc_pairingDelete:{req:{ttl:c.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:c.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:c.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:c.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:c.ONE_DAY,prompt:!1,tag:0},res:{ttl:c.ONE_DAY,prompt:!1,tag:0}}},V={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},F="history_created",G="history_updated",B="history_deleted",H="history_sync",J={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},Y="https://verify.walletconnect.org",W=Y,Z=`${W}/v3`,Q=["https://verify.walletconnect.com",Y],X={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"},ee={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"},te={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"},ie={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"},se={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"},re={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"};var ne=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),s=0;s>>0,o=new Uint8Array(n);e[t];){var l=i[e.charCodeAt(t)];if(255===l)return;for(var g=0,p=n-1;(0!==l||g>>0,o[p]=l%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");r=g,t++}if(" "!==e[t]){for(var d=n-r;d!==n&&0===o[d];)d++;for(var u=new Uint8Array(s+(n-d)),y=s;d!==n;)u[y++]=o[d++];return u}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var i=0,s=0,r=0,n=t.length;r!==n&&0===t[r];)r++,i++;for(var o=(n-r)*l+1>>>0,c=new Uint8Array(o);r!==n;){for(var g=t[r],p=0,d=o-1;(0!==g||p>>0,c[d]=g%a>>>0,g=g/a>>>0;if(0!==g)throw new Error("Non-zero carry");s=p,r++}for(var u=o-s;u!==o&&0===c[u];)u++;for(var y=h.repeat(i);u{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};class ae{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 he{constructor(e,t,i){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if("string"==typeof e){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))}throw Error("Can only multibase decode strings")}or(e){return le(this,e)}}class ce{constructor(e){this.decoders=e}or(e){return le(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 le=(e,t)=>new ce({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class ge{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new ae(e,t,i),this.decoder=new he(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const pe=({name:e,prefix:t,encode:i,decode:s})=>new ge(e,t,i,s),de=({prefix:e,name:t,alphabet:i})=>{const{encode:s,decode:r}=ne(i,t);return pe({prefix:e,name:t,encode:s,decode:e=>oe(r(e))})},ue=({name:e,prefix:t,bitsPerChar:i,alphabet:s})=>pe({prefix:t,name:e,encode:e=>((e,t,i)=>{const s="="===t[t.length-1],r=(1<i;)o-=i,n+=t[r&a>>o];if(o&&(n+=t[r&a<((e,t,i,s)=>{const r={};for(let e=0;e=8&&(a-=8,o[c++]=255&h>>a)}if(a>=i||255&h<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,s,i,e)}),ye=pe({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var me=Object.freeze({__proto__:null,identity:ye});const be=ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var fe=Object.freeze({__proto__:null,base2:be});const we=ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ve=Object.freeze({__proto__:null,base8:we});const _e=de({prefix:"9",name:"base10",alphabet:"0123456789"});var Ee=Object.freeze({__proto__:null,base10:_e});const Ie=ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Pe=ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var xe=Object.freeze({__proto__:null,base16:Ie,base16upper:Pe});const Te=ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Se=ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Oe=ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ae=ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Re=ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ze=ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ce=ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),De=ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ke=ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ne=Object.freeze({__proto__:null,base32:Te,base32upper:Se,base32pad:Oe,base32padupper:Ae,base32hex:Re,base32hexupper:ze,base32hexpad:Ce,base32hexpadupper:De,base32z:ke});const Me=de({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ue=de({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ke=Object.freeze({__proto__:null,base36:Me,base36upper:Ue});const $e=de({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Le=de({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var je=Object.freeze({__proto__:null,base58btc:$e,base58flickr:Le});const qe=ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ve=ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Fe=ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ge=ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Be=Object.freeze({__proto__:null,base64:qe,base64pad:Ve,base64url:Fe,base64urlpad:Ge});const He=Array.from("๐Ÿš€๐Ÿชโ˜„๐Ÿ›ฐ๐ŸŒŒ๐ŸŒ‘๐ŸŒ’๐ŸŒ“๐ŸŒ”๐ŸŒ•๐ŸŒ–๐ŸŒ—๐ŸŒ˜๐ŸŒ๐ŸŒ๐ŸŒŽ๐Ÿ‰โ˜€๐Ÿ’ป๐Ÿ–ฅ๐Ÿ’พ๐Ÿ’ฟ๐Ÿ˜‚โค๐Ÿ˜๐Ÿคฃ๐Ÿ˜Š๐Ÿ™๐Ÿ’•๐Ÿ˜ญ๐Ÿ˜˜๐Ÿ‘๐Ÿ˜…๐Ÿ‘๐Ÿ˜๐Ÿ”ฅ๐Ÿฅฐ๐Ÿ’”๐Ÿ’–๐Ÿ’™๐Ÿ˜ข๐Ÿค”๐Ÿ˜†๐Ÿ™„๐Ÿ’ช๐Ÿ˜‰โ˜บ๐Ÿ‘Œ๐Ÿค—๐Ÿ’œ๐Ÿ˜”๐Ÿ˜Ž๐Ÿ˜‡๐ŸŒน๐Ÿคฆ๐ŸŽ‰๐Ÿ’žโœŒโœจ๐Ÿคท๐Ÿ˜ฑ๐Ÿ˜Œ๐ŸŒธ๐Ÿ™Œ๐Ÿ˜‹๐Ÿ’—๐Ÿ’š๐Ÿ˜๐Ÿ’›๐Ÿ™‚๐Ÿ’“๐Ÿคฉ๐Ÿ˜„๐Ÿ˜€๐Ÿ–ค๐Ÿ˜ƒ๐Ÿ’ฏ๐Ÿ™ˆ๐Ÿ‘‡๐ŸŽถ๐Ÿ˜’๐Ÿคญโฃ๐Ÿ˜œ๐Ÿ’‹๐Ÿ‘€๐Ÿ˜ช๐Ÿ˜‘๐Ÿ’ฅ๐Ÿ™‹๐Ÿ˜ž๐Ÿ˜ฉ๐Ÿ˜ก๐Ÿคช๐Ÿ‘Š๐Ÿฅณ๐Ÿ˜ฅ๐Ÿคค๐Ÿ‘‰๐Ÿ’ƒ๐Ÿ˜ณโœ‹๐Ÿ˜š๐Ÿ˜๐Ÿ˜ด๐ŸŒŸ๐Ÿ˜ฌ๐Ÿ™ƒ๐Ÿ€๐ŸŒท๐Ÿ˜ป๐Ÿ˜“โญโœ…๐Ÿฅบ๐ŸŒˆ๐Ÿ˜ˆ๐Ÿค˜๐Ÿ’ฆโœ”๐Ÿ˜ฃ๐Ÿƒ๐Ÿ’โ˜น๐ŸŽŠ๐Ÿ’˜๐Ÿ˜ โ˜๐Ÿ˜•๐ŸŒบ๐ŸŽ‚๐ŸŒป๐Ÿ˜๐Ÿ–•๐Ÿ’๐Ÿ™Š๐Ÿ˜น๐Ÿ—ฃ๐Ÿ’ซ๐Ÿ’€๐Ÿ‘‘๐ŸŽต๐Ÿคž๐Ÿ˜›๐Ÿ”ด๐Ÿ˜ค๐ŸŒผ๐Ÿ˜ซโšฝ๐Ÿค™โ˜•๐Ÿ†๐Ÿคซ๐Ÿ‘ˆ๐Ÿ˜ฎ๐Ÿ™†๐Ÿป๐Ÿƒ๐Ÿถ๐Ÿ’๐Ÿ˜ฒ๐ŸŒฟ๐Ÿงก๐ŸŽโšก๐ŸŒž๐ŸŽˆโŒโœŠ๐Ÿ‘‹๐Ÿ˜ฐ๐Ÿคจ๐Ÿ˜ถ๐Ÿค๐Ÿšถ๐Ÿ’ฐ๐Ÿ“๐Ÿ’ข๐ŸคŸ๐Ÿ™๐Ÿšจ๐Ÿ’จ๐Ÿคฌโœˆ๐ŸŽ€๐Ÿบ๐Ÿค“๐Ÿ˜™๐Ÿ’Ÿ๐ŸŒฑ๐Ÿ˜–๐Ÿ‘ถ๐Ÿฅดโ–ถโžกโ“๐Ÿ’Ž๐Ÿ’ธโฌ‡๐Ÿ˜จ๐ŸŒš๐Ÿฆ‹๐Ÿ˜ท๐Ÿ•บโš ๐Ÿ™…๐Ÿ˜Ÿ๐Ÿ˜ต๐Ÿ‘Ž๐Ÿคฒ๐Ÿค ๐Ÿคง๐Ÿ“Œ๐Ÿ”ต๐Ÿ’…๐Ÿง๐Ÿพ๐Ÿ’๐Ÿ˜—๐Ÿค‘๐ŸŒŠ๐Ÿคฏ๐Ÿทโ˜Ž๐Ÿ’ง๐Ÿ˜ฏ๐Ÿ’†๐Ÿ‘†๐ŸŽค๐Ÿ™‡๐Ÿ‘โ„๐ŸŒด๐Ÿ’ฃ๐Ÿธ๐Ÿ’Œ๐Ÿ“๐Ÿฅ€๐Ÿคข๐Ÿ‘…๐Ÿ’ก๐Ÿ’ฉ๐Ÿ‘๐Ÿ“ธ๐Ÿ‘ป๐Ÿค๐Ÿคฎ๐ŸŽผ๐Ÿฅต๐Ÿšฉ๐ŸŽ๐ŸŠ๐Ÿ‘ผ๐Ÿ’๐Ÿ“ฃ๐Ÿฅ‚"),Je=He.reduce(((e,t,i)=>(e[i]=t,e)),[]),Ye=He.reduce(((e,t,i)=>(e[t.codePointAt(0)]=i,e)),[]);const We=pe({prefix:"๐Ÿš€",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+=Je[t]),"")},decode:function(e){const t=[];for(const i of e){const e=Ye[i.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${i}`);t.push(e)}return new Uint8Array(t)}});var Ze=Object.freeze({__proto__:null,base256emoji:We}),Qe=function e(t,i,s){i=i||[];for(var r=s=s||0;t>=tt;)i[s++]=255&t|Xe,t/=128;for(;t&et;)i[s++]=255&t|Xe,t>>>=7;return i[s]=0|t,e.bytes=s-r+1,i},Xe=128,et=-128,tt=Math.pow(2,31);var it=function e(t,i){var s,r=0,n=0,o=i=i||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=n<28?(s&rt)<=st);return e.bytes=o-i,r},st=128,rt=127;var nt=Math.pow(2,7),ot=Math.pow(2,14),at=Math.pow(2,21),ht=Math.pow(2,28),ct=Math.pow(2,35),lt=Math.pow(2,42),gt=Math.pow(2,49),pt=Math.pow(2,56),dt=Math.pow(2,63),ut={encode:Qe,decode:it,encodingLength:function(e){return e(ut.encode(e,t,i),t),mt=e=>ut.encodingLength(e),bt=(e,t)=>{const i=t.byteLength,s=mt(e),r=s+mt(i),n=new Uint8Array(r+i);return yt(e,n,0),yt(i,n,s),n.set(t,r),new ft(e,i,t,n)};class ft{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}}const wt=({name:e,code:t,encode:i})=>new vt(e,t,i);class vt{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?bt(this.code,t):t.then((e=>bt(this.code,e)))}throw Error("Unknown type, must be binary type")}}const _t=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),Et=wt({name:"sha2-256",code:18,encode:_t("SHA-256")}),It=wt({name:"sha2-512",code:19,encode:_t("SHA-512")});Object.freeze({__proto__:null,sha256:Et,sha512:It});const Pt=oe,xt={code:0,name:"identity",encode:Pt,digest:e=>bt(0,Pt(e))};Object.freeze({__proto__:null,identity:xt});new TextEncoder,new TextDecoder;const Tt={...me,...fe,...ve,...Ee,...xe,...Ne,...Ke,...je,...Be,...Ze};function St(e,t,i,s){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:i},decoder:{decode:s}}}const Ot=St("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),At=St("ascii","a",(e=>{let t="a";for(let i=0;i{const t=function(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?globalThis.Buffer.allocUnsafe(e):new Uint8Array(e)}((e=e.substring(1)).length);for(let i=0;i{if(!this.initialized){const e=await this.getKeyChain();typeof e<"u"&&(this.keychain=e),this.initialized=!0}},this.has=e=>(this.isInitialized(),this.keychain.has(e)),this.set=async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()},this.get=e=>{this.isInitialized();const t=this.keychain.get(e);if(typeof t>"u"){const{message:t}=(0,p.GuA)("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t},this.del=async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()},this.core=e,this.logger=(0,a.U5)(t,this.name)}get context(){return(0,a.oI)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,(0,p.h0Y)(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?(0,p.PUk)(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Ct{constructor(e,t,i){this.core=e,this.logger=t,this.name="crypto",this.randomSessionIdentifier=(0,p.two)(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=e=>(this.isInitialized(),this.keychain.has(e)),this.getClientId=async()=>{this.isInitialized();const e=await this.getClientSeed(),t=g.TZ(e);return g.UF(t.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const e=(0,p.TZl)();return this.setPrivateKey(e.publicKey,e.privateKey)},this.signJWT=async e=>{this.isInitialized();const t=await this.getClientSeed(),i=g.TZ(t),s=this.randomSessionIdentifier,r=x;return await g.FA(s,e,r,i)},this.generateSharedKey=(e,t,i)=>{this.isInitialized();const s=this.getPrivateKey(e),r=(0,p.ovp)(s,t);return this.setSymKey(r,i)},this.setSymKey=async(e,t)=>{this.isInitialized();const i=t||(0,p.EN$)(e);return await this.keychain.set(i,e),i},this.deleteKeyPair=async e=>{this.isInitialized(),await this.keychain.del(e)},this.deleteSymKey=async e=>{this.isInitialized(),await this.keychain.del(e)},this.encode=async(e,t,i)=>{this.isInitialized();const s=(0,p.AwN)(i),r=(0,l.h)(t);if((0,p.ps1)(s))return(0,p.Tw2)(r,i?.encoding);if((0,p.V7m)(s)){const t=s.senderPublicKey,i=s.receiverPublicKey;e=await this.generateSharedKey(t,i)}const n=this.getSymKey(e),{type:o,senderPublicKey:a}=s;return(0,p.wa2)({type:o,symKey:n,message:r,senderPublicKey:a,encoding:i?.encoding})},this.decode=async(e,t,i)=>{this.isInitialized();const s=(0,p.C5G)(t,i);if((0,p.ps1)(s)){const e=(0,p.F$L)(t,i?.encoding);return(0,l.j)(e)}if((0,p.V7m)(s)){const t=s.receiverPublicKey,i=s.senderPublicKey;e=await this.generateSharedKey(t,i)}try{const s=this.getSymKey(e),r=(0,p.YcA)({symKey:s,encoded:t,encoding:i?.encoding});return(0,l.j)(r)}catch(t){this.logger.error(`Failed to decode message from topic: '${e}', clientId: '${await this.getClientId()}'`),this.logger.error(t)}},this.getPayloadType=(e,t=p.EWt)=>{const i=(0,p.iui)({encoded:e,encoding:t});return(0,p.x0t)(i.type)},this.getPayloadSenderPublicKey=(e,t=p.EWt)=>{const i=(0,p.iui)({encoded:e,encoding:t});return i.senderPublicKey?(0,d.dI)(i.senderPublicKey,p.bEt):void 0},this.core=e,this.logger=(0,a.U5)(t,this.name),this.keychain=i||new zt(this.core,this.logger)}get context(){return(0,a.oI)(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(P)}catch{e=(0,p.two)(),await this.keychain.set(P,e)}return function(e,t="utf8"){const i=Rt[t];if(!i)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?i.decoder.decode(`${i.prefix}${e}`):globalThis.Buffer.from(e,"utf8")}(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Dt extends h.dQ{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.name="messages",this.version="0.3",this.initialized=!1,this.storagePrefix=_,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const e=await this.getRelayerMessages();typeof e<"u"&&(this.messages=e),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}finally{this.initialized=!0}}},this.set=async(e,t)=>{this.isInitialized();const i=(0,p.ALl)(t);let s=this.messages.get(e);return typeof s>"u"&&(s={}),typeof s[i]<"u"||(s[i]=t,this.messages.set(e,s),await this.persist()),i},this.get=e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t},this.has=(e,t)=>{this.isInitialized();return typeof this.get(e)[(0,p.ALl)(t)]<"u"},this.del=async e=>{this.isInitialized(),this.messages.delete(e),await this.persist()},this.logger=(0,a.U5)(e,this.name),this.core=t}get context(){return(0,a.oI)(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,(0,p.h0Y)(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?(0,p.PUk)(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}var kt=Object.defineProperty,Nt=Object.defineProperties,Mt=Object.getOwnPropertyDescriptors,Ut=Object.getOwnPropertySymbols,Kt=Object.prototype.hasOwnProperty,$t=Object.prototype.propertyIsEnumerable,Lt=(e,t,i)=>t in e?kt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,jt=(e,t)=>{for(var i in t||(t={}))Kt.call(t,i)&&Lt(e,i,t[i]);if(Ut)for(var i of Ut(t))$t.call(t,i)&&Lt(e,i,t[i]);return e},qt=(e,t)=>Nt(e,Mt(t));class Vt extends h.qE{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new s.EventEmitter,this.name="publisher",this.queue=new Map,this.publishTimeout=(0,c.toMiliseconds)(c.ONE_MINUTE),this.initialPublishTimeout=(0,c.toMiliseconds)(15*c.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(e,t,i)=>{var s;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:i}});const r=i?.ttl||T,n=(0,p.n6V)(i),o=i?.prompt||!1,a=i?.tag||0,h=i?.id||(0,y.getBigIntRpcId)().toString(),c={topic:e,message:t,opts:{ttl:r,relay:n,prompt:o,tag:a,id:h,attestation:i?.attestation}},l=`Failed to publish payload, please try again. id:${h} tag:${a}`;try{const s=new Promise((async s=>{const n=({id:e})=>{c.opts.id===e&&(this.removeRequestFromQueue(e),this.relayer.events.removeListener(A.publish,n),s(c))};this.relayer.events.on(A.publish,n);const l=(0,p.K3g)(new Promise(((s,n)=>{this.rpcPublish({topic:e,message:t,ttl:r,prompt:o,tag:a,id:h,attestation:i?.attestation}).then(s).catch((e=>{this.logger.warn(e,e?.message),n(e)}))})),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${h} tag:${a}`);try{await l,this.events.removeListener(A.publish,n)}catch(e){this.queue.set(h,qt(jt({},c),{attempt:1})),this.logger.warn(e,e?.message)}}));this.logger.trace({type:"method",method:"publish",params:{id:h,topic:e,message:t,opts:i}}),await(0,p.K3g)(s,this.publishTimeout,l)}catch(e){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(e),null!=(s=i?.internal)&&s.throwOnFailedPublish)throw e}finally{this.queue.delete(h)}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.relayer=e,this.logger=(0,a.U5)(t,this.name),this.registerEventListeners()}get context(){return(0,a.oI)(this.logger)}async rpcPublish(e){var t,i,s,r;const{topic:n,message:o,ttl:a=T,prompt:h,tag:c,id:l,attestation:g}=e,d={method:(0,p.aa1)((0,p.n6V)().protocol).publish,params:{topic:n,message:o,ttl:a,prompt:h,tag:c,attestation:g},id:l};(0,p.b07)(null==(t=d.params)?void 0:t.prompt)&&(null==(i=d.params)||delete i.prompt),(0,p.b07)(null==(s=d.params)?void 0:s.tag)&&(null==(r=d.params)||delete r.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:d});const u=await this.relayer.request(d);return this.relayer.events.emit(A.publish,e),this.logger.debug("Successfully Published Payload"),u}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach((async(e,t)=>{const i=e.attempt+1;this.queue.set(t,qt(jt({},e),{attempt:i}));const{topic:s,message:r,opts:n,attestation:o}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish({topic:s,message:r,ttl:n.ttl,prompt:n.prompt,tag:n.tag,id:n.id,attestation:o}),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)}))}registerEventListeners(){this.relayer.core.heartbeat.on(n.li.pulse,(()=>{if(this.needsTransportRestart)return this.needsTransportRestart=!1,void this.relayer.events.emit(A.connection_stalled);this.checkQueue()})),this.relayer.on(A.message_ack,(e=>{this.removeRequestFromQueue(e.id.toString())}))}}class Ft{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")return void this.map.delete(e);if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const s=i.filter((e=>e!==t));s.length?this.map.set(e,s):this.map.delete(e)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var Gt=Object.defineProperty,Bt=Object.defineProperties,Ht=Object.getOwnPropertyDescriptors,Jt=Object.getOwnPropertySymbols,Yt=Object.prototype.hasOwnProperty,Wt=Object.prototype.propertyIsEnumerable,Zt=(e,t,i)=>t in e?Gt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Qt=(e,t)=>{for(var i in t||(t={}))Yt.call(t,i)&&Zt(e,i,t[i]);if(Jt)for(var i of Jt(t))Wt.call(t,i)&&Zt(e,i,t[i]);return e},Xt=(e,t)=>Bt(e,Ht(t));class ei extends h.mF{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new Ft,this.events=new s.EventEmitter,this.name="subscription",this.version="0.3",this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=_,this.subscribeTimeout=(0,c.toMiliseconds)(c.ONE_MINUTE),this.initialSubscribeTimeout=(0,c.toMiliseconds)(15*c.ONE_SECOND),this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId(),await this.restore()),this.initialized=!0},this.subscribe=async(e,t)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}});try{const i=(0,p.n6V)(t),s={topic:e,relay:i,transportType:t?.transportType};this.pending.set(e,s);const r=await this.rpcSubscribe(e,i,t);return"string"==typeof r&&(this.onSubscribe(r,s),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}})),r}catch(e){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(e),e}},this.unsubscribe=async(e,t)=>{await this.restartToComplete(),this.isInitialized(),typeof t?.id<"u"?await this.unsubscribeById(e,t.id,t):await this.unsubscribeByTopic(e,t)},this.isSubscribed=async e=>{if(this.topics.includes(e))return!0;const t=`${this.pendingSubscriptionWatchLabel}_${e}`;return await new Promise(((i,s)=>{const r=new c.Watch;r.start(t);const n=setInterval((()=>{(!this.pending.has(e)&&this.topics.includes(e)||this.cached.some((t=>t.topic===e)))&&(clearInterval(n),r.stop(t),i(!0)),r.elapsed(t)>=j&&(clearInterval(n),r.stop(t),s(new Error("Subscription resolution timeout")))}),this.pollingInterval)})).catch((()=>!1))},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{await this.restore(),await this.onRestart()},this.checkPending=async()=>{if(!(0!==this.pending.size||this.initialized&&this.relayer.connected))return;const e=[];this.pending.forEach((t=>{e.push(t)})),await this.batchSubscribe(e)},this.registerEventListeners=()=>{this.relayer.core.heartbeat.on(n.li.pulse,(async()=>{await this.checkPending()})),this.events.on(U,(async e=>{const t=U;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})),this.events.on(K,(async e=>{const t=K;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}))},this.relayer=e,this.logger=(0,a.U5)(t,this.name),this.clientId=""}get context(){return(0,a.oI)(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}reset(){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 i=>await this.unsubscribeById(e,i,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=(0,p.n6V)(i);await this.rpcUnsubscribe(e,t,s);const r=(0,p.Hjj)("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,r),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(e){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(e),e}}async rpcSubscribe(e,t,i){var s;i?.transportType===N.relay&&await this.restartToComplete();const r={method:(0,p.aa1)(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});const n=null==(s=i?.internal)?void 0:s.throwOnFailedPublish;try{const t=this.getSubscriptionId(e);if(i?.transportType===N.link_mode)return setTimeout((()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(r).catch((e=>this.logger.warn(e)))}),(0,c.toMiliseconds)(c.ONE_SECOND)),t;const s=new Promise((async t=>{const i=s=>{s.topic===e&&(this.events.removeListener(U,i),t(s.id))};this.events.on(U,i);try{const s=await(0,p.K3g)(new Promise(((e,t)=>{this.relayer.request(r).catch((e=>{this.logger.warn(e,e?.message),t(e)})).then(e)})),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(U,i),t(s)}catch{}})),o=await(0,p.K3g)(s,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!o&&n)throw new Error(`Subscribing to ${e} failed, please try again`);return o?t:null}catch(e){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(A.connection_stalled),n)throw e}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:(0,p.aa1)(t.protocol).batchSubscribe,params:{topics:e.map((e=>e.topic))}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await(0,p.K3g)(new Promise((e=>{this.relayer.request(i).catch((e=>this.logger.warn(e))).then(e)})),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(A.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:(0,p.aa1)(t.protocol).batchFetchMessages,params:{topics:e.map((e=>e.topic))}};let s;this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{s=await await(0,p.K3g)(new Promise(((e,t)=>{this.relayer.request(i).catch((e=>{this.logger.warn(e),t(e)})).then(e)})),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(A.connection_stalled)}return s}rpcUnsubscribe(e,t,i){const s={method:(0,p.aa1)(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,Xt(Qt({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach((e=>{this.setSubscription(e.id,Qt({},e)),this.pending.delete(e.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.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,Qt({},t)),this.topicMap.set(t.topic,e),this.events.emit(U,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:t}=(0,p.GuA)("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}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(K,Xt(Qt({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit($)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i"u"||!e.length)return;if(this.subscriptions.size){const{message:e}=(0,p.GuA)("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(e.map((e=>Xt(Qt({},e),{id:this.getSubscriptionId(e.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(await(0,p.yy4)((0,c.toMiliseconds)(c.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){!this.relayer.connected&&!this.relayer.connecting&&await this.relayer.transportOpen()}getSubscriptionId(e){return(0,p.ALl)(e+this.clientId)}}var ti=Object.defineProperty,ii=Object.getOwnPropertySymbols,si=Object.prototype.hasOwnProperty,ri=Object.prototype.propertyIsEnumerable,ni=(e,t,i)=>t in e?ti(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,oi=(e,t)=>{for(var i in t||(t={}))si.call(t,i)&&ni(e,i,t[i]);if(ii)for(var i of ii(t))ri.call(t,i)&&ni(e,i,t[i]);return e};class ai extends h.m5{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new s.EventEmitter,this.name="relayer",this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1,this.heartBeatTimeout=(0,c.toMiliseconds)(c.THIRTY_SECONDS+c.FIVE_SECONDS),this.requestsInFlight=[],this.connectTimeout=(0,c.toMiliseconds)(15*c.ONE_SECOND),this.request=async e=>{var t,i;this.logger.debug("Publishing Request Payload");const s=e.id||(0,y.getBigIntRpcId)().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:e.method,topic:null==(t=e.params)?void 0:t.topic},"relayer.request - publishing...");const r=`${s}:${(null==(i=e.params)?void 0:i.tag)||""}`;this.requestsInFlight.push(r);const n=await this.provider.request(e);return this.requestsInFlight=this.requestsInFlight.filter((e=>e!==r)),n}catch(e){throw this.logger.debug(`Failed to Publish Request: ${s}`),e}},this.resetPingTimeout=()=>{if((0,p.Lln)())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout((()=>{var e,t,i;this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),null==(i=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)||i.terminate()}),this.heartBeatTimeout)}catch(e){this.logger.warn(e,e?.message)}},this.onPayloadHandler=e=>{this.onProviderPayload(e),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.warn({},"Relayer connected ๐Ÿ›œ"),this.startPingTimeout(),this.events.emit(A.connect)},this.onDisconnectHandler=()=>{this.logger.warn({},"Relayer disconnected ๐Ÿ›‘"),this.requestsInFlight=[],this.onProviderDisconnect()},this.onProviderErrorHandler=e=>{this.logger.fatal(e,`Fatal socket error: ${e?.message}`),this.events.emit(A.error,e),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(R,this.onPayloadHandler),this.provider.on(z,this.onConnectHandler),this.provider.on(C,this.onDisconnectHandler),this.provider.on(D,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&"string"!=typeof e.logger?(0,a.U5)(e.logger,this.name):(0,a.h6)((0,a.iP)({level:e.logger||"error"})),this.messages=new Dt(this.logger,e.core),this.subscriber=new ei(this,this.logger),this.publisher=new Vt(this,this.logger),this.relayUrl=e?.relayUrl||O,this.projectId=e.projectId,(0,p.m01)()?this.packageName=(0,p.R7U)():(0,p.aRZ)()&&(this.bundleId=(0,p.R7U)()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.cached.length>0)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return(0,a.oI)(this.logger)}get connected(){var e,t,i;return 1===(null==(i=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:i.readyState)}get connecting(){var e,t,i;return 0===(null==(i=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:i.readyState)}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:N.relay})}async subscribe(e,t){var i,s,r;this.isInitialized(),(null==t||!t.transportType||"relay"===t?.transportType)&&await this.toEstablishConnection();const n=typeof(null==(i=t?.internal)?void 0:i.throwOnFailedPublish)>"u"||(null==(s=t?.internal)?void 0:s.throwOnFailedPublish);let o,a=(null==(r=this.subscriber.topicMap.get(e))?void 0:r[0])||"";const h=t=>{t.topic===e&&(this.subscriber.off(U,h),o())};return await Promise.all([new Promise((e=>{o=e,this.subscriber.on(U,h)})),new Promise((async(i,s)=>{a=await this.subscriber.subscribe(e,oi({internal:{throwOnFailedPublish:n}},t)).catch((e=>{n&&s(e)}))||a,i()}))]),a}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 transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await(0,p.K3g)(this.provider.disconnect(),2e3,"provider.disconnect()").catch((()=>this.onProviderDisconnect())):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise((async(t,i)=>{await this.connect(e).then(t).catch(i).finally((()=>{this.connectPromise=void 0}))})),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await(0,p.sc7)())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(0===e?.length)return void this.logger.trace("Batch message events is empty. Ignoring...");const t=e.sort(((e,t)=>e.publishedAt-t.publishedAt));this.logger.debug(`Batch of ${t.length} message events sorted`);for(const e of t)try{await this.onMessageEvent(e)}catch(e){this.logger.warn(e,"Error while processing batch message event: "+e?.message)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:i}=e;if(!t.sessionExists){const e={topic:i,expiry:(0,p.Xw0)(c.FIVE_MINUTES),relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,e)}this.events.emit(A.message,e),await this.recordMessageEvent(e)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise((async(e,t)=>{const i=()=>{t(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(C,i),await(0,p.K3g)(new Promise(((e,t)=>{this.provider.connect().then(e).catch(t)})),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch((e=>{t(e)})).finally((()=>{this.provider.off(C,i),clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0})),await new Promise((async(e,t)=>{const i=()=>{t(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(C,i),await this.subscriber.start().then(e).catch(t).finally((()=>{this.provider.off(C,i)}))})),this.hasExperiencedNetworkDisruption=!1,e()}))}catch(e){await this.subscriber.stop();const t=e;this.logger.warn({},t.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise((e=>setTimeout(e,(0,c.toMiliseconds)(1*t)))),t++}}startPingTimeout(){var e,t,i,s,r;if((0,p.Lln)())try{null!=(t=null==(e=this.provider)?void 0:e.connection)&&t.socket&&(null==(r=null==(s=null==(i=this.provider)?void 0:i.connection)?void 0:s.socket)||r.on("ping",(()=>{this.resetPingTimeout()}))),this.resetPingTimeout()}catch(e){this.logger.warn(e,e?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new u.F(new m.A((0,p.jUZ)({sdkVersion:k,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:t,message:i}=e;await this.messages.set(t,i)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||0===i.length)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.warn(`Ignoring message for non-subscribed topic ${t}`),!0;const s=this.messages.has(t,i);return s&&this.logger.warn(`Ignoring duplicate message: ${i}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),(0,y.isJsonRpcRequest)(e)){if(!e.method.endsWith("_subscription"))return;const t=e.params,{topic:i,message:s,publishedAt:r,attestation:n}=t.data,o={topic:i,message:s,publishedAt:r,transportType:N.relay,attestation:n};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(oi({type:"event",event:t.id},o)),this.events.emit(t.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else(0,y.isJsonRpcResponse)(e)&&this.events.emit(A.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(A.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=(0,y.formatJsonRpcResult)(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(R,this.onPayloadHandler),this.provider.off(z,this.onConnectHandler),this.provider.off(C,this.onDisconnectHandler),this.provider.off(D,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await(0,p.sc7)();(0,p.uym)((async t=>{e!==t&&(e=t,t?await this.transportOpen().catch((e=>this.logger.error(e,e?.message))):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}))}async onProviderDisconnect(){await this.subscriber.stop(),clearTimeout(this.pingTimeout),this.events.emit(A.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&(this.reconnectTimeout||this.connectPromise||(this.reconnectTimeout=setTimeout((async()=>{clearTimeout(this.reconnectTimeout),await this.transportOpen().catch((e=>this.logger.error(e,e?.message)))}),(0,c.toMiliseconds)(.1))))}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.transportOpen()}}var hi=Object.defineProperty,ci=Object.getOwnPropertySymbols,li=Object.prototype.hasOwnProperty,gi=Object.prototype.propertyIsEnumerable,pi=(e,t,i)=>t in e?hi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,di=(e,t)=>{for(var i in t||(t={}))li.call(t,i)&&pi(e,i,t[i]);if(ci)for(var i of ci(t))gi.call(t,i)&&pi(e,i,t[i]);return e};class ui extends h.pi{constructor(e,t,i,s=_,r=void 0){super(e,t,i,s),this.core=e,this.logger=t,this.name=i,this.map=new Map,this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=_,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>{this.getKey&&null!==e&&!(0,p.b07)(e)?this.map.set(this.getKey(e),e):(0,p.CTo)(e)?this.map.set(e.id,e):(0,p.mr0)(e)&&this.map.set(e.topic,e)})),this.cached=[],this.initialized=!0)},this.set=async(e,t)=>{this.isInitialized(),this.map.has(e)?await this.update(e,t):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:e,value:t}),this.map.set(e,t),await this.persist())},this.get=e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e)),this.getAll=e=>(this.isInitialized(),e?this.values.filter((t=>Object.keys(e).every((i=>f()(t[i],e[i]))))):this.values),this.update=async(e,t)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:e,update:t});const i=di(di({},this.getData(e)),t);this.map.set(e,i),await this.persist()},this.delete=async(e,t)=>{this.isInitialized(),this.map.has(e)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:e,reason:t}),this.map.delete(e),this.addToRecentlyDeleted(e),await this.persist())},this.logger=(0,a.U5)(t,this.name),this.storagePrefix=s,this.getKey=r}get context(){return(0,a.oI)(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 t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:t}=(0,p.GuA)("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}const{message:t}=(0,p.GuA)("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}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:e}=(0,p.GuA)("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}class yi{constructor(e,t){this.core=e,this.logger=t,this.name="pairing",this.version="0.3",this.events=new(r()),this.initialized=!1,this.storagePrefix=_,this.ignoredPayloadTypes=[p.Lp_],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:e})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...e])]},this.create=async e=>{this.isInitialized();const t=(0,p.two)(),i=await this.core.crypto.setSymKey(t),s=(0,p.Xw0)(c.FIVE_MINUTES),r={protocol:S},n={topic:i,expiry:s,relay:r,active:!1,methods:e?.methods},o=(0,p.QJh)({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:t,relay:r,expiryTimestamp:s,methods:e?.methods});return this.events.emit(V.create,n),this.core.expirer.set(i,s),await this.pairings.set(i,n),await this.core.relayer.subscribe(i,{transportType:e?.transportType}),{topic:i,uri:o}},this.pair=async e=>{this.isInitialized();const t=this.core.eventClient.createEvent({properties:{topic:e?.uri,trace:[X.pairing_started]}});this.isValidPair(e,t);const{topic:i,symKey:s,relay:r,expiryTimestamp:n,methods:o}=(0,p.wYp)(e.uri);let a;if(t.props.properties.topic=i,t.addTrace(X.pairing_uri_validation_success),t.addTrace(X.pairing_uri_not_expired),this.pairings.keys.includes(i)){if(a=this.pairings.get(i),t.addTrace(X.existing_pairing),a.active)throw t.setError(ee.active_pairing_already_exists),new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);t.addTrace(X.pairing_not_expired)}const h=n||(0,p.Xw0)(c.FIVE_MINUTES),l={topic:i,relay:r,expiry:h,active:!1,methods:o};this.core.expirer.set(i,h),await this.pairings.set(i,l),t.addTrace(X.store_new_pairing),e.activatePairing&&await this.activate({topic:i}),this.events.emit(V.create,l),t.addTrace(X.emit_inactive_pairing),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(s,i),t.addTrace(X.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{t.setError(ee.no_internet_connection)}try{await this.core.relayer.subscribe(i,{relay:r})}catch(e){throw t.setError(ee.subscribe_pairing_topic_failure),e}return t.addTrace(X.subscribe_pairing_topic_success),l},this.activate=async({topic:e})=>{this.isInitialized();const t=(0,p.Xw0)(c.FIVE_MINUTES);this.core.expirer.set(e,t),await this.pairings.update(e,{active:!0,expiry:t})},this.ping=async e=>{this.isInitialized(),await this.isValidPing(e),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:t}=e;if(this.pairings.keys.includes(t)){const e=await this.sendRequest(t,"wc_pairingPing",{}),{done:i,resolve:s,reject:r}=(0,p.Wx8)();this.events.once((0,p.hEn)("pairing_ping",e),(({error:e})=>{e?r(e):s()})),await i()}},this.updateExpiry=async({topic:e,expiry:t})=>{this.isInitialized(),await this.pairings.update(e,{expiry:t})},this.updateMetadata=async({topic:e,metadata:t})=>{this.isInitialized(),await this.pairings.update(e,{peerMetadata:t})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.pairings.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",(0,p.Hjj)("USER_DISCONNECTED")),await this.deletePairing(t))},this.formatUriFromPairing=e=>{this.isInitialized();const{topic:t,relay:i,expiry:s,methods:r}=e,n=this.core.crypto.keychain.get(t);return(0,p.QJh)({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:n,relay:i,expiryTimestamp:s,methods:r})},this.sendRequest=async(e,t,i)=>{const s=(0,y.formatJsonRpcRequest)(t,i),r=await this.core.crypto.encode(e,s),n=q[t].req;return this.core.history.set(e,s),this.core.relayer.publish(e,r,n),s.id},this.sendResult=async(e,t,i)=>{const s=(0,y.formatJsonRpcResult)(e,i),r=await this.core.crypto.encode(t,s),n=await this.core.history.get(t,e),o=q[n.request.method].res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(s)},this.sendError=async(e,t,i)=>{const s=(0,y.formatJsonRpcError)(e,i),r=await this.core.crypto.encode(t,s),n=await this.core.history.get(t,e),o=q[n.request.method]?q[n.request.method].res:q.unregistered_method.res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(s)},this.deletePairing=async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,(0,p.Hjj)("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])},this.cleanup=async()=>{const e=this.pairings.getAll().filter((e=>(0,p._dF)(e.expiry)));await Promise.all(e.map((e=>this.deletePairing(e.topic))))},this.onRelayEventRequest=e=>{const{topic:t,payload:i}=e;switch(i.method){case"wc_pairingPing":return this.onPairingPingRequest(t,i);case"wc_pairingDelete":return this.onPairingDeleteRequest(t,i);default:return this.onUnknownRpcMethodRequest(t,i)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:i}=e,s=(await this.core.history.get(t,i.id)).request.method;return"wc_pairingPing"===s?this.onPairingPingResponse(t,i):this.onUnknownRpcMethodResponse(s)},this.onPairingPingRequest=async(e,t)=>{const{id:i}=t;try{this.isValidPing({topic:e}),await this.sendResult(i,e,!0),this.events.emit(V.ping,{id:i,topic:e})}catch(t){await this.sendError(i,e,t),this.logger.error(t)}},this.onPairingPingResponse=(e,t)=>{const{id:i}=t;setTimeout((()=>{(0,y.isJsonRpcResult)(t)?this.events.emit((0,p.hEn)("pairing_ping",i),{}):(0,y.isJsonRpcError)(t)&&this.events.emit((0,p.hEn)("pairing_ping",i),{error:t.error})}),500)},this.onPairingDeleteRequest=async(e,t)=>{const{id:i}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit(V.delete,{id:i,topic:e})}catch(t){await this.sendError(i,e,t),this.logger.error(t)}},this.onUnknownRpcMethodRequest=async(e,t)=>{const{id:i,method:s}=t;try{if(this.registeredMethods.includes(s))return;const t=(0,p.Hjj)("WC_METHOD_UNSUPPORTED",s);await this.sendError(i,e,t),this.logger.error(t)}catch(t){await this.sendError(i,e,t),this.logger.error(t)}},this.onUnknownRpcMethodResponse=e=>{this.registeredMethods.includes(e)||this.logger.error((0,p.Hjj)("WC_METHOD_UNSUPPORTED",e))},this.isValidPair=(e,t)=>{var i;if(!(0,p.TeY)(e)){const{message:i}=(0,p.GuA)("MISSING_OR_INVALID",`pair() params: ${e}`);throw t.setError(ee.malformed_pairing_uri),new Error(i)}if(!(0,p.AYU)(e.uri)){const{message:i}=(0,p.GuA)("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw t.setError(ee.malformed_pairing_uri),new Error(i)}const s=(0,p.wYp)(e?.uri);if(null==(i=s?.relay)||!i.protocol){const{message:e}=(0,p.GuA)("MISSING_OR_INVALID","pair() uri#relay-protocol");throw t.setError(ee.malformed_pairing_uri),new Error(e)}if(null==s||!s.symKey){const{message:e}=(0,p.GuA)("MISSING_OR_INVALID","pair() uri#symKey");throw t.setError(ee.malformed_pairing_uri),new Error(e)}if(null!=s&&s.expiryTimestamp&&(0,c.toMiliseconds)(s?.expiryTimestamp){if(!(0,p.TeY)(e)){const{message:t}=(0,p.GuA)("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidDisconnect=async e=>{if(!(0,p.TeY)(e)){const{message:t}=(0,p.GuA)("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidPairingTopic=async e=>{if(!(0,p.Qhg)(e,!1)){const{message:t}=(0,p.GuA)("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.pairings.keys.includes(e)){const{message:t}=(0,p.GuA)("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if((0,p._dF)(this.pairings.get(e).expiry)){await this.deletePairing(e);const{message:t}=(0,p.GuA)("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}},this.core=e,this.logger=(0,a.U5)(t,this.name),this.pairings=new ui(this.core,this.logger,this.name,this.storagePrefix)}get context(){return(0,a.oI)(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(A.message,(async e=>{const{topic:t,message:i,transportType:s}=e;if(!this.pairings.keys.includes(t)||s===N.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const r=await this.core.crypto.decode(t,i);try{(0,y.isJsonRpcRequest)(r)?(this.core.history.set(t,r),this.onRelayEventRequest({topic:t,payload:r})):(0,y.isJsonRpcResponse)(r)&&(await this.core.history.resolve(r),await this.onRelayEventResponse({topic:t,payload:r}),this.core.history.delete(t,r.id))}catch(e){this.logger.error(e)}}))}registerExpirerEvents(){this.core.expirer.on(J.expired,(async e=>{const{topic:t}=(0,p.c82)(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(V.expire,{topic:t}))}))}}class mi extends h.lZ{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new s.EventEmitter,this.name="history",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=_,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>this.records.set(e.id,e))),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(e,t,i)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:e,request:t,chainId:i}),this.records.has(t.id))return;const s={id:t.id,topic:e,request:{method:t.method,params:t.params||null},chainId:i,expiry:(0,p.Xw0)(c.THIRTY_DAYS)};this.records.set(s.id,s),this.persist(),this.events.emit(F,s)},this.resolve=async e=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:e}),!this.records.has(e.id))return;const t=await this.getRecord(e.id);typeof t.response>"u"&&(t.response=(0,y.isJsonRpcError)(e)?{error:e.error}:{result:e.result},this.records.set(t.id,t),this.persist(),this.events.emit(G,t))},this.get=async(e,t)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:e,id:t}),await this.getRecord(t)),this.delete=(e,t)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:t}),this.values.forEach((i=>{if(i.topic===e){if(typeof t<"u"&&i.id!==t)return;this.records.delete(i.id),this.events.emit(B,i)}})),this.persist()},this.exists=async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=(0,a.U5)(t,this.name)}get context(){return(0,a.oI)(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:(0,y.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:t}=(0,p.GuA)("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(H)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:e}=(0,p.GuA)("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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(F,(e=>{const t=F;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})})),this.events.on(G,(e=>{const t=G;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})})),this.events.on(B,(e=>{const t=B;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})})),this.core.heartbeat.on(n.li.pulse,(()=>{this.cleanup()}))}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach((t=>{(0,c.toMiliseconds)(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(B,t,!1),e=!0)})),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}class bi extends h.Vx{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new s.EventEmitter,this.name="expirer",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=_,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>this.expirations.set(e.target,e))),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=e=>{try{const t=this.formatTarget(e);return typeof this.getExpiration(t)<"u"}catch{return!1}},this.set=(e,t)=>{this.isInitialized();const i=this.formatTarget(e),s={target:i,expiry:t};this.expirations.set(i,s),this.checkExpiry(i,s),this.events.emit(J.created,{target:i,expiration:s})},this.get=e=>{this.isInitialized();const t=this.formatTarget(e);return this.getExpiration(t)},this.del=e=>{if(this.isInitialized(),this.has(e)){const t=this.formatTarget(e),i=this.getExpiration(t);this.expirations.delete(t),this.events.emit(J.deleted,{target:t,expiration:i})}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=(0,a.U5)(t,this.name)}get context(){return(0,a.oI)(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("string"==typeof e)return(0,p.ADD)(e);if("number"==typeof e)return(0,p.gOF)(e);const{message:t}=(0,p.GuA)("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(J.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:e}=(0,p.GuA)("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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:t}=(0,p.GuA)("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(t),new Error(t)}return t}checkExpiry(e,t){const{expiry:i}=t;(0,c.toMiliseconds)(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(J.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach(((e,t)=>this.checkExpiry(t,e)))}registerEventListeners(){this.core.heartbeat.on(n.li.pulse,(()=>this.checkExpirations())),this.events.on(J.created,(e=>{const t=J.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(J.expired,(e=>{const t=J.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(J.deleted,(e=>{const t=J.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}))}isInitialized(){if(!this.initialized){const{message:e}=(0,p.GuA)("NOT_INITIALIZED",this.name);throw new Error(e)}}}class fi extends h.zl{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,this.name="verify-api",this.verifyUrlV3=Z,this.storagePrefix=_,this.version=2,this.init=async()=>{var e;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&(0,c.toMiliseconds)(null==(e=this.publicKey)?void 0:e.expiresAt){if(!(0,p.BdH)()||this.isDevEnv)return;const t=window.location.origin,{id:i,decryptedId:s}=e,r=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${t}&id=${i}&decryptedId=${s}`;try{const e=(0,w.getDocument)(),t=this.startAbortTimer(5*c.ONE_SECOND),s=await new Promise(((s,n)=>{const o=()=>{window.removeEventListener("message",h),e.body.removeChild(a),n("attestation aborted")};this.abortController.signal.addEventListener("abort",o);const a=e.createElement("iframe");a.src=r,a.style.display="none",a.addEventListener("error",o,{signal:this.abortController.signal});const h=r=>{if(r.data&&"string"==typeof r.data)try{const n=JSON.parse(r.data);if("verify_attestation"===n.type){if((0,g.Cq)(n.attestation).payload.id!==i)return;clearInterval(t),e.body.removeChild(a),this.abortController.signal.removeEventListener("abort",o),window.removeEventListener("message",h),s(null===n.attestation?"":n.attestation)}}catch(e){this.logger.warn(e)}};e.body.appendChild(a),window.addEventListener("message",h,{signal:this.abortController.signal})}));return this.logger.debug("jwt attestation",s),s}catch(e){this.logger.warn(e)}return""},this.resolve=async e=>{if(this.isDevEnv)return"";const{attestationId:t,hash:i,encryptedId:s}=e;if(""===t)return void this.logger.debug("resolve: attestationId is empty, skipping");if(t){if((0,g.Cq)(t).payload.id!==s)return;const e=await this.isValidJwtAttestation(t);if(e)return e.isVerified?e:void this.logger.warn("resolve: jwt attestation: origin url not verified")}if(!i)return;const r=this.getVerifyUrl(e?.verifyUrl);return this.fetchAttestation(i,r)},this.fetchAttestation=async(e,t)=>{this.logger.debug(`resolving attestation: ${e} from url: ${t}`);const i=this.startAbortTimer(5*c.ONE_SECOND),s=await fetch(`${t}/attestation/${e}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(i),200===s.status?await s.json():void 0},this.getVerifyUrl=e=>{let t=e||W;return Q.includes(t)||(this.logger.info(`verify url: ${t}, not included in trusted list, assigning default: ${W}`),t=W),t},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const e=this.startAbortTimer(c.FIVE_SECONDS),t=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(e),await t.json()}catch(e){this.logger.warn(e)}},this.persistPublicKey=async e=>{this.logger.debug("persisting public key to local storage",e),await this.store.setItem(this.storeKey,e),this.publicKey=e},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 e=>{const t=await this.getPublicKey();try{if(t)return this.validateAttestation(e,t)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}const i=await this.fetchAndPersistPublicKey();try{if(i)return this.validateAttestation(e,i)}catch(e){this.logger.error(e),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 e=>{const t=await this.fetchPublicKey();t&&(await this.persistPublicKey(t),e(t))}));const e=await this.fetchPromise;return this.fetchPromise=void 0,e},this.validateAttestation=(e,t)=>{const i=(0,p.U0i)(e,t.publicKey),s={hasExpired:(0,c.toMiliseconds)(i.exp)this.abortController.abort()),(0,c.toMiliseconds)(e))}}class wi extends h.GF{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.context="echo",this.registerDeviceToken=async e=>{const{clientId:t,token:i,notificationType:s,enableEncrypted:r=!1}=e,n=`https://echo.walletconnect.com/${this.projectId}/clients`;await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t,type:s,token:i,always_raw:r})})},this.logger=(0,a.U5)(t,this.context)}}var vi=Object.defineProperty,_i=Object.getOwnPropertySymbols,Ei=Object.prototype.hasOwnProperty,Ii=Object.prototype.propertyIsEnumerable,Pi=(e,t,i)=>t in e?vi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,xi=(e,t)=>{for(var i in t||(t={}))Ei.call(t,i)&&Pi(e,i,t[i]);if(_i)for(var i of _i(t))Ii.call(t,i)&&Pi(e,i,t[i]);return e};class Ti extends h.$Q{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,this.context="event-client",this.storagePrefix=_,this.storageVersion=.1,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!(0,p.w8K)())try{const e={eventId:(0,p.gZm)(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:(0,p.ojD)(this.core.relayer.protocol,this.core.relayer.version,k)}}};await this.sendEvent([e])}catch(e){this.logger.warn(e)}},this.createEvent=e=>{const{event:t="ERROR",type:i="",properties:{topic:s,trace:r}}=e,n=(0,p.gZm)(),o=this.core.projectId||"",a=Date.now(),h=xi({eventId:n,timestamp:a,props:{event:t,type:i,properties:{topic:s,trace:r}},bundleId:o,domain:this.getAppDomain()},this.setMethods(n));return this.telemetryEnabled&&(this.events.set(n,h),this.shouldPersist=!0),h},this.getEvent=e=>{const{eventId:t,topic:i}=e;if(t)return this.events.get(t);const s=Array.from(this.events.values()).find((e=>e.props.properties.topic===i));return s?xi(xi({},s),this.setMethods(s.eventId)):void 0},this.deleteEvent=e=>{const{eventId:t}=e;this.events.delete(t),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(n.li.pulse,(async()=>{this.shouldPersist&&await this.persist(),this.events.forEach((e=>{(0,c.fromMiliseconds)(Date.now())-(0,c.fromMiliseconds)(e.timestamp)>86400&&(this.events.delete(e.eventId),this.shouldPersist=!0)}))}))},this.setMethods=e=>({addTrace:t=>this.addTrace(e,t),setError:t=>this.setError(e,t)}),this.addTrace=(e,t)=>{const i=this.events.get(e);i&&(i.props.properties.trace.push(t),this.events.set(e,i),this.shouldPersist=!0)},this.setError=(e,t)=>{const i=this.events.get(e);i&&(i.props.type=t,i.timestamp=Date.now(),this.events.set(e,i),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 e=await this.core.storage.getItem(this.storageKey)||[];if(!e.length)return;e.forEach((e=>{this.events.set(e.eventId,xi(xi({},e),this.setMethods(e.eventId)))}))}catch(e){this.logger.warn(e)}},this.submit=async()=>{if(!this.telemetryEnabled||0===this.events.size)return;const e=[];for(const[t,i]of this.events)i.props.type&&e.push(i);if(0!==e.length)try{if((await this.sendEvent(e)).ok)for(const t of e)this.events.delete(t.eventId),this.shouldPersist=!0}catch(e){this.logger.warn(e)}},this.sendEvent=async e=>{const t=this.getAppDomain()?"":"&sp=desktop";return await fetch(`https://pulse.walletconnect.org/batch?projectId=${this.core.projectId}&st=events_sdk&sv=js-${k}${t}`,{method:"POST",body:JSON.stringify(e)})},this.getAppDomain=()=>(0,p.lFF)().url,this.logger=(0,a.U5)(t,this.context),this.telemetryEnabled=i,i?this.restore().then((async()=>{await this.submit(),this.setEventListeners()})):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var Si=Object.defineProperty,Oi=Object.getOwnPropertySymbols,Ai=Object.prototype.hasOwnProperty,Ri=Object.prototype.propertyIsEnumerable,zi=(e,t,i)=>t in e?Si(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Ci=(e,t)=>{for(var i in t||(t={}))Ai.call(t,i)&&zi(e,i,t[i]);if(Oi)for(var i of Oi(t))Ri.call(t,i)&&zi(e,i,t[i]);return e};class Di extends h.ZP{constructor(e){var t;super(e),this.protocol="wc",this.version=2,this.name=v,this.events=new s.EventEmitter,this.initialized=!1,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.dispatchEnvelope=({topic:e,message:t,sessionExists:i})=>{if(!e||!t)return;const s={topic:e,message:t,publishedAt:Date.now(),transportType:N.link_mode};this.relayer.onLinkMessageEvent(s,{sessionExists:i})},this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||O,this.customStoragePrefix=null!=e&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=(0,a.iP)({level:"string"==typeof e?.logger&&e.logger?e.logger:E,name:v}),{logger:r,chunkLoggerController:h}=(0,a.D5)({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=h,null!=(t=this.logChunkController)&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var e,t;null!=(e=this.logChunkController)&&e.downloadLogsBlobInBrowser&&(null==(t=this.logChunkController)||t.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=(0,a.U5)(r,this.name),this.heartbeat=new n.VH,this.crypto=new Ct(this,this.logger,e?.keychain),this.history=new mi(this,this.logger),this.expirer=new bi(this,this.logger),this.storage=null!=e&&e.storage?e.storage:new o.A(Ci(Ci({},I),e?.storageOptions)),this.relayer=new ai({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new yi(this,this.logger),this.verify=new fi(this,this.logger,this.storage),this.echoClient=new wi(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Ti(this,this.logger,e?.telemetryEnabled)}static async init(e){const t=new Di(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem("WALLETCONNECT_CLIENT_ID",i),t}get context(){return(0,a.oI)(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return null==(e=this.logChunkController)?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(M,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(M)||[],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 ki=Di}}]);