UNPKG

@walletconnect/core

Version:
1 lines 95.6 kB
import Yi,{EventEmitter as ie}from"events";import{HEARTBEAT_EVENTS as se,HeartBeat as Ji}from"@walletconnect/heartbeat";import Xi from"@walletconnect/keyvaluestorage";import{generateChildLogger as F,getLoggerContext as B,getDefaultLoggerOptions as Zi,generatePlatformLogger as Qi}from"@walletconnect/logger";import{IMessageTracker as es,IPublisher as ts,ISubscriber as is,IRelayer as ss,IStore as rs,IJsonRpcHistory as ns,IExpirer as os,IVerify as as,IEchoClient as cs,IEventClient as hs,ICore as ls}from"@walletconnect/types";import{ONE_DAY as re,SIX_HOURS as us,THIRTY_DAYS as Re,FIVE_SECONDS as Ae,THIRTY_SECONDS as xe,toMiliseconds as $,ONE_MINUTE as it,ONE_SECOND as Q,FIVE_MINUTES as le,fromMiliseconds as st}from"@walletconnect/time";import{safeJsonStringify as ds,safeJsonParse as rt}from"@walletconnect/safe-json";import*as Ie from"@walletconnect/relay-auth";import{decodeJWT as nt}from"@walletconnect/relay-auth";import{mapToObj as Ne,objToMap as $e,getInternalError as b,generateRandomBytes32 as ze,generateKeyPair as ps,deriveSymKey as gs,hashKey as ys,validateEncoding as bs,isTypeTwoEnvelope as ot,encodeTypeTwoEnvelope as ms,isTypeOneEnvelope as at,encrypt as fs,validateDecoding as Ds,decodeTypeTwoEnvelope as vs,decrypt as _s,deserialize as ct,decodeTypeByte as ws,BASE64 as ht,BASE16 as Es,hashMessage as Te,getRelayProtocolApi as ne,getRelayProtocolName as Ce,isUndefined as ue,createExpiringPromise as H,getSdkError as de,sleep as Is,createLogger as Ts,isAndroid as Cs,getAppId as lt,isIos as Ps,isOnline as ut,calcExpiry as pe,isNode as dt,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 gt,createDelayedPromise as zs,engineEvent as Le,isExpired as yt,isValidParams as ke,isValidUrl as Ls,isValidString as ks,formatTopicTarget as js,formatIdTarget as Us,isTestRun as bt,isBrowser as Fs,verifyP256Jwt as Ms,uuidv4 as mt,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 ft,isJsonRpcResponse as Dt,formatJsonRpcResult as vt,formatJsonRpcRequest as _t,formatJsonRpcError as Gs,isJsonRpcResult as Ws,isJsonRpcError as wt}from"@walletconnect/jsonrpc-utils";import Hs from"@walletconnect/jsonrpc-ws-connection";import{getDocument as Ys}from"@walletconnect/window-getters";const Ue="wc",Fe=2,ge="core",W=`${Ue}@2:${ge}:`,Et={name:ge,logger:"error"},It={database:":memory:"},Tt="crypto",Me="client_ed25519_seed",Ct=re,Pt="keychain",St="0.3",Ot="messages",Rt="0.3",At=us,xt="publisher",Nt="irn",$t="error",Ke="wss://relay.walletconnect.org",zt="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"},Lt="_subscription",M={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},kt=.1,Js={database:":memory:"},Pe="2.22.2",Xs=1e4,ee={link_mode:"link_mode",relay:"relay"},ye={inbound:"inbound",outbound:"outbound"},jt="0.3",Ut="WALLETCONNECT_CLIENT_ID",Be="WALLETCONNECT_LINK_MODE_APPS",j={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Zs=Re,Ft="subscription",Mt="0.3",Qs=Ae*1e3,Kt="pairing",Bt="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"},Vt="history",qt="0.3",Gt="expirer",q={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},Wt="0.3",tr=re,Ht="verify-api",ir="https://verify.walletconnect.com",Yt="https://verify.walletconnect.org",be=Yt,Jt=`${be}/v3`,Xt=[ir,Yt],Zt="echo",Qt="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",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},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",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},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"},ei=.1,ti="event-client",ii=86400,si="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 g(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,w=0,E=u.length;w!==E&&u[w]===0;)w++,m++;for(var L=(E-w)*l+1>>>0,I=new Uint8Array(L);w!==E;){for(var k=u[w],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,w++}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,w=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<w)&&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");w=k,m++}if(u[m]!==" "){for(var S=E-w;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 _(u){var m=y(u);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:g,decodeUnsafe:y,decode:_}}var hr=cr,lr=hr;const ri=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 pr{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 gr{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 ni(this,e)}}class yr{constructor(e){this.decoders=e}or(e){return ni(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 ni=(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 pr(e,t,i),this.decoder=new gr(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=>ri(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 g=s[r[l]];if(g===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<t|g,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},x=({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 _r=x({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var wr=Object.freeze({__proto__:null,base2:_r});const Er=x({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=x({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Sr=x({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Or=Object.freeze({__proto__:null,base16:Pr,base16upper:Sr});const Rr=x({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ar=x({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),xr=x({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Nr=x({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),$r=x({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),zr=x({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Lr=x({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),kr=x({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),jr=x({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=x({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Wr=x({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Hr=x({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Yr=x({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Jr=Object.freeze({__proto__:null,base64:Gr,base64pad:Wr,base64url:Hr,base64urlpad:Yr});const oi=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=oi.reduce((r,e,t)=>(r[t]=e,r),[]),Zr=oi.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=ci,ai=128,nn=127,on=~nn,an=Math.pow(2,31);function ci(r,e,t){e=e||[],t=t||0;for(var i=t;r>=an;)e[t++]=r&255|ai,r/=128;for(;r&on;)e[t++]=r&255|ai,r>>>=7;return e[t]=r|0,ci.bytes=t-i+1,e}var cn=Ve,hn=128,hi=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&hi)<<s:(o&hi)*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),pn=Math.pow(2,28),gn=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<pn?4:r<gn?5:r<yn?6:r<bn?7:r<mn?8:r<fn?9:10},vn={encode:rn,decode:cn,encodingLength:Dn},li=vn;const ui=(r,e,t=0)=>(li.encode(r,e,t),e),di=r=>li.encodingLength(r),qe=(r,e)=>{const t=e.byteLength,i=di(r),s=i+di(t),n=new Uint8Array(s+t);return ui(r,n,0),ui(t,n,i),n.set(e,s),new _n(r,t,e,n)};class _n{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 wn(r,e,t);class wn{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 gi=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),En=pi({name:"sha2-256",code:18,encode:gi("SHA-256")}),In=pi({name:"sha2-512",code:19,encode:gi("SHA-512")});var Tn=Object.freeze({__proto__:null,sha256:En,sha512:In});const yi=0,Cn="identity",bi=ri,Pn=r=>qe(yi,bi(r)),Sn={code:yi,name:Cn,encode:bi,digest:Pn};var On=Object.freeze({__proto__:null,identity:Sn});new TextEncoder,new TextDecoder;const mi={...vr,...wr,...Ir,...Cr,...Or,...Ur,...Kr,...qr,...Jr,...sn};({...Tn,...On});function fi(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?fi(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function Di(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const vi=Di("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ge=Di("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:vi,"utf-8":vi,hex:mi.base16,latin1:Ge,ascii:Ge,binary:Ge,...mi};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?fi(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",Pt),J(this,"version",St),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=F(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,R=(r,e,t)=>Ln(r,typeof e!="symbol"?e+"":e,t);class wi{constructor(e,t,i){this.core=e,this.logger=t,R(this,"name",Tt),R(this,"keychain"),R(this,"randomSessionIdentifier",ze()),R(this,"initialized",!1),R(this,"clientId"),R(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),R(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),R(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const s=await this.getClientSeed(),n=Ie.generateKeyPair(s),o=Ie.encodeIss(n.publicKey);return this.clientId=o,o}),R(this,"generateKeyPair",()=>{this.isInitialized();const s=ps();return this.setPrivateKey(s.publicKey,s.privateKey)}),R(this,"signJWT",async s=>{this.isInitialized();const n=await this.getClientSeed(),o=Ie.generateKeyPair(n),a=this.randomSessionIdentifier,c=Ct;return await Ie.signJWT(a,s,c,o)}),R(this,"generateSharedKey",(s,n,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=gs(a,n);return this.setSymKey(c,o)}),R(this,"setSymKey",async(s,n)=>{this.isInitialized();const o=n||ys(s);return await this.keychain.set(o,s),o}),R(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),R(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),R(this,"encode",async(s,n,o)=>{this.isInitialized();const a=bs(o),c=ds(n);if(ot(a))return ms(c,o?.encoding);if(at(a)){const y=a.senderPublicKey,_=a.receiverPublicKey;s=await this.generateSharedKey(y,_)}const h=this.getSymKey(s),{type:l,senderPublicKey:g}=a;return fs({type:l,symKey:h,message:c,senderPublicKey:g,encoding:o?.encoding})}),R(this,"decode",async(s,n,o)=>{this.isInitialized();const a=Ds(n,o);if(ot(a)){const c=vs(n,o?.encoding);return rt(c)}if(at(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 rt(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),R(this,"getPayloadType",(s,n=ht)=>{const o=ct({encoded:s,encoding:n});return ws(o.type)}),R(this,"getPayloadSenderPublicKey",(s,n=ht)=>{const o=ct({encoded:s,encoding:n});return o.senderPublicKey?Vs(o.senderPublicKey,Es):void 0}),this.core=e,this.logger=F(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,Ei=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(Ei)for(var t of Ei(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 Ii extends es{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",Ot),K(this,"version",Rt),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=F(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,Ti=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(Ti)for(var t of Ti(e))Hn.call(e,t)&&He(r,t,e[t]);return r},Ci=(r,e)=>qn(r,Gn(e)),G=(r,e,t)=>He(r,typeof e!="symbol"?e+"":e,t);class Yn extends ts{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,G(this,"events",new ie),G(this,"name",xt),G(this,"queue",new Map),G(this,"publishTimeout",$(it)),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 g=n?.ttl||At,y=n?.prompt||!1,_=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:g,prompt:y,tag:_,attestation:n?.attestation},n?.tvf)},w=`Failed to publish payload, please try again. id:${u} tag:${_}`;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:${_}`);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,w)}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:g,tvf:y,publishMethod:_,prompt:u,tag:m,ttl:D=le}=l,w=l.id||je().toString(),E=ne(Ce().protocol),L=_||E.publish,I={id:w,method:L,params:ce(Ci(ce({},h),{ttl:D,prompt:u,tag:m,attestation:g}),y)},k=`Failed to publish custom payload, please try again. id:${w} 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 we;((we=I.id)==null?void 0:we.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,we)=>{this.rpcPublish(I,l).then(Z).catch(Ee=>{this.logger.warn(Ee,Ee?.message),we(Ee)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${L} id:${w} tag:${m}`);try{await te,this.events.removeListener(C.publish,O)}catch(Z){this.queue.set(w,{request:I,opts:l,attempt:1}),this.logger.warn(Z,Z?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:w,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(w)}}),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=F(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,Ci(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,Pi=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(Pi)for(var t of Pi(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 Si extends is{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",Ft),f(this,"version",Mt),f(this,"pending",new Map),f(this,"cached",[]),f(this,"initialized",!1),f(this,"storagePrefix",W),f(this,"subscribeTimeout",$(it)),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(j.created,async i=>{const s=j.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()}),this.events.on(j.deleted,async i=>{const s=j.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()})}),this.relayer=e,this.logger=F(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(g=>this.logger.warn(g))},$(Q)),o;const h=new Promise(async g=>{const y=_=>{_.topic===e&&(this.events.removeListener(j.created,y),g(_.id))};this.events.on(j.created,y);try{const _=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(j.created,y),g(_)}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(j.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(j.deleted,Je(fe({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(j.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(j.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 Is($(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,Oi=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,Ri=(r,e)=>{for(var t in e||(e={}))no.call(e,t)&&Xe(r,t,e[t]);if(Oi)for(var t of Oi(e))oo.call(e,t)&&Xe(r,t,e[t]);return r},p=(r,e,t)=>Xe(r,typeof e!="symbol"?e+"":e,t);class Ai extends ss{constructor(e){var t;super(e),p(this,"protocol","wc"),p(this,"version",2),p(this,"core"),p(this,"logger"),p(this,"events",new ie),p(this,"provider"),p(this,"messages"),p(this,"subscriber"),p(this,"publisher"),p(this,"name",zt),p(this,"transportExplicitlyClosed",!1),p(this,"initialized",!1),p(this,"connectionAttemptInProgress",!1),p(this,"relayUrl"),p(this,"projectId"),p(this,"packageName"),p(this,"bundleId"),p(this,"hasExperiencedNetworkDisruption",!1),p(this,"pingTimeout"),p(this,"heartBeatTimeout",$(xe+Ae)),p(this,"reconnectTimeout"),p(this,"connectPromise"),p(this,"reconnectInProgress",!1),p(this,"requestsInFlight",[]),p(this,"connectTimeout",$(Q*15)),p(this,"request",async i=>{var s,n;this.logger.debug("Publishing Request Payload");const o=i.id||je().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:i.method,topic:(s=i.params)==null?void 0:s.topic},"relayer.request - publishing...");const a=`${o}:${((n=i.params)==null?void 0:n.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(i);return this.requestsInFlight=this.requestsInFlight.filter(h=>h!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),p(this,"resetPingTimeout",()=>{dt()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var i,s,n,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(n=(s=(i=this.provider)==null?void 0:i.connection)==null?void 0:s.socket)==null?void 0:n.terminate)==null||o.call(n)}catch(a){this.logger.warn(a,a?.message)}},this.heartBeatTimeout))}),p(this,"onPayloadHandler",i=>{this.onProviderPayload(i),this.resetPingTimeout()}),p(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(C.connect)}),p(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),p(this,"onProviderErrorHandler",i=>{this.logger.fatal(`Fatal socket error: ${i.message}`),this.events.emit(C.error,i),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),p(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=Ts({logger:(t=e.logger)!=null?t:$t,name:this.name}),this.messages=new Ii(this.logger,e.core),this.subscriber=new Si(this,this.logger),this.publisher=new Yn(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Ke,Cs()?this.packageName=lt():Ps()&&(this.bundleId=lt()),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(j.created,h),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(j.created,h)}),new Promise(async(l,g)=>{a=await this.subscriber.subscribe(e,Ri({internal:{throwOnFailedPublish:o}},t)).catch(y=>{o&&g(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