@walletconnect/core
Version:
Core for WalletConnect Protocol
1 lines • 95.2 kB
JavaScript
import Ji,{EventEmitter as ie}from"events";import{HEARTBEAT_EVENTS as se,HeartBeat as Xi}from"@walletconnect/heartbeat";import Zi from"@walletconnect/keyvaluestorage";import{generateChildLogger as j,getLoggerContext as B,pino as Qi,getDefaultLoggerOptions as it,generatePlatformLogger as es}from"@walletconnect/logger";import{IMessageTracker as ts,IPublisher as is,ISubscriber as ss,IRelayer as rs,IStore as ns,IJsonRpcHistory as os,IExpirer as as,IVerify as cs,IEchoClient as hs,IEventClient as ls,ICore as us}from"@walletconnect/types";import{ONE_DAY as re,SIX_HOURS as ds,THIRTY_DAYS as Re,FIVE_SECONDS as Ae,THIRTY_SECONDS as xe,toMiliseconds as $,ONE_MINUTE as st,ONE_SECOND as Q,FIVE_MINUTES as le,fromMiliseconds as rt}from"@walletconnect/time";import{safeJsonStringify as gs,safeJsonParse as nt}from"@walletconnect/safe-json";import*as Ie from"@walletconnect/relay-auth";import{decodeJWT as ot}from"@walletconnect/relay-auth";import{mapToObj as Ne,objToMap as $e,getInternalError as b,generateRandomBytes32 as ze,generateKeyPair as ps,deriveSymKey as ys,hashKey as bs,validateEncoding as ms,isTypeTwoEnvelope as at,encodeTypeTwoEnvelope as fs,isTypeOneEnvelope as ct,encrypt as Ds,validateDecoding as vs,decodeTypeTwoEnvelope as ws,decrypt as _s,deserialize as ht,decodeTypeByte as Es,BASE64 as lt,BASE16 as Is,hashMessage as Te,getRelayProtocolApi as ne,getRelayProtocolName as Ce,isUndefined as ue,createExpiringPromise as H,getSdkError as de,sleep as Ts,isAndroid as Cs,getAppId as ut,isIos as Ps,isOnline as dt,calcExpiry as ge,isNode as gt,formatRelayRpcUrl as Ss,subscribeToNetworkChange as Os,isAppVisible as Rs,isProposalStruct as As,isSessionStruct as xs,parseExpirerTarget as Ns,TYPE_1 as $s,formatUri as pt,parseUri as yt,createDelayedPromise as zs,engineEvent as Le,isExpired as bt,isValidParams as ke,isValidUrl as Ls,isValidString as ks,formatTopicTarget as js,formatIdTarget as Us,isTestRun as mt,isBrowser as Fs,verifyP256Jwt as Ms,uuidv4 as ft,formatUA as Ks,getAppMetadata as Bs}from"@walletconnect/utils";import{toString as Vs}from"uint8arrays";import{JsonRpcProvider as qs}from"@walletconnect/jsonrpc-provider";import{getBigIntRpcId as je,isJsonRpcRequest as Dt,isJsonRpcResponse as vt,formatJsonRpcResult as wt,formatJsonRpcRequest as _t,formatJsonRpcError as Gs,isJsonRpcResult as Ws,isJsonRpcError as Et}from"@walletconnect/jsonrpc-utils";import Hs from"@walletconnect/jsonrpc-ws-connection";import{getDocument as Ys}from"@walletconnect/window-getters";const Ue="wc",Fe=2,pe="core",W=`${Ue}@2:${pe}:`,It={name:pe,logger:"error"},Tt={database:":memory:"},Ct="crypto",Me="client_ed25519_seed",Pt=re,St="keychain",Ot="0.3",Rt="messages",At="0.3",xt=ds,Nt="publisher",$t="irn",zt="error",Ke="wss://relay.walletconnect.org",Lt="relayer",C={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"},kt="_subscription",M={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},jt=.1,Js={database:":memory:"},Pe="2.21.8",Xs=1e4,ee={link_mode:"link_mode",relay:"relay"},ye={inbound:"inbound",outbound:"outbound"},Ut="0.3",Ft="WALLETCONNECT_CLIENT_ID",Be="WALLETCONNECT_LINK_MODE_APPS",U={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Zs=Re,Mt="subscription",Kt="0.3",Qs=Ae*1e3,Bt="pairing",Vt="0.3",er=Re,oe={wc_pairingDelete:{req:{ttl:re,prompt:!1,tag:1e3},res:{ttl:re,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:xe,prompt:!1,tag:1002},res:{ttl:xe,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:re,prompt:!1,tag:0},res:{ttl:re,prompt:!1,tag:0}}},ae={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},V={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},qt="history",Gt="0.3",Wt="expirer",q={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},Ht="0.3",tr=re,Yt="verify-api",ir="https://verify.walletconnect.com",Jt="https://verify.walletconnect.org",be=Jt,Xt=`${be}/v3`,Zt=[ir,Jt],Qt="echo",ei="https://echo.walletconnect.com",sr="event-client",Y={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"},X={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"},rr={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"},nr={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"},or={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"},ar={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"},ti=.1,ii="event-client",si=86400,ri="https://pulse.walletconnect.org/batch";function cr(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 a=r.length,c=r.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function p(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";for(var m=0,D=0,_=0,E=u.length;_!==E&&u[_]===0;)_++,m++;for(var L=(E-_)*l+1>>>0,I=new Uint8Array(L);_!==E;){for(var k=u[_],T=0,S=L-1;(k!==0||T<D)&&S!==-1;S--,T++)k+=256*I[S]>>>0,I[S]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");D=T,_++}for(var O=L-D;O!==L&&I[O]===0;)O++;for(var te=c.repeat(m);O<L;++O)te+=r.charAt(I[O]);return te}function y(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;var m=0;if(u[m]!==" "){for(var D=0,_=0;u[m]===c;)D++,m++;for(var E=(u.length-m)*h+1>>>0,L=new Uint8Array(E);u[m];){var I=t[u.charCodeAt(m)];if(I===255)return;for(var k=0,T=E-1;(I!==0||k<_)&&T!==-1;T--,k++)I+=a*L[T]>>>0,L[T]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");_=k,m++}if(u[m]!==" "){for(var S=E-_;S!==E&&L[S]===0;)S++;for(var O=new Uint8Array(D+(E-S)),te=D;S!==E;)O[te++]=L[S++];return O}}}function w(u){var m=y(u);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:y,decode:w}}var hr=cr,lr=hr;const ni=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")},ur=r=>new TextEncoder().encode(r),dr=r=>new TextDecoder().decode(r);class gr{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 pr{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 oi(this,e)}}class yr{constructor(e){this.decoders=e}or(e){return oi(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 oi=(r,e)=>new yr({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});class br{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new gr(e,t,i),this.decoder=new pr(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Se=({name:r,prefix:e,encode:t,decode:i})=>new br(r,e,t,i),me=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:s}=lr(t,e);return Se({prefix:r,name:e,encode:i,decode:n=>ni(s(n))})},mr=(r,e,t,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=r.length;for(;r[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,h=0;for(let l=0;l<n;++l){const p=s[r[l]];if(p===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<t|p,a+=t,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},fr=(r,e,t)=>{const i=e[e.length-1]==="=",s=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,n+=e[s&a>>o];if(o&&(n+=e[s&a<<t-o]),i)for(;n.length*t&7;)n+="=";return n},A=({name:r,prefix:e,bitsPerChar:t,alphabet:i})=>Se({prefix:e,name:r,encode(s){return fr(s,i,t)},decode(s){return mr(s,i,t,r)}}),Dr=Se({prefix:"\0",name:"identity",encode:r=>dr(r),decode:r=>ur(r)});var vr=Object.freeze({__proto__:null,identity:Dr});const wr=A({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var _r=Object.freeze({__proto__:null,base2:wr});const Er=A({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ir=Object.freeze({__proto__:null,base8:Er});const Tr=me({prefix:"9",name:"base10",alphabet:"0123456789"});var Cr=Object.freeze({__proto__:null,base10:Tr});const Pr=A({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Sr=A({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Or=Object.freeze({__proto__:null,base16:Pr,base16upper:Sr});const Rr=A({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ar=A({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),xr=A({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Nr=A({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),$r=A({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),zr=A({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Lr=A({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),kr=A({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),jr=A({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ur=Object.freeze({__proto__:null,base32:Rr,base32upper:Ar,base32pad:xr,base32padupper:Nr,base32hex:$r,base32hexupper:zr,base32hexpad:Lr,base32hexpadupper:kr,base32z:jr});const Fr=me({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Mr=me({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Kr=Object.freeze({__proto__:null,base36:Fr,base36upper:Mr});const Br=me({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Vr=me({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var qr=Object.freeze({__proto__:null,base58btc:Br,base58flickr:Vr});const Gr=A({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Wr=A({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Hr=A({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Yr=A({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Jr=Object.freeze({__proto__:null,base64:Gr,base64pad:Wr,base64url:Hr,base64urlpad:Yr});const ai=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}"),Xr=ai.reduce((r,e,t)=>(r[t]=e,r),[]),Zr=ai.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Qr(r){return r.reduce((e,t)=>(e+=Xr[t],e),"")}function en(r){const e=[];for(const t of r){const i=Zr[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const tn=Se({prefix:"\u{1F680}",name:"base256emoji",encode:Qr,decode:en});var sn=Object.freeze({__proto__:null,base256emoji:tn}),rn=hi,ci=128,nn=127,on=~nn,an=Math.pow(2,31);function hi(r,e,t){e=e||[],t=t||0;for(var i=t;r>=an;)e[t++]=r&255|ci,r/=128;for(;r&on;)e[t++]=r&255|ci,r>>>=7;return e[t]=r|0,hi.bytes=t-i+1,e}var cn=Ve,hn=128,li=127;function Ve(r,i){var t=0,i=i||0,s=0,n=i,o,a=r.length;do{if(n>=a)throw Ve.bytes=0,new RangeError("Could not decode varint");o=r[n++],t+=s<28?(o&li)<<s:(o&li)*Math.pow(2,s),s+=7}while(o>=hn);return Ve.bytes=n-i,t}var ln=Math.pow(2,7),un=Math.pow(2,14),dn=Math.pow(2,21),gn=Math.pow(2,28),pn=Math.pow(2,35),yn=Math.pow(2,42),bn=Math.pow(2,49),mn=Math.pow(2,56),fn=Math.pow(2,63),Dn=function(r){return r<ln?1:r<un?2:r<dn?3:r<gn?4:r<pn?5:r<yn?6:r<bn?7:r<mn?8:r<fn?9:10},vn={encode:rn,decode:cn,encodingLength:Dn},ui=vn;const di=(r,e,t=0)=>(ui.encode(r,e,t),e),gi=r=>ui.encodingLength(r),qe=(r,e)=>{const t=e.byteLength,i=gi(r),s=i+gi(t),n=new Uint8Array(s+t);return di(r,n,0),di(t,n,i),n.set(e,s),new wn(r,t,e,n)};class wn{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}}const pi=({name:r,code:e,encode:t})=>new _n(r,e,t);class _n{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?qe(this.code,t):t.then(i=>qe(this.code,i))}else throw Error("Unknown type, must be binary type")}}const yi=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),En=pi({name:"sha2-256",code:18,encode:yi("SHA-256")}),In=pi({name:"sha2-512",code:19,encode:yi("SHA-512")});var Tn=Object.freeze({__proto__:null,sha256:En,sha512:In});const bi=0,Cn="identity",mi=ni,Pn=r=>qe(bi,mi(r)),Sn={code:bi,name:Cn,encode:mi,digest:Pn};var On=Object.freeze({__proto__:null,identity:Sn});new TextEncoder,new TextDecoder;const fi={...vr,..._r,...Ir,...Cr,...Or,...Ur,...Kr,...qr,...Jr,...sn};({...Tn,...On});function Di(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function Rn(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Di(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function vi(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const wi=vi("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ge=vi("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=Rn(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),An={utf8:wi,"utf-8":wi,hex:fi.base16,latin1:Ge,ascii:Ge,binary:Ge,...fi};function xn(r,e="utf8"){const t=An[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Di(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var Nn=Object.defineProperty,$n=(r,e,t)=>e in r?Nn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,J=(r,e,t)=>$n(r,typeof e!="symbol"?e+"":e,t);class _i{constructor(e,t){this.core=e,this.logger=t,J(this,"keychain",new Map),J(this,"name",St),J(this,"version",Ot),J(this,"initialized",!1),J(this,"storagePrefix",W),J(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),J(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),J(this,"set",async(i,s)=>{this.isInitialized(),this.keychain.set(i,s),await this.persist()}),J(this,"get",i=>{this.isInitialized();const s=this.keychain.get(i);if(typeof s>"u"){const{message:n}=b("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return s}),J(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=j(t,this.name)}get context(){return B(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Ne(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?$e(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=b("NOT_INITIALIZED",this.name);throw new Error(e)}}}var zn=Object.defineProperty,Ln=(r,e,t)=>e in r?zn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,x=(r,e,t)=>Ln(r,typeof e!="symbol"?e+"":e,t);class Ei{constructor(e,t,i){this.core=e,this.logger=t,x(this,"name",Ct),x(this,"keychain"),x(this,"randomSessionIdentifier",ze()),x(this,"initialized",!1),x(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),x(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),x(this,"getClientId",async()=>{this.isInitialized();const s=await this.getClientSeed(),n=Ie.generateKeyPair(s);return Ie.encodeIss(n.publicKey)}),x(this,"generateKeyPair",()=>{this.isInitialized();const s=ps();return this.setPrivateKey(s.publicKey,s.privateKey)}),x(this,"signJWT",async s=>{this.isInitialized();const n=await this.getClientSeed(),o=Ie.generateKeyPair(n),a=this.randomSessionIdentifier,c=Pt;return await Ie.signJWT(a,s,c,o)}),x(this,"generateSharedKey",(s,n,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=ys(a,n);return this.setSymKey(c,o)}),x(this,"setSymKey",async(s,n)=>{this.isInitialized();const o=n||bs(s);return await this.keychain.set(o,s),o}),x(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),x(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),x(this,"encode",async(s,n,o)=>{this.isInitialized();const a=ms(o),c=gs(n);if(at(a))return fs(c,o?.encoding);if(ct(a)){const y=a.senderPublicKey,w=a.receiverPublicKey;s=await this.generateSharedKey(y,w)}const h=this.getSymKey(s),{type:l,senderPublicKey:p}=a;return Ds({type:l,symKey:h,message:c,senderPublicKey:p,encoding:o?.encoding})}),x(this,"decode",async(s,n,o)=>{this.isInitialized();const a=vs(n,o);if(at(a)){const c=ws(n,o?.encoding);return nt(c)}if(ct(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;s=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(s),h=_s({symKey:c,encoded:n,encoding:o?.encoding});return nt(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),x(this,"getPayloadType",(s,n=lt)=>{const o=ht({encoded:s,encoding:n});return Es(o.type)}),x(this,"getPayloadSenderPublicKey",(s,n=lt)=>{const o=ht({encoded:s,encoding:n});return o.senderPublicKey?Vs(o.senderPublicKey,Is):void 0}),this.core=e,this.logger=j(t,this.name),this.keychain=i||new _i(this.core,this.logger)}get context(){return B(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(Me)}catch{e=ze(),await this.keychain.set(Me,e)}return xn(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=b("NOT_INITIALIZED",this.name);throw new Error(e)}}}var kn=Object.defineProperty,jn=Object.defineProperties,Un=Object.getOwnPropertyDescriptors,Ii=Object.getOwnPropertySymbols,Fn=Object.prototype.hasOwnProperty,Mn=Object.prototype.propertyIsEnumerable,We=(r,e,t)=>e in r?kn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Kn=(r,e)=>{for(var t in e||(e={}))Fn.call(e,t)&&We(r,t,e[t]);if(Ii)for(var t of Ii(e))Mn.call(e,t)&&We(r,t,e[t]);return r},Bn=(r,e)=>jn(r,Un(e)),K=(r,e,t)=>We(r,typeof e!="symbol"?e+"":e,t);class Ti extends ts{constructor(e,t){super(e,t),this.logger=e,this.core=t,K(this,"messages",new Map),K(this,"messagesWithoutClientAck",new Map),K(this,"name",Rt),K(this,"version",At),K(this,"initialized",!1),K(this,"storagePrefix",W),K(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const s=await this.getRelayerMessagesWithoutClientAck();typeof s<"u"&&(this.messagesWithoutClientAck=s),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}}}),K(this,"set",async(i,s,n)=>{this.isInitialized();const o=Te(s);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(i,a),n===ye.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,Bn(Kn({},c),{[o]:s}))}return await this.persist(),o}),K(this,"get",i=>{this.isInitialized();let s=this.messages.get(i);return typeof s>"u"&&(s={}),s}),K(this,"getWithoutAck",i=>{this.isInitialized();const s={};for(const n of i){const o=this.messagesWithoutClientAck.get(n)||{};s[n]=Object.values(o)}return s}),K(this,"has",(i,s)=>{this.isInitialized();const n=this.get(i),o=Te(s);return typeof n[o]<"u"}),K(this,"ack",async(i,s)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(i);if(typeof n>"u")return;const o=Te(s);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,n),await this.persist()}),K(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=j(e,this.name),this.core=t}get context(){return B(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Ne(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Ne(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?$e(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?$e(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=b("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Vn=Object.defineProperty,qn=Object.defineProperties,Gn=Object.getOwnPropertyDescriptors,Ci=Object.getOwnPropertySymbols,Wn=Object.prototype.hasOwnProperty,Hn=Object.prototype.propertyIsEnumerable,He=(r,e,t)=>e in r?Vn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ce=(r,e)=>{for(var t in e||(e={}))Wn.call(e,t)&&He(r,t,e[t]);if(Ci)for(var t of Ci(e))Hn.call(e,t)&&He(r,t,e[t]);return r},Pi=(r,e)=>qn(r,Gn(e)),G=(r,e,t)=>He(r,typeof e!="symbol"?e+"":e,t);class Yn extends is{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,G(this,"events",new ie),G(this,"name",Nt),G(this,"queue",new Map),G(this,"publishTimeout",$(st)),G(this,"initialPublishTimeout",$(Q*15)),G(this,"needsTransportRestart",!1),G(this,"publish",async(i,s,n)=>{var o,a,c,h,l;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:s,opts:n}});const p=n?.ttl||xt,y=n?.prompt||!1,w=n?.tag||0,u=n?.id||je().toString(),m=ne(Ce().protocol),D={id:u,method:n?.publishMethod||m.publish,params:ce({topic:i,message:s,ttl:p,prompt:y,tag:w,attestation:n?.attestation},n?.tvf&&{tvf:n.tvf})},_=`Failed to publish payload, please try again. id:${u} tag:${w}`;try{ue((o=D.params)==null?void 0:o.prompt)&&((a=D.params)==null||delete a.prompt),ue((c=D.params)==null?void 0:c.tag)&&((h=D.params)==null||delete h.tag);const E=new Promise(async L=>{const I=({id:T})=>{var S;((S=D.id)==null?void 0:S.toString())===T.toString()&&(this.removeRequestFromQueue(T),this.relayer.events.removeListener(C.publish,I),L())};this.relayer.events.on(C.publish,I);const k=H(new Promise((T,S)=>{this.rpcPublish(D,n).then(T).catch(O=>{this.logger.warn(O,O?.message),S(O)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${w}`);try{await k,this.events.removeListener(C.publish,I)}catch(T){this.queue.set(u,{request:D,opts:n,attempt:1}),this.logger.warn(T,T?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:i,message:s,opts:n}}),await H(E,this.publishTimeout,_)}catch(E){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(E),(l=n?.internal)!=null&&l.throwOnFailedPublish)throw E}finally{this.queue.delete(u)}}),G(this,"publishCustom",async i=>{var s,n,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:i});const{payload:h,opts:l={}}=i,{attestation:p,tvf:y,publishMethod:w,prompt:u,tag:m,ttl:D=le}=l,_=l.id||je().toString(),E=ne(Ce().protocol),L=w||E.publish,I={id:_,method:L,params:ce(Pi(ce({},h),{ttl:D,prompt:u,tag:m,attestation:p}),y)},k=`Failed to publish custom payload, please try again. id:${_} tag:${m}`;try{ue((s=I.params)==null?void 0:s.prompt)&&((n=I.params)==null||delete n.prompt),ue((o=I.params)==null?void 0:o.tag)&&((a=I.params)==null||delete a.tag);const T=new Promise(async S=>{const O=({id:Z})=>{var _e;((_e=I.id)==null?void 0:_e.toString())===Z.toString()&&(this.removeRequestFromQueue(Z),this.relayer.events.removeListener(C.publish,O),S())};this.relayer.events.on(C.publish,O);const te=H(new Promise((Z,_e)=>{this.rpcPublish(I,l).then(Z).catch(Ee=>{this.logger.warn(Ee,Ee?.message),_e(Ee)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${L} id:${_} tag:${m}`);try{await te,this.events.removeListener(C.publish,O)}catch(Z){this.queue.set(_,{request:I,opts:l,attempt:1}),this.logger.warn(Z,Z?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:_,payload:h,opts:l}}),await H(T,this.publishTimeout,k)}catch(T){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(T),(c=l?.internal)!=null&&c.throwOnFailedPublish)throw T}finally{this.queue.delete(_)}}),G(this,"on",(i,s)=>{this.events.on(i,s)}),G(this,"once",(i,s)=>{this.events.once(i,s)}),G(this,"off",(i,s)=>{this.events.off(i,s)}),G(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.relayer=e,this.logger=j(t,this.name),this.registerEventListeners()}get context(){return B(this.logger)}async rpcPublish(e,t){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const i=await this.relayer.request(e);return this.relayer.events.emit(C.publish,ce(ce({},e),t)),this.logger.debug("Successfully Published Payload"),i}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{var i;const s=e.attempt+1;this.queue.set(t,Pi(ce({},e),{attempt:s})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(i=e.request.params)==null?void 0:i.tag}, attempt: ${s}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(se.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(C.connection_stalled);return}this.checkQueue()}),this.relayer.on(C.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var Jn=Object.defineProperty,Xn=(r,e,t)=>e in r?Jn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,he=(r,e,t)=>Xn(r,typeof e!="symbol"?e+"":e,t);class Zn{constructor(){he(this,"map",new Map),he(this,"set",(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),he(this,"get",e=>this.map.get(e)||[]),he(this,"exists",(e,t)=>this.get(e).includes(t)),he(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)}),he(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Qn=Object.defineProperty,eo=Object.defineProperties,to=Object.getOwnPropertyDescriptors,Si=Object.getOwnPropertySymbols,io=Object.prototype.hasOwnProperty,so=Object.prototype.propertyIsEnumerable,Ye=(r,e,t)=>e in r?Qn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,fe=(r,e)=>{for(var t in e||(e={}))io.call(e,t)&&Ye(r,t,e[t]);if(Si)for(var t of Si(e))so.call(e,t)&&Ye(r,t,e[t]);return r},Je=(r,e)=>eo(r,to(e)),f=(r,e,t)=>Ye(r,typeof e!="symbol"?e+"":e,t);class Oi extends ss{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,f(this,"subscriptions",new Map),f(this,"topicMap",new Zn),f(this,"events",new ie),f(this,"name",Mt),f(this,"version",Kt),f(this,"pending",new Map),f(this,"cached",[]),f(this,"initialized",!1),f(this,"storagePrefix",W),f(this,"subscribeTimeout",$(st)),f(this,"initialSubscribeTimeout",$(Q*15)),f(this,"clientId"),f(this,"batchSubscribeTopicsLimit",500),f(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),f(this,"subscribe",async(i,s)=>{var n;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}});try{const o=Ce(s),a={topic:i,relay:o,transportType:s?.transportType};(n=s?.internal)!=null&&n.skipSubscribe||this.pending.set(i,a);const c=await this.rpcSubscribe(i,o,s);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),f(this,"unsubscribe",async(i,s)=>{this.isInitialized(),typeof s?.id<"u"?await this.unsubscribeById(i,s.id,s):await this.unsubscribeByTopic(i,s)}),f(this,"isSubscribed",i=>new Promise(s=>{s(this.topicMap.topics.includes(i))})),f(this,"isKnownTopic",i=>new Promise(s=>{s(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(n=>n.topic===i))})),f(this,"on",(i,s)=>{this.events.on(i,s)}),f(this,"once",(i,s)=>{this.events.once(i,s)}),f(this,"off",(i,s)=>{this.events.off(i,s)}),f(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),f(this,"start",async()=>{await this.onConnect()}),f(this,"stop",async()=>{await this.onDisconnect()}),f(this,"restart",async()=>{await this.restore(),await this.onRestart()}),f(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(s=>{i.push(s)}),await this.batchSubscribe(i)}),f(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(se.pulse,async()=>{await this.checkPending()}),this.events.on(U.created,async i=>{const s=U.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()}),this.events.on(U.deleted,async i=>{const s=U.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()})}),this.relayer=e,this.logger=j(t,this.name),this.clientId=""}get context(){return B(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(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=Ce(i);await this.restartToComplete({topic:e,id:t,relay:s}),await this.rpcUnsubscribe(e,t,s);const n=de("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,i){var s,n;const o=await this.getSubscriptionId(e);if((s=i?.internal)!=null&&s.skipSubscribe)return o;(!i||i?.transportType===ee.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const a={method:ne(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(n=i?.internal)==null?void 0:n.throwOnFailedPublish;try{if(i?.transportType===ee.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(p=>this.logger.warn(p))},$(Q)),o;const h=new Promise(async p=>{const y=w=>{w.topic===e&&(this.events.removeListener(U.created,y),p(w.id))};this.events.on(U.created,y);try{const w=await H(new Promise((u,m)=>{this.relayer.request(a).catch(D=>{this.logger.warn(D,D?.message),m(D)}).then(u)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(U.created,y),p(w)}catch{}}),l=await H(h,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return l?o:null}catch(h){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(C.connection_stalled),c)throw h}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:ne(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{await await H(new Promise(s=>{this.relayer.request(i).catch(n=>this.logger.warn(n)).then(s)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(C.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:ne(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let s;try{s=await await H(new Promise((n,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(C.connection_stalled)}return s}rpcUnsubscribe(e,t,i){const s={method:ne(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,Je(fe({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,fe({},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.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,fe({},t)),this.topicMap.set(t.topic,e),this.events.emit(U.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}=b("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(U.deleted,Je(fe({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(U.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<t;i++){const s=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(U.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(t=>{var i;return t.topic===((i=this.subscriptions.get(t.id))==null?void 0:i.topic)})){const{message:t}=b("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){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async t=>Je(fe({},t),{id:await this.getSubscriptionId(t.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 Ts($(Q)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=b("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return Te(e+await this.getClientId())}}var ro=Object.defineProperty,Ri=Object.getOwnPropertySymbols,no=Object.prototype.hasOwnProperty,oo=Object.prototype.propertyIsEnumerable,Xe=(r,e,t)=>e in r?ro(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ai=(r,e)=>{for(var t in e||(e={}))no.call(e,t)&&Xe(r,t,e[t]);if(Ri)for(var t of Ri(e))oo.call(e,t)&&Xe(r,t,e[t]);return r},g=(r,e,t)=>Xe(r,typeof e!="symbol"?e+"":e,t);class xi extends rs{constructor(e){super(e),g(this,"protocol","wc"),g(this,"version",2),g(this,"core"),g(this,"logger"),g(this,"events",new ie),g(this,"provider"),g(this,"messages"),g(this,"subscriber"),g(this,"publisher"),g(this,"name",Lt),g(this,"transportExplicitlyClosed",!1),g(this,"initialized",!1),g(this,"connectionAttemptInProgress",!1),g(this,"relayUrl"),g(this,"projectId"),g(this,"packageName"),g(this,"bundleId"),g(this,"hasExperiencedNetworkDisruption",!1),g(this,"pingTimeout"),g(this,"heartBeatTimeout",$(xe+Ae)),g(this,"reconnectTimeout"),g(this,"connectPromise"),g(this,"reconnectInProgress",!1),g(this,"requestsInFlight",[]),g(this,"connectTimeout",$(Q*15)),g(this,"request",async t=>{var i,s;this.logger.debug("Publishing Request Payload");const n=t.id||je().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(i=t.params)==null?void 0:i.topic},"relayer.request - publishing...");const o=`${n}:${((s=t.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(t);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),g(this,"resetPingTimeout",()=>{gt()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,i,s,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(s=(i=(t=this.provider)==null?void 0:t.connection)==null?void 0:i.socket)==null?void 0:s.terminate)==null||n.call(s)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),g(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),g(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(C.connect)}),g(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),g(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(C.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),g(this,"registerProviderListeners",()=>{this.provider.on(M.payload,this.onPayloadHandler),this.provider.on(M.connect,this.onConnectHandler),this.provider.on(M.disconnect,this.onDisconnectHandler),this.provider.on(M.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?j(e.logger,this.name):Qi(it({level:e.logger||zt})),this.messages=new Ti(this.logger,e.core),this.subscriber=new Oi(this,this.logger),this.publisher=new Yn(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Ke,Cs()?this.packageName=ut():Ps()&&(this.bundleId=ut()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e?.message))}get context(){return B(this.logger)}get connected(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}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:ee.relay},ye.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,t){var i,s,n;this.isInitialized(),(!(t!=null&&t.transportType)||t?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((i=t?.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(s=t?.internal)==null?void 0:s.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const h=l=>{l.topic===e&&(this.subscriber.off(U.created,h),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(U.created,h)}),new Promise(async(l,p)=>{a=await this.subscriber.subscribe(e,Ai({internal:{throwOnFailedPublish:o}},t)).catch(y=>{o&&p(y)})||a,l()})]),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 H(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(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.confirmOnl