UNPKG

@walletconnect/core

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