>>0,f[O]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");w=k,b++}for(var L=P-w;L!==P&&f[L]===0;)L++;for(var ee=c.repeat(g);L>>0,P=new Uint8Array(D);l[g];){var f=t[l.charCodeAt(g)];if(f===255)return;for(var N=0,k=D-1;(f!==0||N>>0,P[k]=f%256>>>0,f=f/256>>>0;if(f!==0)throw new Error("Non-zero carry");b=N,g++}if(l[g]!==" "){for(var O=D-b;O!==D&&P[O]===0;)O++;for(var L=new Uint8Array(w+(D-O)),ee=w;O!==D;)L[ee++]=P[O++];return L}}}function m(l){var g=y(l);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:y,decode:m}}var Ls=zs,$s=Ls;const index_es_Ot=o=>{if(o instanceof Uint8Array&&o.constructor.name==="Uint8Array")return o;if(o instanceof ArrayBuffer)return new Uint8Array(o);if(ArrayBuffer.isView(o))return new Uint8Array(o.buffer,o.byteOffset,o.byteLength);throw new Error("Unknown type, must be binary type")},ks=o=>new TextEncoder().encode(o),Us=o=>new TextDecoder().decode(o);class Fs{constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Ms{constructor(e,t,s){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=s}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 index_es_At(this,e)}}class Ks{constructor(e){this.decoders=e}or(e){return index_es_At(this,e)}decode(e){const t=e[0],s=this.decoders[t];if(s)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const index_es_At=(o,e)=>new Ks({...o.decoders||{[o.prefix]:o},...e.decoders||{[e.prefix]:e}});class Bs{constructor(e,t,s,i){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=i,this.encoder=new Fs(e,t,s),this.decoder=new Ms(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ne=({name:o,prefix:e,encode:t,decode:s})=>new Bs(o,e,t,s),index_es_W=({prefix:o,name:e,alphabet:t})=>{const{encode:s,decode:i}=$s(t,e);return ne({prefix:o,name:e,encode:s,decode:r=>index_es_Ot(i(r))})},Vs=(o,e,t,s)=>{const i={};for(let u=0;u=8&&(a-=8,n[h++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return n},js=(o,e,t)=>{const s=e[e.length-1]==="=",i=(1<t;)n-=t,r+=e[i&a>>n];if(n&&(r+=e[i&a<ne({prefix:e,name:o,encode(i){return js(i,s,t)},decode(i){return Vs(i,s,t,o)}}),qs=ne({prefix:"\0",name:"identity",encode:o=>Us(o),decode:o=>ks(o)});var Gs=Object.freeze({__proto__:null,identity:qs});const Hs=core_dist_index_es_({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ys=Object.freeze({__proto__:null,base2:Hs});const Js=core_dist_index_es_({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Xs=Object.freeze({__proto__:null,base8:Js});const Ws=index_es_W({prefix:"9",name:"base10",alphabet:"0123456789"});var Zs=Object.freeze({__proto__:null,base10:Ws});const Qs=core_dist_index_es_({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),index_es_er=core_dist_index_es_({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var index_es_tr=Object.freeze({__proto__:null,base16:Qs,base16upper:index_es_er});const index_es_ir=core_dist_index_es_({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),index_es_sr=core_dist_index_es_({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),index_es_rr=core_dist_index_es_({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),index_es_nr=core_dist_index_es_({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),index_es_or=core_dist_index_es_({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),index_es_ar=core_dist_index_es_({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),index_es_cr=core_dist_index_es_({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),index_es_hr=core_dist_index_es_({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),index_es_lr=core_dist_index_es_({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var index_es_ur=Object.freeze({__proto__:null,base32:index_es_ir,base32upper:index_es_sr,base32pad:index_es_rr,base32padupper:index_es_nr,base32hex:index_es_or,base32hexupper:index_es_ar,base32hexpad:index_es_cr,base32hexpadupper:index_es_hr,base32z:index_es_lr});const index_es_dr=index_es_W({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),index_es_pr=index_es_W({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var index_es_gr=Object.freeze({__proto__:null,base36:index_es_dr,base36upper:index_es_pr});const index_es_yr=index_es_W({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),index_es_Dr=index_es_W({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var index_es_mr=Object.freeze({__proto__:null,base58btc:index_es_yr,base58flickr:index_es_Dr});const index_es_br=core_dist_index_es_({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),index_es_fr=core_dist_index_es_({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),index_es_vr=core_dist_index_es_({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),dist_index_es_r=core_dist_index_es_({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var index_es_Er=Object.freeze({__proto__:null,base64:index_es_br,base64pad:index_es_fr,base64url:index_es_vr,base64urlpad:dist_index_es_r});const index_es_Nt=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}"),index_es_wr=index_es_Nt.reduce((o,e,t)=>(o[t]=e,o),[]),index_es_Ir=index_es_Nt.reduce((o,e,t)=>(o[e.codePointAt(0)]=t,o),[]);function index_es_Tr(o){return o.reduce((e,t)=>(e+=index_es_wr[t],e),"")}function index_es_Cr(o){const e=[];for(const t of o){const s=index_es_Ir[t.codePointAt(0)];if(s===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}const index_es_Pr=ne({prefix:"\u{1F680}",name:"base256emoji",encode:index_es_Tr,decode:index_es_Cr});var index_es_Sr=Object.freeze({__proto__:null,base256emoji:index_es_Pr}),index_es_Rr=index_es_Lt,index_es_zt=128,index_es_xr=127,index_es_Or=~index_es_xr,index_es_Ar=Math.pow(2,31);function index_es_Lt(o,e,t){e=e||[],t=t||0;for(var s=t;o>=index_es_Ar;)e[t++]=o&255|index_es_zt,o/=128;for(;o&index_es_Or;)e[t++]=o&255|index_es_zt,o>>>=7;return e[t]=o|0,index_es_Lt.bytes=t-s+1,e}var index_es_Nr=_e,index_es_zr=128,index_es_$t=127;function _e(o,s){var t=0,s=s||0,i=0,r=s,n,a=o.length;do{if(r>=a)throw _e.bytes=0,new RangeError("Could not decode varint");n=o[r++],t+=i<28?(n&index_es_$t)<=index_es_zr);return _e.bytes=r-s,t}var index_es_Lr=Math.pow(2,7),index_es_$r=Math.pow(2,14),index_es_kr=Math.pow(2,21),index_es_Ur=Math.pow(2,28),index_es_Fr=Math.pow(2,35),index_es_Mr=Math.pow(2,42),index_es_Kr=Math.pow(2,49),index_es_Br=Math.pow(2,56),index_es_Vr=Math.pow(2,63),index_es_jr=function(o){return o(index_es_kt.encode(o,e,t),e),index_es_Ft=o=>index_es_kt.encodingLength(o),index_es_Ee=(o,e)=>{const t=e.byteLength,s=index_es_Ft(o),i=s+index_es_Ft(t),r=new Uint8Array(i+t);return index_es_Ut(o,r,0),index_es_Ut(t,r,s),r.set(e,i),new index_es_Gr(o,t,e,r)};class index_es_Gr{constructor(e,t,s,i){this.code=e,this.size=t,this.digest=s,this.bytes=i}}const index_es_Mt=({name:o,code:e,encode:t})=>new index_es_Hr(o,e,t);class index_es_Hr{constructor(e,t,s){this.name=e,this.code=t,this.encode=s}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?index_es_Ee(this.code,t):t.then(s=>index_es_Ee(this.code,s))}else throw Error("Unknown type, must be binary type")}}const index_es_Kt=o=>async e=>new Uint8Array(await crypto.subtle.digest(o,e)),index_es_Yr=index_es_Mt({name:"sha2-256",code:18,encode:index_es_Kt("SHA-256")}),index_es_Jr=index_es_Mt({name:"sha2-512",code:19,encode:index_es_Kt("SHA-512")});var index_es_Xr=Object.freeze({__proto__:null,sha256:index_es_Yr,sha512:index_es_Jr});const index_es_Bt=0,index_es_Wr="identity",index_es_Vt=index_es_Ot,index_es_Zr=o=>index_es_Ee(index_es_Bt,index_es_Vt(o)),index_es_Qr={code:index_es_Bt,name:index_es_Wr,encode:index_es_Vt,digest:index_es_Zr};var index_es_en=Object.freeze({__proto__:null,identity:index_es_Qr});new TextEncoder,new TextDecoder;const index_es_jt={...Gs,...Ys,...Xs,...Zs,...index_es_tr,...index_es_ur,...index_es_gr,...index_es_mr,...index_es_Er,...index_es_Sr};({...index_es_Xr,...index_es_en});function index_es_tn(o=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(o):new Uint8Array(o)}function index_es_qt(o,e,t,s){return{name:o,prefix:e,encoder:{name:o,prefix:e,encode:t},decoder:{decode:s}}}const index_es_Gt=index_es_qt("utf8","u",o=>"u"+new TextDecoder("utf8").decode(o),o=>new TextEncoder().encode(o.substring(1))),index_es_we=index_es_qt("ascii","a",o=>{let e="a";for(let t=0;t{o=o.substring(1);const e=index_es_tn(o.length);for(let t=0;t{if(!this.initialized){const s=await this.getKeyChain();typeof s<"u"&&(this.keychain=s),this.initialized=!0}},this.has=s=>(this.isInitialized(),this.keychain.has(s)),this.set=async(s,i)=>{this.isInitialized(),this.keychain.set(s,i),await this.persist()},this.get=s=>{this.isInitialized();const i=this.keychain.get(s);if(typeof i>"u"){const{message:r}=index_es_S("NO_MATCHING_KEY",`${this.name}: ${s}`);throw new Error(r)}return i},this.del=async s=>{this.isInitialized(),this.keychain.delete(s),await this.persist()},this.core=e,this.logger=dist_index_es_E(t,this.name)}get context(){return dist_index_es_y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,At(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?index_es_Ct(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=index_es_S("NOT_INITIALIZED",this.name);throw new Error(e)}}}class index_es_Yt{constructor(e,t,s){this.core=e,this.logger=t,this.name=index_es_Ze,this.randomSessionIdentifier=yr(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=i=>(this.isInitialized(),this.keychain.has(i)),this.getClientId=async()=>{this.isInitialized();const i=await this.getClientSeed(),r=generateKeyPair(i);return encodeIss(r.publicKey)},this.generateKeyPair=()=>{this.isInitialized();const i=hr();return this.setPrivateKey(i.publicKey,i.privateKey)},this.signJWT=async i=>{this.isInitialized();const r=await this.getClientSeed(),n=generateKeyPair(r),a=this.randomSessionIdentifier,c=index_es_Qe;return await signJWT(a,i,c,n)},this.generateSharedKey=(i,r,n)=>{this.isInitialized();const a=this.getPrivateKey(i),c=gr(a,r);return this.setSymKey(c,n)},this.setSymKey=async(i,r)=>{this.isInitialized();const n=r||vr(i);return await this.keychain.set(n,i),n},this.deleteKeyPair=async i=>{this.isInitialized(),await this.keychain.del(i)},this.deleteSymKey=async i=>{this.isInitialized(),await this.keychain.del(i)},this.encode=async(i,r,n)=>{this.isInitialized();const a=On(n),c=safeJsonStringify(r);if(Rr(a))return wr(c,n?.encoding);if($r(a)){const y=a.senderPublicKey,m=a.receiverPublicKey;i=await this.generateSharedKey(y,m)}const h=this.getSymKey(i),{type:u,senderPublicKey:d}=a;return Er({type:u,symKey:h,message:c,senderPublicKey:d,encoding:n?.encoding})},this.decode=async(i,r,n)=>{this.isInitialized();const a=Sr(r,n);if(Rr(a)){const c=Nr(r,n?.encoding);return safeJsonParse(c)}if($r(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;i=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(i),h=Or({symKey:c,encoded:r,encoding:n?.encoding});return safeJsonParse(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}},this.getPayloadType=(i,r=ge)=>{const n=Q({encoded:i,encoding:r});return index_es_C(n.type)},this.getPayloadSenderPublicKey=(i,r=ge)=>{const n=Q({encoded:i,encoding:r});return n.senderPublicKey?to_string_toString(n.senderPublicKey,index_es_g):void 0},this.core=e,this.logger=dist_index_es_E(t,this.name),this.keychain=s||new index_es_Ht(this.core,this.logger)}get context(){return dist_index_es_y(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(index_es_me)}catch{e=yr(),await this.keychain.set(index_es_me,e)}return index_es_rn(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=index_es_S("NOT_INITIALIZED",this.name);throw new Error(e)}}}class index_es_Jt extends index_es_a{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.name=it,this.version=st,this.initialized=!1,this.storagePrefix=dist_index_es_A,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const s=await this.getRelayerMessages();typeof s<"u"&&(this.messages=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(s){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(s)}finally{this.initialized=!0}}},this.set=async(s,i)=>{this.isInitialized();const r=br(i);let n=this.messages.get(s);return typeof n>"u"&&(n={}),typeof n[r]<"u"||(n[r]=i,this.messages.set(s,n),await this.persist()),r},this.get=s=>{this.isInitialized();let i=this.messages.get(s);return typeof i>"u"&&(i={}),i},this.has=(s,i)=>{this.isInitialized();const r=this.get(s),n=br(i);return typeof r[n]<"u"},this.del=async s=>{this.isInitialized(),this.messages.delete(s),await this.persist()},this.logger=dist_index_es_E(e,this.name),this.core=t}get context(){return dist_index_es_y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,At(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?index_es_Ct(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=index_es_S("NOT_INITIALIZED",this.name);throw new Error(e)}}}var index_es_nn=Object.defineProperty,index_es_on=Object.defineProperties,index_es_an=Object.getOwnPropertyDescriptors,index_es_Xt=Object.getOwnPropertySymbols,index_es_cn=Object.prototype.hasOwnProperty,index_es_hn=Object.prototype.propertyIsEnumerable,index_es_Wt=(o,e,t)=>e in o?index_es_nn(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,index_es_Zt=(o,e)=>{for(var t in e||(e={}))index_es_cn.call(e,t)&&index_es_Wt(o,t,e[t]);if(index_es_Xt)for(var t of index_es_Xt(e))index_es_hn.call(e,t)&&index_es_Wt(o,t,e[t]);return o},index_es_Qt=(o,e)=>index_es_on(o,index_es_an(e));class index_es_ln extends types_dist_index_es_g{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.events=new external_events_.EventEmitter,this.name=rt,this.queue=new Map,this.publishTimeout=(0,cjs.toMiliseconds)(cjs.ONE_MINUTE),this.initialPublishTimeout=(0,cjs.toMiliseconds)(cjs.ONE_SECOND*15),this.needsTransportRestart=!1,this.publish=async(s,i,r)=>{var n;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:s,message:i,opts:r}});const a=r?.ttl||index_es_be,c=Tr(r),h=r?.prompt||!1,u=r?.tag||0,d=r?.id||getBigIntRpcId().toString(),y={topic:s,message:i,opts:{ttl:a,relay:c,prompt:h,tag:u,id:d,attestation:r?.attestation}},m=`Failed to publish payload, please try again. id:${d} tag:${u}`;try{const l=new Promise(async g=>{const w=({id:D})=>{y.opts.id===D&&(this.removeRequestFromQueue(D),this.relayer.events.removeListener(core_dist_index_es_v.publish,w),g(y))};this.relayer.events.on(core_dist_index_es_v.publish,w);const b=xt(new Promise((D,P)=>{this.rpcPublish({topic:s,message:i,ttl:a,prompt:h,tag:u,id:d,attestation:r?.attestation}).then(D).catch(f=>{this.logger.warn(f,f?.message),P(f)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${u}`);try{await b,this.events.removeListener(core_dist_index_es_v.publish,w)}catch(D){this.queue.set(d,index_es_Qt(index_es_Zt({},y),{attempt:1})),this.logger.warn(D,D?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:s,message:i,opts:r}}),await xt(l,this.publishTimeout,m)}catch(l){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(l),(n=r?.internal)!=null&&n.throwOnFailedPublish)throw l}finally{this.queue.delete(d)}},this.on=(s,i)=>{this.events.on(s,i)},this.once=(s,i)=>{this.events.once(s,i)},this.off=(s,i)=>{this.events.off(s,i)},this.removeListener=(s,i)=>{this.events.removeListener(s,i)},this.relayer=e,this.logger=dist_index_es_E(t,this.name),this.registerEventListeners()}get context(){return dist_index_es_y(this.logger)}async rpcPublish(e){var t,s,i,r;const{topic:n,message:a,ttl:c=index_es_be,prompt:h,tag:u,id:d,attestation:y}=e,m={method:Ar(Tr().protocol).publish,params:{topic:n,message:a,ttl:c,prompt:h,tag:u,attestation:y},id:d};index_es_P((t=m.params)==null?void 0:t.prompt)&&((s=m.params)==null||delete s.prompt),index_es_P((i=m.params)==null?void 0:i.tag)&&((r=m.params)==null||delete r.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:m});const l=await this.relayer.request(m);return this.relayer.events.emit(core_dist_index_es_v.publish,e),this.logger.debug("Successfully Published Payload"),l}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const s=e.attempt+1;this.queue.set(t,index_es_Qt(index_es_Zt({},e),{attempt:s}));const{topic:i,message:r,opts:n,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${s}`),await this.rpcPublish({topic:i,message:r,ttl:n.ttl,prompt:n.prompt,tag:n.tag,id:n.id,attestation:a}),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(r.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(core_dist_index_es_v.connection_stalled);return}this.checkQueue()}),this.relayer.on(core_dist_index_es_v.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class index_es_un{constructor(){this.map=new Map,this.set=(e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])},this.get=e=>this.map.get(e)||[],this.exists=(e,t)=>this.get(e).includes(t),this.delete=(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const s=this.get(e);if(!this.exists(e,t))return;const i=s.filter(r=>r!==t);if(!i.length){this.map.delete(e);return}this.map.set(e,i)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}var index_es_dn=Object.defineProperty,index_es_pn=Object.defineProperties,index_es_gn=Object.getOwnPropertyDescriptors,ei=Object.getOwnPropertySymbols,index_es_yn=Object.prototype.hasOwnProperty,index_es_Dn=Object.prototype.propertyIsEnumerable,ti=(o,e,t)=>e in o?index_es_dn(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,index_es_Z=(o,e)=>{for(var t in e||(e={}))index_es_yn.call(e,t)&&ti(o,t,e[t]);if(ei)for(var t of ei(e))index_es_Dn.call(e,t)&&ti(o,t,e[t]);return o},Ie=(o,e)=>index_es_pn(o,index_es_gn(e));class ii extends dist_index_es_d{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,this.subscriptions=new Map,this.topicMap=new index_es_un,this.events=new external_events_.EventEmitter,this.name=dt,this.version=index_es_pt,this.pending=new Map,this.cached=[],this.initialized=!1,this.pendingSubscriptionWatchLabel="pending_sub_watch_label",this.pollingInterval=20,this.storagePrefix=dist_index_es_A,this.subscribeTimeout=(0,cjs.toMiliseconds)(cjs.ONE_MINUTE),this.initialSubscribeTimeout=(0,cjs.toMiliseconds)(cjs.ONE_SECOND*15),this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),this.clientId=await this.relayer.core.crypto.getClientId(),await this.restore()),this.initialized=!0},this.subscribe=async(s,i)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:s,opts:i}});try{const r=Tr(i),n={topic:s,relay:r,transportType:i?.transportType};this.pending.set(s,n);const a=await this.rpcSubscribe(s,r,i);return typeof a=="string"&&(this.onSubscribe(a,n),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:s,opts:i}})),a}catch(r){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(r),r}},this.unsubscribe=async(s,i)=>{await this.restartToComplete(),this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(s,i.id,i):await this.unsubscribeByTopic(s,i)},this.isSubscribed=async s=>{if(this.topics.includes(s))return!0;const i=`${this.pendingSubscriptionWatchLabel}_${s}`;return await new Promise((r,n)=>{const a=new cjs.Watch;a.start(i);const c=setInterval(()=>{(!this.pending.has(s)&&this.topics.includes(s)||this.cached.some(h=>h.topic===s))&&(clearInterval(c),a.stop(i),r(!0)),a.elapsed(i)>=index_es_gt&&(clearInterval(c),a.stop(i),n(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)},this.on=(s,i)=>{this.events.on(s,i)},this.once=(s,i)=>{this.events.once(s,i)},this.off=(s,i)=>{this.events.off(s,i)},this.removeListener=(s,i)=>{this.events.removeListener(s,i)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{await this.restore(),await this.onRestart()},this.checkPending=async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const s=[];this.pending.forEach(i=>{s.push(i)}),await this.batchSubscribe(s)},this.registerEventListeners=()=>{this.relayer.core.heartbeat.on(r.pulse,async()=>{await this.checkPending()}),this.events.on(index_es_T.created,async s=>{const i=index_es_T.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:s}),await this.persist()}),this.events.on(index_es_T.deleted,async s=>{const i=index_es_T.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:s}),await this.persist()})},this.relayer=e,this.logger=dist_index_es_E(t,this.name),this.clientId=""}get context(){return dist_index_es_y(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}hasSubscription(e,t){let s=!1;try{s=this.getSubscription(e).topic===t}catch{}return s}reset(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const s=this.topicMap.get(e);await Promise.all(s.map(async i=>await this.unsubscribeById(e,i,t)))}async unsubscribeById(e,t,s){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}});try{const i=Tr(s);await this.rpcUnsubscribe(e,t,i);const r=index_es_("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,r),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,t,s){var i;s?.transportType===dist_index_es_M.relay&&await this.restartToComplete();const r={method:Ar(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});const n=(i=s?.internal)==null?void 0:i.throwOnFailedPublish;try{const a=this.getSubscriptionId(e);if(s?.transportType===dist_index_es_M.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(r).catch(u=>this.logger.warn(u))},(0,cjs.toMiliseconds)(cjs.ONE_SECOND)),a;const c=new Promise(async u=>{const d=y=>{y.topic===e&&(this.events.removeListener(index_es_T.created,d),u(y.id))};this.events.on(index_es_T.created,d);try{const y=await xt(new Promise((m,l)=>{this.relayer.request(r).catch(g=>{this.logger.warn(g,g?.message),l(g)}).then(m)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(index_es_T.created,d),u(y)}catch{}}),h=await xt(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!h&&n)throw new Error(`Subscribing to ${e} failed, please try again`);return h?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(core_dist_index_es_v.connection_stalled),n)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,s={method:Ar(t.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});try{await await xt(new Promise(i=>{this.relayer.request(s).catch(r=>this.logger.warn(r)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(core_dist_index_es_v.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,s={method:Ar(t.protocol).batchFetchMessages,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});let i;try{i=await await xt(new Promise((r,n)=>{this.relayer.request(s).catch(a=>{this.logger.warn(a),n(a)}).then(r)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(core_dist_index_es_v.connection_stalled)}return i}rpcUnsubscribe(e,t,s){const i={method:Ar(s.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,t){this.setSubscription(e,Ie(index_es_Z({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,index_es_Z({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,s){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,s),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,index_es_Z({},t)),this.topicMap.set(t.topic,e),this.events.emit(index_es_T.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:s}=index_es_S("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const s=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(s.topic,e),this.events.emit(index_es_T.deleted,Ie(index_es_Z({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(index_es_T.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let s=0;s"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=index_es_S("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(e.map(t=>Ie(index_es_Z({},t),{id: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 Gt((0,cjs.toMiliseconds)(cjs.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}=index_es_S("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(){!this.relayer.connected&&!this.relayer.connecting&&await this.relayer.transportOpen()}getSubscriptionId(e){return br(e+this.clientId)}}var index_es_mn=Object.defineProperty,si=Object.getOwnPropertySymbols,index_es_bn=Object.prototype.hasOwnProperty,index_es_fn=Object.prototype.propertyIsEnumerable,ri=(o,e,t)=>e in o?index_es_mn(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,ni=(o,e)=>{for(var t in e||(e={}))index_es_bn.call(e,t)&&ri(o,t,e[t]);if(si)for(var t of si(e))index_es_fn.call(e,t)&&ri(o,t,e[t]);return o};class oi extends index_es_u{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new external_events_.EventEmitter,this.name=at,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1,this.heartBeatTimeout=(0,cjs.toMiliseconds)(cjs.THIRTY_SECONDS+cjs.FIVE_SECONDS),this.requestsInFlight=[],this.connectTimeout=(0,cjs.toMiliseconds)(cjs.ONE_SECOND*15),this.request=async t=>{var s,i;this.logger.debug("Publishing Request Payload");const r=t.id||getBigIntRpcId().toString();await this.toEstablishConnection();try{this.logger.trace({id:r,method:t.method,topic:(s=t.params)==null?void 0:s.topic},"relayer.request - publishing...");const n=`${r}:${((i=t.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(n);const a=await this.provider.request(t);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==n),a}catch(n){throw this.logger.debug(`Failed to Publish Request: ${r}`),n}},this.resetPingTimeout=()=>{if(ce())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,s,i;this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(i=(s=(t=this.provider)==null?void 0:t.connection)==null?void 0:s.socket)==null||i.terminate()},this.heartBeatTimeout)}catch(t){this.logger.warn(t,t?.message)}},this.onPayloadHandler=t=>{this.onProviderPayload(t),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(core_dist_index_es_v.connect)},this.onDisconnectHandler=()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()},this.onProviderErrorHandler=t=>{this.logger.fatal(t,`Fatal socket error: ${t?.message}`),this.events.emit(core_dist_index_es_v.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()},this.registerProviderListeners=()=>{this.provider.on(core_dist_index_es_C.payload,this.onPayloadHandler),this.provider.on(core_dist_index_es_C.connect,this.onConnectHandler),this.provider.on(core_dist_index_es_C.disconnect,this.onDisconnectHandler),this.provider.on(core_dist_index_es_C.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?dist_index_es_E(e.logger,this.name):pino_default()(logger_dist_index_es_k({level:e.logger||ot})),this.messages=new index_es_Jt(this.logger,e.core),this.subscriber=new ii(this,this.logger),this.publisher=new index_es_ln(this,this.logger),this.relayUrl=e?.relayUrl||fe,this.projectId=e.projectId,Ot()?this.packageName=St():Nt()&&(this.bundleId=St()),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.cached.length>0)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return dist_index_es_y(this.logger)}get connected(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===1}get connecting(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===0}async publish(e,t,s){this.isInitialized(),await this.publisher.publish(e,t,s),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:dist_index_es_M.relay})}async subscribe(e,t){var s,i,r;this.isInitialized(),(!(t!=null&&t.transportType)||t?.transportType==="relay")&&await this.toEstablishConnection();const n=typeof((s=t?.internal)==null?void 0:s.throwOnFailedPublish)>"u"?!0:(i=t?.internal)==null?void 0:i.throwOnFailedPublish;let a=((r=this.subscriber.topicMap.get(e))==null?void 0:r[0])||"",c;const h=u=>{u.topic===e&&(this.subscriber.off(index_es_T.created,h),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(index_es_T.created,h)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(e,ni({internal:{throwOnFailedPublish:n}},t)).catch(y=>{n&&d(y)})||a,u()})]),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 xt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){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,s)=>{await this.connect(e).then(t).catch(s).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 go())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((s,i)=>s.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const s of t)try{await this.onMessageEvent(s)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:s}=e;if(!t.sessionExists){const i=Lt(cjs.FIVE_MINUTES),r={topic:s,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(s,r)}this.events.emit(core_dist_index_es_v.message,e),await this.recordMessageEvent(e)}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{this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(s,i)=>{const r=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(core_dist_index_es_C.disconnect,r),await xt(new Promise((n,a)=>{this.provider.connect().then(n).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(n=>{i(n)}).finally(()=>{this.provider.off(core_dist_index_es_C.disconnect,r),clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0}),await new Promise(async(n,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(core_dist_index_es_C.disconnect,c),await this.subscriber.start().then(n).catch(a).finally(()=>{this.provider.off(core_dist_index_es_C.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,s()})}catch(s){await this.subscriber.stop();const i=s;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(s=>setTimeout(s,(0,cjs.toMiliseconds)(t*1))),t++}}startPingTimeout(){var e,t,s,i,r;if(ce())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((r=(i=(s=this.provider)==null?void 0:s.connection)==null?void 0:i.socket)==null||r.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(n){this.logger.warn(n,n?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new dist_index_es_o(new dist_index_es_f(It({sdkVersion:index_es_re,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e){const{topic:t,message:s}=e;await this.messages.set(t,s)}async shouldIgnoreMessageEvent(e){const{topic:t,message:s}=e;if(!s||s.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${s}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.warn(`Ignoring message for non-subscribed topic ${t}`),!0;const i=this.messages.has(t,s);return i&&this.logger.warn(`Ignoring duplicate message: ${s}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),isJsonRpcRequest(e)){if(!e.method.endsWith(ct))return;const t=e.params,{topic:s,message:i,publishedAt:r,attestation:n}=t.data,a={topic:s,message:i,publishedAt:r,transportType:dist_index_es_M.relay,attestation:n};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(ni({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else isJsonRpcResponse(e)&&this.events.emit(core_dist_index_es_v.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(core_dist_index_es_v.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=formatJsonRpcResult(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(core_dist_index_es_C.payload,this.onPayloadHandler),this.provider.off(core_dist_index_es_C.connect,this.onConnectHandler),this.provider.off(core_dist_index_es_C.disconnect,this.onDisconnectHandler),this.provider.off(core_dist_index_es_C.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await go();vo(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(s=>this.logger.error(s,s?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){await this.subscriber.stop(),clearTimeout(this.pingTimeout),this.events.emit(core_dist_index_es_v.disconnect),this.connectionAttemptInProgress=!1,!this.transportExplicitlyClosed&&(this.reconnectTimeout||this.connectPromise||(this.reconnectTimeout=setTimeout(async()=>{clearTimeout(this.reconnectTimeout),await this.transportOpen().catch(e=>this.logger.error(e,e?.message))},(0,cjs.toMiliseconds)(index_es_ht))))}isInitialized(){if(!this.initialized){const{message:e}=index_es_S("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.transportOpen()}}var index_es_vn=Object.defineProperty,ai=Object.getOwnPropertySymbols,core_dist_index_es_n=Object.prototype.hasOwnProperty,index_es_En=Object.prototype.propertyIsEnumerable,ci=(o,e,t)=>e in o?index_es_vn(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,hi=(o,e)=>{for(var t in e||(e={}))core_dist_index_es_n.call(e,t)&&ci(o,t,e[t]);if(ai)for(var t of ai(e))index_es_En.call(e,t)&&ci(o,t,e[t]);return o};class li extends dist_index_es_p{constructor(e,t,s,i=dist_index_es_A,r=void 0){super(e,t,s,i),this.core=e,this.logger=t,this.name=s,this.map=new Map,this.version=lt,this.cached=[],this.initialized=!1,this.storagePrefix=dist_index_es_A,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>{this.getKey&&n!==null&&!index_es_P(n)?this.map.set(this.getKey(n),n):Xr(n)?this.map.set(n.id,n):eo(n)&&this.map.set(n.topic,n)}),this.cached=[],this.initialized=!0)},this.set=async(n,a)=>{this.isInitialized(),this.map.has(n)?await this.update(n,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:n,value:a}),this.map.set(n,a),await this.persist())},this.get=n=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:n}),this.getData(n)),this.getAll=n=>(this.isInitialized(),n?this.values.filter(a=>Object.keys(n).every(c=>lodash_isequal_default()(a[c],n[c]))):this.values),this.update=async(n,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:n,update:a});const c=hi(hi({},this.getData(n)),a);this.map.set(n,c),await this.persist()},this.delete=async(n,a)=>{this.isInitialized(),this.map.has(n)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:n,reason:a}),this.map.delete(n),this.addToRecentlyDeleted(n),await this.persist())},this.logger=dist_index_es_E(t,this.name),this.storagePrefix=i,this.getKey=r}get context(){return dist_index_es_y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:i}=index_es_S("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:s}=index_es_S("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:t}=index_es_S("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=index_es_S("NOT_INITIALIZED",this.name);throw new Error(e)}}}class ui{constructor(e,t){this.core=e,this.logger=t,this.name=index_es_yt,this.version=index_es_Dt,this.events=new (external_events_default()),this.initialized=!1,this.storagePrefix=dist_index_es_A,this.ignoredPayloadTypes=[D],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:s})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...s])]},this.create=async s=>{this.isInitialized();const i=yr(),r=await this.core.crypto.setSymKey(i),n=Lt(cjs.FIVE_MINUTES),a={protocol:nt},c={topic:r,expiry:n,relay:a,active:!1,methods:s?.methods},h=Mr({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:i,relay:a,expiryTimestamp:n,methods:s?.methods});return this.events.emit(index_es_j.create,c),this.core.expirer.set(r,n),await this.pairings.set(r,c),await this.core.relayer.subscribe(r,{transportType:s?.transportType}),{topic:r,uri:h}},this.pair=async s=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:s?.uri,trace:[core_dist_index_es_z.pairing_started]}});this.isValidPair(s,i);const{topic:r,symKey:n,relay:a,expiryTimestamp:c,methods:h}=Vr(s.uri);i.props.properties.topic=r,i.addTrace(core_dist_index_es_z.pairing_uri_validation_success),i.addTrace(core_dist_index_es_z.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(r)){if(u=this.pairings.get(r),i.addTrace(core_dist_index_es_z.existing_pairing),u.active)throw i.setError(index_es_$.active_pairing_already_exists),new Error(`Pairing already exists: ${r}. Please try again with a new connection URI.`);i.addTrace(core_dist_index_es_z.pairing_not_expired)}const d=c||Lt(cjs.FIVE_MINUTES),y={topic:r,relay:a,expiry:d,active:!1,methods:h};this.core.expirer.set(r,d),await this.pairings.set(r,y),i.addTrace(core_dist_index_es_z.store_new_pairing),s.activatePairing&&await this.activate({topic:r}),this.events.emit(index_es_j.create,y),i.addTrace(core_dist_index_es_z.emit_inactive_pairing),this.core.crypto.keychain.has(r)||await this.core.crypto.setSymKey(n,r),i.addTrace(core_dist_index_es_z.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(index_es_$.no_internet_connection)}try{await this.core.relayer.subscribe(r,{relay:a})}catch(m){throw i.setError(index_es_$.subscribe_pairing_topic_failure),m}return i.addTrace(core_dist_index_es_z.subscribe_pairing_topic_success),y},this.activate=async({topic:s})=>{this.isInitialized();const i=Lt(cjs.THIRTY_DAYS);this.core.expirer.set(s,i),await this.pairings.update(s,{active:!0,expiry:i})},this.ping=async s=>{this.isInitialized(),await this.isValidPing(s);const{topic:i}=s;if(this.pairings.keys.includes(i)){const r=await this.sendRequest(i,"wc_pairingPing",{}),{done:n,resolve:a,reject:c}=Dt();this.events.once(qt("pairing_ping",r),({error:h})=>{h?c(h):a()}),await n()}},this.updateExpiry=async({topic:s,expiry:i})=>{this.isInitialized(),await this.pairings.update(s,{expiry:i})},this.updateMetadata=async({topic:s,metadata:i})=>{this.isInitialized(),await this.pairings.update(s,{peerMetadata:i})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async s=>{this.isInitialized(),await this.isValidDisconnect(s);const{topic:i}=s;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",index_es_("USER_DISCONNECTED")),await this.deletePairing(i))},this.formatUriFromPairing=s=>{this.isInitialized();const{topic:i,relay:r,expiry:n,methods:a}=s,c=this.core.crypto.keychain.get(i);return Mr({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:r,expiryTimestamp:n,methods:a})},this.sendRequest=async(s,i,r)=>{const n=formatJsonRpcRequest(i,r),a=await this.core.crypto.encode(s,n),c=index_es_V[i].req;return this.core.history.set(s,n),this.core.relayer.publish(s,a,c),n.id},this.sendResult=async(s,i,r)=>{const n=formatJsonRpcResult(s,r),a=await this.core.crypto.encode(i,n),c=await this.core.history.get(i,s),h=index_es_V[c.request.method].res;await this.core.relayer.publish(i,a,h),await this.core.history.resolve(n)},this.sendError=async(s,i,r)=>{const n=formatJsonRpcError(s,r),a=await this.core.crypto.encode(i,n),c=await this.core.history.get(i,s),h=index_es_V[c.request.method]?index_es_V[c.request.method].res:index_es_V.unregistered_method.res;await this.core.relayer.publish(i,a,h),await this.core.history.resolve(n)},this.deletePairing=async(s,i)=>{await this.core.relayer.unsubscribe(s),await Promise.all([this.pairings.delete(s,index_es_("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(s),i?Promise.resolve():this.core.expirer.del(s)])},this.cleanup=async()=>{const s=this.pairings.getAll().filter(i=>Ft(i.expiry));await Promise.all(s.map(i=>this.deletePairing(i.topic)))},this.onRelayEventRequest=s=>{const{topic:i,payload:r}=s;switch(r.method){case"wc_pairingPing":return this.onPairingPingRequest(i,r);case"wc_pairingDelete":return this.onPairingDeleteRequest(i,r);default:return this.onUnknownRpcMethodRequest(i,r)}},this.onRelayEventResponse=async s=>{const{topic:i,payload:r}=s,n=(await this.core.history.get(i,r.id)).request.method;switch(n){case"wc_pairingPing":return this.onPairingPingResponse(i,r);default:return this.onUnknownRpcMethodResponse(n)}},this.onPairingPingRequest=async(s,i)=>{const{id:r}=i;try{this.isValidPing({topic:s}),await this.sendResult(r,s,!0),this.events.emit(index_es_j.ping,{id:r,topic:s})}catch(n){await this.sendError(r,s,n),this.logger.error(n)}},this.onPairingPingResponse=(s,i)=>{const{id:r}=i;setTimeout(()=>{isJsonRpcResult(i)?this.events.emit(qt("pairing_ping",r),{}):isJsonRpcError(i)&&this.events.emit(qt("pairing_ping",r),{error:i.error})},500)},this.onPairingDeleteRequest=async(s,i)=>{const{id:r}=i;try{this.isValidDisconnect({topic:s}),await this.deletePairing(s),this.events.emit(index_es_j.delete,{id:r,topic:s})}catch(n){await this.sendError(r,s,n),this.logger.error(n)}},this.onUnknownRpcMethodRequest=async(s,i)=>{const{id:r,method:n}=i;try{if(this.registeredMethods.includes(n))return;const a=index_es_("WC_METHOD_UNSUPPORTED",n);await this.sendError(r,s,a),this.logger.error(a)}catch(a){await this.sendError(r,s,a),this.logger.error(a)}},this.onUnknownRpcMethodResponse=s=>{this.registeredMethods.includes(s)||this.logger.error(index_es_("WC_METHOD_UNSUPPORTED",s))},this.isValidPair=(s,i)=>{var r;if(!so(s)){const{message:a}=index_es_S("MISSING_OR_INVALID",`pair() params: ${s}`);throw i.setError(index_es_$.malformed_pairing_uri),new Error(a)}if(!Zr(s.uri)){const{message:a}=index_es_S("MISSING_OR_INVALID",`pair() uri: ${s.uri}`);throw i.setError(index_es_$.malformed_pairing_uri),new Error(a)}const n=Vr(s?.uri);if(!((r=n?.relay)!=null&&r.protocol)){const{message:a}=index_es_S("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(index_es_$.malformed_pairing_uri),new Error(a)}if(!(n!=null&&n.symKey)){const{message:a}=index_es_S("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(index_es_$.malformed_pairing_uri),new Error(a)}if(n!=null&&n.expiryTimestamp&&(0,cjs.toMiliseconds)(n?.expiryTimestamp){if(!so(s)){const{message:r}=index_es_S("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(r)}const{topic:i}=s;await this.isValidPairingTopic(i)},this.isValidDisconnect=async s=>{if(!so(s)){const{message:r}=index_es_S("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(r)}const{topic:i}=s;await this.isValidPairingTopic(i)},this.isValidPairingTopic=async s=>{if(!index_es_b(s,!1)){const{message:i}=index_es_S("MISSING_OR_INVALID",`pairing topic should be a string: ${s}`);throw new Error(i)}if(!this.pairings.keys.includes(s)){const{message:i}=index_es_S("NO_MATCHING_KEY",`pairing topic doesn't exist: ${s}`);throw new Error(i)}if(Ft(this.pairings.get(s).expiry)){await this.deletePairing(s);const{message:i}=index_es_S("EXPIRED",`pairing topic: ${s}`);throw new Error(i)}},this.core=e,this.logger=dist_index_es_E(t,this.name),this.pairings=new li(this.core,this.logger,this.name,this.storagePrefix)}get context(){return dist_index_es_y(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=index_es_S("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(core_dist_index_es_v.message,async e=>{const{topic:t,message:s,transportType:i}=e;if(!this.pairings.keys.includes(t)||i===dist_index_es_M.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))return;const r=await this.core.crypto.decode(t,s);try{isJsonRpcRequest(r)?(this.core.history.set(t,r),this.onRelayEventRequest({topic:t,payload:r})):isJsonRpcResponse(r)&&(await this.core.history.resolve(r),await this.onRelayEventResponse({topic:t,payload:r}),this.core.history.delete(t,r.id))}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(core_dist_index_es_x.expired,async e=>{const{topic:t}=Kt(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(index_es_j.expire,{topic:t}))})}}class di extends dist_index_es_h{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.records=new Map,this.events=new external_events_.EventEmitter,this.name=index_es_mt,this.version=index_es_bt,this.cached=[],this.initialized=!1,this.storagePrefix=dist_index_es_A,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(s=>this.records.set(s.id,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(s,i,r)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:s,request:i,chainId:r}),this.records.has(i.id))return;const n={id:i.id,topic:s,request:{method:i.method,params:i.params||null},chainId:r,expiry:Lt(cjs.THIRTY_DAYS)};this.records.set(n.id,n),this.persist(),this.events.emit(dist_index_es_R.created,n)},this.resolve=async s=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:s}),!this.records.has(s.id))return;const i=await this.getRecord(s.id);typeof i.response>"u"&&(i.response=isJsonRpcError(s)?{error:s.error}:{result:s.result},this.records.set(i.id,i),this.persist(),this.events.emit(dist_index_es_R.updated,i))},this.get=async(s,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:s,id:i}),await this.getRecord(i)),this.delete=(s,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(r=>{if(r.topic===s){if(typeof i<"u"&&r.id!==i)return;this.records.delete(r.id),this.events.emit(dist_index_es_R.deleted,r)}}),this.persist()},this.exists=async(s,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===s:!1),this.on=(s,i)=>{this.events.on(s,i)},this.once=(s,i)=>{this.events.once(s,i)},this.off=(s,i)=>{this.events.off(s,i)},this.removeListener=(s,i)=>{this.events.removeListener(s,i)},this.logger=dist_index_es_E(t,this.name)}get context(){return dist_index_es_y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const s={topic:t.topic,request:formatJsonRpcRequest(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(s)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:s}=index_es_S("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(dist_index_es_R.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=index_es_S("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(dist_index_es_R.created,e=>{const t=dist_index_es_R.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(dist_index_es_R.updated,e=>{const t=dist_index_es_R.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(dist_index_es_R.deleted,e=>{const t=dist_index_es_R.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(r.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{(0,cjs.toMiliseconds)(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(dist_index_es_R.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=index_es_S("NOT_INITIALIZED",this.name);throw new Error(e)}}}class pi extends dist_index_es_x{constructor(e,t){super(e,t),this.core=e,this.logger=t,this.expirations=new Map,this.events=new external_events_.EventEmitter,this.name=index_es_ft,this.version=index_es_vt,this.cached=[],this.initialized=!1,this.storagePrefix=dist_index_es_A,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(s=>this.expirations.set(s.target,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=s=>{try{const i=this.formatTarget(s);return typeof this.getExpiration(i)<"u"}catch{return!1}},this.set=(s,i)=>{this.isInitialized();const r=this.formatTarget(s),n={target:r,expiry:i};this.expirations.set(r,n),this.checkExpiry(r,n),this.events.emit(core_dist_index_es_x.created,{target:r,expiration:n})},this.get=s=>{this.isInitialized();const i=this.formatTarget(s);return this.getExpiration(i)},this.del=s=>{if(this.isInitialized(),this.has(s)){const i=this.formatTarget(s),r=this.getExpiration(i);this.expirations.delete(i),this.events.emit(core_dist_index_es_x.deleted,{target:i,expiration:r})}},this.on=(s,i)=>{this.events.on(s,i)},this.once=(s,i)=>{this.events.once(s,i)},this.off=(s,i)=>{this.events.off(s,i)},this.removeListener=(s,i)=>{this.events.removeListener(s,i)},this.logger=dist_index_es_E(t,this.name)}get context(){return dist_index_es_y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return Vt(e);if(typeof e=="number")return Mt(e);const{message:t}=index_es_S("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(core_dist_index_es_x.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=index_es_S("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:s}=index_es_S("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(s),new Error(s)}return t}checkExpiry(e,t){const{expiry:s}=t;(0,cjs.toMiliseconds)(s)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(core_dist_index_es_x.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(r.pulse,()=>this.checkExpirations()),this.events.on(core_dist_index_es_x.created,e=>{const t=core_dist_index_es_x.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(core_dist_index_es_x.expired,e=>{const t=core_dist_index_es_x.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(core_dist_index_es_x.deleted,e=>{const t=core_dist_index_es_x.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=index_es_S("NOT_INITIALIZED",this.name);throw new Error(e)}}}class gi extends types_dist_index_es_y{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,this.name=index_es_t,this.verifyUrlV3=index_es_wt,this.storagePrefix=dist_index_es_A,this.version=index_es_De,this.init=async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&(0,cjs.toMiliseconds)((i=this.publicKey)==null?void 0:i.expiresAt){if(!V()||this.isDevEnv)return;const r=window.location.origin,{id:n,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${r}&id=${n}&decryptedId=${a}`;try{const h=(0,dist_cjs.getDocument)(),u=this.startAbortTimer(cjs.ONE_SECOND*5),d=await new Promise((y,m)=>{const l=()=>{window.removeEventListener("message",w),h.body.removeChild(g),m("attestation aborted")};this.abortController.signal.addEventListener("abort",l);const g=h.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",l,{signal:this.abortController.signal});const w=b=>{if(b.data&&typeof b.data=="string")try{const D=JSON.parse(b.data);if(D.type==="verify_attestation"){if(utils_decodeJWT(D.attestation).payload.id!==n)return;clearInterval(u),h.body.removeChild(g),this.abortController.signal.removeEventListener("abort",l),window.removeEventListener("message",w),y(D.attestation===null?"":D.attestation)}}catch(D){this.logger.warn(D)}};h.body.appendChild(g),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",d),d}catch(h){this.logger.warn(h)}return""},this.resolve=async i=>{if(this.isDevEnv)return"";const{attestationId:r,hash:n,encryptedId:a}=i;if(r===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(r){if(utils_decodeJWT(r).payload.id!==a)return;const h=await this.isValidJwtAttestation(r);if(h){if(!h.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return h}}if(!n)return;const c=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(n,c)},this.fetchAttestation=async(i,r)=>{this.logger.debug(`resolving attestation: ${i} from url: ${r}`);const n=this.startAbortTimer(cjs.ONE_SECOND*5),a=await fetch(`${r}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(n),a.status===200?await a.json():void 0},this.getVerifyUrl=i=>{let r=i||index_es_X;return index_es_It.includes(r)||(this.logger.info(`verify url: ${r}, not included in trusted list, assigning default: ${index_es_X}`),r=index_es_X),r},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(cjs.FIVE_SECONDS),r=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await r.json()}catch(i){this.logger.warn(i)}},this.persistPublicKey=async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i},this.removePublicKey=async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async i=>{const r=await this.getPublicKey();try{if(r)return this.validateAttestation(i,r)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const n=await this.fetchAndPersistPublicKey();try{if(n)return this.validateAttestation(i,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async r=>{const n=await this.fetchPublicKey();n&&(await this.persistPublicKey(n),r(n))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i},this.validateAttestation=(i,r)=>{const n=jr(i,r.publicKey),a={hasExpired:(0,cjs.toMiliseconds)(n.exp)this.abortController.abort(),(0,cjs.toMiliseconds)(e))}}class yi extends index_es_v{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.context=index_es_Tt,this.registerDeviceToken=async s=>{const{clientId:i,token:r,notificationType:n,enableEncrypted:a=!1}=s,c=`${dist_index_es_Ct}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:n,token:r,always_raw:a})})},this.logger=dist_index_es_E(t,this.context)}}var index_es_wn=Object.defineProperty,Di=Object.getOwnPropertySymbols,index_es_In=Object.prototype.hasOwnProperty,index_es_Tn=Object.prototype.propertyIsEnumerable,mi=(o,e,t)=>e in o?index_es_wn(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,index_es_Q=(o,e)=>{for(var t in e||(e={}))index_es_In.call(e,t)&&mi(o,t,e[t]);if(Di)for(var t of Di(e))index_es_Tn.call(e,t)&&mi(o,t,e[t]);return o};class bi extends types_dist_index_es_C{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,this.context=index_es_St,this.storagePrefix=dist_index_es_A,this.storageVersion=index_es_Pt,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!zt())try{const i={eventId:Jt(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Ge(this.core.relayer.protocol,this.core.relayer.version,index_es_re)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}},this.createEvent=i=>{const{event:r="ERROR",type:n="",properties:{topic:a,trace:c}}=i,h=Jt(),u=this.core.projectId||"",d=Date.now(),y=index_es_Q({eventId:h,timestamp:d,props:{event:r,type:n,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(h));return this.telemetryEnabled&&(this.events.set(h,y),this.shouldPersist=!0),y},this.getEvent=i=>{const{eventId:r,topic:n}=i;if(r)return this.events.get(r);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===n);if(a)return index_es_Q(index_es_Q({},a),this.setMethods(a.eventId))},this.deleteEvent=i=>{const{eventId:r}=i;this.events.delete(r),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(r.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{(0,cjs.fromMiliseconds)(Date.now())-(0,cjs.fromMiliseconds)(i.timestamp)>index_es_Rt&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})},this.setMethods=i=>({addTrace:r=>this.addTrace(i,r),setError:r=>this.setError(i,r)}),this.addTrace=(i,r)=>{const n=this.events.get(i);n&&(n.props.properties.trace.push(r),this.events.set(i,n),this.shouldPersist=!0)},this.setError=(i,r)=>{const n=this.events.get(i);n&&(n.props.type=r,n.timestamp=Date.now(),this.events.set(i,n),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},this.restore=async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(r=>{this.events.set(r.eventId,index_es_Q(index_es_Q({},r),this.setMethods(r.eventId)))})}catch(i){this.logger.warn(i)}},this.submit=async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[r,n]of this.events)n.props.type&&i.push(n);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const r of i)this.events.delete(r.eventId),this.shouldPersist=!0}catch(r){this.logger.warn(r)}},this.sendEvent=async i=>{const r=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${index_es_xt}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${index_es_re}${r}`,{method:"POST",body:JSON.stringify(i)})},this.getAppDomain=()=>$t().url,this.logger=dist_index_es_E(t,this.context),this.telemetryEnabled=s,s?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var index_es_Cn=Object.defineProperty,fi=Object.getOwnPropertySymbols,index_es_Pn=Object.prototype.hasOwnProperty,index_es_Sn=Object.prototype.propertyIsEnumerable,vi=(o,e,t)=>e in o?index_es_Cn(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,_i=(o,e)=>{for(var t in e||(e={}))index_es_Pn.call(e,t)&&vi(o,t,e[t]);if(fi)for(var t of fi(e))index_es_Sn.call(e,t)&&vi(o,t,e[t]);return o};class index_es_oe extends types_dist_index_es_n{constructor(e){var t;super(e),this.protocol=index_es_ye,this.version=index_es_De,this.name=index_es_J,this.events=new external_events_.EventEmitter,this.initialized=!1,this.on=(n,a)=>this.events.on(n,a),this.once=(n,a)=>this.events.once(n,a),this.off=(n,a)=>this.events.off(n,a),this.removeListener=(n,a)=>this.events.removeListener(n,a),this.dispatchEnvelope=({topic:n,message:a,sessionExists:c})=>{if(!n||!a)return;const h={topic:n,message:a,publishedAt:Date.now(),transportType:dist_index_es_M.link_mode};this.relayer.onLinkMessageEvent(h,{sessionExists:c})},this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||fe,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const s=logger_dist_index_es_k({level:typeof e?.logger=="string"&&e.logger?e.logger:index_es_Xe.logger,name:index_es_J}),{logger:i,chunkLoggerController:r}=index_es_A({opts:s,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=r,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var n,a;(n=this.logChunkController)!=null&&n.downloadLogsBlobInBrowser&&((a=this.logChunkController)==null||a.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=dist_index_es_E(i,this.name),this.heartbeat=new index_es_i,this.crypto=new index_es_Yt(this,this.logger,e?.keychain),this.history=new di(this,this.logger),this.expirer=new pi(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new index_es_h(_i(_i({},index_es_We),e?.storageOptions)),this.relayer=new oi({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new ui(this,this.logger),this.verify=new gi(this,this.logger,this.storage),this.echoClient=new yi(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new bi(this,this.logger,e?.telemetryEnabled)}static async init(e){const t=new index_es_oe(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem(ut,s),t}get context(){return dist_index_es_y(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(index_es_ve,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.eventClient.init(),this.linkModeSupportedApps=await this.storage.getItem(index_es_ve)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}}const index_es_Rn=index_es_oe;
//# sourceMappingURL=index.es.js.map
;// ./node_modules/@walletconnect/sign-client/dist/index.es.js
-const dist_index_es_be="wc",Ce=2,index_es_Le="client",dist_index_es_ye=`${dist_index_es_be}@${Ce}:${index_es_Le}:`,dist_index_es_we={name:index_es_Le,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},cs={session_proposal:"session_proposal",session_update:"session_update",session_extend:"session_extend",session_ping:"session_ping",session_delete:"session_delete",session_expire:"session_expire",session_request:"session_request",session_request_sent:"session_request_sent",session_event:"session_event",proposal_expire:"proposal_expire",session_authenticate:"session_authenticate",session_request_expire:"session_request_expire"},ls={database:":memory:"},index_es_xe="WALLETCONNECT_DEEPLINK_CHOICE",ps={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},hs="history",ds="0.3",index_es_st="proposal",us=(/* unused pure expression or super */ null && (ss)),index_es_it="Proposal expired",index_es_rt="session",sign_client_dist_index_es_z=cjs.SEVEN_DAYS,index_es_nt="engine",sign_client_dist_index_es_v={wc_sessionPropose:{req:{ttl:cjs.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:cjs.ONE_DAY,prompt:!1,tag:1104},res:{ttl:cjs.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:cjs.ONE_DAY,prompt:!1,tag:1106},res:{ttl:cjs.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:cjs.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:cjs.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:cjs.ONE_DAY,prompt:!1,tag:1112},res:{ttl:cjs.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:cjs.ONE_DAY,prompt:!1,tag:1114},res:{ttl:cjs.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:cjs.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:cjs.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1119}}},dist_index_es_me={min:cjs.FIVE_MINUTES,max:cjs.SEVEN_DAYS},sign_client_dist_index_es_x={idle:"IDLE",active:"ACTIVE"},index_es_ot="request",index_es_at=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],index_es_ct="wc",gs=1.5,index_es_lt="auth",dist_index_es_pt="authKeys",dist_index_es_ht="pairingTopics",index_es_dt="requests",index_es_oe=`${index_es_ct}@${1.5}:${index_es_lt}:`,index_es_ae=`${index_es_oe}:PUB_KEY`;var ys=Object.defineProperty,index_es_ws=Object.defineProperties,index_es_ms=Object.getOwnPropertyDescriptors,index_es_ut=Object.getOwnPropertySymbols,index_es_s=Object.prototype.hasOwnProperty,index_es_Es=Object.prototype.propertyIsEnumerable,dist_index_es_gt=(q,o,e)=>o in q?ys(q,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):q[o]=e,sign_client_dist_index_es_I=(q,o)=>{for(var e in o||(o={}))index_es_s.call(o,e)&&dist_index_es_gt(q,e,o[e]);if(index_es_ut)for(var e of index_es_ut(o))index_es_Es.call(o,e)&&dist_index_es_gt(q,e,o[e]);return q},dist_index_es_D=(q,o)=>index_es_ws(q,index_es_ms(o));class index_es_Rs extends M{constructor(o){super(o),this.name=index_es_nt,this.events=new (external_events_default()),this.initialized=!1,this.requestQueue={state:sign_client_dist_index_es_x.idle,queue:[]},this.sessionRequestQueue={state:sign_client_dist_index_es_x.idle,queue:[]},this.requestQueueDelay=cjs.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(sign_client_dist_index_es_v)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},(0,cjs.toMiliseconds)(this.requestQueueDelay)))},this.connect=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const t=dist_index_es_D(sign_client_dist_index_es_I({},e),{requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}});await this.isValidConnect(t);const{pairingTopic:s,requiredNamespaces:i,optionalNamespaces:r,sessionProperties:n,relays:a}=t;let c=s,h,p=!1;try{c&&(p=this.client.core.pairing.pairings.get(c).active)}catch(E){throw this.client.logger.error(`connect() -> pairing.get(${c}) failed`),E}if(!c||!p){const{topic:E,uri:S}=await this.client.core.pairing.create();c=E,h=S}if(!c){const{message:E}=index_es_S("NO_MATCHING_KEY",`connect() pairing topic: ${c}`);throw new Error(E)}const d=await this.client.core.crypto.generateKeyPair(),l=sign_client_dist_index_es_v.wc_sessionPropose.req.ttl||cjs.FIVE_MINUTES,w=Mt(l),m=sign_client_dist_index_es_I({requiredNamespaces:i,optionalNamespaces:r,relays:a??[{protocol:rt}],proposer:{publicKey:d,metadata:this.client.metadata},expiryTimestamp:w,pairingTopic:c},n&&{sessionProperties:n}),{reject:y,resolve:_,done:R}=_t(l,index_es_it);this.events.once(Lt("session_connect"),async({error:E,session:S})=>{if(E)y(E);else if(S){S.self.publicKey=d;const M=dist_index_es_D(sign_client_dist_index_es_I({},S),{pairingTopic:m.pairingTopic,requiredNamespaces:m.requiredNamespaces,optionalNamespaces:m.optionalNamespaces,transportType:dist_index_es_M.relay});await this.client.session.set(S.topic,M),await this.setExpiry(S.topic,S.expiry),c&&await this.client.core.pairing.updateMetadata({topic:c,metadata:S.peer.metadata}),this.cleanupDuplicatePairings(M),_(M)}});const V=await this.sendRequest({topic:c,method:"wc_sessionPropose",params:m,throwOnFailedPublish:!0});return await this.setProposal(V,sign_client_dist_index_es_I({id:V},m)),{uri:h,approval:R}},this.pair=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(e)}catch(t){throw this.client.logger.error("pair() failed"),t}},this.approve=async e=>{var t,s,i;const r=this.client.core.eventClient.createEvent({properties:{topic:(t=e?.id)==null?void 0:t.toString(),trace:[Is.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(N){throw r.setError(Ts.no_internet_connection),N}try{await this.isValidProposalId(e?.id)}catch(N){throw this.client.logger.error(`approve() -> proposal.get(${e?.id}) failed`),r.setError(Ts.proposal_not_found),N}try{await this.isValidApprove(e)}catch(N){throw this.client.logger.error("approve() -> isValidApprove() failed"),r.setError(Ts.session_approve_namespace_validation_failure),N}const{id:n,relayProtocol:a,namespaces:c,sessionProperties:h,sessionConfig:p}=e,d=this.client.proposal.get(n);this.client.core.eventClient.deleteEvent({eventId:r.eventId});const{pairingTopic:l,proposer:w,requiredNamespaces:m,optionalNamespaces:y}=d;let _=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:l});_||(_=(i=this.client.core.eventClient)==null?void 0:i.createEvent({type:Is.session_approve_started,properties:{topic:l,trace:[Is.session_approve_started,Is.session_namespaces_validation_success]}}));const R=await this.client.core.crypto.generateKeyPair(),V=w.publicKey,E=await this.client.core.crypto.generateSharedKey(R,V),S=sign_client_dist_index_es_I(sign_client_dist_index_es_I({relay:{protocol:a??"irn"},namespaces:c,controller:{publicKey:R,metadata:this.client.metadata},expiry:Mt(sign_client_dist_index_es_z)},h&&{sessionProperties:h}),p&&{sessionConfig:p}),M=dist_index_es_M.relay;_.addTrace(Is.subscribing_session_topic);try{await this.client.core.relayer.subscribe(E,{transportType:M})}catch(N){throw _.setError(Ts.subscribe_session_topic_failure),N}_.addTrace(Is.subscribe_session_topic_success);const W=dist_index_es_D(sign_client_dist_index_es_I({},S),{topic:E,requiredNamespaces:m,optionalNamespaces:y,pairingTopic:l,acknowledged:!1,self:S.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:R,transportType:dist_index_es_M.relay});await this.client.session.set(E,W),_.addTrace(Is.store_session);try{_.addTrace(Is.publishing_session_settle),await this.sendRequest({topic:E,method:"wc_sessionSettle",params:S,throwOnFailedPublish:!0}).catch(N=>{throw _?.setError(Ts.session_settle_publish_failure),N}),_.addTrace(Is.session_settle_publish_success),_.addTrace(Is.publishing_session_approve),await this.sendResult({id:n,topic:l,result:{relay:{protocol:a??"irn"},responderPublicKey:R},throwOnFailedPublish:!0}).catch(N=>{throw _?.setError(Ts.session_approve_publish_failure),N}),_.addTrace(Is.session_approve_publish_success)}catch(N){throw this.client.logger.error(N),this.client.session.delete(E,U("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(E),N}return this.client.core.eventClient.deleteEvent({eventId:_.eventId}),await this.client.core.pairing.updateMetadata({topic:l,metadata:w.metadata}),await this.client.proposal.delete(n,U("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:l}),await this.setExpiry(E,Mt(sign_client_dist_index_es_z)),{topic:E,acknowledged:()=>Promise.resolve(this.client.session.get(E))}},this.reject=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(e)}catch(r){throw this.client.logger.error("reject() -> isValidReject() failed"),r}const{id:t,reason:s}=e;let i;try{i=this.client.proposal.get(t).pairingTopic}catch(r){throw this.client.logger.error(`reject() -> proposal.get(${t}) failed`),r}i&&(await this.sendError({id:t,topic:i,error:s,rpcOpts:sign_client_dist_index_es_v.wc_sessionPropose.reject}),await this.client.proposal.delete(t,U("USER_DISCONNECTED")))},this.update=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(e)}catch(p){throw this.client.logger.error("update() -> isValidUpdate() failed"),p}const{topic:t,namespaces:s}=e,{done:i,resolve:r,reject:n}=_t(),a=payloadId(),c=getBigIntRpcId().toString(),h=this.client.session.get(t).namespaces;return this.events.once(Lt("session_update",a),({error:p})=>{p?n(p):r()}),await this.client.session.update(t,{namespaces:s}),await this.sendRequest({topic:t,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:a,relayRpcId:c}).catch(p=>{this.client.logger.error(p),this.client.session.update(t,{namespaces:h}),n(p)}),{acknowledged:i}},this.extend=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(e)}catch(a){throw this.client.logger.error("extend() -> isValidExtend() failed"),a}const{topic:t}=e,s=payloadId(),{done:i,resolve:r,reject:n}=_t();return this.events.once(Lt("session_extend",s),({error:a})=>{a?n(a):r()}),await this.setExpiry(t,Mt(sign_client_dist_index_es_z)),this.sendRequest({topic:t,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(a=>{n(a)}),{acknowledged:i}},this.request=async e=>{this.isInitialized();try{await this.isValidRequest(e)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:t,request:s,topic:i,expiry:r=sign_client_dist_index_es_v.wc_sessionRequest.req.ttl}=e,n=this.client.session.get(i);n?.transportType===dist_index_es_M.relay&&await this.confirmOnlineStateOrThrow();const a=payloadId(),c=getBigIntRpcId().toString(),{done:h,resolve:p,reject:d}=_t(r,"Request expired. Please try again.");this.events.once(Lt("session_request",a),({error:w,result:m})=>{w?d(w):p(m)});const l=this.getAppLinkIfEnabled(n.peer.metadata,n.transportType);return l?(await this.sendRequest({clientRpcId:a,relayRpcId:c,topic:i,method:"wc_sessionRequest",params:{request:dist_index_es_D(sign_client_dist_index_es_I({},s),{expiryTimestamp:Mt(r)}),chainId:t},expiry:r,throwOnFailedPublish:!0,appLink:l}).catch(w=>d(w)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:t,id:a}),await h()):await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:a,relayRpcId:c,topic:i,method:"wc_sessionRequest",params:{request:dist_index_es_D(sign_client_dist_index_es_I({},s),{expiryTimestamp:Mt(r)}),chainId:t},expiry:r,throwOnFailedPublish:!0}).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:t,id:a}),w()}),new Promise(async w=>{var m;if(!((m=n.sessionConfig)!=null&&m.disableDeepLink)){const y=await qt(this.client.core.storage,index_es_xe);await Ft({id:a,topic:i,wcDeepLink:y})}w()}),h()]).then(w=>w[2])},this.respond=async e=>{this.isInitialized(),await this.isValidRespond(e);const{topic:t,response:s}=e,{id:i}=s,r=this.client.session.get(t);r.transportType===dist_index_es_M.relay&&await this.confirmOnlineStateOrThrow();const n=this.getAppLinkIfEnabled(r.peer.metadata,r.transportType);isJsonRpcResult(s)?await this.sendResult({id:i,topic:t,result:s.result,throwOnFailedPublish:!0,appLink:n}):isJsonRpcError(s)&&await this.sendError({id:i,topic:t,error:s.error,appLink:n}),this.cleanupAfterResponse(e)},this.ping=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(e)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:t}=e;if(this.client.session.keys.includes(t)){const s=payloadId(),i=getBigIntRpcId().toString(),{done:r,resolve:n,reject:a}=_t();this.events.once(Lt("session_ping",s),({error:c})=>{c?a(c):n()}),await Promise.all([this.sendRequest({topic:t,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:i}),r()])}else this.client.core.pairing.pairings.keys.includes(t)&&await this.client.core.pairing.ping({topic:t})},this.emit=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(e);const{topic:t,event:s,chainId:i}=e,r=getBigIntRpcId().toString();await this.sendRequest({topic:t,method:"wc_sessionEvent",params:{event:s,chainId:i},throwOnFailedPublish:!0,relayRpcId:r})},this.disconnect=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(e);const{topic:t}=e;if(this.client.session.keys.includes(t))await this.sendRequest({topic:t,method:"wc_sessionDelete",params:U("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:t,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(t))await this.client.core.pairing.disconnect({topic:t});else{const{message:s}=index_es_S("MISMATCHED_TOPIC",`Session or pairing topic not found: ${t}`);throw new Error(s)}},this.find=e=>(this.isInitialized(),this.client.session.getAll().filter(t=>zr(t,e))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(e,t)=>{var s;this.isInitialized(),this.isValidAuthenticate(e);const i=t&&this.client.core.linkModeSupportedApps.includes(t)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),r=i?dist_index_es_M.link_mode:dist_index_es_M.relay;r===dist_index_es_M.relay&&await this.confirmOnlineStateOrThrow();const{chains:n,statement:a="",uri:c,domain:h,nonce:p,type:d,exp:l,nbf:w,methods:m=[],expiry:y}=e,_=[...e.resources||[]],{topic:R,uri:V}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:r});this.client.logger.info({message:"Generated new pairing",pairing:{topic:R,uri:V}});const E=await this.client.core.crypto.generateKeyPair(),S=hr(E);if(await Promise.all([this.client.auth.authKeys.set(index_es_ae,{responseTopic:S,publicKey:E}),this.client.auth.pairingTopics.set(S,{topic:S,pairingTopic:R})]),await this.client.core.relayer.subscribe(S,{transportType:r}),this.client.logger.info(`sending request to new pairing topic: ${R}`),m.length>0){const{namespace:O}=re(n[0]);let T=ir(O,"request",m);Y(_)&&(T=cr(T,_.pop())),_.push(T)}const M=y&&y>sign_client_dist_index_es_v.wc_sessionAuthenticate.req.ttl?y:sign_client_dist_index_es_v.wc_sessionAuthenticate.req.ttl,W={authPayload:{type:d??"caip122",chains:n,statement:a,aud:c,domain:h,version:"1",nonce:p,iat:new Date().toISOString(),exp:l,nbf:w,resources:_},requester:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:Mt(M)},N={eip155:{chains:n,methods:[...new Set(["personal_sign",...m])],events:["chainChanged","accountsChanged"]}},De={requiredNamespaces:{},optionalNamespaces:N,relays:[{protocol:"irn"}],pairingTopic:R,proposer:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:Mt(sign_client_dist_index_es_v.wc_sessionPropose.req.ttl)},{done:wt,resolve:Ve,reject:Ee}=_t(M,"Request expired"),ce=async({error:O,session:T})=>{if(this.events.off(Lt("session_request",G),Re),O)Ee(O);else if(T){T.self.publicKey=E,await this.client.session.set(T.topic,T),await this.setExpiry(T.topic,T.expiry),R&&await this.client.core.pairing.updateMetadata({topic:R,metadata:T.peer.metadata});const le=this.client.session.get(T.topic);await this.deleteProposal(Z),Ve({session:le})}},Re=async O=>{var T,le,Me;if(await this.deletePendingAuthRequest(G,{message:"fulfilled",code:0}),O.error){const te=U("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return O.error.code===te.code?void 0:(this.events.off(Lt("session_connect"),ce),Ee(O.error.message))}await this.deleteProposal(Z),this.events.off(Lt("session_connect"),ce);const{cacaos:ke,responder:j}=O.result,Ie=[],$e=[];for(const te of ke){await nr({cacao:te,projectId:this.client.core.projectId})||(this.client.logger.error(te,"Signature verification failed"),Ee(U("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:fe}=te,ve=Y(fe.resources),Ke=[ln(fe.iss)],mt=index_es_fe(fe.iss);if(ve){const qe=ar(ve),_t=ur(ve);Ie.push(...qe),Ke.push(..._t)}for(const qe of Ke)$e.push(`${qe}:${mt}`)}const ee=await this.client.core.crypto.generateSharedKey(E,j.publicKey);let pe;Ie.length>0&&(pe={topic:ee,acknowledged:!0,self:{publicKey:E,metadata:this.client.metadata},peer:j,controller:j.publicKey,expiry:Mt(sign_client_dist_index_es_z),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:R,namespaces:Jr([...new Set(Ie)],[...new Set($e)]),transportType:r},await this.client.core.relayer.subscribe(ee,{transportType:r}),await this.client.session.set(ee,pe),R&&await this.client.core.pairing.updateMetadata({topic:R,metadata:j.metadata}),pe=this.client.session.get(ee)),(T=this.client.metadata.redirect)!=null&&T.linkMode&&(le=j.metadata.redirect)!=null&&le.linkMode&&(Me=j.metadata.redirect)!=null&&Me.universal&&t&&(this.client.core.addLinkModeSupportedApp(j.metadata.redirect.universal),this.client.session.update(ee,{transportType:dist_index_es_M.link_mode})),Ve({auths:ke,session:pe})},G=payloadId(),Z=payloadId();this.events.once(Lt("session_connect"),ce),this.events.once(Lt("session_request",G),Re);let Se;try{if(i){const O=formatJsonRpcRequest("wc_sessionAuthenticate",W,G);this.client.core.history.set(R,O);const T=await this.client.core.crypto.encode("",O,{type:index_es_M,encoding:lr});Se=xr(t,R,T)}else await Promise.all([this.sendRequest({topic:R,method:"wc_sessionAuthenticate",params:W,expiry:e.expiry,throwOnFailedPublish:!0,clientRpcId:G}),this.sendRequest({topic:R,method:"wc_sessionPropose",params:De,expiry:sign_client_dist_index_es_v.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:Z})])}catch(O){throw this.events.off(Lt("session_connect"),ce),this.events.off(Lt("session_request",G),Re),O}return await this.setProposal(Z,sign_client_dist_index_es_I({id:Z},De)),await this.setAuthRequest(G,{request:dist_index_es_D(sign_client_dist_index_es_I({},W),{verifyContext:{}}),pairingTopic:R,transportType:r}),{uri:Se??V,response:wt}},this.approveSessionAuthenticate=async e=>{const{id:t,auths:s}=e,i=this.client.core.eventClient.createEvent({properties:{topic:t.toString(),trace:[Cs.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw i.setError(Ps.no_internet_connection),y}const r=this.getPendingAuthRequest(t);if(!r)throw i.setError(Ps.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${t}`);const n=r.transportType||dist_index_es_M.relay;n===dist_index_es_M.relay&&await this.confirmOnlineStateOrThrow();const a=r.requester.publicKey,c=await this.client.core.crypto.generateKeyPair(),h=hr(a),p={type:D,receiverPublicKey:a,senderPublicKey:c},d=[],l=[];for(const y of s){if(!await nr({cacao:y,projectId:this.client.core.projectId})){i.setError(Ps.invalid_cacao);const S=U("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:t,topic:h,error:S,encodeOpts:p}),new Error(S.message)}i.addTrace(Cs.cacaos_verified);const{p:_}=y,R=Y(_.resources),V=[ln(_.iss)],E=index_es_fe(_.iss);if(R){const S=ar(R),M=ur(R);d.push(...S),V.push(...M)}for(const S of V)l.push(`${S}:${E}`)}const w=await this.client.core.crypto.generateSharedKey(c,a);i.addTrace(Cs.create_authenticated_session_topic);let m;if(d?.length>0){m={topic:w,acknowledged:!0,self:{publicKey:c,metadata:this.client.metadata},peer:{publicKey:a,metadata:r.requester.metadata},controller:a,expiry:Mt(sign_client_dist_index_es_z),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:r.pairingTopic,namespaces:Jr([...new Set(d)],[...new Set(l)]),transportType:n},i.addTrace(Cs.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(w,{transportType:n})}catch(y){throw i.setError(Ps.subscribe_authenticated_session_topic_failure),y}i.addTrace(Cs.subscribe_authenticated_session_topic_success),await this.client.session.set(w,m),i.addTrace(Cs.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:r.pairingTopic,metadata:r.requester.metadata})}i.addTrace(Cs.publishing_authenticated_session_approve);try{await this.sendResult({topic:h,id:t,result:{cacaos:s,responder:{publicKey:c,metadata:this.client.metadata}},encodeOpts:p,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(r.requester.metadata,n)})}catch(y){throw i.setError(Ps.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(t,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:r.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:i.eventId}),{session:m}},this.rejectSessionAuthenticate=async e=>{this.isInitialized();const{id:t,reason:s}=e,i=this.getPendingAuthRequest(t);if(!i)throw new Error(`Could not find pending auth request with id ${t}`);i.transportType===dist_index_es_M.relay&&await this.confirmOnlineStateOrThrow();const r=i.requester.publicKey,n=await this.client.core.crypto.generateKeyPair(),a=hr(r),c={type:D,receiverPublicKey:r,senderPublicKey:n};await this.sendError({id:t,topic:a,error:s,encodeOpts:c,rpcOpts:sign_client_dist_index_es_v.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(i.requester.metadata,i.transportType)}),await this.client.auth.requests.delete(t,{message:"rejected",code:0}),await this.client.proposal.delete(t,U("USER_DISCONNECTED"))},this.formatAuthMessage=e=>{this.isInitialized();const{request:t,iss:s}=e;return dn(t,s)},this.processRelayMessageCache=()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const e=this.relayMessageCache.shift();e&&await this.onRelayMessage(e)}catch(e){this.client.logger.error(e)}},50)},this.cleanupDuplicatePairings=async e=>{if(e.pairingTopic)try{const t=this.client.core.pairing.pairings.get(e.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(i=>{var r,n;return((r=i.peerMetadata)==null?void 0:r.url)&&((n=i.peerMetadata)==null?void 0:n.url)===e.peer.metadata.url&&i.topic&&i.topic!==t.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(i=>this.client.core.pairing.disconnect({topic:i.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(t){this.client.logger.error(t)}},this.deleteSession=async e=>{var t;const{topic:s,expirerHasDeleted:i=!1,emitEvent:r=!0,id:n=0}=e,{self:a}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,U("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(a.publicKey)&&await this.client.core.crypto.deleteKeyPair(a.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),i||this.client.core.expirer.del(s),this.client.core.storage.removeItem(index_es_xe).catch(c=>this.client.logger.warn(c)),this.getPendingSessionRequests().forEach(c=>{c.topic===s&&this.deletePendingSessionRequest(c.id,U("USER_DISCONNECTED"))}),s===((t=this.sessionRequestQueue.queue[0])==null?void 0:t.topic)&&(this.sessionRequestQueue.state=sign_client_dist_index_es_x.idle),r&&this.client.events.emit("session_delete",{id:n,topic:s})},this.deleteProposal=async(e,t)=>{if(t)try{const s=this.client.proposal.get(e),i=this.client.core.eventClient.getEvent({topic:s.pairingTopic});i?.setError(Ts.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(e,U("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"proposal")},this.deletePendingSessionRequest=async(e,t,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(e,t),s?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(i=>i.id!==e),s&&(this.sessionRequestQueue.state=sign_client_dist_index_es_x.idle,this.client.events.emit("session_request_expire",{id:e}))},this.deletePendingAuthRequest=async(e,t,s=!1)=>{await Promise.all([this.client.auth.requests.delete(e,t),s?Promise.resolve():this.client.core.expirer.del(e)])},this.setExpiry=async(e,t)=>{this.client.session.keys.includes(e)&&(this.client.core.expirer.set(e,t),await this.client.session.update(e,{expiry:t}))},this.setProposal=async(e,t)=>{this.client.core.expirer.set(e,Mt(sign_client_dist_index_es_v.wc_sessionPropose.req.ttl)),await this.client.proposal.set(e,t)},this.setAuthRequest=async(e,t)=>{const{request:s,pairingTopic:i,transportType:r=dist_index_es_M.relay}=t;this.client.core.expirer.set(e,s.expiryTimestamp),await this.client.auth.requests.set(e,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:e,pairingTopic:i,verifyContext:s.verifyContext,transportType:r})},this.setPendingSessionRequest=async e=>{const{id:t,topic:s,params:i,verifyContext:r}=e,n=i.request.expiryTimestamp||Mt(sign_client_dist_index_es_v.wc_sessionRequest.req.ttl);this.client.core.expirer.set(t,n),await this.client.pendingRequest.set(t,{id:t,topic:s,params:i,verifyContext:r})},this.sendRequest=async e=>{const{topic:t,method:s,params:i,expiry:r,relayRpcId:n,clientRpcId:a,throwOnFailedPublish:c,appLink:h}=e,p=formatJsonRpcRequest(s,i,a);let d;const l=!!h;try{const y=l?lr:ge;d=await this.client.core.crypto.encode(t,p,{encoding:y})}catch(y){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${t} failed`),y}let w;if(index_es_at.includes(s)){const y=yr(JSON.stringify(p)),_=yr(d);w=await this.client.core.verify.register({id:_,decryptedId:y})}const m=sign_client_dist_index_es_v[s].req;if(m.attestation=w,r&&(m.ttl=r),n&&(m.id=n),this.client.core.history.set(t,p),l){const y=xr(h,t,d);await global.Linking.openURL(y,this.client.name)}else{const y=sign_client_dist_index_es_v[s].req;r&&(y.ttl=r),n&&(y.id=n),c?(y.internal=dist_index_es_D(sign_client_dist_index_es_I({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(t,d,y)):this.client.core.relayer.publish(t,d,y).catch(_=>this.client.logger.error(_))}return p.id},this.sendResult=async e=>{const{id:t,topic:s,result:i,throwOnFailedPublish:r,encodeOpts:n,appLink:a}=e,c=formatJsonRpcResult(t,i);let h;const p=a&&typeof(global==null?void 0:global.Linking)<"u";try{const l=p?lr:ge;h=await this.client.core.crypto.encode(s,c,dist_index_es_D(sign_client_dist_index_es_I({},n||{}),{encoding:l}))}catch(l){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),l}let d;try{d=await this.client.core.history.get(s,t)}catch(l){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${t}) failed`),l}if(p){const l=xr(a,s,h);await global.Linking.openURL(l,this.client.name)}else{const l=sign_client_dist_index_es_v[d.request.method].res;r?(l.internal=dist_index_es_D(sign_client_dist_index_es_I({},l.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,h,l)):this.client.core.relayer.publish(s,h,l).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(c)},this.sendError=async e=>{const{id:t,topic:s,error:i,encodeOpts:r,rpcOpts:n,appLink:a}=e,c=formatJsonRpcError(t,i);let h;const p=a&&typeof(global==null?void 0:global.Linking)<"u";try{const l=p?lr:ge;h=await this.client.core.crypto.encode(s,c,dist_index_es_D(sign_client_dist_index_es_I({},r||{}),{encoding:l}))}catch(l){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),l}let d;try{d=await this.client.core.history.get(s,t)}catch(l){throw this.client.logger.error(`sendError() -> history.get(${s}, ${t}) failed`),l}if(p){const l=xr(a,s,h);await global.Linking.openURL(l,this.client.name)}else{const l=n||sign_client_dist_index_es_v[d.request.method].res;this.client.core.relayer.publish(s,h,l)}await this.client.core.history.resolve(c)},this.cleanup=async()=>{const e=[],t=[];this.client.session.getAll().forEach(s=>{let i=!1;Kt(s.expiry)&&(i=!0),this.client.core.crypto.keychain.has(s.topic)||(i=!0),i&&e.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{Kt(s.expiryTimestamp)&&t.push(s.id)}),await Promise.all([...e.map(s=>this.deleteSession({topic:s})),...t.map(s=>this.deleteProposal(s))])},this.onRelayEventRequest=async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===sign_client_dist_index_es_x.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=sign_client_dist_index_es_x.active;const e=this.requestQueue.queue.shift();if(e)try{await this.processRequest(e)}catch(t){this.client.logger.warn(t)}}this.requestQueue.state=sign_client_dist_index_es_x.idle},this.processRequest=async e=>{const{topic:t,payload:s,attestation:i,transportType:r,encryptedId:n}=e,a=s.method;if(!this.shouldIgnorePairingRequest({topic:t,requestMethod:a}))switch(a){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:t,payload:s,attestation:i,encryptedId:n});case"wc_sessionSettle":return await this.onSessionSettleRequest(t,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(t,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(t,s);case"wc_sessionPing":return await this.onSessionPingRequest(t,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(t,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:t,payload:s,attestation:i,encryptedId:n,transportType:r});case"wc_sessionEvent":return await this.onSessionEventRequest(t,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:t,payload:s,attestation:i,encryptedId:n,transportType:r});default:return this.client.logger.info(`Unsupported request method ${a}`)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:s,transportType:i}=e,r=(await this.client.core.history.get(t,s.id)).request.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeResponse(t,s,i);case"wc_sessionSettle":return this.onSessionSettleResponse(t,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,s);case"wc_sessionExtend":return this.onSessionExtendResponse(t,s);case"wc_sessionPing":return this.onSessionPingResponse(t,s);case"wc_sessionRequest":return this.onSessionRequestResponse(t,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(t,s);default:return this.client.logger.info(`Unsupported response method ${r}`)}},this.onRelayEventUnknownPayload=e=>{const{topic:t}=e,{message:s}=index_es_S("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)},this.shouldIgnorePairingRequest=e=>{const{topic:t,requestMethod:s}=e,i=this.expectedPairingMethodMap.get(t);return!i||i.includes(s)?!1:!!(i.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async e=>{const{topic:t,payload:s,attestation:i,encryptedId:r}=e,{params:n,id:a}=s;try{const c=this.client.core.eventClient.getEvent({topic:t});this.isValidConnect(sign_client_dist_index_es_I({},s.params));const h=n.expiryTimestamp||Mt(sign_client_dist_index_es_v.wc_sessionPropose.req.ttl),p=sign_client_dist_index_es_I({id:a,pairingTopic:t,expiryTimestamp:h},n);await this.setProposal(a,p);const d=await this.getVerifyContext({attestationId:i,hash:yr(JSON.stringify(s)),encryptedId:r,metadata:p.proposer.metadata});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),c?.setError(index_es_$.proposal_listener_not_found)),c?.addTrace(core_dist_index_es_z.emit_session_proposal),this.client.events.emit("session_proposal",{id:a,params:p,verifyContext:d})}catch(c){await this.sendError({id:a,topic:t,error:c,rpcOpts:sign_client_dist_index_es_v.wc_sessionPropose.autoReject}),this.client.logger.error(c)}},this.onSessionProposeResponse=async(e,t,s)=>{const{id:i}=t;if(isJsonRpcResult(t)){const{result:r}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:r});const n=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:n});const a=n.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:a});const c=r.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:c});const h=await this.client.core.crypto.generateSharedKey(a,c);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:h});const p=await this.client.core.relayer.subscribe(h,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:p}),await this.client.core.pairing.activate({topic:e})}else if(isJsonRpcError(t)){await this.client.proposal.delete(i,U("USER_DISCONNECTED"));const r=Lt("session_connect");if(this.events.listenerCount(r)===0)throw new Error(`emitting ${r} without any listeners, 954`);this.events.emit(Lt("session_connect"),{error:t.error})}},this.onSessionSettleRequest=async(e,t)=>{const{id:s,params:i}=t;try{this.isValidSessionSettleRequest(i);const{relay:r,controller:n,expiry:a,namespaces:c,sessionProperties:h,sessionConfig:p}=t.params,d=dist_index_es_D(sign_client_dist_index_es_I(sign_client_dist_index_es_I({topic:e,relay:r,expiry:a,namespaces:c,acknowledged:!0,pairingTopic:"",requiredNamespaces:{},optionalNamespaces:{},controller:n.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:n.publicKey,metadata:n.metadata}},h&&{sessionProperties:h}),p&&{sessionConfig:p}),{transportType:dist_index_es_M.relay}),l=Lt("session_connect");if(this.events.listenerCount(l)===0)throw new Error(`emitting ${l} without any listeners 997`);this.events.emit(Lt("session_connect"),{session:d}),await this.sendResult({id:t.id,topic:e,result:!0,throwOnFailedPublish:!0})}catch(r){await this.sendError({id:s,topic:e,error:r}),this.client.logger.error(r)}},this.onSessionSettleResponse=async(e,t)=>{const{id:s}=t;isJsonRpcResult(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(Lt("session_approve",s),{})):isJsonRpcError(t)&&(await this.client.session.delete(e,U("USER_DISCONNECTED")),this.events.emit(Lt("session_approve",s),{error:t.error}))},this.onSessionUpdateRequest=async(e,t)=>{const{params:s,id:i}=t;try{const r=`${e}_session_update`,n=yo.get(r);if(n&&this.isRequestOutOfSync(n,i)){this.client.logger.info(`Discarding out of sync request - ${i}`),this.sendError({id:i,topic:e,error:U("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(sign_client_dist_index_es_I({topic:e},s));try{yo.set(r,i),await this.client.session.update(e,{namespaces:s.namespaces}),await this.sendResult({id:i,topic:e,result:!0,throwOnFailedPublish:!0})}catch(a){throw yo.delete(r),a}this.client.events.emit("session_update",{id:i,topic:e,params:s})}catch(r){await this.sendError({id:i,topic:e,error:r}),this.client.logger.error(r)}},this.isRequestOutOfSync=(e,t)=>parseInt(t.toString().slice(0,-3))<=parseInt(e.toString().slice(0,-3)),this.onSessionUpdateResponse=(e,t)=>{const{id:s}=t,i=Lt("session_update",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);isJsonRpcResult(t)?this.events.emit(Lt("session_update",s),{}):isJsonRpcError(t)&&this.events.emit(Lt("session_update",s),{error:t.error})},this.onSessionExtendRequest=async(e,t)=>{const{id:s}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,Mt(sign_client_dist_index_es_z)),await this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:s,topic:e})}catch(i){await this.sendError({id:s,topic:e,error:i}),this.client.logger.error(i)}},this.onSessionExtendResponse=(e,t)=>{const{id:s}=t,i=Lt("session_extend",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);isJsonRpcResult(t)?this.events.emit(Lt("session_extend",s),{}):isJsonRpcError(t)&&this.events.emit(Lt("session_extend",s),{error:t.error})},this.onSessionPingRequest=async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:e})}catch(i){await this.sendError({id:s,topic:e,error:i}),this.client.logger.error(i)}},this.onSessionPingResponse=(e,t)=>{const{id:s}=t,i=Lt("session_ping",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);setTimeout(()=>{isJsonRpcResult(t)?this.events.emit(Lt("session_ping",s),{}):isJsonRpcError(t)&&this.events.emit(Lt("session_ping",s),{error:t.error})},500)},this.onSessionDeleteRequest=async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),Promise.all([new Promise(i=>{this.client.core.relayer.once(dist_index_es_v.publish,async()=>{i(await this.deleteSession({topic:e,id:s}))})}),this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:e,error:U("USER_DISCONNECTED")})]).catch(i=>this.client.logger.error(i))}catch(i){this.client.logger.error(i)}},this.onSessionRequest=async e=>{var t,s,i;const{topic:r,payload:n,attestation:a,encryptedId:c,transportType:h}=e,{id:p,params:d}=n;try{await this.isValidRequest(sign_client_dist_index_es_I({topic:r},d));const l=this.client.session.get(r),w=await this.getVerifyContext({attestationId:a,hash:yr(JSON.stringify(formatJsonRpcRequest("wc_sessionRequest",d,p))),encryptedId:c,metadata:l.peer.metadata,transportType:h}),m={id:p,topic:r,params:d,verifyContext:w};await this.setPendingSessionRequest(m),h===dist_index_es_M.link_mode&&(t=l.peer.metadata.redirect)!=null&&t.universal&&this.client.core.addLinkModeSupportedApp((s=l.peer.metadata.redirect)==null?void 0:s.universal),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(m):(this.addSessionRequestToSessionRequestQueue(m),this.processSessionRequestQueue())}catch(l){await this.sendError({id:p,topic:r,error:l}),this.client.logger.error(l)}},this.onSessionRequestResponse=(e,t)=>{const{id:s}=t,i=Lt("session_request",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);isJsonRpcResult(t)?this.events.emit(Lt("session_request",s),{result:t.result}):isJsonRpcError(t)&&this.events.emit(Lt("session_request",s),{error:t.error})},this.onSessionEventRequest=async(e,t)=>{const{id:s,params:i}=t;try{const r=`${e}_session_event_${i.event.name}`,n=yo.get(r);if(n&&this.isRequestOutOfSync(n,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(sign_client_dist_index_es_I({topic:e},i)),this.client.events.emit("session_event",{id:s,topic:e,params:i}),yo.set(r,s)}catch(r){await this.sendError({id:s,topic:e,error:r}),this.client.logger.error(r)}},this.onSessionAuthenticateResponse=(e,t)=>{const{id:s}=t;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:e,payload:t}),isJsonRpcResult(t)?this.events.emit(Lt("session_request",s),{result:t.result}):isJsonRpcError(t)&&this.events.emit(Lt("session_request",s),{error:t.error})},this.onSessionAuthenticateRequest=async e=>{var t;const{topic:s,payload:i,attestation:r,encryptedId:n,transportType:a}=e;try{const{requester:c,authPayload:h,expiryTimestamp:p}=i.params,d=await this.getVerifyContext({attestationId:r,hash:yr(JSON.stringify(i)),encryptedId:n,metadata:c.metadata,transportType:a}),l={requester:c,pairingTopic:s,id:i.id,authPayload:h,verifyContext:d,expiryTimestamp:p};await this.setAuthRequest(i.id,{request:l,pairingTopic:s,transportType:a}),a===dist_index_es_M.link_mode&&(t=c.metadata.redirect)!=null&&t.universal&&this.client.core.addLinkModeSupportedApp(c.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:i.params,id:i.id,verifyContext:d})}catch(c){this.client.logger.error(c);const h=i.params.requester.publicKey,p=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(i.params.requester.metadata,a),l={type:D,receiverPublicKey:h,senderPublicKey:p};await this.sendError({id:i.id,topic:s,error:c,encodeOpts:l,rpcOpts:sign_client_dist_index_es_v.wc_sessionAuthenticate.autoReject,appLink:d})}},this.addSessionRequestToSessionRequestQueue=e=>{this.sessionRequestQueue.queue.push(e)},this.cleanupAfterResponse=e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=sign_client_dist_index_es_x.idle,this.processSessionRequestQueue()},(0,cjs.toMiliseconds)(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:e,error:t})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(i=>i.topic===e&&i.request.method==="wc_sessionRequest").forEach(i=>{const r=i.request.id,n=Lt("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);this.events.emit(Lt("session_request",i.request.id),{error:t})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===sign_client_dist_index_es_x.active){this.client.logger.info("session request queue is already active.");return}const e=this.sessionRequestQueue.queue[0];if(!e){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=sign_client_dist_index_es_x.active,this.emitSessionRequest(e)}catch(t){this.client.logger.error(t)}},this.emitSessionRequest=e=>{this.client.events.emit("session_request",e)},this.onPairingCreated=e=>{if(e.methods&&this.expectedPairingMethodMap.set(e.topic,e.methods),e.active)return;const t=this.client.proposal.getAll().find(s=>s.pairingTopic===e.topic);t&&this.onSessionProposeRequest({topic:e.topic,payload:formatJsonRpcRequest("wc_sessionPropose",{requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces,relays:t.relays,proposer:t.proposer,sessionProperties:t.sessionProperties},t.id)})},this.isValidConnect=async e=>{if(!to(e)){const{message:a}=index_es_S("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(a)}const{pairingTopic:t,requiredNamespaces:s,optionalNamespaces:i,sessionProperties:r,relays:n}=e;if(I(t)||await this.isValidPairingTopic(t),!eo(n,!0)){const{message:a}=index_es_S("MISSING_OR_INVALID",`connect() relays: ${n}`);throw new Error(a)}!I(s)&&Z(s)!==0&&this.validateNamespaces(s,"requiredNamespaces"),!I(i)&&Z(i)!==0&&this.validateNamespaces(i,"optionalNamespaces"),I(r)||this.validateSessionProps(r,"sessionProperties")},this.validateNamespaces=(e,t)=>{const s=Xr(e,"connect()",t);if(s)throw new Error(s.message)},this.isValidApprove=async e=>{if(!to(e))throw new Error(index_es_S("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:s,relayProtocol:i,sessionProperties:r}=e;this.checkRecentlyDeleted(t),await this.isValidProposalId(t);const n=this.client.proposal.get(t),a=Wn(s,"approve()");if(a)throw new Error(a.message);const c=zn(n.requiredNamespaces,s,"approve()");if(c)throw new Error(c.message);if(!index_es_b(i,!0)){const{message:h}=index_es_S("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(h)}I(r)||this.validateSessionProps(r,"sessionProperties")},this.isValidReject=async e=>{if(!to(e)){const{message:i}=index_es_S("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(i)}const{id:t,reason:s}=e;if(this.checkRecentlyDeleted(t),await this.isValidProposalId(t),!ro(s)){const{message:i}=index_es_S("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(i)}},this.isValidSessionSettleRequest=e=>{if(!to(e)){const{message:c}=index_es_S("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(c)}const{relay:t,controller:s,namespaces:i,expiry:r}=e;if(!Jn(t)){const{message:c}=index_es_S("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(c)}const n=Zr(s,"onSessionSettleRequest()");if(n)throw new Error(n.message);const a=Wn(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);if(Kt(r)){const{message:c}=index_es_S("EXPIRED","onSessionSettleRequest()");throw new Error(c)}},this.isValidUpdate=async e=>{if(!to(e)){const{message:a}=index_es_S("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(a)}const{topic:t,namespaces:s}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const i=this.client.session.get(t),r=Wn(s,"update()");if(r)throw new Error(r.message);const n=zn(i.requiredNamespaces,s,"update()");if(n)throw new Error(n.message)},this.isValidExtend=async e=>{if(!to(e)){const{message:s}=index_es_S("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(s)}const{topic:t}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t)},this.isValidRequest=async e=>{if(!to(e)){const{message:a}=index_es_S("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(a)}const{topic:t,request:s,chainId:i,expiry:r}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const{namespaces:n}=this.client.session.get(t);if(!co(n,i)){const{message:a}=index_es_S("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(a)}if(!oo(s)){const{message:a}=index_es_S("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(a)}if(!ao(n,i,s.method)){const{message:a}=index_es_S("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(a)}if(r&&!po(r,dist_index_es_me)){const{message:a}=index_es_S("MISSING_OR_INVALID",`request() expiry: ${r}. Expiry must be a number (in seconds) between ${dist_index_es_me.min} and ${dist_index_es_me.max}`);throw new Error(a)}},this.isValidRespond=async e=>{var t;if(!to(e)){const{message:r}=index_es_S("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(r)}const{topic:s,response:i}=e;try{await this.isValidSessionTopic(s)}catch(r){throw(t=e?.response)!=null&&t.id&&this.cleanupAfterResponse(e),r}if(!so(i)){const{message:r}=index_es_S("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(r)}},this.isValidPing=async e=>{if(!to(e)){const{message:s}=index_es_S("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidEmit=async e=>{if(!to(e)){const{message:n}=index_es_S("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(n)}const{topic:t,event:s,chainId:i}=e;await this.isValidSessionTopic(t);const{namespaces:r}=this.client.session.get(t);if(!co(r,i)){const{message:n}=index_es_S("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(n)}if(!io(s)){const{message:n}=index_es_S("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(n)}if(!uo(r,i,s.name)){const{message:n}=index_es_S("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(n)}},this.isValidDisconnect=async e=>{if(!to(e)){const{message:s}=index_es_S("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidAuthenticate=e=>{const{chains:t,uri:s,domain:i,nonce:r}=e;if(!Array.isArray(t)||t.length===0)throw new Error("chains is required and must be a non-empty array");if(!index_es_b(s,!1))throw new Error("uri is required parameter");if(!index_es_b(i,!1))throw new Error("domain is required parameter");if(!index_es_b(r,!1))throw new Error("nonce is required parameter");if([...new Set(t.map(a=>re(a).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:n}=re(t[0]);if(n!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async e=>{const{attestationId:t,hash:s,encryptedId:i,metadata:r,transportType:n}=e,a={verified:{verifyUrl:r.verifyUrl||index_es_J,validation:"UNKNOWN",origin:r.url||""}};try{if(n===dist_index_es_M.link_mode){const h=this.getAppLinkIfEnabled(r,n);return a.verified.validation=h&&new URL(h).origin===new URL(r.url).origin?"VALID":"INVALID",a}const c=await this.client.core.verify.resolve({attestationId:t,hash:s,encryptedId:i,verifyUrl:r.verifyUrl});c&&(a.verified.origin=c.origin,a.verified.isScam=c.isScam,a.verified.validation=c.origin===new URL(r.url).origin?"VALID":"INVALID")}catch(c){this.client.logger.warn(c)}return this.client.logger.debug(`Verify context: ${JSON.stringify(a)}`),a},this.validateSessionProps=(e,t)=>{Object.values(e).forEach(s=>{if(!index_es_b(s,!1)){const{message:i}=index_es_S("MISSING_OR_INVALID",`${t} must be in Record format. Received: ${JSON.stringify(s)}`);throw new Error(i)}})},this.getPendingAuthRequest=e=>{const t=this.client.auth.requests.get(e);return typeof t=="object"?t:void 0},this.addToRecentlyDeleted=(e,t)=>{if(this.recentlyDeletedMap.set(e,t),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const i=this.recentlyDeletedLimit/2;for(const r of this.recentlyDeletedMap.keys()){if(s++>=i)break;this.recentlyDeletedMap.delete(r)}}},this.checkRecentlyDeleted=e=>{const t=this.recentlyDeletedMap.get(e);if(t){const{message:s}=index_es_S("MISSING_OR_INVALID",`Record was recently deleted - ${t}: ${e}`);throw new Error(s)}},this.isLinkModeEnabled=(e,t)=>{var s,i,r,n,a,c,h,p,d;return!e||t!==dist_index_es_M.link_mode?!1:((i=(s=this.client.metadata)==null?void 0:s.redirect)==null?void 0:i.linkMode)===!0&&((n=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:n.universal)!==void 0&&((c=(a=this.client.metadata)==null?void 0:a.redirect)==null?void 0:c.universal)!==""&&((h=e?.redirect)==null?void 0:h.universal)!==void 0&&((p=e?.redirect)==null?void 0:p.universal)!==""&&((d=e?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(e.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"},this.getAppLinkIfEnabled=(e,t)=>{var s;return this.isLinkModeEnabled(e,t)?(s=e?.redirect)==null?void 0:s.universal:void 0},this.handleLinkModeMessage=({url:e})=>{if(!e||!e.includes("wc_ev")||!e.includes("topic"))return;const t=Bt(e,"topic")||"",s=decodeURIComponent(Bt(e,"wc_ev")||""),i=this.client.session.keys.includes(t);i&&this.client.session.update(t,{transportType:dist_index_es_M.link_mode}),this.client.core.dispatchEnvelope({topic:t,message:s,sessionExists:i})},this.registerLinkModeListeners=async()=>{var e;if(Wt()||index_es_()&&(e=this.client.metadata.redirect)!=null&&e.linkMode){const t=global==null?void 0:global.Linking;if(typeof t<"u"){t.addEventListener("url",this.handleLinkModeMessage,this.client.name);const s=await t.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}}isInitialized(){if(!this.initialized){const{message:o}=index_es_S("NOT_INITIALIZED",this.name);throw new Error(o)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(dist_index_es_v.message,o=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(o):this.onRelayMessage(o)})}async onRelayMessage(o){const{topic:e,message:t,attestation:s,transportType:i}=o,{publicKey:r}=this.client.auth.authKeys.keys.includes(index_es_ae)?this.client.auth.authKeys.get(index_es_ae):{responseTopic:void 0,publicKey:void 0},n=await this.client.core.crypto.decode(e,t,{receiverPublicKey:r,encoding:i===dist_index_es_M.link_mode?lr:ge});try{isJsonRpcRequest(n)?(this.client.core.history.set(e,n),this.onRelayEventRequest({topic:e,payload:n,attestation:s,transportType:i,encryptedId:yr(t)})):isJsonRpcResponse(n)?(await this.client.core.history.resolve(n),await this.onRelayEventResponse({topic:e,payload:n,transportType:i}),this.client.core.history.delete(e,n.id)):this.onRelayEventUnknownPayload({topic:e,payload:n,transportType:i})}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(core_dist_index_es_S.expired,async o=>{const{topic:e,id:t}=Vt(o.target);if(t&&this.client.pendingRequest.keys.includes(t))return await this.deletePendingSessionRequest(t,index_es_S("EXPIRED"),!0);if(t&&this.client.auth.requests.keys.includes(t))return await this.deletePendingAuthRequest(t,index_es_S("EXPIRED"),!0);e?this.client.session.keys.includes(e)&&(await this.deleteSession({topic:e,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:e})):t&&(await this.deleteProposal(t,!0),this.client.events.emit("proposal_expire",{id:t}))})}registerPairingEvents(){this.client.core.pairing.events.on(index_es_V.create,o=>this.onPairingCreated(o)),this.client.core.pairing.events.on(index_es_V.delete,o=>{this.addToRecentlyDeleted(o.topic,"pairing")})}isValidPairingTopic(o){if(!index_es_b(o,!1)){const{message:e}=index_es_S("MISSING_OR_INVALID",`pairing topic should be a string: ${o}`);throw new Error(e)}if(!this.client.core.pairing.pairings.keys.includes(o)){const{message:e}=index_es_S("NO_MATCHING_KEY",`pairing topic doesn't exist: ${o}`);throw new Error(e)}if(Kt(this.client.core.pairing.pairings.get(o).expiry)){const{message:e}=index_es_S("EXPIRED",`pairing topic: ${o}`);throw new Error(e)}}async isValidSessionTopic(o){if(!index_es_b(o,!1)){const{message:e}=index_es_S("MISSING_OR_INVALID",`session topic should be a string: ${o}`);throw new Error(e)}if(this.checkRecentlyDeleted(o),!this.client.session.keys.includes(o)){const{message:e}=index_es_S("NO_MATCHING_KEY",`session topic doesn't exist: ${o}`);throw new Error(e)}if(Kt(this.client.session.get(o).expiry)){await this.deleteSession({topic:o});const{message:e}=index_es_S("EXPIRED",`session topic: ${o}`);throw new Error(e)}if(!this.client.core.crypto.keychain.has(o)){const{message:e}=index_es_S("MISSING_OR_INVALID",`session topic does not exist in keychain: ${o}`);throw await this.deleteSession({topic:o}),new Error(e)}}async isValidSessionOrPairingTopic(o){if(this.checkRecentlyDeleted(o),this.client.session.keys.includes(o))await this.isValidSessionTopic(o);else if(this.client.core.pairing.pairings.keys.includes(o))this.isValidPairingTopic(o);else if(index_es_b(o,!1)){const{message:e}=index_es_S("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${o}`);throw new Error(e)}else{const{message:e}=index_es_S("MISSING_OR_INVALID",`session or pairing topic should be a string: ${o}`);throw new Error(e)}}async isValidProposalId(o){if(!no(o)){const{message:e}=index_es_S("MISSING_OR_INVALID",`proposal id should be a number: ${o}`);throw new Error(e)}if(!this.client.proposal.keys.includes(o)){const{message:e}=index_es_S("NO_MATCHING_KEY",`proposal id doesn't exist: ${o}`);throw new Error(e)}if(Kt(this.client.proposal.get(o).expiryTimestamp)){await this.deleteProposal(o);const{message:e}=index_es_S("EXPIRED",`proposal id: ${o}`);throw new Error(e)}}}class index_es_Ss extends ni{constructor(o,e){super(o,e,index_es_st,dist_index_es_ye),this.core=o,this.logger=e}}class dist_index_es_yt extends ni{constructor(o,e){super(o,e,index_es_rt,dist_index_es_ye),this.core=o,this.logger=e}}class index_es_Is extends ni{constructor(o,e){super(o,e,index_es_ot,dist_index_es_ye,t=>t.id),this.core=o,this.logger=e}}class index_es_fs extends ni{constructor(o,e){super(o,e,dist_index_es_pt,index_es_oe,()=>index_es_ae),this.core=o,this.logger=e}}class index_es_vs extends ni{constructor(o,e){super(o,e,dist_index_es_ht,index_es_oe),this.core=o,this.logger=e}}class index_es_qs extends ni{constructor(o,e){super(o,e,index_es_dt,index_es_oe,t=>t.id),this.core=o,this.logger=e}}class index_es_Ts{constructor(o,e){this.core=o,this.logger=e,this.authKeys=new index_es_fs(this.core,this.logger),this.pairingTopics=new index_es_vs(this.core,this.logger),this.requests=new index_es_qs(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}class dist_index_es_e extends types_dist_index_es_S{constructor(o){super(o),this.protocol=dist_index_es_be,this.version=Ce,this.name=dist_index_es_we.name,this.events=new external_events_.EventEmitter,this.on=(t,s)=>this.events.on(t,s),this.once=(t,s)=>this.events.once(t,s),this.off=(t,s)=>this.events.off(t,s),this.removeListener=(t,s)=>this.events.removeListener(t,s),this.removeAllListeners=t=>this.events.removeAllListeners(t),this.connect=async t=>{try{return await this.engine.connect(t)}catch(s){throw this.logger.error(s.message),s}},this.pair=async t=>{try{return await this.engine.pair(t)}catch(s){throw this.logger.error(s.message),s}},this.approve=async t=>{try{return await this.engine.approve(t)}catch(s){throw this.logger.error(s.message),s}},this.reject=async t=>{try{return await this.engine.reject(t)}catch(s){throw this.logger.error(s.message),s}},this.update=async t=>{try{return await this.engine.update(t)}catch(s){throw this.logger.error(s.message),s}},this.extend=async t=>{try{return await this.engine.extend(t)}catch(s){throw this.logger.error(s.message),s}},this.request=async t=>{try{return await this.engine.request(t)}catch(s){throw this.logger.error(s.message),s}},this.respond=async t=>{try{return await this.engine.respond(t)}catch(s){throw this.logger.error(s.message),s}},this.ping=async t=>{try{return await this.engine.ping(t)}catch(s){throw this.logger.error(s.message),s}},this.emit=async t=>{try{return await this.engine.emit(t)}catch(s){throw this.logger.error(s.message),s}},this.disconnect=async t=>{try{return await this.engine.disconnect(t)}catch(s){throw this.logger.error(s.message),s}},this.find=t=>{try{return this.engine.find(t)}catch(s){throw this.logger.error(s.message),s}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(t){throw this.logger.error(t.message),t}},this.authenticate=async(t,s)=>{try{return await this.engine.authenticate(t,s)}catch(i){throw this.logger.error(i.message),i}},this.formatAuthMessage=t=>{try{return this.engine.formatAuthMessage(t)}catch(s){throw this.logger.error(s.message),s}},this.approveSessionAuthenticate=async t=>{try{return await this.engine.approveSessionAuthenticate(t)}catch(s){throw this.logger.error(s.message),s}},this.rejectSessionAuthenticate=async t=>{try{return await this.engine.rejectSessionAuthenticate(t)}catch(s){throw this.logger.error(s.message),s}},this.name=o?.name||dist_index_es_we.name,this.metadata=o?.metadata||Nt(),this.signConfig=o?.signConfig;const e=typeof o?.logger<"u"&&typeof o?.logger!="string"?o.logger:pino_default()(logger_dist_index_es_k({level:o?.logger||dist_index_es_we.logger}));this.core=o?.core||new index_es_bn(o),this.logger=dist_index_es_E(e,this.name),this.session=new dist_index_es_yt(this.core,this.logger),this.proposal=new index_es_Ss(this.core,this.logger),this.pendingRequest=new index_es_Is(this.core,this.logger),this.engine=new index_es_Rs(this),this.auth=new index_es_Ts(this.core,this.logger)}static async init(o){const e=new dist_index_es_e(o);return await e.initialize(),e}get context(){return dist_index_es_y(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),this.engine.processRelayMessageCache()}catch(o){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(o.message),o}}}const index_es_Ns=(/* unused pure expression or super */ null && (dist_index_es_yt)),index_es_Ps=(/* unused pure expression or super */ null && (dist_index_es_e));
+const Ce="wc",index_es_Le=2,index_es_xe="client",dist_index_es_ye=`${Ce}@${index_es_Le}:${index_es_xe}:`,dist_index_es_we={name:index_es_xe,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},cs={session_proposal:"session_proposal",session_update:"session_update",session_extend:"session_extend",session_ping:"session_ping",session_delete:"session_delete",session_expire:"session_expire",session_request:"session_request",session_request_sent:"session_request_sent",session_event:"session_event",proposal_expire:"proposal_expire",session_authenticate:"session_authenticate",session_request_expire:"session_request_expire"},ls={database:":memory:"},dist_index_es_De="WALLETCONNECT_DEEPLINK_CHOICE",ps={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},hs="history",ds="0.3",index_es_it="proposal",us=(/* unused pure expression or super */ null && (Ct)),index_es_rt="Proposal expired",index_es_nt="session",index_es_H=cjs.SEVEN_DAYS,index_es_ot="engine",sign_client_dist_index_es_v={wc_sessionPropose:{req:{ttl:cjs.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:cjs.ONE_DAY,prompt:!1,tag:1104},res:{ttl:cjs.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:cjs.ONE_DAY,prompt:!1,tag:1106},res:{ttl:cjs.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:cjs.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:cjs.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:cjs.ONE_DAY,prompt:!1,tag:1112},res:{ttl:cjs.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:cjs.ONE_DAY,prompt:!1,tag:1114},res:{ttl:cjs.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:cjs.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:cjs.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:cjs.FIVE_MINUTES,prompt:!1,tag:1119}}},dist_index_es_me={min:cjs.FIVE_MINUTES,max:cjs.SEVEN_DAYS},sign_client_dist_index_es_x={idle:"IDLE",active:"ACTIVE"},index_es_at="request",index_es_ct=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],index_es_lt="wc",gs=1.5,dist_index_es_pt="auth",dist_index_es_ht="authKeys",index_es_dt="pairingTopics",index_es_ut="requests",dist_index_es_oe=`${index_es_lt}@${1.5}:${dist_index_es_pt}:`,index_es_ae=`${dist_index_es_oe}:PUB_KEY`;var ys=Object.defineProperty,index_es_ws=Object.defineProperties,ms=Object.getOwnPropertyDescriptors,dist_index_es_gt=Object.getOwnPropertySymbols,_s=Object.prototype.hasOwnProperty,Es=Object.prototype.propertyIsEnumerable,dist_index_es_yt=(q,o,e)=>o in q?ys(q,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):q[o]=e,sign_client_dist_index_es_I=(q,o)=>{for(var e in o||(o={}))_s.call(o,e)&&dist_index_es_yt(q,e,o[e]);if(dist_index_es_gt)for(var e of dist_index_es_gt(o))Es.call(o,e)&&dist_index_es_yt(q,e,o[e]);return q},dist_index_es_D=(q,o)=>index_es_ws(q,ms(o));class index_es_Rs extends M{constructor(o){super(o),this.name=index_es_ot,this.events=new (external_events_default()),this.initialized=!1,this.requestQueue={state:sign_client_dist_index_es_x.idle,queue:[]},this.sessionRequestQueue={state:sign_client_dist_index_es_x.idle,queue:[]},this.requestQueueDelay=cjs.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(sign_client_dist_index_es_v)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},(0,cjs.toMiliseconds)(this.requestQueueDelay)))},this.connect=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const t=dist_index_es_D(sign_client_dist_index_es_I({},e),{requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}});await this.isValidConnect(t);const{pairingTopic:s,requiredNamespaces:i,optionalNamespaces:r,sessionProperties:n,relays:a}=t;let c=s,h,p=!1;try{c&&(p=this.client.core.pairing.pairings.get(c).active)}catch(E){throw this.client.logger.error(`connect() -> pairing.get(${c}) failed`),E}if(!c||!p){const{topic:E,uri:S}=await this.client.core.pairing.create();c=E,h=S}if(!c){const{message:E}=index_es_S("NO_MATCHING_KEY",`connect() pairing topic: ${c}`);throw new Error(E)}const d=await this.client.core.crypto.generateKeyPair(),l=sign_client_dist_index_es_v.wc_sessionPropose.req.ttl||cjs.FIVE_MINUTES,w=Lt(l),m=sign_client_dist_index_es_I({requiredNamespaces:i,optionalNamespaces:r,relays:a??[{protocol:nt}],proposer:{publicKey:d,metadata:this.client.metadata},expiryTimestamp:w,pairingTopic:c},n&&{sessionProperties:n}),{reject:y,resolve:_,done:R}=Dt(l,index_es_rt);this.events.once(qt("session_connect"),async({error:E,session:S})=>{if(E)y(E);else if(S){S.self.publicKey=d;const M=dist_index_es_D(sign_client_dist_index_es_I({},S),{pairingTopic:m.pairingTopic,requiredNamespaces:m.requiredNamespaces,optionalNamespaces:m.optionalNamespaces,transportType:dist_index_es_M.relay});await this.client.session.set(S.topic,M),await this.setExpiry(S.topic,S.expiry),c&&await this.client.core.pairing.updateMetadata({topic:c,metadata:S.peer.metadata}),this.cleanupDuplicatePairings(M),_(M)}});const V=await this.sendRequest({topic:c,method:"wc_sessionPropose",params:m,throwOnFailedPublish:!0});return await this.setProposal(V,sign_client_dist_index_es_I({id:V},m)),{uri:h,approval:R}},this.pair=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(e)}catch(t){throw this.client.logger.error("pair() failed"),t}},this.approve=async e=>{var t,s,i;const r=this.client.core.eventClient.createEvent({properties:{topic:(t=e?.id)==null?void 0:t.toString(),trace:[xs.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(N){throw r.setError(Os.no_internet_connection),N}try{await this.isValidProposalId(e?.id)}catch(N){throw this.client.logger.error(`approve() -> proposal.get(${e?.id}) failed`),r.setError(Os.proposal_not_found),N}try{await this.isValidApprove(e)}catch(N){throw this.client.logger.error("approve() -> isValidApprove() failed"),r.setError(Os.session_approve_namespace_validation_failure),N}const{id:n,relayProtocol:a,namespaces:c,sessionProperties:h,sessionConfig:p}=e,d=this.client.proposal.get(n);this.client.core.eventClient.deleteEvent({eventId:r.eventId});const{pairingTopic:l,proposer:w,requiredNamespaces:m,optionalNamespaces:y}=d;let _=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:l});_||(_=(i=this.client.core.eventClient)==null?void 0:i.createEvent({type:xs.session_approve_started,properties:{topic:l,trace:[xs.session_approve_started,xs.session_namespaces_validation_success]}}));const R=await this.client.core.crypto.generateKeyPair(),V=w.publicKey,E=await this.client.core.crypto.generateSharedKey(R,V),S=sign_client_dist_index_es_I(sign_client_dist_index_es_I({relay:{protocol:a??"irn"},namespaces:c,controller:{publicKey:R,metadata:this.client.metadata},expiry:Lt(index_es_H)},h&&{sessionProperties:h}),p&&{sessionConfig:p}),M=dist_index_es_M.relay;_.addTrace(xs.subscribing_session_topic);try{await this.client.core.relayer.subscribe(E,{transportType:M})}catch(N){throw _.setError(Os.subscribe_session_topic_failure),N}_.addTrace(xs.subscribe_session_topic_success);const W=dist_index_es_D(sign_client_dist_index_es_I({},S),{topic:E,requiredNamespaces:m,optionalNamespaces:y,pairingTopic:l,acknowledged:!1,self:S.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:R,transportType:dist_index_es_M.relay});await this.client.session.set(E,W),_.addTrace(xs.store_session);try{_.addTrace(xs.publishing_session_settle),await this.sendRequest({topic:E,method:"wc_sessionSettle",params:S,throwOnFailedPublish:!0}).catch(N=>{throw _?.setError(Os.session_settle_publish_failure),N}),_.addTrace(xs.session_settle_publish_success),_.addTrace(xs.publishing_session_approve),await this.sendResult({id:n,topic:l,result:{relay:{protocol:a??"irn"},responderPublicKey:R},throwOnFailedPublish:!0}).catch(N=>{throw _?.setError(Os.session_approve_publish_failure),N}),_.addTrace(xs.session_approve_publish_success)}catch(N){throw this.client.logger.error(N),this.client.session.delete(E,index_es_("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(E),N}return this.client.core.eventClient.deleteEvent({eventId:_.eventId}),await this.client.core.pairing.updateMetadata({topic:l,metadata:w.metadata}),await this.client.proposal.delete(n,index_es_("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:l}),await this.setExpiry(E,Lt(index_es_H)),{topic:E,acknowledged:()=>Promise.resolve(this.client.session.get(E))}},this.reject=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(e)}catch(r){throw this.client.logger.error("reject() -> isValidReject() failed"),r}const{id:t,reason:s}=e;let i;try{i=this.client.proposal.get(t).pairingTopic}catch(r){throw this.client.logger.error(`reject() -> proposal.get(${t}) failed`),r}i&&(await this.sendError({id:t,topic:i,error:s,rpcOpts:sign_client_dist_index_es_v.wc_sessionPropose.reject}),await this.client.proposal.delete(t,index_es_("USER_DISCONNECTED")))},this.update=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(e)}catch(p){throw this.client.logger.error("update() -> isValidUpdate() failed"),p}const{topic:t,namespaces:s}=e,{done:i,resolve:r,reject:n}=Dt(),a=payloadId(),c=getBigIntRpcId().toString(),h=this.client.session.get(t).namespaces;return this.events.once(qt("session_update",a),({error:p})=>{p?n(p):r()}),await this.client.session.update(t,{namespaces:s}),await this.sendRequest({topic:t,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:a,relayRpcId:c}).catch(p=>{this.client.logger.error(p),this.client.session.update(t,{namespaces:h}),n(p)}),{acknowledged:i}},this.extend=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(e)}catch(a){throw this.client.logger.error("extend() -> isValidExtend() failed"),a}const{topic:t}=e,s=payloadId(),{done:i,resolve:r,reject:n}=Dt();return this.events.once(qt("session_extend",s),({error:a})=>{a?n(a):r()}),await this.setExpiry(t,Lt(index_es_H)),this.sendRequest({topic:t,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(a=>{n(a)}),{acknowledged:i}},this.request=async e=>{this.isInitialized();try{await this.isValidRequest(e)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:t,request:s,topic:i,expiry:r=sign_client_dist_index_es_v.wc_sessionRequest.req.ttl}=e,n=this.client.session.get(i);n?.transportType===dist_index_es_M.relay&&await this.confirmOnlineStateOrThrow();const a=payloadId(),c=getBigIntRpcId().toString(),{done:h,resolve:p,reject:d}=Dt(r,"Request expired. Please try again.");this.events.once(qt("session_request",a),({error:w,result:m})=>{w?d(w):p(m)});const l=this.getAppLinkIfEnabled(n.peer.metadata,n.transportType);return l?(await this.sendRequest({clientRpcId:a,relayRpcId:c,topic:i,method:"wc_sessionRequest",params:{request:dist_index_es_D(sign_client_dist_index_es_I({},s),{expiryTimestamp:Lt(r)}),chainId:t},expiry:r,throwOnFailedPublish:!0,appLink:l}).catch(w=>d(w)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:t,id:a}),await h()):await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:a,relayRpcId:c,topic:i,method:"wc_sessionRequest",params:{request:dist_index_es_D(sign_client_dist_index_es_I({},s),{expiryTimestamp:Lt(r)}),chainId:t},expiry:r,throwOnFailedPublish:!0}).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:t,id:a}),w()}),new Promise(async w=>{var m;if(!((m=n.sessionConfig)!=null&&m.disableDeepLink)){const y=await Ht(this.client.core.storage,dist_index_es_De);await Bt({id:a,topic:i,wcDeepLink:y})}w()}),h()]).then(w=>w[2])},this.respond=async e=>{this.isInitialized(),await this.isValidRespond(e);const{topic:t,response:s}=e,{id:i}=s,r=this.client.session.get(t);r.transportType===dist_index_es_M.relay&&await this.confirmOnlineStateOrThrow();const n=this.getAppLinkIfEnabled(r.peer.metadata,r.transportType);isJsonRpcResult(s)?await this.sendResult({id:i,topic:t,result:s.result,throwOnFailedPublish:!0,appLink:n}):isJsonRpcError(s)&&await this.sendError({id:i,topic:t,error:s.error,appLink:n}),this.cleanupAfterResponse(e)},this.ping=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(e)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:t}=e;if(this.client.session.keys.includes(t)){const s=payloadId(),i=getBigIntRpcId().toString(),{done:r,resolve:n,reject:a}=Dt();this.events.once(qt("session_ping",s),({error:c})=>{c?a(c):n()}),await Promise.all([this.sendRequest({topic:t,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:i}),r()])}else this.client.core.pairing.pairings.keys.includes(t)&&await this.client.core.pairing.ping({topic:t})},this.emit=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(e);const{topic:t,event:s,chainId:i}=e,r=getBigIntRpcId().toString(),n=payloadId();await this.sendRequest({topic:t,method:"wc_sessionEvent",params:{event:s,chainId:i},throwOnFailedPublish:!0,relayRpcId:r,clientRpcId:n})},this.disconnect=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(e);const{topic:t}=e;if(this.client.session.keys.includes(t))await this.sendRequest({topic:t,method:"wc_sessionDelete",params:index_es_("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:t,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(t))await this.client.core.pairing.disconnect({topic:t});else{const{message:s}=index_es_S("MISMATCHED_TOPIC",`Session or pairing topic not found: ${t}`);throw new Error(s)}},this.find=e=>(this.isInitialized(),this.client.session.getAll().filter(t=>Qr(t,e))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(e,t)=>{var s;this.isInitialized(),this.isValidAuthenticate(e);const i=t&&this.client.core.linkModeSupportedApps.includes(t)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),r=i?dist_index_es_M.link_mode:dist_index_es_M.relay;r===dist_index_es_M.relay&&await this.confirmOnlineStateOrThrow();const{chains:n,statement:a="",uri:c,domain:h,nonce:p,type:d,exp:l,nbf:w,methods:m=[],expiry:y}=e,_=[...e.resources||[]],{topic:R,uri:V}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:r});this.client.logger.info({message:"Generated new pairing",pairing:{topic:R,uri:V}});const E=await this.client.core.crypto.generateKeyPair(),S=vr(E);if(await Promise.all([this.client.auth.authKeys.set(index_es_ae,{responseTopic:S,publicKey:E}),this.client.auth.pairingTopics.set(S,{topic:S,pairingTopic:R})]),await this.client.core.relayer.subscribe(S,{transportType:r}),this.client.logger.info(`sending request to new pairing topic: ${R}`),m.length>0){const{namespace:O}=re(n[0]);let T=ur(O,"request",m);Y(_)&&(T=lr(T,_.pop())),_.push(T)}const M=y&&y>sign_client_dist_index_es_v.wc_sessionAuthenticate.req.ttl?y:sign_client_dist_index_es_v.wc_sessionAuthenticate.req.ttl,W={authPayload:{type:d??"caip122",chains:n,statement:a,aud:c,domain:h,version:"1",nonce:p,iat:new Date().toISOString(),exp:l,nbf:w,resources:_},requester:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:Lt(M)},N={eip155:{chains:n,methods:[...new Set(["personal_sign",...m])],events:["chainChanged","accountsChanged"]}},Ve={requiredNamespaces:{},optionalNamespaces:N,relays:[{protocol:"irn"}],pairingTopic:R,proposer:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:Lt(sign_client_dist_index_es_v.wc_sessionPropose.req.ttl)},{done:mt,resolve:Me,reject:Ee}=Dt(M,"Request expired"),ce=async({error:O,session:T})=>{if(this.events.off(qt("session_request",G),Re),O)Ee(O);else if(T){T.self.publicKey=E,await this.client.session.set(T.topic,T),await this.setExpiry(T.topic,T.expiry),R&&await this.client.core.pairing.updateMetadata({topic:R,metadata:T.peer.metadata});const le=this.client.session.get(T.topic);await this.deleteProposal(Z),Me({session:le})}},Re=async O=>{var T,le,ke;if(await this.deletePendingAuthRequest(G,{message:"fulfilled",code:0}),O.error){const te=index_es_("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return O.error.code===te.code?void 0:(this.events.off(qt("session_connect"),ce),Ee(O.error.message))}await this.deleteProposal(Z),this.events.off(qt("session_connect"),ce);const{cacaos:$e,responder:j}=O.result,Ie=[],Ke=[];for(const te of $e){await or({cacao:te,projectId:this.client.core.projectId})||(this.client.logger.error(te,"Signature verification failed"),Ee(index_es_("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:fe}=te,ve=Y(fe.resources),Ue=[ln(fe.iss)],_t=index_es_fe(fe.iss);if(ve){const qe=dr(ve),Et=fr(ve);Ie.push(...qe),Ue.push(...Et)}for(const qe of Ue)Ke.push(`${qe}:${_t}`)}const ee=await this.client.core.crypto.generateSharedKey(E,j.publicKey);let pe;Ie.length>0&&(pe={topic:ee,acknowledged:!0,self:{publicKey:E,metadata:this.client.metadata},peer:j,controller:j.publicKey,expiry:Lt(index_es_H),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:R,namespaces:Yr([...new Set(Ie)],[...new Set(Ke)]),transportType:r},await this.client.core.relayer.subscribe(ee,{transportType:r}),await this.client.session.set(ee,pe),R&&await this.client.core.pairing.updateMetadata({topic:R,metadata:j.metadata}),pe=this.client.session.get(ee)),(T=this.client.metadata.redirect)!=null&&T.linkMode&&(le=j.metadata.redirect)!=null&&le.linkMode&&(ke=j.metadata.redirect)!=null&&ke.universal&&t&&(this.client.core.addLinkModeSupportedApp(j.metadata.redirect.universal),this.client.session.update(ee,{transportType:dist_index_es_M.link_mode})),Me({auths:$e,session:pe})},G=payloadId(),Z=payloadId();this.events.once(qt("session_connect"),ce),this.events.once(qt("session_request",G),Re);let Se;try{if(i){const O=formatJsonRpcRequest("wc_sessionAuthenticate",W,G);this.client.core.history.set(R,O);const T=await this.client.core.crypto.encode("",O,{type:index_es_M,encoding:pr});Se=Kr(t,R,T)}else await Promise.all([this.sendRequest({topic:R,method:"wc_sessionAuthenticate",params:W,expiry:e.expiry,throwOnFailedPublish:!0,clientRpcId:G}),this.sendRequest({topic:R,method:"wc_sessionPropose",params:Ve,expiry:sign_client_dist_index_es_v.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:Z})])}catch(O){throw this.events.off(qt("session_connect"),ce),this.events.off(qt("session_request",G),Re),O}return await this.setProposal(Z,sign_client_dist_index_es_I({id:Z},Ve)),await this.setAuthRequest(G,{request:dist_index_es_D(sign_client_dist_index_es_I({},W),{verifyContext:{}}),pairingTopic:R,transportType:r}),{uri:Se??V,response:mt}},this.approveSessionAuthenticate=async e=>{const{id:t,auths:s}=e,i=this.client.core.eventClient.createEvent({properties:{topic:t.toString(),trace:[As.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw i.setError(Ns.no_internet_connection),y}const r=this.getPendingAuthRequest(t);if(!r)throw i.setError(Ns.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${t}`);const n=r.transportType||dist_index_es_M.relay;n===dist_index_es_M.relay&&await this.confirmOnlineStateOrThrow();const a=r.requester.publicKey,c=await this.client.core.crypto.generateKeyPair(),h=vr(a),p={type:D,receiverPublicKey:a,senderPublicKey:c},d=[],l=[];for(const y of s){if(!await or({cacao:y,projectId:this.client.core.projectId})){i.setError(Ns.invalid_cacao);const S=index_es_("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:t,topic:h,error:S,encodeOpts:p}),new Error(S.message)}i.addTrace(As.cacaos_verified);const{p:_}=y,R=Y(_.resources),V=[ln(_.iss)],E=index_es_fe(_.iss);if(R){const S=dr(R),M=fr(R);d.push(...S),V.push(...M)}for(const S of V)l.push(`${S}:${E}`)}const w=await this.client.core.crypto.generateSharedKey(c,a);i.addTrace(As.create_authenticated_session_topic);let m;if(d?.length>0){m={topic:w,acknowledged:!0,self:{publicKey:c,metadata:this.client.metadata},peer:{publicKey:a,metadata:r.requester.metadata},controller:a,expiry:Lt(index_es_H),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:r.pairingTopic,namespaces:Yr([...new Set(d)],[...new Set(l)]),transportType:n},i.addTrace(As.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(w,{transportType:n})}catch(y){throw i.setError(Ns.subscribe_authenticated_session_topic_failure),y}i.addTrace(As.subscribe_authenticated_session_topic_success),await this.client.session.set(w,m),i.addTrace(As.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:r.pairingTopic,metadata:r.requester.metadata})}i.addTrace(As.publishing_authenticated_session_approve);try{await this.sendResult({topic:h,id:t,result:{cacaos:s,responder:{publicKey:c,metadata:this.client.metadata}},encodeOpts:p,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(r.requester.metadata,n)})}catch(y){throw i.setError(Ns.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(t,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:r.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:i.eventId}),{session:m}},this.rejectSessionAuthenticate=async e=>{this.isInitialized();const{id:t,reason:s}=e,i=this.getPendingAuthRequest(t);if(!i)throw new Error(`Could not find pending auth request with id ${t}`);i.transportType===dist_index_es_M.relay&&await this.confirmOnlineStateOrThrow();const r=i.requester.publicKey,n=await this.client.core.crypto.generateKeyPair(),a=vr(r),c={type:D,receiverPublicKey:r,senderPublicKey:n};await this.sendError({id:t,topic:a,error:s,encodeOpts:c,rpcOpts:sign_client_dist_index_es_v.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(i.requester.metadata,i.transportType)}),await this.client.auth.requests.delete(t,{message:"rejected",code:0}),await this.client.proposal.delete(t,index_es_("USER_DISCONNECTED"))},this.formatAuthMessage=e=>{this.isInitialized();const{request:t,iss:s}=e;return dn(t,s)},this.processRelayMessageCache=()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const e=this.relayMessageCache.shift();e&&await this.onRelayMessage(e)}catch(e){this.client.logger.error(e)}},50)},this.cleanupDuplicatePairings=async e=>{if(e.pairingTopic)try{const t=this.client.core.pairing.pairings.get(e.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(i=>{var r,n;return((r=i.peerMetadata)==null?void 0:r.url)&&((n=i.peerMetadata)==null?void 0:n.url)===e.peer.metadata.url&&i.topic&&i.topic!==t.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(i=>this.client.core.pairing.disconnect({topic:i.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(t){this.client.logger.error(t)}},this.deleteSession=async e=>{var t;const{topic:s,expirerHasDeleted:i=!1,emitEvent:r=!0,id:n=0}=e,{self:a}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,index_es_("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(a.publicKey)&&await this.client.core.crypto.deleteKeyPair(a.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),i||this.client.core.expirer.del(s),this.client.core.storage.removeItem(dist_index_es_De).catch(c=>this.client.logger.warn(c)),this.getPendingSessionRequests().forEach(c=>{c.topic===s&&this.deletePendingSessionRequest(c.id,index_es_("USER_DISCONNECTED"))}),s===((t=this.sessionRequestQueue.queue[0])==null?void 0:t.topic)&&(this.sessionRequestQueue.state=sign_client_dist_index_es_x.idle),r&&this.client.events.emit("session_delete",{id:n,topic:s})},this.deleteProposal=async(e,t)=>{if(t)try{const s=this.client.proposal.get(e),i=this.client.core.eventClient.getEvent({topic:s.pairingTopic});i?.setError(Os.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(e,index_es_("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"proposal")},this.deletePendingSessionRequest=async(e,t,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(e,t),s?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(i=>i.id!==e),s&&(this.sessionRequestQueue.state=sign_client_dist_index_es_x.idle,this.client.events.emit("session_request_expire",{id:e}))},this.deletePendingAuthRequest=async(e,t,s=!1)=>{await Promise.all([this.client.auth.requests.delete(e,t),s?Promise.resolve():this.client.core.expirer.del(e)])},this.setExpiry=async(e,t)=>{this.client.session.keys.includes(e)&&(this.client.core.expirer.set(e,t),await this.client.session.update(e,{expiry:t}))},this.setProposal=async(e,t)=>{this.client.core.expirer.set(e,Lt(sign_client_dist_index_es_v.wc_sessionPropose.req.ttl)),await this.client.proposal.set(e,t)},this.setAuthRequest=async(e,t)=>{const{request:s,pairingTopic:i,transportType:r=dist_index_es_M.relay}=t;this.client.core.expirer.set(e,s.expiryTimestamp),await this.client.auth.requests.set(e,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:e,pairingTopic:i,verifyContext:s.verifyContext,transportType:r})},this.setPendingSessionRequest=async e=>{const{id:t,topic:s,params:i,verifyContext:r}=e,n=i.request.expiryTimestamp||Lt(sign_client_dist_index_es_v.wc_sessionRequest.req.ttl);this.client.core.expirer.set(t,n),await this.client.pendingRequest.set(t,{id:t,topic:s,params:i,verifyContext:r})},this.sendRequest=async e=>{const{topic:t,method:s,params:i,expiry:r,relayRpcId:n,clientRpcId:a,throwOnFailedPublish:c,appLink:h}=e,p=formatJsonRpcRequest(s,i,a);let d;const l=!!h;try{const y=l?pr:ge;d=await this.client.core.crypto.encode(t,p,{encoding:y})}catch(y){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${t} failed`),y}let w;if(index_es_ct.includes(s)){const y=br(JSON.stringify(p)),_=br(d);w=await this.client.core.verify.register({id:_,decryptedId:y})}const m=sign_client_dist_index_es_v[s].req;if(m.attestation=w,r&&(m.ttl=r),n&&(m.id=n),this.client.core.history.set(t,p),l){const y=Kr(h,t,d);await global.Linking.openURL(y,this.client.name)}else{const y=sign_client_dist_index_es_v[s].req;r&&(y.ttl=r),n&&(y.id=n),c?(y.internal=dist_index_es_D(sign_client_dist_index_es_I({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(t,d,y)):this.client.core.relayer.publish(t,d,y).catch(_=>this.client.logger.error(_))}return p.id},this.sendResult=async e=>{const{id:t,topic:s,result:i,throwOnFailedPublish:r,encodeOpts:n,appLink:a}=e,c=formatJsonRpcResult(t,i);let h;const p=a&&typeof(global==null?void 0:global.Linking)<"u";try{const l=p?pr:ge;h=await this.client.core.crypto.encode(s,c,dist_index_es_D(sign_client_dist_index_es_I({},n||{}),{encoding:l}))}catch(l){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),l}let d;try{d=await this.client.core.history.get(s,t)}catch(l){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${t}) failed`),l}if(p){const l=Kr(a,s,h);await global.Linking.openURL(l,this.client.name)}else{const l=sign_client_dist_index_es_v[d.request.method].res;r?(l.internal=dist_index_es_D(sign_client_dist_index_es_I({},l.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,h,l)):this.client.core.relayer.publish(s,h,l).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(c)},this.sendError=async e=>{const{id:t,topic:s,error:i,encodeOpts:r,rpcOpts:n,appLink:a}=e,c=formatJsonRpcError(t,i);let h;const p=a&&typeof(global==null?void 0:global.Linking)<"u";try{const l=p?pr:ge;h=await this.client.core.crypto.encode(s,c,dist_index_es_D(sign_client_dist_index_es_I({},r||{}),{encoding:l}))}catch(l){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),l}let d;try{d=await this.client.core.history.get(s,t)}catch(l){throw this.client.logger.error(`sendError() -> history.get(${s}, ${t}) failed`),l}if(p){const l=Kr(a,s,h);await global.Linking.openURL(l,this.client.name)}else{const l=n||sign_client_dist_index_es_v[d.request.method].res;this.client.core.relayer.publish(s,h,l)}await this.client.core.history.resolve(c)},this.cleanup=async()=>{const e=[],t=[];this.client.session.getAll().forEach(s=>{let i=!1;Ft(s.expiry)&&(i=!0),this.client.core.crypto.keychain.has(s.topic)||(i=!0),i&&e.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{Ft(s.expiryTimestamp)&&t.push(s.id)}),await Promise.all([...e.map(s=>this.deleteSession({topic:s})),...t.map(s=>this.deleteProposal(s))])},this.onRelayEventRequest=async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===sign_client_dist_index_es_x.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=sign_client_dist_index_es_x.active;const e=this.requestQueue.queue.shift();if(e)try{await this.processRequest(e)}catch(t){this.client.logger.warn(t)}}this.requestQueue.state=sign_client_dist_index_es_x.idle},this.processRequest=async e=>{const{topic:t,payload:s,attestation:i,transportType:r,encryptedId:n}=e,a=s.method;if(!this.shouldIgnorePairingRequest({topic:t,requestMethod:a}))switch(a){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:t,payload:s,attestation:i,encryptedId:n});case"wc_sessionSettle":return await this.onSessionSettleRequest(t,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(t,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(t,s);case"wc_sessionPing":return await this.onSessionPingRequest(t,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(t,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:t,payload:s,attestation:i,encryptedId:n,transportType:r});case"wc_sessionEvent":return await this.onSessionEventRequest(t,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:t,payload:s,attestation:i,encryptedId:n,transportType:r});default:return this.client.logger.info(`Unsupported request method ${a}`)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:s,transportType:i}=e,r=(await this.client.core.history.get(t,s.id)).request.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeResponse(t,s,i);case"wc_sessionSettle":return this.onSessionSettleResponse(t,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,s);case"wc_sessionExtend":return this.onSessionExtendResponse(t,s);case"wc_sessionPing":return this.onSessionPingResponse(t,s);case"wc_sessionRequest":return this.onSessionRequestResponse(t,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(t,s);default:return this.client.logger.info(`Unsupported response method ${r}`)}},this.onRelayEventUnknownPayload=e=>{const{topic:t}=e,{message:s}=index_es_S("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)},this.shouldIgnorePairingRequest=e=>{const{topic:t,requestMethod:s}=e,i=this.expectedPairingMethodMap.get(t);return!i||i.includes(s)?!1:!!(i.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async e=>{const{topic:t,payload:s,attestation:i,encryptedId:r}=e,{params:n,id:a}=s;try{const c=this.client.core.eventClient.getEvent({topic:t});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),c?.setError(index_es_$.proposal_listener_not_found)),this.isValidConnect(sign_client_dist_index_es_I({},s.params));const h=n.expiryTimestamp||Lt(sign_client_dist_index_es_v.wc_sessionPropose.req.ttl),p=sign_client_dist_index_es_I({id:a,pairingTopic:t,expiryTimestamp:h},n);await this.setProposal(a,p);const d=await this.getVerifyContext({attestationId:i,hash:br(JSON.stringify(s)),encryptedId:r,metadata:p.proposer.metadata});c?.addTrace(core_dist_index_es_z.emit_session_proposal),this.client.events.emit("session_proposal",{id:a,params:p,verifyContext:d})}catch(c){await this.sendError({id:a,topic:t,error:c,rpcOpts:sign_client_dist_index_es_v.wc_sessionPropose.autoReject}),this.client.logger.error(c)}},this.onSessionProposeResponse=async(e,t,s)=>{const{id:i}=t;if(isJsonRpcResult(t)){const{result:r}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:r});const n=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:n});const a=n.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:a});const c=r.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:c});const h=await this.client.core.crypto.generateSharedKey(a,c);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",sessionTopic:h});const p=await this.client.core.relayer.subscribe(h,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:p}),await this.client.core.pairing.activate({topic:e})}else if(isJsonRpcError(t)){await this.client.proposal.delete(i,index_es_("USER_DISCONNECTED"));const r=qt("session_connect");if(this.events.listenerCount(r)===0)throw new Error(`emitting ${r} without any listeners, 954`);this.events.emit(qt("session_connect"),{error:t.error})}},this.onSessionSettleRequest=async(e,t)=>{const{id:s,params:i}=t;try{this.isValidSessionSettleRequest(i);const{relay:r,controller:n,expiry:a,namespaces:c,sessionProperties:h,sessionConfig:p}=t.params,d=dist_index_es_D(sign_client_dist_index_es_I(sign_client_dist_index_es_I({topic:e,relay:r,expiry:a,namespaces:c,acknowledged:!0,pairingTopic:"",requiredNamespaces:{},optionalNamespaces:{},controller:n.publicKey,self:{publicKey:"",metadata:this.client.metadata},peer:{publicKey:n.publicKey,metadata:n.metadata}},h&&{sessionProperties:h}),p&&{sessionConfig:p}),{transportType:dist_index_es_M.relay}),l=qt("session_connect");if(this.events.listenerCount(l)===0)throw new Error(`emitting ${l} without any listeners 997`);this.events.emit(qt("session_connect"),{session:d}),await this.sendResult({id:t.id,topic:e,result:!0,throwOnFailedPublish:!0})}catch(r){await this.sendError({id:s,topic:e,error:r}),this.client.logger.error(r)}},this.onSessionSettleResponse=async(e,t)=>{const{id:s}=t;isJsonRpcResult(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(qt("session_approve",s),{})):isJsonRpcError(t)&&(await this.client.session.delete(e,index_es_("USER_DISCONNECTED")),this.events.emit(qt("session_approve",s),{error:t.error}))},this.onSessionUpdateRequest=async(e,t)=>{const{params:s,id:i}=t;try{const r=`${e}_session_update`,n=bo.get(r);if(n&&this.isRequestOutOfSync(n,i)){this.client.logger.warn(`Discarding out of sync request - ${i}`),this.sendError({id:i,topic:e,error:index_es_("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(sign_client_dist_index_es_I({topic:e},s));try{bo.set(r,i),await this.client.session.update(e,{namespaces:s.namespaces}),await this.sendResult({id:i,topic:e,result:!0,throwOnFailedPublish:!0})}catch(a){throw bo.delete(r),a}this.client.events.emit("session_update",{id:i,topic:e,params:s})}catch(r){await this.sendError({id:i,topic:e,error:r}),this.client.logger.error(r)}},this.isRequestOutOfSync=(e,t)=>t.toString().slice(0,-3){const{id:s}=t,i=qt("session_update",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);isJsonRpcResult(t)?this.events.emit(qt("session_update",s),{}):isJsonRpcError(t)&&this.events.emit(qt("session_update",s),{error:t.error})},this.onSessionExtendRequest=async(e,t)=>{const{id:s}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,Lt(index_es_H)),await this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:s,topic:e})}catch(i){await this.sendError({id:s,topic:e,error:i}),this.client.logger.error(i)}},this.onSessionExtendResponse=(e,t)=>{const{id:s}=t,i=qt("session_extend",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);isJsonRpcResult(t)?this.events.emit(qt("session_extend",s),{}):isJsonRpcError(t)&&this.events.emit(qt("session_extend",s),{error:t.error})},this.onSessionPingRequest=async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:e})}catch(i){await this.sendError({id:s,topic:e,error:i}),this.client.logger.error(i)}},this.onSessionPingResponse=(e,t)=>{const{id:s}=t,i=qt("session_ping",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);setTimeout(()=>{isJsonRpcResult(t)?this.events.emit(qt("session_ping",s),{}):isJsonRpcError(t)&&this.events.emit(qt("session_ping",s),{error:t.error})},500)},this.onSessionDeleteRequest=async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),Promise.all([new Promise(i=>{this.client.core.relayer.once(core_dist_index_es_v.publish,async()=>{i(await this.deleteSession({topic:e,id:s}))})}),this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:e,error:index_es_("USER_DISCONNECTED")})]).catch(i=>this.client.logger.error(i))}catch(i){this.client.logger.error(i)}},this.onSessionRequest=async e=>{var t,s,i;const{topic:r,payload:n,attestation:a,encryptedId:c,transportType:h}=e,{id:p,params:d}=n;try{await this.isValidRequest(sign_client_dist_index_es_I({topic:r},d));const l=this.client.session.get(r),w=await this.getVerifyContext({attestationId:a,hash:br(JSON.stringify(formatJsonRpcRequest("wc_sessionRequest",d,p))),encryptedId:c,metadata:l.peer.metadata,transportType:h}),m={id:p,topic:r,params:d,verifyContext:w};await this.setPendingSessionRequest(m),h===dist_index_es_M.link_mode&&(t=l.peer.metadata.redirect)!=null&&t.universal&&this.client.core.addLinkModeSupportedApp((s=l.peer.metadata.redirect)==null?void 0:s.universal),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(m):(this.addSessionRequestToSessionRequestQueue(m),this.processSessionRequestQueue())}catch(l){await this.sendError({id:p,topic:r,error:l}),this.client.logger.error(l)}},this.onSessionRequestResponse=(e,t)=>{const{id:s}=t,i=qt("session_request",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);isJsonRpcResult(t)?this.events.emit(qt("session_request",s),{result:t.result}):isJsonRpcError(t)&&this.events.emit(qt("session_request",s),{error:t.error})},this.onSessionEventRequest=async(e,t)=>{const{id:s,params:i}=t;try{const r=`${e}_session_event_${i.event.name}`,n=bo.get(r);if(n&&this.isRequestOutOfSync(n,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(sign_client_dist_index_es_I({topic:e},i)),this.client.events.emit("session_event",{id:s,topic:e,params:i}),bo.set(r,s)}catch(r){await this.sendError({id:s,topic:e,error:r}),this.client.logger.error(r)}},this.onSessionAuthenticateResponse=(e,t)=>{const{id:s}=t;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:e,payload:t}),isJsonRpcResult(t)?this.events.emit(qt("session_request",s),{result:t.result}):isJsonRpcError(t)&&this.events.emit(qt("session_request",s),{error:t.error})},this.onSessionAuthenticateRequest=async e=>{var t;const{topic:s,payload:i,attestation:r,encryptedId:n,transportType:a}=e;try{const{requester:c,authPayload:h,expiryTimestamp:p}=i.params,d=await this.getVerifyContext({attestationId:r,hash:br(JSON.stringify(i)),encryptedId:n,metadata:c.metadata,transportType:a}),l={requester:c,pairingTopic:s,id:i.id,authPayload:h,verifyContext:d,expiryTimestamp:p};await this.setAuthRequest(i.id,{request:l,pairingTopic:s,transportType:a}),a===dist_index_es_M.link_mode&&(t=c.metadata.redirect)!=null&&t.universal&&this.client.core.addLinkModeSupportedApp(c.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:i.params,id:i.id,verifyContext:d})}catch(c){this.client.logger.error(c);const h=i.params.requester.publicKey,p=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(i.params.requester.metadata,a),l={type:D,receiverPublicKey:h,senderPublicKey:p};await this.sendError({id:i.id,topic:s,error:c,encodeOpts:l,rpcOpts:sign_client_dist_index_es_v.wc_sessionAuthenticate.autoReject,appLink:d})}},this.addSessionRequestToSessionRequestQueue=e=>{this.sessionRequestQueue.queue.push(e)},this.cleanupAfterResponse=e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=sign_client_dist_index_es_x.idle,this.processSessionRequestQueue()},(0,cjs.toMiliseconds)(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:e,error:t})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(i=>i.topic===e&&i.request.method==="wc_sessionRequest").forEach(i=>{const r=i.request.id,n=qt("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);this.events.emit(qt("session_request",i.request.id),{error:t})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===sign_client_dist_index_es_x.active){this.client.logger.info("session request queue is already active.");return}const e=this.sessionRequestQueue.queue[0];if(!e){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=sign_client_dist_index_es_x.active,this.emitSessionRequest(e)}catch(t){this.client.logger.error(t)}},this.emitSessionRequest=e=>{this.client.events.emit("session_request",e)},this.onPairingCreated=e=>{if(e.methods&&this.expectedPairingMethodMap.set(e.topic,e.methods),e.active)return;const t=this.client.proposal.getAll().find(s=>s.pairingTopic===e.topic);t&&this.onSessionProposeRequest({topic:e.topic,payload:formatJsonRpcRequest("wc_sessionPropose",{requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces,relays:t.relays,proposer:t.proposer,sessionProperties:t.sessionProperties},t.id)})},this.isValidConnect=async e=>{if(!so(e)){const{message:a}=index_es_S("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(a)}const{pairingTopic:t,requiredNamespaces:s,optionalNamespaces:i,sessionProperties:r,relays:n}=e;if(index_es_P(t)||await this.isValidPairingTopic(t),!ro(n,!0)){const{message:a}=index_es_S("MISSING_OR_INVALID",`connect() relays: ${n}`);throw new Error(a)}!index_es_P(s)&&Z(s)!==0&&this.validateNamespaces(s,"requiredNamespaces"),!index_es_P(i)&&Z(i)!==0&&this.validateNamespaces(i,"optionalNamespaces"),index_es_P(r)||this.validateSessionProps(r,"sessionProperties")},this.validateNamespaces=(e,t)=>{const s=to(e,"connect()",t);if(s)throw new Error(s.message)},this.isValidApprove=async e=>{if(!so(e))throw new Error(index_es_S("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:s,relayProtocol:i,sessionProperties:r}=e;this.checkRecentlyDeleted(t),await this.isValidProposalId(t);const n=this.client.proposal.get(t),a=Wn(s,"approve()");if(a)throw new Error(a.message);const c=zn(n.requiredNamespaces,s,"approve()");if(c)throw new Error(c.message);if(!index_es_b(i,!0)){const{message:h}=index_es_S("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(h)}index_es_P(r)||this.validateSessionProps(r,"sessionProperties")},this.isValidReject=async e=>{if(!so(e)){const{message:i}=index_es_S("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(i)}const{id:t,reason:s}=e;if(this.checkRecentlyDeleted(t),await this.isValidProposalId(t),!io(s)){const{message:i}=index_es_S("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(i)}},this.isValidSessionSettleRequest=e=>{if(!so(e)){const{message:c}=index_es_S("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(c)}const{relay:t,controller:s,namespaces:i,expiry:r}=e;if(!Jn(t)){const{message:c}=index_es_S("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(c)}const n=no(s,"onSessionSettleRequest()");if(n)throw new Error(n.message);const a=Wn(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);if(Ft(r)){const{message:c}=index_es_S("EXPIRED","onSessionSettleRequest()");throw new Error(c)}},this.isValidUpdate=async e=>{if(!so(e)){const{message:a}=index_es_S("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(a)}const{topic:t,namespaces:s}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const i=this.client.session.get(t),r=Wn(s,"update()");if(r)throw new Error(r.message);const n=zn(i.requiredNamespaces,s,"update()");if(n)throw new Error(n.message)},this.isValidExtend=async e=>{if(!so(e)){const{message:s}=index_es_S("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(s)}const{topic:t}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t)},this.isValidRequest=async e=>{if(!so(e)){const{message:a}=index_es_S("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(a)}const{topic:t,request:s,chainId:i,expiry:r}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const{namespaces:n}=this.client.session.get(t);if(!lo(n,i)){const{message:a}=index_es_S("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(a)}if(!co(s)){const{message:a}=index_es_S("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(a)}if(!fo(n,i,s.method)){const{message:a}=index_es_S("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(a)}if(r&&!yo(r,dist_index_es_me)){const{message:a}=index_es_S("MISSING_OR_INVALID",`request() expiry: ${r}. Expiry must be a number (in seconds) between ${dist_index_es_me.min} and ${dist_index_es_me.max}`);throw new Error(a)}},this.isValidRespond=async e=>{var t;if(!so(e)){const{message:r}=index_es_S("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(r)}const{topic:s,response:i}=e;try{await this.isValidSessionTopic(s)}catch(r){throw(t=e?.response)!=null&&t.id&&this.cleanupAfterResponse(e),r}if(!ao(i)){const{message:r}=index_es_S("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(r)}},this.isValidPing=async e=>{if(!so(e)){const{message:s}=index_es_S("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidEmit=async e=>{if(!so(e)){const{message:n}=index_es_S("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(n)}const{topic:t,event:s,chainId:i}=e;await this.isValidSessionTopic(t);const{namespaces:r}=this.client.session.get(t);if(!lo(r,i)){const{message:n}=index_es_S("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(n)}if(!uo(s)){const{message:n}=index_es_S("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(n)}if(!po(r,i,s.name)){const{message:n}=index_es_S("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(n)}},this.isValidDisconnect=async e=>{if(!so(e)){const{message:s}=index_es_S("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(s)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidAuthenticate=e=>{const{chains:t,uri:s,domain:i,nonce:r}=e;if(!Array.isArray(t)||t.length===0)throw new Error("chains is required and must be a non-empty array");if(!index_es_b(s,!1))throw new Error("uri is required parameter");if(!index_es_b(i,!1))throw new Error("domain is required parameter");if(!index_es_b(r,!1))throw new Error("nonce is required parameter");if([...new Set(t.map(a=>re(a).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:n}=re(t[0]);if(n!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async e=>{const{attestationId:t,hash:s,encryptedId:i,metadata:r,transportType:n}=e,a={verified:{verifyUrl:r.verifyUrl||index_es_X,validation:"UNKNOWN",origin:r.url||""}};try{if(n===dist_index_es_M.link_mode){const h=this.getAppLinkIfEnabled(r,n);return a.verified.validation=h&&new URL(h).origin===new URL(r.url).origin?"VALID":"INVALID",a}const c=await this.client.core.verify.resolve({attestationId:t,hash:s,encryptedId:i,verifyUrl:r.verifyUrl});c&&(a.verified.origin=c.origin,a.verified.isScam=c.isScam,a.verified.validation=c.origin===new URL(r.url).origin?"VALID":"INVALID")}catch(c){this.client.logger.warn(c)}return this.client.logger.debug(`Verify context: ${JSON.stringify(a)}`),a},this.validateSessionProps=(e,t)=>{Object.values(e).forEach(s=>{if(!index_es_b(s,!1)){const{message:i}=index_es_S("MISSING_OR_INVALID",`${t} must be in Record format. Received: ${JSON.stringify(s)}`);throw new Error(i)}})},this.getPendingAuthRequest=e=>{const t=this.client.auth.requests.get(e);return typeof t=="object"?t:void 0},this.addToRecentlyDeleted=(e,t)=>{if(this.recentlyDeletedMap.set(e,t),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const i=this.recentlyDeletedLimit/2;for(const r of this.recentlyDeletedMap.keys()){if(s++>=i)break;this.recentlyDeletedMap.delete(r)}}},this.checkRecentlyDeleted=e=>{const t=this.recentlyDeletedMap.get(e);if(t){const{message:s}=index_es_S("MISSING_OR_INVALID",`Record was recently deleted - ${t}: ${e}`);throw new Error(s)}},this.isLinkModeEnabled=(e,t)=>{var s,i,r,n,a,c,h,p,d;return!e||t!==dist_index_es_M.link_mode?!1:((i=(s=this.client.metadata)==null?void 0:s.redirect)==null?void 0:i.linkMode)===!0&&((n=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:n.universal)!==void 0&&((c=(a=this.client.metadata)==null?void 0:a.redirect)==null?void 0:c.universal)!==""&&((h=e?.redirect)==null?void 0:h.universal)!==void 0&&((p=e?.redirect)==null?void 0:p.universal)!==""&&((d=e?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(e.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"},this.getAppLinkIfEnabled=(e,t)=>{var s;return this.isLinkModeEnabled(e,t)?(s=e?.redirect)==null?void 0:s.universal:void 0},this.handleLinkModeMessage=({url:e})=>{if(!e||!e.includes("wc_ev")||!e.includes("topic"))return;const t=Wt(e,"topic")||"",s=decodeURIComponent(Wt(e,"wc_ev")||""),i=this.client.session.keys.includes(t);i&&this.client.session.update(t,{transportType:dist_index_es_M.link_mode}),this.client.core.dispatchEnvelope({topic:t,message:s,sessionExists:i})},this.registerLinkModeListeners=async()=>{var e;if(zt()||$()&&(e=this.client.metadata.redirect)!=null&&e.linkMode){const t=global==null?void 0:global.Linking;if(typeof t<"u"){t.addEventListener("url",this.handleLinkModeMessage,this.client.name);const s=await t.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}}isInitialized(){if(!this.initialized){const{message:o}=index_es_S("NOT_INITIALIZED",this.name);throw new Error(o)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(core_dist_index_es_v.message,o=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(o):this.onRelayMessage(o)})}async onRelayMessage(o){const{topic:e,message:t,attestation:s,transportType:i}=o,{publicKey:r}=this.client.auth.authKeys.keys.includes(index_es_ae)?this.client.auth.authKeys.get(index_es_ae):{responseTopic:void 0,publicKey:void 0},n=await this.client.core.crypto.decode(e,t,{receiverPublicKey:r,encoding:i===dist_index_es_M.link_mode?pr:ge});try{isJsonRpcRequest(n)?(this.client.core.history.set(e,n),this.onRelayEventRequest({topic:e,payload:n,attestation:s,transportType:i,encryptedId:br(t)})):isJsonRpcResponse(n)?(await this.client.core.history.resolve(n),await this.onRelayEventResponse({topic:e,payload:n,transportType:i}),this.client.core.history.delete(e,n.id)):this.onRelayEventUnknownPayload({topic:e,payload:n,transportType:i})}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(core_dist_index_es_x.expired,async o=>{const{topic:e,id:t}=Kt(o.target);if(t&&this.client.pendingRequest.keys.includes(t))return await this.deletePendingSessionRequest(t,index_es_S("EXPIRED"),!0);if(t&&this.client.auth.requests.keys.includes(t))return await this.deletePendingAuthRequest(t,index_es_S("EXPIRED"),!0);e?this.client.session.keys.includes(e)&&(await this.deleteSession({topic:e,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:e})):t&&(await this.deleteProposal(t,!0),this.client.events.emit("proposal_expire",{id:t}))})}registerPairingEvents(){this.client.core.pairing.events.on(index_es_j.create,o=>this.onPairingCreated(o)),this.client.core.pairing.events.on(index_es_j.delete,o=>{this.addToRecentlyDeleted(o.topic,"pairing")})}isValidPairingTopic(o){if(!index_es_b(o,!1)){const{message:e}=index_es_S("MISSING_OR_INVALID",`pairing topic should be a string: ${o}`);throw new Error(e)}if(!this.client.core.pairing.pairings.keys.includes(o)){const{message:e}=index_es_S("NO_MATCHING_KEY",`pairing topic doesn't exist: ${o}`);throw new Error(e)}if(Ft(this.client.core.pairing.pairings.get(o).expiry)){const{message:e}=index_es_S("EXPIRED",`pairing topic: ${o}`);throw new Error(e)}}async isValidSessionTopic(o){if(!index_es_b(o,!1)){const{message:e}=index_es_S("MISSING_OR_INVALID",`session topic should be a string: ${o}`);throw new Error(e)}if(this.checkRecentlyDeleted(o),!this.client.session.keys.includes(o)){const{message:e}=index_es_S("NO_MATCHING_KEY",`session topic doesn't exist: ${o}`);throw new Error(e)}if(Ft(this.client.session.get(o).expiry)){await this.deleteSession({topic:o});const{message:e}=index_es_S("EXPIRED",`session topic: ${o}`);throw new Error(e)}if(!this.client.core.crypto.keychain.has(o)){const{message:e}=index_es_S("MISSING_OR_INVALID",`session topic does not exist in keychain: ${o}`);throw await this.deleteSession({topic:o}),new Error(e)}}async isValidSessionOrPairingTopic(o){if(this.checkRecentlyDeleted(o),this.client.session.keys.includes(o))await this.isValidSessionTopic(o);else if(this.client.core.pairing.pairings.keys.includes(o))this.isValidPairingTopic(o);else if(index_es_b(o,!1)){const{message:e}=index_es_S("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${o}`);throw new Error(e)}else{const{message:e}=index_es_S("MISSING_OR_INVALID",`session or pairing topic should be a string: ${o}`);throw new Error(e)}}async isValidProposalId(o){if(!oo(o)){const{message:e}=index_es_S("MISSING_OR_INVALID",`proposal id should be a number: ${o}`);throw new Error(e)}if(!this.client.proposal.keys.includes(o)){const{message:e}=index_es_S("NO_MATCHING_KEY",`proposal id doesn't exist: ${o}`);throw new Error(e)}if(Ft(this.client.proposal.get(o).expiryTimestamp)){await this.deleteProposal(o);const{message:e}=index_es_S("EXPIRED",`proposal id: ${o}`);throw new Error(e)}}}class index_es_Ss extends li{constructor(o,e){super(o,e,index_es_it,dist_index_es_ye),this.core=o,this.logger=e}}class dist_index_es_wt extends li{constructor(o,e){super(o,e,index_es_nt,dist_index_es_ye),this.core=o,this.logger=e}}class index_es_Is extends li{constructor(o,e){super(o,e,index_es_at,dist_index_es_ye,t=>t.id),this.core=o,this.logger=e}}class fs extends li{constructor(o,e){super(o,e,dist_index_es_ht,dist_index_es_oe,()=>index_es_ae),this.core=o,this.logger=e}}class vs extends li{constructor(o,e){super(o,e,index_es_dt,dist_index_es_oe),this.core=o,this.logger=e}}class index_es_qs extends li{constructor(o,e){super(o,e,index_es_ut,dist_index_es_oe,t=>t.id),this.core=o,this.logger=e}}class index_es_Ts{constructor(o,e){this.core=o,this.logger=e,this.authKeys=new fs(this.core,this.logger),this.pairingTopics=new vs(this.core,this.logger),this.requests=new index_es_qs(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}class dist_index_es_e extends types_dist_index_es_S{constructor(o){super(o),this.protocol=Ce,this.version=index_es_Le,this.name=dist_index_es_we.name,this.events=new external_events_.EventEmitter,this.on=(t,s)=>this.events.on(t,s),this.once=(t,s)=>this.events.once(t,s),this.off=(t,s)=>this.events.off(t,s),this.removeListener=(t,s)=>this.events.removeListener(t,s),this.removeAllListeners=t=>this.events.removeAllListeners(t),this.connect=async t=>{try{return await this.engine.connect(t)}catch(s){throw this.logger.error(s.message),s}},this.pair=async t=>{try{return await this.engine.pair(t)}catch(s){throw this.logger.error(s.message),s}},this.approve=async t=>{try{return await this.engine.approve(t)}catch(s){throw this.logger.error(s.message),s}},this.reject=async t=>{try{return await this.engine.reject(t)}catch(s){throw this.logger.error(s.message),s}},this.update=async t=>{try{return await this.engine.update(t)}catch(s){throw this.logger.error(s.message),s}},this.extend=async t=>{try{return await this.engine.extend(t)}catch(s){throw this.logger.error(s.message),s}},this.request=async t=>{try{return await this.engine.request(t)}catch(s){throw this.logger.error(s.message),s}},this.respond=async t=>{try{return await this.engine.respond(t)}catch(s){throw this.logger.error(s.message),s}},this.ping=async t=>{try{return await this.engine.ping(t)}catch(s){throw this.logger.error(s.message),s}},this.emit=async t=>{try{return await this.engine.emit(t)}catch(s){throw this.logger.error(s.message),s}},this.disconnect=async t=>{try{return await this.engine.disconnect(t)}catch(s){throw this.logger.error(s.message),s}},this.find=t=>{try{return this.engine.find(t)}catch(s){throw this.logger.error(s.message),s}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(t){throw this.logger.error(t.message),t}},this.authenticate=async(t,s)=>{try{return await this.engine.authenticate(t,s)}catch(i){throw this.logger.error(i.message),i}},this.formatAuthMessage=t=>{try{return this.engine.formatAuthMessage(t)}catch(s){throw this.logger.error(s.message),s}},this.approveSessionAuthenticate=async t=>{try{return await this.engine.approveSessionAuthenticate(t)}catch(s){throw this.logger.error(s.message),s}},this.rejectSessionAuthenticate=async t=>{try{return await this.engine.rejectSessionAuthenticate(t)}catch(s){throw this.logger.error(s.message),s}},this.name=o?.name||dist_index_es_we.name,this.metadata=o?.metadata||$t(),this.signConfig=o?.signConfig;const e=typeof o?.logger<"u"&&typeof o?.logger!="string"?o.logger:pino_default()(logger_dist_index_es_k({level:o?.logger||dist_index_es_we.logger}));this.core=o?.core||new index_es_Rn(o),this.logger=dist_index_es_E(e,this.name),this.session=new dist_index_es_wt(this.core,this.logger),this.proposal=new index_es_Ss(this.core,this.logger),this.pendingRequest=new index_es_Is(this.core,this.logger),this.engine=new index_es_Rs(this),this.auth=new index_es_Ts(this.core,this.logger)}static async init(o){const e=new dist_index_es_e(o);return await e.initialize(),e}get context(){return dist_index_es_y(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},(0,cjs.toMiliseconds)(cjs.ONE_SECOND))}catch(o){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(o.message),o}}}const index_es_Ns=(/* unused pure expression or super */ null && (dist_index_es_wt)),index_es_Ps=(/* unused pure expression or super */ null && (dist_index_es_e));
//# sourceMappingURL=index.es.js.map
// EXTERNAL MODULE: ./node_modules/lodash/lodash.js
@@ -6749,15 +6749,15 @@ var lodash = __webpack_require__(302543);
var node_ponyfill = __webpack_require__(144484);
var node_ponyfill_default = /*#__PURE__*/__webpack_require__.n(node_ponyfill);
;// ./node_modules/@walletconnect/jsonrpc-http-connection/dist/index.es.js
-var jsonrpc_http_connection_dist_index_es_P=Object.defineProperty,jsonrpc_http_connection_dist_index_es_w=Object.defineProperties,jsonrpc_http_connection_dist_index_es_E=Object.getOwnPropertyDescriptors,jsonrpc_http_connection_dist_index_es_c=Object.getOwnPropertySymbols,dist_index_es_L=Object.prototype.hasOwnProperty,jsonrpc_http_connection_dist_index_es_O=Object.prototype.propertyIsEnumerable,jsonrpc_http_connection_dist_index_es_l=(r,t,e)=>t in r?jsonrpc_http_connection_dist_index_es_P(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,jsonrpc_http_connection_dist_index_es_p=(r,t)=>{for(var e in t||(t={}))dist_index_es_L.call(t,e)&&jsonrpc_http_connection_dist_index_es_l(r,e,t[e]);if(jsonrpc_http_connection_dist_index_es_c)for(var e of jsonrpc_http_connection_dist_index_es_c(t))jsonrpc_http_connection_dist_index_es_O.call(t,e)&&jsonrpc_http_connection_dist_index_es_l(r,e,t[e]);return r},jsonrpc_http_connection_dist_index_es_v=(r,t)=>jsonrpc_http_connection_dist_index_es_w(r,jsonrpc_http_connection_dist_index_es_E(t));const index_es_j={Accept:"application/json","Content-Type":"application/json"},index_es_T="POST",jsonrpc_http_connection_dist_index_es_d={headers:index_es_j,method:index_es_T},jsonrpc_http_connection_dist_index_es_g=10;class jsonrpc_http_connection_dist_index_es_f{constructor(t,e=!1){if(this.url=t,this.disableProviderPing=e,this.events=new external_events_.EventEmitter,this.isAvailable=!1,this.registering=!1,!isHttpUrl(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);this.url=t,this.disableProviderPing=e}get connected(){return this.isAvailable}get connecting(){return this.registering}on(t,e){this.events.on(t,e)}once(t,e){this.events.once(t,e)}off(t,e){this.events.off(t,e)}removeListener(t,e){this.events.removeListener(t,e)}async open(t=this.url){await this.register(t)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(t){this.isAvailable||await this.register();try{const e=safeJsonStringify(t),s=await(await node_ponyfill_default()(this.url,jsonrpc_http_connection_dist_index_es_v(jsonrpc_http_connection_dist_index_es_p({},jsonrpc_http_connection_dist_index_es_d),{body:e}))).json();this.onPayload({data:s})}catch(e){this.onError(t.id,e)}}async register(t=this.url){if(!isHttpUrl(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);if(this.registering){const e=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=e||this.events.listenerCount("open")>=e)&&this.events.setMaxListeners(e+1),new Promise((s,i)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),i(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));s()})})}this.url=t,this.registering=!0;try{if(!this.disableProviderPing){const e=safeJsonStringify({id:1,jsonrpc:"2.0",method:"test",params:[]});await node_ponyfill_default()(t,jsonrpc_http_connection_dist_index_es_v(jsonrpc_http_connection_dist_index_es_p({},jsonrpc_http_connection_dist_index_es_d),{body:e}))}this.onOpen()}catch(e){const s=this.parseError(e);throw this.events.emit("register_error",s),this.onClose(),s}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(t){if(typeof t.data>"u")return;const e=typeof t.data=="string"?safeJsonParse(t.data):t.data;this.events.emit("payload",e)}onError(t,e){const s=this.parseError(e),i=s.message||s.toString(),n=formatJsonRpcError(t,i);this.events.emit("payload",n)}parseError(t,e=this.url){return parseConnectionError(t,e,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>jsonrpc_http_connection_dist_index_es_g&&this.events.setMaxListeners(jsonrpc_http_connection_dist_index_es_g)}}
+var dist_index_es_P=Object.defineProperty,jsonrpc_http_connection_dist_index_es_w=Object.defineProperties,jsonrpc_http_connection_dist_index_es_E=Object.getOwnPropertyDescriptors,jsonrpc_http_connection_dist_index_es_c=Object.getOwnPropertySymbols,dist_index_es_L=Object.prototype.hasOwnProperty,jsonrpc_http_connection_dist_index_es_O=Object.prototype.propertyIsEnumerable,jsonrpc_http_connection_dist_index_es_l=(r,t,e)=>t in r?dist_index_es_P(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,jsonrpc_http_connection_dist_index_es_p=(r,t)=>{for(var e in t||(t={}))dist_index_es_L.call(t,e)&&jsonrpc_http_connection_dist_index_es_l(r,e,t[e]);if(jsonrpc_http_connection_dist_index_es_c)for(var e of jsonrpc_http_connection_dist_index_es_c(t))jsonrpc_http_connection_dist_index_es_O.call(t,e)&&jsonrpc_http_connection_dist_index_es_l(r,e,t[e]);return r},jsonrpc_http_connection_dist_index_es_v=(r,t)=>jsonrpc_http_connection_dist_index_es_w(r,jsonrpc_http_connection_dist_index_es_E(t));const dist_index_es_j={Accept:"application/json","Content-Type":"application/json"},dist_index_es_T="POST",jsonrpc_http_connection_dist_index_es_d={headers:dist_index_es_j,method:dist_index_es_T},jsonrpc_http_connection_dist_index_es_g=10;class jsonrpc_http_connection_dist_index_es_f{constructor(t,e=!1){if(this.url=t,this.disableProviderPing=e,this.events=new external_events_.EventEmitter,this.isAvailable=!1,this.registering=!1,!isHttpUrl(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);this.url=t,this.disableProviderPing=e}get connected(){return this.isAvailable}get connecting(){return this.registering}on(t,e){this.events.on(t,e)}once(t,e){this.events.once(t,e)}off(t,e){this.events.off(t,e)}removeListener(t,e){this.events.removeListener(t,e)}async open(t=this.url){await this.register(t)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(t){this.isAvailable||await this.register();try{const e=safeJsonStringify(t),s=await(await node_ponyfill_default()(this.url,jsonrpc_http_connection_dist_index_es_v(jsonrpc_http_connection_dist_index_es_p({},jsonrpc_http_connection_dist_index_es_d),{body:e}))).json();this.onPayload({data:s})}catch(e){this.onError(t.id,e)}}async register(t=this.url){if(!isHttpUrl(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);if(this.registering){const e=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=e||this.events.listenerCount("open")>=e)&&this.events.setMaxListeners(e+1),new Promise((s,i)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),i(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return i(new Error("HTTP connection is missing or invalid"));s()})})}this.url=t,this.registering=!0;try{if(!this.disableProviderPing){const e=safeJsonStringify({id:1,jsonrpc:"2.0",method:"test",params:[]});await node_ponyfill_default()(t,jsonrpc_http_connection_dist_index_es_v(jsonrpc_http_connection_dist_index_es_p({},jsonrpc_http_connection_dist_index_es_d),{body:e}))}this.onOpen()}catch(e){const s=this.parseError(e);throw this.events.emit("register_error",s),this.onClose(),s}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(t){if(typeof t.data>"u")return;const e=typeof t.data=="string"?safeJsonParse(t.data):t.data;this.events.emit("payload",e)}onError(t,e){const s=this.parseError(e),i=s.message||s.toString(),n=formatJsonRpcError(t,i);this.events.emit("payload",n)}parseError(t,e=this.url){return parseConnectionError(t,e,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>jsonrpc_http_connection_dist_index_es_g&&this.events.setMaxListeners(jsonrpc_http_connection_dist_index_es_g)}}
//# sourceMappingURL=index.es.js.map
;// ./node_modules/@walletconnect/universal-provider/dist/index.es.js
-const universal_provider_dist_index_es_D="error",dist_index_es_rt="wss://relay.walletconnect.org",dist_index_es_nt="wc",dist_index_es_at="universal_provider",universal_provider_dist_index_es_S=`${dist_index_es_nt}@2:${dist_index_es_at}:`,universal_provider_dist_index_es_="https://rpc.walletconnect.org/v1/",universal_provider_dist_index_es_f="generic",dist_index_es_ot=`${universal_provider_dist_index_es_}bundler`,universal_provider_dist_index_es_p={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var dist_index_es_ct=Object.defineProperty,universal_provider_dist_index_es_ht=Object.defineProperties,universal_provider_dist_index_es_pt=Object.getOwnPropertyDescriptors,dist_index_es_j=Object.getOwnPropertySymbols,dist_index_es_dt=Object.prototype.hasOwnProperty,dist_index_es_ut=Object.prototype.propertyIsEnumerable,dist_index_es_R=(r,t,e)=>t in r?dist_index_es_ct(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,universal_provider_dist_index_es_g=(r,t)=>{for(var e in t||(t={}))dist_index_es_dt.call(t,e)&&dist_index_es_R(r,e,t[e]);if(dist_index_es_j)for(var e of dist_index_es_j(t))dist_index_es_ut.call(t,e)&&dist_index_es_R(r,e,t[e]);return r},dist_index_es_lt=(r,t)=>universal_provider_dist_index_es_ht(r,universal_provider_dist_index_es_pt(t));function universal_provider_dist_index_es_h(r,t,e){var s;const i=re(r);return((s=t.rpcMap)==null?void 0:s[i.reference])||`${universal_provider_dist_index_es_}?chainId=${i.namespace}:${i.reference}&projectId=${e}`}function universal_provider_dist_index_es_l(r){return r.includes(":")?r.split(":")[1]:r}function index_es_U(r){return r.map(t=>`${t.split(":")[0]}:${t.split(":")[1]}`)}function dist_index_es_mt(r,t){const e=Object.keys(t.namespaces).filter(i=>i.includes(r));if(!e.length)return[];const s=[];return e.forEach(i=>{const n=t.namespaces[i].accounts;s.push(...n)}),s}function dist_index_es_$(r={},t={}){const e=dist_index_es_T(r),s=dist_index_es_T(t);return (0,lodash.merge)(e,s)}function dist_index_es_T(r){var t,e,s,i;const n={};if(!Z(r))return n;for(const[a,c]of Object.entries(r)){const m=Oe(a)?[a]:c.chains,I=c.methods||[],V=c.events||[],B=c.rpcMap||{},v=Dn(a);n[v]=dist_index_es_lt(universal_provider_dist_index_es_g(universal_provider_dist_index_es_g({},n[v]),c),{chains:N(m,(t=n[v])==null?void 0:t.chains),methods:N(I,(e=n[v])==null?void 0:e.methods),events:N(V,(s=n[v])==null?void 0:s.events),rpcMap:universal_provider_dist_index_es_g(universal_provider_dist_index_es_g({},B),(i=n[v])==null?void 0:i.rpcMap)})}return n}function dist_index_es_vt(r){return r.includes(":")?r.split(":")[2]:r}function universal_provider_dist_index_es_k(r){const t={};for(const[e,s]of Object.entries(r)){const i=s.methods||[],n=s.events||[],a=s.accounts||[],c=Oe(e)?[e]:s.chains?s.chains:index_es_U(s.accounts);t[e]={chains:c,methods:i,events:n,accounts:a}}return t}function universal_provider_dist_index_es_E(r){return typeof r=="number"?r:r.includes("0x")?parseInt(r,16):(r=r.includes(":")?r.split(":")[1]:r,isNaN(Number(r))?r:Number(r))}const universal_provider_dist_index_es_L={},universal_provider_dist_index_es_o=r=>universal_provider_dist_index_es_L[r],universal_provider_dist_index_es_b=(r,t)=>{universal_provider_dist_index_es_L[r]=t};class dist_index_es_ft{constructor(t){this.name="polkadot",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){this.httpProviders[t]||this.setHttpProvider(t,e),this.chainId=t,this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}getAccounts(){const t=this.namespace.accounts;return t?t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2])||[]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{var s;const i=universal_provider_dist_index_es_l(e);t[i]=this.createHttpProvider(i,(s=this.namespace.rpcMap)==null?void 0:s[e])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}var dist_index_es_Pt=Object.defineProperty,universal_provider_dist_index_es_gt=Object.defineProperties,dist_index_es_wt=Object.getOwnPropertyDescriptors,dist_index_es_F=Object.getOwnPropertySymbols,dist_index_es_Ct=Object.prototype.hasOwnProperty,dist_index_es_It=Object.prototype.propertyIsEnumerable,index_es_G=(r,t,e)=>t in r?dist_index_es_Pt(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,universal_provider_dist_index_es_M=(r,t)=>{for(var e in t||(t={}))dist_index_es_Ct.call(t,e)&&index_es_G(r,e,t[e]);if(dist_index_es_F)for(var e of dist_index_es_F(t))dist_index_es_It.call(t,e)&&index_es_G(r,e,t[e]);return r},universal_provider_dist_index_es_x=(r,t)=>universal_provider_dist_index_es_gt(r,dist_index_es_wt(t));class dist_index_es_Ht{constructor(t){this.name="eip155",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(t){switch(t.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(t);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(t);case"wallet_getCallsStatus":return await this.getCallStatus(t)}return this.namespace.methods.includes(t.request.method)?await this.client.request(t):this.getHttpProvider().request(t.request)}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}setDefaultChain(t,e){this.httpProviders[t]||this.setHttpProvider(parseInt(t),e),this.chainId=parseInt(t),this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(`${this.name}:${t}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{var s;const i=parseInt(universal_provider_dist_index_es_l(e));t[i]=this.createHttpProvider(i,(s=this.namespace.rpcMap)==null?void 0:s[e])}),t}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}getHttpProvider(){const t=this.chainId,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}async handleSwitchChain(t){var e,s;let i=t.request.params?(e=t.request.params[0])==null?void 0:e.chainId:"0x0";i=i.startsWith("0x")?i:`0x${i}`;const n=parseInt(i,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:t.topic,request:{method:t.request.method,params:[{chainId:i}]},chainId:(s=this.namespace.chains)==null?void 0:s[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(t){return this.namespace.chains.includes(`${this.name}:${t}`)}async getCapabilities(t){var e,s,i;const n=(s=(e=t.request)==null?void 0:e.params)==null?void 0:s[0];if(!n)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const a=this.client.session.get(t.topic),c=((i=a?.sessionProperties)==null?void 0:i.capabilities)||{};if(c!=null&&c[n])return c?.[n];const m=await this.client.request(t);try{await this.client.session.update(t.topic,{sessionProperties:universal_provider_dist_index_es_x(universal_provider_dist_index_es_M({},a.sessionProperties||{}),{capabilities:universal_provider_dist_index_es_x(universal_provider_dist_index_es_M({},c||{}),{[n]:m})})})}catch(I){console.warn("Failed to update session with capabilities",I)}return m}async getCallStatus(t){var e,s;const i=this.client.session.get(t.topic),n=(e=i.sessionProperties)==null?void 0:e.bundler_name;if(n){const c=this.getBundlerUrl(t.chainId,n);try{return await this.getUserOperationReceipt(c,t)}catch(m){console.warn("Failed to fetch call status from bundler",m,c)}}const a=(s=i.sessionProperties)==null?void 0:s.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,t)}catch(c){console.warn("Failed to fetch call status from custom bundler",c,a)}if(this.namespace.methods.includes(t.request.method))return await this.client.request(t);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(t,e){var s;const i=new URL(t),n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(formatJsonRpcRequest("eth_getUserOperationReceipt",[(s=e.request.params)==null?void 0:s[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(t,e){return`${dist_index_es_ot}?projectId=${this.client.core.projectId}&chainId=${t}&bundler=${e}`}}class dist_index_es_$t{constructor(t){this.name="solana",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){this.httpProviders[t]||this.setHttpProvider(t,e),this.chainId=t,this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{var s;const i=universal_provider_dist_index_es_l(e);t[i]=this.createHttpProvider(i,(s=this.namespace.rpcMap)==null?void 0:s[e])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}class dist_index_es_Et{constructor(t){this.name="cosmos",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){this.httpProviders[t]||this.setHttpProvider(t,e),this.chainId=t,this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{var s;const i=universal_provider_dist_index_es_l(e);t[i]=this.createHttpProvider(i,(s=this.namespace.rpcMap)==null?void 0:s[e])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}class dist_index_es_bt{constructor(t){this.name="algorand",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){if(!this.httpProviders[t]){const s=e||universal_provider_dist_index_es_h(`${this.name}:${t}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);this.setHttpProvider(t,s)}this.chainId=t,this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{var s;t[e]=this.createHttpProvider(e,(s=this.namespace.rpcMap)==null?void 0:s[e])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}class dist_index_es_At{constructor(t){this.name="cip34",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){this.httpProviders[t]||this.setHttpProvider(t,e),this.chainId=t,this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{const s=this.getCardanoRPCUrl(e),i=universal_provider_dist_index_es_l(e);t[i]=this.createHttpProvider(i,s)}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}getCardanoRPCUrl(t){const e=this.namespace.rpcMap;if(e)return e[t]}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||this.getCardanoRPCUrl(t);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}class dist_index_es_Nt{constructor(t){this.name="elrond",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){this.httpProviders[t]||this.setHttpProvider(t,e),this.chainId=t,this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{var s;const i=universal_provider_dist_index_es_l(e);t[i]=this.createHttpProvider(i,(s=this.namespace.rpcMap)==null?void 0:s[e])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}class universal_provider_dist_index_es_yt{constructor(t){this.name="multiversx",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){this.httpProviders[t]||this.setHttpProvider(t,e),this.chainId=t,this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{var s;const i=universal_provider_dist_index_es_l(e);t[i]=this.createHttpProvider(i,(s=this.namespace.rpcMap)==null?void 0:s[e])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}class dist_index_es_Ot{constructor(t){this.name="near",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){if(this.chainId=t,!this.httpProviders[t]){const s=e||universal_provider_dist_index_es_h(`${this.name}:${t}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);this.setHttpProvider(t,s)}this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const t=this.namespace.accounts;return t?t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2])||[]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{var s;t[e]=this.createHttpProvider(e,(s=this.namespace.rpcMap)==null?void 0:s[e])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace);return typeof s>"u"?void 0:new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}class dist_index_es_qt{constructor(t){this.name="tezos",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){if(this.chainId=t,!this.httpProviders[t]){const s=e||universal_provider_dist_index_es_h(`${this.name}:${t}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);this.setHttpProvider(t,s)}this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const t=this.namespace.accounts;return t?t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2])||[]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{t[e]=this.createHttpProvider(e)}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace);return typeof s>"u"?void 0:new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s))}}class dist_index_es_Dt{constructor(t){this.name=universal_provider_dist_index_es_f,this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(t.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(t.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(t.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(t.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider(t.chainId).request(t.request)}setDefaultChain(t,e){this.httpProviders[t]||this.setHttpProvider(t,e),this.chainId=t,this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){var t,e;const s={};return(e=(t=this.namespace)==null?void 0:t.accounts)==null||e.forEach(i=>{const n=re(i);s[`${n.namespace}:${n.reference}`]=this.createHttpProvider(i)}),s}getHttpProvider(t){const e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}var dist_index_es_St=Object.defineProperty,dist_index_es_t=Object.defineProperties,dist_index_es_jt=Object.getOwnPropertyDescriptors,dist_index_es_J=Object.getOwnPropertySymbols,dist_index_es_Rt=Object.prototype.hasOwnProperty,dist_index_es_Ut=Object.prototype.propertyIsEnumerable,universal_provider_dist_index_es_z=(r,t,e)=>t in r?dist_index_es_St(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,universal_provider_dist_index_es_w=(r,t)=>{for(var e in t||(t={}))dist_index_es_Rt.call(t,e)&&universal_provider_dist_index_es_z(r,e,t[e]);if(dist_index_es_J)for(var e of dist_index_es_J(t))dist_index_es_Ut.call(t,e)&&universal_provider_dist_index_es_z(r,e,t[e]);return r},dist_index_es_A=(r,t)=>dist_index_es_t(r,dist_index_es_jt(t));class universal_provider_dist_index_es_C{constructor(t){this.events=new (external_events_default()),this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=t,this.logger=typeof t?.logger<"u"&&typeof t?.logger!="string"?t.logger:pino_default()(logger_dist_index_es_k({level:t?.logger||universal_provider_dist_index_es_D})),this.disableProviderPing=t?.disableProviderPing||!1}static async init(t){const e=new universal_provider_dist_index_es_C(t);return await e.initialize(),e}async request(t,e,s){const[i,n]=this.validateChain(e);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(i).request({request:universal_provider_dist_index_es_w({},t),chainId:`${i}:${n}`,topic:this.session.topic,expiry:s})}sendAsync(t,e,s,i){const n=new Date().getTime();this.request(t,s,i).then(a=>e(null,formatJsonRpcResult(n,a))).catch(a=>e(a,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var t;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(t=this.session)==null?void 0:t.topic,reason:U("USER_DISCONNECTED")}),await this.cleanup()}async connect(t){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(t),await this.cleanupPendingPairings(),!t.skipPairing)return await this.pair(t.pairingTopic)}async authenticate(t,e){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(t),await this.cleanupPendingPairings();const{uri:s,response:i}=await this.client.authenticate(t,e);s&&(this.uri=s,this.events.emit("display_uri",s));const n=await i();if(this.session=n.session,this.session){const a=universal_provider_dist_index_es_k(this.session.namespaces);this.namespaces=dist_index_es_$(this.namespaces,a),this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(t,e){this.events.on(t,e)}once(t,e){this.events.once(t,e)}removeListener(t,e){this.events.removeListener(t,e)}off(t,e){this.events.off(t,e)}get isWalletConnect(){return!0}async pair(t){this.shouldAbortPairingAttempt=!1;let e=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(e>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:s,approval:i}=await this.client.connect({pairingTopic:t,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});s&&(this.uri=s,this.events.emit("display_uri",s)),await i().then(n=>{this.session=n;const a=universal_provider_dist_index_es_k(n.namespaces);this.namespaces=dist_index_es_$(this.namespaces,a),this.persist("namespaces",this.namespaces)}).catch(n=>{if(n.message!==index_es_it)throw n;e++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(t,e){try{if(!this.session)return;const[s,i]=this.validateChain(t),n=this.getProvider(s);n.name===universal_provider_dist_index_es_f?n.setDefaultChain(`${s}:${i}`,e):n.setDefaultChain(i,e)}catch(s){if(!/Please call connect/.test(s.message))throw s}}async cleanupPendingPairings(t={}){this.logger.info("Cleaning up inactive pairings...");const e=this.client.pairing.getAll();if(L(e)){for(const s of e)t.deletePairings?this.client.core.expirer.set(s.topic,0):await this.client.core.relayer.subscriber.unsubscribe(s.topic);this.logger.info(`Inactive pairings cleared: ${e.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const t=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[t]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await dist_index_es_e.init({core:this.providerOpts.core,logger:this.providerOpts.logger||universal_provider_dist_index_es_D,relayUrl:this.providerOpts.relayUrl||dist_index_es_rt,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const t=[...new Set(Object.keys(this.session.namespaces).map(e=>Dn(e)))];universal_provider_dist_index_es_b("client",this.client),universal_provider_dist_index_es_b("events",this.events),universal_provider_dist_index_es_b("disableProviderPing",this.disableProviderPing),t.forEach(e=>{if(!this.session)return;const s=dist_index_es_mt(e,this.session),i=index_es_U(s),n=dist_index_es_$(this.namespaces,this.optionalNamespaces),a=dist_index_es_A(universal_provider_dist_index_es_w({},n[e]),{accounts:s,chains:i});switch(e){case"eip155":this.rpcProviders[e]=new dist_index_es_Ht({namespace:a});break;case"algorand":this.rpcProviders[e]=new dist_index_es_bt({namespace:a});break;case"solana":this.rpcProviders[e]=new dist_index_es_$t({namespace:a});break;case"cosmos":this.rpcProviders[e]=new dist_index_es_Et({namespace:a});break;case"polkadot":this.rpcProviders[e]=new dist_index_es_ft({namespace:a});break;case"cip34":this.rpcProviders[e]=new dist_index_es_At({namespace:a});break;case"elrond":this.rpcProviders[e]=new dist_index_es_Nt({namespace:a});break;case"multiversx":this.rpcProviders[e]=new universal_provider_dist_index_es_yt({namespace:a});break;case"near":this.rpcProviders[e]=new dist_index_es_Ot({namespace:a});break;case"tezos":this.rpcProviders[e]=new dist_index_es_qt({namespace:a});break;default:this.rpcProviders[universal_provider_dist_index_es_f]?this.rpcProviders[universal_provider_dist_index_es_f].updateNamespace(a):this.rpcProviders[universal_provider_dist_index_es_f]=new dist_index_es_Dt({namespace:a})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",t=>{this.events.emit("session_ping",t)}),this.client.on("session_event",t=>{const{params:e}=t,{event:s}=e;if(s.name==="accountsChanged"){const i=s.data;i&&L(i)&&this.events.emit("accountsChanged",i.map(dist_index_es_vt))}else if(s.name==="chainChanged"){const i=e.chainId,n=e.event.data,a=Dn(i),c=universal_provider_dist_index_es_E(i)!==universal_provider_dist_index_es_E(n)?`${a}:${universal_provider_dist_index_es_E(n)}`:i;this.onChainChanged(c)}else this.events.emit(s.name,s.data);this.events.emit("session_event",t)}),this.client.on("session_update",({topic:t,params:e})=>{var s;const{namespaces:i}=e,n=(s=this.client)==null?void 0:s.session.get(t);this.session=dist_index_es_A(universal_provider_dist_index_es_w({},n),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:t,params:e})}),this.client.on("session_delete",async t=>{await this.cleanup(),this.events.emit("session_delete",t),this.events.emit("disconnect",dist_index_es_A(universal_provider_dist_index_es_w({},U("USER_DISCONNECTED")),{data:t.topic}))}),this.on(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,t=>{this.onChainChanged(t,!0)})}getProvider(t){return this.rpcProviders[t]||this.rpcProviders[universal_provider_dist_index_es_f]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(t=>{var e;this.getProvider(t).updateNamespace((e=this.session)==null?void 0:e.namespaces[t])})}setNamespaces(t){const{namespaces:e,optionalNamespaces:s,sessionProperties:i}=t;e&&Object.keys(e).length&&(this.namespaces=e),s&&Object.keys(s).length&&(this.optionalNamespaces=s),this.sessionProperties=i,this.persist("namespaces",e),this.persist("optionalNamespaces",s)}validateChain(t){const[e,s]=t?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[e,s];if(e&&!Object.keys(this.namespaces||{}).map(a=>Dn(a)).includes(e))throw new Error(`Namespace '${e}' is not configured. Please call connect() first with namespace config.`);if(e&&s)return[e,s];const i=Dn(Object.keys(this.namespaces)[0]),n=this.rpcProviders[i].getDefaultChain();return[i,n]}async requestAccounts(){const[t]=this.validateChain();return await this.getProvider(t).requestAccounts()}onChainChanged(t,e=!1){if(!this.namespaces)return;const[s,i]=this.validateChain(t);i&&(e||this.getProvider(s).setDefaultChain(i),this.namespaces[s]?this.namespaces[s].defaultChain=i:this.namespaces[`${s}:${i}`]?this.namespaces[`${s}:${i}`].defaultChain=i:this.namespaces[`${s}:${i}`]={defaultChain:i},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",i))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(t,e){this.client.core.storage.setItem(`${universal_provider_dist_index_es_S}/${t}`,e)}async getFromStore(t){return await this.client.core.storage.getItem(`${universal_provider_dist_index_es_S}/${t}`)}}const dist_index_es_Tt=universal_provider_dist_index_es_C;
+const universal_provider_dist_index_es_D="error",dist_index_es_rt="wss://relay.walletconnect.org",dist_index_es_nt="wc",dist_index_es_at="universal_provider",universal_provider_dist_index_es_S=`${dist_index_es_nt}@2:${dist_index_es_at}:`,universal_provider_dist_index_es_="https://rpc.walletconnect.org/v1/",universal_provider_dist_index_es_f="generic",dist_index_es_ot=`${universal_provider_dist_index_es_}bundler`,universal_provider_dist_index_es_p={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var dist_index_es_ct=Object.defineProperty,universal_provider_dist_index_es_ht=Object.defineProperties,universal_provider_dist_index_es_pt=Object.getOwnPropertyDescriptors,universal_provider_dist_index_es_j=Object.getOwnPropertySymbols,dist_index_es_dt=Object.prototype.hasOwnProperty,dist_index_es_ut=Object.prototype.propertyIsEnumerable,universal_provider_dist_index_es_R=(r,t,e)=>t in r?dist_index_es_ct(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,universal_provider_dist_index_es_g=(r,t)=>{for(var e in t||(t={}))dist_index_es_dt.call(t,e)&&universal_provider_dist_index_es_R(r,e,t[e]);if(universal_provider_dist_index_es_j)for(var e of universal_provider_dist_index_es_j(t))dist_index_es_ut.call(t,e)&&universal_provider_dist_index_es_R(r,e,t[e]);return r},dist_index_es_lt=(r,t)=>universal_provider_dist_index_es_ht(r,universal_provider_dist_index_es_pt(t));function universal_provider_dist_index_es_h(r,t,e){var s;const i=re(r);return((s=t.rpcMap)==null?void 0:s[i.reference])||`${universal_provider_dist_index_es_}?chainId=${i.namespace}:${i.reference}&projectId=${e}`}function universal_provider_dist_index_es_l(r){return r.includes(":")?r.split(":")[1]:r}function index_es_U(r){return r.map(t=>`${t.split(":")[0]}:${t.split(":")[1]}`)}function dist_index_es_mt(r,t){const e=Object.keys(t.namespaces).filter(i=>i.includes(r));if(!e.length)return[];const s=[];return e.forEach(i=>{const n=t.namespaces[i].accounts;s.push(...n)}),s}function dist_index_es_$(r={},t={}){const e=universal_provider_dist_index_es_T(r),s=universal_provider_dist_index_es_T(t);return (0,lodash.merge)(e,s)}function universal_provider_dist_index_es_T(r){var t,e,s,i;const n={};if(!Z(r))return n;for(const[a,c]of Object.entries(r)){const m=Oe(a)?[a]:c.chains,I=c.methods||[],V=c.events||[],B=c.rpcMap||{},v=Dn(a);n[v]=dist_index_es_lt(universal_provider_dist_index_es_g(universal_provider_dist_index_es_g({},n[v]),c),{chains:N(m,(t=n[v])==null?void 0:t.chains),methods:N(I,(e=n[v])==null?void 0:e.methods),events:N(V,(s=n[v])==null?void 0:s.events),rpcMap:universal_provider_dist_index_es_g(universal_provider_dist_index_es_g({},B),(i=n[v])==null?void 0:i.rpcMap)})}return n}function dist_index_es_vt(r){return r.includes(":")?r.split(":")[2]:r}function universal_provider_dist_index_es_k(r){const t={};for(const[e,s]of Object.entries(r)){const i=s.methods||[],n=s.events||[],a=s.accounts||[],c=Oe(e)?[e]:s.chains?s.chains:index_es_U(s.accounts);t[e]={chains:c,methods:i,events:n,accounts:a}}return t}function universal_provider_dist_index_es_E(r){return typeof r=="number"?r:r.includes("0x")?parseInt(r,16):(r=r.includes(":")?r.split(":")[1]:r,isNaN(Number(r))?r:Number(r))}const universal_provider_dist_index_es_L={},universal_provider_dist_index_es_o=r=>universal_provider_dist_index_es_L[r],universal_provider_dist_index_es_b=(r,t)=>{universal_provider_dist_index_es_L[r]=t};class dist_index_es_ft{constructor(t){this.name="polkadot",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){this.httpProviders[t]||this.setHttpProvider(t,e),this.chainId=t,this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}getAccounts(){const t=this.namespace.accounts;return t?t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2])||[]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{var s;const i=universal_provider_dist_index_es_l(e);t[i]=this.createHttpProvider(i,(s=this.namespace.rpcMap)==null?void 0:s[e])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}var dist_index_es_Pt=Object.defineProperty,universal_provider_dist_index_es_gt=Object.defineProperties,universal_provider_dist_index_es_wt=Object.getOwnPropertyDescriptors,index_es_F=Object.getOwnPropertySymbols,universal_provider_dist_index_es_Ct=Object.prototype.hasOwnProperty,dist_index_es_It=Object.prototype.propertyIsEnumerable,index_es_G=(r,t,e)=>t in r?dist_index_es_Pt(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,universal_provider_dist_index_es_M=(r,t)=>{for(var e in t||(t={}))universal_provider_dist_index_es_Ct.call(t,e)&&index_es_G(r,e,t[e]);if(index_es_F)for(var e of index_es_F(t))dist_index_es_It.call(t,e)&&index_es_G(r,e,t[e]);return r},universal_provider_dist_index_es_x=(r,t)=>universal_provider_dist_index_es_gt(r,universal_provider_dist_index_es_wt(t));class dist_index_es_Ht{constructor(t){this.name="eip155",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(t){switch(t.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(t);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(t);case"wallet_getCallsStatus":return await this.getCallStatus(t)}return this.namespace.methods.includes(t.request.method)?await this.client.request(t):this.getHttpProvider().request(t.request)}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}setDefaultChain(t,e){this.httpProviders[t]||this.setHttpProvider(parseInt(t),e),this.chainId=parseInt(t),this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(`${this.name}:${t}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{var s;const i=parseInt(universal_provider_dist_index_es_l(e));t[i]=this.createHttpProvider(i,(s=this.namespace.rpcMap)==null?void 0:s[e])}),t}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}getHttpProvider(){const t=this.chainId,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}async handleSwitchChain(t){var e,s;let i=t.request.params?(e=t.request.params[0])==null?void 0:e.chainId:"0x0";i=i.startsWith("0x")?i:`0x${i}`;const n=parseInt(i,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:t.topic,request:{method:t.request.method,params:[{chainId:i}]},chainId:(s=this.namespace.chains)==null?void 0:s[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(t){return this.namespace.chains.includes(`${this.name}:${t}`)}async getCapabilities(t){var e,s,i;const n=(s=(e=t.request)==null?void 0:e.params)==null?void 0:s[0];if(!n)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const a=this.client.session.get(t.topic),c=((i=a?.sessionProperties)==null?void 0:i.capabilities)||{};if(c!=null&&c[n])return c?.[n];const m=await this.client.request(t);try{await this.client.session.update(t.topic,{sessionProperties:universal_provider_dist_index_es_x(universal_provider_dist_index_es_M({},a.sessionProperties||{}),{capabilities:universal_provider_dist_index_es_x(universal_provider_dist_index_es_M({},c||{}),{[n]:m})})})}catch(I){console.warn("Failed to update session with capabilities",I)}return m}async getCallStatus(t){var e,s;const i=this.client.session.get(t.topic),n=(e=i.sessionProperties)==null?void 0:e.bundler_name;if(n){const c=this.getBundlerUrl(t.chainId,n);try{return await this.getUserOperationReceipt(c,t)}catch(m){console.warn("Failed to fetch call status from bundler",m,c)}}const a=(s=i.sessionProperties)==null?void 0:s.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,t)}catch(c){console.warn("Failed to fetch call status from custom bundler",c,a)}if(this.namespace.methods.includes(t.request.method))return await this.client.request(t);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(t,e){var s;const i=new URL(t),n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(formatJsonRpcRequest("eth_getUserOperationReceipt",[(s=e.request.params)==null?void 0:s[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(t,e){return`${dist_index_es_ot}?projectId=${this.client.core.projectId}&chainId=${t}&bundler=${e}`}}class dist_index_es_$t{constructor(t){this.name="solana",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){this.httpProviders[t]||this.setHttpProvider(t,e),this.chainId=t,this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{var s;const i=universal_provider_dist_index_es_l(e);t[i]=this.createHttpProvider(i,(s=this.namespace.rpcMap)==null?void 0:s[e])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}class dist_index_es_Et{constructor(t){this.name="cosmos",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){this.httpProviders[t]||this.setHttpProvider(t,e),this.chainId=t,this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{var s;const i=universal_provider_dist_index_es_l(e);t[i]=this.createHttpProvider(i,(s=this.namespace.rpcMap)==null?void 0:s[e])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}class dist_index_es_bt{constructor(t){this.name="algorand",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){if(!this.httpProviders[t]){const s=e||universal_provider_dist_index_es_h(`${this.name}:${t}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);this.setHttpProvider(t,s)}this.chainId=t,this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{var s;t[e]=this.createHttpProvider(e,(s=this.namespace.rpcMap)==null?void 0:s[e])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}class dist_index_es_At{constructor(t){this.name="cip34",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){this.httpProviders[t]||this.setHttpProvider(t,e),this.chainId=t,this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{const s=this.getCardanoRPCUrl(e),i=universal_provider_dist_index_es_l(e);t[i]=this.createHttpProvider(i,s)}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}getCardanoRPCUrl(t){const e=this.namespace.rpcMap;if(e)return e[t]}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||this.getCardanoRPCUrl(t);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}class dist_index_es_Nt{constructor(t){this.name="elrond",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){this.httpProviders[t]||this.setHttpProvider(t,e),this.chainId=t,this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{var s;const i=universal_provider_dist_index_es_l(e);t[i]=this.createHttpProvider(i,(s=this.namespace.rpcMap)==null?void 0:s[e])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}class universal_provider_dist_index_es_yt{constructor(t){this.name="multiversx",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){this.httpProviders[t]||this.setHttpProvider(t,e),this.chainId=t,this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{var s;const i=universal_provider_dist_index_es_l(e);t[i]=this.createHttpProvider(i,(s=this.namespace.rpcMap)==null?void 0:s[e])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}class dist_index_es_Ot{constructor(t){this.name="near",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){if(this.chainId=t,!this.httpProviders[t]){const s=e||universal_provider_dist_index_es_h(`${this.name}:${t}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);this.setHttpProvider(t,s)}this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const t=this.namespace.accounts;return t?t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2])||[]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{var s;t[e]=this.createHttpProvider(e,(s=this.namespace.rpcMap)==null?void 0:s[e])}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace);return typeof s>"u"?void 0:new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}class dist_index_es_qt{constructor(t){this.name="tezos",this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider().request(t.request)}setDefaultChain(t,e){if(this.chainId=t,!this.httpProviders[t]){const s=e||universal_provider_dist_index_es_h(`${this.name}:${t}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);this.setHttpProvider(t,s)}this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const t=this.namespace.accounts;return t?t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2])||[]:[]}createHttpProviders(){const t={};return this.namespace.chains.forEach(e=>{t[e]=this.createHttpProvider(e)}),t}getHttpProvider(){const t=`${this.name}:${this.chainId}`,e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace);return typeof s>"u"?void 0:new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s))}}class dist_index_es_Dt{constructor(t){this.name=universal_provider_dist_index_es_f,this.namespace=t.namespace,this.events=universal_provider_dist_index_es_o("events"),this.client=universal_provider_dist_index_es_o("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(t.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(t.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(t.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(t.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider(t.chainId).request(t.request)}setDefaultChain(t,e){this.httpProviders[t]||this.setHttpProvider(t,e),this.chainId=t,this.events.emit(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,`${this.name}:${t}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getAccounts(){const t=this.namespace.accounts;return t?[...new Set(t.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){var t,e;const s={};return(e=(t=this.namespace)==null?void 0:t.accounts)==null||e.forEach(i=>{const n=re(i);s[`${n.namespace}:${n.reference}`]=this.createHttpProvider(i)}),s}getHttpProvider(t){const e=this.httpProviders[t];if(typeof e>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return e}setHttpProvider(t,e){const s=this.createHttpProvider(t,e);s&&(this.httpProviders[t]=s)}createHttpProvider(t,e){const s=e||universal_provider_dist_index_es_h(t,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${t}`);return new dist_index_es_o(new jsonrpc_http_connection_dist_index_es_f(s,universal_provider_dist_index_es_o("disableProviderPing")))}}var dist_index_es_St=Object.defineProperty,dist_index_es_t=Object.defineProperties,dist_index_es_jt=Object.getOwnPropertyDescriptors,dist_index_es_J=Object.getOwnPropertySymbols,dist_index_es_Rt=Object.prototype.hasOwnProperty,dist_index_es_Ut=Object.prototype.propertyIsEnumerable,universal_provider_dist_index_es_z=(r,t,e)=>t in r?dist_index_es_St(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,universal_provider_dist_index_es_w=(r,t)=>{for(var e in t||(t={}))dist_index_es_Rt.call(t,e)&&universal_provider_dist_index_es_z(r,e,t[e]);if(dist_index_es_J)for(var e of dist_index_es_J(t))dist_index_es_Ut.call(t,e)&&universal_provider_dist_index_es_z(r,e,t[e]);return r},universal_provider_dist_index_es_A=(r,t)=>dist_index_es_t(r,dist_index_es_jt(t));class universal_provider_dist_index_es_C{constructor(t){this.events=new (external_events_default()),this.rpcProviders={},this.shouldAbortPairingAttempt=!1,this.maxPairingAttempts=10,this.disableProviderPing=!1,this.providerOpts=t,this.logger=typeof t?.logger<"u"&&typeof t?.logger!="string"?t.logger:pino_default()(logger_dist_index_es_k({level:t?.logger||universal_provider_dist_index_es_D})),this.disableProviderPing=t?.disableProviderPing||!1}static async init(t){const e=new universal_provider_dist_index_es_C(t);return await e.initialize(),e}async request(t,e,s){const[i,n]=this.validateChain(e);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(i).request({request:universal_provider_dist_index_es_w({},t),chainId:`${i}:${n}`,topic:this.session.topic,expiry:s})}sendAsync(t,e,s,i){const n=new Date().getTime();this.request(t,s,i).then(a=>e(null,formatJsonRpcResult(n,a))).catch(a=>e(a,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties}),await this.requestAccounts()}async disconnect(){var t;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(t=this.session)==null?void 0:t.topic,reason:index_es_("USER_DISCONNECTED")}),await this.cleanup()}async connect(t){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(t),await this.cleanupPendingPairings(),!t.skipPairing)return await this.pair(t.pairingTopic)}async authenticate(t,e){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(t),await this.cleanupPendingPairings();const{uri:s,response:i}=await this.client.authenticate(t,e);s&&(this.uri=s,this.events.emit("display_uri",s));const n=await i();if(this.session=n.session,this.session){const a=universal_provider_dist_index_es_k(this.session.namespaces);this.namespaces=dist_index_es_$(this.namespaces,a),this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(t,e){this.events.on(t,e)}once(t,e){this.events.once(t,e)}removeListener(t,e){this.events.removeListener(t,e)}off(t,e){this.events.off(t,e)}get isWalletConnect(){return!0}async pair(t){this.shouldAbortPairingAttempt=!1;let e=0;do{if(this.shouldAbortPairingAttempt)throw new Error("Pairing aborted");if(e>=this.maxPairingAttempts)throw new Error("Max auto pairing attempts reached");const{uri:s,approval:i}=await this.client.connect({pairingTopic:t,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});s&&(this.uri=s,this.events.emit("display_uri",s)),await i().then(n=>{this.session=n;const a=universal_provider_dist_index_es_k(n.namespaces);this.namespaces=dist_index_es_$(this.namespaces,a),this.persist("namespaces",this.namespaces)}).catch(n=>{if(n.message!==index_es_rt)throw n;e++})}while(!this.session);return this.onConnect(),this.session}setDefaultChain(t,e){try{if(!this.session)return;const[s,i]=this.validateChain(t),n=this.getProvider(s);n.name===universal_provider_dist_index_es_f?n.setDefaultChain(`${s}:${i}`,e):n.setDefaultChain(i,e)}catch(s){if(!/Please call connect/.test(s.message))throw s}}async cleanupPendingPairings(t={}){this.logger.info("Cleaning up inactive pairings...");const e=this.client.pairing.getAll();if(L(e)){for(const s of e)t.deletePairings?this.client.core.expirer.set(s.topic,0):await this.client.core.relayer.subscriber.unsubscribe(s.topic);this.logger.info(`Inactive pairings cleared: ${e.length}`)}}abortPairingAttempt(){this.shouldAbortPairingAttempt=!0}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const t=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[t]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await dist_index_es_e.init({core:this.providerOpts.core,logger:this.providerOpts.logger||universal_provider_dist_index_es_D,relayUrl:this.providerOpts.relayUrl||dist_index_es_rt,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const t=[...new Set(Object.keys(this.session.namespaces).map(e=>Dn(e)))];universal_provider_dist_index_es_b("client",this.client),universal_provider_dist_index_es_b("events",this.events),universal_provider_dist_index_es_b("disableProviderPing",this.disableProviderPing),t.forEach(e=>{if(!this.session)return;const s=dist_index_es_mt(e,this.session),i=index_es_U(s),n=dist_index_es_$(this.namespaces,this.optionalNamespaces),a=universal_provider_dist_index_es_A(universal_provider_dist_index_es_w({},n[e]),{accounts:s,chains:i});switch(e){case"eip155":this.rpcProviders[e]=new dist_index_es_Ht({namespace:a});break;case"algorand":this.rpcProviders[e]=new dist_index_es_bt({namespace:a});break;case"solana":this.rpcProviders[e]=new dist_index_es_$t({namespace:a});break;case"cosmos":this.rpcProviders[e]=new dist_index_es_Et({namespace:a});break;case"polkadot":this.rpcProviders[e]=new dist_index_es_ft({namespace:a});break;case"cip34":this.rpcProviders[e]=new dist_index_es_At({namespace:a});break;case"elrond":this.rpcProviders[e]=new dist_index_es_Nt({namespace:a});break;case"multiversx":this.rpcProviders[e]=new universal_provider_dist_index_es_yt({namespace:a});break;case"near":this.rpcProviders[e]=new dist_index_es_Ot({namespace:a});break;case"tezos":this.rpcProviders[e]=new dist_index_es_qt({namespace:a});break;default:this.rpcProviders[universal_provider_dist_index_es_f]?this.rpcProviders[universal_provider_dist_index_es_f].updateNamespace(a):this.rpcProviders[universal_provider_dist_index_es_f]=new dist_index_es_Dt({namespace:a})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",t=>{this.events.emit("session_ping",t)}),this.client.on("session_event",t=>{const{params:e}=t,{event:s}=e;if(s.name==="accountsChanged"){const i=s.data;i&&L(i)&&this.events.emit("accountsChanged",i.map(dist_index_es_vt))}else if(s.name==="chainChanged"){const i=e.chainId,n=e.event.data,a=Dn(i),c=universal_provider_dist_index_es_E(i)!==universal_provider_dist_index_es_E(n)?`${a}:${universal_provider_dist_index_es_E(n)}`:i;this.onChainChanged(c)}else this.events.emit(s.name,s.data);this.events.emit("session_event",t)}),this.client.on("session_update",({topic:t,params:e})=>{var s;const{namespaces:i}=e,n=(s=this.client)==null?void 0:s.session.get(t);this.session=universal_provider_dist_index_es_A(universal_provider_dist_index_es_w({},n),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:t,params:e})}),this.client.on("session_delete",async t=>{await this.cleanup(),this.events.emit("session_delete",t),this.events.emit("disconnect",universal_provider_dist_index_es_A(universal_provider_dist_index_es_w({},index_es_("USER_DISCONNECTED")),{data:t.topic}))}),this.on(universal_provider_dist_index_es_p.DEFAULT_CHAIN_CHANGED,t=>{this.onChainChanged(t,!0)})}getProvider(t){return this.rpcProviders[t]||this.rpcProviders[universal_provider_dist_index_es_f]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(t=>{var e;this.getProvider(t).updateNamespace((e=this.session)==null?void 0:e.namespaces[t])})}setNamespaces(t){const{namespaces:e,optionalNamespaces:s,sessionProperties:i}=t;e&&Object.keys(e).length&&(this.namespaces=e),s&&Object.keys(s).length&&(this.optionalNamespaces=s),this.sessionProperties=i,this.persist("namespaces",e),this.persist("optionalNamespaces",s)}validateChain(t){const[e,s]=t?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[e,s];if(e&&!Object.keys(this.namespaces||{}).map(a=>Dn(a)).includes(e))throw new Error(`Namespace '${e}' is not configured. Please call connect() first with namespace config.`);if(e&&s)return[e,s];const i=Dn(Object.keys(this.namespaces)[0]),n=this.rpcProviders[i].getDefaultChain();return[i,n]}async requestAccounts(){const[t]=this.validateChain();return await this.getProvider(t).requestAccounts()}onChainChanged(t,e=!1){if(!this.namespaces)return;const[s,i]=this.validateChain(t);i&&(e||this.getProvider(s).setDefaultChain(i),this.namespaces[s]?this.namespaces[s].defaultChain=i:this.namespaces[`${s}:${i}`]?this.namespaces[`${s}:${i}`].defaultChain=i:this.namespaces[`${s}:${i}`]={defaultChain:i},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",i))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(t,e){this.client.core.storage.setItem(`${universal_provider_dist_index_es_S}/${t}`,e)}async getFromStore(t){return await this.client.core.storage.getItem(`${universal_provider_dist_index_es_S}/${t}`)}}const dist_index_es_Tt=universal_provider_dist_index_es_C;
//# sourceMappingURL=index.es.js.map
;// ./node_modules/@walletconnect/ethereum-provider/dist/index.es.js
-const ethereum_provider_dist_index_es_R="wc",ethereum_provider_dist_index_es_T="ethereum_provider",ethereum_provider_dist_index_es_$=`${ethereum_provider_dist_index_es_R}@2:${ethereum_provider_dist_index_es_T}:`,ethereum_provider_dist_index_es_j="https://rpc.walletconnect.org/v1/",dist_index_es_u=["eth_sendTransaction","personal_sign"],ethereum_provider_dist_index_es_y=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],ethereum_provider_dist_index_es_g=["chainChanged","accountsChanged"],ethereum_provider_dist_index_es_b=["chainChanged","accountsChanged","message","disconnect","connect"];var index_es_q=Object.defineProperty,dist_index_es_N=Object.defineProperties,ethereum_provider_dist_index_es_D=Object.getOwnPropertyDescriptors,ethereum_provider_dist_index_es_M=Object.getOwnPropertySymbols,dist_index_es_U=Object.prototype.hasOwnProperty,index_es_Q=Object.prototype.propertyIsEnumerable,ethereum_provider_dist_index_es_O=(r,t,s)=>t in r?index_es_q(r,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[t]=s,ethereum_provider_dist_index_es_p=(r,t)=>{for(var s in t||(t={}))dist_index_es_U.call(t,s)&ðereum_provider_dist_index_es_O(r,s,t[s]);if(ethereum_provider_dist_index_es_M)for(var s of ethereum_provider_dist_index_es_M(t))index_es_Q.call(t,s)&ðereum_provider_dist_index_es_O(r,s,t[s]);return r},ethereum_provider_dist_index_es_E=(r,t)=>dist_index_es_N(r,ethereum_provider_dist_index_es_D(t));function ethereum_provider_dist_index_es_m(r){return Number(r[0].split(":")[1])}function ethereum_provider_dist_index_es_v(r){return`0x${r.toString(16)}`}function ethereum_provider_dist_index_es_L(r){const{chains:t,optionalChains:s,methods:i,optionalMethods:e,events:n,optionalEvents:o,rpcMap:c}=r;if(!L(t))throw new Error("Invalid chains");const a={chains:t,methods:i||dist_index_es_u,events:n||ethereum_provider_dist_index_es_g,rpcMap:ethereum_provider_dist_index_es_p({},t.length?{[ethereum_provider_dist_index_es_m(t)]:c[ethereum_provider_dist_index_es_m(t)]}:{})},h=n?.filter(l=>!ethereum_provider_dist_index_es_g.includes(l)),d=i?.filter(l=>!dist_index_es_u.includes(l));if(!s&&!o&&!e&&!(h!=null&&h.length)&&!(d!=null&&d.length))return{required:t.length?a:void 0};const w=h?.length&&d?.length||!s,I={chains:[...new Set(w?a.chains.concat(s||[]):s)],methods:[...new Set(a.methods.concat(e!=null&&e.length?e:ethereum_provider_dist_index_es_y))],events:[...new Set(a.events.concat(o!=null&&o.length?o:ethereum_provider_dist_index_es_b))],rpcMap:c};return{required:t.length?a:void 0,optional:s.length?I:void 0}}class ethereum_provider_dist_index_es_C{constructor(){this.events=new external_events_.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=ethereum_provider_dist_index_es_$,this.on=(t,s)=>(this.events.on(t,s),this),this.once=(t,s)=>(this.events.once(t,s),this),this.removeListener=(t,s)=>(this.events.removeListener(t,s),this),this.off=(t,s)=>(this.events.off(t,s),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){const s=new ethereum_provider_dist_index_es_C;return await s.initialize(t),s}async request(t,s){return await this.signer.request(t,this.formatChainId(this.chainId),s)}sendAsync(t,s,i){this.signer.sendAsync(t,s,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:s,optional:i}=ethereum_provider_dist_index_es_L(this.rpc);try{const e=await new Promise(async(o,c)=>{var a;this.rpc.showQrModal&&((a=this.modal)==null||a.subscribeModal(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(ethereum_provider_dist_index_es_E(ethereum_provider_dist_index_es_p({namespaces:ethereum_provider_dist_index_es_p({},s&&{[this.namespace]:s})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:t?.pairingTopic})).then(h=>{o(h)}).catch(h=>{c(new Error(h.message))})});if(!e)return;const n=mt(e.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:n),this.setAccounts(n),this.events.emit("connect",{chainId:ethereum_provider_dist_index_es_v(this.chainId)})}catch(e){throw this.signer.logger.error(e),e}finally{this.modal&&this.modal.closeModal()}}async authenticate(t,s){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:t?.chains});try{const i=await new Promise(async(n,o)=>{var c;this.rpc.showQrModal&&((c=this.modal)==null||c.subscribeModal(a=>{!a.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),o(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(ethereum_provider_dist_index_es_E(ethereum_provider_dist_index_es_p({},t),{chains:this.rpc.chains}),s).then(a=>{n(a)}).catch(a=>{o(new Error(a.message))})}),e=i.session;if(e){const n=mt(e.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:n),this.setAccounts(n),this.events.emit("connect",{chainId:ethereum_provider_dist_index_es_v(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{const{params:s}=t,{event:i}=s;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",t)}),this.signer.on("chainChanged",t=>{const s=parseInt(t);this.chainId=s,this.events.emit("chainChanged",ethereum_provider_dist_index_es_v(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",ethereum_provider_dist_index_es_E(ethereum_provider_dist_index_es_p({},U("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{var s,i;this.rpc.showQrModal&&((s=this.modal)==null||s.closeModal(),(i=this.modal)==null||i.openModal({uri:t})),this.events.emit("display_uri",t)})}switchEthereumChain(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const s=t.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));s.length&&(this.chainId=s[0],this.events.emit("chainChanged",ethereum_provider_dist_index_es_v(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const s=this.parseChainId(t);this.chainId=s,this.switchEthereumChain(s)}}parseAccountId(t){const[s,i,e]=t.split(":");return{chainId:`${s}:${i}`,address:e}}setAccounts(t){this.accounts=t.filter(s=>this.parseChainId(this.parseAccountId(s).chainId)===this.chainId).map(s=>this.parseAccountId(s).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var s,i;const e=(s=t?.chains)!=null?s:[],n=(i=t?.optionalChains)!=null?i:[],o=e.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const c=e.length?t?.methods||dist_index_es_u:[],a=e.length?t?.events||ethereum_provider_dist_index_es_g:[],h=t?.optionalMethods||[],d=t?.optionalEvents||[],w=t?.rpcMap||this.buildRpcMap(o,t.projectId),I=t?.qrModalOptions||void 0;return{chains:e?.map(l=>this.formatChainId(l)),optionalChains:n.map(l=>this.formatChainId(l)),methods:c,events:a,optionalMethods:h,optionalEvents:d,rpcMap:w,showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:I,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,s){const i={};return t.forEach(e=>{i[e]=this.getRpcUrl(e,s)}),i}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=this.rpc.chains.length?ethereum_provider_dist_index_es_m(this.rpc.chains):ethereum_provider_dist_index_es_m(this.rpc.optionalChains),this.signer=await dist_index_es_Tt.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing,relayUrl:t.relayUrl,storageOptions:t.storageOptions,customStoragePrefix:t.customStoragePrefix,telemetryEnabled:t.telemetryEnabled}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let s;try{const{WalletConnectModal:i}=await __webpack_require__.e(/* import() */ 940).then(__webpack_require__.bind(__webpack_require__, 380940));s=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(s)try{this.modal=new s(ethereum_provider_dist_index_es_p({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:s,optionalChains:i,rpcMap:e}=t;s&&L(s)&&(this.rpc.chains=s.map(n=>this.formatChainId(n)),s.forEach(n=>{this.rpc.rpcMap[n]=e?.[n]||this.getRpcUrl(n)})),i&&L(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=e?.[n]||this.getRpcUrl(n)}))}getRpcUrl(t,s){var i;return((i=this.rpc.rpcMap)==null?void 0:i[t])||`${ethereum_provider_dist_index_es_j}?chainId=eip155:${t}&projectId=${s||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),s=this.session.namespaces[`${this.namespace}:${t}`]?this.session.namespaces[`${this.namespace}:${t}`]:this.session.namespaces[this.namespace];this.setChainIds(t?[this.formatChainId(t)]:s?.accounts),this.setAccounts(s?.accounts)}catch(t){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(t),await this.disconnect().catch(s=>this.signer.logger.warn(s))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(s=>this.parseAccount(s))}}const ethereum_provider_dist_index_es_x=(/* unused pure expression or super */ null && (ethereum_provider_dist_index_es_C));
+const ethereum_provider_dist_index_es_R="wc",ethereum_provider_dist_index_es_T="ethereum_provider",ethereum_provider_dist_index_es_$=`${ethereum_provider_dist_index_es_R}@2:${ethereum_provider_dist_index_es_T}:`,ethereum_provider_dist_index_es_j="https://rpc.walletconnect.org/v1/",ethereum_provider_dist_index_es_g=["eth_sendTransaction","personal_sign"],ethereum_provider_dist_index_es_y=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],dist_index_es_u=["chainChanged","accountsChanged"],ethereum_provider_dist_index_es_b=["chainChanged","accountsChanged","message","disconnect","connect"];var index_es_q=Object.defineProperty,dist_index_es_N=Object.defineProperties,ethereum_provider_dist_index_es_D=Object.getOwnPropertyDescriptors,ethereum_provider_dist_index_es_M=Object.getOwnPropertySymbols,dist_index_es_U=Object.prototype.hasOwnProperty,dist_index_es_Q=Object.prototype.propertyIsEnumerable,ethereum_provider_dist_index_es_O=(r,t,s)=>t in r?index_es_q(r,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[t]=s,ethereum_provider_dist_index_es_p=(r,t)=>{for(var s in t||(t={}))dist_index_es_U.call(t,s)&ðereum_provider_dist_index_es_O(r,s,t[s]);if(ethereum_provider_dist_index_es_M)for(var s of ethereum_provider_dist_index_es_M(t))dist_index_es_Q.call(t,s)&ðereum_provider_dist_index_es_O(r,s,t[s]);return r},ethereum_provider_dist_index_es_E=(r,t)=>dist_index_es_N(r,ethereum_provider_dist_index_es_D(t));function ethereum_provider_dist_index_es_m(r){return Number(r[0].split(":")[1])}function ethereum_provider_dist_index_es_v(r){return`0x${r.toString(16)}`}function ethereum_provider_dist_index_es_L(r){const{chains:t,optionalChains:s,methods:i,optionalMethods:e,events:n,optionalEvents:o,rpcMap:c}=r;if(!L(t))throw new Error("Invalid chains");const a={chains:t,methods:i||ethereum_provider_dist_index_es_g,events:n||dist_index_es_u,rpcMap:ethereum_provider_dist_index_es_p({},t.length?{[ethereum_provider_dist_index_es_m(t)]:c[ethereum_provider_dist_index_es_m(t)]}:{})},h=n?.filter(l=>!dist_index_es_u.includes(l)),d=i?.filter(l=>!ethereum_provider_dist_index_es_g.includes(l));if(!s&&!o&&!e&&!(h!=null&&h.length)&&!(d!=null&&d.length))return{required:t.length?a:void 0};const w=h?.length&&d?.length||!s,I={chains:[...new Set(w?a.chains.concat(s||[]):s)],methods:[...new Set(a.methods.concat(e!=null&&e.length?e:ethereum_provider_dist_index_es_y))],events:[...new Set(a.events.concat(o!=null&&o.length?o:ethereum_provider_dist_index_es_b))],rpcMap:c};return{required:t.length?a:void 0,optional:s.length?I:void 0}}class ethereum_provider_dist_index_es_C{constructor(){this.events=new external_events_.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=ethereum_provider_dist_index_es_$,this.on=(t,s)=>(this.events.on(t,s),this),this.once=(t,s)=>(this.events.once(t,s),this),this.removeListener=(t,s)=>(this.events.removeListener(t,s),this),this.off=(t,s)=>(this.events.off(t,s),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){const s=new ethereum_provider_dist_index_es_C;return await s.initialize(t),s}async request(t,s){return await this.signer.request(t,this.formatChainId(this.chainId),s)}sendAsync(t,s,i){this.signer.sendAsync(t,s,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:s,optional:i}=ethereum_provider_dist_index_es_L(this.rpc);try{const e=await new Promise(async(o,c)=>{var a;this.rpc.showQrModal&&((a=this.modal)==null||a.subscribeModal(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))})),await this.signer.connect(ethereum_provider_dist_index_es_E(ethereum_provider_dist_index_es_p({namespaces:ethereum_provider_dist_index_es_p({},s&&{[this.namespace]:s})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:t?.pairingTopic})).then(h=>{o(h)}).catch(h=>{c(new Error(h.message))})});if(!e)return;const n=mt(e.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:n),this.setAccounts(n),this.events.emit("connect",{chainId:ethereum_provider_dist_index_es_v(this.chainId)})}catch(e){throw this.signer.logger.error(e),e}finally{this.modal&&this.modal.closeModal()}}async authenticate(t,s){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:t?.chains});try{const i=await new Promise(async(n,o)=>{var c;this.rpc.showQrModal&&((c=this.modal)==null||c.subscribeModal(a=>{!a.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),o(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(ethereum_provider_dist_index_es_E(ethereum_provider_dist_index_es_p({},t),{chains:this.rpc.chains}),s).then(a=>{n(a)}).catch(a=>{o(new Error(a.message))})}),e=i.session;if(e){const n=mt(e.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:n),this.setAccounts(n),this.events.emit("connect",{chainId:ethereum_provider_dist_index_es_v(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{const{params:s}=t,{event:i}=s;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",t)}),this.signer.on("chainChanged",t=>{const s=parseInt(t);this.chainId=s,this.events.emit("chainChanged",ethereum_provider_dist_index_es_v(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",ethereum_provider_dist_index_es_E(ethereum_provider_dist_index_es_p({},index_es_("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{var s,i;this.rpc.showQrModal&&((s=this.modal)==null||s.closeModal(),(i=this.modal)==null||i.openModal({uri:t})),this.events.emit("display_uri",t)})}switchEthereumChain(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const s=t.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));s.length&&(this.chainId=s[0],this.events.emit("chainChanged",ethereum_provider_dist_index_es_v(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const s=this.parseChainId(t);this.chainId=s,this.switchEthereumChain(s)}}parseAccountId(t){const[s,i,e]=t.split(":");return{chainId:`${s}:${i}`,address:e}}setAccounts(t){this.accounts=t.filter(s=>this.parseChainId(this.parseAccountId(s).chainId)===this.chainId).map(s=>this.parseAccountId(s).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var s,i;const e=(s=t?.chains)!=null?s:[],n=(i=t?.optionalChains)!=null?i:[],o=e.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const c=e.length?t?.methods||ethereum_provider_dist_index_es_g:[],a=e.length?t?.events||dist_index_es_u:[],h=t?.optionalMethods||[],d=t?.optionalEvents||[],w=t?.rpcMap||this.buildRpcMap(o,t.projectId),I=t?.qrModalOptions||void 0;return{chains:e?.map(l=>this.formatChainId(l)),optionalChains:n.map(l=>this.formatChainId(l)),methods:c,events:a,optionalMethods:h,optionalEvents:d,rpcMap:w,showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:I,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,s){const i={};return t.forEach(e=>{i[e]=this.getRpcUrl(e,s)}),i}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=this.rpc.chains.length?ethereum_provider_dist_index_es_m(this.rpc.chains):ethereum_provider_dist_index_es_m(this.rpc.optionalChains),this.signer=await dist_index_es_Tt.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing,relayUrl:t.relayUrl,storageOptions:t.storageOptions,customStoragePrefix:t.customStoragePrefix,telemetryEnabled:t.telemetryEnabled,logger:t.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let s;try{const{WalletConnectModal:i}=await __webpack_require__.e(/* import() */ 940).then(__webpack_require__.bind(__webpack_require__, 380940));s=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(s)try{this.modal=new s(ethereum_provider_dist_index_es_p({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:s,optionalChains:i,rpcMap:e}=t;s&&L(s)&&(this.rpc.chains=s.map(n=>this.formatChainId(n)),s.forEach(n=>{this.rpc.rpcMap[n]=e?.[n]||this.getRpcUrl(n)})),i&&L(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=e?.[n]||this.getRpcUrl(n)}))}getRpcUrl(t,s){var i;return((i=this.rpc.rpcMap)==null?void 0:i[t])||`${ethereum_provider_dist_index_es_j}?chainId=eip155:${t}&projectId=${s||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),s=this.session.namespaces[`${this.namespace}:${t}`]?this.session.namespaces[`${this.namespace}:${t}`]:this.session.namespaces[this.namespace];this.setChainIds(t?[this.formatChainId(t)]:s?.accounts),this.setAccounts(s?.accounts)}catch(t){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(t),await this.disconnect().catch(s=>this.signer.logger.warn(s))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(s=>this.parseAccount(s))}}const ethereum_provider_dist_index_es_x=(/* unused pure expression or super */ null && (ethereum_provider_dist_index_es_C));
//# sourceMappingURL=index.es.js.map
@@ -11427,4030 +11427,6 @@ function __classPrivateFieldSet(receiver, privateMap, value) {
}
-/***/ }),
-
-/***/ 194112:
-/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
-
-"use strict";
-
-
-var elliptic = exports;
-
-elliptic.version = (__webpack_require__(417559)/* .version */ .rE);
-elliptic.utils = __webpack_require__(938402);
-elliptic.rand = __webpack_require__(415037);
-elliptic.curve = __webpack_require__(777867);
-elliptic.curves = __webpack_require__(727483);
-
-// Protocols
-elliptic.ec = __webpack_require__(252040);
-elliptic.eddsa = __webpack_require__(636983);
-
-
-/***/ }),
-
-/***/ 774278:
-/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
-
-"use strict";
-
-
-var BN = __webpack_require__(439404);
-var utils = __webpack_require__(938402);
-var getNAF = utils.getNAF;
-var getJSF = utils.getJSF;
-var assert = utils.assert;
-
-function BaseCurve(type, conf) {
- this.type = type;
- this.p = new BN(conf.p, 16);
-
- // Use Montgomery, when there is no fast reduction for the prime
- this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
-
- // Useful for many curves
- this.zero = new BN(0).toRed(this.red);
- this.one = new BN(1).toRed(this.red);
- this.two = new BN(2).toRed(this.red);
-
- // Curve configuration, optional
- this.n = conf.n && new BN(conf.n, 16);
- this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
-
- // Temporary arrays
- this._wnafT1 = new Array(4);
- this._wnafT2 = new Array(4);
- this._wnafT3 = new Array(4);
- this._wnafT4 = new Array(4);
-
- this._bitLength = this.n ? this.n.bitLength() : 0;
-
- // Generalized Greg Maxwell's trick
- var adjustCount = this.n && this.p.div(this.n);
- if (!adjustCount || adjustCount.cmpn(100) > 0) {
- this.redN = null;
- } else {
- this._maxwellTrick = true;
- this.redN = this.n.toRed(this.red);
- }
-}
-module.exports = BaseCurve;
-
-BaseCurve.prototype.point = function point() {
- throw new Error('Not implemented');
-};
-
-BaseCurve.prototype.validate = function validate() {
- throw new Error('Not implemented');
-};
-
-BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
- assert(p.precomputed);
- var doubles = p._getDoubles();
-
- var naf = getNAF(k, 1, this._bitLength);
- var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
- I /= 3;
-
- // Translate into more windowed form
- var repr = [];
- var j;
- var nafW;
- for (j = 0; j < naf.length; j += doubles.step) {
- nafW = 0;
- for (var l = j + doubles.step - 1; l >= j; l--)
- nafW = (nafW << 1) + naf[l];
- repr.push(nafW);
- }
-
- var a = this.jpoint(null, null, null);
- var b = this.jpoint(null, null, null);
- for (var i = I; i > 0; i--) {
- for (j = 0; j < repr.length; j++) {
- nafW = repr[j];
- if (nafW === i)
- b = b.mixedAdd(doubles.points[j]);
- else if (nafW === -i)
- b = b.mixedAdd(doubles.points[j].neg());
- }
- a = a.add(b);
- }
- return a.toP();
-};
-
-BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
- var w = 4;
-
- // Precompute window
- var nafPoints = p._getNAFPoints(w);
- w = nafPoints.wnd;
- var wnd = nafPoints.points;
-
- // Get NAF form
- var naf = getNAF(k, w, this._bitLength);
-
- // Add `this`*(N+1) for every w-NAF index
- var acc = this.jpoint(null, null, null);
- for (var i = naf.length - 1; i >= 0; i--) {
- // Count zeroes
- for (var l = 0; i >= 0 && naf[i] === 0; i--)
- l++;
- if (i >= 0)
- l++;
- acc = acc.dblp(l);
-
- if (i < 0)
- break;
- var z = naf[i];
- assert(z !== 0);
- if (p.type === 'affine') {
- // J +- P
- if (z > 0)
- acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
- else
- acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
- } else {
- // J +- J
- if (z > 0)
- acc = acc.add(wnd[(z - 1) >> 1]);
- else
- acc = acc.add(wnd[(-z - 1) >> 1].neg());
- }
- }
- return p.type === 'affine' ? acc.toP() : acc;
-};
-
-BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
- points,
- coeffs,
- len,
- jacobianResult) {
- var wndWidth = this._wnafT1;
- var wnd = this._wnafT2;
- var naf = this._wnafT3;
-
- // Fill all arrays
- var max = 0;
- var i;
- var j;
- var p;
- for (i = 0; i < len; i++) {
- p = points[i];
- var nafPoints = p._getNAFPoints(defW);
- wndWidth[i] = nafPoints.wnd;
- wnd[i] = nafPoints.points;
- }
-
- // Comb small window NAFs
- for (i = len - 1; i >= 1; i -= 2) {
- var a = i - 1;
- var b = i;
- if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
- naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength);
- naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength);
- max = Math.max(naf[a].length, max);
- max = Math.max(naf[b].length, max);
- continue;
- }
-
- var comb = [
- points[a], /* 1 */
- null, /* 3 */
- null, /* 5 */
- points[b], /* 7 */
- ];
-
- // Try to avoid Projective points, if possible
- if (points[a].y.cmp(points[b].y) === 0) {
- comb[1] = points[a].add(points[b]);
- comb[2] = points[a].toJ().mixedAdd(points[b].neg());
- } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
- comb[1] = points[a].toJ().mixedAdd(points[b]);
- comb[2] = points[a].add(points[b].neg());
- } else {
- comb[1] = points[a].toJ().mixedAdd(points[b]);
- comb[2] = points[a].toJ().mixedAdd(points[b].neg());
- }
-
- var index = [
- -3, /* -1 -1 */
- -1, /* -1 0 */
- -5, /* -1 1 */
- -7, /* 0 -1 */
- 0, /* 0 0 */
- 7, /* 0 1 */
- 5, /* 1 -1 */
- 1, /* 1 0 */
- 3, /* 1 1 */
- ];
-
- var jsf = getJSF(coeffs[a], coeffs[b]);
- max = Math.max(jsf[0].length, max);
- naf[a] = new Array(max);
- naf[b] = new Array(max);
- for (j = 0; j < max; j++) {
- var ja = jsf[0][j] | 0;
- var jb = jsf[1][j] | 0;
-
- naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
- naf[b][j] = 0;
- wnd[a] = comb;
- }
- }
-
- var acc = this.jpoint(null, null, null);
- var tmp = this._wnafT4;
- for (i = max; i >= 0; i--) {
- var k = 0;
-
- while (i >= 0) {
- var zero = true;
- for (j = 0; j < len; j++) {
- tmp[j] = naf[j][i] | 0;
- if (tmp[j] !== 0)
- zero = false;
- }
- if (!zero)
- break;
- k++;
- i--;
- }
- if (i >= 0)
- k++;
- acc = acc.dblp(k);
- if (i < 0)
- break;
-
- for (j = 0; j < len; j++) {
- var z = tmp[j];
- p;
- if (z === 0)
- continue;
- else if (z > 0)
- p = wnd[j][(z - 1) >> 1];
- else if (z < 0)
- p = wnd[j][(-z - 1) >> 1].neg();
-
- if (p.type === 'affine')
- acc = acc.mixedAdd(p);
- else
- acc = acc.add(p);
- }
- }
- // Zeroify references
- for (i = 0; i < len; i++)
- wnd[i] = null;
-
- if (jacobianResult)
- return acc;
- else
- return acc.toP();
-};
-
-function BasePoint(curve, type) {
- this.curve = curve;
- this.type = type;
- this.precomputed = null;
-}
-BaseCurve.BasePoint = BasePoint;
-
-BasePoint.prototype.eq = function eq(/*other*/) {
- throw new Error('Not implemented');
-};
-
-BasePoint.prototype.validate = function validate() {
- return this.curve.validate(this);
-};
-
-BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
- bytes = utils.toArray(bytes, enc);
-
- var len = this.p.byteLength();
-
- // uncompressed, hybrid-odd, hybrid-even
- if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
- bytes.length - 1 === 2 * len) {
- if (bytes[0] === 0x06)
- assert(bytes[bytes.length - 1] % 2 === 0);
- else if (bytes[0] === 0x07)
- assert(bytes[bytes.length - 1] % 2 === 1);
-
- var res = this.point(bytes.slice(1, 1 + len),
- bytes.slice(1 + len, 1 + 2 * len));
-
- return res;
- } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
- bytes.length - 1 === len) {
- return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
- }
- throw new Error('Unknown point format');
-};
-
-BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
- return this.encode(enc, true);
-};
-
-BasePoint.prototype._encode = function _encode(compact) {
- var len = this.curve.p.byteLength();
- var x = this.getX().toArray('be', len);
-
- if (compact)
- return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
-
- return [ 0x04 ].concat(x, this.getY().toArray('be', len));
-};
-
-BasePoint.prototype.encode = function encode(enc, compact) {
- return utils.encode(this._encode(compact), enc);
-};
-
-BasePoint.prototype.precompute = function precompute(power) {
- if (this.precomputed)
- return this;
-
- var precomputed = {
- doubles: null,
- naf: null,
- beta: null,
- };
- precomputed.naf = this._getNAFPoints(8);
- precomputed.doubles = this._getDoubles(4, power);
- precomputed.beta = this._getBeta();
- this.precomputed = precomputed;
-
- return this;
-};
-
-BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
- if (!this.precomputed)
- return false;
-
- var doubles = this.precomputed.doubles;
- if (!doubles)
- return false;
-
- return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
-};
-
-BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
- if (this.precomputed && this.precomputed.doubles)
- return this.precomputed.doubles;
-
- var doubles = [ this ];
- var acc = this;
- for (var i = 0; i < power; i += step) {
- for (var j = 0; j < step; j++)
- acc = acc.dbl();
- doubles.push(acc);
- }
- return {
- step: step,
- points: doubles,
- };
-};
-
-BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
- if (this.precomputed && this.precomputed.naf)
- return this.precomputed.naf;
-
- var res = [ this ];
- var max = (1 << wnd) - 1;
- var dbl = max === 1 ? null : this.dbl();
- for (var i = 1; i < max; i++)
- res[i] = res[i - 1].add(dbl);
- return {
- wnd: wnd,
- points: res,
- };
-};
-
-BasePoint.prototype._getBeta = function _getBeta() {
- return null;
-};
-
-BasePoint.prototype.dblp = function dblp(k) {
- var r = this;
- for (var i = 0; i < k; i++)
- r = r.dbl();
- return r;
-};
-
-
-/***/ }),
-
-/***/ 826491:
-/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
-
-"use strict";
-
-
-var utils = __webpack_require__(938402);
-var BN = __webpack_require__(439404);
-var inherits = __webpack_require__(672017);
-var Base = __webpack_require__(774278);
-
-var assert = utils.assert;
-
-function EdwardsCurve(conf) {
- // NOTE: Important as we are creating point in Base.call()
- this.twisted = (conf.a | 0) !== 1;
- this.mOneA = this.twisted && (conf.a | 0) === -1;
- this.extended = this.mOneA;
-
- Base.call(this, 'edwards', conf);
-
- this.a = new BN(conf.a, 16).umod(this.red.m);
- this.a = this.a.toRed(this.red);
- this.c = new BN(conf.c, 16).toRed(this.red);
- this.c2 = this.c.redSqr();
- this.d = new BN(conf.d, 16).toRed(this.red);
- this.dd = this.d.redAdd(this.d);
-
- assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
- this.oneC = (conf.c | 0) === 1;
-}
-inherits(EdwardsCurve, Base);
-module.exports = EdwardsCurve;
-
-EdwardsCurve.prototype._mulA = function _mulA(num) {
- if (this.mOneA)
- return num.redNeg();
- else
- return this.a.redMul(num);
-};
-
-EdwardsCurve.prototype._mulC = function _mulC(num) {
- if (this.oneC)
- return num;
- else
- return this.c.redMul(num);
-};
-
-// Just for compatibility with Short curve
-EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
- return this.point(x, y, z, t);
-};
-
-EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
- x = new BN(x, 16);
- if (!x.red)
- x = x.toRed(this.red);
-
- var x2 = x.redSqr();
- var rhs = this.c2.redSub(this.a.redMul(x2));
- var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
-
- var y2 = rhs.redMul(lhs.redInvm());
- var y = y2.redSqrt();
- if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
- throw new Error('invalid point');
-
- var isOdd = y.fromRed().isOdd();
- if (odd && !isOdd || !odd && isOdd)
- y = y.redNeg();
-
- return this.point(x, y);
-};
-
-EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
- y = new BN(y, 16);
- if (!y.red)
- y = y.toRed(this.red);
-
- // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
- var y2 = y.redSqr();
- var lhs = y2.redSub(this.c2);
- var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
- var x2 = lhs.redMul(rhs.redInvm());
-
- if (x2.cmp(this.zero) === 0) {
- if (odd)
- throw new Error('invalid point');
- else
- return this.point(this.zero, y);
- }
-
- var x = x2.redSqrt();
- if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
- throw new Error('invalid point');
-
- if (x.fromRed().isOdd() !== odd)
- x = x.redNeg();
-
- return this.point(x, y);
-};
-
-EdwardsCurve.prototype.validate = function validate(point) {
- if (point.isInfinity())
- return true;
-
- // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
- point.normalize();
-
- var x2 = point.x.redSqr();
- var y2 = point.y.redSqr();
- var lhs = x2.redMul(this.a).redAdd(y2);
- var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
-
- return lhs.cmp(rhs) === 0;
-};
-
-function Point(curve, x, y, z, t) {
- Base.BasePoint.call(this, curve, 'projective');
- if (x === null && y === null && z === null) {
- this.x = this.curve.zero;
- this.y = this.curve.one;
- this.z = this.curve.one;
- this.t = this.curve.zero;
- this.zOne = true;
- } else {
- this.x = new BN(x, 16);
- this.y = new BN(y, 16);
- this.z = z ? new BN(z, 16) : this.curve.one;
- this.t = t && new BN(t, 16);
- if (!this.x.red)
- this.x = this.x.toRed(this.curve.red);
- if (!this.y.red)
- this.y = this.y.toRed(this.curve.red);
- if (!this.z.red)
- this.z = this.z.toRed(this.curve.red);
- if (this.t && !this.t.red)
- this.t = this.t.toRed(this.curve.red);
- this.zOne = this.z === this.curve.one;
-
- // Use extended coordinates
- if (this.curve.extended && !this.t) {
- this.t = this.x.redMul(this.y);
- if (!this.zOne)
- this.t = this.t.redMul(this.z.redInvm());
- }
- }
-}
-inherits(Point, Base.BasePoint);
-
-EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
- return Point.fromJSON(this, obj);
-};
-
-EdwardsCurve.prototype.point = function point(x, y, z, t) {
- return new Point(this, x, y, z, t);
-};
-
-Point.fromJSON = function fromJSON(curve, obj) {
- return new Point(curve, obj[0], obj[1], obj[2]);
-};
-
-Point.prototype.inspect = function inspect() {
- if (this.isInfinity())
- return '';
- return '';
-};
-
-Point.prototype.isInfinity = function isInfinity() {
- // XXX This code assumes that zero is always zero in red
- return this.x.cmpn(0) === 0 &&
- (this.y.cmp(this.z) === 0 ||
- (this.zOne && this.y.cmp(this.curve.c) === 0));
-};
-
-Point.prototype._extDbl = function _extDbl() {
- // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
- // #doubling-dbl-2008-hwcd
- // 4M + 4S
-
- // A = X1^2
- var a = this.x.redSqr();
- // B = Y1^2
- var b = this.y.redSqr();
- // C = 2 * Z1^2
- var c = this.z.redSqr();
- c = c.redIAdd(c);
- // D = a * A
- var d = this.curve._mulA(a);
- // E = (X1 + Y1)^2 - A - B
- var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
- // G = D + B
- var g = d.redAdd(b);
- // F = G - C
- var f = g.redSub(c);
- // H = D - B
- var h = d.redSub(b);
- // X3 = E * F
- var nx = e.redMul(f);
- // Y3 = G * H
- var ny = g.redMul(h);
- // T3 = E * H
- var nt = e.redMul(h);
- // Z3 = F * G
- var nz = f.redMul(g);
- return this.curve.point(nx, ny, nz, nt);
-};
-
-Point.prototype._projDbl = function _projDbl() {
- // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
- // #doubling-dbl-2008-bbjlp
- // #doubling-dbl-2007-bl
- // and others
- // Generally 3M + 4S or 2M + 4S
-
- // B = (X1 + Y1)^2
- var b = this.x.redAdd(this.y).redSqr();
- // C = X1^2
- var c = this.x.redSqr();
- // D = Y1^2
- var d = this.y.redSqr();
-
- var nx;
- var ny;
- var nz;
- var e;
- var h;
- var j;
- if (this.curve.twisted) {
- // E = a * C
- e = this.curve._mulA(c);
- // F = E + D
- var f = e.redAdd(d);
- if (this.zOne) {
- // X3 = (B - C - D) * (F - 2)
- nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
- // Y3 = F * (E - D)
- ny = f.redMul(e.redSub(d));
- // Z3 = F^2 - 2 * F
- nz = f.redSqr().redSub(f).redSub(f);
- } else {
- // H = Z1^2
- h = this.z.redSqr();
- // J = F - 2 * H
- j = f.redSub(h).redISub(h);
- // X3 = (B-C-D)*J
- nx = b.redSub(c).redISub(d).redMul(j);
- // Y3 = F * (E - D)
- ny = f.redMul(e.redSub(d));
- // Z3 = F * J
- nz = f.redMul(j);
- }
- } else {
- // E = C + D
- e = c.redAdd(d);
- // H = (c * Z1)^2
- h = this.curve._mulC(this.z).redSqr();
- // J = E - 2 * H
- j = e.redSub(h).redSub(h);
- // X3 = c * (B - E) * J
- nx = this.curve._mulC(b.redISub(e)).redMul(j);
- // Y3 = c * E * (C - D)
- ny = this.curve._mulC(e).redMul(c.redISub(d));
- // Z3 = E * J
- nz = e.redMul(j);
- }
- return this.curve.point(nx, ny, nz);
-};
-
-Point.prototype.dbl = function dbl() {
- if (this.isInfinity())
- return this;
-
- // Double in extended coordinates
- if (this.curve.extended)
- return this._extDbl();
- else
- return this._projDbl();
-};
-
-Point.prototype._extAdd = function _extAdd(p) {
- // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
- // #addition-add-2008-hwcd-3
- // 8M
-
- // A = (Y1 - X1) * (Y2 - X2)
- var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
- // B = (Y1 + X1) * (Y2 + X2)
- var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
- // C = T1 * k * T2
- var c = this.t.redMul(this.curve.dd).redMul(p.t);
- // D = Z1 * 2 * Z2
- var d = this.z.redMul(p.z.redAdd(p.z));
- // E = B - A
- var e = b.redSub(a);
- // F = D - C
- var f = d.redSub(c);
- // G = D + C
- var g = d.redAdd(c);
- // H = B + A
- var h = b.redAdd(a);
- // X3 = E * F
- var nx = e.redMul(f);
- // Y3 = G * H
- var ny = g.redMul(h);
- // T3 = E * H
- var nt = e.redMul(h);
- // Z3 = F * G
- var nz = f.redMul(g);
- return this.curve.point(nx, ny, nz, nt);
-};
-
-Point.prototype._projAdd = function _projAdd(p) {
- // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
- // #addition-add-2008-bbjlp
- // #addition-add-2007-bl
- // 10M + 1S
-
- // A = Z1 * Z2
- var a = this.z.redMul(p.z);
- // B = A^2
- var b = a.redSqr();
- // C = X1 * X2
- var c = this.x.redMul(p.x);
- // D = Y1 * Y2
- var d = this.y.redMul(p.y);
- // E = d * C * D
- var e = this.curve.d.redMul(c).redMul(d);
- // F = B - E
- var f = b.redSub(e);
- // G = B + E
- var g = b.redAdd(e);
- // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
- var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
- var nx = a.redMul(f).redMul(tmp);
- var ny;
- var nz;
- if (this.curve.twisted) {
- // Y3 = A * G * (D - a * C)
- ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
- // Z3 = F * G
- nz = f.redMul(g);
- } else {
- // Y3 = A * G * (D - C)
- ny = a.redMul(g).redMul(d.redSub(c));
- // Z3 = c * F * G
- nz = this.curve._mulC(f).redMul(g);
- }
- return this.curve.point(nx, ny, nz);
-};
-
-Point.prototype.add = function add(p) {
- if (this.isInfinity())
- return p;
- if (p.isInfinity())
- return this;
-
- if (this.curve.extended)
- return this._extAdd(p);
- else
- return this._projAdd(p);
-};
-
-Point.prototype.mul = function mul(k) {
- if (this._hasDoubles(k))
- return this.curve._fixedNafMul(this, k);
- else
- return this.curve._wnafMul(this, k);
-};
-
-Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
- return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
-};
-
-Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
- return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
-};
-
-Point.prototype.normalize = function normalize() {
- if (this.zOne)
- return this;
-
- // Normalize coordinates
- var zi = this.z.redInvm();
- this.x = this.x.redMul(zi);
- this.y = this.y.redMul(zi);
- if (this.t)
- this.t = this.t.redMul(zi);
- this.z = this.curve.one;
- this.zOne = true;
- return this;
-};
-
-Point.prototype.neg = function neg() {
- return this.curve.point(this.x.redNeg(),
- this.y,
- this.z,
- this.t && this.t.redNeg());
-};
-
-Point.prototype.getX = function getX() {
- this.normalize();
- return this.x.fromRed();
-};
-
-Point.prototype.getY = function getY() {
- this.normalize();
- return this.y.fromRed();
-};
-
-Point.prototype.eq = function eq(other) {
- return this === other ||
- this.getX().cmp(other.getX()) === 0 &&
- this.getY().cmp(other.getY()) === 0;
-};
-
-Point.prototype.eqXToP = function eqXToP(x) {
- var rx = x.toRed(this.curve.red).redMul(this.z);
- if (this.x.cmp(rx) === 0)
- return true;
-
- var xc = x.clone();
- var t = this.curve.redN.redMul(this.z);
- for (;;) {
- xc.iadd(this.curve.n);
- if (xc.cmp(this.curve.p) >= 0)
- return false;
-
- rx.redIAdd(t);
- if (this.x.cmp(rx) === 0)
- return true;
- }
-};
-
-// Compatibility with BaseCurve
-Point.prototype.toP = Point.prototype.normalize;
-Point.prototype.mixedAdd = Point.prototype.add;
-
-
-/***/ }),
-
-/***/ 777867:
-/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
-
-"use strict";
-
-
-var curve = exports;
-
-curve.base = __webpack_require__(774278);
-curve.short = __webpack_require__(43461);
-curve.mont = __webpack_require__(34397);
-curve.edwards = __webpack_require__(826491);
-
-
-/***/ }),
-
-/***/ 34397:
-/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
-
-"use strict";
-
-
-var BN = __webpack_require__(439404);
-var inherits = __webpack_require__(672017);
-var Base = __webpack_require__(774278);
-
-var utils = __webpack_require__(938402);
-
-function MontCurve(conf) {
- Base.call(this, 'mont', conf);
-
- this.a = new BN(conf.a, 16).toRed(this.red);
- this.b = new BN(conf.b, 16).toRed(this.red);
- this.i4 = new BN(4).toRed(this.red).redInvm();
- this.two = new BN(2).toRed(this.red);
- this.a24 = this.i4.redMul(this.a.redAdd(this.two));
-}
-inherits(MontCurve, Base);
-module.exports = MontCurve;
-
-MontCurve.prototype.validate = function validate(point) {
- var x = point.normalize().x;
- var x2 = x.redSqr();
- var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
- var y = rhs.redSqrt();
-
- return y.redSqr().cmp(rhs) === 0;
-};
-
-function Point(curve, x, z) {
- Base.BasePoint.call(this, curve, 'projective');
- if (x === null && z === null) {
- this.x = this.curve.one;
- this.z = this.curve.zero;
- } else {
- this.x = new BN(x, 16);
- this.z = new BN(z, 16);
- if (!this.x.red)
- this.x = this.x.toRed(this.curve.red);
- if (!this.z.red)
- this.z = this.z.toRed(this.curve.red);
- }
-}
-inherits(Point, Base.BasePoint);
-
-MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
- return this.point(utils.toArray(bytes, enc), 1);
-};
-
-MontCurve.prototype.point = function point(x, z) {
- return new Point(this, x, z);
-};
-
-MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
- return Point.fromJSON(this, obj);
-};
-
-Point.prototype.precompute = function precompute() {
- // No-op
-};
-
-Point.prototype._encode = function _encode() {
- return this.getX().toArray('be', this.curve.p.byteLength());
-};
-
-Point.fromJSON = function fromJSON(curve, obj) {
- return new Point(curve, obj[0], obj[1] || curve.one);
-};
-
-Point.prototype.inspect = function inspect() {
- if (this.isInfinity())
- return '';
- return '';
-};
-
-Point.prototype.isInfinity = function isInfinity() {
- // XXX This code assumes that zero is always zero in red
- return this.z.cmpn(0) === 0;
-};
-
-Point.prototype.dbl = function dbl() {
- // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
- // 2M + 2S + 4A
-
- // A = X1 + Z1
- var a = this.x.redAdd(this.z);
- // AA = A^2
- var aa = a.redSqr();
- // B = X1 - Z1
- var b = this.x.redSub(this.z);
- // BB = B^2
- var bb = b.redSqr();
- // C = AA - BB
- var c = aa.redSub(bb);
- // X3 = AA * BB
- var nx = aa.redMul(bb);
- // Z3 = C * (BB + A24 * C)
- var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
- return this.curve.point(nx, nz);
-};
-
-Point.prototype.add = function add() {
- throw new Error('Not supported on Montgomery curve');
-};
-
-Point.prototype.diffAdd = function diffAdd(p, diff) {
- // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
- // 4M + 2S + 6A
-
- // A = X2 + Z2
- var a = this.x.redAdd(this.z);
- // B = X2 - Z2
- var b = this.x.redSub(this.z);
- // C = X3 + Z3
- var c = p.x.redAdd(p.z);
- // D = X3 - Z3
- var d = p.x.redSub(p.z);
- // DA = D * A
- var da = d.redMul(a);
- // CB = C * B
- var cb = c.redMul(b);
- // X5 = Z1 * (DA + CB)^2
- var nx = diff.z.redMul(da.redAdd(cb).redSqr());
- // Z5 = X1 * (DA - CB)^2
- var nz = diff.x.redMul(da.redISub(cb).redSqr());
- return this.curve.point(nx, nz);
-};
-
-Point.prototype.mul = function mul(k) {
- var t = k.clone();
- var a = this; // (N / 2) * Q + Q
- var b = this.curve.point(null, null); // (N / 2) * Q
- var c = this; // Q
-
- for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
- bits.push(t.andln(1));
-
- for (var i = bits.length - 1; i >= 0; i--) {
- if (bits[i] === 0) {
- // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
- a = a.diffAdd(b, c);
- // N * Q = 2 * ((N / 2) * Q + Q))
- b = b.dbl();
- } else {
- // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
- b = a.diffAdd(b, c);
- // N * Q + Q = 2 * ((N / 2) * Q + Q)
- a = a.dbl();
- }
- }
- return b;
-};
-
-Point.prototype.mulAdd = function mulAdd() {
- throw new Error('Not supported on Montgomery curve');
-};
-
-Point.prototype.jumlAdd = function jumlAdd() {
- throw new Error('Not supported on Montgomery curve');
-};
-
-Point.prototype.eq = function eq(other) {
- return this.getX().cmp(other.getX()) === 0;
-};
-
-Point.prototype.normalize = function normalize() {
- this.x = this.x.redMul(this.z.redInvm());
- this.z = this.curve.one;
- return this;
-};
-
-Point.prototype.getX = function getX() {
- // Normalize coordinates
- this.normalize();
-
- return this.x.fromRed();
-};
-
-
-/***/ }),
-
-/***/ 43461:
-/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
-
-"use strict";
-
-
-var utils = __webpack_require__(938402);
-var BN = __webpack_require__(439404);
-var inherits = __webpack_require__(672017);
-var Base = __webpack_require__(774278);
-
-var assert = utils.assert;
-
-function ShortCurve(conf) {
- Base.call(this, 'short', conf);
-
- this.a = new BN(conf.a, 16).toRed(this.red);
- this.b = new BN(conf.b, 16).toRed(this.red);
- this.tinv = this.two.redInvm();
-
- this.zeroA = this.a.fromRed().cmpn(0) === 0;
- this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
-
- // If the curve is endomorphic, precalculate beta and lambda
- this.endo = this._getEndomorphism(conf);
- this._endoWnafT1 = new Array(4);
- this._endoWnafT2 = new Array(4);
-}
-inherits(ShortCurve, Base);
-module.exports = ShortCurve;
-
-ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
- // No efficient endomorphism
- if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
- return;
-
- // Compute beta and lambda, that lambda * P = (beta * Px; Py)
- var beta;
- var lambda;
- if (conf.beta) {
- beta = new BN(conf.beta, 16).toRed(this.red);
- } else {
- var betas = this._getEndoRoots(this.p);
- // Choose the smallest beta
- beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
- beta = beta.toRed(this.red);
- }
- if (conf.lambda) {
- lambda = new BN(conf.lambda, 16);
- } else {
- // Choose the lambda that is matching selected beta
- var lambdas = this._getEndoRoots(this.n);
- if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
- lambda = lambdas[0];
- } else {
- lambda = lambdas[1];
- assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
- }
- }
-
- // Get basis vectors, used for balanced length-two representation
- var basis;
- if (conf.basis) {
- basis = conf.basis.map(function(vec) {
- return {
- a: new BN(vec.a, 16),
- b: new BN(vec.b, 16),
- };
- });
- } else {
- basis = this._getEndoBasis(lambda);
- }
-
- return {
- beta: beta,
- lambda: lambda,
- basis: basis,
- };
-};
-
-ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
- // Find roots of for x^2 + x + 1 in F
- // Root = (-1 +- Sqrt(-3)) / 2
- //
- var red = num === this.p ? this.red : BN.mont(num);
- var tinv = new BN(2).toRed(red).redInvm();
- var ntinv = tinv.redNeg();
-
- var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);
-
- var l1 = ntinv.redAdd(s).fromRed();
- var l2 = ntinv.redSub(s).fromRed();
- return [ l1, l2 ];
-};
-
-ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
- // aprxSqrt >= sqrt(this.n)
- var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
-
- // 3.74
- // Run EGCD, until r(L + 1) < aprxSqrt
- var u = lambda;
- var v = this.n.clone();
- var x1 = new BN(1);
- var y1 = new BN(0);
- var x2 = new BN(0);
- var y2 = new BN(1);
-
- // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
- var a0;
- var b0;
- // First vector
- var a1;
- var b1;
- // Second vector
- var a2;
- var b2;
-
- var prevR;
- var i = 0;
- var r;
- var x;
- while (u.cmpn(0) !== 0) {
- var q = v.div(u);
- r = v.sub(q.mul(u));
- x = x2.sub(q.mul(x1));
- var y = y2.sub(q.mul(y1));
-
- if (!a1 && r.cmp(aprxSqrt) < 0) {
- a0 = prevR.neg();
- b0 = x1;
- a1 = r.neg();
- b1 = x;
- } else if (a1 && ++i === 2) {
- break;
- }
- prevR = r;
-
- v = u;
- u = r;
- x2 = x1;
- x1 = x;
- y2 = y1;
- y1 = y;
- }
- a2 = r.neg();
- b2 = x;
-
- var len1 = a1.sqr().add(b1.sqr());
- var len2 = a2.sqr().add(b2.sqr());
- if (len2.cmp(len1) >= 0) {
- a2 = a0;
- b2 = b0;
- }
-
- // Normalize signs
- if (a1.negative) {
- a1 = a1.neg();
- b1 = b1.neg();
- }
- if (a2.negative) {
- a2 = a2.neg();
- b2 = b2.neg();
- }
-
- return [
- { a: a1, b: b1 },
- { a: a2, b: b2 },
- ];
-};
-
-ShortCurve.prototype._endoSplit = function _endoSplit(k) {
- var basis = this.endo.basis;
- var v1 = basis[0];
- var v2 = basis[1];
-
- var c1 = v2.b.mul(k).divRound(this.n);
- var c2 = v1.b.neg().mul(k).divRound(this.n);
-
- var p1 = c1.mul(v1.a);
- var p2 = c2.mul(v2.a);
- var q1 = c1.mul(v1.b);
- var q2 = c2.mul(v2.b);
-
- // Calculate answer
- var k1 = k.sub(p1).sub(p2);
- var k2 = q1.add(q2).neg();
- return { k1: k1, k2: k2 };
-};
-
-ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
- x = new BN(x, 16);
- if (!x.red)
- x = x.toRed(this.red);
-
- var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
- var y = y2.redSqrt();
- if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
- throw new Error('invalid point');
-
- // XXX Is there any way to tell if the number is odd without converting it
- // to non-red form?
- var isOdd = y.fromRed().isOdd();
- if (odd && !isOdd || !odd && isOdd)
- y = y.redNeg();
-
- return this.point(x, y);
-};
-
-ShortCurve.prototype.validate = function validate(point) {
- if (point.inf)
- return true;
-
- var x = point.x;
- var y = point.y;
-
- var ax = this.a.redMul(x);
- var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
- return y.redSqr().redISub(rhs).cmpn(0) === 0;
-};
-
-ShortCurve.prototype._endoWnafMulAdd =
- function _endoWnafMulAdd(points, coeffs, jacobianResult) {
- var npoints = this._endoWnafT1;
- var ncoeffs = this._endoWnafT2;
- for (var i = 0; i < points.length; i++) {
- var split = this._endoSplit(coeffs[i]);
- var p = points[i];
- var beta = p._getBeta();
-
- if (split.k1.negative) {
- split.k1.ineg();
- p = p.neg(true);
- }
- if (split.k2.negative) {
- split.k2.ineg();
- beta = beta.neg(true);
- }
-
- npoints[i * 2] = p;
- npoints[i * 2 + 1] = beta;
- ncoeffs[i * 2] = split.k1;
- ncoeffs[i * 2 + 1] = split.k2;
- }
- var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
-
- // Clean-up references to points and coefficients
- for (var j = 0; j < i * 2; j++) {
- npoints[j] = null;
- ncoeffs[j] = null;
- }
- return res;
- };
-
-function Point(curve, x, y, isRed) {
- Base.BasePoint.call(this, curve, 'affine');
- if (x === null && y === null) {
- this.x = null;
- this.y = null;
- this.inf = true;
- } else {
- this.x = new BN(x, 16);
- this.y = new BN(y, 16);
- // Force redgomery representation when loading from JSON
- if (isRed) {
- this.x.forceRed(this.curve.red);
- this.y.forceRed(this.curve.red);
- }
- if (!this.x.red)
- this.x = this.x.toRed(this.curve.red);
- if (!this.y.red)
- this.y = this.y.toRed(this.curve.red);
- this.inf = false;
- }
-}
-inherits(Point, Base.BasePoint);
-
-ShortCurve.prototype.point = function point(x, y, isRed) {
- return new Point(this, x, y, isRed);
-};
-
-ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
- return Point.fromJSON(this, obj, red);
-};
-
-Point.prototype._getBeta = function _getBeta() {
- if (!this.curve.endo)
- return;
-
- var pre = this.precomputed;
- if (pre && pre.beta)
- return pre.beta;
-
- var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
- if (pre) {
- var curve = this.curve;
- var endoMul = function(p) {
- return curve.point(p.x.redMul(curve.endo.beta), p.y);
- };
- pre.beta = beta;
- beta.precomputed = {
- beta: null,
- naf: pre.naf && {
- wnd: pre.naf.wnd,
- points: pre.naf.points.map(endoMul),
- },
- doubles: pre.doubles && {
- step: pre.doubles.step,
- points: pre.doubles.points.map(endoMul),
- },
- };
- }
- return beta;
-};
-
-Point.prototype.toJSON = function toJSON() {
- if (!this.precomputed)
- return [ this.x, this.y ];
-
- return [ this.x, this.y, this.precomputed && {
- doubles: this.precomputed.doubles && {
- step: this.precomputed.doubles.step,
- points: this.precomputed.doubles.points.slice(1),
- },
- naf: this.precomputed.naf && {
- wnd: this.precomputed.naf.wnd,
- points: this.precomputed.naf.points.slice(1),
- },
- } ];
-};
-
-Point.fromJSON = function fromJSON(curve, obj, red) {
- if (typeof obj === 'string')
- obj = JSON.parse(obj);
- var res = curve.point(obj[0], obj[1], red);
- if (!obj[2])
- return res;
-
- function obj2point(obj) {
- return curve.point(obj[0], obj[1], red);
- }
-
- var pre = obj[2];
- res.precomputed = {
- beta: null,
- doubles: pre.doubles && {
- step: pre.doubles.step,
- points: [ res ].concat(pre.doubles.points.map(obj2point)),
- },
- naf: pre.naf && {
- wnd: pre.naf.wnd,
- points: [ res ].concat(pre.naf.points.map(obj2point)),
- },
- };
- return res;
-};
-
-Point.prototype.inspect = function inspect() {
- if (this.isInfinity())
- return '';
- return '';
-};
-
-Point.prototype.isInfinity = function isInfinity() {
- return this.inf;
-};
-
-Point.prototype.add = function add(p) {
- // O + P = P
- if (this.inf)
- return p;
-
- // P + O = P
- if (p.inf)
- return this;
-
- // P + P = 2P
- if (this.eq(p))
- return this.dbl();
-
- // P + (-P) = O
- if (this.neg().eq(p))
- return this.curve.point(null, null);
-
- // P + Q = O
- if (this.x.cmp(p.x) === 0)
- return this.curve.point(null, null);
-
- var c = this.y.redSub(p.y);
- if (c.cmpn(0) !== 0)
- c = c.redMul(this.x.redSub(p.x).redInvm());
- var nx = c.redSqr().redISub(this.x).redISub(p.x);
- var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
- return this.curve.point(nx, ny);
-};
-
-Point.prototype.dbl = function dbl() {
- if (this.inf)
- return this;
-
- // 2P = O
- var ys1 = this.y.redAdd(this.y);
- if (ys1.cmpn(0) === 0)
- return this.curve.point(null, null);
-
- var a = this.curve.a;
-
- var x2 = this.x.redSqr();
- var dyinv = ys1.redInvm();
- var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
-
- var nx = c.redSqr().redISub(this.x.redAdd(this.x));
- var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
- return this.curve.point(nx, ny);
-};
-
-Point.prototype.getX = function getX() {
- return this.x.fromRed();
-};
-
-Point.prototype.getY = function getY() {
- return this.y.fromRed();
-};
-
-Point.prototype.mul = function mul(k) {
- k = new BN(k, 16);
- if (this.isInfinity())
- return this;
- else if (this._hasDoubles(k))
- return this.curve._fixedNafMul(this, k);
- else if (this.curve.endo)
- return this.curve._endoWnafMulAdd([ this ], [ k ]);
- else
- return this.curve._wnafMul(this, k);
-};
-
-Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
- var points = [ this, p2 ];
- var coeffs = [ k1, k2 ];
- if (this.curve.endo)
- return this.curve._endoWnafMulAdd(points, coeffs);
- else
- return this.curve._wnafMulAdd(1, points, coeffs, 2);
-};
-
-Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
- var points = [ this, p2 ];
- var coeffs = [ k1, k2 ];
- if (this.curve.endo)
- return this.curve._endoWnafMulAdd(points, coeffs, true);
- else
- return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
-};
-
-Point.prototype.eq = function eq(p) {
- return this === p ||
- this.inf === p.inf &&
- (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
-};
-
-Point.prototype.neg = function neg(_precompute) {
- if (this.inf)
- return this;
-
- var res = this.curve.point(this.x, this.y.redNeg());
- if (_precompute && this.precomputed) {
- var pre = this.precomputed;
- var negate = function(p) {
- return p.neg();
- };
- res.precomputed = {
- naf: pre.naf && {
- wnd: pre.naf.wnd,
- points: pre.naf.points.map(negate),
- },
- doubles: pre.doubles && {
- step: pre.doubles.step,
- points: pre.doubles.points.map(negate),
- },
- };
- }
- return res;
-};
-
-Point.prototype.toJ = function toJ() {
- if (this.inf)
- return this.curve.jpoint(null, null, null);
-
- var res = this.curve.jpoint(this.x, this.y, this.curve.one);
- return res;
-};
-
-function JPoint(curve, x, y, z) {
- Base.BasePoint.call(this, curve, 'jacobian');
- if (x === null && y === null && z === null) {
- this.x = this.curve.one;
- this.y = this.curve.one;
- this.z = new BN(0);
- } else {
- this.x = new BN(x, 16);
- this.y = new BN(y, 16);
- this.z = new BN(z, 16);
- }
- if (!this.x.red)
- this.x = this.x.toRed(this.curve.red);
- if (!this.y.red)
- this.y = this.y.toRed(this.curve.red);
- if (!this.z.red)
- this.z = this.z.toRed(this.curve.red);
-
- this.zOne = this.z === this.curve.one;
-}
-inherits(JPoint, Base.BasePoint);
-
-ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
- return new JPoint(this, x, y, z);
-};
-
-JPoint.prototype.toP = function toP() {
- if (this.isInfinity())
- return this.curve.point(null, null);
-
- var zinv = this.z.redInvm();
- var zinv2 = zinv.redSqr();
- var ax = this.x.redMul(zinv2);
- var ay = this.y.redMul(zinv2).redMul(zinv);
-
- return this.curve.point(ax, ay);
-};
-
-JPoint.prototype.neg = function neg() {
- return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
-};
-
-JPoint.prototype.add = function add(p) {
- // O + P = P
- if (this.isInfinity())
- return p;
-
- // P + O = P
- if (p.isInfinity())
- return this;
-
- // 12M + 4S + 7A
- var pz2 = p.z.redSqr();
- var z2 = this.z.redSqr();
- var u1 = this.x.redMul(pz2);
- var u2 = p.x.redMul(z2);
- var s1 = this.y.redMul(pz2.redMul(p.z));
- var s2 = p.y.redMul(z2.redMul(this.z));
-
- var h = u1.redSub(u2);
- var r = s1.redSub(s2);
- if (h.cmpn(0) === 0) {
- if (r.cmpn(0) !== 0)
- return this.curve.jpoint(null, null, null);
- else
- return this.dbl();
- }
-
- var h2 = h.redSqr();
- var h3 = h2.redMul(h);
- var v = u1.redMul(h2);
-
- var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
- var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
- var nz = this.z.redMul(p.z).redMul(h);
-
- return this.curve.jpoint(nx, ny, nz);
-};
-
-JPoint.prototype.mixedAdd = function mixedAdd(p) {
- // O + P = P
- if (this.isInfinity())
- return p.toJ();
-
- // P + O = P
- if (p.isInfinity())
- return this;
-
- // 8M + 3S + 7A
- var z2 = this.z.redSqr();
- var u1 = this.x;
- var u2 = p.x.redMul(z2);
- var s1 = this.y;
- var s2 = p.y.redMul(z2).redMul(this.z);
-
- var h = u1.redSub(u2);
- var r = s1.redSub(s2);
- if (h.cmpn(0) === 0) {
- if (r.cmpn(0) !== 0)
- return this.curve.jpoint(null, null, null);
- else
- return this.dbl();
- }
-
- var h2 = h.redSqr();
- var h3 = h2.redMul(h);
- var v = u1.redMul(h2);
-
- var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
- var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
- var nz = this.z.redMul(h);
-
- return this.curve.jpoint(nx, ny, nz);
-};
-
-JPoint.prototype.dblp = function dblp(pow) {
- if (pow === 0)
- return this;
- if (this.isInfinity())
- return this;
- if (!pow)
- return this.dbl();
-
- var i;
- if (this.curve.zeroA || this.curve.threeA) {
- var r = this;
- for (i = 0; i < pow; i++)
- r = r.dbl();
- return r;
- }
-
- // 1M + 2S + 1A + N * (4S + 5M + 8A)
- // N = 1 => 6M + 6S + 9A
- var a = this.curve.a;
- var tinv = this.curve.tinv;
-
- var jx = this.x;
- var jy = this.y;
- var jz = this.z;
- var jz4 = jz.redSqr().redSqr();
-
- // Reuse results
- var jyd = jy.redAdd(jy);
- for (i = 0; i < pow; i++) {
- var jx2 = jx.redSqr();
- var jyd2 = jyd.redSqr();
- var jyd4 = jyd2.redSqr();
- var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
-
- var t1 = jx.redMul(jyd2);
- var nx = c.redSqr().redISub(t1.redAdd(t1));
- var t2 = t1.redISub(nx);
- var dny = c.redMul(t2);
- dny = dny.redIAdd(dny).redISub(jyd4);
- var nz = jyd.redMul(jz);
- if (i + 1 < pow)
- jz4 = jz4.redMul(jyd4);
-
- jx = nx;
- jz = nz;
- jyd = dny;
- }
-
- return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
-};
-
-JPoint.prototype.dbl = function dbl() {
- if (this.isInfinity())
- return this;
-
- if (this.curve.zeroA)
- return this._zeroDbl();
- else if (this.curve.threeA)
- return this._threeDbl();
- else
- return this._dbl();
-};
-
-JPoint.prototype._zeroDbl = function _zeroDbl() {
- var nx;
- var ny;
- var nz;
- // Z = 1
- if (this.zOne) {
- // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
- // #doubling-mdbl-2007-bl
- // 1M + 5S + 14A
-
- // XX = X1^2
- var xx = this.x.redSqr();
- // YY = Y1^2
- var yy = this.y.redSqr();
- // YYYY = YY^2
- var yyyy = yy.redSqr();
- // S = 2 * ((X1 + YY)^2 - XX - YYYY)
- var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
- s = s.redIAdd(s);
- // M = 3 * XX + a; a = 0
- var m = xx.redAdd(xx).redIAdd(xx);
- // T = M ^ 2 - 2*S
- var t = m.redSqr().redISub(s).redISub(s);
-
- // 8 * YYYY
- var yyyy8 = yyyy.redIAdd(yyyy);
- yyyy8 = yyyy8.redIAdd(yyyy8);
- yyyy8 = yyyy8.redIAdd(yyyy8);
-
- // X3 = T
- nx = t;
- // Y3 = M * (S - T) - 8 * YYYY
- ny = m.redMul(s.redISub(t)).redISub(yyyy8);
- // Z3 = 2*Y1
- nz = this.y.redAdd(this.y);
- } else {
- // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
- // #doubling-dbl-2009-l
- // 2M + 5S + 13A
-
- // A = X1^2
- var a = this.x.redSqr();
- // B = Y1^2
- var b = this.y.redSqr();
- // C = B^2
- var c = b.redSqr();
- // D = 2 * ((X1 + B)^2 - A - C)
- var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
- d = d.redIAdd(d);
- // E = 3 * A
- var e = a.redAdd(a).redIAdd(a);
- // F = E^2
- var f = e.redSqr();
-
- // 8 * C
- var c8 = c.redIAdd(c);
- c8 = c8.redIAdd(c8);
- c8 = c8.redIAdd(c8);
-
- // X3 = F - 2 * D
- nx = f.redISub(d).redISub(d);
- // Y3 = E * (D - X3) - 8 * C
- ny = e.redMul(d.redISub(nx)).redISub(c8);
- // Z3 = 2 * Y1 * Z1
- nz = this.y.redMul(this.z);
- nz = nz.redIAdd(nz);
- }
-
- return this.curve.jpoint(nx, ny, nz);
-};
-
-JPoint.prototype._threeDbl = function _threeDbl() {
- var nx;
- var ny;
- var nz;
- // Z = 1
- if (this.zOne) {
- // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
- // #doubling-mdbl-2007-bl
- // 1M + 5S + 15A
-
- // XX = X1^2
- var xx = this.x.redSqr();
- // YY = Y1^2
- var yy = this.y.redSqr();
- // YYYY = YY^2
- var yyyy = yy.redSqr();
- // S = 2 * ((X1 + YY)^2 - XX - YYYY)
- var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
- s = s.redIAdd(s);
- // M = 3 * XX + a
- var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
- // T = M^2 - 2 * S
- var t = m.redSqr().redISub(s).redISub(s);
- // X3 = T
- nx = t;
- // Y3 = M * (S - T) - 8 * YYYY
- var yyyy8 = yyyy.redIAdd(yyyy);
- yyyy8 = yyyy8.redIAdd(yyyy8);
- yyyy8 = yyyy8.redIAdd(yyyy8);
- ny = m.redMul(s.redISub(t)).redISub(yyyy8);
- // Z3 = 2 * Y1
- nz = this.y.redAdd(this.y);
- } else {
- // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
- // 3M + 5S
-
- // delta = Z1^2
- var delta = this.z.redSqr();
- // gamma = Y1^2
- var gamma = this.y.redSqr();
- // beta = X1 * gamma
- var beta = this.x.redMul(gamma);
- // alpha = 3 * (X1 - delta) * (X1 + delta)
- var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
- alpha = alpha.redAdd(alpha).redIAdd(alpha);
- // X3 = alpha^2 - 8 * beta
- var beta4 = beta.redIAdd(beta);
- beta4 = beta4.redIAdd(beta4);
- var beta8 = beta4.redAdd(beta4);
- nx = alpha.redSqr().redISub(beta8);
- // Z3 = (Y1 + Z1)^2 - gamma - delta
- nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
- // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
- var ggamma8 = gamma.redSqr();
- ggamma8 = ggamma8.redIAdd(ggamma8);
- ggamma8 = ggamma8.redIAdd(ggamma8);
- ggamma8 = ggamma8.redIAdd(ggamma8);
- ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
- }
-
- return this.curve.jpoint(nx, ny, nz);
-};
-
-JPoint.prototype._dbl = function _dbl() {
- var a = this.curve.a;
-
- // 4M + 6S + 10A
- var jx = this.x;
- var jy = this.y;
- var jz = this.z;
- var jz4 = jz.redSqr().redSqr();
-
- var jx2 = jx.redSqr();
- var jy2 = jy.redSqr();
-
- var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
-
- var jxd4 = jx.redAdd(jx);
- jxd4 = jxd4.redIAdd(jxd4);
- var t1 = jxd4.redMul(jy2);
- var nx = c.redSqr().redISub(t1.redAdd(t1));
- var t2 = t1.redISub(nx);
-
- var jyd8 = jy2.redSqr();
- jyd8 = jyd8.redIAdd(jyd8);
- jyd8 = jyd8.redIAdd(jyd8);
- jyd8 = jyd8.redIAdd(jyd8);
- var ny = c.redMul(t2).redISub(jyd8);
- var nz = jy.redAdd(jy).redMul(jz);
-
- return this.curve.jpoint(nx, ny, nz);
-};
-
-JPoint.prototype.trpl = function trpl() {
- if (!this.curve.zeroA)
- return this.dbl().add(this);
-
- // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
- // 5M + 10S + ...
-
- // XX = X1^2
- var xx = this.x.redSqr();
- // YY = Y1^2
- var yy = this.y.redSqr();
- // ZZ = Z1^2
- var zz = this.z.redSqr();
- // YYYY = YY^2
- var yyyy = yy.redSqr();
- // M = 3 * XX + a * ZZ2; a = 0
- var m = xx.redAdd(xx).redIAdd(xx);
- // MM = M^2
- var mm = m.redSqr();
- // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
- var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
- e = e.redIAdd(e);
- e = e.redAdd(e).redIAdd(e);
- e = e.redISub(mm);
- // EE = E^2
- var ee = e.redSqr();
- // T = 16*YYYY
- var t = yyyy.redIAdd(yyyy);
- t = t.redIAdd(t);
- t = t.redIAdd(t);
- t = t.redIAdd(t);
- // U = (M + E)^2 - MM - EE - T
- var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
- // X3 = 4 * (X1 * EE - 4 * YY * U)
- var yyu4 = yy.redMul(u);
- yyu4 = yyu4.redIAdd(yyu4);
- yyu4 = yyu4.redIAdd(yyu4);
- var nx = this.x.redMul(ee).redISub(yyu4);
- nx = nx.redIAdd(nx);
- nx = nx.redIAdd(nx);
- // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
- var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
- ny = ny.redIAdd(ny);
- ny = ny.redIAdd(ny);
- ny = ny.redIAdd(ny);
- // Z3 = (Z1 + E)^2 - ZZ - EE
- var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
-
- return this.curve.jpoint(nx, ny, nz);
-};
-
-JPoint.prototype.mul = function mul(k, kbase) {
- k = new BN(k, kbase);
-
- return this.curve._wnafMul(this, k);
-};
-
-JPoint.prototype.eq = function eq(p) {
- if (p.type === 'affine')
- return this.eq(p.toJ());
-
- if (this === p)
- return true;
-
- // x1 * z2^2 == x2 * z1^2
- var z2 = this.z.redSqr();
- var pz2 = p.z.redSqr();
- if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
- return false;
-
- // y1 * z2^3 == y2 * z1^3
- var z3 = z2.redMul(this.z);
- var pz3 = pz2.redMul(p.z);
- return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
-};
-
-JPoint.prototype.eqXToP = function eqXToP(x) {
- var zs = this.z.redSqr();
- var rx = x.toRed(this.curve.red).redMul(zs);
- if (this.x.cmp(rx) === 0)
- return true;
-
- var xc = x.clone();
- var t = this.curve.redN.redMul(zs);
- for (;;) {
- xc.iadd(this.curve.n);
- if (xc.cmp(this.curve.p) >= 0)
- return false;
-
- rx.redIAdd(t);
- if (this.x.cmp(rx) === 0)
- return true;
- }
-};
-
-JPoint.prototype.inspect = function inspect() {
- if (this.isInfinity())
- return '';
- return '';
-};
-
-JPoint.prototype.isInfinity = function isInfinity() {
- // XXX This code assumes that zero is always zero in red
- return this.z.cmpn(0) === 0;
-};
-
-
-/***/ }),
-
-/***/ 727483:
-/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
-
-"use strict";
-
-
-var curves = exports;
-
-var hash = __webpack_require__(277952);
-var curve = __webpack_require__(777867);
-var utils = __webpack_require__(938402);
-
-var assert = utils.assert;
-
-function PresetCurve(options) {
- if (options.type === 'short')
- this.curve = new curve.short(options);
- else if (options.type === 'edwards')
- this.curve = new curve.edwards(options);
- else
- this.curve = new curve.mont(options);
- this.g = this.curve.g;
- this.n = this.curve.n;
- this.hash = options.hash;
-
- assert(this.g.validate(), 'Invalid curve');
- assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
-}
-curves.PresetCurve = PresetCurve;
-
-function defineCurve(name, options) {
- Object.defineProperty(curves, name, {
- configurable: true,
- enumerable: true,
- get: function() {
- var curve = new PresetCurve(options);
- Object.defineProperty(curves, name, {
- configurable: true,
- enumerable: true,
- value: curve,
- });
- return curve;
- },
- });
-}
-
-defineCurve('p192', {
- type: 'short',
- prime: 'p192',
- p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
- a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
- b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
- n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
- hash: hash.sha256,
- gRed: false,
- g: [
- '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
- '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811',
- ],
-});
-
-defineCurve('p224', {
- type: 'short',
- prime: 'p224',
- p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
- a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
- b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
- n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
- hash: hash.sha256,
- gRed: false,
- g: [
- 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
- 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34',
- ],
-});
-
-defineCurve('p256', {
- type: 'short',
- prime: null,
- p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
- a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
- b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
- n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
- hash: hash.sha256,
- gRed: false,
- g: [
- '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
- '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5',
- ],
-});
-
-defineCurve('p384', {
- type: 'short',
- prime: null,
- p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
- 'fffffffe ffffffff 00000000 00000000 ffffffff',
- a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
- 'fffffffe ffffffff 00000000 00000000 fffffffc',
- b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
- '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
- n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
- 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
- hash: hash.sha384,
- gRed: false,
- g: [
- 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
- '5502f25d bf55296c 3a545e38 72760ab7',
- '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
- '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f',
- ],
-});
-
-defineCurve('p521', {
- type: 'short',
- prime: null,
- p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
- 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
- 'ffffffff ffffffff ffffffff ffffffff ffffffff',
- a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
- 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
- 'ffffffff ffffffff ffffffff ffffffff fffffffc',
- b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
- '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
- '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
- n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
- 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
- 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
- hash: hash.sha512,
- gRed: false,
- g: [
- '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
- '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
- 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
- '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
- '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
- '3fad0761 353c7086 a272c240 88be9476 9fd16650',
- ],
-});
-
-defineCurve('curve25519', {
- type: 'mont',
- prime: 'p25519',
- p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
- a: '76d06',
- b: '1',
- n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
- hash: hash.sha256,
- gRed: false,
- g: [
- '9',
- ],
-});
-
-defineCurve('ed25519', {
- type: 'edwards',
- prime: 'p25519',
- p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
- a: '-1',
- c: '1',
- // -121665 * (121666^(-1)) (mod P)
- d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
- n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
- hash: hash.sha256,
- gRed: false,
- g: [
- '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
-
- // 4/5
- '6666666666666666666666666666666666666666666666666666666666666658',
- ],
-});
-
-var pre;
-try {
- pre = __webpack_require__(604674);
-} catch (e) {
- pre = undefined;
-}
-
-defineCurve('secp256k1', {
- type: 'short',
- prime: 'k256',
- p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
- a: '0',
- b: '7',
- n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
- h: '1',
- hash: hash.sha256,
-
- // Precomputed endomorphism
- beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
- lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
- basis: [
- {
- a: '3086d221a7d46bcde86c90e49284eb15',
- b: '-e4437ed6010e88286f547fa90abfe4c3',
- },
- {
- a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
- b: '3086d221a7d46bcde86c90e49284eb15',
- },
- ],
-
- gRed: false,
- g: [
- '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
- '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
- pre,
- ],
-});
-
-
-/***/ }),
-
-/***/ 252040:
-/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
-
-"use strict";
-
-
-var BN = __webpack_require__(439404);
-var HmacDRBG = __webpack_require__(932723);
-var utils = __webpack_require__(938402);
-var curves = __webpack_require__(727483);
-var rand = __webpack_require__(415037);
-var assert = utils.assert;
-
-var KeyPair = __webpack_require__(934747);
-var Signature = __webpack_require__(236390);
-
-function EC(options) {
- if (!(this instanceof EC))
- return new EC(options);
-
- // Shortcut `elliptic.ec(curve-name)`
- if (typeof options === 'string') {
- assert(Object.prototype.hasOwnProperty.call(curves, options),
- 'Unknown curve ' + options);
-
- options = curves[options];
- }
-
- // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
- if (options instanceof curves.PresetCurve)
- options = { curve: options };
-
- this.curve = options.curve.curve;
- this.n = this.curve.n;
- this.nh = this.n.ushrn(1);
- this.g = this.curve.g;
-
- // Point on curve
- this.g = options.curve.g;
- this.g.precompute(options.curve.n.bitLength() + 1);
-
- // Hash for function for DRBG
- this.hash = options.hash || options.curve.hash;
-}
-module.exports = EC;
-
-EC.prototype.keyPair = function keyPair(options) {
- return new KeyPair(this, options);
-};
-
-EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
- return KeyPair.fromPrivate(this, priv, enc);
-};
-
-EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
- return KeyPair.fromPublic(this, pub, enc);
-};
-
-EC.prototype.genKeyPair = function genKeyPair(options) {
- if (!options)
- options = {};
-
- // Instantiate Hmac_DRBG
- var drbg = new HmacDRBG({
- hash: this.hash,
- pers: options.pers,
- persEnc: options.persEnc || 'utf8',
- entropy: options.entropy || rand(this.hash.hmacStrength),
- entropyEnc: options.entropy && options.entropyEnc || 'utf8',
- nonce: this.n.toArray(),
- });
-
- var bytes = this.n.byteLength();
- var ns2 = this.n.sub(new BN(2));
- for (;;) {
- var priv = new BN(drbg.generate(bytes));
- if (priv.cmp(ns2) > 0)
- continue;
-
- priv.iaddn(1);
- return this.keyFromPrivate(priv);
- }
-};
-
-EC.prototype._truncateToN = function _truncateToN(msg, truncOnly, bitLength) {
- var byteLength;
- if (BN.isBN(msg) || typeof msg === 'number') {
- msg = new BN(msg, 16);
- byteLength = msg.byteLength();
- } else if (typeof msg === 'object') {
- // BN assumes an array-like input and asserts length
- byteLength = msg.length;
- msg = new BN(msg, 16);
- } else {
- // BN converts the value to string
- var str = msg.toString();
- // HEX encoding
- byteLength = (str.length + 1) >>> 1;
- msg = new BN(str, 16);
- }
- // Allow overriding
- if (typeof bitLength !== 'number') {
- bitLength = byteLength * 8;
- }
- var delta = bitLength - this.n.bitLength();
- if (delta > 0)
- msg = msg.ushrn(delta);
- if (!truncOnly && msg.cmp(this.n) >= 0)
- return msg.sub(this.n);
- else
- return msg;
-};
-
-EC.prototype.sign = function sign(msg, key, enc, options) {
- if (typeof enc === 'object') {
- options = enc;
- enc = null;
- }
- if (!options)
- options = {};
-
- key = this.keyFromPrivate(key, enc);
- msg = this._truncateToN(msg, false, options.msgBitLength);
-
- // Zero-extend key to provide enough entropy
- var bytes = this.n.byteLength();
- var bkey = key.getPrivate().toArray('be', bytes);
-
- // Zero-extend nonce to have the same byte size as N
- var nonce = msg.toArray('be', bytes);
-
- // Instantiate Hmac_DRBG
- var drbg = new HmacDRBG({
- hash: this.hash,
- entropy: bkey,
- nonce: nonce,
- pers: options.pers,
- persEnc: options.persEnc || 'utf8',
- });
-
- // Number of bytes to generate
- var ns1 = this.n.sub(new BN(1));
-
- for (var iter = 0; ; iter++) {
- var k = options.k ?
- options.k(iter) :
- new BN(drbg.generate(this.n.byteLength()));
- k = this._truncateToN(k, true);
- if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
- continue;
-
- var kp = this.g.mul(k);
- if (kp.isInfinity())
- continue;
-
- var kpX = kp.getX();
- var r = kpX.umod(this.n);
- if (r.cmpn(0) === 0)
- continue;
-
- var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
- s = s.umod(this.n);
- if (s.cmpn(0) === 0)
- continue;
-
- var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
- (kpX.cmp(r) !== 0 ? 2 : 0);
-
- // Use complement of `s`, if it is > `n / 2`
- if (options.canonical && s.cmp(this.nh) > 0) {
- s = this.n.sub(s);
- recoveryParam ^= 1;
- }
-
- return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
- }
-};
-
-EC.prototype.verify = function verify(msg, signature, key, enc, options) {
- if (!options)
- options = {};
-
- msg = this._truncateToN(msg, false, options.msgBitLength);
- key = this.keyFromPublic(key, enc);
- signature = new Signature(signature, 'hex');
-
- // Perform primitive values validation
- var r = signature.r;
- var s = signature.s;
- if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
- return false;
- if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
- return false;
-
- // Validate signature
- var sinv = s.invm(this.n);
- var u1 = sinv.mul(msg).umod(this.n);
- var u2 = sinv.mul(r).umod(this.n);
- var p;
-
- if (!this.curve._maxwellTrick) {
- p = this.g.mulAdd(u1, key.getPublic(), u2);
- if (p.isInfinity())
- return false;
-
- return p.getX().umod(this.n).cmp(r) === 0;
- }
-
- // NOTE: Greg Maxwell's trick, inspired by:
- // https://git.io/vad3K
-
- p = this.g.jmulAdd(u1, key.getPublic(), u2);
- if (p.isInfinity())
- return false;
-
- // Compare `p.x` of Jacobian point with `r`,
- // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
- // inverse of `p.z^2`
- return p.eqXToP(r);
-};
-
-EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
- assert((3 & j) === j, 'The recovery param is more than two bits');
- signature = new Signature(signature, enc);
-
- var n = this.n;
- var e = new BN(msg);
- var r = signature.r;
- var s = signature.s;
-
- // A set LSB signifies that the y-coordinate is odd
- var isYOdd = j & 1;
- var isSecondKey = j >> 1;
- if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
- throw new Error('Unable to find sencond key candinate');
-
- // 1.1. Let x = r + jn.
- if (isSecondKey)
- r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
- else
- r = this.curve.pointFromX(r, isYOdd);
-
- var rInv = signature.r.invm(n);
- var s1 = n.sub(e).mul(rInv).umod(n);
- var s2 = s.mul(rInv).umod(n);
-
- // 1.6.1 Compute Q = r^-1 (sR - eG)
- // Q = r^-1 (sR + -eG)
- return this.g.mulAdd(s1, r, s2);
-};
-
-EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
- signature = new Signature(signature, enc);
- if (signature.recoveryParam !== null)
- return signature.recoveryParam;
-
- for (var i = 0; i < 4; i++) {
- var Qprime;
- try {
- Qprime = this.recoverPubKey(e, signature, i);
- } catch (e) {
- continue;
- }
-
- if (Qprime.eq(Q))
- return i;
- }
- throw new Error('Unable to find valid recovery factor');
-};
-
-
-/***/ }),
-
-/***/ 934747:
-/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
-
-"use strict";
-
-
-var BN = __webpack_require__(439404);
-var utils = __webpack_require__(938402);
-var assert = utils.assert;
-
-function KeyPair(ec, options) {
- this.ec = ec;
- this.priv = null;
- this.pub = null;
-
- // KeyPair(ec, { priv: ..., pub: ... })
- if (options.priv)
- this._importPrivate(options.priv, options.privEnc);
- if (options.pub)
- this._importPublic(options.pub, options.pubEnc);
-}
-module.exports = KeyPair;
-
-KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
- if (pub instanceof KeyPair)
- return pub;
-
- return new KeyPair(ec, {
- pub: pub,
- pubEnc: enc,
- });
-};
-
-KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
- if (priv instanceof KeyPair)
- return priv;
-
- return new KeyPair(ec, {
- priv: priv,
- privEnc: enc,
- });
-};
-
-KeyPair.prototype.validate = function validate() {
- var pub = this.getPublic();
-
- if (pub.isInfinity())
- return { result: false, reason: 'Invalid public key' };
- if (!pub.validate())
- return { result: false, reason: 'Public key is not a point' };
- if (!pub.mul(this.ec.curve.n).isInfinity())
- return { result: false, reason: 'Public key * N != O' };
-
- return { result: true, reason: null };
-};
-
-KeyPair.prototype.getPublic = function getPublic(compact, enc) {
- // compact is optional argument
- if (typeof compact === 'string') {
- enc = compact;
- compact = null;
- }
-
- if (!this.pub)
- this.pub = this.ec.g.mul(this.priv);
-
- if (!enc)
- return this.pub;
-
- return this.pub.encode(enc, compact);
-};
-
-KeyPair.prototype.getPrivate = function getPrivate(enc) {
- if (enc === 'hex')
- return this.priv.toString(16, 2);
- else
- return this.priv;
-};
-
-KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
- this.priv = new BN(key, enc || 16);
-
- // Ensure that the priv won't be bigger than n, otherwise we may fail
- // in fixed multiplication method
- this.priv = this.priv.umod(this.ec.curve.n);
-};
-
-KeyPair.prototype._importPublic = function _importPublic(key, enc) {
- if (key.x || key.y) {
- // Montgomery points only have an `x` coordinate.
- // Weierstrass/Edwards points on the other hand have both `x` and
- // `y` coordinates.
- if (this.ec.curve.type === 'mont') {
- assert(key.x, 'Need x coordinate');
- } else if (this.ec.curve.type === 'short' ||
- this.ec.curve.type === 'edwards') {
- assert(key.x && key.y, 'Need both x and y coordinate');
- }
- this.pub = this.ec.curve.point(key.x, key.y);
- return;
- }
- this.pub = this.ec.curve.decodePoint(key, enc);
-};
-
-// ECDH
-KeyPair.prototype.derive = function derive(pub) {
- if(!pub.validate()) {
- assert(pub.validate(), 'public point not validated');
- }
- return pub.mul(this.priv).getX();
-};
-
-// ECDSA
-KeyPair.prototype.sign = function sign(msg, enc, options) {
- return this.ec.sign(msg, this, enc, options);
-};
-
-KeyPair.prototype.verify = function verify(msg, signature, options) {
- return this.ec.verify(msg, signature, this, undefined, options);
-};
-
-KeyPair.prototype.inspect = function inspect() {
- return '