UNPKG

@walletconnect/core

Version:
1 lines 98.2 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var Q=require("events"),ee=require("@walletconnect/heartbeat"),di=require("@walletconnect/keyvaluestorage"),f=require("@walletconnect/logger"),Y=require("@walletconnect/types"),u=require("@walletconnect/time"),_e=require("@walletconnect/safe-json"),ve=require("@walletconnect/relay-auth"),c=require("@walletconnect/utils"),pi=require("uint8arrays"),yi=require("@walletconnect/jsonrpc-provider"),M=require("@walletconnect/jsonrpc-utils"),Ei=require("@walletconnect/jsonrpc-ws-connection"),bi=require("@walletconnect/window-getters");function we(r){return r&&typeof r=="object"&&"default"in r?r:{default:r}}function mi(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 fi=we(Q),Di=we(di),be=mi(ve),_i=we(Ei);const Te="wc",Ie=2,ae="core",H=`${Te}@2:${ae}:`,je={name:ae,logger:"error"},Be={database:":memory:"},Ve="crypto",Ce="client_ed25519_seed",Ke=u.ONE_DAY,qe="keychain",Ge="0.3",Ye="messages",He="0.3",We=u.SIX_HOURS,Je="publisher",Xe="irn",Ze="error",Re="wss://relay.walletconnect.org",Qe="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"},et="_subscription",B={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},tt=.1,vi={database:":memory:"},me="2.22.2",wi=1e4,te={link_mode:"link_mode",relay:"relay"},ce={inbound:"inbound",outbound:"outbound"},it="0.3",st="WALLETCONNECT_CLIENT_ID",Se="WALLETCONNECT_LINK_MODE_APPS",F={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Ti=u.THIRTY_DAYS,rt="subscription",nt="0.3",Ii=u.FIVE_SECONDS*1e3,ot="pairing",at="0.3",Ci=u.THIRTY_DAYS,se={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}}},re={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"},ct="history",ht="0.3",lt="expirer",q={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},ut="0.3",Ri=u.ONE_DAY,gt="verify-api",Si="https://verify.walletconnect.com",dt="https://verify.walletconnect.org",he=dt,pt=`${he}/v3`,yt=[Si,dt],Et="echo",bt="https://echo.walletconnect.com",Oi="event-client",W={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},X={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Pi={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},Ai={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},Ni={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"},xi={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"},mt=.1,ft="event-client",Dt=86400,_t="https://pulse.walletconnect.org/batch";function Li(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 E(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 m=0,_=0,T=0,I=d.length;T!==I&&d[T]===0;)T++,m++;for(var z=(I-T)*g+1>>>0,C=new Uint8Array(z);T!==I;){for(var k=d[T],R=0,P=z-1;(k!==0||R<_)&&P!==-1;P--,R++)k+=256*C[P]>>>0,C[P]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");_=R,T++}for(var A=z-_;A!==z&&C[A]===0;)A++;for(var ie=h.repeat(m);A<z;++A)ie+=r.charAt(C[A]);return ie}function b(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var _=0,T=0;d[m]===h;)_++,m++;for(var I=(d.length-m)*l+1>>>0,z=new Uint8Array(I);d[m];){var C=t[d.charCodeAt(m)];if(C===255)return;for(var k=0,R=I-1;(C!==0||k<T)&&R!==-1;R--,k++)C+=a*z[R]>>>0,z[R]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");T=k,m++}if(d[m]!==" "){for(var P=I-T;P!==I&&z[P]===0;)P++;for(var A=new Uint8Array(_+(I-P)),ie=_;P!==I;)A[ie++]=z[P++];return A}}}function w(d){var m=b(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:E,decodeUnsafe:b,decode:w}}var Ui=Li,$i=Ui;const vt=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")},zi=r=>new TextEncoder().encode(r),Mi=r=>new TextDecoder().decode(r);class ki{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 Fi{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 wt(this,e)}}class ji{constructor(e){this.decoders=e}or(e){return wt(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 wt=(r,e)=>new ji({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});class Bi{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new ki(e,t,i),this.decoder=new Fi(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const fe=({name:r,prefix:e,encode:t,decode:i})=>new Bi(r,e,t,i),le=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:s}=$i(t,e);return fe({prefix:r,name:e,encode:i,decode:n=>vt(s(n))})},Vi=(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 E=s[r[g]];if(E===void 0)throw new SyntaxError(`Non-${i} character`);h=h<<t|E,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},L=({name:r,prefix:e,bitsPerChar:t,alphabet:i})=>fe({prefix:e,name:r,encode(s){return Ki(s,i,t)},decode(s){return Vi(s,i,t,r)}}),qi=fe({prefix:"\0",name:"identity",encode:r=>Mi(r),decode:r=>zi(r)});var Gi=Object.freeze({__proto__:null,identity:qi});const Yi=L({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Hi=Object.freeze({__proto__:null,base2:Yi});const Wi=L({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ji=Object.freeze({__proto__:null,base8:Wi});const Xi=le({prefix:"9",name:"base10",alphabet:"0123456789"});var Zi=Object.freeze({__proto__:null,base10:Xi});const Qi=L({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),es=L({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ts=Object.freeze({__proto__:null,base16:Qi,base16upper:es});const is=L({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ss=L({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),rs=L({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ns=L({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),os=L({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),as=L({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cs=L({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),hs=L({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ls=L({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var us=Object.freeze({__proto__:null,base32:is,base32upper:ss,base32pad:rs,base32padupper:ns,base32hex:os,base32hexupper:as,base32hexpad:cs,base32hexpadupper:hs,base32z:ls});const gs=le({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ds=le({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ps=Object.freeze({__proto__:null,base36:gs,base36upper:ds});const ys=le({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Es=le({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var bs=Object.freeze({__proto__:null,base58btc:ys,base58flickr:Es});const ms=L({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),fs=L({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ds=L({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_s=L({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var vs=Object.freeze({__proto__:null,base64:ms,base64pad:fs,base64url:Ds,base64urlpad:_s});const Tt=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}"),ws=Tt.reduce((r,e,t)=>(r[t]=e,r),[]),Ts=Tt.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Is(r){return r.reduce((e,t)=>(e+=ws[t],e),"")}function Cs(r){const e=[];for(const t of r){const i=Ts[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const Rs=fe({prefix:"\u{1F680}",name:"base256emoji",encode:Is,decode:Cs});var Ss=Object.freeze({__proto__:null,base256emoji:Rs}),Os=Ct,It=128,Ps=127,As=~Ps,Ns=Math.pow(2,31);function Ct(r,e,t){e=e||[],t=t||0;for(var i=t;r>=Ns;)e[t++]=r&255|It,r/=128;for(;r&As;)e[t++]=r&255|It,r>>>=7;return e[t]=r|0,Ct.bytes=t-i+1,e}var xs=Oe,Ls=128,Rt=127;function Oe(r,i){var t=0,i=i||0,s=0,n=i,o,a=r.length;do{if(n>=a)throw Oe.bytes=0,new RangeError("Could not decode varint");o=r[n++],t+=s<28?(o&Rt)<<s:(o&Rt)*Math.pow(2,s),s+=7}while(o>=Ls);return Oe.bytes=n-i,t}var Us=Math.pow(2,7),$s=Math.pow(2,14),zs=Math.pow(2,21),Ms=Math.pow(2,28),ks=Math.pow(2,35),Fs=Math.pow(2,42),js=Math.pow(2,49),Bs=Math.pow(2,56),Vs=Math.pow(2,63),Ks=function(r){return r<Us?1:r<$s?2:r<zs?3:r<Ms?4:r<ks?5:r<Fs?6:r<js?7:r<Bs?8:r<Vs?9:10},qs={encode:Os,decode:xs,encodingLength:Ks},St=qs;const Ot=(r,e,t=0)=>(St.encode(r,e,t),e),Pt=r=>St.encodingLength(r),Pe=(r,e)=>{const t=e.byteLength,i=Pt(r),s=i+Pt(t),n=new Uint8Array(s+t);return Ot(r,n,0),Ot(t,n,i),n.set(e,s),new Gs(r,t,e,n)};class Gs{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}}const At=({name:r,code:e,encode:t})=>new Ys(r,e,t);class Ys{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?Pe(this.code,t):t.then(i=>Pe(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Nt=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),Hs=At({name:"sha2-256",code:18,encode:Nt("SHA-256")}),Ws=At({name:"sha2-512",code:19,encode:Nt("SHA-512")});var Js=Object.freeze({__proto__:null,sha256:Hs,sha512:Ws});const xt=0,Xs="identity",Lt=vt,Zs=r=>Pe(xt,Lt(r)),Qs={code:xt,name:Xs,encode:Lt,digest:Zs};var er=Object.freeze({__proto__:null,identity:Qs});new TextEncoder,new TextDecoder;const Ut={...Gi,...Hi,...Ji,...Zi,...ts,...us,...ps,...bs,...vs,...Ss};({...Js,...er});function $t(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function tr(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?$t(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function zt(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const Mt=zt("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ae=zt("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=tr(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ir={utf8:Mt,"utf-8":Mt,hex:Ut.base16,latin1:Ae,ascii:Ae,binary:Ae,...Ut};function sr(r,e="utf8"){const t=ir[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?$t(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var rr=Object.defineProperty,nr=(r,e,t)=>e in r?rr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,J=(r,e,t)=>nr(r,typeof e!="symbol"?e+"":e,t);class kt{constructor(e,t){this.core=e,this.logger=t,J(this,"keychain",new Map),J(this,"name",qe),J(this,"version",Ge),J(this,"initialized",!1),J(this,"storagePrefix",H),J(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),J(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),J(this,"set",async(i,s)=>{this.isInitialized(),this.keychain.set(i,s),await this.persist()}),J(this,"get",i=>{this.isInitialized();const s=this.keychain.get(i);if(typeof s>"u"){const{message:n}=c.getInternalError("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return s}),J(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=f.generateChildLogger(t,this.name)}get context(){return f.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 or=Object.defineProperty,ar=(r,e,t)=>e in r?or(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,N=(r,e,t)=>ar(r,typeof e!="symbol"?e+"":e,t);class Ft{constructor(e,t,i){this.core=e,this.logger=t,N(this,"name",Ve),N(this,"keychain"),N(this,"randomSessionIdentifier",c.generateRandomBytes32()),N(this,"initialized",!1),N(this,"clientId"),N(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),N(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),N(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const s=await this.getClientSeed(),n=be.generateKeyPair(s),o=be.encodeIss(n.publicKey);return this.clientId=o,o}),N(this,"generateKeyPair",()=>{this.isInitialized();const s=c.generateKeyPair();return this.setPrivateKey(s.publicKey,s.privateKey)}),N(this,"signJWT",async s=>{this.isInitialized();const n=await this.getClientSeed(),o=be.generateKeyPair(n),a=this.randomSessionIdentifier,h=Ke;return await be.signJWT(a,s,h,o)}),N(this,"generateSharedKey",(s,n,o)=>{this.isInitialized();const a=this.getPrivateKey(s),h=c.deriveSymKey(a,n);return this.setSymKey(h,o)}),N(this,"setSymKey",async(s,n)=>{this.isInitialized();const o=n||c.hashKey(s);return await this.keychain.set(o,s),o}),N(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),N(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),N(this,"encode",async(s,n,o)=>{this.isInitialized();const a=c.validateEncoding(o),h=_e.safeJsonStringify(n);if(c.isTypeTwoEnvelope(a))return c.encodeTypeTwoEnvelope(h,o?.encoding);if(c.isTypeOneEnvelope(a)){const b=a.senderPublicKey,w=a.receiverPublicKey;s=await this.generateSharedKey(b,w)}const l=this.getSymKey(s),{type:g,senderPublicKey:E}=a;return c.encrypt({type:g,symKey:l,message:h,senderPublicKey:E,encoding:o?.encoding})}),N(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 _e.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 _e.safeJsonParse(l)}catch(h){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(h)}}),N(this,"getPayloadType",(s,n=c.BASE64)=>{const o=c.deserialize({encoded:s,encoding:n});return c.decodeTypeByte(o.type)}),N(this,"getPayloadSenderPublicKey",(s,n=c.BASE64)=>{const o=c.deserialize({encoded:s,encoding:n});return o.senderPublicKey?pi.toString(o.senderPublicKey,c.BASE16):void 0}),this.core=e,this.logger=f.generateChildLogger(t,this.name),this.keychain=i||new kt(this.core,this.logger)}get context(){return f.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(Ce)}catch{e=c.generateRandomBytes32(),await this.keychain.set(Ce,e)}return sr(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 cr=Object.defineProperty,hr=Object.defineProperties,lr=Object.getOwnPropertyDescriptors,jt=Object.getOwnPropertySymbols,ur=Object.prototype.hasOwnProperty,gr=Object.prototype.propertyIsEnumerable,Ne=(r,e,t)=>e in r?cr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,dr=(r,e)=>{for(var t in e||(e={}))ur.call(e,t)&&Ne(r,t,e[t]);if(jt)for(var t of jt(e))gr.call(e,t)&&Ne(r,t,e[t]);return r},pr=(r,e)=>hr(r,lr(e)),V=(r,e,t)=>Ne(r,typeof e!="symbol"?e+"":e,t);class Bt extends Y.IMessageTracker{constructor(e,t){super(e,t),this.logger=e,this.core=t,V(this,"messages",new Map),V(this,"messagesWithoutClientAck",new Map),V(this,"name",Ye),V(this,"version",He),V(this,"initialized",!1),V(this,"storagePrefix",H),V(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}}}),V(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===ce.inbound){const h=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,pr(dr({},h),{[o]:s}))}return await this.persist(),o}),V(this,"get",i=>{this.isInitialized();let s=this.messages.get(i);return typeof s>"u"&&(s={}),s}),V(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}),V(this,"has",(i,s)=>{this.isInitialized();const n=this.get(i),o=c.hashMessage(s);return typeof n[o]<"u"}),V(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()}),V(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=f.generateChildLogger(e,this.name),this.core=t}get context(){return f.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 yr=Object.defineProperty,Er=Object.defineProperties,br=Object.getOwnPropertyDescriptors,Vt=Object.getOwnPropertySymbols,mr=Object.prototype.hasOwnProperty,fr=Object.prototype.propertyIsEnumerable,xe=(r,e,t)=>e in r?yr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ne=(r,e)=>{for(var t in e||(e={}))mr.call(e,t)&&xe(r,t,e[t]);if(Vt)for(var t of Vt(e))fr.call(e,t)&&xe(r,t,e[t]);return r},Kt=(r,e)=>Er(r,br(e)),G=(r,e,t)=>xe(r,typeof e!="symbol"?e+"":e,t);class Dr extends Y.IPublisher{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,G(this,"events",new Q.EventEmitter),G(this,"name",Je),G(this,"queue",new Map),G(this,"publishTimeout",u.toMiliseconds(u.ONE_MINUTE)),G(this,"initialPublishTimeout",u.toMiliseconds(u.ONE_SECOND*15)),G(this,"needsTransportRestart",!1),G(this,"publish",async(i,s,n)=>{var o,a,h,l,g;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:s,opts:n}});const E=n?.ttl||We,b=n?.prompt||!1,w=n?.tag||0,d=n?.id||M.getBigIntRpcId().toString(),m=c.getRelayProtocolApi(c.getRelayProtocolName().protocol),_={id:d,method:n?.publishMethod||m.publish,params:ne({topic:i,message:s,ttl:E,prompt:b,tag:w,attestation:n?.attestation},n?.tvf)},T=`Failed to publish payload, please try again. id:${d} tag:${w}`;try{c.isUndefined((o=_.params)==null?void 0:o.prompt)&&((a=_.params)==null||delete a.prompt),c.isUndefined((h=_.params)==null?void 0:h.tag)&&((l=_.params)==null||delete l.tag);const I=new Promise(async z=>{const C=({id:R})=>{var P;((P=_.id)==null?void 0:P.toString())===R.toString()&&(this.removeRequestFromQueue(R),this.relayer.events.removeListener(S.publish,C),z())};this.relayer.events.on(S.publish,C);const k=c.createExpiringPromise(new Promise((R,P)=>{this.rpcPublish(_,n).then(R).catch(A=>{this.logger.warn(A,A?.message),P(A)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${w}`);try{await k,this.events.removeListener(S.publish,C)}catch(R){this.queue.set(d,{request:_,opts:n,attempt:1}),this.logger.warn(R,R?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:i,message:s,opts:n}}),await c.createExpiringPromise(I,this.publishTimeout,T)}catch(I){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(I),(g=n?.internal)!=null&&g.throwOnFailedPublish)throw I}finally{this.queue.delete(d)}}),G(this,"publishCustom",async i=>{var s,n,o,a,h;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:i});const{payload:l,opts:g={}}=i,{attestation:E,tvf:b,publishMethod:w,prompt:d,tag:m,ttl:_=u.FIVE_MINUTES}=g,T=g.id||M.getBigIntRpcId().toString(),I=c.getRelayProtocolApi(c.getRelayProtocolName().protocol),z=w||I.publish,C={id:T,method:z,params:ne(Kt(ne({},l),{ttl:_,prompt:d,tag:m,attestation:E}),b)},k=`Failed to publish custom payload, please try again. id:${T} tag:${m}`;try{c.isUndefined((s=C.params)==null?void 0:s.prompt)&&((n=C.params)==null||delete n.prompt),c.isUndefined((o=C.params)==null?void 0:o.tag)&&((a=C.params)==null||delete a.tag);const R=new Promise(async P=>{const A=({id:Z})=>{var ye;((ye=C.id)==null?void 0:ye.toString())===Z.toString()&&(this.removeRequestFromQueue(Z),this.relayer.events.removeListener(S.publish,A),P())};this.relayer.events.on(S.publish,A);const ie=c.createExpiringPromise(new Promise((Z,ye)=>{this.rpcPublish(C,g).then(Z).catch(Ee=>{this.logger.warn(Ee,Ee?.message),ye(Ee)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${z} id:${T} tag:${m}`);try{await ie,this.events.removeListener(S.publish,A)}catch(Z){this.queue.set(T,{request:C,opts:g,attempt:1}),this.logger.warn(Z,Z?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:T,payload:l,opts:g}}),await c.createExpiringPromise(R,this.publishTimeout,k)}catch(R){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(R),(h=g?.internal)!=null&&h.throwOnFailedPublish)throw R}finally{this.queue.delete(T)}}),G(this,"on",(i,s)=>{this.events.on(i,s)}),G(this,"once",(i,s)=>{this.events.once(i,s)}),G(this,"off",(i,s)=>{this.events.off(i,s)}),G(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.relayer=e,this.logger=f.generateChildLogger(t,this.name),this.registerEventListeners()}get context(){return f.getLoggerContext(this.logger)}async rpcPublish(e,t){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const i=await this.relayer.request(e);return this.relayer.events.emit(S.publish,ne(ne({},e),t)),this.logger.debug("Successfully Published Payload"),i}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{var i;const s=e.attempt+1;this.queue.set(t,Kt(ne({},e),{attempt:s})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(i=e.request.params)==null?void 0:i.tag}, attempt: ${s}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(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 _r=Object.defineProperty,vr=(r,e,t)=>e in r?_r(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,oe=(r,e,t)=>vr(r,typeof e!="symbol"?e+"":e,t);class wr{constructor(){oe(this,"map",new Map),oe(this,"set",(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),oe(this,"get",e=>this.map.get(e)||[]),oe(this,"exists",(e,t)=>this.get(e).includes(t)),oe(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)}),oe(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Tr=Object.defineProperty,Ir=Object.defineProperties,Cr=Object.getOwnPropertyDescriptors,qt=Object.getOwnPropertySymbols,Rr=Object.prototype.hasOwnProperty,Sr=Object.prototype.propertyIsEnumerable,Le=(r,e,t)=>e in r?Tr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ue=(r,e)=>{for(var t in e||(e={}))Rr.call(e,t)&&Le(r,t,e[t]);if(qt)for(var t of qt(e))Sr.call(e,t)&&Le(r,t,e[t]);return r},Ue=(r,e)=>Ir(r,Cr(e)),D=(r,e,t)=>Le(r,typeof e!="symbol"?e+"":e,t);class Gt extends Y.ISubscriber{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,D(this,"subscriptions",new Map),D(this,"topicMap",new wr),D(this,"events",new Q.EventEmitter),D(this,"name",rt),D(this,"version",nt),D(this,"pending",new Map),D(this,"cached",[]),D(this,"initialized",!1),D(this,"storagePrefix",H),D(this,"subscribeTimeout",u.toMiliseconds(u.ONE_MINUTE)),D(this,"initialSubscribeTimeout",u.toMiliseconds(u.ONE_SECOND*15)),D(this,"clientId"),D(this,"batchSubscribeTopicsLimit",500),D(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),D(this,"subscribe",async(i,s)=>{var n;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}});try{const o=c.getRelayProtocolName(s),a={topic:i,relay:o,transportType:s?.transportType};(n=s?.internal)!=null&&n.skipSubscribe||this.pending.set(i,a);const h=await this.rpcSubscribe(i,o,s);return typeof h=="string"&&(this.onSubscribe(h,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}})),h}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),D(this,"unsubscribe",async(i,s)=>{this.isInitialized(),typeof s?.id<"u"?await this.unsubscribeById(i,s.id,s):await this.unsubscribeByTopic(i,s)}),D(this,"isSubscribed",i=>new Promise(s=>{s(this.topicMap.topics.includes(i))})),D(this,"isKnownTopic",i=>new Promise(s=>{s(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(n=>n.topic===i))})),D(this,"on",(i,s)=>{this.events.on(i,s)}),D(this,"once",(i,s)=>{this.events.once(i,s)}),D(this,"off",(i,s)=>{this.events.off(i,s)}),D(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),D(this,"start",async()=>{await this.onConnect()}),D(this,"stop",async()=>{await this.onDisconnect()}),D(this,"restart",async()=>{await this.restore(),await this.onRestart()}),D(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)}),D(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(ee.HEARTBEAT_EVENTS.pulse,async()=>{await this.checkPending()}),this.events.on(F.created,async i=>{const s=F.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()}),this.events.on(F.deleted,async i=>{const s=F.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()})}),this.relayer=e,this.logger=f.generateChildLogger(t,this.name),this.clientId=""}get context(){return f.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.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=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,n;const o=await this.getSubscriptionId(e);if((s=i?.internal)!=null&&s.skipSubscribe)return o;(!i||i?.transportType===te.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const a={method:c.getRelayProtocolApi(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const h=(n=i?.internal)==null?void 0:n.throwOnFailedPublish;try{if(i?.transportType===te.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(E=>this.logger.warn(E))},u.toMiliseconds(u.ONE_SECOND)),o;const l=new Promise(async E=>{const b=w=>{w.topic===e&&(this.events.removeListener(F.created,b),E(w.id))};this.events.on(F.created,b);try{const w=await c.createExpiringPromise(new Promise((d,m)=>{this.relayer.request(a).catch(_=>{this.logger.warn(_,_?.message),m(_)}).then(d)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(F.created,b),E(w)}catch{}}),g=await c.createExpiringPromise(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!g&&h)throw new Error(`Subscribing to ${e} failed, please try again`);return g?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(S.connection_stalled),h)throw l}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,Ue(ue({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,ue({},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,ue({},t)),this.topicMap.set(t.topic,e),this.events.emit(F.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(F.deleted,Ue(ue({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(F.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(F.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(t=>{var i;return t.topic===((i=this.subscriptions.get(t.id))==null?void 0:i.topic)})){const{message:t}=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=>Ue(ue({},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 Or=Object.defineProperty,Yt=Object.getOwnPropertySymbols,Pr=Object.prototype.hasOwnProperty,Ar=Object.prototype.propertyIsEnumerable,$e=(r,e,t)=>e in r?Or(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ht=(r,e)=>{for(var t in e||(e={}))Pr.call(e,t)&&$e(r,t,e[t]);if(Yt)for(var t of Yt(e))Ar.call(e,t)&&$e(r,t,e[t]);return r},y=(r,e,t)=>$e(r,typeof e!="symbol"?e+"":e,t);class Wt extends Y.IRelayer{constructor(e){var t;super(e),y(this,"protocol","wc"),y(this,"version",2),y(this,"core"),y(this,"logger"),y(this,"events",new Q.EventEmitter),y(this,"provider"),y(this,"messages"),y(this,"subscriber"),y(this,"publisher"),y(this,"name",Qe),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",u.toMiliseconds(u.THIRTY_SECONDS+u.FIVE_SECONDS)),y(this,"reconnectTimeout"),y(this,"connectPromise"),y(this,"reconnectInProgress",!1),y(this,"requestsInFlight",[]),y(this,"connectTimeout",u.toMiliseconds(u.ONE_SECOND*15)),y(this,"request",async i=>{var s,n;this.logger.debug("Publishing Request Payload");const o=i.id||M.getBigIntRpcId().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:i.method,topic:(s=i.params)==null?void 0:s.topic},"relayer.request - publishing...");const a=`${o}:${((n=i.params)==null?void 0:n.tag)||""}`;this.requestsInFlight.push(a);const h=await this.provider.request(i);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==a),h}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),y(this,"resetPingTimeout",()=>{c.isNode()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var i,s,n,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(n=(s=(i=this.provider)==null?void 0:i.connection)==null?void 0:s.socket)==null?void 0:n.terminate)==null||o.call(n)}catch(a){this.logger.warn(a,a?.message)}},this.heartBeatTimeout))}),y(this,"onPayloadHandler",i=>{this.onProviderPayload(i),this.resetPingTimeout()}),y(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(S.connect)}),y(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),y(this,"onProviderErrorHandler",i=>{this.logger.fatal(`Fatal socket error: ${i.message}`),this.events.emit(S.error,i),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),y(this,"registerProviderListeners",()=>{this.provider.on(B.payload,this.onPayloadHandler),this.provider.on(B.connect,this.onConnectHandler),this.provider.on(B.disconnect,this.onDisconnectHandler),this.provider.on(B.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=c.createLogger({logger:(t=e.logger)!=null?t:Ze,name:this.name}),this.messages=new Bt(this.logger,e.core),this.subscriber=new Gt(this,this.logger),this.publisher=new Dr(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Re,c.isAndroid()?this.packageName=c.getAppId():c.isIos()&&(this.bundleId=c.getAppId()),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 f.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:te.relay},ce.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,t){var i,s,n;this.isInitialized(),(!(t!=null&&t.transportType)||t?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((i=t?.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(s=t?.internal)==null?void 0:s.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",h;const l=g=>{g.topic===e&&(this.subscriber.off(F.created,l),h())};return await Promise.all([new Promise(g=>{h=g,this.subscriber.on(F.created,l)}),new Promise(async(g,E)=>{a=await this.subscriber.subscribe(e,Ht({internal:{throwOnFailedPublish:o}},t)).catch(b=>{o&&E(b)})||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.info(