@walletconnect/core
Version:
Core for WalletConnect Protocol
1 lines • 95.7 kB
JavaScript
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var Z=require("events"),ee=require("@walletconnect/heartbeat"),hi=require("@walletconnect/keyvaluestorage"),m=require("@walletconnect/logger"),V=require("@walletconnect/types"),u=require("@walletconnect/time"),De=require("@walletconnect/safe-json"),me=require("@walletconnect/relay-auth"),c=require("@walletconnect/utils"),li=require("uint8arrays"),ui=require("@walletconnect/jsonrpc-provider"),L=require("@walletconnect/jsonrpc-utils"),gi=require("@walletconnect/jsonrpc-ws-connection"),di=require("@walletconnect/window-getters");function fe(r){return r&&typeof r=="object"&&"default"in r?r:{default:r}}function pi(r){if(r&&r.__esModule)return r;var e=Object.create(null);return r&&Object.keys(r).forEach(function(t){if(t!=="default"){var i=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:function(){return r[t]}})}}),e.default=r,Object.freeze(e)}var yi=fe(Z),Ei=fe(hi),de=pi(me),bi=fe(gi);const _e="wc",ve=2,re="core",K=`${_e}@2:${re}:`,ke={name:re,logger:"error"},Fe={database:":memory:"},Be="crypto",we="client_ed25519_seed",Ve=u.ONE_DAY,Ke="keychain",qe="0.3",Ge="messages",Ye="0.3",Te=u.SIX_HOURS,He="publisher",We="irn",Je="error",Ie="wss://relay.walletconnect.org",Xe="relayer",S={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"},Ze="_subscription",z={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Qe=.1,Di={database:":memory:"},pe="2.19.2",mi=1e4,Q={link_mode:"link_mode",relay:"relay"},ne={inbound:"inbound",outbound:"outbound"},et="0.3",tt="WALLETCONNECT_CLIENT_ID",Ce="WALLETCONNECT_LINK_MODE_APPS",U={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},fi=u.THIRTY_DAYS,it="subscription",st="0.3",_i=u.FIVE_SECONDS*1e3,rt="pairing",nt="0.3",vi=u.THIRTY_DAYS,te={wc_pairingDelete:{req:{ttl:u.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:u.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:u.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:u.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:u.ONE_DAY,prompt:!1,tag:0},res:{ttl:u.ONE_DAY,prompt:!1,tag:0}}},ie={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},k={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},ot="history",at="0.3",ct="expirer",F={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},ht="0.3",wi=u.ONE_DAY,lt="verify-api",Ti="https://verify.walletconnect.com",ut="https://verify.walletconnect.org",oe=ut,gt=`${oe}/v3`,dt=[Ti,ut],pt="echo",yt="https://echo.walletconnect.com",Ii="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"},J={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"},Ci={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"},Ri={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"},Si={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"},Oi={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"},Et=.1,bt="event-client",Dt=86400,mt="https://pulse.walletconnect.org/batch";function Pi(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,h=r.charAt(0),l=Math.log(a)/Math.log(256),g=Math.log(256)/Math.log(a);function p(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var D=0,x=0,C=0,_=d.length;C!==_&&d[C]===0;)C++,D++;for(var j=(_-C)*g+1>>>0,R=new Uint8Array(j);C!==_;){for(var G=d[C],X=0,B=j-1;(G!==0||X<x)&&B!==-1;B--,X++)G+=256*R[B]>>>0,R[B]=G%a>>>0,G=G/a>>>0;if(G!==0)throw new Error("Non-zero carry");x=X,C++}for(var W=j-x;W!==j&&R[W]===0;)W++;for(var ge=h.repeat(D);W<j;++W)ge+=r.charAt(R[W]);return ge}function y(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var D=0;if(d[D]!==" "){for(var x=0,C=0;d[D]===h;)x++,D++;for(var _=(d.length-D)*l+1>>>0,j=new Uint8Array(_);d[D];){var R=t[d.charCodeAt(D)];if(R===255)return;for(var G=0,X=_-1;(R!==0||G<C)&&X!==-1;X--,G++)R+=a*j[X]>>>0,j[X]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");C=G,D++}if(d[D]!==" "){for(var B=_-C;B!==_&&j[B]===0;)B++;for(var W=new Uint8Array(x+(_-B)),ge=x;B!==_;)W[ge++]=j[B++];return W}}}function T(d){var D=y(d);if(D)return D;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:y,decode:T}}var Ai=Pi,Ni=Ai;const ft=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")},xi=r=>new TextEncoder().encode(r),Li=r=>new TextDecoder().decode(r);class Ui{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 $i{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 _t(this,e)}}class zi{constructor(e){this.decoders=e}or(e){return _t(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 _t=(r,e)=>new zi({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});class Mi{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new Ui(e,t,i),this.decoder=new $i(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ye=({name:r,prefix:e,encode:t,decode:i})=>new Mi(r,e,t,i),ae=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:s}=Ni(t,e);return ye({prefix:r,name:e,encode:i,decode:n=>ft(s(n))})},ji=(r,e,t,i)=>{const s={};for(let g=0;g<e.length;++g)s[e[g]]=g;let n=r.length;for(;r[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,h=0,l=0;for(let g=0;g<n;++g){const p=s[r[g]];if(p===void 0)throw new SyntaxError(`Non-${i} character`);h=h<<t|p,a+=t,a>=8&&(a-=8,o[l++]=255&h>>a)}if(a>=t||255&h<<8-a)throw new SyntaxError("Unexpected end of data");return o},ki=(r,e,t)=>{const i=e[e.length-1]==="=",s=(1<<t)-1;let n="",o=0,a=0;for(let h=0;h<r.length;++h)for(a=a<<8|r[h],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},O=({name:r,prefix:e,bitsPerChar:t,alphabet:i})=>ye({prefix:e,name:r,encode(s){return ki(s,i,t)},decode(s){return ji(s,i,t,r)}}),Fi=ye({prefix:"\0",name:"identity",encode:r=>Li(r),decode:r=>xi(r)});var Bi=Object.freeze({__proto__:null,identity:Fi});const Vi=O({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ki=Object.freeze({__proto__:null,base2:Vi});const qi=O({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Gi=Object.freeze({__proto__:null,base8:qi});const Yi=ae({prefix:"9",name:"base10",alphabet:"0123456789"});var Hi=Object.freeze({__proto__:null,base10:Yi});const Wi=O({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ji=O({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Xi=Object.freeze({__proto__:null,base16:Wi,base16upper:Ji});const Zi=O({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Qi=O({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),es=O({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ts=O({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),is=O({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ss=O({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),rs=O({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ns=O({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),os=O({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var as=Object.freeze({__proto__:null,base32:Zi,base32upper:Qi,base32pad:es,base32padupper:ts,base32hex:is,base32hexupper:ss,base32hexpad:rs,base32hexpadupper:ns,base32z:os});const cs=ae({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),hs=ae({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ls=Object.freeze({__proto__:null,base36:cs,base36upper:hs});const us=ae({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),gs=ae({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ds=Object.freeze({__proto__:null,base58btc:us,base58flickr:gs});const ps=O({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ys=O({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Es=O({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),bs=O({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ds=Object.freeze({__proto__:null,base64:ps,base64pad:ys,base64url:Es,base64urlpad:bs});const vt=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}"),ms=vt.reduce((r,e,t)=>(r[t]=e,r),[]),fs=vt.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function _s(r){return r.reduce((e,t)=>(e+=ms[t],e),"")}function vs(r){const e=[];for(const t of r){const i=fs[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const ws=ye({prefix:"\u{1F680}",name:"base256emoji",encode:_s,decode:vs});var Ts=Object.freeze({__proto__:null,base256emoji:ws}),Is=Tt,wt=128,Cs=127,Rs=~Cs,Ss=Math.pow(2,31);function Tt(r,e,t){e=e||[],t=t||0;for(var i=t;r>=Ss;)e[t++]=r&255|wt,r/=128;for(;r&Rs;)e[t++]=r&255|wt,r>>>=7;return e[t]=r|0,Tt.bytes=t-i+1,e}var Os=Re,Ps=128,It=127;function Re(r,i){var t=0,i=i||0,s=0,n=i,o,a=r.length;do{if(n>=a)throw Re.bytes=0,new RangeError("Could not decode varint");o=r[n++],t+=s<28?(o&It)<<s:(o&It)*Math.pow(2,s),s+=7}while(o>=Ps);return Re.bytes=n-i,t}var As=Math.pow(2,7),Ns=Math.pow(2,14),xs=Math.pow(2,21),Ls=Math.pow(2,28),Us=Math.pow(2,35),$s=Math.pow(2,42),zs=Math.pow(2,49),Ms=Math.pow(2,56),js=Math.pow(2,63),ks=function(r){return r<As?1:r<Ns?2:r<xs?3:r<Ls?4:r<Us?5:r<$s?6:r<zs?7:r<Ms?8:r<js?9:10},Fs={encode:Is,decode:Os,encodingLength:ks},Ct=Fs;const Rt=(r,e,t=0)=>(Ct.encode(r,e,t),e),St=r=>Ct.encodingLength(r),Se=(r,e)=>{const t=e.byteLength,i=St(r),s=i+St(t),n=new Uint8Array(s+t);return Rt(r,n,0),Rt(t,n,i),n.set(e,s),new Bs(r,t,e,n)};class Bs{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}}const Ot=({name:r,code:e,encode:t})=>new Vs(r,e,t);class Vs{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?Se(this.code,t):t.then(i=>Se(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Pt=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),Ks=Ot({name:"sha2-256",code:18,encode:Pt("SHA-256")}),qs=Ot({name:"sha2-512",code:19,encode:Pt("SHA-512")});var Gs=Object.freeze({__proto__:null,sha256:Ks,sha512:qs});const At=0,Ys="identity",Nt=ft,Hs=r=>Se(At,Nt(r)),Ws={code:At,name:Ys,encode:Nt,digest:Hs};var Js=Object.freeze({__proto__:null,identity:Ws});new TextEncoder,new TextDecoder;const xt={...Bi,...Ki,...Gi,...Hi,...Xi,...as,...ls,...ds,...Ds,...Ts};({...Gs,...Js});function Xs(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}function Lt(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const Ut=Lt("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Oe=Lt("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=Xs(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Zs={utf8:Ut,"utf-8":Ut,hex:xt.base16,latin1:Oe,ascii:Oe,binary:Oe,...xt};function Qs(r,e="utf8"){const t=Zs[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r,"utf8"):t.decoder.decode(`${t.prefix}${r}`)}var er=Object.defineProperty,tr=(r,e,t)=>e in r?er(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,H=(r,e,t)=>tr(r,typeof e!="symbol"?e+"":e,t);class $t{constructor(e,t){this.core=e,this.logger=t,H(this,"keychain",new Map),H(this,"name",Ke),H(this,"version",qe),H(this,"initialized",!1),H(this,"storagePrefix",K),H(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),H(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),H(this,"set",async(i,s)=>{this.isInitialized(),this.keychain.set(i,s),await this.persist()}),H(this,"get",i=>{this.isInitialized();const s=this.keychain.get(i);if(typeof s>"u"){const{message:n}=c.getInternalError("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return s}),H(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=m.generateChildLogger(t,this.name)}get context(){return m.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,c.mapToObj(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?c.objToMap(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=c.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}}var ir=Object.defineProperty,sr=(r,e,t)=>e in r?ir(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,P=(r,e,t)=>sr(r,typeof e!="symbol"?e+"":e,t);class zt{constructor(e,t,i){this.core=e,this.logger=t,P(this,"name",Be),P(this,"keychain"),P(this,"randomSessionIdentifier",c.generateRandomBytes32()),P(this,"initialized",!1),P(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),P(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),P(this,"getClientId",async()=>{this.isInitialized();const s=await this.getClientSeed(),n=de.generateKeyPair(s);return de.encodeIss(n.publicKey)}),P(this,"generateKeyPair",()=>{this.isInitialized();const s=c.generateKeyPair();return this.setPrivateKey(s.publicKey,s.privateKey)}),P(this,"signJWT",async s=>{this.isInitialized();const n=await this.getClientSeed(),o=de.generateKeyPair(n),a=this.randomSessionIdentifier,h=Ve;return await de.signJWT(a,s,h,o)}),P(this,"generateSharedKey",(s,n,o)=>{this.isInitialized();const a=this.getPrivateKey(s),h=c.deriveSymKey(a,n);return this.setSymKey(h,o)}),P(this,"setSymKey",async(s,n)=>{this.isInitialized();const o=n||c.hashKey(s);return await this.keychain.set(o,s),o}),P(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),P(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),P(this,"encode",async(s,n,o)=>{this.isInitialized();const a=c.validateEncoding(o),h=De.safeJsonStringify(n);if(c.isTypeTwoEnvelope(a))return c.encodeTypeTwoEnvelope(h,o?.encoding);if(c.isTypeOneEnvelope(a)){const y=a.senderPublicKey,T=a.receiverPublicKey;s=await this.generateSharedKey(y,T)}const l=this.getSymKey(s),{type:g,senderPublicKey:p}=a;return c.encrypt({type:g,symKey:l,message:h,senderPublicKey:p,encoding:o?.encoding})}),P(this,"decode",async(s,n,o)=>{this.isInitialized();const a=c.validateDecoding(n,o);if(c.isTypeTwoEnvelope(a)){const h=c.decodeTypeTwoEnvelope(n,o?.encoding);return De.safeJsonParse(h)}if(c.isTypeOneEnvelope(a)){const h=a.receiverPublicKey,l=a.senderPublicKey;s=await this.generateSharedKey(h,l)}try{const h=this.getSymKey(s),l=c.decrypt({symKey:h,encoded:n,encoding:o?.encoding});return De.safeJsonParse(l)}catch(h){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(h)}}),P(this,"getPayloadType",(s,n=c.BASE64)=>{const o=c.deserialize({encoded:s,encoding:n});return c.decodeTypeByte(o.type)}),P(this,"getPayloadSenderPublicKey",(s,n=c.BASE64)=>{const o=c.deserialize({encoded:s,encoding:n});return o.senderPublicKey?li.toString(o.senderPublicKey,c.BASE16):void 0}),this.core=e,this.logger=m.generateChildLogger(t,this.name),this.keychain=i||new $t(this.core,this.logger)}get context(){return m.getLoggerContext(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(we)}catch{e=c.generateRandomBytes32(),await this.keychain.set(we,e)}return Qs(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=c.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}}var rr=Object.defineProperty,nr=Object.defineProperties,or=Object.getOwnPropertyDescriptors,Mt=Object.getOwnPropertySymbols,ar=Object.prototype.hasOwnProperty,cr=Object.prototype.propertyIsEnumerable,Pe=(r,e,t)=>e in r?rr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,hr=(r,e)=>{for(var t in e||(e={}))ar.call(e,t)&&Pe(r,t,e[t]);if(Mt)for(var t of Mt(e))cr.call(e,t)&&Pe(r,t,e[t]);return r},lr=(r,e)=>nr(r,or(e)),M=(r,e,t)=>Pe(r,typeof e!="symbol"?e+"":e,t);class jt extends V.IMessageTracker{constructor(e,t){super(e,t),this.logger=e,this.core=t,M(this,"messages",new Map),M(this,"messagesWithoutClientAck",new Map),M(this,"name",Ge),M(this,"version",Ye),M(this,"initialized",!1),M(this,"storagePrefix",K),M(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}}}),M(this,"set",async(i,s,n)=>{this.isInitialized();const o=c.hashMessage(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===ne.inbound){const h=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,lr(hr({},h),{[o]:s}))}return await this.persist(),o}),M(this,"get",i=>{this.isInitialized();let s=this.messages.get(i);return typeof s>"u"&&(s={}),s}),M(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}),M(this,"has",(i,s)=>{this.isInitialized();const n=this.get(i),o=c.hashMessage(s);return typeof n[o]<"u"}),M(this,"ack",async(i,s)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(i);if(typeof n>"u")return;const o=c.hashMessage(s);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,n),await this.persist()}),M(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=m.generateChildLogger(e,this.name),this.core=t}get context(){return m.getLoggerContext(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,c.mapToObj(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,c.mapToObj(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?c.objToMap(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?c.objToMap(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=c.getInternalError("NOT_INITIALIZED",this.name);throw new Error(e)}}}var ur=Object.defineProperty,gr=Object.defineProperties,dr=Object.getOwnPropertyDescriptors,kt=Object.getOwnPropertySymbols,pr=Object.prototype.hasOwnProperty,yr=Object.prototype.propertyIsEnumerable,Ae=(r,e,t)=>e in r?ur(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ee=(r,e)=>{for(var t in e||(e={}))pr.call(e,t)&&Ae(r,t,e[t]);if(kt)for(var t of kt(e))yr.call(e,t)&&Ae(r,t,e[t]);return r},Ne=(r,e)=>gr(r,dr(e)),q=(r,e,t)=>Ae(r,typeof e!="symbol"?e+"":e,t);class Er extends V.IPublisher{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,q(this,"events",new Z.EventEmitter),q(this,"name",He),q(this,"queue",new Map),q(this,"publishTimeout",u.toMiliseconds(u.ONE_MINUTE)),q(this,"initialPublishTimeout",u.toMiliseconds(u.ONE_SECOND*15)),q(this,"needsTransportRestart",!1),q(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||Te,h=c.getRelayProtocolName(n),l=n?.prompt||!1,g=n?.tag||0,p=n?.id||L.getBigIntRpcId().toString(),y={topic:i,message:s,opts:{ttl:a,relay:h,prompt:l,tag:g,id:p,attestation:n?.attestation,tvf:n?.tvf}},T=`Failed to publish payload, please try again. id:${p} tag:${g}`;try{const d=new Promise(async D=>{const x=({id:_})=>{y.opts.id===_&&(this.removeRequestFromQueue(_),this.relayer.events.removeListener(S.publish,x),D(y))};this.relayer.events.on(S.publish,x);const C=c.createExpiringPromise(new Promise((_,j)=>{this.rpcPublish({topic:i,message:s,ttl:a,prompt:l,tag:g,id:p,attestation:n?.attestation,tvf:n?.tvf}).then(_).catch(R=>{this.logger.warn(R,R?.message),j(R)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${g}`);try{await C,this.events.removeListener(S.publish,x)}catch(_){this.queue.set(p,Ne(Ee({},y),{attempt:1})),this.logger.warn(_,_?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:i,message:s,opts:n}}),await c.createExpiringPromise(d,this.publishTimeout,T)}catch(d){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(d),(o=n?.internal)!=null&&o.throwOnFailedPublish)throw d}finally{this.queue.delete(p)}}),q(this,"on",(i,s)=>{this.events.on(i,s)}),q(this,"once",(i,s)=>{this.events.once(i,s)}),q(this,"off",(i,s)=>{this.events.off(i,s)}),q(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.relayer=e,this.logger=m.generateChildLogger(t,this.name),this.registerEventListeners()}get context(){return m.getLoggerContext(this.logger)}async rpcPublish(e){var t,i,s,n;const{topic:o,message:a,ttl:h=Te,prompt:l,tag:g,id:p,attestation:y,tvf:T}=e,d={method:c.getRelayProtocolApi(c.getRelayProtocolName().protocol).publish,params:Ee({topic:o,message:a,ttl:h,prompt:l,tag:g,attestation:y},T),id:p};c.isUndefined((t=d.params)==null?void 0:t.prompt)&&((i=d.params)==null||delete i.prompt),c.isUndefined((s=d.params)==null?void 0:s.tag)&&((n=d.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:d});const D=await this.relayer.request(d);return this.relayer.events.emit(S.publish,e),this.logger.debug("Successfully Published Payload"),D}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const i=e.attempt+1;this.queue.set(t,Ne(Ee({},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(Ne(Ee({},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(ee.HEARTBEAT_EVENTS.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(S.connection_stalled);return}this.checkQueue()}),this.relayer.on(S.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var br=Object.defineProperty,Dr=(r,e,t)=>e in r?br(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,se=(r,e,t)=>Dr(r,typeof e!="symbol"?e+"":e,t);class mr{constructor(){se(this,"map",new Map),se(this,"set",(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),se(this,"get",e=>this.map.get(e)||[]),se(this,"exists",(e,t)=>this.get(e).includes(t)),se(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)}),se(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var fr=Object.defineProperty,_r=Object.defineProperties,vr=Object.getOwnPropertyDescriptors,Ft=Object.getOwnPropertySymbols,wr=Object.prototype.hasOwnProperty,Tr=Object.prototype.propertyIsEnumerable,xe=(r,e,t)=>e in r?fr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ce=(r,e)=>{for(var t in e||(e={}))wr.call(e,t)&&xe(r,t,e[t]);if(Ft)for(var t of Ft(e))Tr.call(e,t)&&xe(r,t,e[t]);return r},Le=(r,e)=>_r(r,vr(e)),f=(r,e,t)=>xe(r,typeof e!="symbol"?e+"":e,t);class Bt extends V.ISubscriber{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,f(this,"subscriptions",new Map),f(this,"topicMap",new mr),f(this,"events",new Z.EventEmitter),f(this,"name",it),f(this,"version",st),f(this,"pending",new Map),f(this,"cached",[]),f(this,"initialized",!1),f(this,"storagePrefix",K),f(this,"subscribeTimeout",u.toMiliseconds(u.ONE_MINUTE)),f(this,"initialSubscribeTimeout",u.toMiliseconds(u.ONE_SECOND*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=c.getRelayProtocolName(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(ee.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.events.on(U.created,async i=>{const s=U.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()}),this.events.on(U.deleted,async i=>{const s=U.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()})}),this.relayer=e,this.logger=m.generateChildLogger(t,this.name),this.clientId=""}get context(){return m.getLoggerContext(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}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.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=c.getRelayProtocolName(i);await this.restartToComplete({topic:e,id:t,relay:s}),await this.rpcUnsubscribe(e,t,s);const n=c.getSdkError("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,t,i){var s;(!i||i?.transportType===Q.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:c.getRelayProtocolApi(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(g=>this.logger.warn(g))},u.toMiliseconds(u.ONE_SECOND)),a;const h=new Promise(async g=>{const p=y=>{y.topic===e&&(this.events.removeListener(U.created,p),g(y.id))};this.events.on(U.created,p);try{const y=await c.createExpiringPromise(new Promise((T,d)=>{this.relayer.request(n).catch(D=>{this.logger.warn(D,D?.message),d(D)}).then(T)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(U.created,p),g(y)}catch{}}),l=await c.createExpiringPromise(h,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return l?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(S.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:c.getRelayProtocolApi(t.protocol).batchSubscribe,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await c.createExpiringPromise(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(S.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:c.getRelayProtocolApi(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 c.createExpiringPromise(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(S.connection_stalled)}return s}rpcUnsubscribe(e,t,i){const s={method:c.getRelayProtocolApi(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,t){this.setSubscription(e,Le(ce({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,ce({},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,ce({},t)),this.topicMap.set(t.topic,e),this.events.emit(U.created,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:i}=c.getInternalError("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(U.deleted,Le(ce({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(U.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<t;i++){const s=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(U.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=c.getInternalError("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async t=>Le(ce({},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 c.sleep(u.toMiliseconds(u.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=c.getInternalError("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 c.hashMessage(e+await this.getClientId())}}var Ir=Object.defineProperty,Vt=Object.getOwnPropertySymbols,Cr=Object.prototype.hasOwnProperty,Rr=Object.prototype.propertyIsEnumerable,Ue=(r,e,t)=>e in r?Ir(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Kt=(r,e)=>{for(var t in e||(e={}))Cr.call(e,t)&&Ue(r,t,e[t]);if(Vt)for(var t of Vt(e))Rr.call(e,t)&&Ue(r,t,e[t]);return r},b=(r,e,t)=>Ue(r,typeof e!="symbol"?e+"":e,t);class qt extends V.IRelayer{constructor(e){super(e),b(this,"protocol","wc"),b(this,"version",2),b(this,"core"),b(this,"logger"),b(this,"events",new Z.EventEmitter),b(this,"provider"),b(this,"messages"),b(this,"subscriber"),b(this,"publisher"),b(this,"name",Xe),b(this,"transportExplicitlyClosed",!1),b(this,"initialized",!1),b(this,"connectionAttemptInProgress",!1),b(this,"relayUrl"),b(this,"projectId"),b(this,"packageName"),b(this,"bundleId"),b(this,"hasExperiencedNetworkDisruption",!1),b(this,"pingTimeout"),b(this,"heartBeatTimeout",u.toMiliseconds(u.THIRTY_SECONDS+u.FIVE_SECONDS)),b(this,"reconnectTimeout"),b(this,"connectPromise"),b(this,"reconnectInProgress",!1),b(this,"requestsInFlight",[]),b(this,"connectTimeout",u.toMiliseconds(u.ONE_SECOND*15)),b(this,"request",async t=>{var i,s;this.logger.debug("Publishing Request Payload");const n=t.id||L.getBigIntRpcId().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(h=>h!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),b(this,"resetPingTimeout",()=>{c.isNode()&&(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))}),b(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),b(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(S.connect)}),b(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),b(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(S.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),b(this,"registerProviderListeners",()=>{this.provider.on(z.payload,this.onPayloadHandler),this.provider.on(z.connect,this.onConnectHandler),this.provider.on(z.disconnect,this.onDisconnectHandler),this.provider.on(z.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?m.generateChildLogger(e.logger,this.name):m.pino(m.getDefaultLoggerOptions({level:e.logger||Je})),this.messages=new jt(this.logger,e.core),this.subscriber=new Bt(this,this.logger),this.publisher=new Er(this,this.logger),this.relayUrl=e?.relayUrl||Ie,this.projectId=e.projectId,c.isAndroid()?this.packageName=c.getAppId():c.isIos()&&(this.bundleId=c.getAppId()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return m.getLoggerContext(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},ne.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])||"",h;const l=g=>{g.topic===e&&(this.subscriber.off(U.created,l),h())};return await Promise.all([new Promise(g=>{h=g,this.subscriber.on(U.created,l)}),new Promise(async(g,p)=>{a=await this.subscriber.subscribe(e,Kt({internal:{throwOnFailedPublish:o}},t)).catch(y=>{o&&p(y)})||a,g()})]),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 c.createExpiringPromise(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 c.isOnline())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=c.calcExpiry(u.FIVE_MINUTES),n={topic:i,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(S.message,e),await this.recordMessageEvent(e,ne.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 subscribe"))};this.provider.once(z.disco